bevy-sensor 0.5.2

Bevy library for capturing multi-view images of 3D OBJ models (YCB dataset) for sensor simulation
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
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
//! bevy-sensor: Multi-view rendering for YCB object dataset
//!
//! This library provides Bevy-based rendering of 3D objects from multiple viewpoints,
//! designed to match TBP (Thousand Brains Project) habitat sensor conventions for
//! use in neocortx sensorimotor learning experiments.
//!
//! # Headless Rendering (NEW)
//!
//! Render directly to memory buffers for use in sensorimotor learning:
//!
//! ```ignore
//! use bevy_sensor::{render_to_buffer, RenderConfig, ViewpointConfig, ObjectRotation};
//! use std::path::Path;
//!
//! let config = RenderConfig::tbp_default(); // 64x64, RGBD
//! let viewpoint = bevy_sensor::generate_viewpoints(&ViewpointConfig::default())[0];
//! let rotation = ObjectRotation::identity();
//!
//! let output = render_to_buffer(
//!     Path::new("/tmp/ycb/003_cracker_box"),
//!     &viewpoint,
//!     &rotation,
//!     &config,
//! )?;
//!
//! // output.rgba: Vec<u8> - RGBA pixels (64*64*4 bytes)
//! // output.depth: Vec<f32> - Depth values (64*64 floats)
//! ```
//!
//! # File-based Capture (Legacy)
//!
//! ```ignore
//! use bevy_sensor::{SensorConfig, ViewpointConfig, ObjectRotation};
//!
//! let config = SensorConfig {
//!     viewpoints: ViewpointConfig::default(),
//!     object_rotations: ObjectRotation::tbp_benchmark_rotations(),
//!     ..Default::default()
//! };
//! ```
//!
//! # YCB Dataset
//!
//! Download YCB models programmatically:
//!
//! ```ignore
//! use bevy_sensor::ycb::{download_models, Subset};
//!
//! // Download representative subset (3 objects)
//! download_models("/tmp/ycb", Subset::Representative).await?;
//! ```

use bevy::prelude::*;
use std::f32::consts::PI;
use std::path::Path;

// Headless rendering implementation
// Full GPU rendering requires a display - see render module for details
mod render;

// Batch rendering API for efficient multi-viewpoint rendering
pub mod batch;

// WebGPU and cross-platform backend support
pub mod backend;

// Model caching system for efficient multi-viewpoint rendering
pub mod cache;

// Test fixtures for pre-rendered images (CI/CD support)
pub mod fixtures;

// Re-export ycbust types for convenience
pub use ycbust::{
    self, DownloadOptions, Subset as YcbSubset, REPRESENTATIVE_OBJECTS, TBP_SIMILAR_OBJECTS,
    TBP_STANDARD_OBJECTS,
};

/// YCB dataset utilities
pub mod ycb {
    pub use ycbust::{
        download_ycb, DownloadOptions, Subset, REPRESENTATIVE_OBJECTS, TBP_SIMILAR_OBJECTS,
        TBP_STANDARD_OBJECTS,
    };

    use std::path::Path;

    /// Download YCB models to the specified directory.
    ///
    /// # Arguments
    /// * `output_dir` - Directory to download models to
    /// * `subset` - Which subset of objects to download
    ///
    /// # Example
    /// ```ignore
    /// use bevy_sensor::ycb::{download_models, Subset};
    ///
    /// download_models("/tmp/ycb", Subset::Representative).await?;
    /// ```
    pub async fn download_models<P: AsRef<Path>>(
        output_dir: P,
        subset: Subset,
    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        download_ycb(subset, output_dir.as_ref(), DownloadOptions::default()).await?;
        Ok(())
    }

    /// Download YCB models with custom options.
    pub async fn download_models_with_options<P: AsRef<Path>>(
        output_dir: P,
        subset: Subset,
        options: DownloadOptions,
    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        download_ycb(subset, output_dir.as_ref(), options).await?;
        Ok(())
    }

    /// Download specific YCB objects by object ID using the standard `google_16k` meshes.
    ///
    /// Thin wrapper over [`ycbust::download_objects`] (added upstream in v0.3.3):
    /// preserves this crate's ergonomic `P: AsRef<Path>` surface while delegating
    /// skip / resume / integrity / parallelism to the upstream implementation.
    pub async fn download_objects<P: AsRef<Path>>(
        output_dir: P,
        object_ids: &[&str],
    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        ycbust::download_objects(object_ids, output_dir.as_ref(), DownloadOptions::default())
            .await?;
        Ok(())
    }

    /// Check if YCB models exist at the given path
    pub fn models_exist<P: AsRef<Path>>(output_dir: P) -> bool {
        ycbust::object_mesh_path(output_dir.as_ref(), "003_cracker_box").exists()
    }

    /// Get the path to a specific YCB object's OBJ file
    pub fn object_mesh_path<P: AsRef<Path>>(output_dir: P, object_id: &str) -> std::path::PathBuf {
        ycbust::object_mesh_path(output_dir.as_ref(), object_id)
    }

    /// Get the path to a specific YCB object's texture file
    pub fn object_texture_path<P: AsRef<Path>>(
        output_dir: P,
        object_id: &str,
    ) -> std::path::PathBuf {
        ycbust::object_texture_path(output_dir.as_ref(), object_id)
    }
}

/// Initialize bevy-sensor rendering backend configuration.
///
/// **IMPORTANT**: Call this function ONCE at the start of your application,
/// before any rendering operations, especially when using bevy-sensor as a library.
///
/// This ensures proper backend selection (WebGPU for WSL2, Vulkan for Linux, etc.)
/// and is critical for GPU rendering on WSL2 environments.
///
/// # Why This Matters
///
/// The WGPU rendering backend caches its backend selection early during initialization.
/// When bevy-sensor is used as a library, environment variables must be set BEFORE
/// any GPU rendering code runs. This function does that automatically.
///
/// # Example
///
/// ```ignore
/// use bevy_sensor;
///
/// fn main() {
///     // Initialize FIRST, before any rendering
///     bevy_sensor::initialize();
///
///     // Now use the rendering API
///     let output = bevy_sensor::render_to_buffer(
///         object_dir, &viewpoint, &rotation, &config
///     )?;
/// }
/// ```
///
/// # Calling Multiple Times
///
/// Safe to call multiple times - subsequent calls are no-ops after the first call.
pub fn initialize() {
    // Use a OnceCell equivalent to ensure this only runs once
    use std::sync::atomic::{AtomicBool, Ordering};
    static INITIALIZED: AtomicBool = AtomicBool::new(false);

    if !INITIALIZED.swap(true, Ordering::SeqCst) {
        // First call - initialize backend
        let config = backend::BackendConfig::new();
        config.apply_env();
    }
}

/// Object rotation in Euler angles (degrees), matching TBP benchmark format.
/// Format: [pitch, yaw, roll] or [x, y, z] rotation.
#[derive(Clone, Debug, PartialEq)]
pub struct ObjectRotation {
    /// Rotation around X-axis (pitch) in degrees
    pub pitch: f64,
    /// Rotation around Y-axis (yaw) in degrees
    pub yaw: f64,
    /// Rotation around Z-axis (roll) in degrees
    pub roll: f64,
}

impl ObjectRotation {
    /// Create a new rotation from Euler angles in degrees
    pub fn new(pitch: f64, yaw: f64, roll: f64) -> Self {
        Self { pitch, yaw, roll }
    }

    /// Create from TBP-style array [pitch, yaw, roll] in degrees
    pub fn from_array(arr: [f64; 3]) -> Self {
        Self {
            pitch: arr[0],
            yaw: arr[1],
            roll: arr[2],
        }
    }

    /// Identity rotation (no rotation)
    pub fn identity() -> Self {
        Self::new(0.0, 0.0, 0.0)
    }

