oxihuman-export 0.1.2

Export pipeline for OxiHuman — glTF, COLLADA, STL, and streaming formats
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
// Copyright (C) 2026 COOLJAPAN OU (Team KitaSan)
// SPDX-License-Identifier: Apache-2.0

//! Stanford PLY format exporter — ASCII and binary little-endian.

use std::io::Write;
use std::path::Path;

use oxihuman_mesh::MeshBuffers;

/// PLY export format variant.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PlyFormat {
    /// ASCII text format (human-readable).
    Ascii,
    /// Binary little-endian (compact and fast).
    BinaryLittleEndian,
}

/// Write the PLY header to a writer.
fn write_ply_header(
    writer: &mut impl Write,
    format: PlyFormat,
    vertex_count: usize,
    face_count: usize,
    has_normals: bool,
    has_uvs: bool,
    has_colors: bool,
) -> anyhow::Result<()> {
    let format_str = match format {
        PlyFormat::Ascii => "ascii 1.0",
        PlyFormat::BinaryLittleEndian => "binary_little_endian 1.0",
    };

    writeln!(writer, "ply")?;
    writeln!(writer, "format {}", format_str)?;
    writeln!(writer, "comment Generated by OxiHuman")?;
    writeln!(writer, "element vertex {}", vertex_count)?;
    writeln!(writer, "property float x")?;
    writeln!(writer, "property float y")?;
    writeln!(writer, "property float z")?;

    if has_normals {
        writeln!(writer, "property float nx")?;
        writeln!(writer, "property float ny")?;
        writeln!(writer, "property float nz")?;
    }

    if has_uvs {
        writeln!(writer, "property float s")?;
        writeln!(writer, "property float t")?;
    }

    if has_colors {
        writeln!(writer, "property uchar red")?;
        writeln!(writer, "property uchar green")?;
        writeln!(writer, "property uchar blue")?;
    }

    if face_count > 0 {
        writeln!(writer, "element face {}", face_count)?;
        writeln!(writer, "property list uchar int vertex_indices")?;
    }

    writeln!(writer, "end_header")?;
    Ok(())
}

/// Export a mesh as a PLY file.
/// Includes vertex positions, normals, and UV texture coordinates.
/// Includes face connectivity.
#[allow(dead_code)]
pub fn export_ply(mesh: &MeshBuffers, path: &Path, format: PlyFormat) -> anyhow::Result<()> {
    let vertex_count = mesh.positions.len();
    let face_count = mesh.indices.len() / 3;
    let has_normals = !mesh.normals.is_empty();
    let has_uvs = !mesh.uvs.is_empty();

    let mut buf: Vec<u8> = Vec::new();
    write_ply_header(
        &mut buf,
        format,
        vertex_count,
        face_count,
        has_normals,
        has_uvs,
        false,
    )?;

    match format {
        PlyFormat::Ascii => {
            for i in 0..vertex_count {
                let p = mesh.positions[i];
                let mut line = format!("{} {} {}", p[0], p[1], p[2]);

                if has_normals && i < mesh.normals.len() {
                    let n = mesh.normals[i];
                    line.push_str(&format!(" {} {} {}", n[0], n[1], n[2]));
                }

                if has_uvs && i < mesh.uvs.len() {
                    let uv = mesh.uvs[i];
                    line.push_str(&format!(" {} {}", uv[0], uv[1]));
                }

                writeln!(buf, "{}", line)?;
            }

            for tri in mesh.indices.chunks_exact(3) {
                writeln!(buf, "3 {} {} {}", tri[0], tri[1], tri[2])?;
            }
        }
        PlyFormat::BinaryLittleEndian => {
            for i in 0..vertex_count {
                let p = mesh.positions[i];
                buf.write_all(&p[0].to_le_bytes())?;
                buf.write_all(&p[1].to_le_bytes())?;
                buf.write_all(&p[2].to_le_bytes())?;

                if has_normals && i < mesh.normals.len() {
                    let n = mesh.normals[i];
                    buf.write_all(&n[0].to_le_bytes())?;
                    buf.write_all(&n[1].to_le_bytes())?;
                    buf.write_all(&n[2].to_le_bytes())?;
                }

                if has_uvs && i < mesh.uvs.len() {
                    let uv = mesh.uvs[i];
                    buf.write_all(&uv[0].to_le_bytes())?;
                    buf.write_all(&uv[1].to_le_bytes())?;
                }
            }

            for tri in mesh.indices.chunks_exact(3) {
                buf.write_all(&[3u8])?;
                buf.write_all(&(tri[0] as i32).to_le_bytes())?;
                buf.write_all(&(tri[1] as i32).to_le_bytes())?;
                buf.write_all(&(tri[2] as i32).to_le_bytes())?;
            }
        }
    }

    std::fs::write(path, buf)?;
    Ok(())
}

