mecha10-sim 0.7.0

Mecha10 simulation support — scene generation, asset management
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
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
//! Environment config (`environment.json`) parsing and validation.
//!
//! This module is the Rust-side representation of the full `environment.json` document (schema:
//! `packages/mecha10-templates/templates/configs/simulation/schemas/environment-config.schema.json`),
//! most notably the `type: "image"` billboard object introduced for LAB-2025 (porting Godot's
//! config-driven PNG billboard rendering to the MuJoCo simulator).
//!
//! `EnvironmentConfig` now mirrors every field the hand-written schema requires/describes
//! (previously only `id`/`version`/`name`/`description`/`features.objects[]` were modeled here;
//! `scene_path`, `dimensions`, and the rest of `features` were silently unparsed even though the
//! schema already required/described them). This is deliberately option (b) from that
//! tightening pass rather than making this struct `schemars`-derive the schema: the hand-written
//! JSON under `mecha10-templates` stays the schema source of truth (it's what `mecha10 config
//! push`'s validation gate and `cargo run --example export_schemas` both read via
//! `mecha10_schema_registry::environment_config_schema`), and this struct is kept in lockstep
//! with it by hand -- see `config_validation.rs`'s `validate_environment_configs_rejects_*` tests
//! (schema-side) and this module's own tests (struct-side) for the two halves of that guarantee.
//! `rewards` stays `serde_json::Value`: no committed `environment.json` (here or under
//! `mecha10-templates`) has ever populated it, so there's no real shape to type against yet.
//!
//! Scope note (LAB-2025): the actual MJCF generation that turns a `type: "image"` object into a
//! MuJoCo `<texture>`/`<material>`/`<geom type="plane">` triple lives in
//! `mecha10_rl.mujoco.mjcf_generator` (Python), which was extracted out of this repo into the
//! external `mecha-industries/mecha10-rl` repo (LAB-1830) and is not reachable from here. This
//! module only covers what's verifiable in-repo: parsing `environment.json` into typed Rust
//! structs and validating that an image object's fields (in particular, that `source` resolves to
//! a file that actually exists on disk) are well-formed. See
//! the "Simulation: MuJoCo Architecture" Linear doc for the target MJCF mapping contract and the
//! tracked `mecha10-rl` follow-up.

