scena 1.7.2

A Rust-native scene-graph renderer with typed scene state, glTF assets, and explicit prepare/render lifecycles.
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
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
use std::collections::{BTreeMap, BTreeSet};

use serde_json::Value;

use crate::scene::recipe::types::SceneRecipeDiagnosticV1;
use crate::scene::recipe::validation::diagnostic;

use super::super::{finite_vec3, validate_known_fields, validate_required_id};

const MORPH_FIELDS: &[&str] = &["id", "source_geometry", "targets"];
const MORPH_TARGET_FIELDS: &[&str] = &["position_deltas"];
const SKIN_FIELDS: &[&str] = &["id", "source_geometry", "joints", "weights"];

#[derive(Debug, Default)]
pub(in crate::scene::recipe::validation::authoring) struct MorphValidationInfo {
    pub(in crate::scene::recipe::validation::authoring) ids: BTreeSet<String>,
    pub(in crate::scene::recipe::validation::authoring) vertex_counts: BTreeMap<String, usize>,
    pub(in crate::scene::recipe::validation::authoring) target_counts: BTreeMap<String, usize>,
}

#[derive(Debug, Default)]
pub(in crate::scene::recipe::validation::authoring) struct SkinValidationInfo {
    pub(in crate::scene::recipe::validation::authoring) ids: BTreeSet<String>,
    pub(in crate::scene::recipe::validation::authoring) vertex_counts: BTreeMap<String, usize>,
    pub(in crate::scene::recipe::validation::authoring) target_counts: BTreeMap<String, usize>,
    pub(in crate::scene::recipe::validation::authoring) max_joint_indices:
        BTreeMap<String, SkinJointIndexLimit>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(in crate::scene::recipe::validation::authoring) struct SkinJointIndexLimit {
    pub(in crate::scene::recipe::validation::authoring) index: usize,
    pub(in crate::scene::recipe::validation::authoring) path: String,
}

pub(in crate::scene::recipe::validation::authoring) fn geometry_vertex_counts(
    value: Option<&Value>,
) -> BTreeMap<String, usize> {
    value
        .and_then(Value::as_array)
        .into_iter()
        .flatten()
        .filter_map(|geometry| {
            let id = geometry.get("id")?.as_str()?;
            let count = geometry
                .get("mesh")?
                .get("positions")?
                .as_array()
                .map(Vec::len)?;
            Some((id.to_owned(), count))
        })
        .collect()
}

pub(in crate::scene::recipe::validation::authoring) fn validate_morphs(
    value: Option<&Value>,
    source_geometry_ids: &BTreeSet<String>,
    source_vertex_counts: &BTreeMap<String, usize>,
    diagnostics: &mut Vec<SceneRecipeDiagnosticV1>,
) -> MorphValidationInfo {
    let mut info = MorphValidationInfo::default();
    let Some(value) = value else {
        return info;
    };
    let Some(morphs) = value.as_array() else {
        diagnostics.push(diagnostic(
            "invalid_morphs",
            "error",
            "$.morphs",
            "morphs must be an array",
            "emit morphs:[{id,source_geometry,targets}]",
            None,
            false,
        ));
        return info;
    };

    for (index, morph) in morphs.iter().enumerate() {
        let path = format!("$.morphs[{index}]");
        let Some(object) = morph.as_object() else {
            diagnostics.push(diagnostic(
                "invalid_morph",
                "error",
                &path,
                "morph entry must be an object",
                "emit {id,source_geometry,targets}",
                None,
                false,
            ));
            continue;
        };
        validate_known_fields(&path, object, MORPH_FIELDS, diagnostics);
        validate_required_id(&path, object.get("id"), diagnostics);
        let Some(id) = object.get("id").and_then(Value::as_str) else {
            continue;
        };
        info.ids.insert(id.to_owned());
        let source = match validate_source_geometry(
            &format!("{path}.source_geometry"),
            object.get("source_geometry"),
            source_geometry_ids,
            diagnostics,
        ) {
            Some(source) => source,
            None => continue,
        };
        if let Some(count) = source_vertex_counts.get(source) {
            info.vertex_counts.insert(id.to_owned(), *count);
        }
        let target_count = validate_morph_targets(
            &format!("{path}.targets"),
            object.get("targets"),
            source_vertex_counts.get(source).copied(),
            diagnostics,
        );
        if let Some(target_count) = target_count {
            info.target_counts.insert(id.to_owned(), target_count);
        }
    }

    info
}

pub(in crate::scene::recipe::validation::authoring) fn validate_skins(
    value: Option<&Value>,
    source_geometry_ids: &BTreeSet<String>,
    source_vertex_counts: &BTreeMap<String, usize>,
    source_morph_target_counts: &BTreeMap<String, usize>,
    diagnostics: &mut Vec<SceneRecipeDiagnosticV1>,
) -> SkinValidationInfo {
    let mut info = SkinValidationInfo::default();
    let Some(value) = value else {
        return info;
    };
    let Some(skins) = value.as_array() else {
        diagnostics.push(diagnostic(
            "invalid_skins",
            "error",
            "$.skins",
            "skins must be an array",
            "emit skins:[{id,source_geometry,joints,weights}]",
            None,
            false,
        ));
        return info;
    };

    for (index, skin) in skins.iter().enumerate() {
        let path = format!("$.skins[{index}]");
        let Some(object) = skin.as_object() else {
            diagnostics.push(diagnostic(
                "invalid_skin",
                "error",
                &path,
                "skin entry must be an object",
                "emit {id,source_geometry,joints,weights}",
                None,
                false,
            ));
            continue;
        };
        validate_known_fields(&path, object, SKIN_FIELDS, diagnostics);
        validate_required_id(&path, object.get("id"), diagnostics);
        let Some(id) = object.get("id").and_then(Value::as_str) else {
            continue;
        };
        info.ids.insert(id.to_owned());
        let source = match validate_source_geometry(
            &format!("{path}.source_geometry"),
            object.get("source_geometry"),
            source_geometry_ids,
            diagnostics,
        ) {
            Some(source) => source,
            None => continue,
        };
        let source_vertex_count = source_vertex_counts.get(source).copied();
        if let Some(limit) = validate_skin_joints(
            &format!("{path}.joints"),
            object.get("joints"),
            source_vertex_count,
            diagnostics,
        ) {
            info.max_joint_indices.insert(id.to_owned(), limit);
        }
        validate_skin_weights(
            &format!("{path}.weights"),
            object.get("weights"),
            source_vertex_count,
            diagnostics,
        );
        if let Some(count) = source_vertex_count {
            info.vertex_counts.insert(id.to_owned(), count);
        }
        if let Some(target_count) = source_morph_target_counts.get(source) {
            info.target_counts.insert(id.to_owned(), *target_count);
        }
    }

    info
}

fn validate_source_geometry<'a>(
    path: &str,
    value: Option<&'a Value>,
    ids: &BTreeSet<String>,
    diagnostics: &mut Vec<SceneRecipeDiagnosticV1>,
) -> Option<&'a str> {
    match value.and_then(Value::as_str) {
        Some(value) if ids.contains(value) => Some(value),
        Some(value) => {
            diagnostics.push(diagnostic(
                "unknown_geometry_ref",
                "error",
                path,
                format!("geometry reference '{value}' does not name a declared geometry"),
                "declare the source geometry before referencing it",
                None,
                false,
            ));
            None
        }
        None => {
            diagnostics.push(diagnostic(
                "missing_geometry_ref",
                "error",
                path,
                "deformation must include a source_geometry string",
                "set source_geometry to a declared geometry id",
                None,
                false,
            ));
            None
        }
    }
}

