1use bevy::prelude::*;
54use std::f32::consts::PI;
55use std::path::Path;
56
57mod render;
60
61pub mod batch;
63
64pub mod backend;
66
67pub mod cache;
69
70pub mod fixtures;
72
73#[allow(deprecated)]
75pub use ycbust::{
76 self, DownloadOptions, Subset as YcbSubset, REPRESENTATIVE_OBJECTS, TBP_STANDARD_OBJECTS,
77 TEN_OBJECTS,
78};
79
80pub mod ycb {
82 #[allow(deprecated)]
83 pub use ycbust::{
84 download_ycb, DownloadOptions, Subset, REPRESENTATIVE_OBJECTS, TBP_STANDARD_OBJECTS,
85 TEN_OBJECTS,
86 };
87
88 use reqwest::Client;
89 use std::path::Path;
90
91 pub async fn download_models<P: AsRef<Path>>(
104 output_dir: P,
105 subset: Subset,
106 ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
107 let options = DownloadOptions {
108 overwrite: false,
109 full: false,
110 show_progress: true,
111 delete_archives: true,
112 };
113 download_ycb(subset, output_dir.as_ref(), options).await?;
114 Ok(())
115 }
116
117 pub async fn download_models_with_options<P: AsRef<Path>>(
119 output_dir: P,
120 subset: Subset,
121 options: DownloadOptions,
122 ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
123 download_ycb(subset, output_dir.as_ref(), options).await?;
124 Ok(())
125 }
126
127 pub async fn download_objects<P: AsRef<Path>>(
129 output_dir: P,
130 object_ids: &[&str],
131 ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
132 let output_dir = output_dir.as_ref();
133 let client = Client::new();
134 let options = DownloadOptions {
135 overwrite: false,
136 full: false,
137 show_progress: true,
138 delete_archives: true,
139 };
140
141 std::fs::create_dir_all(output_dir)?;
142
143 for object_id in object_ids {
144 let url = ycbust::get_tgz_url(object_id, "google_16k");
145 let archive_path = output_dir.join(format!("{object_id}_google_16k.tgz"));
146
147 if archive_path.exists() && !options.overwrite {
148 continue;
149 }
150
151 ycbust::download_file(&client, &url, &archive_path, options.show_progress).await?;
152 ycbust::extract_tgz(&archive_path, output_dir, options.delete_archives)?;
153 }
154
155 Ok(())
156 }
157
158 pub fn models_exist<P: AsRef<Path>>(output_dir: P) -> bool {
160 let path = output_dir.as_ref();
161 path.join("003_cracker_box/google_16k/textured.obj")
163 .exists()
164 }
165
166 pub fn object_mesh_path<P: AsRef<Path>>(output_dir: P, object_id: &str) -> std::path::PathBuf {
168 output_dir
169 .as_ref()
170 .join(object_id)
171 .join("google_16k")
172 .join("textured.obj")
173 }
174
175 pub fn object_texture_path<P: AsRef<Path>>(
177 output_dir: P,
178 object_id: &str,
179 ) -> std::path::PathBuf {
180 output_dir
181 .as_ref()
182 .join(object_id)
183 .join("google_16k")
184 .join("texture_map.png")
185 }
186}
187
188pub fn initialize() {
222 use std::sync::atomic::{AtomicBool, Ordering};
224 static INITIALIZED: AtomicBool = AtomicBool::new(false);
225
226 if !INITIALIZED.swap(true, Ordering::SeqCst) {
227 let config = backend::BackendConfig::new();
229 config.apply_env();
230 }
231}
232
233#[derive(Clone, Debug, PartialEq)]
236pub struct ObjectRotation {
237 pub pitch: f64,
239 pub yaw: f64,
241 pub roll: f64,
243}
244
245impl ObjectRotation {
246 pub fn new(pitch: f64, yaw: f64, roll: f64) -> Self {
248 Self { pitch, yaw, roll }
249 }
250
251 pub fn from_array(arr: [f64; 3]) -> Self {
253 Self {
254 pitch: arr[0],
255 yaw: arr[1],
256 roll: arr[2],
257 }
258 }
259
260 pub fn identity() -> Self {
262 Self::new(0.0, 0.0, 0.0)
263 }
264
265 pub fn tbp_benchmark_rotations() -> Vec<Self> {
268 vec![
269 Self::from_array([0.0, 0.0, 0.0]),
270 Self::from_array([0.0, 90.0, 0.0]),
271 Self::from_array([0.0, 180.0, 0.0]),
272 ]
273 }
274
275 pub fn tbp_known_orientations() -> Vec<Self> {
278 vec![
279 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]),
288 Self::from_array([45.0, 135.0, 0.0]),
289 Self::from_array([45.0, 225.0, 0.0]),
290 Self::from_array([45.0, 315.0, 0.0]),
291 Self::from_array([-45.0, 45.0, 0.0]),
292 Self::from_array([-45.0, 135.0, 0.0]),
293 Self::from_array([-45.0, 225.0, 0.0]),
294 Self::from_array([-45.0, 315.0, 0.0]),
295 ]
296 }
297
298 pub fn to_quat(&self) -> Quat {
300 Quat::from_euler(
301 EulerRot::XYZ,
302 (self.pitch as f32).to_radians(),
303 (self.yaw as f32).to_radians(),
304 (self.roll as f32).to_radians(),
305 )
306 }
307
308 pub fn to_transform(&self) -> Transform {
310 Transform::from_rotation(self.to_quat())
311 }
312}
313
314impl Default for ObjectRotation {
315 fn default() -> Self {
316 Self::identity()
317 }
318}
319
320#[derive(Clone, Debug)]
323pub struct ViewpointConfig {
324 pub radius: f32,
326 pub yaw_count: usize,
328 pub pitch_angles_deg: Vec<f32>,
330}
331
332impl Default for ViewpointConfig {
333 fn default() -> Self {
334 Self {
335 radius: 0.5,
336 yaw_count: 8,
337 pitch_angles_deg: vec![-30.0, 0.0, 30.0],
340 }
341 }
342}
343
344impl ViewpointConfig {
345 pub fn viewpoint_count(&self) -> usize {
347 self.yaw_count * self.pitch_angles_deg.len()
348 }
349}
350
351#[derive(Clone, Debug, Resource)]
353pub struct SensorConfig {
354 pub viewpoints: ViewpointConfig,
356 pub object_rotations: Vec<ObjectRotation>,
358 pub output_dir: String,
360 pub filename_pattern: String,
362}
363
364impl Default for SensorConfig {
365 fn default() -> Self {
366 Self {
367 viewpoints: ViewpointConfig::default(),
368 object_rotations: vec![ObjectRotation::identity()],
369 output_dir: ".".to_string(),
370 filename_pattern: "capture_{rot}_{view}.png".to_string(),
371 }
372 }
373}
374
375impl SensorConfig {
376 pub fn tbp_benchmark() -> Self {
378 Self {
379 viewpoints: ViewpointConfig::default(),
380 object_rotations: ObjectRotation::tbp_benchmark_rotations(),
381 output_dir: ".".to_string(),
382 filename_pattern: "capture_{rot}_{view}.png".to_string(),
383 }
384 }
385
386 pub fn tbp_full_training() -> Self {
388 Self {
389 viewpoints: ViewpointConfig::default(),
390 object_rotations: ObjectRotation::tbp_known_orientations(),
391 output_dir: ".".to_string(),
392 filename_pattern: "capture_{rot}_{view}.png".to_string(),
393 }
394 }
395
396 pub fn total_captures(&self) -> usize {
398 self.viewpoints.viewpoint_count() * self.object_rotations.len()
399 }
400}
401
402pub fn generate_viewpoints(config: &ViewpointConfig) -> Vec<Transform> {
409 let mut views = Vec::with_capacity(config.viewpoint_count());
410
411 for pitch_deg in &config.pitch_angles_deg {
412 let pitch = pitch_deg.to_radians();
413
414 for i in 0..config.yaw_count {
415 let yaw = (i as f32) * 2.0 * PI / (config.yaw_count as f32);
416
417 let x = config.radius * pitch.cos() * yaw.sin();
422 let y = config.radius * pitch.sin();
423 let z = config.radius * pitch.cos() * yaw.cos();
424
425 let transform = Transform::from_xyz(x, y, z).looking_at(Vec3::ZERO, Vec3::Y);
426 views.push(transform);
427 }
428 }
429 views
430}
431
432#[derive(Component)]
434pub struct CaptureTarget;
435
436#[derive(Component)]
438pub struct CaptureCamera;
439
440#[derive(Clone, Debug, PartialEq)]
448pub struct RenderConfig {
449 pub width: u32,
451 pub height: u32,
453 pub zoom: f32,
456 pub near_plane: f32,
458 pub far_plane: f32,
460 pub lighting: LightingConfig,
462}
463
464#[derive(Clone, Debug, PartialEq)]
468pub struct LightingConfig {
469 pub ambient_brightness: f32,
471 pub key_light_intensity: f32,
473 pub key_light_position: [f32; 3],
475 pub fill_light_intensity: f32,
477 pub fill_light_position: [f32; 3],
479 pub shadows_enabled: bool,
481}
482
483impl Default for LightingConfig {
484 fn default() -> Self {
485 Self {
486 ambient_brightness: 0.3,
487 key_light_intensity: 1500.0,
488 key_light_position: [4.0, 8.0, 4.0],
489 fill_light_intensity: 500.0,
490 fill_light_position: [-4.0, 2.0, -4.0],
491 shadows_enabled: false,
492 }
493 }
494}
495
496impl LightingConfig {
497 pub fn bright() -> Self {
499 Self {
500 ambient_brightness: 0.5,
501 key_light_intensity: 2000.0,
502 key_light_position: [4.0, 8.0, 4.0],
503 fill_light_intensity: 800.0,
504 fill_light_position: [-4.0, 2.0, -4.0],
505 shadows_enabled: false,
506 }
507 }
508
509 pub fn soft() -> Self {
511 Self {
512 ambient_brightness: 0.4,
513 key_light_intensity: 1000.0,
514 key_light_position: [3.0, 6.0, 3.0],
515 fill_light_intensity: 600.0,
516 fill_light_position: [-3.0, 3.0, -3.0],
517 shadows_enabled: false,
518 }
519 }
520
521 pub fn unlit() -> Self {
523 Self {
524 ambient_brightness: 1.0,
525 key_light_intensity: 0.0,
526 key_light_position: [0.0, 0.0, 0.0],
527 fill_light_intensity: 0.0,
528 fill_light_position: [0.0, 0.0, 0.0],
529 shadows_enabled: false,
530 }
531 }
532}
533
534impl Default for RenderConfig {
535 fn default() -> Self {
536 Self::tbp_default()
537 }
538}
539
540impl RenderConfig {
541 pub fn tbp_default() -> Self {
549 Self {
550 width: 64,
551 height: 64,
552 zoom: 4.0,
553 near_plane: 0.01,
554 far_plane: 10.0,
555 lighting: LightingConfig::default(),
556 }
557 }
558
559 pub fn preview() -> Self {
561 Self {
562 width: 256,
563 height: 256,
564 zoom: 1.0,
565 near_plane: 0.01,
566 far_plane: 10.0,
567 lighting: LightingConfig::default(),
568 }
569 }
570
571 pub fn high_res() -> Self {
573 Self {
574 width: 512,
575 height: 512,
576 zoom: 1.0,
577 near_plane: 0.01,
578 far_plane: 10.0,
579 lighting: LightingConfig::default(),
580 }
581 }
582
583 pub fn fov_radians(&self) -> f32 {
590 let base_hfov_rad = 90.0_f32.to_radians();
591 let half_tan = (base_hfov_rad / 2.0).tan() / self.zoom;
592 2.0 * half_tan.atan()
593 }
594
595 pub fn intrinsics(&self) -> CameraIntrinsics {
603 let base_hfov_rad = 90.0_f64.to_radians();
604 let fx_norm = (base_hfov_rad / 2.0).tan() / self.zoom as f64;
606 let fx = (self.width as f64 / 2.0) / fx_norm;
608 let fy = fx; CameraIntrinsics {
611 focal_length: [fx, fy],
612 principal_point: [self.width as f64 / 2.0, self.height as f64 / 2.0],
613 image_size: [self.width, self.height],
614 }
615 }
616}
617
618#[derive(Clone, Debug, PartialEq)]
623pub struct CameraIntrinsics {
624 pub focal_length: [f64; 2],
626 pub principal_point: [f64; 2],
628 pub image_size: [u32; 2],
630}
631
632impl CameraIntrinsics {
633 pub fn project(&self, point: Vec3) -> Option<[f64; 2]> {
635 if point.z <= 0.0 {
636 return None;
637 }
638 let x = (point.x as f64 / point.z as f64) * self.focal_length[0] + self.principal_point[0];
639 let y = (point.y as f64 / point.z as f64) * self.focal_length[1] + self.principal_point[1];
640 Some([x, y])
641 }
642
643 pub fn unproject(&self, pixel: [f64; 2], depth: f64) -> [f64; 3] {
645 let x = (pixel[0] - self.principal_point[0]) / self.focal_length[0] * depth;
646 let y = (pixel[1] - self.principal_point[1]) / self.focal_length[1] * depth;
647 [x, y, depth]
648 }
649}
650
651#[derive(Clone, Debug)]
653pub struct RenderOutput {
654 pub rgba: Vec<u8>,
656 pub depth: Vec<f64>,
660 pub width: u32,
662 pub height: u32,
664 pub intrinsics: CameraIntrinsics,
666 pub camera_transform: Transform,
668 pub object_rotation: ObjectRotation,
670}
671
672impl RenderOutput {
673 pub fn get_rgba(&self, x: u32, y: u32) -> Option<[u8; 4]> {
675 if x >= self.width || y >= self.height {
676 return None;
677 }
678 let idx = ((y * self.width + x) * 4) as usize;
679 Some([
680 self.rgba[idx],
681 self.rgba[idx + 1],
682 self.rgba[idx + 2],
683 self.rgba[idx + 3],
684 ])
685 }
686
687 pub fn get_depth(&self, x: u32, y: u32) -> Option<f64> {
689 if x >= self.width || y >= self.height {
690 return None;
691 }
692 let idx = (y * self.width + x) as usize;
693 Some(self.depth[idx])
694 }
695
696 pub fn get_rgb(&self, x: u32, y: u32) -> Option<[u8; 3]> {
698 self.get_rgba(x, y).map(|rgba| [rgba[0], rgba[1], rgba[2]])
699 }
700
701 pub fn to_rgb_image(&self) -> Vec<Vec<[u8; 3]>> {
703 let mut image = Vec::with_capacity(self.height as usize);
704 for y in 0..self.height {
705 let mut row = Vec::with_capacity(self.width as usize);
706 for x in 0..self.width {
707 row.push(self.get_rgb(x, y).unwrap_or([0, 0, 0]));
708 }
709 image.push(row);
710 }
711 image
712 }
713
714 pub fn to_depth_image(&self) -> Vec<Vec<f64>> {
716 let mut image = Vec::with_capacity(self.height as usize);
717 for y in 0..self.height {
718 let mut row = Vec::with_capacity(self.width as usize);
719 for x in 0..self.width {
720 row.push(self.get_depth(x, y).unwrap_or(0.0));
721 }
722 image.push(row);
723 }
724 image
725 }
726}
727
728#[derive(Debug, Clone)]
730pub enum RenderError {
731 MeshNotFound(String),
733 TextureNotFound(String),
735 FileNotFound { path: String, reason: String },
737 FileWriteFailed { path: String, reason: String },
739 DirectoryCreationFailed { path: String, reason: String },
741 RenderFailed(String),
743 InvalidConfig(String),
745 InvalidInput(String),
747 SerializationError(String),
749 DataParsingError(String),
751 RenderTimeout { duration_secs: u64 },
753}
754
755impl std::fmt::Display for RenderError {
756 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
757 match self {
758 RenderError::MeshNotFound(path) => write!(f, "Mesh not found: {}", path),
759 RenderError::TextureNotFound(path) => write!(f, "Texture not found: {}", path),
760 RenderError::FileNotFound { path, reason } => {
761 write!(f, "File not found at {}: {}", path, reason)
762 }
763 RenderError::FileWriteFailed { path, reason } => {
764 write!(f, "Failed to write file {}: {}", path, reason)
765 }
766 RenderError::DirectoryCreationFailed { path, reason } => {
767 write!(f, "Failed to create directory {}: {}", path, reason)
768 }
769 RenderError::RenderFailed(msg) => write!(f, "Render failed: {}", msg),
770 RenderError::InvalidConfig(msg) => write!(f, "Invalid config: {}", msg),
771 RenderError::InvalidInput(msg) => write!(f, "Invalid input: {}", msg),
772 RenderError::SerializationError(msg) => write!(f, "Serialization error: {}", msg),
773 RenderError::DataParsingError(msg) => write!(f, "Data parsing error: {}", msg),
774 RenderError::RenderTimeout { duration_secs } => {
775 write!(f, "Render timeout after {} seconds", duration_secs)
776 }
777 }
778 }
779}
780
781impl std::error::Error for RenderError {}
782
783pub fn render_to_buffer(
808 object_dir: &Path,
809 camera_transform: &Transform,
810 object_rotation: &ObjectRotation,
811 config: &RenderConfig,
812) -> Result<RenderOutput, RenderError> {
813 render::render_headless(object_dir, camera_transform, object_rotation, config)
815}
816
817pub fn render_all_viewpoints(
830 object_dir: &Path,
831 viewpoint_config: &ViewpointConfig,
832 rotations: &[ObjectRotation],
833 render_config: &RenderConfig,
834) -> Result<Vec<RenderOutput>, RenderError> {
835 let viewpoints = generate_viewpoints(viewpoint_config);
836 let mut outputs = Vec::with_capacity(viewpoints.len() * rotations.len());
837
838 for rotation in rotations {
839 for viewpoint in &viewpoints {
840 let output = render_to_buffer(object_dir, viewpoint, rotation, render_config)?;
841 outputs.push(output);
842 }
843 }
844
845 Ok(outputs)
846}
847
848pub fn render_to_buffer_cached(
916 object_dir: &Path,
917 camera_transform: &Transform,
918 object_rotation: &ObjectRotation,
919 config: &RenderConfig,
920 cache: &mut cache::ModelCache,
921) -> Result<RenderOutput, RenderError> {
922 let mesh_path = object_dir.join("google_16k/textured.obj");
923 let texture_path = object_dir.join("google_16k/texture_map.png");
924
925 cache.cache_scene(mesh_path.clone());
927 cache.cache_texture(texture_path.clone());
928
929 render::render_headless(object_dir, camera_transform, object_rotation, config)
931}
932
933pub fn render_to_files(
950 object_dir: &Path,
951 camera_transform: &Transform,
952 object_rotation: &ObjectRotation,
953 config: &RenderConfig,
954 rgba_path: &Path,
955 depth_path: &Path,
956) -> Result<(), RenderError> {
957 render::render_to_files(
958 object_dir,
959 camera_transform,
960 object_rotation,
961 config,
962 rgba_path,
963 depth_path,
964 )
965}
966
967pub use batch::{
969 BatchRenderConfig, BatchRenderError, BatchRenderOutput, BatchRenderRequest, BatchRenderer,
970 BatchState, RenderStatus,
971};
972
973pub fn create_batch_renderer(config: &BatchRenderConfig) -> Result<BatchRenderer, RenderError> {
991 Ok(BatchRenderer::new(config.clone()))
992}
993
994pub fn queue_render_request(
1019 renderer: &mut BatchRenderer,
1020 request: BatchRenderRequest,
1021) -> Result<(), RenderError> {
1022 renderer
1023 .queue_request(request)
1024 .map_err(|e| RenderError::RenderFailed(e.to_string()))
1025}
1026
1027pub fn render_next_in_batch(
1049 renderer: &mut BatchRenderer,
1050 _timeout_ms: u32,
1051) -> Result<Option<BatchRenderOutput>, RenderError> {
1052 if let Some(request) = renderer.pending_requests.pop_front() {
1053 let output = render_to_buffer(
1054 &request.object_dir,
1055 &request.viewpoint,
1056 &request.object_rotation,
1057 &request.render_config,
1058 )?;
1059 let batch_output = BatchRenderOutput::from_render_output(request, output);
1060 renderer.completed_results.push(batch_output.clone());
1061 renderer.renders_processed += 1;
1062 Ok(Some(batch_output))
1063 } else {
1064 Ok(None)
1065 }
1066}
1067
1068pub fn render_batch(
1087 requests: Vec<BatchRenderRequest>,
1088 config: &BatchRenderConfig,
1089) -> Result<Vec<BatchRenderOutput>, RenderError> {
1090 if requests.is_empty() {
1091 return Ok(Vec::new());
1092 }
1093
1094 if requests.len() > 1 && requests_share_batch_context(&requests) {
1095 let first_request = requests[0].clone();
1096 let viewpoints: Vec<Transform> = requests.iter().map(|request| request.viewpoint).collect();
1097 let outputs = render::render_headless_sequence(
1098 &first_request.object_dir,
1099 &viewpoints,
1100 &first_request.object_rotation,
1101 &first_request.render_config,
1102 )?;
1103
1104 return Ok(requests
1105 .into_iter()
1106 .zip(outputs)
1107 .map(|(request, output)| BatchRenderOutput::from_render_output(request, output))
1108 .collect());
1109 }
1110
1111 let mut renderer = create_batch_renderer(config)?;
1112
1113 for request in requests {
1115 queue_render_request(&mut renderer, request)?;
1116 }
1117
1118 let mut results = Vec::new();
1120 while let Some(output) = render_next_in_batch(&mut renderer, config.frame_timeout_ms)? {
1121 results.push(output);
1122 }
1123
1124 Ok(results)
1125}
1126
1127fn requests_share_batch_context(requests: &[BatchRenderRequest]) -> bool {
1128 let Some(first) = requests.first() else {
1129 return true;
1130 };
1131
1132 requests.iter().all(|request| {
1133 request.object_dir == first.object_dir
1134 && request.object_rotation == first.object_rotation
1135 && request.render_config == first.render_config
1136 })
1137}
1138
1139pub use bevy::prelude::{Quat, Transform, Vec3};
1141
1142#[cfg(test)]
1143mod tests {
1144 use super::*;
1145
1146 #[test]
1147 fn test_object_rotation_identity() {
1148 let rot = ObjectRotation::identity();
1149 assert_eq!(rot.pitch, 0.0);
1150 assert_eq!(rot.yaw, 0.0);
1151 assert_eq!(rot.roll, 0.0);
1152 }
1153
1154 #[test]
1155 fn test_object_rotation_from_array() {
1156 let rot = ObjectRotation::from_array([10.0, 20.0, 30.0]);
1157 assert_eq!(rot.pitch, 10.0);
1158 assert_eq!(rot.yaw, 20.0);
1159 assert_eq!(rot.roll, 30.0);
1160 }
1161
1162 #[test]
1163 fn test_requests_share_batch_context_for_homogeneous_batch() {
1164 let config = RenderConfig::tbp_default();
1165 let request = BatchRenderRequest {
1166 object_dir: "/tmp/ycb/003_cracker_box".into(),
1167 viewpoint: Transform::IDENTITY,
1168 object_rotation: ObjectRotation::identity(),
1169 render_config: config.clone(),
1170 };
1171
1172 assert!(requests_share_batch_context(&[
1173 request.clone(),
1174 BatchRenderRequest {
1175 viewpoint: Transform::from_xyz(1.0, 0.0, 0.0),
1176 ..request
1177 },
1178 ]));
1179 }
1180
1181 #[test]
1182 fn test_requests_share_batch_context_rejects_mixed_objects() {
1183 let config = RenderConfig::tbp_default();
1184 let request = BatchRenderRequest {
1185 object_dir: "/tmp/ycb/003_cracker_box".into(),
1186 viewpoint: Transform::IDENTITY,
1187 object_rotation: ObjectRotation::identity(),
1188 render_config: config.clone(),
1189 };
1190
1191 assert!(!requests_share_batch_context(&[
1192 request.clone(),
1193 BatchRenderRequest {
1194 object_dir: "/tmp/ycb/005_tomato_soup_can".into(),
1195 ..request
1196 },
1197 ]));
1198 }
1199
1200 #[test]
1201 fn test_tbp_benchmark_rotations() {
1202 let rotations = ObjectRotation::tbp_benchmark_rotations();
1203 assert_eq!(rotations.len(), 3);
1204 assert_eq!(rotations[0], ObjectRotation::from_array([0.0, 0.0, 0.0]));
1205 assert_eq!(rotations[1], ObjectRotation::from_array([0.0, 90.0, 0.0]));
1206 assert_eq!(rotations[2], ObjectRotation::from_array([0.0, 180.0, 0.0]));
1207 }
1208
1209 #[test]
1210 fn test_tbp_known_orientations_count() {
1211 let orientations = ObjectRotation::tbp_known_orientations();
1212 assert_eq!(orientations.len(), 14);
1213 }
1214
1215 #[test]
1216 fn test_rotation_to_quat() {
1217 let rot = ObjectRotation::identity();
1218 let quat = rot.to_quat();
1219 assert!((quat.w - 1.0).abs() < 0.001);
1221 assert!(quat.x.abs() < 0.001);
1222 assert!(quat.y.abs() < 0.001);
1223 assert!(quat.z.abs() < 0.001);
1224 }
1225
1226 #[test]
1227 fn test_rotation_90_yaw() {
1228 let rot = ObjectRotation::new(0.0, 90.0, 0.0);
1229 let quat = rot.to_quat();
1230 assert!((quat.w - 0.707).abs() < 0.01);
1232 assert!((quat.y - 0.707).abs() < 0.01);
1233 }
1234
1235 #[test]
1236 fn test_viewpoint_config_default() {
1237 let config = ViewpointConfig::default();
1238 assert_eq!(config.radius, 0.5);
1239 assert_eq!(config.yaw_count, 8);
1240 assert_eq!(config.pitch_angles_deg.len(), 3);
1241 }
1242
1243 #[test]
1244 fn test_viewpoint_count() {
1245 let config = ViewpointConfig::default();
1246 assert_eq!(config.viewpoint_count(), 24); }
1248
1249 #[test]
1250 fn test_generate_viewpoints_count() {
1251 let config = ViewpointConfig::default();
1252 let viewpoints = generate_viewpoints(&config);
1253 assert_eq!(viewpoints.len(), 24);
1254 }
1255
1256 #[test]
1257 fn test_viewpoints_spherical_radius() {
1258 let config = ViewpointConfig::default();
1259 let viewpoints = generate_viewpoints(&config);
1260
1261 for (i, transform) in viewpoints.iter().enumerate() {
1262 let actual_radius = transform.translation.length();
1263 assert!(
1264 (actual_radius - config.radius).abs() < 0.001,
1265 "Viewpoint {} has incorrect radius: {} (expected {})",
1266 i,
1267 actual_radius,
1268 config.radius
1269 );
1270 }
1271 }
1272
1273 #[test]
1274 fn test_viewpoints_looking_at_origin() {
1275 let config = ViewpointConfig::default();
1276 let viewpoints = generate_viewpoints(&config);
1277
1278 for (i, transform) in viewpoints.iter().enumerate() {
1279 let forward = transform.forward();
1280 let to_origin = (Vec3::ZERO - transform.translation).normalize();
1281 let dot = forward.dot(to_origin);
1282 assert!(
1283 dot > 0.99,
1284 "Viewpoint {} not looking at origin, dot product: {}",
1285 i,
1286 dot
1287 );
1288 }
1289 }
1290
1291 #[test]
1292 fn test_sensor_config_default() {
1293 let config = SensorConfig::default();
1294 assert_eq!(config.object_rotations.len(), 1);
1295 assert_eq!(config.total_captures(), 24);
1296 }
1297
1298 #[test]
1299 fn test_sensor_config_tbp_benchmark() {
1300 let config = SensorConfig::tbp_benchmark();
1301 assert_eq!(config.object_rotations.len(), 3);
1302 assert_eq!(config.total_captures(), 72); }
1304
1305 #[test]
1306 fn test_sensor_config_tbp_full() {
1307 let config = SensorConfig::tbp_full_training();
1308 assert_eq!(config.object_rotations.len(), 14);
1309 assert_eq!(config.total_captures(), 336); }
1311
1312 #[test]
1313 fn test_ycb_representative_objects() {
1314 assert_eq!(crate::ycb::REPRESENTATIVE_OBJECTS.len(), 3);
1316 assert!(crate::ycb::REPRESENTATIVE_OBJECTS.contains(&"003_cracker_box"));
1317 }
1318
1319 #[test]
1320 #[allow(deprecated)]
1321 fn test_ycb_ten_objects() {
1322 assert_eq!(crate::ycb::TEN_OBJECTS.len(), 10);
1324 }
1325
1326 #[test]
1327 fn test_ycb_object_mesh_path() {
1328 let path = crate::ycb::object_mesh_path("/tmp/ycb", "003_cracker_box");
1329 assert_eq!(
1330 path,
1331 std::path::Path::new("/tmp/ycb")
1332 .join("003_cracker_box")
1333 .join("google_16k")
1334 .join("textured.obj")
1335 );
1336 }
1337
1338 #[test]
1339 fn test_ycb_object_texture_path() {
1340 let path = crate::ycb::object_texture_path("/tmp/ycb", "003_cracker_box");
1341 assert_eq!(
1342 path,
1343 std::path::Path::new("/tmp/ycb")
1344 .join("003_cracker_box")
1345 .join("google_16k")
1346 .join("texture_map.png")
1347 );
1348 }
1349
1350 #[test]
1355 fn test_render_config_tbp_default() {
1356 let config = RenderConfig::tbp_default();
1357 assert_eq!(config.width, 64);
1359 assert_eq!(config.height, 64);
1360 assert!(config.zoom > 0.0);
1362 assert!(config.near_plane > 0.0);
1364 assert!(config.far_plane > config.near_plane);
1365 }
1366
1367 #[test]
1368 fn test_render_config_preview() {
1369 let config = RenderConfig::preview();
1370 assert_eq!(config.width, 256);
1371 assert_eq!(config.height, 256);
1372 }
1373
1374 #[test]
1375 fn test_render_config_default_is_tbp() {
1376 let default = RenderConfig::default();
1377 let tbp = RenderConfig::tbp_default();
1378 assert_eq!(default.width, tbp.width);
1379 assert_eq!(default.height, tbp.height);
1380 }
1381
1382 #[test]
1383 fn test_render_config_fov() {
1384 let config = RenderConfig::tbp_default();
1385 let fov = config.fov_radians();
1386 assert!(fov > 0.0);
1389 assert!(fov < PI);
1390
1391 let zoomed = RenderConfig {
1393 zoom: config.zoom * 2.0,
1394 ..config
1395 };
1396 assert!(zoomed.fov_radians() < fov);
1397 }
1398
1399 #[test]
1400 fn test_render_config_intrinsics() {
1401 let config = RenderConfig::tbp_default();
1402 let intrinsics = config.intrinsics();
1403
1404 assert_eq!(intrinsics.image_size, [config.width, config.height]);
1406 assert_eq!(
1407 intrinsics.principal_point,
1408 [config.width as f64 / 2.0, config.height as f64 / 2.0]
1409 );
1410 assert_eq!(intrinsics.focal_length[0], intrinsics.focal_length[1]);
1412 assert!(intrinsics.focal_length[0] > 0.0);
1413 }
1414
1415 #[test]
1416 fn test_camera_intrinsics_project() {
1417 let intrinsics = CameraIntrinsics {
1418 focal_length: [100.0, 100.0],
1419 principal_point: [32.0, 32.0],
1420 image_size: [64, 64],
1421 };
1422
1423 let center = intrinsics.project(Vec3::new(0.0, 0.0, 1.0));
1425 assert!(center.is_some());
1426 let [x, y] = center.unwrap();
1427 assert!((x - 32.0).abs() < 0.001);
1428 assert!((y - 32.0).abs() < 0.001);
1429
1430 let behind = intrinsics.project(Vec3::new(0.0, 0.0, -1.0));
1432 assert!(behind.is_none());
1433 }
1434
1435 #[test]
1436 fn test_camera_intrinsics_unproject() {
1437 let intrinsics = CameraIntrinsics {
1438 focal_length: [100.0, 100.0],
1439 principal_point: [32.0, 32.0],
1440 image_size: [64, 64],
1441 };
1442
1443 let point = intrinsics.unproject([32.0, 32.0], 1.0);
1445 assert!((point[0]).abs() < 0.001); assert!((point[1]).abs() < 0.001); assert!((point[2] - 1.0).abs() < 0.001); }
1449
1450 #[test]
1451 fn test_render_output_get_rgba() {
1452 let output = RenderOutput {
1453 rgba: vec![
1454 255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 255, 255, 255, 255,
1455 ],
1456 depth: vec![1.0, 2.0, 3.0, 4.0],
1457 width: 2,
1458 height: 2,
1459 intrinsics: RenderConfig::tbp_default().intrinsics(),
1460 camera_transform: Transform::IDENTITY,
1461 object_rotation: ObjectRotation::identity(),
1462 };
1463
1464 assert_eq!(output.get_rgba(0, 0), Some([255, 0, 0, 255]));
1466 assert_eq!(output.get_rgba(1, 0), Some([0, 255, 0, 255]));
1468 assert_eq!(output.get_rgba(0, 1), Some([0, 0, 255, 255]));
1470 assert_eq!(output.get_rgba(1, 1), Some([255, 255, 255, 255]));
1472 assert_eq!(output.get_rgba(2, 0), None);
1474 }
1475
1476 #[test]
1477 fn test_render_output_get_depth() {
1478 let output = RenderOutput {
1479 rgba: vec![0u8; 16],
1480 depth: vec![1.0, 2.0, 3.0, 4.0],
1481 width: 2,
1482 height: 2,
1483 intrinsics: RenderConfig::tbp_default().intrinsics(),
1484 camera_transform: Transform::IDENTITY,
1485 object_rotation: ObjectRotation::identity(),
1486 };
1487
1488 assert_eq!(output.get_depth(0, 0), Some(1.0));
1489 assert_eq!(output.get_depth(1, 0), Some(2.0));
1490 assert_eq!(output.get_depth(0, 1), Some(3.0));
1491 assert_eq!(output.get_depth(1, 1), Some(4.0));
1492 assert_eq!(output.get_depth(2, 0), None);
1493 }
1494
1495 #[test]
1496 fn test_render_output_to_rgb_image() {
1497 let output = RenderOutput {
1498 rgba: vec![
1499 255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 255, 255, 255, 255,
1500 ],
1501 depth: vec![1.0, 2.0, 3.0, 4.0],
1502 width: 2,
1503 height: 2,
1504 intrinsics: RenderConfig::tbp_default().intrinsics(),
1505 camera_transform: Transform::IDENTITY,
1506 object_rotation: ObjectRotation::identity(),
1507 };
1508
1509 let image = output.to_rgb_image();
1510 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]); }
1517
1518 #[test]
1519 fn test_render_output_to_depth_image() {
1520 let output = RenderOutput {
1521 rgba: vec![0u8; 16],
1522 depth: vec![1.0, 2.0, 3.0, 4.0],
1523 width: 2,
1524 height: 2,
1525 intrinsics: RenderConfig::tbp_default().intrinsics(),
1526 camera_transform: Transform::IDENTITY,
1527 object_rotation: ObjectRotation::identity(),
1528 };
1529
1530 let depth_image = output.to_depth_image();
1531 assert_eq!(depth_image.len(), 2);
1532 assert_eq!(depth_image[0], vec![1.0, 2.0]);
1533 assert_eq!(depth_image[1], vec![3.0, 4.0]);
1534 }
1535
1536 #[test]
1537 fn test_render_error_display() {
1538 let err = RenderError::MeshNotFound("/path/to/mesh.obj".to_string());
1539 assert!(err.to_string().contains("Mesh not found"));
1540 assert!(err.to_string().contains("/path/to/mesh.obj"));
1541 }
1542
1543 #[test]
1548 fn test_object_rotation_extreme_angles() {
1549 let rot = ObjectRotation::new(450.0, -720.0, 1080.0);
1551 let quat = rot.to_quat();
1552 assert!((quat.length() - 1.0).abs() < 0.001);
1554 }
1555
1556 #[test]
1557 fn test_object_rotation_to_transform() {
1558 let rot = ObjectRotation::new(45.0, 90.0, 0.0);
1559 let transform = rot.to_transform();
1560 assert_eq!(transform.translation, Vec3::ZERO);
1562 assert!(transform.rotation != Quat::IDENTITY);
1564 }
1565
1566 #[test]
1567 fn test_viewpoint_config_single_viewpoint() {
1568 let config = ViewpointConfig {
1569 radius: 1.0,
1570 yaw_count: 1,
1571 pitch_angles_deg: vec![0.0],
1572 };
1573 assert_eq!(config.viewpoint_count(), 1);
1574 let viewpoints = generate_viewpoints(&config);
1575 assert_eq!(viewpoints.len(), 1);
1576 let pos = viewpoints[0].translation;
1578 assert!((pos.x).abs() < 0.001);
1579 assert!((pos.y).abs() < 0.001);
1580 assert!((pos.z - 1.0).abs() < 0.001);
1581 }
1582
1583 #[test]
1584 fn test_viewpoint_radius_scaling() {
1585 let config1 = ViewpointConfig {
1586 radius: 0.5,
1587 yaw_count: 4,
1588 pitch_angles_deg: vec![0.0],
1589 };
1590 let config2 = ViewpointConfig {
1591 radius: 2.0,
1592 yaw_count: 4,
1593 pitch_angles_deg: vec![0.0],
1594 };
1595
1596 let v1 = generate_viewpoints(&config1);
1597 let v2 = generate_viewpoints(&config2);
1598
1599 for (vp1, vp2) in v1.iter().zip(v2.iter()) {
1601 let ratio = vp2.translation.length() / vp1.translation.length();
1602 assert!((ratio - 4.0).abs() < 0.01); }
1604 }
1605
1606 #[test]
1607 fn test_camera_intrinsics_project_at_z_zero() {
1608 let intrinsics = CameraIntrinsics {
1609 focal_length: [100.0, 100.0],
1610 principal_point: [32.0, 32.0],
1611 image_size: [64, 64],
1612 };
1613
1614 let result = intrinsics.project(Vec3::new(1.0, 1.0, 0.0));
1616 assert!(result.is_none());
1617 }
1618
1619 #[test]
1620 fn test_camera_intrinsics_roundtrip() {
1621 let intrinsics = CameraIntrinsics {
1622 focal_length: [100.0, 100.0],
1623 principal_point: [32.0, 32.0],
1624 image_size: [64, 64],
1625 };
1626
1627 let original = Vec3::new(0.5, -0.3, 2.0);
1629 let projected = intrinsics.project(original).unwrap();
1630
1631 let unprojected = intrinsics.unproject(projected, original.z as f64);
1633
1634 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); }
1639
1640 #[test]
1641 fn test_render_output_empty() {
1642 let output = RenderOutput {
1643 rgba: vec![],
1644 depth: vec![],
1645 width: 0,
1646 height: 0,
1647 intrinsics: RenderConfig::tbp_default().intrinsics(),
1648 camera_transform: Transform::IDENTITY,
1649 object_rotation: ObjectRotation::identity(),
1650 };
1651
1652 assert_eq!(output.get_rgba(0, 0), None);
1654 assert_eq!(output.get_depth(0, 0), None);
1655 assert!(output.to_rgb_image().is_empty());
1656 assert!(output.to_depth_image().is_empty());
1657 }
1658
1659 #[test]
1660 fn test_render_output_1x1() {
1661 let output = RenderOutput {
1662 rgba: vec![128, 64, 32, 255],
1663 depth: vec![0.5],
1664 width: 1,
1665 height: 1,
1666 intrinsics: RenderConfig::tbp_default().intrinsics(),
1667 camera_transform: Transform::IDENTITY,
1668 object_rotation: ObjectRotation::identity(),
1669 };
1670
1671 assert_eq!(output.get_rgba(0, 0), Some([128, 64, 32, 255]));
1672 assert_eq!(output.get_depth(0, 0), Some(0.5));
1673 assert_eq!(output.get_rgb(0, 0), Some([128, 64, 32]));
1674
1675 let rgb_img = output.to_rgb_image();
1676 assert_eq!(rgb_img.len(), 1);
1677 assert_eq!(rgb_img[0].len(), 1);
1678 assert_eq!(rgb_img[0][0], [128, 64, 32]);
1679 }
1680
1681 #[test]
1682 fn test_render_config_high_res() {
1683 let config = RenderConfig::high_res();
1684 assert_eq!(config.width, 512);
1685 assert_eq!(config.height, 512);
1686
1687 let intrinsics = config.intrinsics();
1688 assert_eq!(intrinsics.image_size, [512, 512]);
1689 assert_eq!(intrinsics.principal_point, [256.0, 256.0]);
1690 }
1691
1692 #[test]
1693 fn test_render_config_zoom_affects_fov() {
1694 let base = RenderConfig {
1699 zoom: 2.0,
1700 ..RenderConfig::tbp_default()
1701 };
1702 let doubled = RenderConfig {
1703 zoom: 4.0,
1704 ..RenderConfig::tbp_default()
1705 };
1706
1707 assert!(doubled.fov_radians() < base.fov_radians());
1709
1710 let base_half_tan = (base.fov_radians() / 2.0).tan();
1712 let doubled_half_tan = (doubled.fov_radians() / 2.0).tan();
1713 assert!((base_half_tan / doubled_half_tan - 2.0).abs() < 1e-4);
1714 }
1715
1716 #[test]
1717 fn test_render_config_zoom_affects_intrinsics() {
1718 let a = RenderConfig {
1721 zoom: 2.0,
1722 ..RenderConfig::tbp_default()
1723 };
1724 let b = RenderConfig {
1725 zoom: 4.0,
1726 ..RenderConfig::tbp_default()
1727 };
1728
1729 let fx_a = a.intrinsics().focal_length[0];
1730 let fx_b = b.intrinsics().focal_length[0];
1731
1732 assert!(fx_b > fx_a);
1734
1735 assert!((fx_a / a.zoom as f64 - fx_b / b.zoom as f64).abs() < 1e-9);
1737 }
1738
1739 #[test]
1740 fn test_lighting_config_variants() {
1741 let default = LightingConfig::default();
1742 let bright = LightingConfig::bright();
1743 let soft = LightingConfig::soft();
1744 let unlit = LightingConfig::unlit();
1745
1746 assert!(bright.key_light_intensity > default.key_light_intensity);
1748
1749 assert_eq!(unlit.key_light_intensity, 0.0);
1751 assert_eq!(unlit.fill_light_intensity, 0.0);
1752 assert_eq!(unlit.ambient_brightness, 1.0);
1753
1754 assert!(soft.key_light_intensity < default.key_light_intensity);
1756 }
1757
1758 #[test]
1759 fn test_all_render_error_variants() {
1760 let errors = vec![
1761 RenderError::MeshNotFound("mesh.obj".to_string()),
1762 RenderError::TextureNotFound("texture.png".to_string()),
1763 RenderError::RenderFailed("GPU error".to_string()),
1764 RenderError::InvalidConfig("bad config".to_string()),
1765 ];
1766
1767 for err in errors {
1768 let msg = err.to_string();
1770 assert!(!msg.is_empty());
1771 }
1772 }
1773
1774 #[test]
1775 fn test_tbp_known_orientations_unique() {
1776 let orientations = ObjectRotation::tbp_known_orientations();
1777
1778 let quats: Vec<Quat> = orientations.iter().map(|r| r.to_quat()).collect();
1780
1781 for (i, q1) in quats.iter().enumerate() {
1782 for (j, q2) in quats.iter().enumerate() {
1783 if i != j {
1784 let dot = q1.dot(*q2).abs();
1786 assert!(
1787 dot < 0.999,
1788 "Orientations {} and {} produce same quaternion",
1789 i,
1790 j
1791 );
1792 }
1793 }
1794 }
1795 }
1796}