euv-core 0.53.0

Core cross-platform runtime for euv featuring arena-based fine-grained reactivity, deterministic layout, flat scene graph, multi-mode rendering, and direct OS platform adapters.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
use super::*;

/// Default metadata for `BlenderExtrasTags3D`.
impl Default for BlenderExtrasTags3D {
    /// Creates default Blender tags with shadows enabled and no collider or buoyancy.
    ///
    /// # Returns
    ///
    /// - `Self` - Default `BlenderExtrasTags3D`.
    fn default() -> Self {
        Self {
            collider: SceneColliderShape3D::None,
            buoyancy_density: 0.0,
            is_trigger: false,
            cast_shadows: true,
            custom_json: None,
        }
    }
}

/// Default single-root registry for `CollectionRegistry3D`.
impl Default for CollectionRegistry3D {
    /// Creates a registry initialized with the default Blender root collection at bit `0`.
    ///
    /// # Returns
    ///
    /// - `Self` - Initialized `CollectionRegistry3D`.
    fn default() -> Self {
        Self {
            entries: vec![CollectionEntry3D {
                name: SCENE_DEFAULT_COLLECTION_NAME.to_string(),
                bit_index: 0,
                visible_viewport: true,
                visible_render: true,
            }],
            active_mask: 1,
        }
    }
}

/// Collection registration and visibility mask management for `CollectionRegistry3D`.
impl CollectionRegistry3D {
    /// Registers or looks up a Blender collection by `name` and returns its 64-bit mask.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable collection registry.
    /// - `&str` - Blender collection name.
    ///
    /// # Returns
    ///
    /// - `u64` - Single-bit collection mask (`1 << bit_index`), or bit `0` if full.
    pub fn register_collection(&mut self, name: &str) -> u64 {
        for entry in self.get_entries().iter() {
            if entry.get_name() == name {
                return 1u64 << u32::from(entry.get_bit_index());
            }
        }
        let next_idx: usize = self.get_entries().len();
        if next_idx >= SCENE_GRAPH_MAX_COLLECTIONS {
            return 1u64;
        }
        let bit_index: u8 = next_idx as u8;
        let bit_mask: u64 = 1u64 << u32::from(bit_index);
        self.get_mut_entries().push(CollectionEntry3D {
            name: name.to_string(),
            bit_index,
            visible_viewport: true,
            visible_render: true,
        });
        let updated_mask: u64 = self.get_active_mask() | bit_mask;
        self.set_active_mask(updated_mask);
        bit_mask
    }

    /// Sets viewport visibility for the collection matching `name` and refreshes `active_mask`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable collection registry.
    /// - `&str` - Target collection name.
    /// - `bool` - Whether the collection is visible in viewport.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` if a matching collection was updated.
    pub fn set_collection_visible(&mut self, name: &str, visible: bool) -> bool {
        let mut found_bit: Option<u8> = None;
        for entry in self.get_mut_entries().iter_mut() {
            if entry.get_name() == name {
                entry.set_visible_viewport(visible);
                found_bit = Some(entry.get_bit_index());
                break;
            }
        }
        if let Some(bit_index) = found_bit {
            let bit_mask: u64 = 1u64 << u32::from(bit_index);
            let next_mask: u64 = if visible {
                self.get_active_mask() | bit_mask
            } else {
                self.get_active_mask() & !bit_mask
            };
            self.set_active_mask(next_mask);
            true
        } else {
            false
        }
    }

    /// Returns `true` when any collection bit in `node_mask` is currently visible.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Collection registry reference.
    /// - `u64` - Node collection membership bitmask.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when at least one assigned collection is active.
    #[must_use]
    pub fn is_mask_visible(&self, node_mask: u64) -> bool {
        (node_mask & self.get_active_mask()) != 0
    }
}

/// Construction and local matrix helpers for `SceneNode3D`.
impl SceneNode3D {
    /// Creates an identity `SceneNode3D` with `name` and optional `parent`.
    ///
    /// # Arguments
    ///
    /// - `&str` - Node label.
    /// - `Option<u32>` - Optional parent node index.
    ///
    /// # Returns
    ///
    /// - `Self` - Constructed identity scene node.
    #[must_use]
    pub fn from_name(name: &str, parent: Option<u32>) -> Self {
        Self {
            name: name.to_string(),
            parent,
            depth: 0,
            local_translation: Vec3::zero(),
            local_rotation: Quat::identity(),
            local_scale: Vec3::splat(1.0),
            world_matrix: Mat4::identity(),
            prev_world_matrix: Mat4::identity(),
            collection_mask: 1,
            visible: true,
            mesh_id: None,
            skin_id: None,
            camera_id: None,
            light_id: None,
            morph_weight_offset: 0,
            morph_weight_count: 0,
            extras: BlenderExtrasTags3D::default(),
        }
    }

