1use bevy::prelude::*;
54use std::f32::consts::PI;
55use std::path::Path;
56
57mod render;
60
61pub mod batch;
63
64pub mod fixtures;
66
67pub use ycbust::{self, DownloadOptions, Subset as YcbSubset, REPRESENTATIVE_OBJECTS, TEN_OBJECTS};
69
70pub mod ycb {
72 pub use ycbust::{download_ycb, DownloadOptions, Subset, REPRESENTATIVE_OBJECTS, TEN_OBJECTS};
73
74 use std::path::Path;
75
76 pub async fn download_models<P: AsRef<Path>>(
89 output_dir: P,
90 subset: Subset,
91 ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
92 let options = DownloadOptions {
93 overwrite: false,
94 full: false,
95 show_progress: true,
96 delete_archives: true,
97 };
98 download_ycb(subset, output_dir.as_ref(), options).await?;
99 Ok(())
100 }
101
102 pub async fn download_models_with_options<P: AsRef<Path>>(
104 output_dir: P,
105 subset: Subset,
106 options: DownloadOptions,
107 ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
108 download_ycb(subset, output_dir.as_ref(), options).await?;
109 Ok(())
110 }
111
112 pub fn models_exist<P: AsRef<Path>>(output_dir: P) -> bool {
114 let path = output_dir.as_ref();
115 path.join("003_cracker_box/google_16k/textured.obj")
117 .exists()
118 }
119
120 pub fn object_mesh_path<P: AsRef<Path>>(output_dir: P, object_id: &str) -> std::path::PathBuf {
122 output_dir
123 .as_ref()
124 .join(object_id)
125 .join("google_16k")
126 .join("textured.obj")
127 }
128
129 pub fn object_texture_path<P: AsRef<Path>>(
131 output_dir: P,
132 object_id: &str,
133 ) -> std::path::PathBuf {
134 output_dir
135 .as_ref()
136 .join(object_id)
137 .join("google_16k")
138 .join("texture_map.png")
139 }
140}
141
142#[derive(Clone, Debug, PartialEq)]
145pub struct ObjectRotation {
146 pub pitch: f64,
148 pub yaw: f64,
150 pub roll: f64,
152}
153
154impl ObjectRotation {
155 pub fn new(pitch: f64, yaw: f64, roll: f64) -> Self {
157 Self { pitch, yaw, roll }
158 }
159
160 pub fn from_array(arr: [f64; 3]) -> Self {
162 Self {
163 pitch: arr[0],
164 yaw: arr[1],
165 roll: arr[2],
166 }
167 }
168
169 pub fn identity() -> Self {
171 Self::new(0.0, 0.0, 0.0)
172 }
173
174 pub fn tbp_benchmark_rotations() -> Vec<Self> {
177 vec![
178 Self::from_array([0.0, 0.0, 0.0]),
179 Self::from_array([0.0, 90.0, 0.0]),
180 Self::from_array([0.0, 180.0, 0.0]),
181 ]
182 }
183
184 pub fn tbp_known_orientations() -> Vec<Self> {
187 vec![
188 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]), Self::from_array([0.0, 270.0, 0.0]), Self::from_array([90.0, 0.0, 0.0]), Self::from_array([-90.0, 0.0, 0.0]), Self::from_array([45.0, 45.0, 0.0]),
197 Self::from_array([45.0, 135.0, 0.0]),
198 Self::from_array([45.0, 225.0, 0.0]),
199 Self::from_array([45.0, 315.0, 0.0]),
200 Self::from_array([-45.0, 45.0, 0.0]),
201 Self::from_array([-45.0, 135.0, 0.0]),
202 Self::from_array([-45.0, 225.0, 0.0]),
203 Self::from_array([-45.0, 315.0, 0.0]),
204 ]
205 }
206
207 pub fn to_quat(&self) -> Quat {
209 Quat::from_euler(
210 EulerRot::XYZ,
211 (self.pitch as f32).to_radians(),
212 (self.yaw as f32).to_radians(),
213 (self.roll as f32).to_radians(),
214 )
215 }
216
217 pub fn to_transform(&self) -> Transform {
219 Transform::from_rotation(self.to_quat())
220 }
221}
222
223impl Default for ObjectRotation {
224 fn default() -> Self {
225 Self::identity()
226 }
227}
228
229#[derive(Clone, Debug)]
232pub struct ViewpointConfig {
233 pub radius: f32,
235 pub yaw_count: usize,
237 pub pitch_angles_deg: Vec<f32>,
239}
240
241impl Default for ViewpointConfig {
242 fn default() -> Self {
243 Self {
244 radius: 0.5,
245 yaw_count: 8,
246 pitch_angles_deg: vec![-30.0, 0.0, 30.0],
249 }
250 }
251}
252
253impl ViewpointConfig {
254 pub fn viewpoint_count(&self) -> usize {
256 self.yaw_count * self.pitch_angles_deg.len()
257 }
258}
259
260#[derive(Clone, Debug, Resource)]
262pub struct SensorConfig {
263 pub viewpoints: ViewpointConfig,
265 pub object_rotations: Vec<ObjectRotation>,
267 pub output_dir: String,
269 pub filename_pattern: String,
271}
272
273impl Default for SensorConfig {
274 fn default() -> Self {
275 Self {
276 viewpoints: ViewpointConfig::default(),
277 object_rotations: vec![ObjectRotation::identity()],
278 output_dir: ".".to_string(),
279 filename_pattern: "capture_{rot}_{view}.png".to_string(),
280 }
281 }
282}
283
284impl SensorConfig {
285 pub fn tbp_benchmark() -> Self {
287 Self {
288 viewpoints: ViewpointConfig::default(),
289 object_rotations: ObjectRotation::tbp_benchmark_rotations(),
290 output_dir: ".".to_string(),
291 filename_pattern: "capture_{rot}_{view}.png".to_string(),
292 }
293 }
294
295 pub fn tbp_full_training() -> Self {
297 Self {
298 viewpoints: ViewpointConfig::default(),
299 object_rotations: ObjectRotation::tbp_known_orientations(),
300 output_dir: ".".to_string(),
301 filename_pattern: "capture_{rot}_{view}.png".to_string(),
302 }
303 }
304
305 pub fn total_captures(&self) -> usize {
307 self.viewpoints.viewpoint_count() * self.object_rotations.len()
308 }
309}
310
311pub fn generate_viewpoints(config: &ViewpointConfig) -> Vec<Transform> {
318 let mut views = Vec::with_capacity(config.viewpoint_count());
319
320 for pitch_deg in &config.pitch_angles_deg {
321 let pitch = pitch_deg.to_radians();
322
323 for i in 0..config.yaw_count {
324 let yaw = (i as f32) * 2.0 * PI / (config.yaw_count as f32);
325
326 let x = config.radius * pitch.cos() * yaw.sin();
331 let y = config.radius * pitch.sin();
332 let z = config.radius * pitch.cos() * yaw.cos();
333
334 let transform = Transform::from_xyz(x, y, z).looking_at(Vec3::ZERO, Vec3::Y);
335 views.push(transform);
336 }
337 }
338 views
339}
340
341#[derive(Component)]
343pub struct CaptureTarget;
344
345#[derive(Component)]
347pub struct CaptureCamera;
348
349#[derive(Clone, Debug)]
357pub struct RenderConfig {
358 pub width: u32,
360 pub height: u32,
362 pub zoom: f32,
365 pub near_plane: f32,
367 pub far_plane: f32,
369 pub lighting: LightingConfig,
371}
372
373#[derive(Clone, Debug)]
377pub struct LightingConfig {
378 pub ambient_brightness: f32,
380 pub key_light_intensity: f32,
382 pub key_light_position: [f32; 3],
384 pub fill_light_intensity: f32,
386 pub fill_light_position: [f32; 3],
388 pub shadows_enabled: bool,
390}
391
392impl Default for LightingConfig {
393 fn default() -> Self {
394 Self {
395 ambient_brightness: 0.3,
396 key_light_intensity: 1500.0,
397 key_light_position: [4.0, 8.0, 4.0],
398 fill_light_intensity: 500.0,
399 fill_light_position: [-4.0, 2.0, -4.0],
400 shadows_enabled: false,
401 }
402 }
403}
404
405impl LightingConfig {
406 pub fn bright() -> Self {
408 Self {
409 ambient_brightness: 0.5,
410 key_light_intensity: 2000.0,
411 key_light_position: [4.0, 8.0, 4.0],
412 fill_light_intensity: 800.0,
413 fill_light_position: [-4.0, 2.0, -4.0],
414 shadows_enabled: false,
415 }
416 }
417
418 pub fn soft() -> Self {
420 Self {
421 ambient_brightness: 0.4,
422 key_light_intensity: 1000.0,
423 key_light_position: [3.0, 6.0, 3.0],
424 fill_light_intensity: 600.0,
425 fill_light_position: [-3.0, 3.0, -3.0],
426 shadows_enabled: false,
427 }
428 }
429
430 pub fn unlit() -> Self {
432 Self {
433 ambient_brightness: 1.0,
434 key_light_intensity: 0.0,
435 key_light_position: [0.0, 0.0, 0.0],
436 fill_light_intensity: 0.0,
437 fill_light_position: [0.0, 0.0, 0.0],
438 shadows_enabled: false,
439 }
440 }
441}
442
443impl Default for RenderConfig {
444 fn default() -> Self {
445 Self::tbp_default()
446 }
447}
448
449impl RenderConfig {
450 pub fn tbp_default() -> Self {
454 Self {
455 width: 64,
456 height: 64,
457 zoom: 1.0,
458 near_plane: 0.01,
459 far_plane: 10.0,
460 lighting: LightingConfig::default(),
461 }
462 }
463
464 pub fn preview() -> Self {
466 Self {
467 width: 256,
468 height: 256,
469 zoom: 1.0,
470 near_plane: 0.01,
471 far_plane: 10.0,
472 lighting: LightingConfig::default(),
473 }
474 }
475
476 pub fn high_res() -> Self {
478 Self {
479 width: 512,
480 height: 512,
481 zoom: 1.0,
482 near_plane: 0.01,
483 far_plane: 10.0,
484 lighting: LightingConfig::default(),
485 }
486 }
487
488 pub fn fov_radians(&self) -> f32 {
492 let base_fov_deg = 60.0_f32;
493 (base_fov_deg / self.zoom).to_radians()
494 }
495
496 pub fn intrinsics(&self) -> CameraIntrinsics {
501 let fov = self.fov_radians() as f64;
502 let fy = (self.height as f64 / 2.0) / (fov / 2.0).tan();
504 let fx = fy; CameraIntrinsics {
507 focal_length: [fx, fy],
508 principal_point: [self.width as f64 / 2.0, self.height as f64 / 2.0],
509 image_size: [self.width, self.height],
510 }
511 }
512}
513
514#[derive(Clone, Debug, PartialEq)]
519pub struct CameraIntrinsics {
520 pub focal_length: [f64; 2],
522 pub principal_point: [f64; 2],
524 pub image_size: [u32; 2],
526}
527
528impl CameraIntrinsics {
529 pub fn project(&self, point: Vec3) -> Option<[f64; 2]> {
531 if point.z <= 0.0 {
532 return None;
533 }
534 let x = (point.x as f64 / point.z as f64) * self.focal_length[0] + self.principal_point[0];
535 let y = (point.y as f64 / point.z as f64) * self.focal_length[1] + self.principal_point[1];
536 Some([x, y])
537 }
538
539 pub fn unproject(&self, pixel: [f64; 2], depth: f64) -> [f64; 3] {
541 let x = (pixel[0] - self.principal_point[0]) / self.focal_length[0] * depth;
542 let y = (pixel[1] - self.principal_point[1]) / self.focal_length[1] * depth;
543 [x, y, depth]
544 }
545}
546
547#[derive(Clone, Debug)]
549pub struct RenderOutput {
550 pub rgba: Vec<u8>,
552 pub depth: Vec<f64>,
556 pub width: u32,
558 pub height: u32,
560 pub intrinsics: CameraIntrinsics,
562 pub camera_transform: Transform,
564 pub object_rotation: ObjectRotation,
566}
567
568impl RenderOutput {
569 pub fn get_rgba(&self, x: u32, y: u32) -> Option<[u8; 4]> {
571 if x >= self.width || y >= self.height {
572 return None;
573 }
574 let idx = ((y * self.width + x) * 4) as usize;
575 Some([
576 self.rgba[idx],
577 self.rgba[idx + 1],
578 self.rgba[idx + 2],
579 self.rgba[idx + 3],
580 ])
581 }
582
583 pub fn get_depth(&self, x: u32, y: u32) -> Option<f64> {
585 if x >= self.width || y >= self.height {
586 return None;
587 }
588 let idx = (y * self.width + x) as usize;
589 Some(self.depth[idx])
590 }
591
592 pub fn get_rgb(&self, x: u32, y: u32) -> Option<[u8; 3]> {
594 self.get_rgba(x, y).map(|rgba| [rgba[0], rgba[1], rgba[2]])
595 }
596
597 pub fn to_rgb_image(&self) -> Vec<Vec<[u8; 3]>> {
599 let mut image = Vec::with_capacity(self.height as usize);
600 for y in 0..self.height {
601 let mut row = Vec::with_capacity(self.width as usize);
602 for x in 0..self.width {
603 row.push(self.get_rgb(x, y).unwrap_or([0, 0, 0]));
604 }
605 image.push(row);
606 }
607 image
608 }
609
610 pub fn to_depth_image(&self) -> Vec<Vec<f64>> {
612 let mut image = Vec::with_capacity(self.height as usize);
613 for y in 0..self.height {
614 let mut row = Vec::with_capacity(self.width as usize);
615 for x in 0..self.width {
616 row.push(self.get_depth(x, y).unwrap_or(0.0));
617 }
618 image.push(row);
619 }
620 image
621 }
622}
623
624#[derive(Debug, Clone)]
626pub enum RenderError {
627 MeshNotFound(String),
629 TextureNotFound(String),
631 RenderFailed(String),
633 InvalidConfig(String),
635}
636
637impl std::fmt::Display for RenderError {
638 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
639 match self {
640 RenderError::MeshNotFound(path) => write!(f, "Mesh not found: {}", path),
641 RenderError::TextureNotFound(path) => write!(f, "Texture not found: {}", path),
642 RenderError::RenderFailed(msg) => write!(f, "Render failed: {}", msg),
643 RenderError::InvalidConfig(msg) => write!(f, "Invalid config: {}", msg),
644 }
645 }
646}
647
648impl std::error::Error for RenderError {}
649
650pub fn render_to_buffer(
675 object_dir: &Path,
676 camera_transform: &Transform,
677 object_rotation: &ObjectRotation,
678 config: &RenderConfig,
679) -> Result<RenderOutput, RenderError> {
680 render::render_headless(object_dir, camera_transform, object_rotation, config)
682}
683
684pub fn render_all_viewpoints(
697 object_dir: &Path,
698 viewpoint_config: &ViewpointConfig,
699 rotations: &[ObjectRotation],
700 render_config: &RenderConfig,
701) -> Result<Vec<RenderOutput>, RenderError> {
702 let viewpoints = generate_viewpoints(viewpoint_config);
703 let mut outputs = Vec::with_capacity(viewpoints.len() * rotations.len());
704
705 for rotation in rotations {
706 for viewpoint in &viewpoints {
707 let output = render_to_buffer(object_dir, viewpoint, rotation, render_config)?;
708 outputs.push(output);
709 }
710 }
711
712 Ok(outputs)
713}
714
715pub fn render_to_files(
732 object_dir: &Path,
733 camera_transform: &Transform,
734 object_rotation: &ObjectRotation,
735 config: &RenderConfig,
736 rgba_path: &Path,
737 depth_path: &Path,
738) -> Result<(), RenderError> {
739 render::render_to_files(
740 object_dir,
741 camera_transform,
742 object_rotation,
743 config,
744 rgba_path,
745 depth_path,
746 )
747}
748
749pub use batch::{
751 BatchRenderConfig, BatchRenderError, BatchRenderOutput, BatchRenderRequest, BatchRenderer,
752 BatchState, RenderStatus,
753};
754
755pub fn create_batch_renderer(config: &BatchRenderConfig) -> Result<BatchRenderer, RenderError> {
773 Ok(BatchRenderer::new(config.clone()))
776}
777
778pub fn queue_render_request(
803 renderer: &mut BatchRenderer,
804 request: BatchRenderRequest,
805) -> Result<(), RenderError> {
806 renderer
807 .queue_request(request)
808 .map_err(|e| RenderError::RenderFailed(e.to_string()))
809}
810
811pub fn render_next_in_batch(
833 renderer: &mut BatchRenderer,
834 _timeout_ms: u32,
835) -> Result<Option<BatchRenderOutput>, RenderError> {
836 if let Some(request) = renderer.pending_requests.pop_front() {
839 let output = render_to_buffer(
840 &request.object_dir,
841 &request.viewpoint,
842 &request.object_rotation,
843 &request.render_config,
844 )?;
845 let batch_output = BatchRenderOutput::from_render_output(request, output);
846 renderer.completed_results.push(batch_output.clone());
847 renderer.renders_processed += 1;
848 Ok(Some(batch_output))
849 } else {
850 Ok(None)
851 }
852}
853
854pub fn render_batch(
873 requests: Vec<BatchRenderRequest>,
874 config: &BatchRenderConfig,
875) -> Result<Vec<BatchRenderOutput>, RenderError> {
876 let mut renderer = create_batch_renderer(config)?;
877
878 for request in requests {
880 queue_render_request(&mut renderer, request)?;
881 }
882
883 let mut results = Vec::new();
885 while let Some(output) = render_next_in_batch(&mut renderer, config.frame_timeout_ms)? {
886 results.push(output);
887 }
888
889 Ok(results)
890}
891
892pub use bevy::prelude::{Quat, Transform, Vec3};
894
895#[cfg(test)]
896mod tests {
897 use super::*;
898
899 #[test]
900 fn test_object_rotation_identity() {
901 let rot = ObjectRotation::identity();
902 assert_eq!(rot.pitch, 0.0);
903 assert_eq!(rot.yaw, 0.0);
904 assert_eq!(rot.roll, 0.0);
905 }
906
907 #[test]
908 fn test_object_rotation_from_array() {
909 let rot = ObjectRotation::from_array([10.0, 20.0, 30.0]);
910 assert_eq!(rot.pitch, 10.0);
911 assert_eq!(rot.yaw, 20.0);
912 assert_eq!(rot.roll, 30.0);
913 }
914
915 #[test]
916 fn test_tbp_benchmark_rotations() {
917 let rotations = ObjectRotation::tbp_benchmark_rotations();
918 assert_eq!(rotations.len(), 3);
919 assert_eq!(rotations[0], ObjectRotation::from_array([0.0, 0.0, 0.0]));
920 assert_eq!(rotations[1], ObjectRotation::from_array([0.0, 90.0, 0.0]));
921 assert_eq!(rotations[2], ObjectRotation::from_array([0.0, 180.0, 0.0]));
922 }
923
924 #[test]
925 fn test_tbp_known_orientations_count() {
926 let orientations = ObjectRotation::tbp_known_orientations();
927 assert_eq!(orientations.len(), 14);
928 }
929
930 #[test]
931 fn test_rotation_to_quat() {
932 let rot = ObjectRotation::identity();
933 let quat = rot.to_quat();
934 assert!((quat.w - 1.0).abs() < 0.001);
936 assert!(quat.x.abs() < 0.001);
937 assert!(quat.y.abs() < 0.001);
938 assert!(quat.z.abs() < 0.001);
939 }
940
941 #[test]
942 fn test_rotation_90_yaw() {
943 let rot = ObjectRotation::new(0.0, 90.0, 0.0);
944 let quat = rot.to_quat();
945 assert!((quat.w - 0.707).abs() < 0.01);
947 assert!((quat.y - 0.707).abs() < 0.01);
948 }
949
950 #[test]
951 fn test_viewpoint_config_default() {
952 let config = ViewpointConfig::default();
953 assert_eq!(config.radius, 0.5);
954 assert_eq!(config.yaw_count, 8);
955 assert_eq!(config.pitch_angles_deg.len(), 3);
956 }
957
958 #[test]
959 fn test_viewpoint_count() {
960 let config = ViewpointConfig::default();
961 assert_eq!(config.viewpoint_count(), 24); }
963
964 #[test]
965 fn test_generate_viewpoints_count() {
966 let config = ViewpointConfig::default();
967 let viewpoints = generate_viewpoints(&config);
968 assert_eq!(viewpoints.len(), 24);
969 }
970
971 #[test]
972 fn test_viewpoints_spherical_radius() {
973 let config = ViewpointConfig::default();
974 let viewpoints = generate_viewpoints(&config);
975
976 for (i, transform) in viewpoints.iter().enumerate() {
977 let actual_radius = transform.translation.length();
978 assert!(
979 (actual_radius - config.radius).abs() < 0.001,
980 "Viewpoint {} has incorrect radius: {} (expected {})",
981 i,
982 actual_radius,
983 config.radius
984 );
985 }
986 }
987
988 #[test]
989 fn test_viewpoints_looking_at_origin() {
990 let config = ViewpointConfig::default();
991 let viewpoints = generate_viewpoints(&config);
992
993 for (i, transform) in viewpoints.iter().enumerate() {
994 let forward = transform.forward();
995 let to_origin = (Vec3::ZERO - transform.translation).normalize();
996 let dot = forward.dot(to_origin);
997 assert!(
998 dot > 0.99,
999 "Viewpoint {} not looking at origin, dot product: {}",
1000 i,
1001 dot
1002 );
1003 }
1004 }
1005
1006 #[test]
1007 fn test_sensor_config_default() {
1008 let config = SensorConfig::default();
1009 assert_eq!(config.object_rotations.len(), 1);
1010 assert_eq!(config.total_captures(), 24);
1011 }
1012
1013 #[test]
1014 fn test_sensor_config_tbp_benchmark() {
1015 let config = SensorConfig::tbp_benchmark();
1016 assert_eq!(config.object_rotations.len(), 3);
1017 assert_eq!(config.total_captures(), 72); }
1019
1020 #[test]
1021 fn test_sensor_config_tbp_full() {
1022 let config = SensorConfig::tbp_full_training();
1023 assert_eq!(config.object_rotations.len(), 14);
1024 assert_eq!(config.total_captures(), 336); }
1026
1027 #[test]
1028 fn test_ycb_representative_objects() {
1029 assert_eq!(crate::ycb::REPRESENTATIVE_OBJECTS.len(), 3);
1031 assert!(crate::ycb::REPRESENTATIVE_OBJECTS.contains(&"003_cracker_box"));
1032 }
1033
1034 #[test]
1035 fn test_ycb_ten_objects() {
1036 assert_eq!(crate::ycb::TEN_OBJECTS.len(), 10);
1038 }
1039
1040 #[test]
1041 fn test_ycb_object_mesh_path() {
1042 let path = crate::ycb::object_mesh_path("/tmp/ycb", "003_cracker_box");
1043 assert_eq!(
1044 path.to_string_lossy(),
1045 "/tmp/ycb/003_cracker_box/google_16k/textured.obj"
1046 );
1047 }
1048
1049 #[test]
1050 fn test_ycb_object_texture_path() {
1051 let path = crate::ycb::object_texture_path("/tmp/ycb", "003_cracker_box");
1052 assert_eq!(
1053 path.to_string_lossy(),
1054 "/tmp/ycb/003_cracker_box/google_16k/texture_map.png"
1055 );
1056 }
1057
1058 #[test]
1063 fn test_render_config_tbp_default() {
1064 let config = RenderConfig::tbp_default();
1065 assert_eq!(config.width, 64);
1066 assert_eq!(config.height, 64);
1067 assert_eq!(config.zoom, 1.0);
1068 assert_eq!(config.near_plane, 0.01);
1069 assert_eq!(config.far_plane, 10.0);
1070 }
1071
1072 #[test]
1073 fn test_render_config_preview() {
1074 let config = RenderConfig::preview();
1075 assert_eq!(config.width, 256);
1076 assert_eq!(config.height, 256);
1077 }
1078
1079 #[test]
1080 fn test_render_config_default_is_tbp() {
1081 let default = RenderConfig::default();
1082 let tbp = RenderConfig::tbp_default();
1083 assert_eq!(default.width, tbp.width);
1084 assert_eq!(default.height, tbp.height);
1085 }
1086
1087 #[test]
1088 fn test_render_config_fov() {
1089 let config = RenderConfig::tbp_default();
1090 let fov = config.fov_radians();
1091 assert!((fov - 1.047).abs() < 0.01);
1093
1094 let zoomed = RenderConfig {
1096 zoom: 2.0,
1097 ..config
1098 };
1099 assert!(zoomed.fov_radians() < fov);
1100 }
1101
1102 #[test]
1103 fn test_render_config_intrinsics() {
1104 let config = RenderConfig::tbp_default();
1105 let intrinsics = config.intrinsics();
1106
1107 assert_eq!(intrinsics.image_size, [64, 64]);
1108 assert_eq!(intrinsics.principal_point, [32.0, 32.0]);
1109 assert!(intrinsics.focal_length[0] > 0.0);
1111 assert!(intrinsics.focal_length[1] > 0.0);
1112 assert!((intrinsics.focal_length[0] - 55.4).abs() < 1.0);
1114 }
1115
1116 #[test]
1117 fn test_camera_intrinsics_project() {
1118 let intrinsics = CameraIntrinsics {
1119 focal_length: [100.0, 100.0],
1120 principal_point: [32.0, 32.0],
1121 image_size: [64, 64],
1122 };
1123
1124 let center = intrinsics.project(Vec3::new(0.0, 0.0, 1.0));
1126 assert!(center.is_some());
1127 let [x, y] = center.unwrap();
1128 assert!((x - 32.0).abs() < 0.001);
1129 assert!((y - 32.0).abs() < 0.001);
1130
1131 let behind = intrinsics.project(Vec3::new(0.0, 0.0, -1.0));
1133 assert!(behind.is_none());
1134 }
1135
1136 #[test]
1137 fn test_camera_intrinsics_unproject() {
1138 let intrinsics = CameraIntrinsics {
1139 focal_length: [100.0, 100.0],
1140 principal_point: [32.0, 32.0],
1141 image_size: [64, 64],
1142 };
1143
1144 let point = intrinsics.unproject([32.0, 32.0], 1.0);
1146 assert!((point[0]).abs() < 0.001); assert!((point[1]).abs() < 0.001); assert!((point[2] - 1.0).abs() < 0.001); }
1150
1151 #[test]
1152 fn test_render_output_get_rgba() {
1153 let output = RenderOutput {
1154 rgba: vec![
1155 255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 255, 255, 255, 255,
1156 ],
1157 depth: vec![1.0, 2.0, 3.0, 4.0],
1158 width: 2,
1159 height: 2,
1160 intrinsics: RenderConfig::tbp_default().intrinsics(),
1161 camera_transform: Transform::IDENTITY,
1162 object_rotation: ObjectRotation::identity(),
1163 };
1164
1165 assert_eq!(output.get_rgba(0, 0), Some([255, 0, 0, 255]));
1167 assert_eq!(output.get_rgba(1, 0), Some([0, 255, 0, 255]));
1169 assert_eq!(output.get_rgba(0, 1), Some([0, 0, 255, 255]));
1171 assert_eq!(output.get_rgba(1, 1), Some([255, 255, 255, 255]));
1173 assert_eq!(output.get_rgba(2, 0), None);
1175 }
1176
1177 #[test]
1178 fn test_render_output_get_depth() {
1179 let output = RenderOutput {
1180 rgba: vec![0u8; 16],
1181 depth: vec![1.0, 2.0, 3.0, 4.0],
1182 width: 2,
1183 height: 2,
1184 intrinsics: RenderConfig::tbp_default().intrinsics(),
1185 camera_transform: Transform::IDENTITY,
1186 object_rotation: ObjectRotation::identity(),
1187 };
1188
1189 assert_eq!(output.get_depth(0, 0), Some(1.0));
1190 assert_eq!(output.get_depth(1, 0), Some(2.0));
1191 assert_eq!(output.get_depth(0, 1), Some(3.0));
1192 assert_eq!(output.get_depth(1, 1), Some(4.0));
1193 assert_eq!(output.get_depth(2, 0), None);
1194 }
1195
1196 #[test]
1197 fn test_render_output_to_rgb_image() {
1198 let output = RenderOutput {
1199 rgba: vec![
1200 255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 255, 255, 255, 255,
1201 ],
1202 depth: vec![1.0, 2.0, 3.0, 4.0],
1203 width: 2,
1204 height: 2,
1205 intrinsics: RenderConfig::tbp_default().intrinsics(),
1206 camera_transform: Transform::IDENTITY,
1207 object_rotation: ObjectRotation::identity(),
1208 };
1209
1210 let image = output.to_rgb_image();
1211 assert_eq!(image.len(), 2); assert_eq!(image[0].len(), 2); assert_eq!(image[0][0], [255, 0, 0]); assert_eq!(image[0][1], [0, 255, 0]); assert_eq!(image[1][0], [0, 0, 255]); assert_eq!(image[1][1], [255, 255, 255]); }
1218
1219 #[test]
1220 fn test_render_output_to_depth_image() {
1221 let output = RenderOutput {
1222 rgba: vec![0u8; 16],
1223 depth: vec![1.0, 2.0, 3.0, 4.0],
1224 width: 2,
1225 height: 2,
1226 intrinsics: RenderConfig::tbp_default().intrinsics(),
1227 camera_transform: Transform::IDENTITY,
1228 object_rotation: ObjectRotation::identity(),
1229 };
1230
1231 let depth_image = output.to_depth_image();
1232 assert_eq!(depth_image.len(), 2);
1233 assert_eq!(depth_image[0], vec![1.0, 2.0]);
1234 assert_eq!(depth_image[1], vec![3.0, 4.0]);
1235 }
1236
1237 #[test]
1238 fn test_render_error_display() {
1239 let err = RenderError::MeshNotFound("/path/to/mesh.obj".to_string());
1240 assert!(err.to_string().contains("Mesh not found"));
1241 assert!(err.to_string().contains("/path/to/mesh.obj"));
1242 }
1243
1244 #[test]
1249 fn test_object_rotation_extreme_angles() {
1250 let rot = ObjectRotation::new(450.0, -720.0, 1080.0);
1252 let quat = rot.to_quat();
1253 assert!((quat.length() - 1.0).abs() < 0.001);
1255 }
1256
1257 #[test]
1258 fn test_object_rotation_to_transform() {
1259 let rot = ObjectRotation::new(45.0, 90.0, 0.0);
1260 let transform = rot.to_transform();
1261 assert_eq!(transform.translation, Vec3::ZERO);
1263 assert!(transform.rotation != Quat::IDENTITY);
1265 }
1266
1267 #[test]
1268 fn test_viewpoint_config_single_viewpoint() {
1269 let config = ViewpointConfig {
1270 radius: 1.0,
1271 yaw_count: 1,
1272 pitch_angles_deg: vec![0.0],
1273 };
1274 assert_eq!(config.viewpoint_count(), 1);
1275 let viewpoints = generate_viewpoints(&config);
1276 assert_eq!(viewpoints.len(), 1);
1277 let pos = viewpoints[0].translation;
1279 assert!((pos.x).abs() < 0.001);
1280 assert!((pos.y).abs() < 0.001);
1281 assert!((pos.z - 1.0).abs() < 0.001);
1282 }
1283
1284 #[test]
1285 fn test_viewpoint_radius_scaling() {
1286 let config1 = ViewpointConfig {
1287 radius: 0.5,
1288 yaw_count: 4,
1289 pitch_angles_deg: vec![0.0],
1290 };
1291 let config2 = ViewpointConfig {
1292 radius: 2.0,
1293 yaw_count: 4,
1294 pitch_angles_deg: vec![0.0],
1295 };
1296
1297 let v1 = generate_viewpoints(&config1);
1298 let v2 = generate_viewpoints(&config2);
1299
1300 for (vp1, vp2) in v1.iter().zip(v2.iter()) {
1302 let ratio = vp2.translation.length() / vp1.translation.length();
1303 assert!((ratio - 4.0).abs() < 0.01); }
1305 }
1306
1307 #[test]
1308 fn test_camera_intrinsics_project_at_z_zero() {
1309 let intrinsics = CameraIntrinsics {
1310 focal_length: [100.0, 100.0],
1311 principal_point: [32.0, 32.0],
1312 image_size: [64, 64],
1313 };
1314
1315 let result = intrinsics.project(Vec3::new(1.0, 1.0, 0.0));
1317 assert!(result.is_none());
1318 }
1319
1320 #[test]
1321 fn test_camera_intrinsics_roundtrip() {
1322 let intrinsics = CameraIntrinsics {
1323 focal_length: [100.0, 100.0],
1324 principal_point: [32.0, 32.0],
1325 image_size: [64, 64],
1326 };
1327
1328 let original = Vec3::new(0.5, -0.3, 2.0);
1330 let projected = intrinsics.project(original).unwrap();
1331
1332 let unprojected = intrinsics.unproject(projected, original.z as f64);
1334
1335 assert!((unprojected[0] - original.x as f64).abs() < 0.001); assert!((unprojected[1] - original.y as f64).abs() < 0.001); assert!((unprojected[2] - original.z as f64).abs() < 0.001); }
1340
1341 #[test]
1342 fn test_render_output_empty() {
1343 let output = RenderOutput {
1344 rgba: vec![],
1345 depth: vec![],
1346 width: 0,
1347 height: 0,
1348 intrinsics: RenderConfig::tbp_default().intrinsics(),
1349 camera_transform: Transform::IDENTITY,
1350 object_rotation: ObjectRotation::identity(),
1351 };
1352
1353 assert_eq!(output.get_rgba(0, 0), None);
1355 assert_eq!(output.get_depth(0, 0), None);
1356 assert!(output.to_rgb_image().is_empty());
1357 assert!(output.to_depth_image().is_empty());
1358 }
1359
1360 #[test]
1361 fn test_render_output_1x1() {
1362 let output = RenderOutput {
1363 rgba: vec![128, 64, 32, 255],
1364 depth: vec![0.5],
1365 width: 1,
1366 height: 1,
1367 intrinsics: RenderConfig::tbp_default().intrinsics(),
1368 camera_transform: Transform::IDENTITY,
1369 object_rotation: ObjectRotation::identity(),
1370 };
1371
1372 assert_eq!(output.get_rgba(0, 0), Some([128, 64, 32, 255]));
1373 assert_eq!(output.get_depth(0, 0), Some(0.5));
1374 assert_eq!(output.get_rgb(0, 0), Some([128, 64, 32]));
1375
1376 let rgb_img = output.to_rgb_image();
1377 assert_eq!(rgb_img.len(), 1);
1378 assert_eq!(rgb_img[0].len(), 1);
1379 assert_eq!(rgb_img[0][0], [128, 64, 32]);
1380 }
1381
1382 #[test]
1383 fn test_render_config_high_res() {
1384 let config = RenderConfig::high_res();
1385 assert_eq!(config.width, 512);
1386 assert_eq!(config.height, 512);
1387
1388 let intrinsics = config.intrinsics();
1389 assert_eq!(intrinsics.image_size, [512, 512]);
1390 assert_eq!(intrinsics.principal_point, [256.0, 256.0]);
1391 }
1392
1393 #[test]
1394 fn test_render_config_zoom_affects_fov() {
1395 let base = RenderConfig::tbp_default();
1396 let zoomed = RenderConfig {
1397 zoom: 2.0,
1398 ..base.clone()
1399 };
1400
1401 assert!(zoomed.fov_radians() < base.fov_radians());
1403 assert!((zoomed.fov_radians() - base.fov_radians() / 2.0).abs() < 0.01);
1405 }
1406
1407 #[test]
1408 fn test_render_config_zoom_affects_intrinsics() {
1409 let base = RenderConfig::tbp_default();
1410 let zoomed = RenderConfig {
1411 zoom: 2.0,
1412 ..base.clone()
1413 };
1414
1415 let base_intrinsics = base.intrinsics();
1417 let zoomed_intrinsics = zoomed.intrinsics();
1418
1419 assert!(zoomed_intrinsics.focal_length[0] > base_intrinsics.focal_length[0]);
1420 }
1421
1422 #[test]
1423 fn test_lighting_config_variants() {
1424 let default = LightingConfig::default();
1425 let bright = LightingConfig::bright();
1426 let soft = LightingConfig::soft();
1427 let unlit = LightingConfig::unlit();
1428
1429 assert!(bright.key_light_intensity > default.key_light_intensity);
1431
1432 assert_eq!(unlit.key_light_intensity, 0.0);
1434 assert_eq!(unlit.fill_light_intensity, 0.0);
1435 assert_eq!(unlit.ambient_brightness, 1.0);
1436
1437 assert!(soft.key_light_intensity < default.key_light_intensity);
1439 }
1440
1441 #[test]
1442 fn test_all_render_error_variants() {
1443 let errors = vec![
1444 RenderError::MeshNotFound("mesh.obj".to_string()),
1445 RenderError::TextureNotFound("texture.png".to_string()),
1446 RenderError::RenderFailed("GPU error".to_string()),
1447 RenderError::InvalidConfig("bad config".to_string()),
1448 ];
1449
1450 for err in errors {
1451 let msg = err.to_string();
1453 assert!(!msg.is_empty());
1454 }
1455 }
1456
1457 #[test]
1458 fn test_tbp_known_orientations_unique() {
1459 let orientations = ObjectRotation::tbp_known_orientations();
1460
1461 let quats: Vec<Quat> = orientations.iter().map(|r| r.to_quat()).collect();
1463
1464 for (i, q1) in quats.iter().enumerate() {
1465 for (j, q2) in quats.iter().enumerate() {
1466 if i != j {
1467 let dot = q1.dot(*q2).abs();
1469 assert!(
1470 dot < 0.999,
1471 "Orientations {} and {} produce same quaternion",
1472 i,
1473 j
1474 );
1475 }
1476 }
1477 }
1478 }
1479}