mirror of
https://github.com/kaosat-dev/Blender_bevy_components_workflow.git
synced 2024-11-22 20:00:53 +00:00
feat(asset preloading): experimented with using the underlying gltf crate
to get the list of assets & preload them * a tiny bit clunky but works and is somewhat cleaner than the previous "staggered loading" approach * enables having level load state (could be used for progress information & co) * modified blueprints spawning to used the new system * various cleanups & related tweaks * fixed issues on the Blender side when with the formating of the ron data for assets
This commit is contained in:
parent
e232fedc4b
commit
253d33f1bb
@ -1,11 +1,12 @@
|
|||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
use bevy::{asset::LoadedUntypedAsset, gltf::Gltf, prelude::*, utils::HashMap};
|
use bevy::{asset::LoadedUntypedAsset, gltf::Gltf, prelude::*, utils::HashMap};
|
||||||
|
use serde::Deserialize;
|
||||||
|
|
||||||
use crate::{BlenvyConfig, BlueprintAnimations};
|
use crate::{BlenvyConfig, BlueprintAnimations};
|
||||||
|
|
||||||
/// helper component, is used to store the list of sub blueprints to enable automatic loading of dependend blueprints
|
/// helper component, is used to store the list of sub blueprints to enable automatic loading of dependend blueprints
|
||||||
#[derive(Component, Reflect, Default, Debug)]
|
#[derive(Component, Reflect, Default, Debug, Deserialize)]
|
||||||
#[reflect(Component)]
|
#[reflect(Component)]
|
||||||
pub struct MyAsset{
|
pub struct MyAsset{
|
||||||
pub name: String,
|
pub name: String,
|
||||||
@ -13,7 +14,7 @@ pub struct MyAsset{
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// helper component, is used to store the list of sub blueprints to enable automatic loading of dependend blueprints
|
/// helper component, is used to store the list of sub blueprints to enable automatic loading of dependend blueprints
|
||||||
#[derive(Component, Reflect, Default, Debug)]
|
#[derive(Component, Reflect, Default, Debug, Deserialize)]
|
||||||
#[reflect(Component)]
|
#[reflect(Component)]
|
||||||
pub struct BlenvyAssets(pub Vec<MyAsset>);
|
pub struct BlenvyAssets(pub Vec<MyAsset>);
|
||||||
|
|
||||||
@ -42,12 +43,12 @@ pub(crate) struct AssetLoadTracker {
|
|||||||
|
|
||||||
/// helper component, for tracking loaded assets
|
/// helper component, for tracking loaded assets
|
||||||
#[derive(Component, Debug)]
|
#[derive(Component, Debug)]
|
||||||
pub(crate) struct AssetsToLoad {
|
pub(crate) struct BlenvyAssetsLoadState {
|
||||||
pub all_loaded: bool,
|
pub all_loaded: bool,
|
||||||
pub asset_infos: Vec<AssetLoadTracker>,
|
pub asset_infos: Vec<AssetLoadTracker>,
|
||||||
pub progress: f32,
|
pub progress: f32,
|
||||||
}
|
}
|
||||||
impl Default for AssetsToLoad {
|
impl Default for BlenvyAssetsLoadState {
|
||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
Self {
|
Self {
|
||||||
all_loaded: Default::default(),
|
all_loaded: Default::default(),
|
||||||
|
@ -17,7 +17,7 @@ use bevy::{
|
|||||||
render::mesh::Mesh,
|
render::mesh::Mesh,
|
||||||
};
|
};
|
||||||
|
|
||||||
use crate::{AssetLoadTracker, AssetsToLoad, BlenvyConfig, BlueprintInstanceReady};
|
use crate::{AssetLoadTracker, BlenvyAssetsLoadState, BlenvyConfig, BlueprintInstanceReady};
|
||||||
|
|
||||||
#[derive(Component, Reflect, Default, Debug)]
|
#[derive(Component, Reflect, Default, Debug)]
|
||||||
#[reflect(Component)]
|
#[reflect(Component)]
|
||||||
@ -71,7 +71,7 @@ pub(crate) fn materials_inject(
|
|||||||
|
|
||||||
commands
|
commands
|
||||||
.entity(entity)
|
.entity(entity)
|
||||||
.insert(AssetsToLoad {
|
.insert(BlenvyAssetsLoadState {
|
||||||
all_loaded: false,
|
all_loaded: false,
|
||||||
asset_infos,
|
asset_infos,
|
||||||
..Default::default()
|
..Default::default()
|
||||||
@ -85,7 +85,7 @@ pub(crate) fn materials_inject(
|
|||||||
// TODO, merge with blueprints_check_assets_loading, make generic ?
|
// TODO, merge with blueprints_check_assets_loading, make generic ?
|
||||||
pub(crate) fn check_for_material_loaded(
|
pub(crate) fn check_for_material_loaded(
|
||||||
mut blueprint_assets_to_load: Query<
|
mut blueprint_assets_to_load: Query<
|
||||||
(Entity, &mut AssetsToLoad),
|
(Entity, &mut BlenvyAssetsLoadState),
|
||||||
With<BlueprintMaterialAssetsNotLoaded>,
|
With<BlueprintMaterialAssetsNotLoaded>,
|
||||||
>,
|
>,
|
||||||
asset_server: Res<AssetServer>,
|
asset_server: Res<AssetServer>,
|
||||||
|
396
crates/blenvy/src/blueprints/spawn_from_blueprints copy.rs
Normal file
396
crates/blenvy/src/blueprints/spawn_from_blueprints copy.rs
Normal file
@ -0,0 +1,396 @@
|
|||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
use bevy::{gltf::Gltf, prelude::*, utils::hashbrown::HashMap};
|
||||||
|
use serde_json::Value;
|
||||||
|
|
||||||
|
use crate::{BlenvyAssets, AssetsToLoad, AssetLoadTracker, BlenvyConfig, BlueprintAnimations, BlueprintAssetsLoaded, BlueprintAssetsNotLoaded};
|
||||||
|
|
||||||
|
/// this is a flag component for our levels/game world
|
||||||
|
#[derive(Component)]
|
||||||
|
pub struct GameWorldTag;
|
||||||
|
|
||||||
|
/// Main component for the blueprints
|
||||||
|
#[derive(Component, Reflect, Default, Debug)]
|
||||||
|
#[reflect(Component)]
|
||||||
|
pub struct BlueprintName(pub String);
|
||||||
|
|
||||||
|
/// path component for the blueprints
|
||||||
|
#[derive(Component, Reflect, Default, Debug)]
|
||||||
|
#[reflect(Component)]
|
||||||
|
pub struct BlueprintPath(pub String);
|
||||||
|
|
||||||
|
/// flag component needed to signify the intent to spawn a Blueprint
|
||||||
|
#[derive(Component, Reflect, Default, Debug)]
|
||||||
|
#[reflect(Component)]
|
||||||
|
pub struct SpawnHere;
|
||||||
|
|
||||||
|
#[derive(Component)]
|
||||||
|
/// flag component for dynamically spawned scenes
|
||||||
|
pub struct Spawned;
|
||||||
|
|
||||||
|
|
||||||
|
#[derive(Component, Debug)]
|
||||||
|
/// flag component added when a Blueprint instance ist Ready : ie :
|
||||||
|
/// - its assets have loaded
|
||||||
|
/// - it has finished spawning
|
||||||
|
pub struct BlueprintInstanceReady;
|
||||||
|
|
||||||
|
#[derive(Component, Reflect, Default, Debug)]
|
||||||
|
#[reflect(Component)]
|
||||||
|
/// flag component marking any spwaned child of blueprints ..unless the original entity was marked with the `NoInBlueprint` marker component
|
||||||
|
pub struct InBlueprint;
|
||||||
|
|
||||||
|
#[derive(Component, Reflect, Default, Debug)]
|
||||||
|
#[reflect(Component)]
|
||||||
|
/// flag component preventing any spawned child of blueprints to be marked with the `InBlueprint` component
|
||||||
|
pub struct NoInBlueprint;
|
||||||
|
|
||||||
|
#[derive(Component, Reflect, Default, Debug)]
|
||||||
|
#[reflect(Component)]
|
||||||
|
// this allows overriding the default library path for a given entity/blueprint
|
||||||
|
pub struct Library(pub PathBuf);
|
||||||
|
|
||||||
|
#[derive(Component, Reflect, Default, Debug)]
|
||||||
|
#[reflect(Component)]
|
||||||
|
/// flag component to force adding newly spawned entity as child of game world
|
||||||
|
pub struct AddToGameWorld;
|
||||||
|
|
||||||
|
#[derive(Component)]
|
||||||
|
/// helper component, just to transfer child data
|
||||||
|
pub(crate) struct OriginalChildren(pub Vec<Entity>);
|
||||||
|
|
||||||
|
|
||||||
|
#[derive(Event, Debug)]
|
||||||
|
pub enum BlueprintEvent {
|
||||||
|
|
||||||
|
/// event fired when a blueprint has finished loading its assets & before it attempts spawning
|
||||||
|
AssetsLoaded {
|
||||||
|
blueprint_name: String,
|
||||||
|
blueprint_path: String,
|
||||||
|
// TODO: add assets list ?
|
||||||
|
},
|
||||||
|
/// event fired when a blueprint is COMPLETELY done spawning ie
|
||||||
|
/// - all its assets have been loaded
|
||||||
|
/// - the spawning attempt has been sucessfull
|
||||||
|
Spawned {
|
||||||
|
blueprint_name: String,
|
||||||
|
blueprint_path: String,
|
||||||
|
},
|
||||||
|
|
||||||
|
///
|
||||||
|
Ready {
|
||||||
|
blueprint_path: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
use gltf::Gltf as RawGltf;
|
||||||
|
|
||||||
|
pub(crate) fn blueprints_prepare_spawn(
|
||||||
|
spawn_placeholders: Query<
|
||||||
|
(
|
||||||
|
Entity,
|
||||||
|
&BlueprintPath,
|
||||||
|
),
|
||||||
|
(Added<BlueprintPath>, Without<Spawned>, Without<SpawnHere>)>,
|
||||||
|
|
||||||
|
// before 0.14 we have to use a seperate query, after migrating we can query at the root level
|
||||||
|
entities_with_assets: Query<
|
||||||
|
(
|
||||||
|
Entity,
|
||||||
|
/*&BlueprintName,
|
||||||
|
&BlueprintPath,
|
||||||
|
Option<&Parent>,*/
|
||||||
|
Option<&Name>,
|
||||||
|
Option<&BlenvyAssets>,
|
||||||
|
),
|
||||||
|
(Added<BlenvyAssets>), // Added<BlenvyAssets>
|
||||||
|
>,
|
||||||
|
|
||||||
|
|
||||||
|
bla_bla : Query<
|
||||||
|
(
|
||||||
|
Entity,
|
||||||
|
&BlueprintName,
|
||||||
|
&BlueprintPath,
|
||||||
|
Option<&Parent>,
|
||||||
|
Option<&BlenvyAssets>,
|
||||||
|
),(Added<BlueprintPath>)
|
||||||
|
>,
|
||||||
|
mut commands: Commands,
|
||||||
|
asset_server: Res<AssetServer>,
|
||||||
|
|
||||||
|
|
||||||
|
) {
|
||||||
|
for (entity, blueprint_path) in spawn_placeholders.iter() {
|
||||||
|
println!("added blueprint_path {:?}", blueprint_path);
|
||||||
|
/*commands.entity(entity).insert(
|
||||||
|
SceneBundle {
|
||||||
|
scene: asset_server.load(format!("{}#Scene0", &blueprint_path.0)), // "levels/World.glb#Scene0"),
|
||||||
|
..default()
|
||||||
|
},
|
||||||
|
);*/
|
||||||
|
// let model_handle: Handle<Gltf> = asset_server.load(model_path.clone());
|
||||||
|
}
|
||||||
|
|
||||||
|
for (entity, blueprint_name, blueprint_path, parent, all_assets) in bla_bla.iter() {
|
||||||
|
println!("added blueprint to spawn {:?} {:?}", blueprint_name, blueprint_path);
|
||||||
|
println!("all assets {:?}", all_assets);
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/* prefetch attempt */
|
||||||
|
let gltf = RawGltf::open(format!("assets/{}", blueprint_path.0)).unwrap();// RawGltf::open("examples/Box.gltf")?;
|
||||||
|
for scene in gltf.scenes() {
|
||||||
|
let foo_extras = scene.extras().clone().unwrap();
|
||||||
|
|
||||||
|
let lookup: HashMap<String, Value> = serde_json::from_str(&foo_extras.get()).unwrap();
|
||||||
|
for (key, value) in lookup.clone().into_iter() {
|
||||||
|
println!("{} / {}", key, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
if lookup.contains_key("BlenvyAssets"){
|
||||||
|
let assets_raw = &lookup["BlenvyAssets"];
|
||||||
|
println!("ASSETS RAW {}", assets_raw);
|
||||||
|
let x: BlenvyAssets = ron::from_str(&assets_raw.as_str().unwrap()).unwrap();
|
||||||
|
println!("YAHA {:?}", x);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
//println!("SCENE EXTRAS {:?}", foo_extras);
|
||||||
|
}
|
||||||
|
|
||||||
|
//////////////
|
||||||
|
|
||||||
|
|
||||||
|
let untyped_handle = asset_server.load_untyped(&blueprint_path.0);
|
||||||
|
let asset_id = untyped_handle.id();
|
||||||
|
let loaded = asset_server.is_loaded_with_dependencies(asset_id);
|
||||||
|
|
||||||
|
let mut asset_infos: Vec<AssetLoadTracker> = vec![];
|
||||||
|
if !loaded {
|
||||||
|
asset_infos.push(AssetLoadTracker {
|
||||||
|
name: blueprint_name.0.clone(),
|
||||||
|
id: asset_id,
|
||||||
|
loaded: false,
|
||||||
|
handle: untyped_handle.clone(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// now insert load tracker
|
||||||
|
if !asset_infos.is_empty() {
|
||||||
|
commands
|
||||||
|
.entity(entity)
|
||||||
|
.insert(AssetsToLoad {
|
||||||
|
all_loaded: false,
|
||||||
|
asset_infos,
|
||||||
|
..Default::default()
|
||||||
|
})
|
||||||
|
.insert(BlueprintAssetsNotLoaded);
|
||||||
|
} else {
|
||||||
|
commands.entity(entity).insert(BlueprintAssetsLoaded);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (child_entity, child_entity_name, all_assets) in entities_with_assets.iter(){
|
||||||
|
println!("added assets {:?} to {:?}", all_assets, child_entity_name);
|
||||||
|
if all_assets.is_some() {
|
||||||
|
let mut asset_infos: Vec<AssetLoadTracker> = vec![];
|
||||||
|
|
||||||
|
for asset in all_assets.unwrap().0.iter() {
|
||||||
|
let untyped_handle = asset_server.load_untyped(&asset.path);
|
||||||
|
//println!("untyped handle {:?}", untyped_handle);
|
||||||
|
//asset_server.load(asset.path);
|
||||||
|
|
||||||
|
let asset_id = untyped_handle.id();
|
||||||
|
//println!("ID {:?}", asset_id);
|
||||||
|
let loaded = asset_server.is_loaded_with_dependencies(asset_id);
|
||||||
|
//println!("Loaded ? {:?}", loaded);
|
||||||
|
if !loaded {
|
||||||
|
asset_infos.push(AssetLoadTracker {
|
||||||
|
name: asset.name.clone(),
|
||||||
|
id: asset_id,
|
||||||
|
loaded: false,
|
||||||
|
handle: untyped_handle.clone(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// now insert load tracker
|
||||||
|
if !asset_infos.is_empty() {
|
||||||
|
commands
|
||||||
|
.entity(child_entity)
|
||||||
|
.insert(AssetsToLoad {
|
||||||
|
all_loaded: false,
|
||||||
|
asset_infos,
|
||||||
|
..Default::default()
|
||||||
|
})
|
||||||
|
.insert(BlueprintAssetsNotLoaded);
|
||||||
|
} else {
|
||||||
|
commands.entity(child_entity).insert(BlueprintAssetsLoaded);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn blueprints_check_assets_loading(
|
||||||
|
mut blueprint_assets_to_load: Query<
|
||||||
|
(Entity, Option<&Name>, &BlueprintPath, &mut AssetsToLoad),
|
||||||
|
With<BlueprintAssetsNotLoaded>,
|
||||||
|
>,
|
||||||
|
asset_server: Res<AssetServer>,
|
||||||
|
mut commands: Commands,
|
||||||
|
mut blueprint_events: EventWriter<BlueprintEvent>,
|
||||||
|
|
||||||
|
) {
|
||||||
|
for (entity, entity_name, blueprint_path, mut assets_to_load) in blueprint_assets_to_load.iter_mut() {
|
||||||
|
let mut all_loaded = true;
|
||||||
|
let mut loaded_amount = 0;
|
||||||
|
let total = assets_to_load.asset_infos.len();
|
||||||
|
for tracker in assets_to_load.asset_infos.iter_mut() {
|
||||||
|
let asset_id = tracker.id;
|
||||||
|
let loaded = asset_server.is_loaded_with_dependencies(asset_id);
|
||||||
|
println!("loading {}: // load state: {:?}", tracker.name, asset_server.load_state(asset_id));
|
||||||
|
|
||||||
|
// FIXME: hack for now
|
||||||
|
let mut failed = false;// asset_server.load_state(asset_id) == bevy::asset::LoadState::Failed(_error);
|
||||||
|
match asset_server.load_state(asset_id) {
|
||||||
|
bevy::asset::LoadState::Failed(_) => {
|
||||||
|
failed = true
|
||||||
|
},
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
tracker.loaded = loaded || failed;
|
||||||
|
if loaded || failed {
|
||||||
|
loaded_amount += 1;
|
||||||
|
} else {
|
||||||
|
all_loaded = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let progress: f32 = loaded_amount as f32 / total as f32;
|
||||||
|
println!("progress: {}",progress);
|
||||||
|
assets_to_load.progress = progress;
|
||||||
|
|
||||||
|
if all_loaded {
|
||||||
|
assets_to_load.all_loaded = true;
|
||||||
|
println!("done with loading {:?}, inserting components", entity_name);
|
||||||
|
blueprint_events.send(BlueprintEvent::AssetsLoaded {blueprint_name:"".into(), blueprint_path: blueprint_path.0.clone() });
|
||||||
|
|
||||||
|
commands
|
||||||
|
.entity(entity)
|
||||||
|
.insert(BlueprintAssetsLoaded)
|
||||||
|
.remove::<BlueprintAssetsNotLoaded>()
|
||||||
|
.remove::<AssetsToLoad>()
|
||||||
|
;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
pub(crate) fn blueprints_spawn(
|
||||||
|
spawn_placeholders: Query<
|
||||||
|
(
|
||||||
|
Entity,
|
||||||
|
&BlueprintName,
|
||||||
|
&BlueprintPath,
|
||||||
|
Option<&Transform>,
|
||||||
|
Option<&Parent>,
|
||||||
|
Option<&AddToGameWorld>,
|
||||||
|
Option<&Name>,
|
||||||
|
),
|
||||||
|
(
|
||||||
|
With<BlueprintAssetsLoaded>,
|
||||||
|
Added<BlueprintAssetsLoaded>,
|
||||||
|
Without<BlueprintAssetsNotLoaded>,
|
||||||
|
),
|
||||||
|
>,
|
||||||
|
|
||||||
|
mut commands: Commands,
|
||||||
|
mut game_world: Query<Entity, With<GameWorldTag>>,
|
||||||
|
|
||||||
|
assets_gltf: Res<Assets<Gltf>>,
|
||||||
|
asset_server: Res<AssetServer>,
|
||||||
|
children: Query<&Children>,
|
||||||
|
) {
|
||||||
|
for (
|
||||||
|
entity,
|
||||||
|
blupeprint_name,
|
||||||
|
blueprint_path,
|
||||||
|
transform,
|
||||||
|
original_parent,
|
||||||
|
add_to_world,
|
||||||
|
name,
|
||||||
|
) in spawn_placeholders.iter()
|
||||||
|
{
|
||||||
|
info!(
|
||||||
|
"attempting to spawn blueprint {:?} for entity {:?}, id: {:?}, parent:{:?}",
|
||||||
|
blupeprint_name.0, name, entity, original_parent
|
||||||
|
);
|
||||||
|
|
||||||
|
// info!("attempting to spawn {:?}", model_path);
|
||||||
|
let model_handle: Handle<Gltf> = asset_server.load(blueprint_path.0.clone()); // FIXME: kinda weird now
|
||||||
|
|
||||||
|
let gltf = assets_gltf.get(&model_handle).unwrap_or_else(|| {
|
||||||
|
panic!(
|
||||||
|
"gltf file {:?} should have been loaded",
|
||||||
|
&blueprint_path.0
|
||||||
|
)
|
||||||
|
});
|
||||||
|
|
||||||
|
// WARNING we work under the assumtion that there is ONLY ONE named scene, and that the first one is the right one
|
||||||
|
let main_scene_name = gltf
|
||||||
|
.named_scenes
|
||||||
|
.keys()
|
||||||
|
.next()
|
||||||
|
.expect("there should be at least one named scene in the gltf file to spawn");
|
||||||
|
|
||||||
|
let scene = &gltf.named_scenes[main_scene_name];
|
||||||
|
|
||||||
|
// transforms are optional, but still deal with them correctly
|
||||||
|
let mut transforms: Transform = Transform::default();
|
||||||
|
if transform.is_some() {
|
||||||
|
transforms = *transform.unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut original_children: Vec<Entity> = vec![];
|
||||||
|
if let Ok(c) = children.get(entity) {
|
||||||
|
for child in c.iter() {
|
||||||
|
original_children.push(*child);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut named_animations:HashMap<String, Handle<AnimationClip>> = HashMap::new() ;
|
||||||
|
for (key, value) in gltf.named_animations.iter() {
|
||||||
|
named_animations.insert(key.to_string(), value.clone());
|
||||||
|
}
|
||||||
|
|
||||||
|
commands.entity(entity).insert((
|
||||||
|
SceneBundle {
|
||||||
|
scene: scene.clone(),
|
||||||
|
transform: transforms,
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
Spawned,
|
||||||
|
BlueprintInstanceReady, // FIXME: not sure if this is should be added here or in the post process
|
||||||
|
OriginalChildren(original_children),
|
||||||
|
BlueprintAnimations {
|
||||||
|
// these are animations specific to the inside of the blueprint
|
||||||
|
named_animations: named_animations//gltf.named_animations.clone(),
|
||||||
|
},
|
||||||
|
));
|
||||||
|
|
||||||
|
if add_to_world.is_some() {
|
||||||
|
let world = game_world
|
||||||
|
.get_single_mut()
|
||||||
|
.expect("there should be a game world present");
|
||||||
|
commands.entity(world).add_child(entity);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -1,8 +1,9 @@
|
|||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
use bevy::{gltf::Gltf, prelude::*, utils::hashbrown::HashMap};
|
use bevy::{gltf::Gltf, prelude::*, utils::hashbrown::HashMap};
|
||||||
|
use serde_json::Value;
|
||||||
|
|
||||||
use crate::{BlenvyAssets, AssetsToLoad, AssetLoadTracker, BlenvyConfig, BlueprintAnimations, BlueprintAssetsLoaded, BlueprintAssetsNotLoaded};
|
use crate::{BlenvyAssets, BlenvyAssetsLoadState, AssetLoadTracker, BlenvyConfig, BlueprintAnimations, BlueprintAssetsLoaded, BlueprintAssetsNotLoaded};
|
||||||
|
|
||||||
/// this is a flag component for our levels/game world
|
/// this is a flag component for our levels/game world
|
||||||
#[derive(Component)]
|
#[derive(Component)]
|
||||||
@ -18,6 +19,18 @@ pub struct BlueprintName(pub String);
|
|||||||
#[reflect(Component)]
|
#[reflect(Component)]
|
||||||
pub struct BlueprintPath(pub String);
|
pub struct BlueprintPath(pub String);
|
||||||
|
|
||||||
|
|
||||||
|
/// Main component for the blueprints
|
||||||
|
/// has both name & path of the blueprint to enable injecting the data from the correct blueprint
|
||||||
|
/// into the entity that contains this component
|
||||||
|
#[derive(Component, Reflect, Default, Debug)]
|
||||||
|
#[reflect(Component)]
|
||||||
|
pub struct BlueprintInfo{
|
||||||
|
pub name: String,
|
||||||
|
pub path: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
/// flag component needed to signify the intent to spawn a Blueprint
|
/// flag component needed to signify the intent to spawn a Blueprint
|
||||||
#[derive(Component, Reflect, Default, Debug)]
|
#[derive(Component, Reflect, Default, Debug)]
|
||||||
#[reflect(Component)]
|
#[reflect(Component)]
|
||||||
@ -83,6 +96,9 @@ pub enum BlueprintEvent {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
use gltf::Gltf as RawGltf;
|
||||||
|
|
||||||
pub(crate) fn blueprints_prepare_spawn(
|
pub(crate) fn blueprints_prepare_spawn(
|
||||||
spawn_placeholders: Query<
|
spawn_placeholders: Query<
|
||||||
(
|
(
|
||||||
@ -105,7 +121,7 @@ pub(crate) fn blueprints_prepare_spawn(
|
|||||||
>,
|
>,
|
||||||
|
|
||||||
|
|
||||||
bla_bla : Query<
|
blueprint_instances_to_spawn : Query<
|
||||||
(
|
(
|
||||||
Entity,
|
Entity,
|
||||||
&BlueprintName,
|
&BlueprintName,
|
||||||
@ -120,7 +136,7 @@ asset_server: Res<AssetServer>,
|
|||||||
|
|
||||||
) {
|
) {
|
||||||
for (entity, blueprint_path) in spawn_placeholders.iter() {
|
for (entity, blueprint_path) in spawn_placeholders.iter() {
|
||||||
//println!("added blueprint_path {:?}", blueprint_path);
|
println!("added blueprint_path {:?}", blueprint_path);
|
||||||
/*commands.entity(entity).insert(
|
/*commands.entity(entity).insert(
|
||||||
SceneBundle {
|
SceneBundle {
|
||||||
scene: asset_server.load(format!("{}#Scene0", &blueprint_path.0)), // "levels/World.glb#Scene0"),
|
scene: asset_server.load(format!("{}#Scene0", &blueprint_path.0)), // "levels/World.glb#Scene0"),
|
||||||
@ -130,9 +146,13 @@ asset_server: Res<AssetServer>,
|
|||||||
// let model_handle: Handle<Gltf> = asset_server.load(model_path.clone());
|
// let model_handle: Handle<Gltf> = asset_server.load(model_path.clone());
|
||||||
}
|
}
|
||||||
|
|
||||||
for (entity, blueprint_name, blueprint_path, parent, all_assets) in bla_bla.iter() {
|
for (entity, blueprint_name, blueprint_path, parent, all_assets) in blueprint_instances_to_spawn.iter() {
|
||||||
println!("added blueprint to spawn {:?} {:?}", blueprint_name, blueprint_path);
|
println!("Detected blueprint to spawn {:?} {:?}", blueprint_name, blueprint_path);
|
||||||
// println!("all assets {:?}", all_assets);
|
println!("all assets {:?}", all_assets);
|
||||||
|
//////////////
|
||||||
|
|
||||||
|
// we add the asset of the blueprint itself
|
||||||
|
// TODO: add detection of already loaded data
|
||||||
let untyped_handle = asset_server.load_untyped(&blueprint_path.0);
|
let untyped_handle = asset_server.load_untyped(&blueprint_path.0);
|
||||||
let asset_id = untyped_handle.id();
|
let asset_id = untyped_handle.id();
|
||||||
let loaded = asset_server.is_loaded_with_dependencies(asset_id);
|
let loaded = asset_server.is_loaded_with_dependencies(asset_id);
|
||||||
@ -147,31 +167,27 @@ asset_server: Res<AssetServer>,
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// now insert load tracker
|
// and we also add all its assets
|
||||||
if !asset_infos.is_empty() {
|
/* prefetch attempt */
|
||||||
commands
|
let gltf = RawGltf::open(format!("assets/{}", blueprint_path.0)).unwrap();// RawGltf::open("examples/Box.gltf")?;
|
||||||
.entity(entity)
|
for scene in gltf.scenes() {
|
||||||
.insert(AssetsToLoad {
|
let foo_extras = scene.extras().clone().unwrap();
|
||||||
all_loaded: false,
|
|
||||||
asset_infos,
|
|
||||||
..Default::default()
|
|
||||||
})
|
|
||||||
.insert(BlueprintAssetsNotLoaded);
|
|
||||||
} else {
|
|
||||||
commands.entity(entity).insert(BlueprintAssetsLoaded);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for (child_entity, child_entity_name, all_assets) in entities_with_assets.iter(){
|
let lookup: HashMap<String, Value> = serde_json::from_str(&foo_extras.get()).unwrap();
|
||||||
println!("added assets {:?} to {:?}", all_assets, child_entity_name);
|
/*for (key, value) in lookup.clone().into_iter() {
|
||||||
if all_assets.is_some() {
|
println!("{} / {}", key, value);
|
||||||
let mut asset_infos: Vec<AssetLoadTracker> = vec![];
|
}*/
|
||||||
|
|
||||||
for asset in all_assets.unwrap().0.iter() {
|
if lookup.contains_key("BlenvyAssets"){
|
||||||
|
let assets_raw = &lookup["BlenvyAssets"];
|
||||||
|
//println!("ASSETS RAW {}", assets_raw);
|
||||||
|
let all_assets: BlenvyAssets = ron::from_str(&assets_raw.as_str().unwrap()).unwrap();
|
||||||
|
println!("all_assets {:?}", all_assets);
|
||||||
|
|
||||||
|
for asset in all_assets.0.iter() {
|
||||||
let untyped_handle = asset_server.load_untyped(&asset.path);
|
let untyped_handle = asset_server.load_untyped(&asset.path);
|
||||||
//println!("untyped handle {:?}", untyped_handle);
|
//println!("untyped handle {:?}", untyped_handle);
|
||||||
//asset_server.load(asset.path);
|
//asset_server.load(asset.path);
|
||||||
|
|
||||||
let asset_id = untyped_handle.id();
|
let asset_id = untyped_handle.id();
|
||||||
//println!("ID {:?}", asset_id);
|
//println!("ID {:?}", asset_id);
|
||||||
let loaded = asset_server.is_loaded_with_dependencies(asset_id);
|
let loaded = asset_server.is_loaded_with_dependencies(asset_id);
|
||||||
@ -185,27 +201,28 @@ asset_server: Res<AssetServer>,
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// now insert load tracker
|
// now insert load tracker
|
||||||
if !asset_infos.is_empty() {
|
if !asset_infos.is_empty() {
|
||||||
commands
|
commands
|
||||||
.entity(child_entity)
|
.entity(entity)
|
||||||
.insert(AssetsToLoad {
|
.insert(BlenvyAssetsLoadState {
|
||||||
all_loaded: false,
|
all_loaded: false,
|
||||||
asset_infos,
|
asset_infos,
|
||||||
..Default::default()
|
..Default::default()
|
||||||
})
|
})
|
||||||
.insert(BlueprintAssetsNotLoaded);
|
.insert(BlueprintAssetsNotLoaded);
|
||||||
} else {
|
} else {
|
||||||
commands.entity(child_entity).insert(BlueprintAssetsLoaded);
|
commands.entity(entity).insert(BlueprintAssetsLoaded);
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn blueprints_check_assets_loading(
|
pub(crate) fn blueprints_check_assets_loading(
|
||||||
mut blueprint_assets_to_load: Query<
|
mut blueprint_assets_to_load: Query<
|
||||||
(Entity, Option<&Name>, &BlueprintPath, &mut AssetsToLoad),
|
(Entity, Option<&Name>, &BlueprintPath, &mut BlenvyAssetsLoadState),
|
||||||
With<BlueprintAssetsNotLoaded>,
|
With<BlueprintAssetsNotLoaded>,
|
||||||
>,
|
>,
|
||||||
asset_server: Res<AssetServer>,
|
asset_server: Res<AssetServer>,
|
||||||
@ -220,7 +237,7 @@ pub(crate) fn blueprints_check_assets_loading(
|
|||||||
for tracker in assets_to_load.asset_infos.iter_mut() {
|
for tracker in assets_to_load.asset_infos.iter_mut() {
|
||||||
let asset_id = tracker.id;
|
let asset_id = tracker.id;
|
||||||
let loaded = asset_server.is_loaded_with_dependencies(asset_id);
|
let loaded = asset_server.is_loaded_with_dependencies(asset_id);
|
||||||
println!("loading {}: // load state: {:?}", tracker.name, asset_server.load_state(asset_id));
|
// println!("loading {}: // load state: {:?}", tracker.name, asset_server.load_state(asset_id));
|
||||||
|
|
||||||
// FIXME: hack for now
|
// FIXME: hack for now
|
||||||
let mut failed = false;// asset_server.load_state(asset_id) == bevy::asset::LoadState::Failed(_error);
|
let mut failed = false;// asset_server.load_state(asset_id) == bevy::asset::LoadState::Failed(_error);
|
||||||
@ -238,20 +255,21 @@ pub(crate) fn blueprints_check_assets_loading(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
let progress: f32 = loaded_amount as f32 / total as f32;
|
let progress: f32 = loaded_amount as f32 / total as f32;
|
||||||
println!("progress: {}",progress);
|
|
||||||
assets_to_load.progress = progress;
|
assets_to_load.progress = progress;
|
||||||
|
|
||||||
if all_loaded {
|
if all_loaded {
|
||||||
assets_to_load.all_loaded = true;
|
assets_to_load.all_loaded = true;
|
||||||
println!("done with loading {:?}, inserting components", entity_name);
|
println!("LOADING: in progress for ALL assets of {:?} (instance of {}), preparing for spawn", entity_name, blueprint_path.0);
|
||||||
blueprint_events.send(BlueprintEvent::AssetsLoaded {blueprint_name:"".into(), blueprint_path: blueprint_path.0.clone() });
|
blueprint_events.send(BlueprintEvent::AssetsLoaded {blueprint_name:"".into(), blueprint_path: blueprint_path.0.clone() });
|
||||||
|
|
||||||
commands
|
commands
|
||||||
.entity(entity)
|
.entity(entity)
|
||||||
.insert(BlueprintAssetsLoaded)
|
.insert(BlueprintAssetsLoaded)
|
||||||
.remove::<BlueprintAssetsNotLoaded>()
|
.remove::<BlueprintAssetsNotLoaded>()
|
||||||
.remove::<AssetsToLoad>()
|
.remove::<BlenvyAssetsLoadState>()
|
||||||
;
|
;
|
||||||
|
}else {
|
||||||
|
println!("LOADING: done for ALL assets of {:?} (instance of {}): {} ",entity_name, blueprint_path.0, progress * 100.0);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -294,7 +312,7 @@ pub(crate) fn blueprints_spawn(
|
|||||||
) in spawn_placeholders.iter()
|
) in spawn_placeholders.iter()
|
||||||
{
|
{
|
||||||
info!(
|
info!(
|
||||||
"attempting to spawn blueprint {:?} for entity {:?}, id: {:?}, parent:{:?}",
|
"all assets loaded, attempting to spawn blueprint {:?} for entity {:?}, id: {:?}, parent:{:?}",
|
||||||
blupeprint_name.0, name, entity, original_parent
|
blupeprint_name.0, name, entity, original_parent
|
||||||
);
|
);
|
||||||
|
|
||||||
|
@ -8,7 +8,7 @@ use bevy::scene::SceneInstance;
|
|||||||
use crate::{BlueprintAnimationPlayerLink, BlueprintAnimations, BlueprintPath};
|
use crate::{BlueprintAnimationPlayerLink, BlueprintAnimations, BlueprintPath};
|
||||||
use crate::{SpawnHere, Spawned};
|
use crate::{SpawnHere, Spawned};
|
||||||
use crate::{
|
use crate::{
|
||||||
AssetsToLoad, BlueprintAssetsLoaded, BlueprintEvent, CopyComponents, InBlueprint, NoInBlueprint, OriginalChildren
|
BlenvyAssetsLoadState, BlueprintAssetsLoaded, BlueprintEvent, CopyComponents, InBlueprint, NoInBlueprint, OriginalChildren
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
@ -99,7 +99,7 @@ pub(crate) fn spawned_blueprint_post_process(
|
|||||||
commands.entity(original).remove::<SpawnHere>();
|
commands.entity(original).remove::<SpawnHere>();
|
||||||
commands.entity(original).remove::<Spawned>();
|
commands.entity(original).remove::<Spawned>();
|
||||||
// commands.entity(original).remove::<Handle<Scene>>(); // FIXME: if we delete the handle to the scene, things get despawned ! not what we want
|
// commands.entity(original).remove::<Handle<Scene>>(); // FIXME: if we delete the handle to the scene, things get despawned ! not what we want
|
||||||
//commands.entity(original).remove::<AssetsToLoad>(); // also clear the sub assets tracker to free up handles, perhaps just freeing up the handles and leave the rest would be better ?
|
//commands.entity(original).remove::<BlenvyAssetsLoadState>(); // also clear the sub assets tracker to free up handles, perhaps just freeing up the handles and leave the rest would be better ?
|
||||||
//commands.entity(original).remove::<BlueprintAssetsLoaded>();
|
//commands.entity(original).remove::<BlueprintAssetsLoaded>();
|
||||||
commands.entity(root_entity).despawn_recursive();
|
commands.entity(root_entity).despawn_recursive();
|
||||||
|
|
||||||
|
@ -107,7 +107,6 @@ fn process_background_shader(
|
|||||||
mut commands: Commands,
|
mut commands: Commands,
|
||||||
) {
|
) {
|
||||||
for background_shader in background_shaders.iter() {
|
for background_shader in background_shaders.iter() {
|
||||||
println!("HEYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY {:?}", background_shader.color);
|
|
||||||
commands.insert_resource(AmbientLight {
|
commands.insert_resource(AmbientLight {
|
||||||
color: background_shader.color,
|
color: background_shader.color,
|
||||||
// Just a guess, see <https://github.com/bevyengine/bevy/issues/12280>
|
// Just a guess, see <https://github.com/bevyengine/bevy/issues/12280>
|
||||||
|
@ -61,7 +61,6 @@ pub fn add_components_from_gltf_extras(world: &mut World) {
|
|||||||
// let gltf_components_config = world.resource::<GltfComponentsConfig>();
|
// let gltf_components_config = world.resource::<GltfComponentsConfig>();
|
||||||
|
|
||||||
for (entity, name, extra, parent) in extras.iter(world) {
|
for (entity, name, extra, parent) in extras.iter(world) {
|
||||||
println!("GLTF EXTRA !!!!");
|
|
||||||
debug!(
|
debug!(
|
||||||
"Name: {}, entity {:?}, parent: {:?}, extras {:?}",
|
"Name: {}, entity {:?}, parent: {:?}, extras {:?}",
|
||||||
name, entity, parent, extra
|
name, entity, parent, extra
|
||||||
@ -77,8 +76,6 @@ pub fn add_components_from_gltf_extras(world: &mut World) {
|
|||||||
|
|
||||||
|
|
||||||
for (entity, name, extra, parent) in scene_extras.iter(world) {
|
for (entity, name, extra, parent) in scene_extras.iter(world) {
|
||||||
println!("GLTF SCENE EXTRA !!!!");
|
|
||||||
|
|
||||||
debug!(
|
debug!(
|
||||||
"Name: {}, entity {:?}, parent: {:?}, scene_extras {:?}",
|
"Name: {}, entity {:?}, parent: {:?}, scene_extras {:?}",
|
||||||
name, entity, parent, extra
|
name, entity, parent, extra
|
||||||
@ -93,8 +90,6 @@ pub fn add_components_from_gltf_extras(world: &mut World) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
for (entity, name, extra, parent) in mesh_extras.iter(world) {
|
for (entity, name, extra, parent) in mesh_extras.iter(world) {
|
||||||
println!("GLTF MESH EXTRA !!!!");
|
|
||||||
|
|
||||||
debug!(
|
debug!(
|
||||||
"Name: {}, entity {:?}, parent: {:?}, mesh_extras {:?}",
|
"Name: {}, entity {:?}, parent: {:?}, mesh_extras {:?}",
|
||||||
name, entity, parent, extra
|
name, entity, parent, extra
|
||||||
|
@ -25,7 +25,7 @@ pub fn setup_game(
|
|||||||
commands.spawn((
|
commands.spawn((
|
||||||
BlueprintName("World".into()),
|
BlueprintName("World".into()),
|
||||||
BlueprintPath("levels/World.glb".into()),
|
BlueprintPath("levels/World.glb".into()),
|
||||||
bevy::prelude::Name::from("world"),
|
bevy::prelude::Name::from("world"), //FIXME: not really needed ? could be infered from blueprint's name/ path
|
||||||
SpawnHere,
|
SpawnHere,
|
||||||
GameWorldTag,
|
GameWorldTag,
|
||||||
InAppRunning,
|
InAppRunning,
|
||||||
|
@ -10,7 +10,7 @@ def assets_to_fake_ron(list_like):
|
|||||||
result = []
|
result = []
|
||||||
for item in list_like:
|
for item in list_like:
|
||||||
result.append(f"(name: \"{item['name']}\", path: \"{item['path']}\")")
|
result.append(f"(name: \"{item['name']}\", path: \"{item['path']}\")")
|
||||||
return result#.join(", ")
|
return f"({result})".replace("'", '')#.join(", ")
|
||||||
|
|
||||||
def export_blueprints(blueprints, settings, blueprints_data):
|
def export_blueprints(blueprints, settings, blueprints_data):
|
||||||
blueprints_path_full = getattr(settings, "blueprints_path_full")
|
blueprints_path_full = getattr(settings, "blueprints_path_full")
|
||||||
@ -39,7 +39,7 @@ def export_blueprints(blueprints, settings, blueprints_data):
|
|||||||
|
|
||||||
all_assets = []
|
all_assets = []
|
||||||
auto_assets = []
|
auto_assets = []
|
||||||
collection["BlenvyAssets"] = assets_to_fake_ron([{"name": asset.name, "path": asset.path} for asset in collection.user_assets] + auto_assets) #all_assets + [{"name": asset.name, "path": asset.path} for asset in collection.user_assets] + auto_assets)
|
collection["BlenvyAssets"] = assets_to_fake_ron([]) #assets_to_fake_ron([{"name": asset.name, "path": asset.path} for asset in collection.user_assets] + auto_assets) #all_assets + [{"name": asset.name, "path": asset.path} for asset in collection.user_assets] + auto_assets)
|
||||||
|
|
||||||
|
|
||||||
# do the actual export
|
# do the actual export
|
||||||
|
@ -20,7 +20,7 @@ def generate_temporary_scene_and_export(settings, gltf_export_settings, gltf_out
|
|||||||
temp_root_collection = temp_scene.collection
|
temp_root_collection = temp_scene.collection
|
||||||
|
|
||||||
print("additional_dataAAAAAAAAAAAAAAAH", additional_data)
|
print("additional_dataAAAAAAAAAAAAAAAH", additional_data)
|
||||||
properties_black_list = ['glTF2ExportSettings', 'user_assets', 'components_meta']
|
properties_black_list = ['glTF2ExportSettings', 'assets', 'user_assets', 'components_meta', 'Components_meta', 'Generated_assets', 'generated_assets']
|
||||||
if additional_data is not None: # FIXME not a fan of having this here
|
if additional_data is not None: # FIXME not a fan of having this here
|
||||||
for entry in dict(additional_data):
|
for entry in dict(additional_data):
|
||||||
# we copy everything over except those on the black list
|
# we copy everything over except those on the black list
|
||||||
|
@ -14,7 +14,7 @@ def assets_to_fake_ron(list_like):
|
|||||||
result = []
|
result = []
|
||||||
for item in list_like:
|
for item in list_like:
|
||||||
result.append(f"(name: \"{item['name']}\", path: \"{item['path']}\")")
|
result.append(f"(name: \"{item['name']}\", path: \"{item['path']}\")")
|
||||||
return result#.join(", ")
|
return f"({result})".replace("'", '')#.join(", ")
|
||||||
|
|
||||||
|
|
||||||
def export_main_scene(scene, settings, blueprints_data):
|
def export_main_scene(scene, settings, blueprints_data):
|
||||||
@ -78,8 +78,8 @@ def export_main_scene(scene, settings, blueprints_data):
|
|||||||
materials_exported_path = os.path.join(materials_path, f"{materials_library_name}{export_gltf_extension}")
|
materials_exported_path = os.path.join(materials_path, f"{materials_library_name}{export_gltf_extension}")
|
||||||
material_assets = [{"name": materials_library_name, "path": materials_exported_path}] # we also add the material library as an asset
|
material_assets = [{"name": materials_library_name, "path": materials_exported_path}] # we also add the material library as an asset
|
||||||
|
|
||||||
#scene["BlenvyAssets"] = assets_to_fake_ron(all_assets + [{"name": asset.name, "path": asset.path} for asset in scene.user_assets] + auto_assets + material_assets)
|
scene["BlenvyAssets"] = assets_to_fake_ron(all_assets + [{"name": asset.name, "path": asset.path} for asset in scene.user_assets] + auto_assets + material_assets)
|
||||||
|
#scene["BlenvyAssets"] = assets_to_fake_ron([{'name':'foo', 'path':'bar'}])
|
||||||
|
|
||||||
if export_separate_dynamic_and_static_objects:
|
if export_separate_dynamic_and_static_objects:
|
||||||
#print("SPLIT STATIC AND DYNAMIC")
|
#print("SPLIT STATIC AND DYNAMIC")
|
||||||
|
Loading…
Reference in New Issue
Block a user