    /// Computes this node's local TRS matrix `T * R * S`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene node reference.
    ///
    /// # Returns
    ///
    /// - `Mat4` - Local transformation matrix.
    #[must_use]
    pub fn local_matrix(&self) -> Mat4 {
        Mat4::from_trs_quat(
            self.get_local_translation(),
            self.get_local_rotation(),
            self.get_local_scale(),
        )
    }
}

/// Default empty hierarchy for `SceneGraph3D`.
impl Default for SceneGraph3D {
    /// Creates an empty `SceneGraph3D` with a default `CollectionRegistry3D`.
    ///
    /// # Returns
    ///
    /// - `Self` - Empty scene graph.
    fn default() -> Self {
        Self {
            nodes: Vec::new(),
            topo_order: Vec::new(),
            dirty_words: Vec::new(),
            morph_weights: Vec::new(),
            collections: CollectionRegistry3D::default(),
            topology_dirty: false,
            revision: 0,
        }
    }
}

/// Hierarchy insertion, dirty bitset management, and zero-allocation propagation for `SceneGraph3D`.
impl SceneGraph3D {
    /// Appends `node` to the graph, marks it dirty, and returns its assigned node index.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable scene graph.
    /// - `SceneNode3D` - Node descriptor to insert.
    ///
    /// # Returns
    ///
    /// - `u32` - Assigned node index inside `nodes`.
    pub fn add_node(&mut self, node: SceneNode3D) -> u32 {
        let node_id: u32 = self.get_nodes().len() as u32;
        self.get_mut_nodes().push(node);
        let needed_words: usize = self.get_nodes().len().div_ceil(64);
        if self.get_dirty_words().len() < needed_words {
            self.get_mut_dirty_words().resize(needed_words, 0);
        }
        self.mark_dirty(node_id);
        self.set_topology_dirty(true);
        node_id
    }

    /// Appends initial shape-key morph weights for `node_id` and records their slice range.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable scene graph.
    /// - `u32` - Target node index.
    /// - `&[f32]` - Initial morph target weights.
    pub fn attach_morph_weights(&mut self, node_id: u32, weights: &[f32]) {
        if weights.is_empty() {
            return;
        }
        let offset: u32 = self.get_morph_weights().len() as u32;
        let count: u16 = weights.len().min(usize::from(u16::MAX)) as u16;
        self.get_mut_morph_weights()
            .extend_from_slice(&weights[..usize::from(count)]);
        if let Some(node) = self.get_mut_nodes().get_mut(node_id as usize) {
            node.set_morph_weight_offset(offset);
            node.set_morph_weight_count(count);
        }
    }

    /// Updates a node's local TRS transform and marks its subtree dirty without allocating.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable scene graph.
    /// - `u32` - Target node index.
    /// - `Vec3` - Local translation.
    /// - `Quat` - Local rotation quaternion.
    /// - `Vec3` - Local non-uniform scale.
    pub fn set_local_trs(&mut self, node_id: u32, translation: Vec3, rotation: Quat, scale: Vec3) {
        if let Some(node) = self.get_mut_nodes().get_mut(node_id as usize) {
            node.set_local_translation(translation);
            node.set_local_rotation(rotation.normalize());
            node.set_local_scale(scale);
            self.mark_dirty(node_id);
        }
    }

    /// Decomposes a local 4x4 matrix into TRS and applies it to `node_id`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable scene graph.
    /// - `u32` - Target node index.
    /// - `Mat4` - Local 4x4 transformation matrix.
    pub fn set_local_matrix(&mut self, node_id: u32, matrix: Mat4) {
        let (translation, rotation, scale): (Vec3, Quat, Vec3) = matrix.decompose_trs();
        self.set_local_trs(node_id, translation, rotation, scale);
    }

    /// Sets the dirty bit for `node_id` in O(1) with zero heap allocations.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable scene graph.
    /// - `u32` - Target node index.
    pub fn mark_dirty(&mut self, node_id: u32) {
        let idx: usize = node_id as usize;
        let word_idx: usize = idx >> 6;
        let bit_mask: u64 = 1u64 << (idx & 63);
        if let Some(word) = self.get_mut_dirty_words().get_mut(word_idx) {
            *word |= bit_mask;
        }
    }

    /// Returns `true` when `node_id` is currently marked dirty.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene graph reference.
    /// - `u32` - Node index.
    ///
    /// # Returns
    ///
    /// - `bool` - Whether the node's world matrix requires recomputation.
    #[must_use]
    pub fn is_dirty(&self, node_id: u32) -> bool {
        let idx: usize = node_id as usize;
        let word_idx: usize = idx >> 6;
        let bit_mask: u64 = 1u64 << (idx & 63);
        self.get_dirty_words()
            .get(word_idx)
            .is_some_and(|word: &u64| (*word & bit_mask) != 0)
    }

