Compare commits

..

3 Commits

Author SHA1 Message Date
kaosat.dev
ee5c74aa9e refactor(Blenvy): deprecated BlueprintName (& BluprintPath), and replaced them with BlueprintInfo
* contains both name & path
 * also experimented with merging the asset load tracking into BlenvyAssets by adding the fields from the
asset loading tracker & ignoring them/ defaulting them for deserialization
2024-06-25 00:45:39 +02:00
kaosat.dev
253d33f1bb 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
2024-06-24 23:47:36 +02:00
kaosat.dev
e232fedc4b chore(Blenvy): minor tweaks 2024-06-24 10:21:51 +02:00
21 changed files with 550 additions and 177 deletions

View File

@ -13,7 +13,7 @@ this crate adds the ability to define Blueprints/Prefabs for [Bevy](https://bevy
A blueprint is a set of **overrideable** components + a hierarchy: ie
* just a Gltf file with Gltf_extras specifying components
* a component called BlueprintName
* a component called BlueprintInfo
Particularly useful when using [Blender](https://www.blender.org/) as an editor for the [Bevy](https://bevyengine.org/) game engine, combined with the Blender add-on that do a lot of the work for you
- [blenvy](https://github.com/kaosat-dev/Blender_bevy_components_workflow/tree/main/tools/blenvy)
@ -51,7 +51,7 @@ fn spawn_blueprint(
){
if keycode.just_pressed(KeyCode::S) {
let new_entity = commands.spawn((
BlueprintName("Health_Pickup".to_string()), // mandatory !!
BlueprintInfo(name: "Health_Pickup".to_string(), path:""), // mandatory !!
SpawnHere, // mandatory !!
TransformBundle::from_transform(Transform::from_xyz(x, 2.0, y)), // VERY important !!
// any other component you want to insert
@ -114,7 +114,7 @@ fn main() {
You can spawn entities from blueprints like this:
```rust no_run
commands.spawn((
BlueprintName("Health_Pickup".to_string()), // mandatory !!
BlueprintInfo("Health_Pickup".to_string()), // mandatory !!
SpawnHere, // mandatory !!
TransformBundle::from_transform(Transform::from_xyz(x, 2.0, y)), // optional
@ -134,7 +134,7 @@ you can just add any additional components you need when spawning :
```rust no_run
commands.spawn((
BlueprintName("Health_Pickup".to_string()),
BlueprintInfo("Health_Pickup".to_string()),
SpawnHere,
TransformBundle::from_transform(Transform::from_xyz(x, 2.0, y)),
// from Rapier/bevy_xpbd: this means the entity will also have a velocity component when inserted into the world
@ -152,7 +152,7 @@ any component you specify when spawning the Blueprint that is also specified **w
for example
```rust no_run
commands.spawn((
BlueprintName("Health_Pickup".to_string()),
BlueprintInfo("Health_Pickup".to_string()),
SpawnHere,
TransformBundle::from_transform(Transform::from_xyz(x, 2.0, y)),
HealthPowerUp(20)// if this is component is also present inside the "Health_Pickup" blueprint, that one will be replaced with this component during spawning
@ -163,7 +163,7 @@ commands.spawn((
### BluePrintBundle
There is also a ```BluePrintBundle``` for convenience , which just has
* a ```BlueprintName``` component
* a ```BlueprintInfo``` component
* a ```SpawnHere``` component
## Additional information
@ -178,7 +178,7 @@ commands
.spawn((
Name::from("test"),
BluePrintBundle {
blueprint: BlueprintName("TestBlueprint".to_string()),
blueprint: BlueprintInfo("TestBlueprint".to_string()),
..Default::default()
},
Library("models".into()) // now the path to the blueprint above will be /assets/models/TestBlueprint.glb

View File

@ -1,11 +1,12 @@
use std::path::{Path, PathBuf};
use bevy::{asset::LoadedUntypedAsset, gltf::Gltf, prelude::*, utils::HashMap};
use serde::Deserialize;
use crate::{BlenvyConfig, BlueprintAnimations};
/// 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)]
pub struct MyAsset{
pub name: String,
@ -13,9 +14,24 @@ pub struct MyAsset{
}
/// 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)]
pub struct BlenvyAssets(pub Vec<MyAsset>);
pub struct BlenvyAssets {
/// only this field should get filled in from the Blender side
pub assets: Vec<MyAsset>,
/// set to default when deserializing
#[serde(default)]
#[reflect(default)]
pub loaded: bool,
/// set to default when deserializing
#[serde(default)]
#[reflect(default)]
pub progress: f32,
#[reflect(ignore)]
#[serde(skip)]
pub asset_infos: Vec<AssetLoadTracker>,
}
//(pub Vec<MyAsset>);
@ -29,7 +45,7 @@ pub(crate) struct BlueprintAssetsLoaded;
pub(crate) struct BlueprintAssetsNotLoaded;
/// helper component, for tracking loaded assets's loading state, id , handle etc
#[derive(Debug)]
#[derive(Debug, Reflect)]
pub(crate) struct AssetLoadTracker {
#[allow(dead_code)]
pub name: String,
@ -42,12 +58,12 @@ pub(crate) struct AssetLoadTracker {
/// helper component, for tracking loaded assets
#[derive(Component, Debug)]
pub(crate) struct AssetsToLoad {
pub(crate) struct BlenvyAssetsLoadState {
pub all_loaded: bool,
pub asset_infos: Vec<AssetLoadTracker>,
pub progress: f32,
}
impl Default for AssetsToLoad {
impl Default for BlenvyAssetsLoadState {
fn default() -> Self {
Self {
all_loaded: Default::default(),

View File

@ -17,7 +17,7 @@ use bevy::{
render::mesh::Mesh,
};
use crate::{AssetLoadTracker, AssetsToLoad, BlenvyConfig, BlueprintInstanceReady};
use crate::{AssetLoadTracker, BlenvyAssetsLoadState, BlenvyConfig, BlueprintInstanceReady};
#[derive(Component, Reflect, Default, Debug)]
#[reflect(Component)]
@ -71,7 +71,7 @@ pub(crate) fn materials_inject(
commands
.entity(entity)
.insert(AssetsToLoad {
.insert(BlenvyAssetsLoadState {
all_loaded: false,
asset_infos,
..Default::default()
@ -85,7 +85,7 @@ pub(crate) fn materials_inject(
// TODO, merge with blueprints_check_assets_loading, make generic ?
pub(crate) fn check_for_material_loaded(
mut blueprint_assets_to_load: Query<
(Entity, &mut AssetsToLoad),
(Entity, &mut BlenvyAssetsLoadState),
With<BlueprintMaterialAssetsNotLoaded>,
>,
asset_server: Res<AssetServer>,

View File

@ -35,15 +35,13 @@ pub enum GltfBlueprintsSet {
#[derive(Bundle)]
pub struct BluePrintBundle {
pub blueprint: BlueprintName,
pub blueprint_path: BlueprintPath,
pub blueprint: BlueprintInfo,
pub spawn_here: SpawnHere,
}
impl Default for BluePrintBundle {
fn default() -> Self {
BluePrintBundle {
blueprint: BlueprintName("default".into()),
blueprint_path: BlueprintPath("".into()),
blueprint: BlueprintInfo{ name: "default".into(), path:"".into()},
spawn_here: SpawnHere,
}
}
@ -76,8 +74,7 @@ fn aabbs_enabled(blenvy_config: Res<BlenvyConfig>) -> bool {
impl Plugin for BlueprintsPlugin {
fn build(&self, app: &mut App) {
app
.register_type::<BlueprintName>()
.register_type::<BlueprintPath>()
.register_type::<BlueprintInfo>()
.register_type::<MaterialInfo>()
.register_type::<SpawnHere>()
.register_type::<BlueprintAnimations>()

View 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);
}
}
}

View File

@ -1,22 +1,24 @@
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};
use crate::{BlenvyAssets, BlenvyAssetsLoadState, 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
/// 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 BlueprintName(pub String);
pub struct BlueprintInfo {
pub name: String,
pub path: 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)]
@ -83,75 +85,87 @@ pub enum BlueprintEvent {
}
use gltf::Gltf as RawGltf;
pub(crate) fn blueprints_prepare_spawn(
spawn_placeholders: Query<
blueprint_instances_to_spawn : 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,
&BlueprintInfo,
Option<&Parent>,
Option<&BlenvyAssets>,
),(Added<BlueprintPath>)
),(Added<BlueprintInfo>)
>,
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_info, parent, all_assets) in blueprint_instances_to_spawn.iter() {
println!("Detected blueprint to spawn {:?} {:?}", blueprint_info.name, blueprint_info.path);
println!("all assets {:?}", all_assets);
//////////////
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);
let untyped_handle = asset_server.load_untyped(&blueprint_path.0);
// we add the asset of the blueprint itself
// TODO: add detection of already loaded data
let untyped_handle = asset_server.load_untyped(&blueprint_info.path);
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(),
name: blueprint_info.name.clone(),
id: asset_id,
loaded: false,
handle: untyped_handle.clone(),
});
}
// and we also add all its assets
/* prefetch attempt */
let gltf = RawGltf::open(format!("assets/{}", blueprint_info.path)).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 all_assets: BlenvyAssets = ron::from_str(&assets_raw.as_str().unwrap()).unwrap();
println!("all_assets {:?}", all_assets);
for asset in all_assets.assets.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(entity)
.insert(AssetsToLoad {
.insert(BlenvyAssetsLoadState {
all_loaded: false,
asset_infos,
..Default::default()
@ -161,51 +175,11 @@ asset_server: Res<AssetServer>,
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),
(Entity, Option<&Name>, &BlueprintInfo, &mut BlenvyAssetsLoadState),
With<BlueprintAssetsNotLoaded>,
>,
asset_server: Res<AssetServer>,
@ -213,14 +187,14 @@ pub(crate) fn blueprints_check_assets_loading(
mut blueprint_events: EventWriter<BlueprintEvent>,
) {
for (entity, entity_name, blueprint_path, mut assets_to_load) in blueprint_assets_to_load.iter_mut() {
for (entity, entity_name, blueprint_info, 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));
// 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);
@ -238,20 +212,21 @@ pub(crate) fn blueprints_check_assets_loading(
}
}
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() });
println!("LOADING: in progress for ALL assets of {:?} (instance of {}), preparing for spawn", entity_name, blueprint_info.path);
blueprint_events.send(BlueprintEvent::AssetsLoaded {blueprint_name:"".into(), blueprint_path: blueprint_info.path.clone() });
commands
.entity(entity)
.insert(BlueprintAssetsLoaded)
.remove::<BlueprintAssetsNotLoaded>()
.remove::<AssetsToLoad>()
.remove::<BlenvyAssetsLoadState>()
;
}else {
println!("LOADING: done for ALL assets of {:?} (instance of {}): {} ",entity_name, blueprint_info.path, progress * 100.0);
}
}
}
@ -262,8 +237,7 @@ pub(crate) fn blueprints_spawn(
spawn_placeholders: Query<
(
Entity,
&BlueprintName,
&BlueprintPath,
&BlueprintInfo,
Option<&Transform>,
Option<&Parent>,
Option<&AddToGameWorld>,
@ -285,8 +259,7 @@ pub(crate) fn blueprints_spawn(
) {
for (
entity,
blupeprint_name,
blueprint_path,
blueprint_info,
transform,
original_parent,
add_to_world,
@ -294,17 +267,17 @@ pub(crate) fn blueprints_spawn(
) in spawn_placeholders.iter()
{
info!(
"attempting to spawn blueprint {:?} for entity {:?}, id: {:?}, parent:{:?}",
blupeprint_name.0, name, entity, original_parent
"all assets loaded, attempting to spawn blueprint {:?} for entity {:?}, id: {:?}, parent:{:?}",
blueprint_info.name, 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 model_handle: Handle<Gltf> = asset_server.load(blueprint_info.path.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
&blueprint_info.path
)
});

View File

@ -5,10 +5,10 @@ use bevy::prelude::*;
use bevy::scene::SceneInstance;
// use bevy::utils::hashbrown::HashSet;
use crate::{BlueprintAnimationPlayerLink, BlueprintAnimations, BlueprintPath};
use crate::{BlueprintAnimationPlayerLink, BlueprintAnimations, BlueprintInfo};
use crate::{SpawnHere, Spawned};
use crate::{
AssetsToLoad, BlueprintAssetsLoaded, BlueprintEvent, CopyComponents, InBlueprint, NoInBlueprint, OriginalChildren
BlenvyAssetsLoadState, BlueprintAssetsLoaded, BlueprintEvent, CopyComponents, InBlueprint, NoInBlueprint, OriginalChildren
};
@ -28,7 +28,7 @@ pub(crate) fn spawned_blueprint_post_process(
&BlueprintAnimations,
Option<&NoInBlueprint>,
Option<&Name>,
&BlueprintPath
&BlueprintInfo
),
(With<SpawnHere>, With<SceneInstance>, With<Spawned>),
>,
@ -39,7 +39,7 @@ pub(crate) fn spawned_blueprint_post_process(
mut blueprint_events: EventWriter<BlueprintEvent>,
) {
for (original, children, original_children, animations, no_inblueprint, name, blueprint_path) in
for (original, children, original_children, animations, no_inblueprint, name, blueprint_info) in
unprocessed_entities.iter()
{
info!("post processing blueprint for entity {:?}", name);
@ -99,11 +99,11 @@ pub(crate) fn spawned_blueprint_post_process(
commands.entity(original).remove::<SpawnHere>();
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::<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(root_entity).despawn_recursive();
blueprint_events.send(BlueprintEvent::Spawned {blueprint_name:"".into(), blueprint_path: blueprint_path.0.clone() });
blueprint_events.send(BlueprintEvent::Spawned {blueprint_name: blueprint_info.name.clone(), blueprint_path: blueprint_info.path.clone() });
debug!("DONE WITH POST PROCESS");
}

View File

@ -107,7 +107,6 @@ fn process_background_shader(
mut commands: Commands,
) {
for background_shader in background_shaders.iter() {
println!("HEYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY {:?}", background_shader.color);
commands.insert_resource(AmbientLight {
color: background_shader.color,
// Just a guess, see <https://github.com/bevyengine/bevy/issues/12280>

View File

@ -61,7 +61,6 @@ pub fn add_components_from_gltf_extras(world: &mut World) {
// let gltf_components_config = world.resource::<GltfComponentsConfig>();
for (entity, name, extra, parent) in extras.iter(world) {
println!("GLTF EXTRA !!!!");
debug!(
"Name: {}, entity {:?}, parent: {:?}, extras {:?}",
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) {
println!("GLTF SCENE EXTRA !!!!");
debug!(
"Name: {}, entity {:?}, parent: {:?}, scene_extras {:?}",
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) {
println!("GLTF MESH EXTRA !!!!");
debug!(
"Name: {}, entity {:?}, parent: {:?}, mesh_extras {:?}",
name, entity, parent, extra

View File

@ -1,6 +1,5 @@
use bevy::prelude::*;
// use bevy_gltf_blueprints::{BluePrintBundle, BlueprintName, BlueprintPath, GameWorldTag};
use blenvy::{BluePrintBundle, BlueprintName, BlueprintPath, GameWorldTag, SpawnHere};
use blenvy::{BluePrintBundle, BlueprintInfo, GameWorldTag, SpawnHere};
use crate::{GameState, InAppRunning};
//use bevy_rapier3d::prelude::Velocity;
@ -23,9 +22,8 @@ pub fn setup_game(
));*/
commands.spawn((
BlueprintName("World".into()),
BlueprintPath("levels/World.glb".into()),
bevy::prelude::Name::from("world"),
BlueprintInfo{name: "World".into(), path: "levels/World.glb".into()},
bevy::prelude::Name::from("world"), //FIXME: not really needed ? could be infered from blueprint's name/ path
SpawnHere,
GameWorldTag,
InAppRunning,
@ -64,11 +62,10 @@ pub fn spawn_test(
let new_entity = commands
.spawn((
BluePrintBundle {
blueprint: BlueprintName("Health_Pickup".to_string()),
blueprint: BlueprintInfo{name: "Health_Pickup".into() , path:"foo/bar.glb".into()}, // FIXME
..Default::default()
},
bevy::prelude::Name::from(format!("test{}", name_index)),
// BlueprintName("Health_Pickup".to_string()),
// SpawnHere,
TransformBundle::from_transform(Transform::from_xyz(x, 2.0, y)),
/*Velocity {

View File

@ -7,7 +7,7 @@ pub use animation::*;
use std::{collections::HashMap, fs, time::Duration};
use blenvy::{
BlenvyAssets, BlueprintAnimationPlayerLink, BlueprintEvent, BlueprintName, GltfBlueprintsSet, SceneAnimations
BlenvyAssets, BlueprintAnimationPlayerLink, BlueprintEvent, BlueprintInfo, GltfBlueprintsSet, SceneAnimations
};
use bevy::{
@ -25,7 +25,7 @@ fn start_game(mut next_app_state: ResMut<NextState<AppState>>) {
}
// if the export from Blender worked correctly, we should have animations (simplified here by using AnimationPlayerLink)
// if the export from Blender worked correctly, we should have an Entity called "Blueprint4_nested" that has a child called "Blueprint3" that has a "BlueprintName" component with value Blueprint3
// if the export from Blender worked correctly, we should have an Entity called "Blueprint4_nested" that has a child called "Blueprint3" that has a "BlueprintInfo" component with value Blueprint3
// if the export from Blender worked correctly, we should have an assets_list
// if the export from Blender worked correctly, we should have the correct tree of entities
#[allow(clippy::too_many_arguments)]
@ -34,7 +34,7 @@ fn validate_export(
parents: Query<&Parent>,
children: Query<&Children>,
names: Query<&Name>,
blueprints: Query<(Entity, &Name, &BlueprintName)>,
blueprints: Query<(Entity, &Name, &BlueprintInfo)>,
animation_player_links: Query<(Entity, &BlueprintAnimationPlayerLink)>,
scene_animations: Query<(Entity, &SceneAnimations)>,
empties_candidates: Query<(Entity, &Name, &GlobalTransform)>,
@ -46,13 +46,13 @@ fn validate_export(
!animation_player_links.is_empty() && scene_animations.into_iter().len() == 4;
let mut nested_blueprint_found = false;
for (entity, name, blueprint_name) in blueprints.iter() {
if name.to_string() == *"Blueprint4_nested" && blueprint_name.0 == *"Blueprint4_nested" {
for (entity, name, blueprint_info) in blueprints.iter() {
if name.to_string() == *"Blueprint4_nested" && blueprint_info.name == *"Blueprint4_nested" {
if let Ok(cur_children) = children.get(entity) {
for child in cur_children.iter() {
if let Ok((_, child_name, child_blueprint_name)) = blueprints.get(*child) {
if let Ok((_, child_name, child_blueprint_info)) = blueprints.get(*child) {
if child_name.to_string() == *"Blueprint3"
&& child_blueprint_name.0 == *"Blueprint3"
&& child_blueprint_info.name == *"Blueprint3"
{
nested_blueprint_found = true;
}

View File

@ -133,7 +133,7 @@ This issue has been resolved in v0.9.
You can enable this option to automatically replace all the **collection instances** inside your main scene with blueprints
- whenever you change your main scene (or your library scene , if that option is enabled), all your collection instances
* will be replaced with empties (this will not be visible to you)
* those empties will have additional custom properties / components : ```BlueprintName``` & ```SpawnHere```
* those empties will have additional custom properties / components : ```BlueprintInfo``` & ```SpawnHere```
* your main scene/ level will be exported to a much more trimmed down gltf file (see next point)
* all the original collections (that you used to create the instances) will be exported as **seperate gltf files** into the "library" folder

View File

@ -153,8 +153,8 @@ General issues:
- [ ] scan for used materials per blueprint !
- [ ] for scenes, scan for used materials of all non instance objects (TODO: what about overrides ?)
- [ ] find a solution for the new color handling
- [ ] add back lighting_components
- [ ] check if scene components are being deleted through our scene re-orgs in the spawn post process
- [x] add back lighting_components
- [x] check if scene components are being deleted through our scene re-orgs in the spawn post process
- [ ] should "blueprint spawned" only be triggered after all its sub blueprints have spawned ?
- [ ] simplify testing example:
@ -171,6 +171,11 @@ General issues:
- [ ] rename repo to "Blenvy"
- [ ] do a deprecation release of all bevy_gltf_xxx crates to point at the new Blenvy crate
- [ ] hidden objects/collections not respected at export !!!
- [ ] add a way of overriding assets for collection instances
- [ ] add a way of visualizing per blueprint instances
- [ ] cleanup all the spurious debug messages
- [ ] deprecate BlueprintName & BlueprintPath & use BlueprintInfo instead
- [ ] fix animation handling
clear && pytest -svv --blender-template ../../testing/bevy_example/art/testing_library.blend --blender-executable /home/ckaos/tools/blender/blender-4.1.0-linux-x64/blender tests/test_bevy_integration_prepare.py && pytest -svv --blender-executable /home/ckaos/tools/blender/blender-4.1.0-linux-x64/blender tests/test_bevy_integration.py

View File

@ -10,7 +10,11 @@ def assets_to_fake_ron(list_like):
result = []
for item in list_like:
result.append(f"(name: \"{item['name']}\", path: \"{item['path']}\")")
return result#.join(", ")
return f"(assets: {result})".replace("'", '')
return f"({result})".replace("'", '')
def export_blueprints(blueprints, settings, blueprints_data):
blueprints_path_full = getattr(settings, "blueprints_path_full")
@ -39,7 +43,7 @@ def export_blueprints(blueprints, settings, blueprints_data):
all_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

View File

@ -97,10 +97,9 @@ def duplicate_object(object, parent, combine_mode, destination_collection, bluep
object.name = original_name + "____bak"
empty_obj = make_empty(original_name, object.location, object.rotation_euler, object.scale, destination_collection)
"""we inject the collection/blueprint name, as a component called 'BlueprintName', but we only do this in the empty, not the original object"""
empty_obj['BlueprintName'] = f'("{blueprint_name}")'
empty_obj["BlueprintPath"] = f'("{blueprint_path}")'
"""we inject the collection/blueprint name & path, as a component called 'BlueprintInfo', but we only do this in the empty, not the original object"""
empty_obj['SpawnHere'] = '()'
empty_obj['BlueprintInfo'] = f'(name: "{blueprint_name}", path: "{blueprint_path}")'
# we copy custom properties over from our original object to our empty
for component_name, component_value in object.items():

View File

@ -20,7 +20,7 @@ def generate_temporary_scene_and_export(settings, gltf_export_settings, gltf_out
temp_root_collection = temp_scene.collection
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
for entry in dict(additional_data):
# we copy everything over except those on the black list

View File

@ -64,7 +64,7 @@ class ExampleExtensionProperties(bpy.types.PropertyGroup):
# blueprint settings
auto_export_blueprints: BoolProperty(
name='Export Blueprints',
description='Replaces collection instances with an Empty with a BlueprintName custom property',
description='Replaces collection instances with an Empty with a BlueprintInfo custom property',
default=True
)
auto_export_blueprints_path: StringProperty(

View File

@ -1,16 +1,7 @@
import bpy
from blenvy.core.object_makers import make_empty
# TODO: replace this with placing scene level custom properties once support for that has been added to bevy_gltf
def upsert_scene_components(main_scenes):
for scene in main_scenes:
if scene.world is not None:
scene['BlenderBackgroundShader'] = ambient_color_to_component(scene.world)
print("FOOOOO WORLD", dir(scene.world))
print("FOOOO scene", dir(scene))
print("foooo", dir(scene.view_settings))
print("GNAAA", scene.view_settings.view_transform)
scene['BlenderShadowSettings'] = scene_shadows_to_component(scene)
if scene.eevee.use_bloom:
@ -32,11 +23,11 @@ def remove_scene_components(main_scenes):
def scene_tonemapping_to_component(scene):
tone_mapping = scene.view_settings.view_transform
blender_to_bevy = {
'NONE': '',
'NONE': 'None',
'AgX': 'AgX',
'Filmic': 'Filmic',
}
bevy_tone_mapping = blender_to_bevy[tone_mapping] if tone_mapping in blender_to_bevy else None
bevy_tone_mapping = blender_to_bevy[tone_mapping] if tone_mapping in blender_to_bevy else 'None'
return bevy_tone_mapping
def scene_colorgrading_to_component(scene):

View File

@ -14,7 +14,10 @@ def assets_to_fake_ron(list_like):
result = []
for item in list_like:
result.append(f"(name: \"{item['name']}\", path: \"{item['path']}\")")
return result#.join(", ")
return f"(assets: {result})".replace("'", '')
return f"({result})".replace("'", '')
def export_main_scene(scene, settings, blueprints_data):
@ -78,8 +81,8 @@ def export_main_scene(scene, settings, blueprints_data):
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
#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:
#print("SPLIT STATIC AND DYNAMIC")

View File

@ -59,7 +59,7 @@ class AutoExportSettings(PropertyGroup):
# blueprint settings
export_blueprints: BoolProperty(
name='Export Blueprints',
description='Replaces collection instances with an Empty with a BlueprintName custom property, and enabled a lot more features !',
description='Replaces collection instances with an Empty with a BlueprintInfo custom property, and enabled a lot more features !',
default=True,
update=save_settings
) # type: ignore

View File

@ -88,7 +88,6 @@ expected_custom_property_values = {'bevy_animation::AnimationPlayer': '(animatio
'bevy_gltf_blueprints::animation::BlueprintAnimations': '(named_animations: "")',
'bevy_gltf_blueprints::animation::SceneAnimations': '(named_animations: "")',
'bevy_gltf_blueprints::materials::MaterialInfo': '(name: " ", source: " ")',
'bevy_gltf_blueprints::spawn_from_blueprints::BlueprintName': '(" ")',
'bevy_gltf_blueprints::spawn_from_blueprints::BlueprintsList': '({})',
'bevy_gltf_blueprints::spawn_from_blueprints::SpawnHere': '()',
'bevy_gltf_components::GltfProcessed': '()',
@ -347,7 +346,6 @@ expected_custom_property_values_randomized = {'bevy_animation::AnimationPlayer':
'bevy_gltf_blueprints::animation::BlueprintAnimations': '(named_animations: "")',
'bevy_gltf_blueprints::animation::SceneAnimations': '(named_animations: "")',
'bevy_gltf_blueprints::materials::MaterialInfo': '(name: "sbnpsago", source: "piuzfbqp")',
'bevy_gltf_blueprints::spawn_from_blueprints::BlueprintName': '("sbnpsago")',
'bevy_gltf_blueprints::spawn_from_blueprints::BlueprintsList': '({})',
'bevy_gltf_blueprints::spawn_from_blueprints::SpawnHere': '()',
'bevy_gltf_components::GltfProcessed': '()',