ferravex_play/
scene.rs

1//! Generational scene hierarchy, exact matrix composition, prefabs, a bounded
2//! binary scene format, and skeleton skin palettes. No renderer or asset loader.
3//!
4//! [`Scene::resolve_path`] and [`Scene::path_from`] use literal name components
5//! and reject ambiguous sibling names. Paths describe the current hierarchy;
6//! retain a [`NodeId`] when identity must survive reparenting.
7use std::collections::HashMap;
8
9pub type Matrix = [f32; 16];
10pub const IDENTITY: Matrix = [
11    1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0,
12];
13const MAX_NODES: usize = 100_000;
14const MAX_NAME: usize = 4096;
15const MAX_BYTES: usize = 16 * 1024 * 1024;
16#[derive(Clone, Copy, Debug, PartialEq)]
17pub struct Transform {
18    pub translation: [f32; 3],
19    pub rotation: [f32; 4],
20    pub scale: [f32; 3],
21}
22impl Default for Transform {
23    fn default() -> Self {
24        Self {
25            translation: [0.0; 3],
26            rotation: [0.0, 0.0, 0.0, 1.0],
27            scale: [1.0; 3],
28        }
29    }
30}
31impl Transform {
32    pub fn valid(self) -> bool {
33        self.translation
34            .into_iter()
35            .chain(self.rotation)
36            .chain(self.scale)
37            .all(f32::is_finite)
38            && self
39                .rotation
40                .into_iter()
41                .map(|n| f64::from(n).powi(2))
42                .sum::<f64>()
43                > 1e-20
44    }
45    /// Column-major T*R*S. Quaternion input is normalized; zero scale is allowed.
46    pub fn matrix(self) -> Result<Matrix, SceneError> {
47        if !self.valid() {
48            return Err(SceneError::InvalidTransform);
49        }
50        let length = self
51            .rotation
52            .into_iter()
53            .map(|v| f64::from(v).powi(2))
54            .sum::<f64>()
55            .sqrt();
56        let [x, y, z, w] = self.rotation.map(|v| (f64::from(v) / length) as f32);
57        let [sx, sy, sz] = self.scale;
58        let [tx, ty, tz] = self.translation;
59        Ok([
60            (1.0 - 2.0 * (y * y + z * z)) * sx,
61            2.0 * (x * y + z * w) * sx,
62            2.0 * (x * z - y * w) * sx,
63            0.0,
64            2.0 * (x * y - z * w) * sy,
65            (1.0 - 2.0 * (x * x + z * z)) * sy,
66            2.0 * (y * z + x * w) * sy,
67            0.0,
68            2.0 * (x * z + y * w) * sz,
69            2.0 * (y * z - x * w) * sz,
70            (1.0 - 2.0 * (x * x + y * y)) * sz,
71            0.0,
72            tx,
73            ty,
74            tz,
75            1.0,
76        ])
77    }
78}
79/// Column-major multiplication. Using matrices preserves shear from nonuniform
80/// parent scale followed by child rotation instead of approximating it as TRS.
81pub fn multiply(a: Matrix, b: Matrix) -> Matrix {
82    std::array::from_fn(|index| {
83        let row = index % 4;
84        let col = index / 4;
85        (0..4)
86            .map(|k| f64::from(a[k * 4 + row]) * f64::from(b[col * 4 + k]))
87            .sum::<f64>() as f32
88    })
89}
90pub fn transform_point(m: Matrix, p: [f32; 3]) -> [f32; 3] {
91    std::array::from_fn(|row| m[row] * p[0] + m[4 + row] * p[1] + m[8 + row] * p[2] + m[12 + row])
92}
93/// Generational handle scoped to the scene that created it. Handles from other
94/// scenes must not be mixed: their slot indices and generations can coincide.
95/// Reparenting preserves identity. Removing a subtree invalidates its handles,
96/// even if later nodes reuse the same slots or names. Decoding a scene remaps
97/// handles; a path is a fresh name lookup, not a persistent identity token.
98#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
99pub struct NodeId {
100    index: u32,
101    generation: u32,
102}
103#[derive(Clone, Copy, Debug, PartialEq, Eq)]
104pub enum SceneError {
105    InvalidNode,
106    InvalidTransform,
107    Cycle,
108    Capacity,
109    NameTooLong,
110    InvalidFormat,
111    InvalidSkeleton,
112}
113impl std::fmt::Display for SceneError {
114    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
115        match self {
116            Self::InvalidNode => f.write_str(
117                "node handle is stale or missing; reacquire it after removing a subtree",
118            ),
119            Self::InvalidTransform => f.write_str(
120                "invalid transform; use finite TRS values and a nonzero quaternion, and avoid world-matrix overflow",
121            ),
122            Self::Cycle => f.write_str(
123                "reparenting would create a cycle; a node cannot be its own ancestor",
124            ),
125            Self::Capacity => write!(
126                f,
127                "scene capacity exceeded or prefab is empty; limits are {MAX_NODES} node slots and {MAX_BYTES} encoded bytes (retired slots cannot be reused)",
128            ),
129            Self::NameTooLong => write!(f, "node name exceeds the {MAX_NAME}-byte UTF-8 limit"),
130            Self::InvalidFormat => f.write_str(
131                "invalid scene or prefab; check GSC1 version 1, lengths, UTF-8 names and acyclic parent links; prefab parents must precede children under one root",
132            ),
133            Self::InvalidSkeleton => f.write_str(
134                "invalid skeleton or pose buffers; use 1..=4096 joints with parents before children, finite inverse-bind matrices and one pose entry per joint",
135            ),
136        }
137    }
138}
139impl std::error::Error for SceneError {}
140
141/// Checked hierarchy lookup/inspection errors, separate from [`SceneError`] so
142/// existing scene mutation error matches remain compatible. Component indices
143/// are zero-based, relative to the supplied parent (or the scene's roots).
144///
145/// Duplicate names remain legal in a scene. Path operations reject an ambiguous
146/// step immediately, even if only one matching sibling has the requested suffix.
147/// Use an already known [`NodeId`] as the parent to address its children instead.
148///
149/// ```
150/// use ferravex_play::scene::{Scene, ScenePathError, Transform};
151/// let mut scene = Scene::new();
152/// let first = scene.create("actor", Transform::default(), None)?;
153/// scene.create("actor", Transform::default(), None)?;
154/// assert_eq!(scene.resolve_path(None, &["actor"]),
155///     Err(ScenePathError::Ambiguous { component: 0, parent: None }));
156/// assert_eq!(scene.resolve_path(Some(first), &[])?, first);
157/// # Ok::<(), Box<dyn std::error::Error>>(())
158/// ```
159#[derive(Clone, Copy, Debug, PartialEq, Eq)]
160pub enum ScenePathError {
161    /// A supplied handle is stale or missing. Foreign-scene handles whose slot
162    /// and generation coincide cannot be detected; see [`NodeId`].
163    InvalidNode(NodeId),
164    /// An empty absolute path cannot select a node; scenes have no implicit root.
165    EmptyPath,
166    /// A path exceeds the scene's maximum of 100,000 name components.
167    TooDeep,
168    /// A component exceeds the existing 4,096-byte UTF-8 node-name limit.
169    NameTooLong { component: usize },
170    /// No direct child (or root when `parent` is `None`) has this name.
171    NotFound {
172        component: usize,
173        parent: Option<NodeId>,
174    },
175    /// More than one direct child (or root) has this name. Never picks the first.
176    Ambiguous {
177        component: usize,
178        parent: Option<NodeId>,
179    },
180    /// Both handles are live, but `node` is neither `ancestor` nor its descendant.
181    NotDescendant { node: NodeId, ancestor: NodeId },
182}
183impl std::fmt::Display for ScenePathError {
184    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
185        match self {
186            Self::InvalidNode(id) => write!(f, "path node handle {id:?} is stale or missing"),
187            Self::EmptyPath => {
188                f.write_str("an absolute scene path needs at least one name component")
189            }
190            Self::TooDeep => write!(f, "scene path exceeds the {MAX_NODES}-component limit"),
191            Self::NameTooLong { component } => write!(
192                f,
193                "scene path component {component} exceeds the {MAX_NAME}-byte UTF-8 name limit"
194            ),
195            Self::NotFound { component, parent } => write!(
196                f,
197                "scene path component {component} has no matching child under {parent:?} (None means scene roots)"
198            ),
199            Self::Ambiguous { component, parent } => write!(
200                f,
201                "scene path component {component} is ambiguous under {parent:?}; duplicate sibling names require a known parent handle"
202            ),
203            Self::NotDescendant { node, ancestor } => write!(
204                f,
205                "path node {node:?} is not within the subtree of {ancestor:?}"
206            ),
207        }
208    }
209}
210impl std::error::Error for ScenePathError {}
211
212#[derive(Clone, Debug)]
213pub struct Node {
214    name: String,
215    local: Transform,
216    parent: Option<NodeId>,
217    children: Vec<NodeId>,
218}
219impl Node {
220    pub fn name(&self) -> &str {
221        &self.name
222    }
223    pub fn local(&self) -> Transform {
224        self.local
225    }
226    pub fn parent(&self) -> Option<NodeId> {
227        self.parent
228    }
229    pub fn children(&self) -> &[NodeId] {
230        &self.children
231    }
232}
233struct Slot {
234    generation: u32,
235    node: Option<Node>,
236}
237#[derive(Default)]
238pub struct Scene {
239    slots: Vec<Slot>,
240    free: Vec<u32>,
241    len: usize,
242}
243#[derive(Clone, Debug)]
244pub struct Prefab {
245    nodes: Vec<PrefabNode>,
246}
247#[derive(Clone, Debug)]
248struct PrefabNode {
249    name: String,
250    local: Transform,
251    parent: Option<usize>,
252}
253impl Prefab {
254    pub fn len(&self) -> usize {
255        self.nodes.len()
256    }
257    pub fn is_empty(&self) -> bool {
258        self.nodes.is_empty()
259    }
260}
261impl Scene {
262    pub fn new() -> Self {
263        Self::default()
264    }
265    pub fn len(&self) -> usize {
266        self.len
267    }
268    pub fn is_empty(&self) -> bool {
269        self.len == 0
270    }
271    pub fn node(&self, id: NodeId) -> Result<&Node, SceneError> {
272        self.slots
273            .get(id.index as usize)
274            .filter(|s| s.generation == id.generation)
275            .and_then(|s| s.node.as_ref())
276            .ok_or(SceneError::InvalidNode)
277    }
278    fn node_mut(&mut self, id: NodeId) -> Result<&mut Node, SceneError> {
279        self.slots
280            .get_mut(id.index as usize)
281            .filter(|s| s.generation == id.generation)
282            .and_then(|s| s.node.as_mut())
283            .ok_or(SceneError::InvalidNode)
284    }
285    pub fn nodes(&self) -> impl Iterator<Item = (NodeId, &Node)> {
286        self.slots.iter().enumerate().filter_map(|(index, slot)| {
287            slot.node.as_ref().map(|node| {
288                (
289                    NodeId {
290                        index: index as u32,
291                        generation: slot.generation,
292                    },
293                    node,
294                )
295            })
296        })
297    }
298    /// Resolves literal name components one hierarchy level at a time.
299    /// `None` starts among scene roots; `Some(parent)` starts among that node's
300    /// direct children. An empty relative path selects its live parent; an empty
301    /// absolute path returns [`ScenePathError::EmptyPath`].
302    ///
303    /// Names are case-sensitive UTF-8, with no normalization, splitting, escaping,
304    /// or special `.`/`..` semantics. For example, `["a/b", ""]` selects the
305    /// empty-named child of root `a/b`. This is the scene hierarchy, not the
306    /// authoring system's expanded identifier namespace.
307    ///
308    /// Duplicate roots/siblings are allowed by mutations but always produce
309    /// [`ScenePathError::Ambiguous`] at the first ambiguous component. A suffix
310    /// never disambiguates a prefix. Missing names return `NotFound`, including
311    /// the component index and its resolved parent. The supplied parent is
312    /// validated first, followed by the entire path's bounds (100,000 components,
313    /// 4,096 bytes per name), before any names are resolved.
314    ///
315    /// No allocation or recursion. Uses existing child links and [`Self::nodes`]
316    /// for roots; work is bounded by scene slots/visited sibling groups and input
317    /// names. The result is a current [`NodeId`], not a persistent path binding:
318    /// removing it and recreating its names can make the same path select a new
319    /// identity. Stale parent handles are rejected even for empty paths.
320    ///
321    /// ```
322    /// use ferravex_play::scene::{Scene, ScenePathError, Transform};
323    /// let mut scene = Scene::new();
324    /// let actor = scene.create("actor", Transform::default(), None)?;
325    /// let socket = scene.create("hand/socket", Transform::default(), Some(actor))?;
326    /// assert_eq!(scene.resolve_path(None, &["actor", "hand/socket"])?, socket);
327    /// assert_eq!(scene.resolve_path(Some(actor), &["hand/socket"])?, socket);
328    /// scene.remove_subtree(actor)?;
329    /// assert_eq!(scene.resolve_path(Some(actor), &[]),
330    ///     Err(ScenePathError::InvalidNode(actor)));
331    /// # Ok::<(), Box<dyn std::error::Error>>(())
332    /// ```
333    pub fn resolve_path(
334        &self,
335        parent: Option<NodeId>,
336        components: &[&str],
337    ) -> Result<NodeId, ScenePathError> {
338        if let Some(parent) = parent {
339            self.node(parent)
340                .map_err(|_| ScenePathError::InvalidNode(parent))?;
341        }
342        if components.len() > MAX_NODES {
343            return Err(ScenePathError::TooDeep);
344        }
345        for (component, name) in components.iter().enumerate() {
346            if name.len() > MAX_NAME {
347                return Err(ScenePathError::NameTooLong { component });
348            }
349        }
350        let mut cursor = parent;
351        for (component, &name) in components.iter().enumerate() {
352            let id = if let Some(parent) = cursor {
353                let node = self
354                    .node(parent)
355                    .map_err(|_| ScenePathError::InvalidNode(parent))?;
356                unique_path_match(
357                    node.children().iter().map(|&id| {
358                        (
359                            id,
360                            self.node(id)
361                                .expect("scene child links reference live nodes"),
362                        )
363                    }),
364                    name,
365                    component,
366                    cursor,
367                )?
368            } else {
369                unique_path_match(
370                    self.nodes().filter(|(_, node)| node.parent().is_none()),
371                    name,
372                    component,
373                    None,
374                )?
375            };
376            cursor = Some(id);
377        }
378        cursor.ok_or(ScenePathError::EmptyPath)
379    }
380    /// Inspects `id` as an unambiguous path from `parent`, excluding the parent's
381    /// own name. `None` includes the root's name; `Some(id)` returns an empty path.
382    /// The parent is checked first, then `id`. Both must be live, and `id` must
383    /// lie in the parent's subtree, or [`ScenePathError::NotDescendant`] is returned.
384    ///
385    /// Walks existing parent links iteratively, then uses [`Self::resolve_path`]
386    /// to check the same duplicate-name policy. On success, resolving the returned
387    /// components from the same parent returns exactly `id`. Duplicate ancestors
388    /// above or equal to an explicit parent do not affect relative paths.
389    ///
390    /// Allocates only a vector of borrowed names, bounded by scene depth (at most
391    /// 100,000 entries); names are not copied. The borrow prevents scene edits
392    /// while the path is in use. Owned copies of paths can change meaning after
393    /// edits; keep the [`NodeId`] to follow the same live node across reparenting.
394    /// Handles are scene-local and must not be reused after decoding a new scene.
395    ///
396    /// ```
397    /// use ferravex_play::scene::{Scene, Transform};
398    /// let mut scene = Scene::new();
399    /// let actor = scene.create("actor", Transform::default(), None)?;
400    /// let socket = scene.create("socket", Transform::default(), Some(actor))?;
401    /// let path = scene.path_from(None, socket)?;
402    /// assert_eq!(path, ["actor", "socket"]);
403    /// assert_eq!(scene.resolve_path(None, &path)?, socket);
404    /// assert_eq!(scene.path_from(Some(actor), socket)?, ["socket"]);
405    /// scene.set_parents(&[(actor, Some(socket)), (socket, None)])?;
406    /// assert_eq!(scene.path_from(None, actor)?, ["socket", "actor"]);
407    /// # Ok::<(), Box<dyn std::error::Error>>(())
408    /// ```
409    pub fn path_from(
410        &self,
411        parent: Option<NodeId>,
412        id: NodeId,
413    ) -> Result<Vec<&str>, ScenePathError> {
414        if let Some(parent) = parent {
415            self.node(parent)
416                .map_err(|_| ScenePathError::InvalidNode(parent))?;
417        }
418        self.node(id).map_err(|_| ScenePathError::InvalidNode(id))?;
419        let mut components = Vec::new();
420        let mut cursor = Some(id);
421        while let Some(current) = cursor {
422            if cursor == parent {
423                break;
424            }
425            let node = self
426                .node(current)
427                .map_err(|_| ScenePathError::InvalidNode(current))?;
428            components.push(node.name());
429            cursor = node.parent();
430        }
431        if cursor != parent {
432            return Err(ScenePathError::NotDescendant {
433                node: id,
434                ancestor: parent.expect("only a specified parent can be outside the ancestry"),
435            });
436        }
437        components.reverse();
438        self.resolve_path(parent, &components)?;
439        Ok(components)
440    }
441    /// Visits a root and its descendants in depth-first, parent-before-child
442    /// order, respecting each node's child order. A stale root is rejected before
443    /// traversal starts. The iterator borrows the scene, preventing edits while
444    /// it is in use, and uses a heap stack rather than recursion.
445    ///
446    /// Collect IDs first when applying edits to the visited nodes:
447    ///
448    /// ```
449    /// use ferravex_play::scene::{Scene, Transform};
450    /// let mut scene = Scene::new();
451    /// let actor = scene.create("actor", Transform::default(), None)?;
452    /// let socket = scene.create("socket", Transform::default(), Some(actor))?;
453    /// let ids: Vec<_> = scene.subtree(actor)?.map(|(id, _)| id).collect();
454    /// assert_eq!(ids, [actor, socket]);
455    /// for id in ids {
456    ///     scene.set_local(id, Transform::default())?;
457    /// }
458    /// # Ok::<(), ferravex_play::scene::SceneError>(())
459    /// ```
460    pub fn subtree(
461        &self,
462        root: NodeId,
463    ) -> Result<impl Iterator<Item = (NodeId, &Node)> + '_, SceneError> {
464        self.node(root)?;
465        let mut pending = vec![root];
466        Ok(std::iter::from_fn(move || {
467            let id = pending.pop()?;
468            let node = self
469                .node(id)
470                .expect("scene child links reference live nodes");
471            pending.extend(node.children.iter().rev().copied());
472            Some((id, node))
473        }))
474    }
475    pub fn create(
476        &mut self,
477        name: impl Into<String>,
478        local: Transform,
479        parent: Option<NodeId>,
480    ) -> Result<NodeId, SceneError> {
481        let name = name.into();
482        if name.len() > MAX_NAME {
483            return Err(SceneError::NameTooLong);
484        }
485        if !local.valid() {
486            return Err(SceneError::InvalidTransform);
487        }
488        if self.len == MAX_NODES || (self.free.is_empty() && self.slots.len() == MAX_NODES) {
489            return Err(SceneError::Capacity);
490        }
491        if let Some(parent) = parent {
492            self.node(parent)?;
493        }
494        let index = if let Some(index) = self.free.pop() {
495            index
496        } else {
497            self.slots.push(Slot {
498                generation: 0,
499                node: None,
500            });
501            (self.slots.len() - 1) as u32
502        };
503        let slot = &mut self.slots[index as usize];
504        let id = NodeId {
505            index,
506            generation: slot.generation,
507        };
508        slot.node = Some(Node {
509            name,
510            local,
511            parent,
512            children: Vec::new(),
513        });
514        self.len += 1;
515        if let Some(parent) = parent {
516            self.node_mut(parent)?.children.push(id);
517        }
518        Ok(id)
519    }
520    pub fn set_local(&mut self, id: NodeId, local: Transform) -> Result<(), SceneError> {
521        if !local.valid() {
522            return Err(SceneError::InvalidTransform);
523        }
524        self.node_mut(id)?.local = local;
525        Ok(())
526    }
527    /// Reparent while retaining local TRS. Cycles and invalid handles are rejected
528    /// before any links change. World-space position may change.
529    pub fn set_parent(&mut self, id: NodeId, parent: Option<NodeId>) -> Result<(), SceneError> {
530        let old = self.node(id)?.parent;
531        let mut ancestor = parent;
532        while let Some(candidate) = ancestor {
533            if candidate == id {
534                return Err(SceneError::Cycle);
535            }
536            ancestor = self.node(candidate)?.parent;
537        }
538        if old == parent {
539            return Ok(());
540        }
541        self.relink(id, parent);
542        Ok(())
543    }
544    /// Applies reparenting edits atomically, retaining every local transform.
545    /// Validates the *final* hierarchy, so edits can succeed even when applying
546    /// them individually in the given order would temporarily create a cycle.
547    /// Any stale handle or final cycle leaves the entire scene unchanged.
548    ///
549    /// Repeated node IDs use the last requested parent; all supplied handles are
550    /// checked, including overwritten requests. Moved children are appended in
551    /// order of their first appearance. Unchanged links retain their order.
552    /// Work and scratch space are linear in scene slots plus requested edits;
553    /// traversal does not recurse, even for deeply nested hierarchies.
554    ///
555    /// ```
556    /// use ferravex_play::scene::{Scene, Transform};
557    /// let mut scene = Scene::new();
558    /// let carrier = scene.create("carrier", Transform::default(), None)?;
559    /// let payload = scene.create("payload", Transform::default(), Some(carrier))?;
560    /// // Make payload the root and attach carrier beneath it in one edit.
561    /// scene.set_parents(&[(carrier, Some(payload)), (payload, None)])?;
562    /// assert_eq!(scene.node(carrier)?.parent(), Some(payload));
563    /// assert_eq!(scene.node(payload)?.parent(), None);
564    /// # Ok::<(), ferravex_play::scene::SceneError>(())
565    /// ```
566    pub fn set_parents(&mut self, changes: &[(NodeId, Option<NodeId>)]) -> Result<(), SceneError> {
567        if changes.is_empty() {
568            return Ok(());
569        }
570        for &(id, parent) in changes {
571            self.node(id)?;
572            if let Some(parent) = parent {
573                self.node(parent)?;
574            }
575        }
576        let mut parents: Vec<_> = self
577            .slots
578            .iter()
579            .map(|slot| slot.node.as_ref().and_then(|node| node.parent))
580            .collect();
581        for &(id, parent) in changes {
582            parents[id.index as usize] = parent;
583        }
584        // Every new cycle must contain an edited node. Each ancestor is visited
585        // at most once across all edits, using the final parent map.
586        let mut marks = vec![0_u8; self.slots.len()];
587        let mut chain = Vec::new();
588        for &(id, _) in changes {
589            let mut cursor = Some(id);
590            while let Some(id) = cursor {
591                let index = id.index as usize;
592                if marks[index] != 0 {
593                    break;
594                }
595                marks[index] = 1;
596                chain.push(index);
597                cursor = parents[index];
598            }
599            if cursor.is_some_and(|id| marks[id.index as usize] == 1) {
600                return Err(SceneError::Cycle);
601            }
602            for index in chain.drain(..) {
603                marks[index] = 2;
604            }
605        }
606        // Detach in one pass; retaining a wide parent's child list separately
607        // for each moved child would make a large batch quadratic.
608        for (index, slot) in self.slots.iter_mut().enumerate() {
609            if let Some(node) = &mut slot.node {
610                let id = NodeId {
611                    index: index as u32,
612                    generation: slot.generation,
613                };
614                node.children
615                    .retain(|child| parents[child.index as usize] == Some(id));
616            }
617        }
618        for &(id, _) in changes {
619            let parent = parents[id.index as usize];
620            let node = self.node_mut(id).expect("validated node");
621            if node.parent == parent {
622                continue;
623            }
624            node.parent = parent;
625            if let Some(parent) = parent {
626                self.node_mut(parent)
627                    .expect("validated parent")
628                    .children
629                    .push(id);
630            }
631        }
632        Ok(())
633    }
634    // Call only after validating all handles and the resulting parent graph.
635    // No fallible operations remain once link mutation begins.
636    fn relink(&mut self, id: NodeId, parent: Option<NodeId>) {
637        let old = self.node(id).expect("validated node").parent;
638        if old == parent {
639            return;
640        }
641        if let Some(old) = old {
642            self.node_mut(old)
643                .expect("scene parent links reference live nodes")
644                .children
645                .retain(|child| *child != id);
646        }
647        if let Some(parent) = parent {
648            self.node_mut(parent)
649                .expect("validated parent")
650                .children
651                .push(id);
652        }
653        self.node_mut(id).expect("validated node").parent = parent;
654    }
655    pub fn world_matrix(&self, id: NodeId) -> Result<Matrix, SceneError> {
656        let node = self.node(id)?;
657        let mut matrix = node.local.matrix()?;
658        let mut parent = node.parent;
659        while let Some(id) = parent {
660            let node = self.node(id)?;
661            matrix = multiply(node.local.matrix()?, matrix);
662            parent = node.parent;
663        }
664        if matrix.into_iter().all(f32::is_finite) {
665            Ok(matrix)
666        } else {
667            Err(SceneError::InvalidTransform)
668        }
669    }
670    pub fn remove_subtree(&mut self, root: NodeId) -> Result<usize, SceneError> {
671        let parent = self.node(root)?.parent;
672        let mut ids = vec![root];
673        let mut index = 0;
674        while index < ids.len() {
675            ids.extend_from_slice(self.node(ids[index])?.children());
676            index += 1;
677        }
678        if let Some(parent) = parent {
679            self.node_mut(parent)?
680                .children
681                .retain(|child| *child != root);
682        }
683        for id in ids.iter().rev() {
684            let slot = &mut self.slots[id.index as usize];
685            slot.node = None;
686            if let Some(next) = slot.generation.checked_add(1) {
687                slot.generation = next;
688                self.free.push(id.index);
689            }
690        }
691        self.len -= ids.len();
692        Ok(ids.len())
693    }
694    /// Captures local transforms and hierarchy; external parent links are omitted.
695    pub fn prefab(&self, root: NodeId) -> Result<Prefab, SceneError> {
696        self.node(root)?;
697        let mut pending = vec![(root, None)];
698        let mut nodes = Vec::new();
699        let mut cursor = 0;
700        while cursor < pending.len() {
701            let (id, parent) = pending[cursor];
702            let node = self.node(id)?;
703            nodes.push(PrefabNode {
704                name: node.name.clone(),
705                local: node.local,
706                parent,
707            });
708            pending.extend(node.children.iter().map(|child| (*child, Some(cursor))));
709            cursor += 1;
710        }
711        Ok(Prefab { nodes })
712    }
713    /// Inserts an independent copy under `parent`, retaining prefab-local TRS.
714    /// All entries, links and capacity are checked before insertion; any returned
715    /// error leaves existing nodes, child order and handle allocation unchanged.
716    ///
717    /// ```
718    /// use ferravex_play::scene::{Scene, Transform};
719    /// let mut scene = Scene::new();
720    /// let source = scene.create("enemy", Transform::default(), None)?;
721    /// let prefab = scene.prefab(source)?;
722    /// let copy = scene.instantiate(&prefab, None)?;
723    /// assert_ne!(source, copy);
724    /// assert_eq!(scene.node(copy)?.name(), "enemy");
725    /// # Ok::<(), ferravex_play::scene::SceneError>(())
726    /// ```
727    pub fn instantiate(
728        &mut self,
729        prefab: &Prefab,
730        parent: Option<NodeId>,
731    ) -> Result<NodeId, SceneError> {
732        if let Some(parent) = parent {
733            self.node(parent)?;
734        }
735        let available = MAX_NODES - self.slots.len() + self.free.len();
736        if prefab.nodes.is_empty() || prefab.nodes.len() > available {
737            return Err(SceneError::Capacity);
738        }
739        // Preflight the whole prefab: a later invalid transform/name must not
740        // leave earlier nodes inserted, and invalid indices must never panic.
741        for (index, node) in prefab.nodes.iter().enumerate() {
742            if node.name.len() > MAX_NAME {
743                return Err(SceneError::NameTooLong);
744            }
745            if !node.local.valid() {
746                return Err(SceneError::InvalidTransform);
747            }
748            match (index, node.parent) {
749                (0, None) => {}
750                (_, Some(parent)) if parent < index => {}
751                _ => return Err(SceneError::InvalidFormat),
752            }
753        }
754        let mut ids = Vec::with_capacity(prefab.nodes.len());
755        for node in &prefab.nodes {
756            let node_parent = node.parent.map(|index| ids[index]).or(parent);
757            ids.push(self.create(node.name.clone(), node.local, node_parent)?);
758        }
759        Ok(ids[0])
760    }
761    pub fn clone_subtree(
762        &mut self,
763        root: NodeId,
764        parent: Option<NodeId>,
765    ) -> Result<NodeId, SceneError> {
766        self.instantiate(&self.prefab(root)?, parent)
767    }
768    /// GSC1 format: magic, u16 version, u32 count; each node has u32 parent
769    /// (MAX=root), u16 UTF-8 name length, name bytes, and 10 little-endian f32 TRS
770    /// values. Handles are remapped; serialized data never trusts slot generations.
771    pub fn encode(&self) -> Result<Vec<u8>, SceneError> {
772        let nodes: Vec<_> = self.nodes().collect();
773        let indices: HashMap<_, _> = nodes
774            .iter()
775            .enumerate()
776            .map(|(i, (id, _))| (*id, i as u32))
777            .collect();
778        let length = 10
779            + nodes
780                .iter()
781                .map(|(_, node)| 46 + node.name.len())
782                .sum::<usize>();
783        if length > MAX_BYTES {
784            return Err(SceneError::Capacity);
785        }
786        let mut bytes = Vec::with_capacity(length);
787        bytes.extend_from_slice(b"GSC1");
788        bytes.extend_from_slice(&1_u16.to_le_bytes());
789        bytes.extend_from_slice(&(nodes.len() as u32).to_le_bytes());
790        for (_, node) in nodes {
791            bytes.extend_from_slice(
792                &node
793                    .parent
794                    .map_or(u32::MAX, |parent| indices[&parent])
795                    .to_le_bytes(),
796            );
797            bytes.extend_from_slice(&(node.name.len() as u16).to_le_bytes());
798            bytes.extend_from_slice(node.name.as_bytes());
799            for value in node
800                .local
801                .translation
802                .into_iter()
803                .chain(node.local.rotation)
804                .chain(node.local.scale)
805            {
806                bytes.extend_from_slice(&value.to_le_bytes());
807            }
808        }
809        Ok(bytes)
810    }
811    pub fn decode(bytes: &[u8]) -> Result<Self, SceneError> {
812        if bytes.len() > MAX_BYTES {
813            return Err(SceneError::InvalidFormat);
814        }
815        let mut reader = Reader { bytes, cursor: 0 };
816        if reader.take(4)? != b"GSC1" || reader.u16()? != 1 {
817            return Err(SceneError::InvalidFormat);
818        }
819        let count = reader.u32()? as usize;
820        if count > MAX_NODES || count > bytes.len().saturating_sub(10) / 46 {
821            return Err(SceneError::InvalidFormat);
822        }
823        let mut scene = Self::new();
824        let mut ids = Vec::with_capacity(count);
825        let mut parents = Vec::with_capacity(count);
826        for _ in 0..count {
827            let parent = reader.u32()?;
828            if parent != u32::MAX && parent as usize >= count {
829                return Err(SceneError::InvalidFormat);
830            }
831            let len = reader.u16()? as usize;
832            if len > MAX_NAME {
833                return Err(SceneError::InvalidFormat);
834            }
835            let name =
836                std::str::from_utf8(reader.take(len)?).map_err(|_| SceneError::InvalidFormat)?;
837            let mut values = [0.0; 10];
838            for value in &mut values {
839                *value = reader.f32()?;
840            }
841            let transform = Transform {
842                translation: [values[0], values[1], values[2]],
843                rotation: [values[3], values[4], values[5], values[6]],
844                scale: [values[7], values[8], values[9]],
845            };
846            ids.push(
847                scene
848                    .create(name, transform, None)
849                    .map_err(|_| SceneError::InvalidFormat)?,
850            );
851            parents.push(parent);
852        }
853        if reader.cursor != bytes.len() {
854            return Err(SceneError::InvalidFormat);
855        }
856        // Validate the parent graph in linear time before linking. Repeatedly
857        // calling set_parent for a long serialized chain would be quadratic.
858        let mut marks = vec![0_u8; count];
859        let mut chain = Vec::new();
860        for start in 0..count {
861            if marks[start] != 0 {
862                continue;
863            }
864            let mut cursor = Some(start);
865            while let Some(index) = cursor {
866                if marks[index] != 0 {
867                    break;
868                }
869                marks[index] = 1;
870                chain.push(index);
871                cursor = (parents[index] != u32::MAX).then_some(parents[index] as usize);
872            }
873            if cursor.is_some_and(|index| marks[index] == 1) {
874                return Err(SceneError::InvalidFormat);
875            }
876            for index in chain.drain(..) {
877                marks[index] = 2;
878            }
879        }
880        for (index, parent) in parents.into_iter().enumerate() {
881            if parent != u32::MAX {
882                let child_id = ids[index];
883                let parent_id = ids[parent as usize];
884                scene.node_mut(child_id)?.parent = Some(parent_id);
885                scene.node_mut(parent_id)?.children.push(child_id);
886            }
887        }
888        Ok(scene)
889    }
890}
891fn unique_path_match<'a>(
892    nodes: impl Iterator<Item = (NodeId, &'a Node)>,
893    name: &str,
894    component: usize,
895    parent: Option<NodeId>,
896) -> Result<NodeId, ScenePathError> {
897    let mut matches = nodes
898        .filter(|(_, node)| node.name() == name)
899        .map(|(id, _)| id);
900    let id = matches
901        .next()
902        .ok_or(ScenePathError::NotFound { component, parent })?;
903    if matches.next().is_some() {
904        return Err(ScenePathError::Ambiguous { component, parent });
905    }
906    Ok(id)
907}
908struct Reader<'a> {
909    bytes: &'a [u8],
910    cursor: usize,
911}
912impl<'a> Reader<'a> {
913    fn take(&mut self, count: usize) -> Result<&'a [u8], SceneError> {
914        let end = self
915            .cursor
916            .checked_add(count)
917            .ok_or(SceneError::InvalidFormat)?;
918        let bytes = self
919            .bytes
920            .get(self.cursor..end)
921            .ok_or(SceneError::InvalidFormat)?;
922        self.cursor = end;
923        Ok(bytes)
924    }
925    fn u16(&mut self) -> Result<u16, SceneError> {
926        Ok(u16::from_le_bytes(
927            self.take(2)?
928                .try_into()
929                .map_err(|_| SceneError::InvalidFormat)?,
930        ))
931    }
932    fn u32(&mut self) -> Result<u32, SceneError> {
933        Ok(u32::from_le_bytes(
934            self.take(4)?
935                .try_into()
936                .map_err(|_| SceneError::InvalidFormat)?,
937        ))
938    }
939    fn f32(&mut self) -> Result<f32, SceneError> {
940        Ok(f32::from_le_bytes(
941            self.take(4)?
942                .try_into()
943                .map_err(|_| SceneError::InvalidFormat)?,
944        ))
945    }
946}
947
948#[derive(Clone, Debug)]
949pub struct Joint {
950    pub parent: Option<usize>,
951    pub inverse_bind: Matrix,
952}
953#[derive(Clone, Debug)]
954pub struct Skeleton {
955    joints: Vec<Joint>,
956}
957impl Skeleton {
958    /// Joints must be parent-before-child; this also proves acyclic hierarchy.
959    pub fn new(joints: Vec<Joint>) -> Result<Self, SceneError> {
960        if joints.is_empty()
961            || joints.len() > 4096
962            || joints.iter().enumerate().any(|(i, joint)| {
963                joint.parent.is_some_and(|parent| parent >= i)
964                    || !joint.inverse_bind.into_iter().all(f32::is_finite)
965            })
966        {
967            return Err(SceneError::InvalidSkeleton);
968        }
969        Ok(Self { joints })
970    }
971    pub fn joint_count(&self) -> usize {
972        self.joints.len()
973    }
974    /// Borrow the validated parent order and inverse-bind data without cloning.
975    /// Joint names and local rest poses remain caller-owned authoring metadata.
976    pub fn joints(&self) -> &[Joint] {
977        &self.joints
978    }
979    pub fn world_pose(&self, locals: &[Transform]) -> Result<Vec<Matrix>, SceneError> {
980        let mut world = vec![IDENTITY; self.joints.len()];
981        self.world_pose_into(locals, &mut world)?;
982        Ok(world)
983    }
984    /// Allocation-free pose evaluation into caller-owned scratch. On numeric
985    /// overflow output may be partially written; use it only after Ok(()).
986    pub fn world_pose_into(
987        &self,
988        locals: &[Transform],
989        world: &mut [Matrix],
990    ) -> Result<(), SceneError> {
991        if locals.len() != self.joints.len() || world.len() != locals.len() {
992            return Err(SceneError::InvalidSkeleton);
993        }
994        if !locals.iter().all(|local| local.valid()) {
995            return Err(SceneError::InvalidTransform);
996        }
997        for (i, (joint, local)) in self.joints.iter().zip(locals).enumerate() {
998            let matrix = local.matrix()?;
999            let matrix = joint
1000                .parent
1001                .map_or(matrix, |parent| multiply(world[parent], matrix));
1002            if !matrix.into_iter().all(f32::is_finite) {
1003                return Err(SceneError::InvalidTransform);
1004            }
1005            world[i] = matrix;
1006        }
1007        Ok(())
1008    }
1009    /// Model-space joint world pose multiplied by inverse bind, ready for skinning.
1010    pub fn skin_palette(&self, locals: &[Transform]) -> Result<Vec<Matrix>, SceneError> {
1011        let mut world = vec![IDENTITY; self.joints.len()];
1012        let mut palette = vec![IDENTITY; self.joints.len()];
1013        self.skin_palette_into(locals, &mut world, &mut palette)?;
1014        Ok(palette)
1015    }
1016    /// Model-space world * inverse-bind using preallocated buffers. Both outputs
1017    /// are scratch on error. No heap allocation or hierarchy traversal recursion.
1018    pub fn skin_palette_into(
1019        &self,
1020        locals: &[Transform],
1021        world: &mut [Matrix],
1022        palette: &mut [Matrix],
1023    ) -> Result<(), SceneError> {
1024        if palette.len() != self.joints.len() {
1025            return Err(SceneError::InvalidSkeleton);
1026        }
1027        self.world_pose_into(locals, world)?;
1028        for ((out, pose), joint) in palette.iter_mut().zip(world).zip(&self.joints) {
1029            let matrix = multiply(*pose, joint.inverse_bind);
1030            if !matrix.into_iter().all(f32::is_finite) {
1031                return Err(SceneError::InvalidTransform);
1032            }
1033            *out = matrix;
1034        }
1035        Ok(())
1036    }
1037}
1038
1039#[cfg(test)]
1040mod tests {
1041    use super::*;
1042    fn translated(x: f32, y: f32, z: f32) -> Transform {
1043        Transform {
1044            translation: [x, y, z],
1045            ..Transform::default()
1046        }
1047    }
1048    #[test]
1049    fn hierarchy_composes_parent_rotation_and_child_translation() {
1050        let mut scene = Scene::new();
1051        let root = scene
1052            .create(
1053                "root",
1054                Transform {
1055                    rotation: [
1056                        0.0,
1057                        0.0,
1058                        std::f32::consts::FRAC_1_SQRT_2,
1059                        std::f32::consts::FRAC_1_SQRT_2,
1060                    ],
1061                    ..translated(2.0, 0.0, 0.0)
1062                },
1063                None,
1064            )
1065            .unwrap();
1066        let child = scene
1067            .create("child", translated(3.0, 0.0, 0.0), Some(root))
1068            .unwrap();
1069        let p = transform_point(scene.world_matrix(child).unwrap(), [0.0; 3]);
1070        assert!((p[0] - 2.0).abs() < 1e-5);
1071        assert!((p[1] - 3.0).abs() < 1e-5);
1072        assert_eq!(scene.set_parent(root, Some(child)), Err(SceneError::Cycle));
1073        assert_eq!(scene.node(root).unwrap().parent(), None);
1074    }
1075    #[test]
1076    fn prefab_copy_is_independent_and_stale_ids_stay_invalid() {
1077        let mut scene = Scene::new();
1078        let root = scene.create("root", Transform::default(), None).unwrap();
1079        let child = scene
1080            .create("child", translated(2.0, 0.0, 0.0), Some(root))
1081            .unwrap();
1082        let copy = scene.clone_subtree(root, None).unwrap();
1083        assert_eq!(scene.len(), 4);
1084        let copied_child = scene.node(copy).unwrap().children()[0];
1085        scene.set_local(child, translated(5.0, 0.0, 0.0)).unwrap();
1086        assert_eq!(
1087            scene.node(copied_child).unwrap().local().translation[0],
1088            2.0
1089        );
1090        assert_eq!(scene.remove_subtree(root).unwrap(), 2);
1091        scene.create("reuse", Transform::default(), None).unwrap();
1092        assert!(matches!(scene.node(root), Err(SceneError::InvalidNode)));
1093        assert!(matches!(scene.node(child), Err(SceneError::InvalidNode)));
1094    }
1095    #[test]
1096    fn subtree_preserves_sibling_order_and_rejects_reused_handles() {
1097        let mut scene = Scene::new();
1098        let root = scene.create("root", Transform::default(), None).unwrap();
1099        let left = scene
1100            .create("left", Transform::default(), Some(root))
1101            .unwrap();
1102        let right = scene
1103            .create("right", Transform::default(), Some(root))
1104            .unwrap();
1105        let leaf = scene
1106            .create("leaf", Transform::default(), Some(left))
1107            .unwrap();
1108        let ids: Vec<_> = scene.subtree(root).unwrap().map(|(id, _)| id).collect();
1109        assert_eq!(ids, [root, left, leaf, right]);
1110        scene.remove_subtree(left).unwrap();
1111        let replacement = scene
1112            .create("replacement", Transform::default(), Some(root))
1113            .unwrap();
1114        assert_eq!(replacement.index, left.index);
1115        assert_ne!(replacement, left);
1116        assert_eq!(scene.subtree(left).err(), Some(SceneError::InvalidNode));
1117        let names: Vec<_> = scene
1118            .subtree(root)
1119            .unwrap()
1120            .map(|(_, node)| node.name())
1121            .collect();
1122        assert_eq!(names, ["root", "right", "replacement"]);
1123    }
1124    #[test]
1125    fn paths_use_literal_names_and_roundtrip_every_level() {
1126        let mut scene = Scene::new();
1127        let root = scene.create("a/b", Transform::default(), None).unwrap();
1128        let names = ["", ".", "..", "父", "\\", "\0", "é", "e\u{301}"];
1129        let mut leaf = root;
1130        for name in names {
1131            leaf = scene
1132                .create(name, Transform::default(), Some(leaf))
1133                .unwrap();
1134        }
1135        let before = scene.encode().unwrap();
1136        for (id, _) in scene.subtree(root).unwrap() {
1137            let absolute = scene.path_from(None, id).unwrap();
1138            assert_eq!(scene.resolve_path(None, &absolute), Ok(id));
1139            let relative = scene.path_from(Some(root), id).unwrap();
1140            assert_eq!(scene.resolve_path(Some(root), &relative), Ok(id));
1141        }
1142        assert_eq!(scene.path_from(Some(root), leaf).unwrap(), names);
1143        assert_eq!(scene.resolve_path(Some(root), &names), Ok(leaf));
1144        assert_eq!(scene.resolve_path(Some(root), &[]), Ok(root));
1145        assert!(scene.path_from(Some(leaf), leaf).unwrap().is_empty());
1146        assert_eq!(scene.encode().unwrap(), before);
1147
1148        let a = scene.create("a", Transform::default(), None).unwrap();
1149        let b = scene.create("b", Transform::default(), Some(a)).unwrap();
1150        assert_eq!(scene.resolve_path(None, &["a/b"]), Ok(root));
1151        assert_eq!(scene.resolve_path(None, &["a", "b"]), Ok(b));
1152        assert_eq!(
1153            scene.resolve_path(None, &["A"]),
1154            Err(ScenePathError::NotFound {
1155                component: 0,
1156                parent: None
1157            })
1158        );
1159        let composed = scene.create("é", Transform::default(), None).unwrap();
1160        let decomposed = scene
1161            .create("e\u{301}", Transform::default(), None)
1162            .unwrap();
1163        assert_eq!(scene.resolve_path(None, &["é"]), Ok(composed));
1164        assert_eq!(scene.resolve_path(None, &["e\u{301}"]), Ok(decomposed));
1165        let unnamed = scene.create("", Transform::default(), None).unwrap();
1166        assert_eq!(scene.resolve_path(None, &[""]), Ok(unnamed));
1167        assert_eq!(scene.path_from(None, unnamed).unwrap(), [""]);
1168    }
1169    #[test]
1170    fn paths_reject_duplicate_prefixes_without_searching_the_suffix() {
1171        let mut scene = Scene::new();
1172        let first = scene.create("actor", Transform::default(), None).unwrap();
1173        let leaf = scene
1174            .create("socket", Transform::default(), Some(first))
1175            .unwrap();
1176        let second = scene.create("actor", Transform::default(), None).unwrap();
1177        let root_error = ScenePathError::Ambiguous {
1178            component: 0,
1179            parent: None,
1180        };
1181        for path in [&["actor"][..], &["actor", "socket"], &["actor", "missing"]] {
1182            assert_eq!(scene.resolve_path(None, path), Err(root_error));
1183        }
1184        assert_eq!(scene.path_from(None, first), Err(root_error));
1185        assert_eq!(scene.path_from(None, leaf), Err(root_error));
1186        assert_eq!(scene.path_from(None, second), Err(root_error));
1187        assert_eq!(scene.resolve_path(Some(first), &["socket"]), Ok(leaf));
1188        assert_eq!(scene.path_from(Some(first), leaf).unwrap(), ["socket"]);
1189
1190        scene.remove_subtree(second).unwrap();
1191        scene
1192            .create("unrelated", Transform::default(), Some(first))
1193            .unwrap();
1194        let duplicate = scene
1195            .create("socket", Transform::default(), Some(first))
1196            .unwrap();
1197        let child_error = ScenePathError::Ambiguous {
1198            component: 1,
1199            parent: Some(first),
1200        };
1201        assert_eq!(
1202            scene.resolve_path(None, &["actor", "socket"]),
1203            Err(child_error)
1204        );
1205        assert_eq!(scene.path_from(None, leaf), Err(child_error));
1206        assert_eq!(scene.path_from(None, duplicate), Err(child_error));
1207        assert_eq!(
1208            scene.resolve_path(Some(first), &["socket"]),
1209            Err(ScenePathError::Ambiguous {
1210                component: 0,
1211                parent: Some(first)
1212            })
1213        );
1214        // An explicit handle still selects a duplicate-named node unambiguously.
1215        assert_eq!(scene.resolve_path(Some(duplicate), &[]), Ok(duplicate));
1216    }
1217    #[test]
1218    fn missing_paths_report_the_component_and_resolved_parent() {
1219        let mut scene = Scene::new();
1220        let first = scene.create("first", Transform::default(), None).unwrap();
1221        let second = scene.create("second", Transform::default(), None).unwrap();
1222        let child = scene
1223            .create("child", Transform::default(), Some(second))
1224            .unwrap();
1225        for (path, component, parent) in [
1226            (vec!["child"], 0, None),
1227            (vec!["first", "child"], 1, Some(first)),
1228            (vec!["second", "child", "missing"], 2, Some(child)),
1229        ] {
1230            assert_eq!(
1231                scene.resolve_path(None, &path),
1232                Err(ScenePathError::NotFound { component, parent })
1233            );
1234        }
1235        // A matching name under an unrelated parent does not create ambiguity.
1236        let other = scene
1237            .create("child", Transform::default(), Some(first))
1238            .unwrap();
1239        assert_eq!(scene.resolve_path(Some(first), &["child"]), Ok(other));
1240        assert_eq!(scene.resolve_path(Some(second), &["child"]), Ok(child));
1241        assert_eq!(scene.path_from(Some(first), other).unwrap(), ["child"]);
1242    }
1243    #[test]
1244    fn path_bounds_are_checked_before_resolving_names() {
1245        let mut scene = Scene::new();
1246        assert_eq!(
1247            scene.resolve_path(None, &[]),
1248            Err(ScenePathError::EmptyPath)
1249        );
1250        let root = scene.create("root", Transform::default(), None).unwrap();
1251        let max_name = "é".repeat(MAX_NAME / 2);
1252        let child = scene
1253            .create(&max_name, Transform::default(), Some(root))
1254            .unwrap();
1255        assert_eq!(scene.resolve_path(Some(root), &[&max_name]), Ok(child));
1256        let long_name = format!("{max_name}x");
1257        assert_eq!(
1258            scene.resolve_path(None, &["missing", &long_name]),
1259            Err(ScenePathError::NameTooLong { component: 1 })
1260        );
1261        scene.create("root", Transform::default(), None).unwrap();
1262        assert_eq!(
1263            scene.resolve_path(None, &["root", &long_name]),
1264            Err(ScenePathError::NameTooLong { component: 1 })
1265        );
1266        let too_deep = vec![""; MAX_NODES + 1];
1267        assert_eq!(
1268            scene.resolve_path(None, &too_deep),
1269            Err(ScenePathError::TooDeep)
1270        );
1271        assert_eq!(
1272            scene.resolve_path(Some(root), &too_deep),
1273            Err(ScenePathError::TooDeep)
1274        );
1275        assert!(matches!(
1276            scene.resolve_path(None, &too_deep[..MAX_NODES]),
1277            Err(ScenePathError::NotFound { component: 0, .. })
1278        ));
1279        scene.remove_subtree(root).unwrap();
1280        for components in [&[][..], &[long_name.as_str()], too_deep.as_slice()] {
1281            assert_eq!(
1282                scene.resolve_path(Some(root), components),
1283                Err(ScenePathError::InvalidNode(root))
1284            );
1285        }
1286    }
1287    #[test]
1288    fn paths_reject_stale_handles_even_when_slots_and_names_are_reused() {
1289        let mut scene = Scene::new();
1290        let root = scene.create("root", Transform::default(), None).unwrap();
1291        let child = scene
1292            .create("child", Transform::default(), Some(root))
1293            .unwrap();
1294        scene.remove_subtree(root).unwrap();
1295        let replacement = scene.create("root", Transform::default(), None).unwrap();
1296        let replacement_child = scene
1297            .create("child", Transform::default(), Some(replacement))
1298            .unwrap();
1299        assert_eq!(root.index, replacement.index);
1300        assert_eq!(child.index, replacement_child.index);
1301        assert_ne!(root, replacement);
1302        assert_ne!(child, replacement_child);
1303        for stale in [root, child] {
1304            assert_eq!(
1305                scene.path_from(None, stale),
1306                Err(ScenePathError::InvalidNode(stale))
1307            );
1308            assert_eq!(
1309                scene.path_from(Some(stale), stale),
1310                Err(ScenePathError::InvalidNode(stale))
1311            );
1312            assert_eq!(
1313                scene.path_from(Some(stale), replacement_child),
1314                Err(ScenePathError::InvalidNode(stale))
1315            );
1316            assert_eq!(
1317                scene.path_from(Some(replacement), stale),
1318                Err(ScenePathError::InvalidNode(stale))
1319            );
1320            assert_eq!(
1321                scene.resolve_path(Some(stale), &["child"]),
1322                Err(ScenePathError::InvalidNode(stale))
1323            );
1324        }
1325        assert_eq!(
1326            scene.resolve_path(None, &["root", "child"]),
1327            Ok(replacement_child)
1328        );
1329    }
1330    #[test]
1331    fn path_inspection_rejects_live_nodes_outside_the_requested_subtree() {
1332        let mut scene = Scene::new();
1333        let root = scene.create("root", Transform::default(), None).unwrap();
1334        let child = scene
1335            .create("child", Transform::default(), Some(root))
1336            .unwrap();
1337        let other = scene.create("other", Transform::default(), None).unwrap();
1338        for (ancestor, node) in [(root, other), (other, child), (child, root)] {
1339            assert_eq!(
1340                scene.path_from(Some(ancestor), node),
1341                Err(ScenePathError::NotDescendant { node, ancestor })
1342            );
1343        }
1344        assert_eq!(scene.path_from(None, child).unwrap(), ["root", "child"]);
1345    }
1346    #[test]
1347    fn paths_follow_successful_batches_and_failed_batches_preserve_identity() {
1348        let mut scene = Scene::new();
1349        let root = scene
1350            .create("root", translated(1.0, 0.0, 0.0), None)
1351            .unwrap();
1352        let child = scene
1353            .create("child", translated(2.0, 0.0, 0.0), Some(root))
1354            .unwrap();
1355        let stale = scene.create("stale", Transform::default(), None).unwrap();
1356        scene.remove_subtree(stale).unwrap();
1357        scene
1358            .set_parents(&[(root, Some(child)), (child, None)])
1359            .unwrap();
1360        assert_eq!(scene.resolve_path(None, &["child", "root"]), Ok(root));
1361        assert_eq!(scene.path_from(None, root).unwrap(), ["child", "root"]);
1362        assert_eq!(scene.node(root).unwrap().local(), translated(1.0, 0.0, 0.0));
1363        let before = scene.encode().unwrap();
1364        let free = scene.free.clone();
1365        for (changes, error) in [
1366            (vec![(root, None), (child, Some(child))], SceneError::Cycle),
1367            (
1368                vec![(root, None), (child, Some(stale)), (child, None)],
1369                SceneError::InvalidNode,
1370            ),
1371        ] {
1372            assert_eq!(scene.set_parents(&changes), Err(error));
1373            assert_eq!(scene.encode().unwrap(), before);
1374            assert_eq!(scene.free, free);
1375            assert_eq!(scene.node(child).unwrap().children(), [root]);
1376            assert_eq!(scene.resolve_path(None, &["child", "root"]), Ok(root));
1377            assert_eq!(scene.path_from(None, root).unwrap(), ["child", "root"]);
1378        }
1379    }
1380    #[test]
1381    fn duplicate_names_remain_legal_in_batches_and_prefabs() {
1382        let mut scene = Scene::new();
1383        let root = scene.create("root", Transform::default(), None).unwrap();
1384        let child = scene
1385            .create("node", Transform::default(), Some(root))
1386            .unwrap();
1387        let other = scene.create("node", Transform::default(), None).unwrap();
1388        scene.set_parents(&[(other, Some(root))]).unwrap();
1389        assert_eq!(scene.node(root).unwrap().children(), [child, other]);
1390        assert!(matches!(
1391            scene.resolve_path(None, &["root", "node"]),
1392            Err(ScenePathError::Ambiguous { component: 1, .. })
1393        ));
1394        scene.set_parents(&[(other, None)]).unwrap();
1395        assert_eq!(scene.resolve_path(None, &["root", "node"]), Ok(child));
1396        let prefab = scene.prefab(root).unwrap();
1397        let copy = scene.instantiate(&prefab, None).unwrap();
1398        assert!(matches!(
1399            scene.path_from(None, child),
1400            Err(ScenePathError::Ambiguous { component: 0, .. })
1401        ));
1402        let copied_child = scene.resolve_path(Some(copy), &["node"]).unwrap();
1403        assert_ne!(child, copied_child);
1404        assert_eq!(scene.path_from(Some(copy), copied_child).unwrap(), ["node"]);
1405        scene.remove_subtree(root).unwrap();
1406        assert_eq!(
1407            scene.resolve_path(None, &["root", "node"]),
1408            Ok(copied_child)
1409        );
1410    }
1411    #[test]
1412    fn paths_remain_compatible_with_the_existing_scene_wire_format() {
1413        let mut scene = Scene::new();
1414        let root = scene.create("父/a", Transform::default(), None).unwrap();
1415        scene.create("", Transform::default(), Some(root)).unwrap();
1416        scene
1417            .create("duplicate", Transform::default(), None)
1418            .unwrap();
1419        scene
1420            .create("duplicate", Transform::default(), None)
1421            .unwrap();
1422        let bytes = scene.encode().unwrap();
1423        assert_eq!(&bytes[..6], b"GSC1\x01\x00");
1424        let decoded = Scene::decode(&bytes).unwrap();
1425        assert_eq!(decoded.encode().unwrap(), bytes);
1426        let id = decoded.resolve_path(None, &["父/a", ""]).unwrap();
1427        assert_eq!(decoded.path_from(None, id).unwrap(), ["父/a", ""]);
1428        assert!(matches!(
1429            decoded.resolve_path(None, &["duplicate"]),
1430            Err(ScenePathError::Ambiguous { component: 0, .. })
1431        ));
1432    }
1433    #[test]
1434    fn deep_paths_are_iterative_and_wide_siblings_are_checked() {
1435        const DEPTH: usize = 20_000;
1436        let mut scene = Scene::new();
1437        let root = scene.create("n", Transform::default(), None).unwrap();
1438        let mut leaf = root;
1439        for _ in 1..DEPTH {
1440            leaf = scene.create("n", Transform::default(), Some(leaf)).unwrap();
1441        }
1442        let path = scene.path_from(None, leaf).unwrap();
1443        assert_eq!(path.len(), DEPTH);
1444        assert_eq!(scene.resolve_path(None, &path), Ok(leaf));
1445        assert_eq!(scene.path_from(Some(root), leaf).unwrap().len(), DEPTH - 1);
1446        let target = scene
1447            .create("target", Transform::default(), Some(leaf))
1448            .unwrap();
1449        for _ in 0..1024 {
1450            scene
1451                .create("other", Transform::default(), Some(leaf))
1452                .unwrap();
1453        }
1454        assert_eq!(scene.resolve_path(Some(leaf), &["target"]), Ok(target));
1455        scene
1456            .create("target", Transform::default(), Some(leaf))
1457            .unwrap();
1458        assert_eq!(
1459            scene.resolve_path(Some(leaf), &["target"]),
1460            Err(ScenePathError::Ambiguous {
1461                component: 0,
1462                parent: Some(leaf)
1463            })
1464        );
1465    }
1466    #[test]
1467    fn path_errors_implement_standard_error_with_actionable_context() {
1468        let id = NodeId {
1469            index: 1,
1470            generation: 2,
1471        };
1472        for (error, expected) in [
1473            (ScenePathError::InvalidNode(id), "stale"),
1474            (ScenePathError::EmptyPath, "at least one"),
1475            (ScenePathError::TooDeep, "100000-component"),
1476            (ScenePathError::NameTooLong { component: 3 }, "4096-byte"),
1477            (
1478                ScenePathError::NotFound {
1479                    component: 3,
1480                    parent: Some(id),
1481                },
1482                "component 3",
1483            ),
1484            (
1485                ScenePathError::Ambiguous {
1486                    component: 3,
1487                    parent: None,
1488                },
1489                "duplicate sibling",
1490            ),
1491            (
1492                ScenePathError::NotDescendant {
1493                    node: id,
1494                    ancestor: id,
1495                },
1496                "not within",
1497            ),
1498        ] {
1499            let standard_error: &dyn std::error::Error = &error;
1500            assert!(standard_error.to_string().contains(expected));
1501        }
1502    }
1503    #[test]
1504    fn batch_reparent_validates_final_graph_and_retains_local_transforms() {
1505        let mut scene = Scene::new();
1506        let carrier = scene
1507            .create("carrier", translated(1.0, 0.0, 0.0), None)
1508            .unwrap();
1509        let payload = scene
1510            .create("payload", translated(2.0, 0.0, 0.0), Some(carrier))
1511            .unwrap();
1512        let leaf = scene
1513            .create("leaf", translated(3.0, 0.0, 0.0), Some(payload))
1514            .unwrap();
1515        assert_eq!(
1516            scene.set_parent(carrier, Some(payload)),
1517            Err(SceneError::Cycle)
1518        );
1519        scene
1520            .set_parents(&[(carrier, Some(payload)), (payload, None)])
1521            .unwrap();
1522        assert_eq!(scene.node(carrier).unwrap().parent(), Some(payload));
1523        assert!(scene.node(carrier).unwrap().children().is_empty());
1524        assert_eq!(scene.node(payload).unwrap().parent(), None);
1525        assert_eq!(scene.node(payload).unwrap().children(), [leaf, carrier]);
1526        assert_eq!(
1527            scene.node(carrier).unwrap().local(),
1528            translated(1.0, 0.0, 0.0)
1529        );
1530        assert_eq!(
1531            scene.node(payload).unwrap().local(),
1532            translated(2.0, 0.0, 0.0)
1533        );
1534        assert_eq!(scene.world_matrix(leaf).unwrap()[12], 5.0);
1535    }
1536    #[test]
1537    fn failed_reparent_edits_leave_links_order_and_allocation_unchanged() {
1538        let mut scene = Scene::new();
1539        let root = scene.create("root", Transform::default(), None).unwrap();
1540        let child = scene
1541            .create("child", Transform::default(), Some(root))
1542            .unwrap();
1543        let leaf = scene
1544            .create("leaf", Transform::default(), Some(child))
1545            .unwrap();
1546        let stale = scene.create("old", Transform::default(), None).unwrap();
1547        scene.remove_subtree(stale).unwrap();
1548        let replacement = scene.create("new", Transform::default(), None).unwrap();
1549        assert_eq!(stale.index, replacement.index);
1550        let before = scene.encode().unwrap();
1551        let free = scene.free.clone();
1552        for (changes, error) in [
1553            (
1554                vec![(child, None), (stale, Some(root))],
1555                SceneError::InvalidNode,
1556            ),
1557            (
1558                vec![(child, None), (leaf, Some(stale))],
1559                SceneError::InvalidNode,
1560            ),
1561            (
1562                vec![(child, Some(stale)), (child, None)],
1563                SceneError::InvalidNode,
1564            ),
1565            (
1566                vec![(replacement, Some(root)), (root, Some(leaf))],
1567                SceneError::Cycle,
1568            ),
1569            (vec![(child, None), (root, Some(root))], SceneError::Cycle),
1570        ] {
1571            assert_eq!(scene.set_parents(&changes), Err(error));
1572            assert_eq!(scene.encode().unwrap(), before);
1573            assert_eq!(scene.node(root).unwrap().children(), [child]);
1574            assert_eq!(scene.node(child).unwrap().children(), [leaf]);
1575            assert_eq!(scene.len(), 4);
1576            assert_eq!(scene.free, free);
1577        }
1578        for (id, parent, error) in [
1579            (child, Some(stale), SceneError::InvalidNode),
1580            (stale, Some(root), SceneError::InvalidNode),
1581            (root, Some(leaf), SceneError::Cycle),
1582        ] {
1583            assert_eq!(scene.set_parent(id, parent), Err(error));
1584            assert_eq!(scene.encode().unwrap(), before);
1585        }
1586    }
1587    #[test]
1588    fn batch_reparent_duplicate_requests_use_final_parent_and_stable_order() {
1589        let mut scene = Scene::new();
1590        let root = scene.create("root", Transform::default(), None).unwrap();
1591        let a = scene.create("a", Transform::default(), Some(root)).unwrap();
1592        let b = scene.create("b", Transform::default(), Some(root)).unwrap();
1593        let c = scene.create("c", Transform::default(), None).unwrap();
1594        let d = scene.create("d", Transform::default(), None).unwrap();
1595        scene
1596            .set_parents(&[
1597                (a, Some(a)), // Overridden before graph validation.
1598                (c, None),
1599                (d, Some(root)),
1600                (a, Some(root)),
1601                (c, Some(root)),
1602            ])
1603            .unwrap();
1604        assert_eq!(scene.node(root).unwrap().children(), [a, b, c, d]);
1605        let before = scene.encode().unwrap();
1606        scene.set_parents(&[]).unwrap();
1607        scene.set_parent(a, Some(root)).unwrap();
1608        assert_eq!(scene.encode().unwrap(), before);
1609        assert_eq!(scene.node(root).unwrap().children(), [a, b, c, d]);
1610    }
1611    #[test]
1612    fn batch_reparent_moves_many_siblings_without_losing_unchanged_links() {
1613        let mut scene = Scene::new();
1614        let from = scene.create("from", Transform::default(), None).unwrap();
1615        let to = scene.create("to", Transform::default(), None).unwrap();
1616        let existing = scene
1617            .create("existing", Transform::default(), Some(to))
1618            .unwrap();
1619        let children: Vec<_> = (0..128)
1620            .map(|_| {
1621                scene
1622                    .create("child", Transform::default(), Some(from))
1623                    .unwrap()
1624            })
1625            .collect();
1626        let changes: Vec<_> = children
1627            .iter()
1628            .enumerate()
1629            .filter_map(|(index, &id)| match index % 3 {
1630                0 => Some((id, Some(to))),
1631                1 => Some((id, None)),
1632                _ => None,
1633            })
1634            .collect();
1635        scene.set_parents(&changes).unwrap();
1636        let kept: Vec<_> = children.iter().copied().skip(2).step_by(3).collect();
1637        let moved: Vec<_> = std::iter::once(existing)
1638            .chain(children.iter().copied().step_by(3))
1639            .collect();
1640        assert_eq!(scene.node(from).unwrap().children(), kept);
1641        assert_eq!(scene.node(to).unwrap().children(), moved);
1642        for (id, parent) in changes {
1643            assert_eq!(scene.node(id).unwrap().parent(), parent);
1644        }
1645        // Successful edits remain consumable by the unchanged binary format.
1646        let bytes = scene.encode().unwrap();
1647        assert_eq!(Scene::decode(&bytes).unwrap().encode().unwrap(), bytes);
1648    }
1649    #[test]
1650    fn prefab_preflight_rejects_bad_entries_without_consuming_handles() {
1651        let mut source = Scene::new();
1652        let root = source.create("root", Transform::default(), None).unwrap();
1653        source
1654            .create("child", Transform::default(), Some(root))
1655            .unwrap();
1656        let prefab = source.prefab(root).unwrap();
1657        let mut invalid = Vec::new();
1658        let mut bad = prefab.clone();
1659        bad.nodes[1].local.translation[0] = f32::NAN;
1660        invalid.push((bad, SceneError::InvalidTransform));
1661        let mut bad = prefab.clone();
1662        bad.nodes[1].name = "x".repeat(MAX_NAME + 1);
1663        invalid.push((bad, SceneError::NameTooLong));
1664        for parent in [None, Some(1), Some(usize::MAX)] {
1665            let mut bad = prefab.clone();
1666            bad.nodes[1].parent = parent;
1667            invalid.push((bad, SceneError::InvalidFormat));
1668        }
1669        let mut bad = prefab.clone();
1670        bad.nodes[0].parent = Some(0);
1671        invalid.push((bad, SceneError::InvalidFormat));
1672        invalid.push((Prefab { nodes: Vec::new() }, SceneError::Capacity));
1673
1674        let mut scene = Scene::new();
1675        let anchor = scene.create("anchor", Transform::default(), None).unwrap();
1676        let stale = scene
1677            .create("old", Transform::default(), Some(anchor))
1678            .unwrap();
1679        scene.remove_subtree(stale).unwrap();
1680        let before = scene.encode().unwrap();
1681        let free = scene.free.clone();
1682        let generations: Vec<_> = scene.slots.iter().map(|slot| slot.generation).collect();
1683        for (prefab, error) in invalid {
1684            assert_eq!(scene.instantiate(&prefab, Some(anchor)), Err(error));
1685            assert_eq!(scene.encode().unwrap(), before);
1686            assert_eq!(scene.free, free);
1687            assert_eq!(scene.len(), 1);
1688            assert_eq!(
1689                scene
1690                    .slots
1691                    .iter()
1692                    .map(|slot| slot.generation)
1693                    .collect::<Vec<_>>(),
1694                generations
1695            );
1696            assert!(scene.node(anchor).unwrap().children().is_empty());
1697        }
1698        assert_eq!(
1699            scene.instantiate(&prefab, Some(stale)),
1700            Err(SceneError::InvalidNode)
1701        );
1702        assert_eq!(scene.encode().unwrap(), before);
1703        let copy = scene.instantiate(&prefab, Some(anchor)).unwrap();
1704        assert_eq!(copy.index, stale.index);
1705        assert_ne!(copy, stale);
1706        assert_eq!(scene.node(anchor).unwrap().children(), [copy]);
1707        assert_eq!(scene.subtree(copy).unwrap().count(), 2);
1708    }
1709    #[test]
1710    fn prefab_capacity_accounts_for_retired_slots_before_insertion() {
1711        let mut scene = Scene::new();
1712        let root = scene.create("root", Transform::default(), None).unwrap();
1713        let single = scene.prefab(root).unwrap();
1714        let mut pair = single.clone();
1715        pair.nodes.push(PrefabNode {
1716            name: "child".into(),
1717            local: Transform::default(),
1718            parent: Some(0),
1719        });
1720        // Model generation-exhausted slots without billions of remove/create calls.
1721        scene.slots.extend((1..MAX_NODES).map(|_| Slot {
1722            generation: u32::MAX,
1723            node: None,
1724        }));
1725        scene.slots[1].generation = 7;
1726        scene.free.push(1);
1727        assert_eq!(
1728            scene.instantiate(&pair, Some(root)),
1729            Err(SceneError::Capacity)
1730        );
1731        assert_eq!(scene.len(), 1);
1732        assert_eq!(scene.free, [1]);
1733        assert!(scene.node(root).unwrap().children().is_empty());
1734        let copy = scene.instantiate(&single, Some(root)).unwrap();
1735        assert_eq!(
1736            copy,
1737            NodeId {
1738                index: 1,
1739                generation: 7
1740            }
1741        );
1742        assert_eq!(scene.len(), 2);
1743    }
1744    #[test]
1745    fn deep_hierarchy_traversal_prefabs_and_reparenting_do_not_recurse() {
1746        const DEPTH: usize = 20_000;
1747        let mut scene = Scene::new();
1748        let root = scene.create("", translated(1.0, 0.0, 0.0), None).unwrap();
1749        let mut leaf = root;
1750        for _ in 1..DEPTH {
1751            leaf = scene
1752                .create("", translated(1.0, 0.0, 0.0), Some(leaf))
1753                .unwrap();
1754        }
1755        assert_eq!(scene.subtree(root).unwrap().count(), DEPTH);
1756        assert_eq!(scene.subtree(root).unwrap().last().unwrap().0, leaf);
1757        assert_eq!(scene.world_matrix(leaf).unwrap()[12], DEPTH as f32);
1758        assert_eq!(
1759            scene.set_parents(&[(root, Some(leaf))]),
1760            Err(SceneError::Cycle)
1761        );
1762        let prefab = scene.prefab(root).unwrap();
1763        let copy = scene.instantiate(&prefab, None).unwrap();
1764        assert_eq!(scene.subtree(copy).unwrap().count(), DEPTH);
1765        assert_eq!(scene.remove_subtree(root).unwrap(), DEPTH);
1766        assert_eq!(scene.subtree(leaf).err(), Some(SceneError::InvalidNode));
1767        let bytes = scene.encode().unwrap();
1768        assert_eq!(Scene::decode(&bytes).unwrap().encode().unwrap(), bytes);
1769        assert_eq!(scene.remove_subtree(copy).unwrap(), DEPTH);
1770        assert!(scene.is_empty());
1771    }
1772    #[test]
1773    fn scene_errors_explain_limits_and_implement_standard_error() {
1774        let error: &dyn std::error::Error = &SceneError::Cycle;
1775        assert!(error.to_string().contains("own ancestor"));
1776        assert!(SceneError::InvalidNode.to_string().contains("stale"));
1777        assert!(SceneError::NameTooLong.to_string().contains("4096-byte"));
1778        assert!(SceneError::Capacity.to_string().contains("100000"));
1779        assert!(
1780            SceneError::InvalidFormat
1781                .to_string()
1782                .contains("GSC1 version 1")
1783        );
1784    }
1785    #[test]
1786    fn scene_binary_roundtrip_and_strict_malformed_rejection() {
1787        let mut scene = Scene::new();
1788        let root = scene.create("父", translated(1.0, 2.0, 3.0), None).unwrap();
1789        scene
1790            .create("child", translated(4.0, 0.0, 0.0), Some(root))
1791            .unwrap();
1792        let bytes = scene.encode().unwrap();
1793        let decoded = Scene::decode(&bytes).unwrap();
1794        assert_eq!(decoded.encode().unwrap(), bytes);
1795        for cut in 0..bytes.len() {
1796            assert!(Scene::decode(&bytes[..cut]).is_err());
1797        }
1798        let mut trailing = bytes.clone();
1799        trailing.push(0);
1800        assert!(Scene::decode(&trailing).is_err());
1801        let mut cycle = bytes.clone();
1802        cycle[10..14].copy_from_slice(&1_u32.to_le_bytes());
1803        assert!(Scene::decode(&cycle).is_err());
1804        let mut oversized = bytes.clone();
1805        oversized[6..10].copy_from_slice(&u32::MAX.to_le_bytes());
1806        assert!(Scene::decode(&oversized).is_err());
1807    }
1808    #[test]
1809    fn skeleton_bind_pose_palette_is_identity_and_animation_moves_child() {
1810        let inverse = translated(-2.0, 0.0, 0.0).matrix().unwrap();
1811        let skeleton = Skeleton::new(vec![
1812            Joint {
1813                parent: None,
1814                inverse_bind: IDENTITY,
1815            },
1816            Joint {
1817                parent: Some(0),
1818                inverse_bind: inverse,
1819            },
1820        ])
1821        .unwrap();
1822        let palette = skeleton
1823            .skin_palette(&[Transform::default(), translated(2.0, 0.0, 0.0)])
1824            .unwrap();
1825        assert_eq!(palette, vec![IDENTITY, IDENTITY]);
1826        let pose = skeleton
1827            .world_pose(&[translated(1.0, 0.0, 0.0), translated(3.0, 0.0, 0.0)])
1828            .unwrap();
1829        assert_eq!(transform_point(pose[1], [0.0; 3]), [4.0, 0.0, 0.0]);
1830        assert!(
1831            Skeleton::new(vec![Joint {
1832                parent: Some(0),
1833                inverse_bind: IDENTITY
1834            }])
1835            .is_err()
1836        );
1837        assert!(skeleton.skin_palette(&[]).is_err());
1838    }
1839}