/// Export a point cloud as a PLY file (no faces).
///
/// - `positions`: Nx3 positions
/// - `normals`: optional Nx3 normals
/// - `colors`: optional Nx3 RGB colors (u8)
#[allow(dead_code)]
pub fn export_point_cloud_ply(
    positions: &[[f32; 3]],
    normals: Option<&[[f32; 3]]>,
    colors: Option<&[[u8; 3]]>,
    path: &Path,
    format: PlyFormat,
) -> anyhow::Result<()> {
    let vertex_count = positions.len();
    let has_normals = normals.is_some();
    let has_colors = colors.is_some();

    let mut buf: Vec<u8> = Vec::new();
    write_ply_header(
        &mut buf,
        format,
        vertex_count,
        0, // no faces
        has_normals,
        false, // no uvs
        has_colors,
    )?;

    match format {
        PlyFormat::Ascii => {
            for i in 0..vertex_count {
                let p = positions[i];
                let mut line = format!("{} {} {}", p[0], p[1], p[2]);

                if let Some(nrm) = normals {
                    if i < nrm.len() {
                        let n = nrm[i];
                        line.push_str(&format!(" {} {} {}", n[0], n[1], n[2]));
                    }
                }

                if let Some(clr) = colors {
                    if i < clr.len() {
                        let c = clr[i];
                        line.push_str(&format!(" {} {} {}", c[0], c[1], c[2]));
                    }
                }

                writeln!(buf, "{}", line)?;
            }
        }
        PlyFormat::BinaryLittleEndian => {
            for i in 0..vertex_count {
                let p = positions[i];
                buf.write_all(&p[0].to_le_bytes())?;
                buf.write_all(&p[1].to_le_bytes())?;
                buf.write_all(&p[2].to_le_bytes())?;

                if let Some(nrm) = normals {
                    if i < nrm.len() {
                        let n = nrm[i];
                        buf.write_all(&n[0].to_le_bytes())?;
                        buf.write_all(&n[1].to_le_bytes())?;
                        buf.write_all(&n[2].to_le_bytes())?;
                    }
                }

                if let Some(clr) = colors {
                    if i < clr.len() {
                        let c = clr[i];
                        buf.write_all(&[c[0], c[1], c[2]])?;
                    }
                }
            }
        }
    }

    std::fs::write(path, buf)?;
    Ok(())
}

/// Export mesh vertex positions as a point cloud PLY (no faces).
#[allow(dead_code)]
pub fn export_mesh_as_point_cloud(
    mesh: &MeshBuffers,
    path: &Path,
    format: PlyFormat,
) -> anyhow::Result<()> {
    let normals = if mesh.normals.is_empty() {
        None
    } else {
        Some(mesh.normals.as_slice())
    };
    export_point_cloud_ply(&mesh.positions, normals, None, path, format)
}

#[cfg(test)]
mod tests {
    use super::*;
    use oxihuman_mesh::MeshBuffers;
    use oxihuman_morph::engine::MeshBuffers as MB;

    fn triangle_mesh() -> MeshBuffers {
        MeshBuffers::from_morph(MB {
            positions: vec![[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]],
            normals: vec![[0.0, 0.0, 1.0]; 3],
            uvs: vec![[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]],
            indices: vec![0, 1, 2],
            has_suit: false,
        })
    }

    fn quad_mesh() -> MeshBuffers {
        MeshBuffers::from_morph(MB {
            positions: vec![
                [0.0, 0.0, 0.0],
                [1.0, 0.0, 0.0],
                [1.0, 1.0, 0.0],
                [0.0, 1.0, 0.0],
            ],
            normals: vec![[0.0, 0.0, 1.0]; 4],
            uvs: vec![[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]],
            indices: vec![0, 1, 2, 0, 2, 3],
            has_suit: false,
        })
    }