    /// TBP benchmark rotations: [0,0,0], [0,90,0], [0,180,0]
    /// Used in shorter YCB experiments to reduce computational load.
    pub fn tbp_benchmark_rotations() -> Vec<Self> {
        vec![
            Self::from_array([0.0, 0.0, 0.0]),
            Self::from_array([0.0, 90.0, 0.0]),
            Self::from_array([0.0, 180.0, 0.0]),
        ]
    }

    /// TBP 14 known orientations (cube faces and corners)
    /// These are the orientations objects are learned in during training.
    pub fn tbp_known_orientations() -> Vec<Self> {
        vec![
            // 6 cube faces (90° rotations around each axis)
            Self::from_array([0.0, 0.0, 0.0]),   // Front
            Self::from_array([0.0, 90.0, 0.0]),  // Right
            Self::from_array([0.0, 180.0, 0.0]), // Back
            Self::from_array([0.0, 270.0, 0.0]), // Left
            Self::from_array([90.0, 0.0, 0.0]),  // Top
            Self::from_array([-90.0, 0.0, 0.0]), // Bottom
            // 8 cube corners (45° rotations)
            Self::from_array([45.0, 45.0, 0.0]),
            Self::from_array([45.0, 135.0, 0.0]),
            Self::from_array([45.0, 225.0, 0.0]),
            Self::from_array([45.0, 315.0, 0.0]),
            Self::from_array([-45.0, 45.0, 0.0]),
            Self::from_array([-45.0, 135.0, 0.0]),
            Self::from_array([-45.0, 225.0, 0.0]),
            Self::from_array([-45.0, 315.0, 0.0]),
        ]
    }

    /// Convert to Bevy Quat (converts f64 to f32 for Bevy compatibility)
    pub fn to_quat(&self) -> Quat {
        Quat::from_euler(
            EulerRot::XYZ,
            (self.pitch as f32).to_radians(),
            (self.yaw as f32).to_radians(),
            (self.roll as f32).to_radians(),
        )
    }

    /// Convert to Bevy Transform (rotation only, no translation)
    pub fn to_transform(&self) -> Transform {
        Transform::from_rotation(self.to_quat())
    }
}

impl Default for ObjectRotation {
    fn default() -> Self {
        Self::identity()
    }
}

/// Configuration for viewpoint generation matching TBP habitat sensor behavior.
/// Uses spherical coordinates to capture objects from multiple elevations.
#[derive(Clone, Debug)]
pub struct ViewpointConfig {
    /// Distance from camera to object center (meters)
    pub radius: f32,
    /// Number of horizontal positions (yaw angles) around the object
    pub yaw_count: usize,
    /// Elevation angles in degrees (pitch). Positive = above, negative = below.
    pub pitch_angles_deg: Vec<f32>,
}

impl Default for ViewpointConfig {
    fn default() -> Self {
        Self {
            radius: 0.5,
            yaw_count: 8,
            // Three elevations: below (-30°), level (0°), above (+30°)
            // This matches TBP's look_up/look_down capability
            pitch_angles_deg: vec![-30.0, 0.0, 30.0],
        }
    }
}

impl ViewpointConfig {
    /// Total number of viewpoints this config will generate
    pub fn viewpoint_count(&self) -> usize {
        self.yaw_count * self.pitch_angles_deg.len()
    }
}

/// Full sensor configuration for capture sessions
#[derive(Clone, Debug, Resource)]
pub struct SensorConfig {
    /// Viewpoint configuration (camera positions)
    pub viewpoints: ViewpointConfig,
    /// Object rotations to capture (each rotation generates a full viewpoint set)
    pub object_rotations: Vec<ObjectRotation>,
    /// Output directory for captures
    pub output_dir: String,
    /// Filename pattern (use {view} for view index, {rot} for rotation index)
    pub filename_pattern: String,
}

impl Default for SensorConfig {
    fn default() -> Self {
        Self {
            viewpoints: ViewpointConfig::default(),
            object_rotations: vec![ObjectRotation::identity()],
            output_dir: ".".to_string(),
            filename_pattern: "capture_{rot}_{view}.png".to_string(),
        }
    }
}

impl SensorConfig {
    /// Create config for TBP benchmark comparison (3 rotations × 24 viewpoints = 72 captures)
    pub fn tbp_benchmark() -> Self {
        Self {
            viewpoints: ViewpointConfig::default(),
            object_rotations: ObjectRotation::tbp_benchmark_rotations(),
            output_dir: ".".to_string(),
            filename_pattern: "capture_{rot}_{view}.png".to_string(),
        }
    }

    /// Create config for full TBP training (14 rotations × 24 viewpoints = 336 captures)
    pub fn tbp_full_training() -> Self {
        Self {
            viewpoints: ViewpointConfig::default(),
            object_rotations: ObjectRotation::tbp_known_orientations(),
            output_dir: ".".to_string(),
            filename_pattern: "capture_{rot}_{view}.png".to_string(),
        }
    }

    /// Total number of captures this config will generate
    pub fn total_captures(&self) -> usize {
        self.viewpoints.viewpoint_count() * self.object_rotations.len()
    }
}

/// Generate camera viewpoints using spherical coordinates.
///
/// Spherical coordinate system (matching TBP habitat sensor conventions):
/// - Yaw: horizontal rotation around Y-axis (0° to 360°)
/// - Pitch: elevation angle from horizontal plane (-90° to +90°)
/// - Radius: distance from origin (object center)
pub fn generate_viewpoints(config: &ViewpointConfig) -> Vec<Transform> {
    let mut views = Vec::with_capacity(config.viewpoint_count());

    for pitch_deg in &config.pitch_angles_deg {
        let pitch = pitch_deg.to_radians();

        for i in 0..config.yaw_count {
            let yaw = (i as f32) * 2.0 * PI / (config.yaw_count as f32);

            // Spherical to Cartesian conversion (Y-up coordinate system)
            // x = r * cos(pitch) * sin(yaw)
            // y = r * sin(pitch)
            // z = r * cos(pitch) * cos(yaw)
            let x = config.radius * pitch.cos() * yaw.sin();
            let y = config.radius * pitch.sin();
            let z = config.radius * pitch.cos() * yaw.cos();

            let transform = Transform::from_xyz(x, y, z).looking_at(Vec3::ZERO, Vec3::Y);
            views.push(transform);
        }
    }
    views
}

/// Marker component for the target object being captured
#[derive(Component)]
pub struct CaptureTarget;

/// Marker component for the capture camera
#[derive(Component)]
pub struct CaptureCamera;

// ============================================================================
// Headless Rendering API (NEW)
// ============================================================================

/// Configuration for headless rendering.
///
/// Matches TBP habitat sensor defaults: 64x64 resolution with RGBD output.
#[derive(Clone, Debug, PartialEq)]
pub struct RenderConfig {
    /// Image width in pixels (default: 64)
    pub width: u32,
    /// Image height in pixels (default: 64)
    pub height: u32,
    /// Zoom factor affecting field of view (default: 1.0)
    /// Use >1 to zoom in (narrower FOV), <1 to zoom out (wider FOV)
    pub zoom: f32,
    /// Near clipping plane in meters (default: 0.01)
    pub near_plane: f32,
    /// Far clipping plane in meters (default: 10.0)
    pub far_plane: f32,
    /// Lighting configuration
    pub lighting: LightingConfig,
}