fn validate_morph_targets(
    path: &str,
    value: Option<&Value>,
    source_vertex_count: Option<usize>,
    diagnostics: &mut Vec<SceneRecipeDiagnosticV1>,
) -> Option<usize> {
    let Some(targets) = value
        .and_then(Value::as_array)
        .filter(|targets| !targets.is_empty())
    else {
        diagnostics.push(diagnostic(
            "invalid_morph",
            "error",
            path,
            "morph targets must be a non-empty array",
            "emit at least one target with position_deltas",
            None,
            false,
        ));
        return None;
    };
    for (target_index, target) in targets.iter().enumerate() {
        let target_path = format!("{path}[{target_index}]");
        let Some(object) = target.as_object() else {
            diagnostics.push(diagnostic(
                "invalid_morph",
                "error",
                &target_path,
                "morph target must be an object",
                "emit {position_deltas:[[x,y,z],...]}",
                None,
                false,
            ));
            continue;
        };
        validate_known_fields(&target_path, object, MORPH_TARGET_FIELDS, diagnostics);
        let Some(deltas) = object
            .get("position_deltas")
            .and_then(Value::as_array)
            .filter(|deltas| !deltas.is_empty())
        else {
            diagnostics.push(diagnostic(
                "invalid_morph",
                "error",
                format!("{target_path}.position_deltas"),
                "morph target position_deltas must be a non-empty array",
                "emit one [x,y,z] delta per source vertex",
                None,
                false,
            ));
            continue;
        };
        if let Some(expected) = source_vertex_count
            && deltas.len() != expected
        {
            diagnostics.push(diagnostic(
                "invalid_morph",
                "error",
                format!("{target_path}.position_deltas"),
                format!(
                    "morph target has {} position deltas but source geometry has {expected} vertices",
                    deltas.len()
                ),
                "emit exactly one [x,y,z] delta per source vertex",
                None,
                false,
            ));
        }
        for (delta_index, delta) in deltas.iter().enumerate() {
            if finite_vec3(delta).is_none() {
                diagnostics.push(diagnostic(
                    "invalid_morph",
                    "error",
                    format!("{target_path}.position_deltas[{delta_index}]"),
                    "morph delta must be a finite [x,y,z] array",
                    "emit three finite numbers",
                    None,
                    false,
                ));
            }
        }
    }
    Some(targets.len())
}

