examples build fix + minor api improvements

This commit is contained in:
Dmitry
2023-04-24 09:40:17 +03:00
parent 8232a4f662
commit 8ebbfc9695
34 changed files with 279 additions and 233 deletions
+4 -5
View File
@@ -4,16 +4,15 @@
//!
//! This example shows simple 2D scene with light sources.
use fyrox::resource::texture::Texture;
use fyrox::{
asset::manager::ResourceManager,
core::{
algebra::{UnitQuaternion, Vector3},
color::Color,
pool::Handle,
},
engine::{
executor::Executor, resource_manager::ResourceManager, GraphicsContext,
GraphicsContextParams,
},
engine::{executor::Executor, GraphicsContext, GraphicsContextParams},
event::{ElementState, Event, VirtualKeyCode, WindowEvent},
event_loop::ControlFlow,
gui::{
@@ -73,7 +72,7 @@ impl SceneLoader {
.build(),
),
)
.with_texture(resource_manager.request_texture("examples/data/starship.png"))
.with_texture(resource_manager.request::<Texture, _>("examples/data/starship.png"))
.build(&mut scene.graph);
}
}
+4 -5
View File
@@ -4,12 +4,11 @@
//!
//! This example shows simple 2D scene with light sources.
use fyrox::resource::model::{Model, ModelResourceExtension};
use fyrox::{
asset::manager::ResourceManager,
core::{algebra::Vector3, color::Color, futures::executor::block_on, pool::Handle},
engine::{
executor::Executor, resource_manager::ResourceManager, GraphicsContext,
GraphicsContextParams,
},
engine::{executor::Executor, GraphicsContext, GraphicsContextParams},
event::Event,
event::{ElementState, VirtualKeyCode, WindowEvent},
event_loop::ControlFlow,
@@ -50,7 +49,7 @@ impl SceneLoader {
.build(&mut scene.graph);
// Load scene.
block_on(resource_manager.request_model("examples/data/2d/scene.rgs"))
block_on(resource_manager.request::<Model, _>("examples/data/2d/scene.rgs"))
.unwrap()
.instantiate(&mut scene);
+5 -6
View File
@@ -7,17 +7,16 @@
pub mod shared;
use fyrox::resource::model::{Model, ModelResourceExtension};
use fyrox::{
asset::manager::ResourceManager,
core::{
algebra::{UnitQuaternion, Vector2, Vector3},
color::Color,
futures,
pool::Handle,
},
engine::{
executor::Executor, resource_manager::ResourceManager, GraphicsContext,
GraphicsContextParams,
},
engine::{executor::Executor, GraphicsContext, GraphicsContextParams},
event::{ElementState, Event, VirtualKeyCode, WindowEvent},
event_loop::ControlFlow,
gui::{
@@ -130,7 +129,7 @@ impl SceneLoader {
// models it is very efficient because single vertex and index buffer can be used
// for all models instances, so memory footprint on GPU will be lower.
let model_resource = resource_manager
.request_model("examples/data/mutant/mutant.FBX")
.request::<Model, _>("examples/data/mutant/mutant.FBX")
.await
.unwrap();
@@ -152,7 +151,7 @@ impl SceneLoader {
// Add simple animation for our model. Animations are loaded from model resources -
// this is because animation is a set of skeleton bones with their own transforms.
let walk_animation_resource = resource_manager
.request_model("examples/data/mutant/walk.fbx")
.request::<Model, _>("examples/data/mutant/walk.fbx")
.await
.unwrap();
+4 -5
View File
@@ -1,17 +1,16 @@
pub mod shared;
use crate::shared::create_camera;
use fyrox::resource::model::{Model, ModelResourceExtension};
use fyrox::{
asset::manager::ResourceManager,
core::{
algebra::{UnitQuaternion, Vector2, Vector3},
color::Color,
futures::executor::block_on,
pool::Handle,
},
engine::{
executor::Executor, resource_manager::ResourceManager, GraphicsContext,
GraphicsContextParams,
},
engine::{executor::Executor, GraphicsContext, GraphicsContextParams},
event::{ElementState, Event, VirtualKeyCode, WindowEvent},
event_loop::ControlFlow,
gui::{
@@ -66,7 +65,7 @@ impl GameSceneLoader {
.build(&mut scene.graph);
let model_resource = block_on(
resource_manager.request_model("examples/data/blend_shape/Gunan_animated2.fbx"),
resource_manager.request::<Model, _>("examples/data/blend_shape/Gunan_animated2.fbx"),
)
.unwrap();
+11 -6
View File
@@ -3,6 +3,8 @@
//! Just shows two textures with compression. Engine compresses textures automatically,
//! based on compression options.
use fyrox::engine::resource_loaders::texture::TextureLoader;
use fyrox::resource::texture::Texture;
use fyrox::{
core::{algebra::Vector2, color::Color, pool::Handle},
engine::{executor::Executor, GraphicsContextParams},
@@ -31,10 +33,13 @@ impl PluginConstructor for GameConstructor {
.resource_manager
.state()
.containers_mut()
.textures
.set_default_import_options(
TextureImportOptions::default().with_compression(CompressionOptions::Quality),
);
.resources
.loaders
.iter_mut()
.find_map(|l| (**l).as_any_mut().downcast_mut::<TextureLoader>())
.unwrap()
.default_import_options =
TextureImportOptions::default().with_compression(CompressionOptions::Quality);
ImageBuilder::new(
WidgetBuilder::new()
@@ -45,7 +50,7 @@ impl PluginConstructor for GameConstructor {
.with_texture(into_gui_texture(
context
.resource_manager
.request_texture("examples/data/MetalMesh_Base_Color.png"),
.request::<Texture, _>("examples/data/MetalMesh_Base_Color.png"),
))
.build(&mut context.user_interface.build_ctx());
@@ -58,7 +63,7 @@ impl PluginConstructor for GameConstructor {
.with_texture(into_gui_texture(
context
.resource_manager
.request_texture("examples/data/R8Texture.png"),
.request::<Texture, _>("examples/data/R8Texture.png"),
))
.build(&mut context.user_interface.build_ctx());
+50 -31
View File
@@ -9,8 +9,14 @@
pub mod shared;
use crate::shared::create_camera;
use fyrox::engine::GraphicsContext;
use fyrox::resource::model::{Model, ModelResourceExtension};
use fyrox::resource::texture::Texture;
use fyrox::{
asset::{
container::event::ResourceEventBroadcaster,
loader::{BoxedLoaderFuture, ResourceLoader},
manager::ResourceManager,
},
core::{
algebra::{Matrix4, Vector3},
color::Color,
@@ -18,15 +24,9 @@ use fyrox::{
instant::Instant,
sstorage::ImmutableString,
},
engine::resource_loaders::{model::ModelLoader, texture::TextureLoader},
engine::{
resource_manager::{
container::event::ResourceEventBroadcaster,
loader::{
model::ModelLoader, texture::TextureLoader, BoxedLoaderFuture, ResourceLoader,
},
ResourceManager,
},
Engine, EngineInitParams, GraphicsContextParams, SerializationContext,
Engine, EngineInitParams, GraphicsContext, GraphicsContextParams, SerializationContext,
},
event::{Event, WindowEvent},
event_loop::{ControlFlow, EventLoop},
@@ -51,16 +51,29 @@ use fyrox::{
},
window::WindowAttributes,
};
use fyrox_resource::untyped::UntypedResource;
use std::any::Any;
use std::sync::Arc;
struct CustomModelLoader(Arc<ModelLoader>);
impl ResourceLoader<ModelResource, ModelImportOptions> for CustomModelLoader {
impl ResourceLoader for CustomModelLoader {
fn extensions(&self) -> &[&str] {
&["rgs", "fbx"]
}
fn as_any(&self) -> &dyn Any {
self
}
fn as_any_mut(&mut self) -> &mut dyn Any {
self
}
fn load(
&self,
resource: ModelResource,
default_import_options: ModelImportOptions,
event_broadcaster: ResourceEventBroadcaster<ModelResource>,
resource: UntypedResource,
event_broadcaster: ResourceEventBroadcaster,
reload: bool,
) -> BoxedLoaderFuture {
// Arc is required as BoxedLoaderFuture has a static lifetime and hence self cannot be
@@ -68,10 +81,8 @@ impl ResourceLoader<ModelResource, ModelImportOptions> for CustomModelLoader {
let loader = self.0.clone();
Box::pin(async move {
println!("CUSTOM LOADER: loading model {:?}", resource.state().path());
loader
.load(resource, default_import_options, event_broadcaster, reload)
.await
println!("CUSTOM LOADER: loading model {:?}", resource.path());
loader.load(resource, event_broadcaster, reload).await
})
}
}
@@ -79,12 +90,23 @@ impl ResourceLoader<ModelResource, ModelImportOptions> for CustomModelLoader {
/// For simplicity we just simply wrap the default loader and log the invocation to the console.
struct CustomTextureLoader(Arc<TextureLoader>);
impl ResourceLoader<TextureResource, TextureImportOptions> for CustomTextureLoader {
impl ResourceLoader for CustomTextureLoader {
fn extensions(&self) -> &[&str] {
&["jpg", "jpeg", "tga", "gif", "bmp", "png", "tiff", "dds"]
}
fn as_any(&self) -> &dyn Any {
self
}
fn as_any_mut(&mut self) -> &mut dyn Any {
self
}
fn load(
&self,
resource: TextureResource,
default_import_options: TextureImportOptions,
event_broadcaster: ResourceEventBroadcaster<TextureResource>,
resource: UntypedResource,
event_broadcaster: ResourceEventBroadcaster,
reload: bool,
) -> BoxedLoaderFuture {
// Arc is required as BoxedLoaderFuture has a static lifetime and hence self cannot be
@@ -92,13 +114,8 @@ impl ResourceLoader<TextureResource, TextureImportOptions> for CustomTextureLoad
let loader = self.0.clone();
Box::pin(async move {
println!(
"CUSTOM LOADER: loading texture {:?}",
resource.state().path()
);
loader
.load(resource, default_import_options, event_broadcaster, reload)
.await
println!("CUSTOM LOADER: loading texture {:?}", resource.path());
loader.load(resource, event_broadcaster, reload).await
})
}
}
@@ -135,7 +152,7 @@ impl GameSceneLoader {
// Add some model with animation.
let model_resource = resource_manager
.request_model("examples/data/mutant/mutant.FBX")
.request::<Model, _>("examples/data/mutant/mutant.FBX")
.await;
let model_handle = model_resource.unwrap().instantiate(&mut scene);
@@ -148,7 +165,9 @@ impl GameSceneLoader {
.set_property(
&ImmutableString::new("diffuseTexture"),
PropertyValue::Sampler {
value: Some(resource_manager.request_texture("examples/data/concrete2.dds")),
value: Some(
resource_manager.request::<Texture, _>("examples/data/concrete2.dds"),
),
fallback: SamplerFallback::White,
},
)
@@ -186,7 +205,7 @@ fn main() {
vsync: true,
};
let serialization_context = Arc::new(SerializationContext::new());
let resource_manager = ResourceManager::new(serialization_context.clone());
let resource_manager = ResourceManager::new();
// Set up our custom loaders
{
+3 -2
View File
@@ -6,8 +6,9 @@
use fyrox::engine::{GraphicsContext, GraphicsContextParams};
use fyrox::{
asset::manager::ResourceManager,
core::instant::Instant,
engine::{resource_manager::ResourceManager, Engine, EngineInitParams, SerializationContext},
engine::{Engine, EngineInitParams, SerializationContext},
event::{Event, WindowEvent},
event_loop::{ControlFlow, EventLoop},
utils::{
@@ -33,7 +34,7 @@ fn main() {
let serialization_context = Arc::new(SerializationContext::new());
let mut engine = Engine::new(EngineInitParams {
graphics_context_params,
resource_manager: ResourceManager::new(serialization_context.clone()),
resource_manager: ResourceManager::new(),
serialization_context,
})
.unwrap();
+6 -4
View File
@@ -4,12 +4,13 @@ pub mod shared;
use crate::shared::create_camera;
use fyrox::{
asset::manager::ResourceManager,
core::{
algebra::{UnitQuaternion, Vector2, Vector3},
color::Color,
pool::Handle,
},
engine::{resource_manager::ResourceManager, Engine, EngineInitParams, SerializationContext},
engine::{Engine, EngineInitParams, SerializationContext},
event::{ElementState, Event, VirtualKeyCode, WindowEvent},
event_loop::{ControlFlow, EventLoop},
gui::{
@@ -31,6 +32,7 @@ use fyrox::{
};
use fyrox::engine::{GraphicsContext, GraphicsContextParams};
use fyrox::resource::model::{Model, ModelResourceExtension};
use std::sync::Arc;
use std::{rc::Rc, time::Instant};
use winit::window::WindowAttributes;
@@ -87,14 +89,14 @@ async fn create_scene(resource_manager: ResourceManager) -> GameScene {
.await;
let model_resource = resource_manager
.request_model("examples/data/mutant/mutant.FBX")
.request::<Model, _>("examples/data/mutant/mutant.FBX")
.await
.unwrap();
let model_handle = model_resource.instantiate(&mut scene);
let walk_animation_resource = resource_manager
.request_model("examples/data/mutant/walk.fbx")
.request::<Model, _>("examples/data/mutant/walk.fbx")
.await
.unwrap();
@@ -119,7 +121,7 @@ fn main() {
let serialization_context = Arc::new(SerializationContext::new());
let mut engine = Engine::new(EngineInitParams {
graphics_context_params,
resource_manager: ResourceManager::new(serialization_context.clone()),
resource_manager: ResourceManager::new(),
serialization_context,
})
.unwrap();
+9 -7
View File
@@ -8,17 +8,17 @@
pub mod shared;
use crate::shared::create_camera;
use fyrox::resource::model::{Model, ModelResourceExtension};
use fyrox::resource::texture::Texture;
use fyrox::{
asset::manager::ResourceManager,
core::{
algebra::{Matrix4, UnitQuaternion, Vector3},
color::Color,
pool::Handle,
sstorage::ImmutableString,
},
engine::{
executor::Executor, resource_manager::ResourceManager, GraphicsContext,
GraphicsContextParams,
},
engine::{executor::Executor, GraphicsContext, GraphicsContextParams},
event::{ElementState, Event, VirtualKeyCode, WindowEvent},
event_loop::ControlFlow,
gui::{
@@ -74,8 +74,8 @@ impl SceneLoader {
// of it. In case of models it is very efficient because single vertex and index buffer
// can be used for all models instances, so memory footprint on GPU will be lower.
let (model_resource, walk_animation_resource) = fyrox::core::futures::join!(
resource_manager.request_model("examples/data/mutant/mutant.FBX"),
resource_manager.request_model("examples/data/mutant/walk.fbx")
resource_manager.request::<Model, _>("examples/data/mutant/mutant.FBX"),
resource_manager.request::<Model, _>("examples/data/mutant/walk.fbx")
);
for z in -10..10 {
@@ -142,7 +142,9 @@ impl SceneLoader {
.set_property(
&ImmutableString::new("diffuseTexture"),
PropertyValue::Sampler {
value: Some(resource_manager.request_texture("examples/data/concrete2.dds")),
value: Some(
resource_manager.request::<Texture, _>("examples/data/concrete2.dds"),
),
fallback: SamplerFallback::White,
},
)
+14 -10
View File
@@ -8,8 +8,9 @@
pub mod shared;
use crate::shared::create_camera;
use fyrox::engine::GraphicsContext;
use fyrox::resource::model::{Model, ModelResourceExtension};
use fyrox::{
asset::manager::ResourceManager,
core::{
algebra::{UnitQuaternion, Vector2, Vector3},
color::Color,
@@ -18,8 +19,7 @@ use fyrox::{
visitor::Visitor,
},
engine::{
resource_manager::ResourceManager, Engine, EngineInitParams, GraphicsContextParams,
SerializationContext,
Engine, EngineInitParams, GraphicsContext, GraphicsContextParams, SerializationContext,
},
event::{ElementState, Event, VirtualKeyCode, WindowEvent},
event_loop::{ControlFlow, EventLoop},
@@ -239,7 +239,7 @@ fn create_scene_async(
// There is no difference between scene created in Fyroxed and any other
// model file, so any scene can be used directly as resource.
let root = resource_manager
.request_model("examples/data/sponza/Sponza.rgs")
.request::<Model, _>("examples/data/sponza/Sponza.rgs")
.await
.unwrap()
.instantiate(&mut scene);
@@ -269,11 +269,15 @@ fn create_scene_async(
context.lock().unwrap().data = Some(GameScene { scene, root });
}
} else {
let scene = SceneLoader::from_file(LIGHTMAP_SCENE_PATH, serialization_context)
.await
.unwrap()
.finish(resource_manager)
.await;
let scene = SceneLoader::from_file(
LIGHTMAP_SCENE_PATH,
serialization_context,
resource_manager.clone(),
)
.await
.unwrap()
.finish(resource_manager)
.await;
let root = scene.graph[scene.graph.get_root()].children()[0];
context.lock().unwrap().data = Some(GameScene { scene, root });
@@ -303,7 +307,7 @@ fn main() {
let serialization_context = Arc::new(SerializationContext::new());
let mut engine = Engine::new(EngineInitParams {
graphics_context_params,
resource_manager: ResourceManager::new(serialization_context.clone()),
resource_manager: ResourceManager::new(),
serialization_context,
})
.unwrap();
+7 -4
View File
@@ -9,14 +9,17 @@ pub mod shared;
use crate::shared::create_camera;
use std::sync::Arc;
use fyrox::engine::{GraphicsContext, GraphicsContextParams};
use fyrox::resource::model::{Model, ModelResourceExtension};
use fyrox::{
asset::manager::ResourceManager,
core::{
algebra::{UnitQuaternion, Vector3},
color::Color,
pool::Handle,
},
engine::{resource_manager::ResourceManager, Engine, EngineInitParams, SerializationContext},
engine::{
Engine, EngineInitParams, GraphicsContext, GraphicsContextParams, SerializationContext,
},
event::{ElementState, Event, VirtualKeyCode, WindowEvent},
event_loop::{ControlFlow, EventLoop},
gui::{
@@ -76,7 +79,7 @@ async fn create_scene(resource_manager: ResourceManager) -> GameScene {
// models it is very efficient because single vertex and index buffer can be used
// for all models instances, so memory footprint on GPU will be lower.
let model_resource = resource_manager
.request_model("examples/data/train/train.FBX")
.request::<Model, _>("examples/data/train/train.FBX")
.await
.unwrap();
@@ -157,7 +160,7 @@ fn main() {
let serialization_context = Arc::new(SerializationContext::new());
let mut engine = Engine::new(EngineInitParams {
graphics_context_params,
resource_manager: ResourceManager::new(serialization_context.clone()),
resource_manager: ResourceManager::new(),
serialization_context,
})
.unwrap();
+7 -6
View File
@@ -7,7 +7,10 @@
pub mod shared;
use crate::shared::create_camera;
use fyrox::material::shader::Shader;
use fyrox::resource::texture::Texture;
use fyrox::{
asset::manager::ResourceManager,
core::{
algebra::{Matrix4, Vector3},
color::Color,
@@ -15,10 +18,7 @@ use fyrox::{
pool::Handle,
sstorage::ImmutableString,
},
engine::{
executor::Executor, resource_manager::ResourceManager, GraphicsContext,
GraphicsContextParams,
},
engine::{executor::Executor, GraphicsContext, GraphicsContextParams},
event_loop::ControlFlow,
gui::{
message::MessageDirection,
@@ -74,7 +74,8 @@ impl Plugin for Game {
fn create_custom_material(resource_manager: ResourceManager) -> SharedMaterial {
let shader =
block_on(resource_manager.request_shader("examples/data/shaders/custom.shader")).unwrap();
block_on(resource_manager.request::<Shader, _>("examples/data/shaders/custom.shader"))
.unwrap();
let mut material = Material::from_shader(shader, Some(resource_manager.clone()));
@@ -82,7 +83,7 @@ fn create_custom_material(resource_manager: ResourceManager) -> SharedMaterial {
.set_property(
&ImmutableString::new("diffuseTexture"),
PropertyValue::Sampler {
value: Some(resource_manager.request_texture("examples/data/concrete2.dds")),
value: Some(resource_manager.request::<Texture, _>("examples/data/concrete2.dds")),
fallback: SamplerFallback::White,
},
)
+4 -5
View File
@@ -7,7 +7,9 @@
pub mod shared;
use crate::shared::create_camera;
use fyrox::resource::model::{Model, ModelResourceExtension};
use fyrox::{
asset::manager::ResourceManager,
core::{
algebra::{Matrix4, Point3, UnitQuaternion, Vector2, Vector3},
arrayvec::ArrayVec,
@@ -17,10 +19,7 @@ use fyrox::{
sstorage::ImmutableString,
},
dpi::LogicalPosition,
engine::{
executor::Executor, resource_manager::ResourceManager, GraphicsContext,
GraphicsContextParams,
},
engine::{executor::Executor, GraphicsContext, GraphicsContextParams},
event::{ElementState, Event, VirtualKeyCode, WindowEvent},
event_loop::ControlFlow,
gui::{
@@ -82,7 +81,7 @@ async fn create_scene(resource_manager: ResourceManager) -> GameScene {
));
resource_manager
.request_model("examples/data/navmesh_scene.rgs")
.request::<Model, _>("examples/data/navmesh_scene.rgs")
.await
.unwrap()
.instantiate(&mut scene);
+2
View File
@@ -1,3 +1,4 @@
use fyrox::resource::texture::TextureResourceExtension;
use fyrox::{
core::{algebra::Vector2, futures::executor::block_on, pool::Handle},
engine::{executor::Executor, GraphicsContext, GraphicsContextParams},
@@ -84,6 +85,7 @@ fn load_scene(context: &PluginContext) -> Scene {
let loader = block_on(SceneLoader::from_file(
"examples/data/rt_scene.rgs",
context.serialization_context.clone(),
context.resource_manager.clone(),
))
.unwrap();
block_on(loader.finish(context.resource_manager.clone()))
+1
View File
@@ -132,6 +132,7 @@ async fn load(game: &mut Game) {
let scene = SceneLoader::load(
"Scene",
game.engine.serialization_context.clone(),
game.engine.resource_manager.clone(),
&mut visitor,
)
.unwrap()
+7 -4
View File
@@ -9,14 +9,17 @@
pub mod shared;
use crate::shared::create_camera;
use fyrox::engine::{GraphicsContext, GraphicsContextParams};
use fyrox::resource::model::{Model, ModelResourceExtension};
use fyrox::{
asset::manager::ResourceManager,
core::{
algebra::{UnitQuaternion, Vector3},
color::Color,
pool::Handle,
},
engine::{resource_manager::ResourceManager, Engine, EngineInitParams, SerializationContext},
engine::{
Engine, EngineInitParams, GraphicsContext, GraphicsContextParams, SerializationContext,
},
event::{ElementState, Event, VirtualKeyCode, WindowEvent},
event_loop::{ControlFlow, EventLoop},
gui::{
@@ -63,7 +66,7 @@ async fn create_scene(resource_manager: ResourceManager) -> GameScene {
// There is no difference between scene created in Fyroxed and any other
// model file, so any scene can be used directly as resource.
resource_manager
.request_model("examples/data/test_scene.rgs")
.request::<Model, _>("examples/data/test_scene.rgs")
.await
.unwrap()
.instantiate(&mut scene);
@@ -91,7 +94,7 @@ fn main() {
let serialization_context = Arc::new(SerializationContext::new());
let mut engine = Engine::new(EngineInitParams {
graphics_context_params,
resource_manager: ResourceManager::new(serialization_context.clone()),
resource_manager: ResourceManager::new(),
serialization_context,
})
.unwrap();
+9 -7
View File
@@ -7,17 +7,17 @@
pub mod shared;
use crate::shared::create_camera;
use fyrox::resource::model::{Model, ModelResourceExtension};
use fyrox::resource::texture::Texture;
use fyrox::{
asset::manager::ResourceManager,
core::{
algebra::{Matrix4, UnitQuaternion, Vector3},
color::Color,
pool::Handle,
sstorage::ImmutableString,
},
engine::{
executor::Executor, resource_manager::ResourceManager, GraphicsContext,
GraphicsContextParams,
},
engine::{executor::Executor, GraphicsContext, GraphicsContextParams},
event::{ElementState, Event, VirtualKeyCode, WindowEvent},
event_loop::ControlFlow,
gui::{
@@ -81,8 +81,8 @@ impl GameSceneLoader {
// of it. In case of models it is very efficient because single vertex and index buffer
// can be used for all models instances, so memory footprint on GPU will be lower.
let (model_resource, walk_animation_resource) = fyrox::core::futures::join!(
resource_manager.request_model("examples/data/mutant/mutant.FBX",),
resource_manager.request_model("examples/data/mutant/walk.fbx",)
resource_manager.request::<Model, _>("examples/data/mutant/mutant.FBX",),
resource_manager.request::<Model, _>("examples/data/mutant/walk.fbx",)
);
// Instantiate model on scene - but only geometry, without any animations.
@@ -111,7 +111,9 @@ impl GameSceneLoader {
.set_property(
&ImmutableString::new("diffuseTexture"),
PropertyValue::Sampler {
value: Some(resource_manager.request_texture("examples/data/concrete2.dds")),
value: Some(
resource_manager.request::<Texture, _>("examples/data/concrete2.dds"),
),
fallback: SamplerFallback::White,
},
)
+2 -1
View File
@@ -35,6 +35,7 @@ use fyrox::{
translate_event,
},
};
use fyrox_sound::buffer::SoundBuffer;
use fyrox_sound::bus::AudioBusGraph;
use std::time::Instant;
@@ -66,7 +67,7 @@ fn main() {
fyrox::core::futures::executor::block_on(fyrox::core::futures::future::join_all(
footstep_paths
.iter()
.map(|&path| game.engine.resource_manager.request_sound_buffer(path)),
.map(|&path| game.engine.resource_manager.request::<SoundBuffer, _>(path)),
))
.into_iter()
.map(|r| r.unwrap())
+6 -6
View File
@@ -9,16 +9,16 @@
pub mod shared;
use crate::shared::create_camera;
use fyrox::engine::GraphicsContext;
use fyrox::resource::model::{Model, ModelResourceExtension};
use fyrox::{
asset::manager::ResourceManager,
core::{
algebra::{UnitQuaternion, Vector2, Vector3},
color::Color,
pool::Handle,
},
engine::{
resource_manager::ResourceManager, Engine, EngineInitParams, GraphicsContextParams,
SerializationContext,
Engine, EngineInitParams, GraphicsContext, GraphicsContextParams, SerializationContext,
},
event::{ElementState, Event, VirtualKeyCode, WindowEvent},
event_loop::{ControlFlow, EventLoop},
@@ -298,7 +298,7 @@ async fn create_scene(resource_manager: ResourceManager) -> GameScene {
// models it is very efficient because single vertex and index buffer can be used
// for all models instances, so memory footprint on GPU will be lower.
let model_resource = resource_manager
.request_model("examples/data/mutant/mutant.FBX")
.request::<Model, _>("examples/data/mutant/mutant.FBX")
.await
.unwrap();
@@ -307,7 +307,7 @@ async fn create_scene(resource_manager: ResourceManager) -> GameScene {
// Add simple animation for our model. Animations are loaded from model resources -
// this is because animation is a set of skeleton bones with their own transforms.
let walk_animation_resource = resource_manager
.request_model("examples/data/mutant/walk.fbx")
.request::<Model, _>("examples/data/mutant/walk.fbx")
.await
.unwrap();
@@ -336,7 +336,7 @@ fn main() {
let serialization_context = Arc::new(SerializationContext::new());
let mut engine = Engine::new(EngineInitParams {
graphics_context_params,
resource_manager: ResourceManager::new(serialization_context.clone()),
resource_manager: ResourceManager::new(),
serialization_context,
})
.unwrap();
+1
View File
@@ -1,4 +1,5 @@
use fyrox_core::algebra::Point3;
use fyrox_sound::buffer::SoundBufferResourceExtension;
use fyrox_sound::{
algebra::{UnitQuaternion, Vector3},
buffer::{DataSource, SoundBufferResource},
+1
View File
@@ -1,4 +1,5 @@
use fyrox_core::algebra::Point3;
use fyrox_sound::buffer::SoundBufferResourceExtension;
use fyrox_sound::{
algebra::{UnitQuaternion, Vector3},
buffer::{DataSource, SoundBufferResource},
+1
View File
@@ -1,3 +1,4 @@
use fyrox_sound::buffer::SoundBufferResourceExtension;
use fyrox_sound::{
buffer::{DataSource, SoundBufferResource},
context::SoundContext,
@@ -1,4 +1,5 @@
use fyrox_core::futures::executor::block_on;
use fyrox_sound::buffer::SoundBufferResourceExtension;
use fyrox_sound::{
algebra::{Point3, UnitQuaternion, Vector3},
buffer::{DataSource, SoundBufferResource},
+1
View File
@@ -1,3 +1,4 @@
use fyrox_sound::buffer::SoundBufferResourceExtension;
use fyrox_sound::engine::SoundEngine;
use fyrox_sound::{
buffer::{DataSource, SoundBufferResource},
+1
View File
@@ -1,3 +1,4 @@
use fyrox_sound::buffer::SoundBufferResourceExtension;
use fyrox_sound::{
buffer::{DataSource, RawStreamingDataSource, SoundBufferResource},
context::SoundContext,
+1
View File
@@ -1,3 +1,4 @@
use fyrox_sound::buffer::SoundBufferResourceExtension;
use fyrox_sound::{
algebra::{Point3, UnitQuaternion, Vector3},
buffer::{DataSource, SoundBufferResource},
+1
View File
@@ -1,3 +1,4 @@
use fyrox_sound::buffer::SoundBufferResourceExtension;
use fyrox_sound::{
buffer::{DataSource, SoundBufferResource},
context::SoundContext,
+1
View File
@@ -1,3 +1,4 @@
use fyrox_sound::buffer::SoundBufferResourceExtension;
use fyrox_sound::engine::State;
use fyrox_sound::{
buffer::{DataSource, SoundBufferResource},
+22 -20
View File
@@ -178,6 +178,28 @@ pub enum SoundBuffer {
pub type SoundBufferResource = Resource<SoundBuffer>;
pub trait SoundBufferResourceExtension {
/// Tries to create new streaming sound buffer from a given data source.
fn new_streaming(data_source: DataSource) -> Result<Resource<SoundBuffer>, DataSource>;
/// Tries to create new generic sound buffer from a given data source.
fn new_generic(data_source: DataSource) -> Result<Resource<SoundBuffer>, DataSource>;
}
impl SoundBufferResourceExtension for SoundBufferResource {
fn new_streaming(data_source: DataSource) -> Result<Resource<SoundBuffer>, DataSource> {
Ok(Resource::new_ok(SoundBuffer::Streaming(
StreamingBuffer::new(data_source)?,
)))
}
fn new_generic(data_source: DataSource) -> Result<Resource<SoundBuffer>, DataSource> {
Ok(Resource::new_ok(SoundBuffer::Generic(GenericBuffer::new(
data_source,
)?)))
}
}
impl TypeUuidProvider for SoundBuffer {
fn type_uuid() -> Uuid {
SOUND_BUFFER_RESOURCE_UUID
@@ -196,26 +218,6 @@ impl SoundBuffer {
pub fn raw_generic(data_source: DataSource) -> Result<Self, DataSource> {
Ok(Self::Generic(GenericBuffer::new(data_source)?))
}
/// Tries to create new streaming sound buffer from a given data source. Returns sound source
/// wrapped into Arc<Mutex<>> that can be directly used with sound sources.
pub fn new_streaming_resource(
data_source: DataSource,
) -> Result<Resource<SoundBuffer>, DataSource> {
Ok(Resource::new_ok(SoundBuffer::Streaming(
StreamingBuffer::new(data_source)?,
)))
}
/// Tries to create new generic sound buffer from a given data source. Returns sound source
/// wrapped into Arc<Mutex<>> that can be directly used with sound sources.
pub fn new_generic_resource(
data_source: DataSource,
) -> Result<Resource<SoundBuffer>, DataSource> {
Ok(Resource::new_ok(SoundBuffer::Generic(GenericBuffer::new(
data_source,
)?)))
}
}
impl Default for SoundBuffer {
+10 -6
View File
@@ -28,7 +28,7 @@ use crate::{
resource::{
curve::CurveResourceState,
model::{Model, ModelResource},
texture::{Texture, TextureKind, TextureResource},
texture::{Texture, TextureKind},
},
scene::{
base::NodeScriptMessage,
@@ -1532,14 +1532,18 @@ impl Drop for Engine {
#[cfg(test)]
mod test {
use crate::script::{ScriptMessageContext, ScriptMessagePayload};
use crate::{
asset::manager::ResourceManager,
core::{pool::Handle, reflect::prelude::*, uuid::Uuid, visitor::prelude::*},
engine::{resource_manager::ResourceManager, ScriptProcessor},
engine::ScriptProcessor,
impl_component_provider,
scene::{base::BaseBuilder, node::Node, pivot::PivotBuilder, Scene, SceneContainer},
script::{Script, ScriptContext, ScriptDeinitContext, ScriptTrait},
script::{
Script, ScriptContext, ScriptDeinitContext, ScriptMessageContext, ScriptMessagePayload,
ScriptTrait,
},
};
use std::sync::mpsc::{self, Sender, TryRecvError};
#[derive(PartialEq, Eq, Clone, Debug)]
@@ -1642,7 +1646,7 @@ mod test {
#[test]
fn test_order() {
let resource_manager = ResourceManager::new(Default::default());
let resource_manager = ResourceManager::new();
let mut scene = Scene::new();
let (tx, rx) = mpsc::channel();
@@ -1808,7 +1812,7 @@ mod test {
#[test]
fn test_messages() {
let resource_manager = ResourceManager::new(Default::default());
let resource_manager = ResourceManager::new();
let mut scene = Scene::new();
let (tx, rx) = mpsc::channel();
+1 -1
View File
@@ -646,7 +646,7 @@ lazy_static! {
mod test {
use crate::material::shader::{
PropertyDefinition, PropertyKind, RenderPassDefinition, SamplerFallback, ShaderDefinition,
ShaderResource,
ShaderResource, ShaderResourceExtension,
};
#[test]
+38 -38
View File
@@ -84,8 +84,10 @@ pub trait ModelResourceExtension: Sized {
dest_graph: &mut Graph,
) -> (Handle<Node>, NodeHandleMap);
/// Tries to instantiate model from given resource.
fn instantiate(&self, dest_scene: &mut Scene) -> Handle<Node>;
/// Instantiates a prefab and places it at specified position and orientation in global coordinates.
fn instantiate_at(
&self,
scene: &mut Scene,
@@ -93,8 +95,37 @@ pub trait ModelResourceExtension: Sized {
orientation: UnitQuaternion<f32>,
) -> Handle<Node>;
/// Tries to retarget animations from given model resource to a node hierarchy starting
/// from `root` on a given scene.
///
/// Animation retargeting allows you to "transfer" animation from a model to a model
/// instance on a scene. Imagine you have a character that should have multiple animations
/// like idle, run, shoot, walk, etc. and you want to store each animation in a separate
/// file. Then when you creating a character on a level you want to have all possible
/// animations assigned to a character, this is where this function comes into play:
/// you just load a model of your character with skeleton, but without any animations,
/// then you load several "models" which have only skeleton with some animation (such
/// "models" can be considered as "animation" resources). After this you need to
/// instantiate model on your level and retarget all animations you need to that instance
/// from other "models". All you have after this is a handle to a model and bunch of
/// handles to specific animations. After this animations can be blended in any combinations
/// you need to. For example idle animation can be blended with walk animation when your
/// character starts walking.
///
/// # Notes
///
/// Most of the 3d model formats can contain only one animation, so in most cases
/// this function will return vector with only one animation.
fn retarget_animations_directly(&self, root: Handle<Node>, graph: &Graph) -> Vec<Animation>;
/// Tries to retarget animations from given model resource to a node hierarchy starting
/// from `root` on a given scene. Unlike [`Self::retarget_animations_directly`], it automatically
/// adds retargetted animations to the specified animation player in the hierarchy of given `root`.
///
/// # Panic
///
/// Panics if `dest_animation_player` is invalid handle, or the node does not have [`AnimationPlayer`]
/// component.
fn retarget_animations_to_player(
&self,
root: Handle<Node>,
@@ -102,6 +133,13 @@ pub trait ModelResourceExtension: Sized {
graph: &mut Graph,
) -> Vec<Handle<Animation>>;
/// Tries to retarget animations from given model resource to a node hierarchy starting
/// from `root` on a given scene. Unlike [`Self::retarget_animations_directly`], it automatically
/// adds retargetted animations to a first animation player in the hierarchy of given `root`.
///
/// # Panic
///
/// Panics if there's no animation player in the given hierarchy (descendant nodes of `root`).
fn retarget_animations(&self, root: Handle<Node>, graph: &mut Graph) -> Vec<Handle<Animation>>;
}
@@ -145,7 +183,6 @@ impl ModelResourceExtension for ModelResource {
(root, old_to_new)
}
/// Tries to instantiate model from given resource.
fn instantiate(&self, dest_scene: &mut Scene) -> Handle<Node> {
let data = self.data_ref();
@@ -163,7 +200,6 @@ impl ModelResourceExtension for ModelResource {
instance_root
}
/// Instantiates a prefab and places it at specified position and orientation in global coordinates.
fn instantiate_at(
&self,
scene: &mut Scene,
@@ -182,27 +218,6 @@ impl ModelResourceExtension for ModelResource {
root
}
/// Tries to retarget animations from given model resource to a node hierarchy starting
/// from `root` on a given scene.
///
/// Animation retargeting allows you to "transfer" animation from a model to a model
/// instance on a scene. Imagine you have a character that should have multiple animations
/// like idle, run, shoot, walk, etc. and you want to store each animation in a separate
/// file. Then when you creating a character on a level you want to have all possible
/// animations assigned to a character, this is where this function comes into play:
/// you just load a model of your character with skeleton, but without any animations,
/// then you load several "models" which have only skeleton with some animation (such
/// "models" can be considered as "animation" resources). After this you need to
/// instantiate model on your level and retarget all animations you need to that instance
/// from other "models". All you have after this is a handle to a model and bunch of
/// handles to specific animations. After this animations can be blended in any combinations
/// you need to. For example idle animation can be blended with walk animation when your
/// character starts walking.
///
/// # Notes
///
/// Most of the 3d model formats can contain only one animation, so in most cases
/// this function will return vector with only one animation.
fn retarget_animations_directly(&self, root: Handle<Node>, graph: &Graph) -> Vec<Animation> {
let mut retargetted_animations = Vec::new();
@@ -247,14 +262,6 @@ impl ModelResourceExtension for ModelResource {
retargetted_animations
}
/// Tries to retarget animations from given model resource to a node hierarchy starting
/// from `root` on a given scene. Unlike [`Self::retarget_animations_directly`], it automatically
/// adds retargetted animations to the specified animation player in the hierarchy of given `root`.
///
/// # Panic
///
/// Panics if `dest_animation_player` is invalid handle, or the node does not have [`AnimationPlayer`]
/// component.
fn retarget_animations_to_player(
&self,
root: Handle<Node>,
@@ -276,13 +283,6 @@ impl ModelResourceExtension for ModelResource {
animation_handles
}
/// Tries to retarget animations from given model resource to a node hierarchy starting
/// from `root` on a given scene. Unlike [`Self::retarget_animations_directly`], it automatically
/// adds retargetted animations to a first animation player in the hierarchy of given `root`.
///
/// # Panic
///
/// Panics if there's no animation player in the given hierarchy (descendant nodes of `root`).
fn retarget_animations(&self, root: Handle<Node>, graph: &mut Graph) -> Vec<Handle<Animation>> {
if let Some((animation_player, _)) = graph.find(root, &mut |n| {
n.query_component_ref::<AnimationPlayer>().is_some()
+44 -42
View File
@@ -427,46 +427,10 @@ impl TextureImportOptions {
pub type TextureResource = Resource<Texture>;
pub trait TextureResourceExtension: Sized {
fn new_render_target(width: u32, height: u32) -> Self;
fn load_from_memory(
data: &[u8],
compression: CompressionOptions,
gen_mip_maps: bool,
) -> Result<Self, TextureError>;
fn from_bytes(
kind: TextureKind,
pixel_kind: TexturePixelKind,
bytes: Vec<u8>,
serialize_content: bool,
) -> Option<Self>;
fn deep_clone(&self) -> Self;
}
impl TextureResourceExtension for TextureResource {
/// Creates new render target for a scene. This method automatically configures GPU texture
/// to correct settings, after render target was created, it must not be modified, otherwise
/// result is undefined.
fn new_render_target(width: u32, height: u32) -> Self {
Resource::new_ok(Texture {
path: Default::default(),
// Render target will automatically set width and height before rendering.
kind: TextureKind::Rectangle { width, height },
bytes: Default::default(),
pixel_kind: TexturePixelKind::RGBA8,
minification_filter: TextureMinificationFilter::Linear,
magnification_filter: TextureMagnificationFilter::Linear,
s_wrap_mode: TextureWrapMode::Repeat,
t_wrap_mode: TextureWrapMode::Repeat,
mip_count: 1,
anisotropy: 1.0,
serialize_content: false,
data_hash: 0,
is_render_target: true,
})
}
fn new_render_target(width: u32, height: u32) -> Self;
/// Tries to load a texture from given data. Use this method if you want to
/// load a texture from embedded data.
@@ -485,6 +449,46 @@ impl TextureResourceExtension for TextureResource {
/// loading. You should use `ResourceManager::request_texture` in majority of cases!
///
/// Main use cases for this method are: procedural textures, icons for GUI.
fn load_from_memory(
data: &[u8],
compression: CompressionOptions,
gen_mip_maps: bool,
) -> Result<Self, TextureError>;
/// Tries to create new texture from given parameters, it may fail only if size of data passed
/// in does not match with required.
fn from_bytes(
kind: TextureKind,
pixel_kind: TexturePixelKind,
bytes: Vec<u8>,
serialize_content: bool,
) -> Option<Self>;
/// Creates a deep clone of the texture. Unlike [`TextureResource::clone`], this method clones the actual texture data,
/// which could be slow.
fn deep_clone(&self) -> Self;
}
impl TextureResourceExtension for TextureResource {
fn new_render_target(width: u32, height: u32) -> Self {
Resource::new_ok(Texture {
path: Default::default(),
// Render target will automatically set width and height before rendering.
kind: TextureKind::Rectangle { width, height },
bytes: Default::default(),
pixel_kind: TexturePixelKind::RGBA8,
minification_filter: TextureMinificationFilter::Linear,
magnification_filter: TextureMagnificationFilter::Linear,
s_wrap_mode: TextureWrapMode::Repeat,
t_wrap_mode: TextureWrapMode::Repeat,
mip_count: 1,
anisotropy: 1.0,
serialize_content: false,
data_hash: 0,
is_render_target: true,
})
}
fn load_from_memory(
data: &[u8],
compression: CompressionOptions,
@@ -497,8 +501,6 @@ impl TextureResourceExtension for TextureResource {
)?))
}
/// Tries to create new texture from given parameters, it may fail only if size of data passed
/// in does not match with required.
fn from_bytes(
kind: TextureKind,
pixel_kind: TexturePixelKind,
@@ -513,8 +515,6 @@ impl TextureResourceExtension for TextureResource {
)?))
}
/// Creates a deep clone of the texture. Unlike [`TextureResource::clone`], this method clones the actual texture data,
/// which could be slow.
fn deep_clone(&self) -> Self {
Resource::new_ok(self.data_ref().clone())
}
@@ -1549,7 +1549,9 @@ impl<'a> TextureDataRefMut<'a> {
#[cfg(test)]
pub mod test {
use crate::resource::texture::{TextureKind, TexturePixelKind, TextureResource};
use crate::resource::texture::{
TextureKind, TexturePixelKind, TextureResource, TextureResourceExtension,
};
pub fn create_test_texture() -> TextureResource {
TextureResource::from_bytes(
-12
View File
@@ -249,18 +249,6 @@ pub struct SceneLoader {
scene: Scene,
}
#[derive(Default)]
struct UsedResourcesSet {
models: FxHashSet<UntypedResource>,
}
impl UsedResourcesSet {
/// Waits asynchronously.
async fn wait_async(self) {
join_all(self.models).await;
}
}
impl SceneLoader {
/// Tries to load scene from given file. File can contain any scene in native engine format.
/// Such scenes can be made in rusty editor.