    /// Returns the borrowed slice of morph target weights owned by `node_id`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene graph reference.
    /// - `u32` - Target node index.
    ///
    /// # Returns
    ///
    /// - `&[f32]` - Morph weights slice (empty when unattached).
    #[must_use]
    pub fn morph_weights_for_node(&self, node_id: u32) -> &[f32] {
        let Some(node) = self.get_nodes().get(node_id as usize) else {
            return &[];
        };
        let start: usize = node.get_morph_weight_offset() as usize;
        let end: usize = start.saturating_add(usize::from(node.get_morph_weight_count()));
        if end <= self.get_morph_weights().len() {
            &self.get_morph_weights()[start..end]
        } else {
            &[]
        }
    }

    /// Overwrites morph weights for `node_id` in place with zero heap allocations.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable scene graph.
    /// - `u32` - Target node index.
    /// - `&[f32]` - New morph target weights.
    pub fn update_morph_weights(&mut self, node_id: u32, weights: &[f32]) {
        let Some((start, count)) =
            self.get_nodes()
                .get(node_id as usize)
                .map(|node: &SceneNode3D| {
                    (
                        node.get_morph_weight_offset() as usize,
                        usize::from(node.get_morph_weight_count()),
                    )
                })
        else {
            return;
        };
        let copy_len: usize = count.min(weights.len());
        let dst_all: &mut Vec<f32> = self.get_mut_morph_weights();
        if start + copy_len <= dst_all.len() {
            dst_all[start..(start + copy_len)].copy_from_slice(&weights[..copy_len]);
        }
    }

    /// Rebuilds the depth-sorted topological traversal list when nodes were inserted or reparented.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable scene graph.
    pub fn ensure_topology_order(&mut self) {
        if !self.get_topology_dirty() {
            return;
        }
        let (order, depths): (Vec<u32>, Vec<u16>) = compute_scene_topo_order(self.get_nodes());
        for (idx, &depth) in depths.iter().enumerate() {
            if let Some(node) = self.get_mut_nodes().get_mut(idx) {
                node.set_depth(depth);
            }
        }
        self.set_topo_order(order);
        self.set_topology_dirty(false);
    }

    /// Propagates dirty local transforms down the hierarchy in topological order with zero steady-state allocations.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable scene graph.
    ///
    /// # Returns
    ///
    /// - `usize` - Number of node world matrices recomputed during this pass.
    pub fn propagate_world_matrices(&mut self) -> usize {
        self.ensure_topology_order();
        let Self {
            nodes,
            topo_order,
            dirty_words,
            revision,
            ..
        } = self;
        let mut updated: usize = 0;
        for &node_id in topo_order.iter() {
            let idx: usize = node_id as usize;
            let parent_opt: Option<u32> = nodes[idx].try_get_parent();
            let self_word: usize = idx >> 6;
            let self_mask: u64 = 1u64 << (idx & 63);
            let mut needs_update: bool = (dirty_words[self_word] & self_mask) != 0;
            if !needs_update && let Some(parent_id) = parent_opt {
                let p_idx: usize = parent_id as usize;
                if p_idx < nodes.len() {
                    let p_word: usize = p_idx >> 6;
                    let p_mask: u64 = 1u64 << (p_idx & 63);
                    if (dirty_words[p_word] & p_mask) != 0 {
                        dirty_words[self_word] |= self_mask;
                        needs_update = true;
                    }
                }
            }
            if !needs_update {
                continue;
            }
            let local_mat: Mat4 = nodes[idx].local_matrix();
            let world_mat: Mat4 = match parent_opt {
                Some(parent_id) if (parent_id as usize) < nodes.len() => {
                    nodes[parent_id as usize].get_world_matrix().mul(local_mat)
                }
                _ => local_mat,
            };
            let prev: Mat4 = nodes[idx].get_world_matrix();
            nodes[idx].set_prev_world_matrix(prev);
            nodes[idx].set_world_matrix(world_mat);
            updated += 1;
        }
        if updated > 0 {
            dirty_words.fill(0);
            *revision = revision.saturating_add(1);
        }
        updated
    }

    /// Returns `true` when `node_id` and its entire ancestor chain are visible and pass collection masks.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene graph reference.
    /// - `u32` - Target node index.
    ///
    /// # Returns
    ///
    /// - `bool` - Effective scene visibility.
    #[must_use]
    pub fn is_node_effectively_visible(&self, node_id: u32) -> bool {
        let nodes: &[SceneNode3D] = self.get_nodes().as_slice();
        let collections: &CollectionRegistry3D = self.get_collections();
        let mut cursor: Option<u32> = Some(node_id);
        let mut guard: usize = 0;
        while let Some(idx) = cursor {
            let Some(node) = nodes.get(idx as usize) else {
                return false;
            };
            if !node.get_visible() || !collections.is_mask_visible(node.get_collection_mask()) {
                return false;
            }
            cursor = node.try_get_parent();
            guard += 1;
            if guard > nodes.len() {
                break;
            }
        }
        true
    }
}