mirror of
https://github.com/bevyengine/bevy
synced 2024-11-10 07:04:33 +00:00
scene: fix dynamically loading RenderPipelines scenes
This commit is contained in:
parent
3c1494eb64
commit
07858aa348
17 changed files with 94 additions and 170 deletions
|
@ -156,8 +156,8 @@ name = "keyboard_input_events"
|
|||
path = "examples/input/keyboard_input_events.rs"
|
||||
|
||||
[[example]]
|
||||
name = "load_scene"
|
||||
path = "examples/scene/load_scene.rs"
|
||||
name = "scene"
|
||||
path = "examples/scene/scene.rs"
|
||||
|
||||
[[example]]
|
||||
name = "properties"
|
||||
|
|
|
@ -33,7 +33,7 @@ impl AppPlugin for AssetPlugin {
|
|||
app.add_stage_before(bevy_app::stage::PRE_UPDATE, stage::LOAD_ASSETS)
|
||||
.add_stage_after(bevy_app::stage::POST_UPDATE, stage::ASSET_EVENTS)
|
||||
.init_resource::<AssetServer>()
|
||||
.register_property_type::<HandleId>();
|
||||
.register_property::<HandleId>();
|
||||
|
||||
#[cfg(feature = "filesystem_watcher")]
|
||||
app.add_system_to_stage(
|
||||
|
|
|
@ -25,11 +25,12 @@ impl AppPlugin for CorePlugin {
|
|||
app.init_resource::<Time>()
|
||||
.init_resource::<EntityLabels>()
|
||||
.register_component::<Timer>()
|
||||
.register_property_type::<Vec2>()
|
||||
.register_property_type::<Vec3>()
|
||||
.register_property_type::<Mat3>()
|
||||
.register_property_type::<Mat4>()
|
||||
.register_property_type::<Quat>()
|
||||
.register_property::<Vec2>()
|
||||
.register_property::<Vec3>()
|
||||
.register_property::<Mat3>()
|
||||
.register_property::<Mat4>()
|
||||
.register_property::<Quat>()
|
||||
.register_property::<Option<String>>()
|
||||
.add_system_to_stage(stage::FIRST, time_system.system())
|
||||
.add_system_to_stage(stage::FIRST, timer_system.system());
|
||||
}
|
||||
|
|
|
@ -13,7 +13,7 @@ use std::{
|
|||
|
||||
impl<T> Properties for Vec<T>
|
||||
where
|
||||
T: Property + Clone,
|
||||
T: Property + Clone + Default,
|
||||
{
|
||||
fn prop(&self, _name: &str) -> Option<&dyn Property> {
|
||||
None
|
||||
|
@ -46,7 +46,7 @@ where
|
|||
|
||||
impl<T> Property for Vec<T>
|
||||
where
|
||||
T: Property + Clone,
|
||||
T: Property + Clone + Default,
|
||||
{
|
||||
fn type_name(&self) -> &str {
|
||||
std::any::type_name::<Self>()
|
||||
|
@ -66,6 +66,9 @@ where
|
|||
|
||||
fn set(&mut self, value: &dyn Property) {
|
||||
if let Some(properties) = value.as_properties() {
|
||||
let len = properties.prop_len();
|
||||
self.resize_with(len, || T::default());
|
||||
|
||||
if properties.property_type() != self.property_type() {
|
||||
panic!(
|
||||
"Properties type mismatch. This type is {:?} but the applied type is {:?}",
|
||||
|
|
|
@ -3,6 +3,7 @@ use crate::Draw;
|
|||
use bevy_core::FloatOrd;
|
||||
use bevy_ecs::{Entity, Query};
|
||||
use bevy_transform::prelude::Transform;
|
||||
use bevy_property::Properties;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct VisibleEntity {
|
||||
|
@ -10,8 +11,9 @@ pub struct VisibleEntity {
|
|||
pub order: FloatOrd,
|
||||
}
|
||||
|
||||
#[derive(Default, Debug)]
|
||||
#[derive(Default, Debug, Properties)]
|
||||
pub struct VisibleEntities {
|
||||
#[property(ignore)]
|
||||
pub value: Vec<VisibleEntity>,
|
||||
}
|
||||
|
||||
|
|
|
@ -7,8 +7,9 @@ use crate::{
|
|||
use bevy_asset::Handle;
|
||||
use bevy_ecs::Bundle;
|
||||
use bevy_transform::components::{Rotation, Scale, Transform, Translation};
|
||||
use bevy_property::Properties;
|
||||
|
||||
#[derive(Default)]
|
||||
#[derive(Default, Properties)]
|
||||
pub struct MainPass;
|
||||
|
||||
#[derive(Bundle, Default)]
|
||||
|
|
|
@ -32,8 +32,8 @@ use bevy_app::prelude::*;
|
|||
use bevy_asset::AddAsset;
|
||||
use bevy_ecs::{IntoQuerySystem, IntoThreadLocalSystem};
|
||||
use bevy_type_registry::RegisterType;
|
||||
use camera::{ActiveCameras, Camera, OrthographicProjection, PerspectiveProjection};
|
||||
use pipeline::{PipelineCompiler, PipelineDescriptor, VertexBufferDescriptors};
|
||||
use camera::{ActiveCameras, Camera, OrthographicProjection, PerspectiveProjection, VisibleEntities};
|
||||
use pipeline::{PipelineCompiler, PipelineDescriptor, VertexBufferDescriptors, ShaderSpecialization, PipelineSpecialization, DynamicBinding, PrimitiveTopology};
|
||||
use render_graph::{
|
||||
base::{self, BaseRenderGraphBuilder, BaseRenderGraphConfig},
|
||||
RenderGraph,
|
||||
|
@ -84,8 +84,14 @@ impl AppPlugin for RenderPlugin {
|
|||
.register_component::<RenderPipelines>()
|
||||
.register_component::<OrthographicProjection>()
|
||||
.register_component::<PerspectiveProjection>()
|
||||
.register_property_type::<Color>()
|
||||
.register_property_type::<Range<f32>>()
|
||||
.register_component::<MainPass>()
|
||||
.register_component::<VisibleEntities>()
|
||||
.register_property::<Color>()
|
||||
.register_property::<Range<f32>>()
|
||||
.register_property::<ShaderSpecialization>()
|
||||
.register_property::<DynamicBinding>()
|
||||
.register_property::<PrimitiveTopology>()
|
||||
.register_properties::<PipelineSpecialization>()
|
||||
.init_resource::<RenderGraph>()
|
||||
.init_resource::<PipelineCompiler>()
|
||||
.init_resource::<RenderResourceBindings>()
|
||||
|
|
|
@ -6,8 +6,9 @@ use crate::{
|
|||
use bevy_asset::{Assets, Handle};
|
||||
use once_cell::sync::Lazy;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
#[derive(Clone, Eq, PartialEq, Debug)]
|
||||
use bevy_property::{Properties, Property};
|
||||
use serde::{Serialize, Deserialize};
|
||||
#[derive(Clone, Eq, PartialEq, Debug, Properties)]
|
||||
pub struct PipelineSpecialization {
|
||||
pub shader_specialization: ShaderSpecialization,
|
||||
pub primitive_topology: PrimitiveTopology,
|
||||
|
@ -34,7 +35,7 @@ impl PipelineSpecialization {
|
|||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Eq, PartialEq, Debug, Default)]
|
||||
#[derive(Clone, Eq, PartialEq, Debug, Default, Property, Serialize, Deserialize)]
|
||||
pub struct ShaderSpecialization {
|
||||
pub shader_defs: HashSet<String>,
|
||||
}
|
||||
|
@ -49,7 +50,7 @@ struct SpecializedPipeline {
|
|||
specialization: PipelineSpecialization,
|
||||
}
|
||||
|
||||
#[derive(Clone, Eq, PartialEq, Debug, Default)]
|
||||
#[derive(Clone, Eq, PartialEq, Debug, Default, Serialize, Deserialize, Property)]
|
||||
pub struct DynamicBinding {
|
||||
pub bind_group: u32,
|
||||
pub binding: u32,
|
||||
|
|
|
@ -10,7 +10,6 @@ use bevy_property::Properties;
|
|||
#[derive(Properties, Default, Clone)]
|
||||
pub struct RenderPipeline {
|
||||
pub pipeline: Handle<PipelineDescriptor>,
|
||||
#[property(ignore)]
|
||||
pub specialization: PipelineSpecialization,
|
||||
}
|
||||
|
||||
|
|
|
@ -1,4 +1,6 @@
|
|||
use crate::texture::TextureFormat;
|
||||
use serde::{Serialize, Deserialize};
|
||||
use bevy_property::Property;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct DepthStencilStateDescriptor {
|
||||
|
@ -51,7 +53,7 @@ pub enum CompareFunction {
|
|||
Always = 7,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)]
|
||||
#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, Serialize, Deserialize, Property)]
|
||||
pub enum PrimitiveTopology {
|
||||
PointList = 0,
|
||||
LineList = 1,
|
||||
|
|
|
@ -102,16 +102,28 @@ impl SceneSpawner {
|
|||
} else {
|
||||
bevy_ecs::Entity::from_id(scene_entity.entity)
|
||||
};
|
||||
if !world.contains(entity) {
|
||||
if world.contains(entity) {
|
||||
for component in scene_entity.components.iter() {
|
||||
let component_registration = component_registry
|
||||
.get_with_name(&component.type_name)
|
||||
.ok_or_else(|| SceneSpawnError::UnregisteredComponent {
|
||||
type_name: component.type_name.to_string(),
|
||||
})?;
|
||||
if component.type_name != "Camera" {
|
||||
component_registration.apply_component_to_entity(world, entity, component);
|
||||
}
|
||||
}
|
||||
|
||||
} else {
|
||||
world.spawn_as_entity(entity, (1,));
|
||||
}
|
||||
for component in scene_entity.components.iter() {
|
||||
let component_registration = component_registry
|
||||
.get_with_name(&component.type_name)
|
||||
.ok_or_else(|| SceneSpawnError::UnregisteredComponent {
|
||||
type_name: component.type_name.to_string(),
|
||||
})?;
|
||||
component_registration.add_component_to_entity(world, resources, entity, component);
|
||||
for component in scene_entity.components.iter() {
|
||||
let component_registration = component_registry
|
||||
.get_with_name(&component.type_name)
|
||||
.ok_or_else(|| SceneSpawnError::UnregisteredComponent {
|
||||
type_name: component.type_name.to_string(),
|
||||
})?;
|
||||
component_registration.add_component_to_entity(world, resources, entity, component);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
|
@ -197,6 +209,7 @@ pub fn scene_spawner_system(world: &mut World, resources: &mut Resources) {
|
|||
}
|
||||
}
|
||||
|
||||
|
||||
scene_spawner.load_queued_scenes(world, resources).unwrap();
|
||||
scene_spawner.spawn_queued_scenes(world, resources).unwrap();
|
||||
scene_spawner
|
||||
|
|
|
@ -5,7 +5,6 @@ use std::fmt;
|
|||
#[derive(Debug, PartialEq, Clone, Copy, Properties)]
|
||||
pub struct Transform {
|
||||
pub value: Mat4,
|
||||
#[property(ignore)]
|
||||
pub sync: bool, // NOTE: this is hopefully a temporary measure to allow setting the transform directly.
|
||||
// ideally setting the transform automatically propagates back to position / translation / rotation,
|
||||
// but right now they are always considered the source of truth
|
||||
|
|
|
@ -13,6 +13,6 @@ pub struct TypeRegistryPlugin;
|
|||
impl AppPlugin for TypeRegistryPlugin {
|
||||
fn build(&self, app: &mut AppBuilder) {
|
||||
app.init_resource::<TypeRegistry>()
|
||||
.register_property_type::<DynamicProperties>();
|
||||
.register_property::<DynamicProperties>();
|
||||
}
|
||||
}
|
||||
|
|
|
@ -7,7 +7,10 @@ pub trait RegisterType {
|
|||
fn register_component<T>(&mut self) -> &mut Self
|
||||
where
|
||||
T: Properties + DeserializeProperty + Component + FromResources;
|
||||
fn register_property_type<T>(&mut self) -> &mut Self
|
||||
fn register_properties<T>(&mut self) -> &mut Self
|
||||
where
|
||||
T: Properties + DeserializeProperty + FromResources;
|
||||
fn register_property<T>(&mut self) -> &mut Self
|
||||
where
|
||||
T: Property + DeserializeProperty;
|
||||
}
|
||||
|
@ -25,7 +28,18 @@ impl RegisterType for AppBuilder {
|
|||
self
|
||||
}
|
||||
|
||||
fn register_property_type<T>(&mut self) -> &mut Self
|
||||
fn register_properties<T>(&mut self) -> &mut Self
|
||||
where
|
||||
T: Properties + DeserializeProperty + Component + FromResources,
|
||||
{
|
||||
{
|
||||
let type_registry = self.app.resources.get::<TypeRegistry>().unwrap();
|
||||
type_registry.property.write().unwrap().register::<T>();
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
fn register_property<T>(&mut self) -> &mut Self
|
||||
where
|
||||
T: Property + DeserializeProperty,
|
||||
{
|
||||
|
|
|
@ -73,6 +73,7 @@ impl ComponentRegistry {
|
|||
pub struct ComponentRegistration {
|
||||
pub ty: TypeId,
|
||||
component_add_fn: fn(&mut World, resources: &Resources, Entity, &dyn Property),
|
||||
component_apply_fn: fn(&mut World, Entity, &dyn Property),
|
||||
component_properties_fn: fn(&Archetype, usize) -> &dyn Properties,
|
||||
pub short_name: String,
|
||||
pub long_name: &'static str,
|
||||
|
@ -91,6 +92,10 @@ impl ComponentRegistration {
|
|||
component.apply(property);
|
||||
world.insert_one(entity, component).unwrap();
|
||||
},
|
||||
component_apply_fn: |world: &mut World, entity: Entity, property: &dyn Property| {
|
||||
let mut component = world.get_mut::<T>(entity).unwrap();
|
||||
component.apply(property);
|
||||
},
|
||||
component_properties_fn: |archetype: &Archetype, index: usize| {
|
||||
// the type has been looked up by the caller, so this is safe
|
||||
unsafe {
|
||||
|
@ -117,6 +122,15 @@ impl ComponentRegistration {
|
|||
(self.component_add_fn)(world, resources, entity, property);
|
||||
}
|
||||
|
||||
pub fn apply_component_to_entity(
|
||||
&self,
|
||||
world: &mut World,
|
||||
entity: Entity,
|
||||
property: &dyn Property,
|
||||
) {
|
||||
(self.component_apply_fn)(world, entity, property);
|
||||
}
|
||||
|
||||
pub fn get_component_properties<'a>(
|
||||
&self,
|
||||
archetype: &'a Archetype,
|
||||
|
|
|
@ -1,131 +0,0 @@
|
|||
use bevy::{prelude::*, type_registry::TypeRegistry};
|
||||
|
||||
/// This example illustrates loading and saving scenes from files
|
||||
fn main() {
|
||||
App::build()
|
||||
.add_default_plugins()
|
||||
// Registering components informs Bevy that they exist. This allows them to be used when loading scenes
|
||||
// This step is only required if you want to load your components from scene files.
|
||||
// Unregistered components can still be used in your code, but they will be ignored during scene save/load.
|
||||
// In the future registering components will also make them usable from the Bevy editor.
|
||||
// The core Bevy plugins already register their components, so you only need this step for custom components.
|
||||
.register_component::<ComponentA>()
|
||||
.register_component::<ComponentB>()
|
||||
.add_startup_system(save_scene_system.thread_local_system())
|
||||
.add_startup_system(load_scene_system.system())
|
||||
.add_system(print_system.system())
|
||||
.run();
|
||||
}
|
||||
|
||||
// Registered components must implement the `Properties` and `FromResources` traits.
|
||||
// The `Properties` trait enables serialization, deserialization, dynamic property access, and change detection.
|
||||
// `Properties` enable a bunch of cool behaviors, so its worth checking out the dedicated `properties.rs` example.
|
||||
// The `FromResources` trait determines how your component is constructed when it loads. For simple use cases you can just
|
||||
// implement the `Default` trait (which automatically implements FromResources). The simplest registered component just needs
|
||||
// these two derives:
|
||||
#[derive(Properties, Default)]
|
||||
struct ComponentA {
|
||||
pub x: f32,
|
||||
pub y: f32,
|
||||
}
|
||||
|
||||
// Some components have fields that cannot (or should not) be written to scene files. These can be ignored with
|
||||
// the #[property(ignore)] attribute. This is also generally where the `FromResources` trait comes into play.
|
||||
// `FromResources` gives you access to your App's current ECS `Resources` when you construct your component.
|
||||
#[derive(Properties)]
|
||||
struct ComponentB {
|
||||
pub value: String,
|
||||
#[property(ignore)]
|
||||
pub time_since_startup: std::time::Duration,
|
||||
}
|
||||
|
||||
impl FromResources for ComponentB {
|
||||
fn from_resources(resources: &Resources) -> Self {
|
||||
let time = resources.get::<Time>().unwrap();
|
||||
ComponentB {
|
||||
time_since_startup: time.time_since_startup(),
|
||||
value: "Default Value".to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn load_scene_system(asset_server: Res<AssetServer>, mut scene_spawner: ResMut<SceneSpawner>) {
|
||||
// Scenes are loaded just like any other asset.
|
||||
let scene_handle: Handle<Scene> = asset_server
|
||||
.load("assets/scenes/load_scene_example.scn")
|
||||
.unwrap();
|
||||
|
||||
// SceneSpawner can "instance" scenes. "instancing" a scene creates a new instance of the scene in the World with new entity ids.
|
||||
// This guarantees that it will not overwrite existing entities.
|
||||
scene_spawner.instance(scene_handle);
|
||||
|
||||
// SceneSpawner can also "load" scenes. "loading" a scene preserves the entity ids in the scene.
|
||||
// In general, you should "instance" scenes when you are dynamically composing your World and "load" scenes for things like game saves.
|
||||
scene_spawner.load(scene_handle);
|
||||
|
||||
// we have now loaded `scene_handle` AND instanced it, which means our World now has one set of entities with the Scene's ids and
|
||||
// one set of entities with new ids
|
||||
|
||||
// This tells the AssetServer to watch for changes to assets.
|
||||
// It enables our scenes to automatically reload in game when we modify their files
|
||||
asset_server.watch_for_changes().unwrap();
|
||||
}
|
||||
|
||||
// Using SceneSpawner instance() and load() queues them up to be added to the World at the beginning of the next update. However if
|
||||
// you need scenes to load immediately, you can use the following approach. But be aware that this takes full control of the ECS world
|
||||
// and therefore blocks other parallel systems from executing until it finishes. In most cases you should use the SceneSpawner
|
||||
// instance() and load() methods.
|
||||
#[allow(dead_code)]
|
||||
fn load_scene_right_now_system(world: &mut World, resources: &mut Resources) {
|
||||
let scene_handle: Handle<Scene> = {
|
||||
let asset_server = resources.get::<AssetServer>().unwrap();
|
||||
let mut scenes = resources.get_mut::<Assets<Scene>>().unwrap();
|
||||
asset_server
|
||||
.load_sync(&mut scenes, "assets/scenes/load_scene_example.scn")
|
||||
.unwrap()
|
||||
};
|
||||
let mut scene_spawner = resources.get_mut::<SceneSpawner>().unwrap();
|
||||
scene_spawner
|
||||
.load_sync(world, resources, scene_handle)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
// This system prints all ComponentA components in our world. Try making a change to a ComponentA in load_scene_example.scn.
|
||||
// You should immediately see the changes appear in the console.
|
||||
fn print_system(mut query: Query<(Entity, &ComponentA)>) {
|
||||
println!("Current World State:");
|
||||
for (entity, component_a) in &mut query.iter() {
|
||||
println!(" Entity({})", entity.id());
|
||||
println!(
|
||||
" ComponentA: {{ x: {} y: {} }}\n",
|
||||
component_a.x, component_a.y
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn save_scene_system(_world: &mut World, resources: &mut Resources) {
|
||||
// Scenes can be created from any ECS World. You can either create a new one for the scene or use the current World.
|
||||
let mut world = World::new();
|
||||
world.spawn((
|
||||
ComponentA { x: 1.0, y: 2.0 },
|
||||
ComponentB {
|
||||
value: "hello".to_string(),
|
||||
..ComponentB::from_resources(resources)
|
||||
},
|
||||
));
|
||||
world.spawn((ComponentA { x: 3.0, y: 4.0 },));
|
||||
|
||||
// The component registry resource contains information about all registered components. This is used to construct scenes.
|
||||
let type_registry = resources.get::<TypeRegistry>().unwrap();
|
||||
let scene = Scene::from_world(&world, &type_registry.component.read().unwrap());
|
||||
|
||||
// Scenes can be serialized like this:
|
||||
println!(
|
||||
"{}",
|
||||
scene
|
||||
.serialize_ron(&type_registry.property.read().unwrap())
|
||||
.unwrap()
|
||||
);
|
||||
|
||||
// TODO: save scene
|
||||
}
|
|
@ -13,9 +13,9 @@ fn main() {
|
|||
App::build()
|
||||
.add_default_plugins()
|
||||
// If you need to deserialize custom property types, register them like this:
|
||||
.register_property_type::<Test>()
|
||||
.register_property_type::<Nested>()
|
||||
.register_property_type::<CustomProperty>()
|
||||
.register_property::<Test>()
|
||||
.register_property::<Nested>()
|
||||
.register_property::<CustomProperty>()
|
||||
.add_startup_system(setup.system())
|
||||
.run();
|
||||
}
|
||||
|
@ -58,7 +58,7 @@ fn setup(type_registry: Res<TypeRegistry>) {
|
|||
patch.set::<usize>("a", 4);
|
||||
|
||||
// You can "apply" Properties on top of other Properties. This will only set properties with the same name and type.
|
||||
// You can use this to "patch" your components with new values.
|
||||
// You can use this to "patch" your properties with new values.
|
||||
test.apply(&patch);
|
||||
assert_eq!(test.a, 4);
|
||||
|
||||
|
|
Loading…
Reference in a new issue