/// Lighting configuration for rendering.
///
/// Controls ambient light and point lights in the scene.
#[derive(Clone, Debug, PartialEq)]
pub struct LightingConfig {
    /// Ambient light brightness (0.0 - 1.0, default: 0.3)
    pub ambient_brightness: f32,
    /// Key light intensity in lumens (default: 1500.0)
    pub key_light_intensity: f32,
    /// Key light position [x, y, z] (default: [4.0, 8.0, 4.0])
    pub key_light_position: [f32; 3],
    /// Fill light intensity in lumens (default: 500.0)
    pub fill_light_intensity: f32,
    /// Fill light position [x, y, z] (default: [-4.0, 2.0, -4.0])
    pub fill_light_position: [f32; 3],
    /// Enable shadows (default: false for performance)
    pub shadows_enabled: bool,
}

impl Default for LightingConfig {
    fn default() -> Self {
        Self {
            ambient_brightness: 0.3,
            key_light_intensity: 1500.0,
            key_light_position: [4.0, 8.0, 4.0],
            fill_light_intensity: 500.0,
            fill_light_position: [-4.0, 2.0, -4.0],
            shadows_enabled: false,
        }
    }
}

impl LightingConfig {
    /// Bright lighting for clear visibility
    pub fn bright() -> Self {
        Self {
            ambient_brightness: 0.5,
            key_light_intensity: 2000.0,
            key_light_position: [4.0, 8.0, 4.0],
            fill_light_intensity: 800.0,
            fill_light_position: [-4.0, 2.0, -4.0],
            shadows_enabled: false,
        }
    }

    /// Soft lighting with minimal shadows
    pub fn soft() -> Self {
        Self {
            ambient_brightness: 0.4,
            key_light_intensity: 1000.0,
            key_light_position: [3.0, 6.0, 3.0],
            fill_light_intensity: 600.0,
            fill_light_position: [-3.0, 3.0, -3.0],
            shadows_enabled: false,
        }
    }

    /// Unlit mode - ambient only, no point lights
    pub fn unlit() -> Self {
        Self {
            ambient_brightness: 1.0,
            key_light_intensity: 0.0,
            key_light_position: [0.0, 0.0, 0.0],
            fill_light_intensity: 0.0,
            fill_light_position: [0.0, 0.0, 0.0],
            shadows_enabled: false,
        }
    }
}

impl Default for RenderConfig {
    fn default() -> Self {
        Self::tbp_default()
    }
}

impl RenderConfig {
    /// TBP-compatible 64x64 RGBD patch sensor configuration.
    ///
    /// Matches TBP's habitat distant patch sensor: 64x64 resolution with
    /// zoom=10 (90° base HFOV → ~9° effective FOV), producing a tight view
    /// of the object's surface patch.
    ///
    /// TBP ref: `missing_depthto3d_sensor2_semantic0.yaml` (zoom=10)
    pub fn tbp_default() -> Self {
        Self {
            width: 64,
            height: 64,
            zoom: 4.0,
            near_plane: 0.01,
            far_plane: 10.0,
            lighting: LightingConfig::default(),
        }
    }

    /// Higher resolution configuration for debugging and visualization.
    pub fn preview() -> Self {
        Self {
            width: 256,
            height: 256,
            zoom: 1.0,
            near_plane: 0.01,
            far_plane: 10.0,
            lighting: LightingConfig::default(),
        }
    }

    /// High resolution configuration for detailed captures.
    pub fn high_res() -> Self {
        Self {
            width: 512,
            height: 512,
            zoom: 1.0,
            near_plane: 0.01,
            far_plane: 10.0,
            lighting: LightingConfig::default(),
        }
    }

    /// Calculate vertical field of view in radians based on zoom.
    ///
    /// TBP zooms by dividing the focal length, not the angle:
    ///   `fx_norm = tan(hfov/2) / zoom`
    /// This is equivalent to `fov = 2 * atan(tan(hfov/2) / zoom)`.
    /// With hfov=90° and zoom=10, effective FOV ≈ 11.4° (not 9°).
    pub fn fov_radians(&self) -> f32 {
        let base_hfov_rad = 90.0_f32.to_radians();
        let half_tan = (base_hfov_rad / 2.0).tan() / self.zoom;
        2.0 * half_tan.atan()
    }

    /// Compute camera intrinsics for use with neocortx.
    ///
    /// Returns focal length and principal point based on resolution and FOV.
    /// Matches TBP Python: `fx = tan(hfov/2) / zoom` in normalized [-1,1] space,
    /// converted to pixel space: `fx_pixel = (width/2) / fx_normalized`.
    ///
    /// TBP ref: `transforms.py:440` `fx = np.tan(hfov[i] / 2.0) / zoom`
    pub fn intrinsics(&self) -> CameraIntrinsics {
        let base_hfov_rad = 90.0_f64.to_radians();
        // TBP normalized focal length: fx_norm = tan(hfov/2) / zoom
        let fx_norm = (base_hfov_rad / 2.0).tan() / self.zoom as f64;
        // Convert to pixel focal length: fx_pixel = (width/2) / fx_norm
        let fx = (self.width as f64 / 2.0) / fx_norm;
        let fy = fx; // Square pixels (TBP adjusts fy for aspect ratio, but we use 64x64)

        CameraIntrinsics {
            focal_length: [fx, fy],
            principal_point: [self.width as f64 / 2.0, self.height as f64 / 2.0],
            image_size: [self.width, self.height],
        }
    }
}

/// Camera intrinsic parameters for 3D reconstruction.
///
/// Compatible with neocortx's VisionIntrinsics format.
/// Uses f64 for TBP numerical precision compatibility.
#[derive(Clone, Debug, PartialEq)]
pub struct CameraIntrinsics {
    /// Focal length in pixels (fx, fy)
    pub focal_length: [f64; 2],
    /// Principal point (cx, cy) - typically image center
    pub principal_point: [f64; 2],
    /// Image dimensions (width, height)
    pub image_size: [u32; 2],
}

impl CameraIntrinsics {
    /// Project a 3D point to 2D pixel coordinates.
    pub fn project(&self, point: Vec3) -> Option<[f64; 2]> {
        if point.z <= 0.0 {
            return None;
        }
        let x = (point.x as f64 / point.z as f64) * self.focal_length[0] + self.principal_point[0];
        let y = (point.y as f64 / point.z as f64) * self.focal_length[1] + self.principal_point[1];
        Some([x, y])
    }

    /// Unproject a 2D pixel to a 3D point at given depth.
    pub fn unproject(&self, pixel: [f64; 2], depth: f64) -> [f64; 3] {
        let x = (pixel[0] - self.principal_point[0]) / self.focal_length[0] * depth;
        let y = (pixel[1] - self.principal_point[1]) / self.focal_length[1] * depth;
        [x, y, depth]
    }
}

/// Output from headless rendering containing RGBA and depth data.
#[derive(Clone, Debug)]
pub struct RenderOutput {
    /// RGBA pixel data in row-major order (width * height * 4 bytes)
    pub rgba: Vec<u8>,
    /// Depth values in meters, row-major order (width * height f64s)
    /// Values are linear depth from camera, not normalized.
    /// Uses f64 for TBP numerical precision compatibility.
    pub depth: Vec<f64>,
    /// Image width in pixels
    pub width: u32,
    /// Image height in pixels
    pub height: u32,
    /// Camera intrinsics used for this render
    pub intrinsics: CameraIntrinsics,
    /// Camera transform (world position and orientation)
    pub camera_transform: Transform,
    /// Object rotation applied during render
    pub object_rotation: ObjectRotation,
}

impl RenderOutput {
    /// Get RGBA pixel at (x, y). Returns None if out of bounds.
    pub fn get_rgba(&self, x: u32, y: u32) -> Option<[u8; 4]> {
        if x >= self.width || y >= self.height {
            return None;
        }
        let idx = ((y * self.width + x) * 4) as usize;
        Some([
            self.rgba[idx],
            self.rgba[idx + 1],
            self.rgba[idx + 2],
            self.rgba[idx + 3],
        ])
    }