    #[test]
    fn export_ply_ascii_creates_file() {
        let mesh = triangle_mesh();
        let path = std::path::PathBuf::from("/tmp/test_ply_ascii_create.ply");
        export_ply(&mesh, &path, PlyFormat::Ascii).expect("should succeed");
        assert!(path.exists());
        std::fs::remove_file(&path).ok();
    }

    #[test]
    fn export_ply_ascii_header_starts_with_ply() {
        let mesh = triangle_mesh();
        let path = std::path::PathBuf::from("/tmp/test_ply_ascii_header.ply");
        export_ply(&mesh, &path, PlyFormat::Ascii).expect("should succeed");
        let content = std::fs::read_to_string(&path).expect("should succeed");
        assert!(content.starts_with("ply\n"), "File must start with 'ply'");
        assert!(content.contains("format ascii 1.0"));
        assert!(content.contains("comment Generated by OxiHuman"));
        std::fs::remove_file(&path).ok();
    }

    #[test]
    fn export_ply_ascii_contains_vertex_count() {
        let mesh = triangle_mesh();
        let path = std::path::PathBuf::from("/tmp/test_ply_ascii_vcount.ply");
        export_ply(&mesh, &path, PlyFormat::Ascii).expect("should succeed");
        let content = std::fs::read_to_string(&path).expect("should succeed");
        assert!(content.contains("element vertex 3"));
        assert!(content.contains("element face 1"));
        std::fs::remove_file(&path).ok();
    }

    #[test]
    fn export_ply_binary_creates_file() {
        let mesh = triangle_mesh();
        let path = std::path::PathBuf::from("/tmp/test_ply_binary_create.ply");
        export_ply(&mesh, &path, PlyFormat::BinaryLittleEndian).expect("should succeed");
        assert!(path.exists());
        std::fs::remove_file(&path).ok();
    }

    #[test]
    fn export_ply_binary_header_in_file() {
        let mesh = triangle_mesh();
        let path = std::path::PathBuf::from("/tmp/test_ply_binary_header.ply");
        export_ply(&mesh, &path, PlyFormat::BinaryLittleEndian).expect("should succeed");
        let bytes = std::fs::read(&path).expect("should succeed");
        // The header is ASCII even in binary format
        let header_end = b"end_header\n";
        let found = bytes.windows(header_end.len()).any(|w| w == header_end);
        assert!(found, "Binary PLY must contain 'end_header'");
        // Verify it starts with "ply"
        assert!(bytes.starts_with(b"ply\n"));
        assert!(bytes
            .windows(b"binary_little_endian 1.0".len())
            .any(|w| w == b"binary_little_endian 1.0"));
        std::fs::remove_file(&path).ok();
    }

    #[test]
    fn export_point_cloud_no_normals_no_colors() {
        let positions: Vec<[f32; 3]> = vec![[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]];
        let path = std::path::PathBuf::from("/tmp/test_ply_pc_bare.ply");
        export_point_cloud_ply(&positions, None, None, &path, PlyFormat::Ascii).expect("should succeed");
        assert!(path.exists());
        let content = std::fs::read_to_string(&path).expect("should succeed");
        assert!(content.contains("element vertex 3"));
        assert!(!content.contains("element face"));
        assert!(!content.contains("property float nx"));
        assert!(!content.contains("property uchar red"));
        std::fs::remove_file(&path).ok();
    }

    #[test]
    fn export_point_cloud_with_normals() {
        let positions: Vec<[f32; 3]> = vec![[0.0, 0.0, 0.0], [1.0, 0.0, 0.0]];
        let normals: Vec<[f32; 3]> = vec![[0.0, 0.0, 1.0], [0.0, 0.0, 1.0]];
        let path = std::path::PathBuf::from("/tmp/test_ply_pc_normals.ply");
        export_point_cloud_ply(&positions, Some(&normals), None, &path, PlyFormat::Ascii).expect("should succeed");
        let content = std::fs::read_to_string(&path).expect("should succeed");
        assert!(content.contains("property float nx"));
        assert!(content.contains("property float ny"));
        assert!(content.contains("property float nz"));
        std::fs::remove_file(&path).ok();
    }