use anyhow::{bail, Result};
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EnvironmentConfig {
    pub id: String,
    pub version: String,
    pub name: String,
    pub description: String,
    pub scene_path: String,
    pub dimensions: EnvironmentDimensions,
    pub features: EnvironmentFeatures,
    #[serde(default)]
    pub rewards: Option<serde_json::Value>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EnvironmentDimensions {
    pub width: f64,
    pub length: f64,
    pub height: f64,
    pub unit: DistanceUnit,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DistanceUnit {
    Meters,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct EnvironmentFeatures {
    #[serde(default)]
    pub floor: Option<FloorFeature>,
    #[serde(default)]
    pub walls: Option<WallsFeature>,
    #[serde(default)]
    pub lighting: Option<LightingFeature>,
    #[serde(default)]
    pub spawn_points: Option<SpawnPointsFeature>,
    #[serde(default)]
    pub obstacles: Option<ObstaclesFeature>,
    #[serde(default)]
    pub objects: Vec<SceneObject>,
    #[serde(default)]
    pub goals: Option<GoalsFeature>,
    #[serde(default)]
    pub npcs: Option<NpcsFeature>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FloorFeature {
    #[serde(rename = "type")]
    pub floor_type: String,
    pub material: String,
    pub friction: f64,
    pub collision: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WallsFeature {
    pub count: u32,
    pub height: f64,
    pub thickness: f64,
    pub material: String,
    pub collision: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LightingFeature {
    pub directional: DirectionalLight,
    pub ambient: AmbientLight,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DirectionalLight {
    pub enabled: bool,
    pub energy: f64,
    pub shadows: bool,
    pub angle: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AmbientLight {
    pub enabled: bool,
    pub color: [f64; 4],
    pub source: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SpawnPointsFeature {
    pub count: u32,
    pub positions: Vec<[f64; 3]>,
    pub default_index: u32,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ObstaclesFeature {
    pub count: u32,
    #[serde(rename = "type")]
    pub obstacle_type: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GoalsFeature {
    pub count: u32,
    #[serde(rename = "type")]
    pub goal_type: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NpcsFeature {
    pub enabled: bool,
    pub count: u32,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum SceneObject {
    Cube(CubeObject),
    Image(ImageObject),
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CubeObject {
    pub position: [f64; 3],
    #[serde(default = "default_scale")]
    pub size: [f64; 3],
    #[serde(default)]
    pub color: Option<[f64; 4]>,
    #[serde(default)]
    pub add_collision: bool,
    #[serde(default)]
    pub material_type: Option<String>,
    #[serde(default)]
    pub roughness: Option<f64>,
    #[serde(default)]
    pub metallic: Option<f64>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ImageObject {
    pub source: String,
    pub position: [f64; 3],
    #[serde(default)]
    pub rotation: [f64; 3],
    #[serde(default = "default_scale")]
    pub scale: [f64; 3],
    #[serde(default)]
    pub interactive: bool,
    #[serde(default = "default_true")]
    pub visible: bool,
    /// Optional back-and-forth patrol motion along one world axis (`find_target_patrol`).
    /// Declares the contract only -- `mecha10-rl` (not this repo) actually advances the
    /// object's position along the line during an episode. Absent for every other bundled
    /// task's image objects, which stay stationary.
    #[serde(default)]
    pub motion: Option<ObjectMotion>,
}

/// Patrol-motion contract for an [`ImageObject`] (schema:
/// `packages/mecha10-templates/templates/configs/simulation/schemas/environment-config.schema.json`'s
/// `imageObject.motion`). Field names/shape are an agreed contract with the external
/// `mecha10-rl` repo, which is what actually moves the object each step -- keep them in
/// lockstep with that schema rather than renaming independently.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ObjectMotion {
    #[serde(rename = "type")]
    pub motion_type: MotionType,
    pub axis: MotionAxis,
    pub range_min: f64,
    pub range_max: f64,
    #[serde(default = "default_motion_speed")]
    pub speed: f64,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum MotionType {
    Patrol,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum MotionAxis {
    X,
    Y,
}

fn default_motion_speed() -> f64 {
    1.0
}

fn default_scale() -> [f64; 3] {
    [1.0, 1.0, 1.0]
}

fn default_true() -> bool {
    true
}

impl EnvironmentConfig {
    /// Load and parse an `environment.json` file from `path`.
    pub fn load(path: &Path) -> Result<Self> {
        super::load_json(path, "environment config")
    }

    /// All `type: "image"` billboard objects declared in this environment.
    pub fn image_objects(&self) -> impl Iterator<Item = &ImageObject> {
        self.features.objects.iter().filter_map(|obj| match obj {
            SceneObject::Image(image) => Some(image),
            SceneObject::Cube(_) => None,
        })
    }
}

impl ImageObject {
    /// Validate this image object, resolving `source` relative to `repo_root` and confirming the
    /// asset file actually exists on disk.
    ///
    /// This is the extent of "generates valid MuJoCo XML" verification achievable from this repo
    /// (LAB-2025): we cannot invoke the external `mecha10_rl.mujoco.mjcf_generator` from here, so
    /// this validates the config contract that generator depends on instead.
    pub fn validate(&self, repo_root: &Path) -> Result<PathBuf> {
        if self.source.trim().is_empty() {
            bail!("image object has an empty `source` path");
        }

        let resolved = repo_root.join(&self.source);
        if !resolved.is_file() {
            bail!(
                "image object `source` does not resolve to a file: {} (resolved: {})",
                self.source,
                resolved.display()
            );
        }

        if self.scale.iter().any(|component| *component <= 0.0) {
            bail!("image object `scale` components must be positive, got {:?}", self.scale);
        }

        Ok(resolved)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn repo_root() -> PathBuf {
        Path::new(env!("CARGO_MANIFEST_DIR"))
            .parent()
            .and_then(Path::parent)
            .expect("repo root")
            .to_path_buf()
    }

    #[test]
    fn parses_cube_object() {
        let json = r#"{
            "type": "cube",
            "position": [1.0, 0.5, 2.0],
            "size": [1.0, 1.0, 1.0],
            "color": [0.8, 0.2, 0.2, 1.0],
            "add_collision": true,
            "material_type": "standard",
            "roughness": 0.8,
            "metallic": 0.0
        }"#;
        let obj: SceneObject = serde_json::from_str(json).unwrap();
        match obj {
            SceneObject::Cube(cube) => {
                assert_eq!(cube.position, [1.0, 0.5, 2.0]);
                assert!(cube.add_collision);
            }
            SceneObject::Image(_) => panic!("expected cube"),
        }
    }

    #[test]
    fn parses_image_object() {
        let json = r#"{
            "type": "image",
            "source": "configs/simulation/images/aiko.jpg",
            "position": [0.0, 0.5, 3.5],
            "rotation": [0, 180, 0],
            "scale": [2.5, 2.5, 2.5],
            "interactive": false,
            "visible": true
        }"#;
        let obj: SceneObject = serde_json::from_str(json).unwrap();
        match obj {
            SceneObject::Image(image) => {
                assert_eq!(image.source, "configs/simulation/images/aiko.jpg");
                assert_eq!(image.position, [0.0, 0.5, 3.5]);
                assert_eq!(image.rotation, [0.0, 180.0, 0.0]);
                assert_eq!(image.scale, [2.5, 2.5, 2.5]);
                assert!(!image.interactive);
                assert!(image.visible);
            }
            SceneObject::Cube(_) => panic!("expected image"),
        }
    }

    #[test]
    fn image_object_defaults() {
        let json = r#"{
            "type": "image",
            "source": "assets/waypoint.png",
            "position": [1.0, 1.0, 1.0]
        }"#;
        let obj: SceneObject = serde_json::from_str(json).unwrap();
        match obj {
            SceneObject::Image(image) => {
                assert_eq!(image.rotation, [0.0, 0.0, 0.0]);
                assert_eq!(image.scale, [1.0, 1.0, 1.0]);
                assert!(!image.interactive);
                assert!(image.visible);
            }
            SceneObject::Cube(_) => panic!("expected image"),
        }
    }

    #[test]
    fn basic_arena_environment_stays_generic_with_no_task_specific_image_objects() {
        let root = repo_root();
        let path = root
            .join("packages/mecha10-templates/templates/configs/simulation/environments/basic_arena/environment.json");
        let config = EnvironmentConfig::load(&path).expect("basic_arena environment.json should parse");

        assert_eq!(config.id, "basic_arena");

        assert!(
            config.image_objects().next().is_none(),
            "basic_arena should declare no image objects - those are task-specific, got: {:?}",
            config.image_objects().map(|i| &i.source).collect::<Vec<_>>()
        );
    }

    #[test]
    fn find_target_task_references_its_cats_preset() {
        let root = repo_root();
        let path = root.join("packages/mecha10-templates/templates/configs/rl/tasks/find_target/task.json");
        let raw = std::fs::read_to_string(&path).expect("find_target/task.json should read");
        let value: serde_json::Value = serde_json::from_str(&raw).expect("find_target/task.json should parse");

        assert_eq!(
            value["preset"], "cats",
            "find_target should reference its 'cats' preset (LAB-3629) rather than authoring objects[] inline"
        );
        assert!(
            value.get("objects").is_none(),
            "find_target/task.json should no longer declare an inline objects[] key"
        );
    }

    #[test]
    fn default_task_references_its_default_preset() {
        let root = repo_root();
        let path = root.join("packages/mecha10-templates/templates/configs/rl/tasks/default/task.json");
        let raw = std::fs::read_to_string(&path).expect("default/task.json should read");
        let value: serde_json::Value = serde_json::from_str(&raw).expect("default/task.json should parse");

        assert_eq!(
            value["env_name"], "basic_arena",
            "default task must declare which environment its 'default' preset resolves against"
        );
        assert_eq!(
            value["preset"], "default",
            "default task should reference its 'default' preset (LAB-3630) rather than authoring objects[] inline"
        );
        assert!(
            value.get("objects").is_none(),
            "default/task.json should not declare an inline objects[] key"
        );
    }

    #[test]
    fn find_target_cats_preset_declares_its_own_image_objects() {
        let root = repo_root();
        let path = root.join(
            "packages/mecha10-templates/templates/configs/simulation/environments/basic_arena/presets/cats/preset.json",
        );
        let raw = std::fs::read_to_string(&path).expect("basic_arena's cats preset.json should read");
        let value: serde_json::Value = serde_json::from_str(&raw).expect("preset.json should parse");
        let objects: Vec<SceneObject> =
            serde_json::from_value(value["objects"].clone()).expect("preset.json objects[] should parse");

        let images: Vec<&ImageObject> = objects
            .iter()
            .filter_map(|obj| match obj {
                SceneObject::Image(image) => Some(image),
                SceneObject::Cube(_) => None,
            })
            .collect();

        let aiko = images
            .iter()
            .find(|image| image.source.ends_with("aiko.jpg"))
            .expect("cats preset should declare an aiko.jpg image object");
        let resolved = aiko.validate(&root).expect("aiko image object should validate");
        assert!(resolved.is_file());
        assert_eq!(aiko.position.len(), 3);
        assert_eq!(aiko.rotation.len(), 3);
        assert_eq!(aiko.scale.len(), 3);

        assert!(
            images.iter().any(|image| image.source.ends_with("phoebe.jpg")),
            "cats preset should also declare a phoebe.jpg image object"
        );
    }

    #[test]
    fn parses_image_object_with_motion_block() {
        let json = r#"{
            "type": "image",
            "source": "configs/simulation/images/aiko.jpg",
            "position": [-3.0, 0.5, 0.0],
            "motion": {
                "type": "patrol",
                "axis": "x",
                "range_min": -8.0,
                "range_max": 8.0,
                "speed": 1.0
            }
        }"#;
        let obj: SceneObject = serde_json::from_str(json).unwrap();
        match obj {
            SceneObject::Image(image) => {
                let motion = image.motion.expect("motion block should round-trip");
                assert_eq!(motion.motion_type, MotionType::Patrol);
                assert_eq!(motion.axis, MotionAxis::X);
                assert_eq!(motion.range_min, -8.0);
                assert_eq!(motion.range_max, 8.0);
                assert_eq!(motion.speed, 1.0);
            }
            SceneObject::Cube(_) => panic!("expected image"),
        }
    }

    #[test]
    fn image_object_motion_defaults_to_none_and_speed_defaults_to_one() {
        let no_motion: SceneObject =
            serde_json::from_str(r#"{"type": "image", "source": "assets/waypoint.png", "position": [1.0, 1.0, 1.0]}"#)
                .unwrap();
        match no_motion {
            SceneObject::Image(image) => assert!(image.motion.is_none()),
            SceneObject::Cube(_) => panic!("expected image"),
        }

        let motion_without_speed: SceneObject = serde_json::from_str(
            r#"{
                "type": "image",
                "source": "assets/waypoint.png",
                "position": [1.0, 1.0, 1.0],
                "motion": {"type": "patrol", "axis": "y", "range_min": -2.0, "range_max": 2.0}
            }"#,
        )
        .unwrap();
        match motion_without_speed {
            SceneObject::Image(image) => {
                let motion = image.motion.expect("motion block should round-trip");
                assert_eq!(motion.axis, MotionAxis::Y);
                assert_eq!(motion.speed, 1.0, "speed should default to 1.0 when omitted");
            }
            SceneObject::Cube(_) => panic!("expected image"),
        }
    }

    #[test]
    fn find_target_patrol_task_references_its_objects_patrol_preset() {
        let root = repo_root();
        let path = root.join("packages/mecha10-templates/templates/configs/rl/tasks/find_target_patrol/task.json");
        let raw = std::fs::read_to_string(&path).expect("find_target_patrol/task.json should read");
        let value: serde_json::Value = serde_json::from_str(&raw).expect("find_target_patrol/task.json should parse");
        assert_eq!(
            value["env_name"], "basic_arena",
            "find_target_patrol must reuse basic_arena"
        );
        assert_eq!(
            value["preset"], "objects_patrol",
            "find_target_patrol should reference its 'objects_patrol' preset (LAB-3629) rather than authoring objects[] inline"
        );
        assert!(
            value.get("objects").is_none(),
            "find_target_patrol/task.json should no longer declare an inline objects[] key"
        );
    }

    #[test]
    fn objects_patrol_preset_declares_patrol_motion_on_its_image_objects() {
        let root = repo_root();
        let path = root.join(
            "packages/mecha10-templates/templates/configs/simulation/environments/basic_arena/presets/objects_patrol/preset.json",
        );
        let raw = std::fs::read_to_string(&path).expect("basic_arena's objects_patrol preset.json should read");
        let value: serde_json::Value = serde_json::from_str(&raw).expect("preset.json should parse");

        let objects: Vec<SceneObject> =
            serde_json::from_value(value["objects"].clone()).expect("preset.json objects[] should parse");

        let images: Vec<&ImageObject> = objects
            .iter()
            .filter_map(|obj| match obj {
                SceneObject::Image(image) => Some(image),
                SceneObject::Cube(_) => None,
            })
            .collect();

        assert!(!images.is_empty(), "find_target_patrol should declare image objects");

        // `source` is relative to a *project* root, not this repo's root - the bundled
        // template directory under `mecha10-templates` is what actually ships every image
        // these tasks reference (the repo root's own `configs/simulation/images/` is a
        // trimmed-down dev sample that only has `aiko.jpg`/`phoebe.jpg`).
        let templates_root = root.join("packages/mecha10-templates/templates");

        for image in &images {
            let resolved = image
                .validate(&templates_root)
                .expect("patrol image object should validate");
            assert!(resolved.is_file());

            let motion = image
                .motion
                .as_ref()
                .unwrap_or_else(|| panic!("{} should declare a motion block", image.source));
            assert_eq!(motion.motion_type, MotionType::Patrol);
            assert_eq!(motion.axis, MotionAxis::X);
            assert!(
                motion.range_min < motion.range_max,
                "range_min should be less than range_max for {}",
                image.source
            );
            // basic_arena is a 20x20m room with 0.5m-thick walls (half-extent 10, wall
            // half-thickness 0.25) - the patrol range must stay clear of both walls.
            assert!(motion.range_min > -9.75 && motion.range_max < 9.75);
        }
    }

    #[test]
    fn moving_objects_arena_declares_patrolling_image_objects_with_no_static_obstacles() {
        let root = repo_root();
        let path = root.join(
            "packages/mecha10-templates/templates/configs/simulation/environments/moving_objects_arena/environment.json",
        );
        let config = EnvironmentConfig::load(&path).expect("moving_objects_arena environment.json should parse");

        assert_eq!(config.id, "moving_objects_arena");

        let images: Vec<&ImageObject> = config.image_objects().collect();
        assert!(
            images.len() >= 2,
            "moving_objects_arena should declare at least two moving image objects, got {}",
            images.len()
        );

        for image in &images {
            let resolved = image
                .validate(&root)
                .unwrap_or_else(|e| panic!("{} should validate: {e}", image.source));
            assert!(resolved.is_file());

            let motion = image
                .motion
                .as_ref()
                .unwrap_or_else(|| panic!("{} should declare a motion block", image.source));
            assert_eq!(motion.motion_type, MotionType::Patrol);
            assert!(
                motion.range_min < motion.range_max,
                "range_min should be less than range_max for {}",
                image.source
            );
            // 20x20m room with 0.5m-thick walls (half-extent 10, wall half-thickness 0.25) - the
            // patrol range must stay clear of both walls.
            assert!(motion.range_min > -9.75 && motion.range_max < 9.75);
        }

        assert!(
            config
                .features
                .obstacles
                .as_ref()
                .map_or(true, |obstacles| obstacles.count == 0),
            "moving_objects_arena should have no static obstacles cluttering the moving-target test"
        );
    }

    #[test]
    fn validate_rejects_missing_source_file() {
        let root = repo_root();
        let image = ImageObject {
            source: "configs/simulation/images/does_not_exist.jpg".to_string(),
            position: [0.0, 0.0, 0.0],
            rotation: [0.0, 0.0, 0.0],
            scale: [1.0, 1.0, 1.0],
            interactive: false,
            visible: true,
            motion: None,
        };
        let err = image
            .validate(&root)
            .expect_err("missing source file should fail validation");
        assert!(err.to_string().contains("does not resolve to a file"));
    }

    /// Minimal document satisfying every field the hand-written schema marks `required`.
    fn minimal_environment_json() -> serde_json::Value {
        serde_json::json!({
            "id": "basic_arena",
            "version": "1.0.0",
            "name": "Basic Arena",
            "description": "A test arena",
            "scene_path": "res://basic_arena.tscn",
            "dimensions": {"width": 20.0, "length": 20.0, "height": 3.0, "unit": "meters"},
            "features": {}
        })
    }

    #[test]
    fn parses_a_minimal_valid_environment_config() {
        let config: EnvironmentConfig = serde_json::from_value(minimal_environment_json()).unwrap();
        assert_eq!(config.scene_path, "res://basic_arena.tscn");
        assert_eq!(config.dimensions.width, 20.0);
        assert_eq!(config.dimensions.unit, DistanceUnit::Meters);
        assert!(config.features.floor.is_none());
    }

    #[test]
    fn rejects_environment_config_missing_scene_path() {
        let mut value = minimal_environment_json();
        value.as_object_mut().unwrap().remove("scene_path");
        let err = serde_json::from_value::<EnvironmentConfig>(value).unwrap_err();
        assert!(err.to_string().contains("scene_path"), "{err}");
    }

    #[test]
    fn rejects_environment_config_missing_dimensions() {
        let mut value = minimal_environment_json();
        value.as_object_mut().unwrap().remove("dimensions");
        let err = serde_json::from_value::<EnvironmentConfig>(value).unwrap_err();
        assert!(err.to_string().contains("dimensions"), "{err}");
    }

    #[test]
    fn rejects_malformed_floor_feature() {
        let mut value = minimal_environment_json();
        value["features"]["floor"] = serde_json::json!({
            "type": "flat",
            "material": "concrete",
            "friction": 0.8
        });
        let err = serde_json::from_value::<EnvironmentConfig>(value).unwrap_err();
        assert!(err.to_string().contains("collision"), "{err}");
    }

    #[test]
    fn parses_full_basic_arena_environment_including_dimensions_and_features() {
        let root = repo_root();
        let path = root
            .join("packages/mecha10-templates/templates/configs/simulation/environments/basic_arena/environment.json");
        let config = EnvironmentConfig::load(&path).expect("basic_arena environment.json should parse");

        assert_eq!(
            config.scene_path,
            "res://packages/mecha10-templates/templates/configs/simulation/environments/basic_arena/basic_arena.tscn"
        );
        assert_eq!(config.dimensions.unit, DistanceUnit::Meters);

        let floor = config.features.floor.expect("basic_arena should declare a floor");
        assert_eq!(floor.material, "concrete");
        assert!(floor.collision);

        let walls = config.features.walls.expect("basic_arena should declare walls");
        assert_eq!(walls.count, 4);

        let lighting = config.features.lighting.expect("basic_arena should declare lighting");
        assert!(lighting.directional.enabled);
        assert!(lighting.ambient.enabled);

        let spawn_points = config
            .features
            .spawn_points
            .expect("basic_arena should declare spawn points");
        assert_eq!(spawn_points.count, 5);
        assert_eq!(spawn_points.positions.len(), 5);

        let obstacles = config.features.obstacles.expect("basic_arena should declare obstacles");
        assert_eq!(obstacles.obstacle_type, "mixed");

        let goals = config.features.goals.expect("basic_arena should declare goals");
        assert_eq!(goals.count, 0);

        let npcs = config.features.npcs.expect("basic_arena should declare npcs");
        assert!(!npcs.enabled);
    }

    #[test]
    fn home_outdoor_urban_environment_stays_generic_with_no_task_specific_image_objects() {
        let root = repo_root();
        let path = root.join(
            "packages/mecha10-templates/templates/configs/simulation/environments/home_outdoor_urban/environment.json",
        );
        let config = EnvironmentConfig::load(&path).expect("home_outdoor_urban environment.json should parse");

        assert_eq!(config.id, "home_outdoor_urban");

        assert!(
            config.image_objects().next().is_none(),
            "home_outdoor_urban should declare no image objects - those are task-specific, got: {:?}",
            config.image_objects().map(|i| &i.source).collect::<Vec<_>>()
        );
    }

    #[test]
    fn every_bundled_environment_is_structural_only_except_the_tracked_moving_objects_arena_exception() {
        // Environments model ground/walls/lighting/obstacles, not task content - `cat_environment`
        // violated this by baking cat image billboards directly into `environment.json` (LAB-3628)
        // and was deleted for it. This test walks every environment bundled under
        // `templates/configs/simulation/environments` so a future environment can't reintroduce
        // the same mistake without this test catching it.
        //
        // `moving_objects_arena` is a known, tracked exception (see its own
        // `moving_objects_arena_declares_patrolling_image_objects_with_no_static_obstacles` test
        // above and the sibling issue to migrate it off baked-in image objects) - it is
        // deliberately excluded here rather than silently allowed to multiply.
        const TRACKED_EXCEPTIONS: &[&str] = &["moving_objects_arena"];

        let root = repo_root();
        let environments_dir = root.join("packages/mecha10-templates/templates/configs/simulation/environments");

        let mut checked = Vec::new();
        for entry in std::fs::read_dir(&environments_dir).expect("environments dir should be readable") {
            let entry = entry.expect("dir entry should be readable");
            if !entry.file_type().expect("file type should be readable").is_dir() {
                continue;
            }
            let name = entry.file_name().to_string_lossy().into_owned();
            if TRACKED_EXCEPTIONS.contains(&name.as_str()) {
                continue;
            }

            let path = entry.path().join("environment.json");
            let config =
                EnvironmentConfig::load(&path).unwrap_or_else(|e| panic!("{} should parse: {e}", path.display()));
            assert!(
                config.image_objects().next().is_none(),
                "{} should declare no image objects - environments are structural-only, task \
                 content belongs in task.json, got: {:?}",
                name,
                config.image_objects().map(|i| &i.source).collect::<Vec<_>>()
            );
            checked.push(name);
        }

        assert!(
            checked.contains(&"basic_arena".to_string()) && checked.contains(&"home_outdoor_urban".to_string()),
            "expected to have actually checked the known structural-only environments, got: {checked:?}"
        );
    }

    #[test]
    fn parses_full_home_outdoor_urban_environment_including_dimensions_and_features() {
        let root = repo_root();
        let path = root.join(
            "packages/mecha10-templates/templates/configs/simulation/environments/home_outdoor_urban/environment.json",
        );
        let config = EnvironmentConfig::load(&path).expect("home_outdoor_urban environment.json should parse");

        assert_eq!(
            config.scene_path,
            "res://packages/mecha10-templates/templates/configs/simulation/environments/home_outdoor_urban/home_outdoor_urban.tscn"
        );
        assert_eq!(config.dimensions.unit, DistanceUnit::Meters);

        // Bigger than basic_arena (20x20) - this environment needs room for
        // a partitioned home interior *and* a separate outdoor urban street section.
        assert!(config.dimensions.width > 20.0);
        assert!(config.dimensions.length > 0.0);

        let floor = config
            .features
            .floor
            .expect("home_outdoor_urban should declare a floor");
        assert!(floor.collision);

        let walls = config.features.walls.expect("home_outdoor_urban should declare walls");
        assert_eq!(walls.count, 4);

        let lighting = config
            .features
            .lighting
            .expect("home_outdoor_urban should declare lighting");
        assert!(lighting.directional.enabled);
        assert!(lighting.ambient.enabled);

        let spawn_points = config
            .features
            .spawn_points
            .expect("home_outdoor_urban should declare spawn points");
        assert_eq!(spawn_points.count, spawn_points.positions.len() as u32);
        assert!(
            spawn_points.count >= 2,
            "home_outdoor_urban should offer spawn points in both the home and outdoor sections"
        );

        let goals = config.features.goals.expect("home_outdoor_urban should declare goals");
        assert!(
            goals.count > 0,
            "a navigation-focused environment should declare goal zones"
        );

        let npcs = config.features.npcs.expect("home_outdoor_urban should declare npcs");
        assert!(npcs.enabled, "home_outdoor_urban should model dynamic pedestrians");

        // Dense obstacle layout (interior partition walls + furniture + street furniture) is the
        // whole point of this environment - planning/navigation needs more to avoid than the
        // open basic_arena provides.
        assert!(
            config.features.objects.len() >= 10,
            "home_outdoor_urban should be densely furnished for navigation testing, got {} objects",
            config.features.objects.len()
        );
        assert!(
            config
                .features
                .objects
                .iter()
                .all(|obj| matches!(obj, SceneObject::Cube(_))),
            "home_outdoor_urban's structural/furniture objects should all be cubes, not task-specific images"
        );
    }

    #[test]
    fn validate_rejects_zero_scale() {
        let root = repo_root();
        let image = ImageObject {
            source: "configs/simulation/images/aiko.jpg".to_string(),
            position: [0.0, 0.0, 0.0],
            rotation: [0.0, 0.0, 0.0],
            scale: [0.0, 1.0, 1.0],
            interactive: false,
            visible: true,
            motion: None,
        };
        let err = image.validate(&root).expect_err("zero scale should fail validation");
        assert!(err.to_string().contains("scale"));
    }
}