1use nightshade::ecs::scene::commands::{save_scene_binary_to_bytes, spawn_scene, subtree_to_scene};
7use nightshade::ecs::scene::{
8 Scene, SceneError, apply_scene_settings, capture_scene_settings, embed_referenced_meshes,
9 embed_referenced_textures, load_scene_binary_from_bytes,
10};
11use nightshade::prelude::{Entity, Vec3, World, tracing};
12
13#[derive(Clone)]
16pub struct Prefab {
17 scene: Scene,
18}
19
20pub fn make_prefab(world: &mut World, root: Entity) -> Prefab {
23 let mut scene = subtree_to_scene(world, root, "prefab");
24 embed_referenced_meshes(world, &mut scene);
25 embed_referenced_textures(world, &mut scene);
26 Prefab { scene }
27}
28
29pub fn spawn_prefab(world: &mut World, prefab: &Prefab, position: Vec3) -> Vec<Entity> {
34 let settings = capture_scene_settings(world);
35 let atmosphere = world.resources.render_settings.atmosphere;
36 let roots = match spawn_scene(world, &prefab.scene, None) {
37 Ok(result) => result.root_entities,
38 Err(error) => {
39 tracing::error!("Failed to spawn prefab: {error}");
40 Vec::new()
41 }
42 };
43 apply_scene_settings(world, &settings);
44 world.resources.render_settings.atmosphere = atmosphere;
45 for &root in &roots {
46 crate::placement::set_position(world, root, position);
47 }
48 roots
49}
50
51pub(crate) fn register_prefab_command(world: &mut World, name: &str, root: Entity) -> bool {
55 let prefab = make_prefab(world, root);
56 world
57 .resources
58 .assets
59 .scene_prefabs
60 .insert(name.to_string(), prefab.scene);
61 true
62}
63
64pub(crate) fn spawn_prefab_named_command(
67 world: &mut World,
68 name: &str,
69 position: Vec3,
70) -> Vec<Entity> {
71 let Some(scene) = world.resources.assets.scene_prefabs.get(name).cloned() else {
72 return Vec::new();
73 };
74 spawn_prefab(world, &Prefab { scene }, position)
75}
76
77pub fn save_prefab(prefab: &Prefab) -> Result<Vec<u8>, SceneError> {
79 let mut scene = prefab.scene.clone();
80 save_scene_binary_to_bytes(&mut scene)
81}
82
83pub fn load_prefab(bytes: &[u8]) -> Result<Prefab, SceneError> {
85 let scene = load_scene_binary_from_bytes(bytes)?;
86 Ok(Prefab { scene })
87}