    /// Get depth value at (x, y) in meters. Returns None if out of bounds.
    pub fn get_depth(&self, x: u32, y: u32) -> Option<f64> {
        if x >= self.width || y >= self.height {
            return None;
        }
        let idx = (y * self.width + x) as usize;
        Some(self.depth[idx])
    }

    /// Get RGB pixel (without alpha) at (x, y).
    pub fn get_rgb(&self, x: u32, y: u32) -> Option<[u8; 3]> {
        self.get_rgba(x, y).map(|rgba| [rgba[0], rgba[1], rgba[2]])
    }

    /// Convert to neocortx-compatible image format: Vec<Vec<[u8; 3]>>
    pub fn to_rgb_image(&self) -> Vec<Vec<[u8; 3]>> {
        let mut image = Vec::with_capacity(self.height as usize);
        for y in 0..self.height {
            let mut row = Vec::with_capacity(self.width as usize);
            for x in 0..self.width {
                row.push(self.get_rgb(x, y).unwrap_or([0, 0, 0]));
            }
            image.push(row);
        }
        image
    }

    /// Convert depth to neocortx-compatible format: Vec<Vec<f64>>
    pub fn to_depth_image(&self) -> Vec<Vec<f64>> {
        let mut image = Vec::with_capacity(self.height as usize);
        for y in 0..self.height {
            let mut row = Vec::with_capacity(self.width as usize);
            for x in 0..self.width {
                row.push(self.get_depth(x, y).unwrap_or(0.0));
            }
            image.push(row);
        }
        image
    }
}

/// Errors that can occur during rendering and file operations.
#[derive(Debug, Clone)]
pub enum RenderError {
    /// Object mesh file not found
    MeshNotFound(String),
    /// Object texture file not found
    TextureNotFound(String),
    /// Generic file not found error
    FileNotFound { path: String, reason: String },
    /// File write failed
    FileWriteFailed { path: String, reason: String },
    /// Directory creation failed
    DirectoryCreationFailed { path: String, reason: String },
    /// Bevy rendering failed
    RenderFailed(String),
    /// Invalid configuration
    InvalidConfig(String),
    /// Invalid input parameters
    InvalidInput(String),
    /// JSON serialization/deserialization error
    SerializationError(String),
    /// Binary data parsing error
    DataParsingError(String),
    /// Render timeout
    RenderTimeout { duration_secs: u64 },
}

impl std::fmt::Display for RenderError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            RenderError::MeshNotFound(path) => write!(f, "Mesh not found: {}", path),
            RenderError::TextureNotFound(path) => write!(f, "Texture not found: {}", path),
            RenderError::FileNotFound { path, reason } => {
                write!(f, "File not found at {}: {}", path, reason)
            }
            RenderError::FileWriteFailed { path, reason } => {
                write!(f, "Failed to write file {}: {}", path, reason)
            }
            RenderError::DirectoryCreationFailed { path, reason } => {
                write!(f, "Failed to create directory {}: {}", path, reason)
            }
            RenderError::RenderFailed(msg) => write!(f, "Render failed: {}", msg),
            RenderError::InvalidConfig(msg) => write!(f, "Invalid config: {}", msg),
            RenderError::InvalidInput(msg) => write!(f, "Invalid input: {}", msg),
            RenderError::SerializationError(msg) => write!(f, "Serialization error: {}", msg),
            RenderError::DataParsingError(msg) => write!(f, "Data parsing error: {}", msg),
            RenderError::RenderTimeout { duration_secs } => {
                write!(f, "Render timeout after {} seconds", duration_secs)
            }
        }
    }
}

impl std::error::Error for RenderError {}

/// Render a YCB object to an in-memory buffer.
///
/// This is the primary API for headless rendering. It spawns a minimal Bevy app,
/// renders a single frame, extracts the RGBA and depth data, and shuts down.
///
/// # Arguments
/// * `object_dir` - Path to YCB object directory (e.g., "/tmp/ycb/003_cracker_box")
/// * `camera_transform` - Camera position and orientation (use `generate_viewpoints`)
/// * `object_rotation` - Rotation to apply to the object
/// * `config` - Render configuration (resolution, depth range, etc.)
///
/// # Example
/// ```ignore
/// use bevy_sensor::{render_to_buffer, RenderConfig, ViewpointConfig, ObjectRotation};
/// use std::path::Path;
///
/// let viewpoints = bevy_sensor::generate_viewpoints(&ViewpointConfig::default());
/// let output = render_to_buffer(
///     Path::new("/tmp/ycb/003_cracker_box"),
///     &viewpoints[0],
///     &ObjectRotation::identity(),
///     &RenderConfig::tbp_default(),
/// )?;
/// ```
pub fn render_to_buffer(
    object_dir: &Path,
    camera_transform: &Transform,
    object_rotation: &ObjectRotation,
    config: &RenderConfig,
) -> Result<RenderOutput, RenderError> {
    // Use the actual Bevy headless renderer
    render::render_headless(object_dir, camera_transform, object_rotation, config)
}

/// Render all viewpoints and rotations for a YCB object.
///
/// Convenience function that renders all combinations of viewpoints and rotations.
///
/// # Arguments
/// * `object_dir` - Path to YCB object directory
/// * `viewpoint_config` - Viewpoint configuration (camera positions)
/// * `rotations` - Object rotations to render
/// * `render_config` - Render configuration
///
/// # Returns
/// Vector of RenderOutput, one per viewpoint × rotation combination.
pub fn render_all_viewpoints(
    object_dir: &Path,
    viewpoint_config: &ViewpointConfig,
    rotations: &[ObjectRotation],
    render_config: &RenderConfig,
) -> Result<Vec<RenderOutput>, RenderError> {
    let viewpoints = generate_viewpoints(viewpoint_config);
    let mut outputs = Vec::with_capacity(viewpoints.len() * rotations.len());

    for rotation in rotations {
        for viewpoint in &viewpoints {
            let output = render_to_buffer(object_dir, viewpoint, rotation, render_config)?;
            outputs.push(output);
        }
    }

    Ok(outputs)
}

/// Render with model caching support for efficient multi-viewpoint rendering.
///
/// This function tracks which models have been loaded and provides performance
/// insights. It still spins up a fresh headless `App` per call. For workloads
/// that render many frames against the same object/config, prefer
/// `RenderSession` (homogeneous batches per episode) or `PersistentRenderer`
/// (one frame per call, scene held loaded across calls — built for surface-
/// policy feedback loops).
///
/// # Arguments
/// * `object_dir` - Path to YCB object directory
/// * `camera_transform` - Camera position and orientation
/// * `object_rotation` - Rotation to apply to the object
/// * `config` - Render configuration
/// * `cache` - Model cache to track loaded assets
///
/// # Returns
/// RenderOutput with rendered RGBA and depth data
///
/// # Example
/// ```ignore
/// use bevy_sensor::{render_to_buffer_cached, cache::ModelCache, RenderConfig, ObjectRotation};
/// use std::path::PathBuf;
///
/// let mut cache = ModelCache::new();
/// let object_dir = PathBuf::from("/tmp/ycb/003_cracker_box");
/// let config = RenderConfig::tbp_default();
/// let viewpoints = bevy_sensor::generate_viewpoints(&ViewpointConfig::default());
///
/// // First render: loads from disk and caches
/// let output1 = render_to_buffer_cached(
///     &object_dir,
///     &viewpoints[0],
///     &ObjectRotation::identity(),
///     &config,
///     &mut cache,
/// )?;
///
/// // Subsequent renders: tracks in cache
/// for viewpoint in &viewpoints[1..] {
///     let output = render_to_buffer_cached(
///         &object_dir,
///         viewpoint,
///         &ObjectRotation::identity(),
///         &config,
///         &mut cache,
///     )?;
/// }
/// ```
///
/// # Note
/// This function uses the same rendering engine as `render_to_buffer()`. The current
/// batch API preserves ordering and output structure but does not yet reuse a live
/// Bevy renderer across calls.
///
/// ```ignore
/// use bevy_sensor::{render_batch, batch::BatchRenderRequest, BatchRenderConfig, RenderConfig, ObjectRotation};
///
/// let requests: Vec<_> = viewpoints.iter().map(|vp| {
///     BatchRenderRequest {
///         object_dir: object_dir.clone(),
///         viewpoint: *vp,
///         object_rotation: ObjectRotation::identity(),
///         render_config: RenderConfig::tbp_default(),
///     }
/// }).collect();
///
/// let outputs = render_batch(requests, &BatchRenderConfig::default())?;
/// ```
pub fn render_to_buffer_cached(
    object_dir: &Path,
    camera_transform: &Transform,
    object_rotation: &ObjectRotation,
    config: &RenderConfig,
    cache: &mut cache::ModelCache,
) -> Result<RenderOutput, RenderError> {
    let mesh_path = object_dir.join("google_16k/textured.obj");
    let texture_path = object_dir.join("google_16k/texture_map.png");

    // Track in cache
    cache.cache_scene(mesh_path.clone());
    cache.cache_texture(texture_path.clone());

    // Render using standard pipeline
    render::render_headless(object_dir, camera_transform, object_rotation, config)
}

