-
-
Notifications
You must be signed in to change notification settings - Fork 3.9k
Add an example demonstrating how to use default query filtering and entity cloning to create a prefab system #17769
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
alice-i-cecile
wants to merge
8
commits into
bevyengine:main
Choose a base branch
from
alice-i-cecile:its-prefabing-time
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
896f09c
Example stub
alice-i-cecile a94fced
Make `Disabled` Clone
alice-i-cecile 5ef6d89
Fix camera
alice-i-cecile a20adfd
Bigger ground plane
alice-i-cecile 5939196
Demo prefab concept
alice-i-cecile 3800528
Spawn entities on mouse position
alice-i-cecile a257fac
Randomize rotations
alice-i-cecile 6634fb0
Avoid double events by stopping propagation
alice-i-cecile File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,126 @@ | ||
//! Generating a collection of "prefab" entities can be faster and cleaner than | ||
//! loading them from assets each time or working entirely in code. | ||
//! | ||
//! Rather than providing an opinonated prefab system, Bevy provides a flexible | ||
//! set of tools that can be used to create and modify your solution. | ||
//! | ||
//! The core workflow is pretty straightforward: | ||
//! | ||
//! 1. Load asssets from disk. | ||
//! 2. Create prefab entities from those assets. | ||
//! 3. Make sure that these prefab entities aren't accidentally modified by adding a component that cause them to be ignored by default. | ||
//! 4. Clone these entities (and their children) out from the prefab when you need to spawn an instance of them. | ||
//! | ||
//! This solution can be easily adapted to meet the needs of your own asset loading workflows, | ||
//! and variants of prefabs (e.g. enemy variants) can readily be constructed ahead of time and stored for easy access. | ||
//! | ||
//! Be mindful of memory usage when defining prefabs; while they won't be seen by game logic, | ||
//! the components and assets that they use will still be loaded into memory (although asset data is shared between instances). | ||
//! Loading and unloading assets dynamically (e.g. per level) is an important strategy to manage memory usage. | ||
|
||
use std::f32::consts::PI; | ||
|
||
use bevy::platform_support::collections::HashMap; | ||
use bevy::{ecs::entity_disabling::Disabled, prelude::*, scene::SceneInstanceReady}; | ||
|
||
fn main() { | ||
App::new() | ||
.add_plugins((DefaultPlugins, MeshPickingPlugin)) | ||
.init_resource::<Prefabs>() | ||
.add_systems(Startup, setup_scene) | ||
.add_observer(spawn_prefab_on_mouse_click) | ||
.run(); | ||
} | ||
|
||
// An example asset that contains a mesh composed of multiple entities. | ||
const GLTF_PATH: &str = "models/animated/Fox.glb"; | ||
|
||
/// We're keeping track of our disabled prefab entities in a resource, | ||
/// allowing us to quickly look up and clone them when we need to spawn them. | ||
#[derive(Resource, Default)] | ||
struct Prefabs(HashMap<String, Entity>); | ||
|
||
fn setup_scene( | ||
mut commands: Commands, | ||
asset_server: Res<AssetServer>, | ||
mut meshes: ResMut<Assets<Mesh>>, | ||
mut materials: ResMut<Assets<StandardMaterial>>, | ||
) { | ||
// Large floor plane to display our models on | ||
commands.spawn(( | ||
Mesh3d(meshes.add(Rectangle::new(500.0, 500.0))), | ||
MeshMaterial3d(materials.add(Color::WHITE)), | ||
Transform::from_rotation(Quat::from_rotation_x(-std::f32::consts::FRAC_PI_2)), | ||
)); | ||
// Light | ||
commands.spawn(( | ||
DirectionalLight { | ||
shadows_enabled: true, | ||
illuminance: 32000.0, | ||
..default() | ||
}, | ||
Transform::from_xyz(100.0, 200.0, 200.0), | ||
)); | ||
// Camera | ||
commands.spawn(( | ||
Camera3d::default(), | ||
Transform::from_xyz(100.0, 400.0, 100.0).looking_at(Vec3::ZERO, Vec3::Y), | ||
)); | ||
|
||
// Load in our test scene that we're storing as a prefab | ||
let mesh_scene = SceneRoot(asset_server.load(GltfAssetLabel::Scene(0).from_asset(GLTF_PATH))); | ||
commands.spawn(mesh_scene).observe(respond_to_scene_loaded); | ||
} | ||
|
||
// This observer will be triggered when the scene is loaded, | ||
// allowing us to modify the scene as we please. | ||
fn respond_to_scene_loaded( | ||
trigger: Trigger<SceneInstanceReady>, | ||
mut prefabs: ResMut<Prefabs>, | ||
mut commands: Commands, | ||
) { | ||
let scene_root_entity = trigger.target(); | ||
// Scenes are typically composed of multiple entities, so we need to | ||
// modify all entities in the scene to disable the scene. | ||
commands | ||
.entity(scene_root_entity) | ||
// TODO: use a custom DQF component to convey semantics | ||
.insert_recursive::<Children>(Disabled); | ||
|
||
// Store the scene root entity in our prefab resource, | ||
// along with a key that we can use to look it up later. | ||
prefabs.0.insert("fox".to_string(), scene_root_entity); | ||
} | ||
|
||
fn spawn_prefab_on_mouse_click( | ||
mut trigger: Trigger<Pointer<Click>>, | ||
prefabs: Res<Prefabs>, | ||
mut commands: Commands, | ||
) { | ||
// Check that the prefab we're looking for is ready | ||
let Some(prefab_entity) = prefabs.0.get("fox") else { | ||
return; | ||
}; | ||
|
||
let maybe_click_position = &trigger.event().event.hit.position; | ||
let Some(click_position) = maybe_click_position else { | ||
return; | ||
}; | ||
|
||
let fresh_clone = commands.entity(*prefab_entity).clone_and_spawn().id(); | ||
commands | ||
.entity(fresh_clone) | ||
.remove_recursive::<Children, Disabled>(); | ||
// Overwrite the position of the prefab entity with the new value we want to spawn it at | ||
// and give it a random rotation. | ||
let random_angle = PI * 2.0 * rand::random::<f32>(); | ||
|
||
commands.entity(fresh_clone).insert( | ||
Transform::from_translation(*click_position) | ||
.with_rotation(Quat::from_rotation_y(random_angle)), | ||
); | ||
|
||
// We've already handled this event; | ||
// so we don't want it to propagate any further. | ||
trigger.propagate(false); | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think this deserves a qualifier or a different more specific name less loaded with context. People will see this name and think "this is the Bevy prefab system", which has implications like "an asset format", "inheritance", etc.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Good call; I definitely think that's the right call for the current stage of maturity.