use anyhow::{ensure, Result};
use realsense_rust::{
config::Config,
context::Context,
frame::DepthFrame,
kind::{Rs2Format, Rs2StreamKind},
pipeline::InactivePipeline,
processing_blocks::pointcloud::PointCloud,
};
use rerun::{self as rr, external::glam::Vec3};
use std::{collections::HashSet, convert::TryFrom, time::Duration};
fn main() -> Result<()> {
let rec = rr::RecordingStreamBuilder::new("realsense_pointcloud").spawn()?;
let context = Context::new()?;
let devices = context.query_devices(HashSet::new());
ensure!(!devices.is_empty(), "No devices found");
println!("Found {} device(s), using the first one", devices.len());
let pipeline = InactivePipeline::try_from(&context)?;
let mut config = Config::new();
config.enable_stream(Rs2StreamKind::Depth, Some(0), 640, 480, Rs2Format::Z16, 30)?;
let mut active_pipeline = pipeline.start(Some(config))?;
let mut pointcloud = PointCloud::new(5)?;
println!("Starting 3D point cloud visualization with Rerun.");
println!("Depth data will be converted to 3D points and displayed in Rerun.");
println!("Press Ctrl+C to quit.");
let mut frame_count = 0;
loop {
let frames = active_pipeline.wait(Some(Duration::from_millis(1000)))?;
let depth_frames: Vec<DepthFrame> = frames.frames_of_type();
if let Some(depth_frame) = depth_frames.into_iter().next() {
frame_count += 1;
pointcloud.queue(depth_frame)?;
match pointcloud.wait(Duration::from_millis(100)) {
Ok(points_frame) => {
let mut positions = Vec::new();
let points_count = points_frame.points_count();
let vertices = points_frame.vertices();
for i in (0..points_count).step_by(8) {
let vertex = vertices[i];
if vertex.xyz[0].is_finite()
&& vertex.xyz[1].is_finite()
&& vertex.xyz[2].is_finite()
{
positions.push(Vec3::new(vertex.xyz[0], vertex.xyz[1], vertex.xyz[2]));
}
}
if !positions.is_empty() {
let point_count = positions.len();
rec.log("pointcloud/depth", &rr::Points3D::new(positions))?;
if frame_count % 30 == 0 {
println!(
"Generated point cloud with {} points (frame {})",
point_count, frame_count
);
}
}
}
Err(e) => {
eprintln!("Error generating point cloud: {}", e);
}
}
}
}
}