fn validate_skin_joints(
    path: &str,
    value: Option<&Value>,
    source_vertex_count: Option<usize>,
    diagnostics: &mut Vec<SceneRecipeDiagnosticV1>,
) -> Option<SkinJointIndexLimit> {
    let Some(rows) = value
        .and_then(Value::as_array)
        .filter(|rows| !rows.is_empty())
    else {
        diagnostics.push(diagnostic(
            "invalid_skin",
            "error",
            path,
            "skin joints must be a non-empty array",
            "emit one four-index joint row per source vertex",
            None,
            false,
        ));
        return None;
    };
    if let Some(expected) = source_vertex_count
        && rows.len() != expected
    {
        diagnostics.push(diagnostic(
            "invalid_skin",
            "error",
            path,
            format!(
                "skin declares {} joint rows but source geometry has {expected} vertices",
                rows.len()
            ),
            "emit exactly one four-index joint row per source vertex",
            None,
            false,
        ));
    }
    let mut max_index = None;
    for (row_index, row) in rows.iter().enumerate() {
        let Some(values) = row.as_array() else {
            diagnostics.push(diagnostic(
                "invalid_skin",
                "error",
                format!("{path}[{row_index}]"),
                "skin joint row must be an array of four integers",
                "emit [j0,j1,j2,j3]",
                None,
                false,
            ));
            continue;
        };
        if values.len() != 4 {
            diagnostics.push(diagnostic(
                "invalid_skin",
                "error",
                format!("{path}[{row_index}]"),
                "skin joint row must contain exactly four indices",
                "emit [j0,j1,j2,j3]",
                None,
                false,
            ));
        }
        for (joint_index, value) in values.iter().enumerate() {
            let value_path = format!("{path}[{row_index}][{joint_index}]");
            match value.as_u64().and_then(|raw| usize::try_from(raw).ok()) {
                Some(index) => {
                    if max_index
                        .as_ref()
                        .is_none_or(|max: &SkinJointIndexLimit| index > max.index)
                    {
                        max_index = Some(SkinJointIndexLimit {
                            index,
                            path: value_path,
                        });
                    }
                }
                None => {
                    diagnostics.push(diagnostic(
                        "invalid_skin",
                        "error",
                        value_path,
                        "skin joint index must be a non-negative usize-compatible integer",
                        "emit integer joint indices into the node skin_binding joint list",
                        None,
                        false,
                    ));
                }
            }
        }
    }
    max_index
}

fn validate_skin_weights(
    path: &str,
    value: Option<&Value>,
    source_vertex_count: Option<usize>,
    diagnostics: &mut Vec<SceneRecipeDiagnosticV1>,
) {
    let Some(rows) = value
        .and_then(Value::as_array)
        .filter(|rows| !rows.is_empty())
    else {
        diagnostics.push(diagnostic(
            "invalid_skin",
            "error",
            path,
            "skin weights must be a non-empty array",
            "emit one four-weight row per source vertex",
            None,
            false,
        ));
        return;
    };
    if let Some(expected) = source_vertex_count
        && rows.len() != expected
    {
        diagnostics.push(diagnostic(
            "invalid_skin",
            "error",
            path,
            format!(
                "skin declares {} weight rows but source geometry has {expected} vertices",
                rows.len()
            ),
            "emit exactly one four-weight row per source vertex",
            None,
            false,
        ));
    }
    for (row_index, row) in rows.iter().enumerate() {
        let Some(values) = row.as_array() else {
            diagnostics.push(diagnostic(
                "invalid_skin",
                "error",
                format!("{path}[{row_index}]"),
                "skin weight row must be an array of four numbers",
                "emit [w0,w1,w2,w3]",
                None,
                false,
            ));
            continue;
        };
        if values.len() != 4 {
            diagnostics.push(diagnostic(
                "invalid_skin",
                "error",
                format!("{path}[{row_index}]"),
                "skin weight row must contain exactly four values",
                "emit [w0,w1,w2,w3]",
                None,
                false,
            ));
        }
        let mut any_positive = false;
        for (weight_index, value) in values.iter().enumerate() {
            match value.as_f64() {
                Some(weight) if weight.is_finite() && (0.0..=1.0).contains(&weight) => {
                    any_positive |= weight > 0.0;
                }
                _ => diagnostics.push(diagnostic(
                    "invalid_skin",
                    "error",
                    format!("{path}[{row_index}][{weight_index}]"),
                    "skin weight must be finite and within [0,1]",
                    "emit normalized non-negative weights",
                    None,
                    false,
                )),
            }
        }
        if !any_positive {
            diagnostics.push(diagnostic(
                "invalid_skin",
                "error",
                format!("{path}[{row_index}]"),
                "skin weight row must contain at least one positive influence",
                "assign the vertex to at least one joint",
                None,
                false,
            ));
        }
    }
}