Skip to main content

nightshade_api/
prefab.rs

1//! Runtime prefabs: capture a configured entity and its children once, then
2//! stamp copies of it anywhere. A prefab is a self-contained snapshot of a
3//! subtree with its meshes and textures embedded, so it survives a
4//! [`save_prefab`] round trip and instances independently of the original.
5
6use 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/// A reusable template captured from a live entity subtree. Build one with
14/// [`make_prefab`] and place copies with [`spawn_prefab`].
15#[derive(Clone)]
16pub struct Prefab {
17    scene: Scene,
18}
19
20/// Captures `root` and everything parented under it into a prefab, embedding the
21/// meshes and textures it references so the template is self-contained.
22pub 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
29/// Stamps a fresh copy of `prefab` into the world with its root moved to
30/// `position`, returning the root entities of the new instance. Scene-level
31/// render settings are preserved across the spawn, which the underlying scene
32/// load would otherwise overwrite.
33pub 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
51/// Captures `root` as a prefab and stores it under `name` so a later
52/// [`spawn_prefab_named_command`] can stamp copies without holding the prefab
53/// value, which is what the data and script command surface needs.
54pub(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
64/// Stamps a copy of the prefab registered under `name`, or nothing when no
65/// prefab is registered there.
66pub(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
77/// Serializes a prefab to self-contained bytes for storing on disk.
78pub 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
83/// Loads a prefab from bytes written by [`save_prefab`].
84pub fn load_prefab(bytes: &[u8]) -> Result<Prefab, SceneError> {
85    let scene = load_scene_binary_from_bytes(bytes)?;
86    Ok(Prefab { scene })
87}