    #[test]
    fn export_point_cloud_with_colors() {
        let positions: Vec<[f32; 3]> = vec![[0.0, 0.0, 0.0], [1.0, 0.0, 0.0]];
        let colors: Vec<[u8; 3]> = vec![[255, 0, 0], [0, 255, 0]];
        let path = std::path::PathBuf::from("/tmp/test_ply_pc_colors.ply");
        export_point_cloud_ply(&positions, None, Some(&colors), &path, PlyFormat::Ascii).expect("should succeed");
        let content = std::fs::read_to_string(&path).expect("should succeed");
        assert!(content.contains("property uchar red"));
        assert!(content.contains("property uchar green"));
        assert!(content.contains("property uchar blue"));
        // Color values should be in the data
        assert!(content.contains("255 0 0") || content.contains("255"));
        std::fs::remove_file(&path).ok();
    }

    #[test]
    fn export_mesh_as_point_cloud_creates_file() {
        let mesh = triangle_mesh();
        let path = std::path::PathBuf::from("/tmp/test_ply_mesh_pc.ply");
        export_mesh_as_point_cloud(&mesh, &path, PlyFormat::Ascii).expect("should succeed");
        assert!(path.exists());
        let content = std::fs::read_to_string(&path).expect("should succeed");
        // Point cloud should have no faces
        assert!(!content.contains("element face"));
        // Should have vertex positions
        assert!(content.contains("element vertex 3"));
        std::fs::remove_file(&path).ok();
    }

    #[test]
    fn ply_ascii_file_has_correct_line_count() {
        // triangle mesh: 3 vertices, 1 face
        // header lines: ply, format, comment, element vertex, x, y, z, nx, ny, nz, s, t, element face, property list, end_header = 15 lines
        // data: 3 vertex lines + 1 face line = 4 lines
        let mesh = triangle_mesh();
        let path = std::path::PathBuf::from("/tmp/test_ply_linecount.ply");
        export_ply(&mesh, &path, PlyFormat::Ascii).expect("should succeed");
        let content = std::fs::read_to_string(&path).expect("should succeed");
        let lines: Vec<&str> = content.lines().collect();
        // header: ply(1) + format(1) + comment(1) + element vertex(1) + x,y,z(3) + nx,ny,nz(3) + s,t(2) + element face(1) + property list(1) + end_header(1) = 15
        // data: 3 vertices + 1 face = 4
        // total = 19
        assert_eq!(lines.len(), 19, "Expected 19 lines, got {}", lines.len());
        std::fs::remove_file(&path).ok();
    }

    #[test]
    fn ply_ascii_vertex_data_is_numeric() {
        let mesh = triangle_mesh();
        let path = std::path::PathBuf::from("/tmp/test_ply_numeric.ply");
        export_ply(&mesh, &path, PlyFormat::Ascii).expect("should succeed");
        let content = std::fs::read_to_string(&path).expect("should succeed");

        // Find end_header line index
        let lines: Vec<&str> = content.lines().collect();
        let header_end = lines
            .iter()
            .position(|l| *l == "end_header")
            .expect("end_header not found");

        // All vertex lines after header must parse as floats
        for line in &lines[header_end + 1..header_end + 1 + 3] {
            for token in line.split_whitespace() {
                token
                    .parse::<f32>()
                    .unwrap_or_else(|_| panic!("Token '{}' in vertex line is not numeric", token));
            }
        }
        std::fs::remove_file(&path).ok();
    }

    #[test]
    fn ply_format_ascii_vs_binary_different_size() {
        let mesh = quad_mesh();
        let ascii_path = std::path::PathBuf::from("/tmp/test_ply_size_ascii.ply");
        let binary_path = std::path::PathBuf::from("/tmp/test_ply_size_binary.ply");

        export_ply(&mesh, &ascii_path, PlyFormat::Ascii).expect("should succeed");
        export_ply(&mesh, &binary_path, PlyFormat::BinaryLittleEndian).expect("should succeed");

        let ascii_size = std::fs::metadata(&ascii_path).expect("should succeed").len();
        let binary_size = std::fs::metadata(&binary_path).expect("should succeed").len();

        // They should differ (typically binary is smaller for this mesh,
        // but at minimum they must not be identical)
        assert_ne!(
            ascii_size, binary_size,
            "ASCII and binary sizes should differ"
        );

        std::fs::remove_file(&ascii_path).ok();
        std::fs::remove_file(&binary_path).ok();
    }
}