Skip to main content

draco_io/
obj_writer.rs

1//! OBJ format writer for meshes and point clouds.
2//!
3//! Supports writing:
4//! - Vertex positions
5//! - Triangle faces (for meshes)
6//! - Vertex normals (if present)
7//! - Vertex texture coordinates (if present)
8//!
9//! # Example
10//!
11//! ```no_run
12//! use draco_io::{ObjWriter, PointCloudWriter, Writer};
13//!
14//! let mesh = draco_core::mesh::Mesh::new();
15//! let mut writer = ObjWriter::new();
16//! writer.add_mesh(&mesh, Some("MyMesh"))?;
17//! writer.write("output.obj")?;
18//!
19//! // Or write point cloud
20//! let mut writer = ObjWriter::new();
21//! writer.add_points(&[[0.0, 0.0, 0.0], [1.0, 0.0, 0.0]]);
22//! writer.write("points.obj")?;
23//! # Ok::<(), std::io::Error>(())
24//! ```
25
26use std::fs::File;
27use std::io::{self, BufWriter, Write};
28use std::path::Path;
29
30use draco_core::draco_types::DataType;
31use draco_core::geometry_attribute::GeometryAttributeType;
32use draco_core::geometry_indices::FaceIndex;
33use draco_core::mesh::Mesh;
34
35use crate::traits::{PointCloudWriter, WriteToBytes, Writer};
36
37/// OBJ format writer.
38///
39/// This struct provides a builder-style API for writing OBJ files.
40/// Meshes or points are added, then written with `write()`.
41///
42/// # Example
43///
44/// ```no_run
45/// use draco_io::{ObjWriter, Writer};
46/// # let mesh = draco_core::mesh::Mesh::new();
47///
48/// let mut writer = ObjWriter::new();
49/// writer.add_mesh(&mesh, Some("Cube"))?;
50/// writer.write("cube.obj")?;
51/// # Ok::<(), std::io::Error>(())
52/// ```
53#[derive(Debug, Clone, Default)]
54pub struct ObjWriter {
55    /// Collected vertex positions
56    positions: Vec<[f32; 3]>,
57    /// Collected vertex normals
58    normals: Vec<[f32; 3]>,
59    /// Collected vertex texture coordinates
60    texcoords: Vec<[f32; 2]>,
61    /// Collected faces (1-based indices)
62    faces: Vec<ObjFace>,
63    /// Object groups with (name, start_face_index)
64    groups: Vec<(String, usize)>,
65}
66
67#[derive(Debug, Clone)]
68struct ObjFace {
69    positions: [u32; 3],
70    texcoords: Option<[u32; 3]>,
71    normals: Option<[u32; 3]>,
72}
73
74impl ObjWriter {
75    /// Create a new OBJ writer.
76    pub fn new() -> Self {
77        Self::default()
78    }
79
80    /// Add raw point positions (for point cloud output).
81    pub fn add_points(&mut self, points: &[[f32; 3]]) {
82        self.positions.extend_from_slice(points);
83    }
84
85    /// Add a single point.
86    pub fn add_point(&mut self, point: [f32; 3]) {
87        self.positions.push(point);
88    }
89
90    /// Get the number of vertices added.
91    pub fn vertex_count(&self) -> usize {
92        self.positions.len()
93    }
94
95    /// Get the number of faces added.
96    pub fn face_count(&self) -> usize {
97        self.faces.len()
98    }
99
100    /// Write the OBJ file to the given path.
101    pub fn write<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
102        let file = File::create(path)?;
103        let mut writer = BufWriter::new(file);
104        self.write_to(&mut writer)
105    }
106
107    /// Write the OBJ data to a writer.
108    pub fn write_to<W: Write>(&self, writer: &mut W) -> io::Result<()> {
109        // Header comment
110        writeln!(writer, "# OBJ file generated by draco-io")?;
111        writeln!(writer, "# Vertices: {}", self.positions.len())?;
112        writeln!(writer, "# Faces: {}", self.faces.len())?;
113        writeln!(writer)?;
114
115        // Write all positions
116        for [x, y, z] in &self.positions {
117            writeln!(writer, "v {:.6} {:.6} {:.6}", x, y, z)?;
118        }
119
120        // Write texture coordinates if present
121        if !self.texcoords.is_empty() {
122            writeln!(writer)?;
123            for [u, v] in &self.texcoords {
124                writeln!(writer, "vt {:.6} {:.6}", u, v)?;
125            }
126        }
127
128        // Write normals if present
129        if !self.normals.is_empty() {
130            writeln!(writer)?;
131            for [x, y, z] in &self.normals {
132                writeln!(writer, "vn {:.6} {:.6} {:.6}", x, y, z)?;
133            }
134        }
135
136        // Write faces with groups
137        if !self.faces.is_empty() {
138            writeln!(writer)?;
139
140            let mut group_iter = self.groups.iter().peekable();
141            let has_texcoords = !self.texcoords.is_empty();
142            let has_normals = !self.normals.is_empty();
143
144            for (i, face) in self.faces.iter().enumerate() {
145                // Check if we need to start a new group
146                if let Some((name, start_idx)) = group_iter.peek() {
147                    if i == *start_idx {
148                        writeln!(writer, "o {}", name)?;
149                        group_iter.next();
150                    }
151                }
152
153                match (
154                    has_texcoords.then_some(face.texcoords).flatten(),
155                    has_normals.then_some(face.normals).flatten(),
156                ) {
157                    (Some(texcoords), Some(normals)) => {
158                        writeln!(
159                            writer,
160                            "f {}/{}/{} {}/{}/{} {}/{}/{}",
161                            face.positions[0],
162                            texcoords[0],
163                            normals[0],
164                            face.positions[1],
165                            texcoords[1],
166                            normals[1],
167                            face.positions[2],
168                            texcoords[2],
169                            normals[2]
170                        )?;
171                    }
172                    (Some(texcoords), None) => {
173                        writeln!(
174                            writer,
175                            "f {}/{} {}/{} {}/{}",
176                            face.positions[0],
177                            texcoords[0],
178                            face.positions[1],
179                            texcoords[1],
180                            face.positions[2],
181                            texcoords[2]
182                        )?;
183                    }
184                    (None, Some(normals)) => {
185                        writeln!(
186                            writer,
187                            "f {}//{} {}//{} {}//{}",
188                            face.positions[0],
189                            normals[0],
190                            face.positions[1],
191                            normals[1],
192                            face.positions[2],
193                            normals[2]
194                        )?;
195                    }
196                    (None, None) => {
197                        writeln!(
198                            writer,
199                            "f {} {} {}",
200                            face.positions[0], face.positions[1], face.positions[2]
201                        )?;
202                    }
203                }
204            }
205        }
206
207        Ok(())
208    }
209
210    /// Write the OBJ data into a byte vector.
211    pub fn write_to_vec(&self) -> io::Result<Vec<u8>> {
212        let mut out = Vec::new();
213        self.write_to(&mut out)?;
214        Ok(out)
215    }
216}
217
218/// Read a float3 from an attribute at a given point index.
219fn read_float3(mesh: &Mesh, att_id: i32, point_idx: usize) -> [f32; 3] {
220    let att = mesh.attribute(att_id);
221    let byte_stride = att.byte_stride() as usize;
222    let buffer = att.buffer();
223    let mut bytes = [0u8; 12];
224    buffer.read(point_idx * byte_stride, &mut bytes);
225    [
226        f32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]),
227        f32::from_le_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]),
228        f32::from_le_bytes([bytes[8], bytes[9], bytes[10], bytes[11]]),
229    ]
230}
231
232/// Read a float2 from an attribute at a given point index.
233fn read_float2(mesh: &Mesh, att_id: i32, point_idx: usize) -> [f32; 2] {
234    let att = mesh.attribute(att_id);
235    let byte_stride = att.byte_stride() as usize;
236    let buffer = att.buffer();
237    let mut bytes = [0u8; 8];
238    buffer.read(point_idx * byte_stride, &mut bytes);
239    [
240        f32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]),
241        f32::from_le_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]),
242    ]
243}
244
245fn require_f32_components(mesh: &Mesh, att_id: i32, components: u8, label: &str) -> io::Result<()> {
246    let att = mesh.attribute(att_id);
247    if att.data_type() != DataType::Float32 || att.num_components() != components {
248        return Err(io::Error::new(
249            io::ErrorKind::InvalidInput,
250            format!("OBJ writer requires {label} attributes to be Float32x{components}"),
251        ));
252    }
253    Ok(())
254}
255
256// ============================================================================
257// Trait Implementations
258// ============================================================================
259
260impl Writer for ObjWriter {
261    fn new() -> Self {
262        Self::default()
263    }
264
265    fn add_mesh(&mut self, mesh: &Mesh, name: Option<&str>) -> io::Result<()> {
266        let vertex_offset = self.positions.len() as u32;
267        let normal_offset = self.normals.len() as u32;
268        let texcoord_offset = self.texcoords.len() as u32;
269        let face_start = self.faces.len();
270
271        // Add group if name provided
272        if let Some(n) = name {
273            self.groups.push((n.to_string(), face_start));
274        }
275
276        // Extract positions
277        let pos_att_id = mesh.named_attribute_id(GeometryAttributeType::Position);
278        if pos_att_id >= 0 {
279            require_f32_components(mesh, pos_att_id, 3, "position")?;
280            for i in 0..mesh.num_points() {
281                self.positions.push(read_float3(mesh, pos_att_id, i));
282            }
283        }
284
285        // Extract normals if present
286        let normal_att_id = mesh.named_attribute_id(GeometryAttributeType::Normal);
287        let has_normals = normal_att_id >= 0;
288        if has_normals {
289            require_f32_components(mesh, normal_att_id, 3, "normal")?;
290            for i in 0..mesh.num_points() {
291                self.normals.push(read_float3(mesh, normal_att_id, i));
292            }
293        }
294
295        // Extract texture coordinates if present
296        let texcoord_att_id = mesh.named_attribute_id(GeometryAttributeType::TexCoord);
297        let has_texcoords = texcoord_att_id >= 0;
298        if has_texcoords {
299            require_f32_components(mesh, texcoord_att_id, 2, "texcoord")?;
300            for i in 0..mesh.num_points() {
301                self.texcoords.push(read_float2(mesh, texcoord_att_id, i));
302            }
303        }
304
305        // Extract faces (convert to 1-based indices with offsets)
306        for i in 0..mesh.num_faces() as u32 {
307            let face = mesh.face(FaceIndex(i));
308            let positions = [
309                face[0].0 + vertex_offset + 1,
310                face[1].0 + vertex_offset + 1,
311                face[2].0 + vertex_offset + 1,
312            ];
313            let normals = has_normals.then(|| {
314                [
315                    face[0].0 + normal_offset + 1,
316                    face[1].0 + normal_offset + 1,
317                    face[2].0 + normal_offset + 1,
318                ]
319            });
320            let texcoords = has_texcoords.then(|| {
321                [
322                    face[0].0 + texcoord_offset + 1,
323                    face[1].0 + texcoord_offset + 1,
324                    face[2].0 + texcoord_offset + 1,
325                ]
326            });
327            self.faces.push(ObjFace {
328                positions,
329                texcoords,
330                normals,
331            });
332        }
333        Ok(())
334    }
335
336    fn write<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
337        self.write(path)
338    }
339
340    fn vertex_count(&self) -> usize {
341        self.vertex_count()
342    }
343
344    fn face_count(&self) -> usize {
345        self.face_count()
346    }
347}
348
349impl PointCloudWriter for ObjWriter {
350    fn add_points(&mut self, points: &[[f32; 3]]) {
351        self.positions.extend_from_slice(points);
352    }
353
354    fn add_point(&mut self, point: [f32; 3]) {
355        self.positions.push(point);
356    }
357}
358
359impl WriteToBytes for ObjWriter {
360    fn write_to_vec(&self) -> io::Result<Vec<u8>> {
361        ObjWriter::write_to_vec(self)
362    }
363
364    fn write_to<W: Write>(&self, writer: &mut W) -> io::Result<()> {
365        ObjWriter::write_to(self, writer)
366    }
367}
368
369// ============================================================================
370// Convenience Functions (for backward compatibility)
371// ============================================================================
372
373/// Write a mesh to an OBJ file with positions and faces.
374///
375/// This is a convenience function. For more control, use `ObjWriter` directly.
376pub fn write_obj_mesh<P: AsRef<Path>>(path: P, mesh: &Mesh) -> io::Result<()> {
377    let mut writer = ObjWriter::new();
378    Writer::add_mesh(&mut writer, mesh, None)?;
379    writer.write(path)
380}
381
382/// Write point positions to an OBJ file (point cloud, no faces).
383///
384/// This is a convenience function. For more control, use `ObjWriter` directly.
385pub fn write_obj_positions<P: AsRef<Path>>(path: P, points: &[[f32; 3]]) -> io::Result<()> {
386    let mut writer = ObjWriter::new();
387    writer.add_points(points);
388    writer.write(path)
389}
390
391// ============================================================================
392// Tests
393// ============================================================================
394
395#[cfg(test)]
396mod tests {
397    use super::*;
398    use draco_core::draco_types::DataType;
399    use draco_core::geometry_attribute::PointAttribute;
400    use draco_core::geometry_indices::PointIndex;
401    use std::fs;
402    use std::io::{BufRead, BufReader};
403    use tempfile::NamedTempFile;
404
405    fn create_triangle_mesh() -> Mesh {
406        let mut mesh = Mesh::new();
407        let mut pos_att = PointAttribute::new();
408
409        pos_att.init(
410            GeometryAttributeType::Position,
411            3,
412            DataType::Float32,
413            false,
414            3,
415        );
416        let buffer = pos_att.buffer_mut();
417        let positions: [[f32; 3]; 3] = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]];
418        for (i, pos) in positions.iter().enumerate() {
419            let bytes: Vec<u8> = pos.iter().flat_map(|v| v.to_le_bytes()).collect();
420            buffer.write(i * 12, &bytes);
421        }
422        mesh.add_attribute(pos_att);
423
424        mesh.set_num_faces(1);
425        mesh.set_face(FaceIndex(0), [PointIndex(0), PointIndex(1), PointIndex(2)]);
426
427        mesh
428    }
429
430    fn add_f32_attribute(
431        mesh: &mut Mesh,
432        attribute_type: GeometryAttributeType,
433        components: u8,
434        values: &[f32],
435    ) {
436        let mut att = PointAttribute::new();
437        att.init(
438            attribute_type,
439            components,
440            DataType::Float32,
441            false,
442            values.len() / components as usize,
443        );
444        let bytes: Vec<u8> = values
445            .iter()
446            .flat_map(|component| component.to_le_bytes())
447            .collect();
448        att.buffer_mut().write(0, &bytes);
449        mesh.add_attribute(att);
450    }
451
452    #[test]
453    fn test_obj_writer_new() {
454        let writer = ObjWriter::new();
455        assert_eq!(writer.vertex_count(), 0);
456        assert_eq!(writer.face_count(), 0);
457    }
458
459    #[test]
460    fn test_obj_writer_add_mesh() {
461        let mesh = create_triangle_mesh();
462        let mut writer = ObjWriter::new();
463        Writer::add_mesh(&mut writer, &mesh, Some("Triangle")).unwrap();
464        assert_eq!(writer.vertex_count(), 3);
465        assert_eq!(writer.face_count(), 1);
466    }
467
468    #[test]
469    fn test_obj_writer_add_points() {
470        let mut writer = ObjWriter::new();
471        writer.add_points(&[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]);
472        assert_eq!(writer.vertex_count(), 2);
473        assert_eq!(writer.face_count(), 0);
474    }
475
476    #[test]
477    fn test_write_obj_positions() {
478        let points = vec![[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]];
479
480        let file = NamedTempFile::new().unwrap();
481        write_obj_positions(file.path(), &points).unwrap();
482
483        let content = fs::read_to_string(file.path()).unwrap();
484        assert!(content.contains("v 0.000000 0.000000 0.000000"));
485        assert!(content.contains("v 1.000000 0.000000 0.000000"));
486        assert!(content.contains("v 0.000000 1.000000 0.000000"));
487    }
488
489    #[test]
490    fn test_write_obj_mesh() {
491        let mesh = create_triangle_mesh();
492        let file = NamedTempFile::new().unwrap();
493        write_obj_mesh(file.path(), &mesh).unwrap();
494
495        let reader = BufReader::new(fs::File::open(file.path()).unwrap());
496        let lines: Vec<String> = reader.lines().map_while(Result::ok).collect();
497
498        // Check vertices and face
499        assert!(lines.iter().any(|l| l.starts_with("v ")));
500        assert!(lines.iter().any(|l| l == "f 1 2 3"));
501    }
502
503    #[test]
504    fn test_multiple_meshes() {
505        let mesh1 = create_triangle_mesh();
506        let mesh2 = create_triangle_mesh();
507
508        let mut writer = ObjWriter::new();
509        Writer::add_mesh(&mut writer, &mesh1, Some("Mesh1")).unwrap();
510        Writer::add_mesh(&mut writer, &mesh2, Some("Mesh2")).unwrap();
511
512        assert_eq!(writer.vertex_count(), 6);
513        assert_eq!(writer.face_count(), 2);
514
515        let file = NamedTempFile::new().unwrap();
516        writer.write(file.path()).unwrap();
517
518        let content = fs::read_to_string(file.path()).unwrap();
519        assert!(content.contains("o Mesh1"));
520        assert!(content.contains("o Mesh2"));
521        // Second mesh should have offset indices
522        assert!(content.contains("f 4 5 6"));
523    }
524
525    #[test]
526    fn test_write_obj_mesh_with_normals_and_texcoords() {
527        let mut mesh = create_triangle_mesh();
528        add_f32_attribute(
529            &mut mesh,
530            GeometryAttributeType::Normal,
531            3,
532            &[0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0],
533        );
534        add_f32_attribute(
535            &mut mesh,
536            GeometryAttributeType::TexCoord,
537            2,
538            &[0.0, 0.0, 1.0, 0.0, 0.0, 1.0],
539        );
540
541        let mut writer = ObjWriter::new();
542        Writer::add_mesh(&mut writer, &mesh, Some("Triangle")).unwrap();
543
544        let content = String::from_utf8(writer.write_to_vec().unwrap()).unwrap();
545        assert!(content.contains("vt 1.000000 0.000000"));
546        assert!(content.contains("vn 0.000000 0.000000 1.000000"));
547        assert!(content.contains("f 1/1/1 2/2/2 3/3/3"));
548    }
549}