/// Render directly to files (for subprocess mode).
///
/// This function is designed for subprocess rendering where the process will exit
/// after rendering. It saves RGBA and depth data directly to the specified files
/// before the process terminates.
///
/// # Arguments
/// * `object_dir` - Path to YCB object directory
/// * `camera_transform` - Camera position and orientation
/// * `object_rotation` - Rotation to apply to the object
/// * `config` - Render configuration
/// * `rgba_path` - Output path for RGBA PNG
/// * `depth_path` - Output path for depth data (raw f32 bytes)
///
/// # Note
/// This function may call `std::process::exit(0)` and not return.
pub fn render_to_files(
    object_dir: &Path,
    camera_transform: &Transform,
    object_rotation: &ObjectRotation,
    config: &RenderConfig,
    rgba_path: &Path,
    depth_path: &Path,
) -> Result<(), RenderError> {
    render::render_to_files(
        object_dir,
        camera_transform,
        object_rotation,
        config,
        rgba_path,
        depth_path,
    )
}

// Re-export batch types for convenient API access
pub use batch::{
    BatchRenderConfig, BatchRenderError, BatchRenderOutput, BatchRenderRequest, BatchRenderer,
    BatchState, RenderStatus,
};

/// Persistent batch render session. See the module docs in `render::RenderSession`
/// for lifetime, thread-affinity, and config-invariance guarantees.
pub use render::RenderSession;

/// Per-step persistent renderer for feedback loops. See the module docs in
/// `render::PersistentRenderer` for lifetime, thread-affinity, and
/// object/config-invariance guarantees. Built for the surface-policy use case
/// in neocortx where a fixed object is rendered from a moving camera many
/// times per episode (issue #65).
pub use render::PersistentRenderer;

/// Create a new batch renderer helper for multi-viewpoint workflows.
///
/// The current implementation stores queued requests and executes them sequentially via
/// `render_to_buffer()`. It does not yet keep a persistent Bevy app alive across renders.
///
/// # Arguments
/// * `config` - Batch rendering configuration
///
/// # Returns
/// A BatchRenderer instance ready to queue render requests
///
/// # Example
/// ```ignore
/// use bevy_sensor::{create_batch_renderer, queue_render_request, render_next_in_batch, BatchRenderConfig};
///
/// let mut renderer = create_batch_renderer(&BatchRenderConfig::default())?;
/// ```
pub fn create_batch_renderer(config: &BatchRenderConfig) -> Result<BatchRenderer, RenderError> {
    Ok(BatchRenderer::new(config.clone()))
}

/// Queue a render request for batch processing.
///
/// Adds a render request to the batch queue. Requests are processed in order
/// when you call render_next_in_batch().
///
/// # Arguments
/// * `renderer` - The batch renderer instance
/// * `request` - The render request
///
/// # Returns
/// Ok if queued successfully, Err if queue is full
///
/// # Example
/// ```ignore
/// use bevy_sensor::{batch::BatchRenderRequest, RenderConfig, ObjectRotation};
/// use std::path::PathBuf;
///
/// queue_render_request(&mut renderer, BatchRenderRequest {
///     object_dir: PathBuf::from("/tmp/ycb/003_cracker_box"),
///     viewpoint: camera_transform,
///     object_rotation: ObjectRotation::identity(),
///     render_config: RenderConfig::tbp_default(),
/// })?;
/// ```
pub fn queue_render_request(
    renderer: &mut BatchRenderer,
    request: BatchRenderRequest,
) -> Result<(), RenderError> {
    renderer
        .queue_request(request)
        .map_err(|e| RenderError::RenderFailed(e.to_string()))
}

/// Process and execute the next render in the batch queue.
///
/// Executes a single queued request via `render_to_buffer()`. Returns None when the queue
/// is empty. Use this in a loop to process all queued renders in a stable order.
///
/// # Arguments
/// * `renderer` - The batch renderer instance
/// * `timeout_ms` - Timeout in milliseconds for this render
///
/// # Returns
/// Some(output) if a render completed, None if queue is empty
///
/// # Example
/// ```ignore
/// loop {
///     match render_next_in_batch(&mut renderer, 500)? {
///         Some(output) => println!("Render complete: {:?}", output.status),
///         None => break, // All renders done
///     }
/// }
/// ```
pub fn render_next_in_batch(
    renderer: &mut BatchRenderer,
    _timeout_ms: u32,
) -> Result<Option<BatchRenderOutput>, RenderError> {
    if let Some(request) = renderer.pending_requests.pop_front() {
        let output = render_to_buffer(
            &request.object_dir,
            &request.viewpoint,
            &request.object_rotation,
            &request.render_config,
        )?;
        let batch_output = BatchRenderOutput::from_render_output(request, output);
        renderer.completed_results.push(batch_output.clone());
        renderer.renders_processed += 1;
        Ok(Some(batch_output))
    } else {
        Ok(None)
    }
}

/// Render multiple requests in batch (convenience function).
///
/// Queues all requests and executes them in batch, returning all results.
/// Simpler than manage queue + loop for one-off batches.
///
/// # Arguments
/// * `requests` - Vector of render requests
/// * `config` - Batch rendering configuration
///
/// # Returns
/// Vector of BatchRenderOutput results in same order as input
///
/// # Example
/// ```ignore
/// use bevy_sensor::{render_batch, batch::BatchRenderRequest, BatchRenderConfig};
///
/// let results = render_batch(requests, &BatchRenderConfig::default())?;
/// ```
pub fn render_batch(
    requests: Vec<BatchRenderRequest>,
    config: &BatchRenderConfig,
) -> Result<Vec<BatchRenderOutput>, RenderError> {
    if requests.is_empty() {
        return Ok(Vec::new());
    }

    if requests.len() > 1 && requests_share_batch_context(&requests) {
        let first_request = requests[0].clone();
        let viewpoints: Vec<Transform> = requests.iter().map(|request| request.viewpoint).collect();
        let outputs = render::render_headless_sequence(
            &first_request.object_dir,
            &viewpoints,
            &first_request.object_rotation,
            &first_request.render_config,
        )?;

        return Ok(requests
            .into_iter()
            .zip(outputs)
            .map(|(request, output)| BatchRenderOutput::from_render_output(request, output))
            .collect());
    }

    let mut renderer = create_batch_renderer(config)?;

    // Queue all requests
    for request in requests {
        queue_render_request(&mut renderer, request)?;
    }

    // Execute all and collect results
    let mut results = Vec::new();
    while let Some(output) = render_next_in_batch(&mut renderer, config.frame_timeout_ms)? {
        results.push(output);
    }

    Ok(results)
}

