use bevy::prelude::*;
use std::f32::consts::PI;
use std::path::Path;
mod render;
pub mod batch;
pub mod backend;
pub mod cache;
pub mod fixtures;
pub use ycbust::{
self, DownloadOptions, Subset as YcbSubset, REPRESENTATIVE_OBJECTS, TBP_SIMILAR_OBJECTS,
TBP_STANDARD_OBJECTS,
};
pub mod ycb {
pub use ycbust::{
download_ycb, DownloadOptions, Subset, REPRESENTATIVE_OBJECTS, TBP_SIMILAR_OBJECTS,
TBP_STANDARD_OBJECTS,
};
use std::path::Path;
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(())
}
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(())
}
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(())
}
pub fn models_exist<P: AsRef<Path>>(output_dir: P) -> bool {
ycbust::object_mesh_path(output_dir.as_ref(), "003_cracker_box").exists()
}
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)
}
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)
}
}
pub fn initialize() {
use std::sync::atomic::{AtomicBool, Ordering};
static INITIALIZED: AtomicBool = AtomicBool::new(false);
if !INITIALIZED.swap(true, Ordering::SeqCst) {
let config = backend::BackendConfig::new();
config.apply_env();
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct ObjectRotation {
pub pitch: f64,
pub yaw: f64,
pub roll: f64,
}
impl ObjectRotation {
pub fn new(pitch: f64, yaw: f64, roll: f64) -> Self {
Self { pitch, yaw, roll }
}
pub fn from_array(arr: [f64; 3]) -> Self {
Self {
pitch: arr[0],
yaw: arr[1],
roll: arr[2],
}
}
pub fn identity() -> Self {
Self::new(0.0, 0.0, 0.0)
}
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]),
]
}
pub fn tbp_known_orientations() -> 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]), 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]),
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]),
]
}
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(),
)
}
pub fn to_transform(&self) -> Transform {
Transform::from_rotation(self.to_quat())
}
}
impl Default for ObjectRotation {
fn default() -> Self {
Self::identity()
}
}
#[derive(Clone, Debug)]
pub struct ViewpointConfig {
pub radius: f32,
pub yaw_count: usize,
pub pitch_angles_deg: Vec<f32>,
}
impl Default for ViewpointConfig {
fn default() -> Self {
Self {
radius: 0.5,
yaw_count: 8,
pitch_angles_deg: vec![-30.0, 0.0, 30.0],
}
}
}
impl ViewpointConfig {
pub fn viewpoint_count(&self) -> usize {
self.yaw_count * self.pitch_angles_deg.len()
}
}
#[derive(Clone, Debug, Resource)]
pub struct SensorConfig {
pub viewpoints: ViewpointConfig,
pub object_rotations: Vec<ObjectRotation>,
pub output_dir: String,
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 {
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(),
}
}
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(),
}
}
pub fn total_captures(&self) -> usize {
self.viewpoints.viewpoint_count() * self.object_rotations.len()
}
}
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);
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
}
#[derive(Component)]
pub struct CaptureTarget;
#[derive(Component)]
pub struct CaptureCamera;
#[derive(Clone, Debug, PartialEq)]
pub struct RenderConfig {
pub width: u32,
pub height: u32,
pub zoom: f32,
pub near_plane: f32,
pub far_plane: f32,
pub lighting: LightingConfig,
}
#[derive(Clone, Debug, PartialEq)]
pub struct LightingConfig {
pub ambient_brightness: f32,
pub key_light_intensity: f32,
pub key_light_position: [f32; 3],
pub fill_light_intensity: f32,
pub fill_light_position: [f32; 3],
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 {
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,
}
}
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,
}
}
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 {
pub fn tbp_default() -> Self {
Self {
width: 64,
height: 64,
zoom: 4.0,
near_plane: 0.01,
far_plane: 10.0,
lighting: LightingConfig::default(),
}
}
pub fn preview() -> Self {
Self {
width: 256,
height: 256,
zoom: 1.0,
near_plane: 0.01,
far_plane: 10.0,
lighting: LightingConfig::default(),
}
}
pub fn high_res() -> Self {
Self {
width: 512,
height: 512,
zoom: 1.0,
near_plane: 0.01,
far_plane: 10.0,
lighting: LightingConfig::default(),
}
}
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()
}
pub fn intrinsics(&self) -> CameraIntrinsics {
let base_hfov_rad = 90.0_f64.to_radians();
let fx_norm = (base_hfov_rad / 2.0).tan() / self.zoom as f64;
let fx = (self.width as f64 / 2.0) / fx_norm;
let fy = fx;
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],
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct CameraIntrinsics {
pub focal_length: [f64; 2],
pub principal_point: [f64; 2],
pub image_size: [u32; 2],
}
impl CameraIntrinsics {
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])
}
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]
}
}
#[derive(Clone, Debug)]
pub struct RenderOutput {
pub rgba: Vec<u8>,
pub depth: Vec<f64>,
pub width: u32,
pub height: u32,
pub intrinsics: CameraIntrinsics,
pub camera_transform: Transform,
pub object_rotation: ObjectRotation,
}
impl RenderOutput {
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],
])
}
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])
}
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]])
}
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
}
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
}
}
#[derive(Debug, Clone)]
pub enum RenderError {
MeshNotFound(String),
TextureNotFound(String),
FileNotFound { path: String, reason: String },
FileWriteFailed { path: String, reason: String },
DirectoryCreationFailed { path: String, reason: String },
RenderFailed(String),
InvalidConfig(String),
InvalidInput(String),
SerializationError(String),
DataParsingError(String),
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 {}
pub fn render_to_buffer(
object_dir: &Path,
camera_transform: &Transform,
object_rotation: &ObjectRotation,
config: &RenderConfig,
) -> Result<RenderOutput, RenderError> {
render::render_headless(object_dir, camera_transform, object_rotation, config)
}
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)
}
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");
cache.cache_scene(mesh_path.clone());
cache.cache_texture(texture_path.clone());
render::render_headless(object_dir, camera_transform, object_rotation, config)
}
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,
)
}
pub use batch::{
BatchRenderConfig, BatchRenderError, BatchRenderOutput, BatchRenderRequest, BatchRenderer,
BatchState, RenderStatus,
};
pub use render::RenderSession;
pub use render::PersistentRenderer;
pub fn create_batch_renderer(config: &BatchRenderConfig) -> Result<BatchRenderer, RenderError> {
Ok(BatchRenderer::new(config.clone()))
}
pub fn queue_render_request(
renderer: &mut BatchRenderer,
request: BatchRenderRequest,
) -> Result<(), RenderError> {
renderer
.queue_request(request)
.map_err(|e| RenderError::RenderFailed(e.to_string()))
}
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)
}
}
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)?;
for request in requests {
queue_render_request(&mut renderer, request)?;
}
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
})
}
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();
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();
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); }
#[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); }
#[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); }
#[test]
fn test_ycb_representative_objects() {
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")
);
}
#[test]
fn test_render_config_tbp_default() {
let config = RenderConfig::tbp_default();
assert_eq!(config.width, 64);
assert_eq!(config.height, 64);
assert!(config.zoom > 0.0);
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();
assert!(fov > 0.0);
assert!(fov < PI);
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();
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]
);
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],
};
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);
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],
};
let point = intrinsics.unproject([32.0, 32.0], 1.0);
assert!((point[0]).abs() < 0.001); assert!((point[1]).abs() < 0.001); assert!((point[2] - 1.0).abs() < 0.001); }
#[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(),
};
assert_eq!(output.get_rgba(0, 0), Some([255, 0, 0, 255]));
assert_eq!(output.get_rgba(1, 0), Some([0, 255, 0, 255]));
assert_eq!(output.get_rgba(0, 1), Some([0, 0, 255, 255]));
assert_eq!(output.get_rgba(1, 1), Some([255, 255, 255, 255]));
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); 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]); }
#[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"));
}
#[test]
fn test_object_rotation_extreme_angles() {
let rot = ObjectRotation::new(450.0, -720.0, 1080.0);
let quat = rot.to_quat();
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();
assert_eq!(transform.translation, Vec3::ZERO);
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);
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);
for (vp1, vp2) in v1.iter().zip(v2.iter()) {
let ratio = vp2.translation.length() / vp1.translation.length();
assert!((ratio - 4.0).abs() < 0.01); }
}
#[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],
};
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],
};
let original = Vec3::new(0.5, -0.3, 2.0);
let projected = intrinsics.project(original).unwrap();
let unprojected = intrinsics.unproject(projected, original.z as f64);
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); }
#[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(),
};
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() {
let base = RenderConfig {
zoom: 2.0,
..RenderConfig::tbp_default()
};
let doubled = RenderConfig {
zoom: 4.0,
..RenderConfig::tbp_default()
};
assert!(doubled.fov_radians() < base.fov_radians());
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() {
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];
assert!(fx_b > fx_a);
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();
assert!(bright.key_light_intensity > default.key_light_intensity);
assert_eq!(unlit.key_light_intensity, 0.0);
assert_eq!(unlit.fill_light_intensity, 0.0);
assert_eq!(unlit.ambient_brightness, 1.0);
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 {
let msg = err.to_string();
assert!(!msg.is_empty());
}
}
#[test]
fn test_tbp_known_orientations_unique() {
let orientations = ObjectRotation::tbp_known_orientations();
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 {
let dot = q1.dot(*q2).abs();
assert!(
dot < 0.999,
"Orientations {} and {} produce same quaternion",
i,
j
);
}
}
}
}
}