fn requests_share_batch_context(requests: &[BatchRenderRequest]) -> bool {
    let Some(first) = requests.first() else {
        return true;
    };

    requests.iter().all(|request| {
        request.object_dir == first.object_dir
            && request.object_rotation == first.object_rotation
            && request.render_config == first.render_config
    })
}

// Re-export bevy types that consumers will need
pub use bevy::prelude::{Quat, Transform, Vec3};

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

    #[test]
    fn test_object_rotation_identity() {
        let rot = ObjectRotation::identity();
        assert_eq!(rot.pitch, 0.0);
        assert_eq!(rot.yaw, 0.0);
        assert_eq!(rot.roll, 0.0);
    }

    #[test]
    fn test_object_rotation_from_array() {
        let rot = ObjectRotation::from_array([10.0, 20.0, 30.0]);
        assert_eq!(rot.pitch, 10.0);
        assert_eq!(rot.yaw, 20.0);
        assert_eq!(rot.roll, 30.0);
    }

    #[test]
    fn test_requests_share_batch_context_for_homogeneous_batch() {
        let config = RenderConfig::tbp_default();
        let request = BatchRenderRequest {
            object_dir: "/tmp/ycb/003_cracker_box".into(),
            viewpoint: Transform::IDENTITY,
            object_rotation: ObjectRotation::identity(),
            render_config: config.clone(),
        };

        assert!(requests_share_batch_context(&[
            request.clone(),
            BatchRenderRequest {
                viewpoint: Transform::from_xyz(1.0, 0.0, 0.0),
                ..request
            },
        ]));
    }

    #[test]
    fn test_requests_share_batch_context_rejects_mixed_objects() {
        let config = RenderConfig::tbp_default();
        let request = BatchRenderRequest {
            object_dir: "/tmp/ycb/003_cracker_box".into(),
            viewpoint: Transform::IDENTITY,
            object_rotation: ObjectRotation::identity(),
            render_config: config.clone(),
        };

        assert!(!requests_share_batch_context(&[
            request.clone(),
            BatchRenderRequest {
                object_dir: "/tmp/ycb/005_tomato_soup_can".into(),
                ..request
            },
        ]));
    }

    #[test]
    fn test_tbp_benchmark_rotations() {
        let rotations = ObjectRotation::tbp_benchmark_rotations();
        assert_eq!(rotations.len(), 3);
        assert_eq!(rotations[0], ObjectRotation::from_array([0.0, 0.0, 0.0]));
        assert_eq!(rotations[1], ObjectRotation::from_array([0.0, 90.0, 0.0]));
        assert_eq!(rotations[2], ObjectRotation::from_array([0.0, 180.0, 0.0]));
    }

    #[test]
    fn test_tbp_known_orientations_count() {
        let orientations = ObjectRotation::tbp_known_orientations();
        assert_eq!(orientations.len(), 14);
    }

    #[test]
    fn test_rotation_to_quat() {
        let rot = ObjectRotation::identity();
        let quat = rot.to_quat();
        // Identity quaternion should be approximately (1, 0, 0, 0)
        assert!((quat.w - 1.0).abs() < 0.001);
        assert!(quat.x.abs() < 0.001);
        assert!(quat.y.abs() < 0.001);
        assert!(quat.z.abs() < 0.001);
    }

    #[test]
    fn test_rotation_90_yaw() {
        let rot = ObjectRotation::new(0.0, 90.0, 0.0);
        let quat = rot.to_quat();
        // 90° Y rotation: w ≈ 0.707, y ≈ 0.707
        assert!((quat.w - 0.707).abs() < 0.01);
        assert!((quat.y - 0.707).abs() < 0.01);
    }

    #[test]
    fn test_viewpoint_config_default() {
        let config = ViewpointConfig::default();
        assert_eq!(config.radius, 0.5);
        assert_eq!(config.yaw_count, 8);
        assert_eq!(config.pitch_angles_deg.len(), 3);
    }

    #[test]
    fn test_viewpoint_count() {
        let config = ViewpointConfig::default();
        assert_eq!(config.viewpoint_count(), 24); // 8 × 3
    }

    #[test]
    fn test_generate_viewpoints_count() {
        let config = ViewpointConfig::default();
        let viewpoints = generate_viewpoints(&config);
        assert_eq!(viewpoints.len(), 24);
    }

    #[test]
    fn test_viewpoints_spherical_radius() {
        let config = ViewpointConfig::default();
        let viewpoints = generate_viewpoints(&config);

        for (i, transform) in viewpoints.iter().enumerate() {
            let actual_radius = transform.translation.length();
            assert!(
                (actual_radius - config.radius).abs() < 0.001,
                "Viewpoint {} has incorrect radius: {} (expected {})",
                i,
                actual_radius,
                config.radius
            );
        }
    }

    #[test]
    fn test_viewpoints_looking_at_origin() {
        let config = ViewpointConfig::default();
        let viewpoints = generate_viewpoints(&config);

        for (i, transform) in viewpoints.iter().enumerate() {
            let forward = transform.forward();
            let to_origin = (Vec3::ZERO - transform.translation).normalize();
            let dot = forward.dot(to_origin);
            assert!(
                dot > 0.99,
                "Viewpoint {} not looking at origin, dot product: {}",
                i,
                dot
            );
        }
    }

    #[test]
    fn test_sensor_config_default() {
        let config = SensorConfig::default();
        assert_eq!(config.object_rotations.len(), 1);
        assert_eq!(config.total_captures(), 24);
    }

    #[test]
    fn test_sensor_config_tbp_benchmark() {
        let config = SensorConfig::tbp_benchmark();
        assert_eq!(config.object_rotations.len(), 3);
        assert_eq!(config.total_captures(), 72); // 3 rotations × 24 viewpoints
    }

    #[test]
    fn test_sensor_config_tbp_full() {
        let config = SensorConfig::tbp_full_training();
        assert_eq!(config.object_rotations.len(), 14);
        assert_eq!(config.total_captures(), 336); // 14 rotations × 24 viewpoints
    }

    #[test]
    fn test_ycb_representative_objects() {
        // Verify representative objects are defined
        assert_eq!(crate::ycb::REPRESENTATIVE_OBJECTS.len(), 3);
        assert!(crate::ycb::REPRESENTATIVE_OBJECTS.contains(&"003_cracker_box"));
    }

    #[test]
    fn test_ycb_tbp_standard_objects() {
        assert_eq!(crate::ycb::TBP_STANDARD_OBJECTS.len(), 10);
        assert!(crate::ycb::TBP_STANDARD_OBJECTS.contains(&"025_mug"));
    }

    #[test]
    fn test_ycb_tbp_similar_objects() {
        assert_eq!(crate::ycb::TBP_SIMILAR_OBJECTS.len(), 10);
        assert!(crate::ycb::TBP_SIMILAR_OBJECTS.contains(&"003_cracker_box"));
    }

    #[test]
    fn test_ycb_object_mesh_path() {
        let path = crate::ycb::object_mesh_path("/tmp/ycb", "003_cracker_box");
        assert_eq!(
            path,
            std::path::Path::new("/tmp/ycb")
                .join("003_cracker_box")
                .join("google_16k")
                .join("textured.obj")
        );
    }

    #[test]
    fn test_ycb_object_texture_path() {
        let path = crate::ycb::object_texture_path("/tmp/ycb", "003_cracker_box");
        assert_eq!(
            path,
            std::path::Path::new("/tmp/ycb")
                .join("003_cracker_box")
                .join("google_16k")
                .join("texture_map.png")
        );
    }

    // =========================================================================
    // Headless Rendering API Tests
    // =========================================================================

    #[test]
    fn test_render_config_tbp_default() {
        let config = RenderConfig::tbp_default();
        // TBP spec: 64x64 patch sensor resolution
        assert_eq!(config.width, 64);
        assert_eq!(config.height, 64);
        // Zoom is a divisor in the FOV formula — must be positive
        assert!(config.zoom > 0.0);
        // Clipping planes must form a valid, positive range
        assert!(config.near_plane > 0.0);
        assert!(config.far_plane > config.near_plane);
    }

    #[test]
    fn test_render_config_preview() {
        let config = RenderConfig::preview();
        assert_eq!(config.width, 256);
        assert_eq!(config.height, 256);
    }

    #[test]
    fn test_render_config_default_is_tbp() {
        let default = RenderConfig::default();
        let tbp = RenderConfig::tbp_default();
        assert_eq!(default.width, tbp.width);
        assert_eq!(default.height, tbp.height);
    }

    #[test]
    fn test_render_config_fov() {
        let config = RenderConfig::tbp_default();
        let fov = config.fov_radians();
        // FOV must be a valid positive angle strictly less than π for any
        // positive zoom — no cameras with ≥180° FOV.
        assert!(fov > 0.0);
        assert!(fov < PI);

        // Zoom in should reduce FOV (tighter view).
        let zoomed = RenderConfig {
            zoom: config.zoom * 2.0,
            ..config
        };
        assert!(zoomed.fov_radians() < fov);
    }

    #[test]
    fn test_render_config_intrinsics() {
        let config = RenderConfig::tbp_default();
        let intrinsics = config.intrinsics();

        // Image size matches config; principal point at image center.
        assert_eq!(intrinsics.image_size, [config.width, config.height]);
        assert_eq!(
            intrinsics.principal_point,
            [config.width as f64 / 2.0, config.height as f64 / 2.0]
        );
        // Square pixels: fx == fy.
        assert_eq!(intrinsics.focal_length[0], intrinsics.focal_length[1]);
        assert!(intrinsics.focal_length[0] > 0.0);
    }

    #[test]
    fn test_camera_intrinsics_project() {
        let intrinsics = CameraIntrinsics {
            focal_length: [100.0, 100.0],
            principal_point: [32.0, 32.0],
            image_size: [64, 64],
        };

        // Point at origin of camera frame projects to principal point
        let center = intrinsics.project(Vec3::new(0.0, 0.0, 1.0));
        assert!(center.is_some());
        let [x, y] = center.unwrap();
        assert!((x - 32.0).abs() < 0.001);
        assert!((y - 32.0).abs() < 0.001);

        // Point behind camera returns None
        let behind = intrinsics.project(Vec3::new(0.0, 0.0, -1.0));
        assert!(behind.is_none());
    }

    #[test]
    fn test_camera_intrinsics_unproject() {
        let intrinsics = CameraIntrinsics {
            focal_length: [100.0, 100.0],
            principal_point: [32.0, 32.0],
            image_size: [64, 64],
        };

        // Unproject principal point at depth 1.0
        let point = intrinsics.unproject([32.0, 32.0], 1.0);
        assert!((point[0]).abs() < 0.001); // x
        assert!((point[1]).abs() < 0.001); // y
        assert!((point[2] - 1.0).abs() < 0.001); // z
    }

    #[test]
    fn test_render_output_get_rgba() {
        let output = RenderOutput {
            rgba: vec![
                255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 255, 255, 255, 255,
            ],
            depth: vec![1.0, 2.0, 3.0, 4.0],
            width: 2,
            height: 2,
            intrinsics: RenderConfig::tbp_default().intrinsics(),
            camera_transform: Transform::IDENTITY,
            object_rotation: ObjectRotation::identity(),
        };

        // Top-left: red
        assert_eq!(output.get_rgba(0, 0), Some([255, 0, 0, 255]));
        // Top-right: green
        assert_eq!(output.get_rgba(1, 0), Some([0, 255, 0, 255]));
        // Bottom-left: blue
        assert_eq!(output.get_rgba(0, 1), Some([0, 0, 255, 255]));
        // Bottom-right: white
        assert_eq!(output.get_rgba(1, 1), Some([255, 255, 255, 255]));
        // Out of bounds
        assert_eq!(output.get_rgba(2, 0), None);
    }

    #[test]
    fn test_render_output_get_depth() {
        let output = RenderOutput {
            rgba: vec![0u8; 16],
            depth: vec![1.0, 2.0, 3.0, 4.0],
            width: 2,
            height: 2,
            intrinsics: RenderConfig::tbp_default().intrinsics(),
            camera_transform: Transform::IDENTITY,
            object_rotation: ObjectRotation::identity(),
        };

        assert_eq!(output.get_depth(0, 0), Some(1.0));
        assert_eq!(output.get_depth(1, 0), Some(2.0));
        assert_eq!(output.get_depth(0, 1), Some(3.0));
        assert_eq!(output.get_depth(1, 1), Some(4.0));
        assert_eq!(output.get_depth(2, 0), None);
    }

    #[test]
    fn test_render_output_to_rgb_image() {
        let output = RenderOutput {
            rgba: vec![
                255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 255, 255, 255, 255,
            ],
            depth: vec![1.0, 2.0, 3.0, 4.0],
            width: 2,
            height: 2,
            intrinsics: RenderConfig::tbp_default().intrinsics(),
            camera_transform: Transform::IDENTITY,
            object_rotation: ObjectRotation::identity(),
        };

        let image = output.to_rgb_image();
        assert_eq!(image.len(), 2); // 2 rows
        assert_eq!(image[0].len(), 2); // 2 columns
        assert_eq!(image[0][0], [255, 0, 0]); // Red
        assert_eq!(image[0][1], [0, 255, 0]); // Green
        assert_eq!(image[1][0], [0, 0, 255]); // Blue
        assert_eq!(image[1][1], [255, 255, 255]); // White
    }

    #[test]
    fn test_render_output_to_depth_image() {
        let output = RenderOutput {
            rgba: vec![0u8; 16],
            depth: vec![1.0, 2.0, 3.0, 4.0],
            width: 2,
            height: 2,
            intrinsics: RenderConfig::tbp_default().intrinsics(),
            camera_transform: Transform::IDENTITY,
            object_rotation: ObjectRotation::identity(),
        };

        let depth_image = output.to_depth_image();
        assert_eq!(depth_image.len(), 2);
        assert_eq!(depth_image[0], vec![1.0, 2.0]);
        assert_eq!(depth_image[1], vec![3.0, 4.0]);
    }

    #[test]
    fn test_render_error_display() {
        let err = RenderError::MeshNotFound("/path/to/mesh.obj".to_string());
        assert!(err.to_string().contains("Mesh not found"));
        assert!(err.to_string().contains("/path/to/mesh.obj"));
    }

    // =========================================================================
    // Edge Case Tests
    // =========================================================================

    #[test]
    fn test_object_rotation_extreme_angles() {
        // Test angles beyond 360 degrees
        let rot = ObjectRotation::new(450.0, -720.0, 1080.0);
        let quat = rot.to_quat();
        // Quaternion should still be valid (normalized)
        assert!((quat.length() - 1.0).abs() < 0.001);
    }

    #[test]
    fn test_object_rotation_to_transform() {
        let rot = ObjectRotation::new(45.0, 90.0, 0.0);
        let transform = rot.to_transform();
        // Transform should have no translation
        assert_eq!(transform.translation, Vec3::ZERO);
        // Should have rotation
        assert!(transform.rotation != Quat::IDENTITY);
    }

    #[test]
    fn test_viewpoint_config_single_viewpoint() {
        let config = ViewpointConfig {
            radius: 1.0,
            yaw_count: 1,
            pitch_angles_deg: vec![0.0],
        };
        assert_eq!(config.viewpoint_count(), 1);
        let viewpoints = generate_viewpoints(&config);
        assert_eq!(viewpoints.len(), 1);
        // Single viewpoint at yaw=0, pitch=0 should be at (0, 0, radius)
        let pos = viewpoints[0].translation;
        assert!((pos.x).abs() < 0.001);
        assert!((pos.y).abs() < 0.001);
        assert!((pos.z - 1.0).abs() < 0.001);
    }

    #[test]
    fn test_viewpoint_radius_scaling() {
        let config1 = ViewpointConfig {
            radius: 0.5,
            yaw_count: 4,
            pitch_angles_deg: vec![0.0],
        };
        let config2 = ViewpointConfig {
            radius: 2.0,
            yaw_count: 4,
            pitch_angles_deg: vec![0.0],
        };

        let v1 = generate_viewpoints(&config1);
        let v2 = generate_viewpoints(&config2);

        // Viewpoints should scale proportionally
        for (vp1, vp2) in v1.iter().zip(v2.iter()) {
            let ratio = vp2.translation.length() / vp1.translation.length();
            assert!((ratio - 4.0).abs() < 0.01); // 2.0 / 0.5 = 4.0
        }
    }

    #[test]
    fn test_camera_intrinsics_project_at_z_zero() {
        let intrinsics = CameraIntrinsics {
            focal_length: [100.0, 100.0],
            principal_point: [32.0, 32.0],
            image_size: [64, 64],
        };

        // Point at z=0 should return None (division by zero protection)
        let result = intrinsics.project(Vec3::new(1.0, 1.0, 0.0));
        assert!(result.is_none());
    }

    #[test]
    fn test_camera_intrinsics_roundtrip() {
        let intrinsics = CameraIntrinsics {
            focal_length: [100.0, 100.0],
            principal_point: [32.0, 32.0],
            image_size: [64, 64],
        };

        // Project a 3D point
        let original = Vec3::new(0.5, -0.3, 2.0);
        let projected = intrinsics.project(original).unwrap();

        // Unproject back with the same depth (convert f32 to f64)
        let unprojected = intrinsics.unproject(projected, original.z as f64);

        // Should get back approximately the same point
        assert!((unprojected[0] - original.x as f64).abs() < 0.001); // x
        assert!((unprojected[1] - original.y as f64).abs() < 0.001); // y
        assert!((unprojected[2] - original.z as f64).abs() < 0.001); // z
    }

    #[test]
    fn test_render_output_empty() {
        let output = RenderOutput {
            rgba: vec![],
            depth: vec![],
            width: 0,
            height: 0,
            intrinsics: RenderConfig::tbp_default().intrinsics(),
            camera_transform: Transform::IDENTITY,
            object_rotation: ObjectRotation::identity(),
        };

        // Should handle empty gracefully
        assert_eq!(output.get_rgba(0, 0), None);
        assert_eq!(output.get_depth(0, 0), None);
        assert!(output.to_rgb_image().is_empty());
        assert!(output.to_depth_image().is_empty());
    }

    #[test]
    fn test_render_output_1x1() {
        let output = RenderOutput {
            rgba: vec![128, 64, 32, 255],
            depth: vec![0.5],
            width: 1,
            height: 1,
            intrinsics: RenderConfig::tbp_default().intrinsics(),
            camera_transform: Transform::IDENTITY,
            object_rotation: ObjectRotation::identity(),
        };

        assert_eq!(output.get_rgba(0, 0), Some([128, 64, 32, 255]));
        assert_eq!(output.get_depth(0, 0), Some(0.5));
        assert_eq!(output.get_rgb(0, 0), Some([128, 64, 32]));

        let rgb_img = output.to_rgb_image();
        assert_eq!(rgb_img.len(), 1);
        assert_eq!(rgb_img[0].len(), 1);
        assert_eq!(rgb_img[0][0], [128, 64, 32]);
    }

    #[test]
    fn test_render_config_high_res() {
        let config = RenderConfig::high_res();
        assert_eq!(config.width, 512);
        assert_eq!(config.height, 512);

        let intrinsics = config.intrinsics();
        assert_eq!(intrinsics.image_size, [512, 512]);
        assert_eq!(intrinsics.principal_point, [256.0, 256.0]);
    }

    #[test]
    fn test_render_config_zoom_affects_fov() {
        // The formula fov = 2·atan(tan(base_hfov/2)/zoom) has an exact
        // invariant: tan(fov/2) * zoom is constant. So doubling zoom
        // halves tan(fov/2). (This is NOT the same as halving fov itself,
        // which only holds as a small-angle approximation.)
        let base = RenderConfig {
            zoom: 2.0,
            ..RenderConfig::tbp_default()
        };
        let doubled = RenderConfig {
            zoom: 4.0,
            ..RenderConfig::tbp_default()
        };

        // Higher zoom → tighter FOV (monotonicity).
        assert!(doubled.fov_radians() < base.fov_radians());

        // Exact invariant: tan(fov/2) scales as 1/zoom.
        let base_half_tan = (base.fov_radians() / 2.0).tan();
        let doubled_half_tan = (doubled.fov_radians() / 2.0).tan();
        assert!((base_half_tan / doubled_half_tan - 2.0).abs() < 1e-4);
    }

    #[test]
    fn test_render_config_zoom_affects_intrinsics() {
        // The formula fx = (width/2)·zoom/tan(base_hfov/2) is linear in
        // zoom for fixed width/base_hfov, so fx/zoom is constant.
        let a = RenderConfig {
            zoom: 2.0,
            ..RenderConfig::tbp_default()
        };
        let b = RenderConfig {
            zoom: 4.0,
            ..RenderConfig::tbp_default()
        };

        let fx_a = a.intrinsics().focal_length[0];
        let fx_b = b.intrinsics().focal_length[0];

        // Monotonic: higher zoom → larger focal length.
        assert!(fx_b > fx_a);

        // Exact linearity: fx/zoom is constant across configs.
        assert!((fx_a / a.zoom as f64 - fx_b / b.zoom as f64).abs() < 1e-9);
    }

    #[test]
    fn test_lighting_config_variants() {
        let default = LightingConfig::default();
        let bright = LightingConfig::bright();
        let soft = LightingConfig::soft();
        let unlit = LightingConfig::unlit();

        // Bright should have higher intensity than default
        assert!(bright.key_light_intensity > default.key_light_intensity);

        // Unlit should have no point lights
        assert_eq!(unlit.key_light_intensity, 0.0);
        assert_eq!(unlit.fill_light_intensity, 0.0);
        assert_eq!(unlit.ambient_brightness, 1.0);

        // Soft should have lower intensity
        assert!(soft.key_light_intensity < default.key_light_intensity);
    }

    #[test]
    fn test_all_render_error_variants() {
        let errors = vec![
            RenderError::MeshNotFound("mesh.obj".to_string()),
            RenderError::TextureNotFound("texture.png".to_string()),
            RenderError::RenderFailed("GPU error".to_string()),
            RenderError::InvalidConfig("bad config".to_string()),
        ];

        for err in errors {
            // All variants should have Display impl
            let msg = err.to_string();
            assert!(!msg.is_empty());
        }
    }

    #[test]
    fn test_tbp_known_orientations_unique() {
        let orientations = ObjectRotation::tbp_known_orientations();

        // All 14 orientations should produce unique quaternions
        let quats: Vec<Quat> = orientations.iter().map(|r| r.to_quat()).collect();

        for (i, q1) in quats.iter().enumerate() {
            for (j, q2) in quats.iter().enumerate() {
                if i != j {
                    // Quaternions should be different (accounting for q == -q equivalence)
                    let dot = q1.dot(*q2).abs();
                    assert!(
                        dot < 0.999,
                        "Orientations {} and {} produce same quaternion",
                        i,
                        j
                    );
                }
            }
        }
    }
}