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
454
455
456
457
458
459
460
461
462
463
464
465
466
// Copyright (C) 2026 COOLJAPAN OU (Team KitaSan)
// SPDX-License-Identifier: Apache-2.0

//! Draco-like mesh compression (quantized vertex attribute encoding).

// ── Types ─────────────────────────────────────────────────────────────────────

#[allow(dead_code)]
pub struct DracoConfig {
    pub position_quantization: u8,
    pub normal_quantization: u8,
    pub uv_quantization: u8,
    pub use_edgebreaker: bool,
    pub compression_level: u8,
}

#[allow(dead_code)]
pub struct CompressedMesh {
    pub data: Vec<u8>,
    pub original_vertex_count: usize,
    pub original_index_count: usize,
    pub quantization_bits: u8,
}

#[allow(dead_code)]
pub struct DracoQuantizedMesh {
    pub positions: Vec<[i32; 3]>,
    pub normals: Vec<[i32; 3]>,
    pub uvs: Vec<[i32; 2]>,
    pub indices: Vec<u32>,
    pub bounds_min: [f32; 3],
    pub bounds_max: [f32; 3],
    pub position_scale: f32,
}

// ── Functions ─────────────────────────────────────────────────────────────────

#[allow(dead_code)]
pub fn default_draco_config() -> DracoConfig {
    DracoConfig {
        position_quantization: 11,
        normal_quantization: 8,
        uv_quantization: 10,
        use_edgebreaker: true,
        compression_level: 7,
    }
}

#[allow(dead_code)]
pub fn quantize_positions(
    positions: &[[f32; 3]],
    bits: u8,
) -> (Vec<[i32; 3]>, [f32; 3], [f32; 3], f32) {
    if positions.is_empty() {
        return (Vec::new(), [0.0; 3], [0.0; 3], 1.0);
    }

    let mut mn = positions[0];
    let mut mx = positions[0];
    for p in positions {
        for k in 0..3 {
            if p[k] < mn[k] {
                mn[k] = p[k];
            }
            if p[k] > mx[k] {
                mx[k] = p[k];
            }
        }
    }

    let range = (0..3)
        .map(|k| mx[k] - mn[k])
        .fold(0.0f32, f32::max)
        .max(1e-9);

    let max_val = ((1i32 << bits) - 1) as f32;
    let scale = range / max_val;

    let quantized = positions
        .iter()
        .map(|p| {
            [
                ((p[0] - mn[0]) / scale).round() as i32,
                ((p[1] - mn[1]) / scale).round() as i32,
                ((p[2] - mn[2]) / scale).round() as i32,
            ]
        })
        .collect();

    (quantized, mn, mx, scale)
}

#[allow(dead_code)]
pub fn dequantize_positions(quantized: &[[i32; 3]], min: [f32; 3], scale: f32) -> Vec<[f32; 3]> {
    quantized
        .iter()
        .map(|q| {
            [
                min[0] + q[0] as f32 * scale,
                min[1] + q[1] as f32 * scale,
                min[2] + q[2] as f32 * scale,
            ]
        })
        .collect()
}

#[allow(dead_code)]
pub fn quantize_normals(normals: &[[f32; 3]], bits: u8) -> Vec<[i32; 3]> {
    let max_val = ((1i32 << bits) - 1) as f32;
    let half = max_val / 2.0;
    normals
        .iter()
        .map(|n| {
            [
                ((n[0] * half) + half).round() as i32,
                ((n[1] * half) + half).round() as i32,
                ((n[2] * half) + half).round() as i32,
            ]
        })
        .collect()
}

#[allow(dead_code)]
pub fn dequantize_normals(quantized: &[[i32; 3]], bits: u8) -> Vec<[f32; 3]> {
    let max_val = ((1i32 << bits) - 1) as f32;
    let half = max_val / 2.0;
    quantized
        .iter()
        .map(|q| {
            [
                (q[0] as f32 - half) / half,
                (q[1] as f32 - half) / half,
                (q[2] as f32 - half) / half,
            ]
        })
        .collect()
}

#[allow(dead_code)]
pub fn quantize_uvs(uvs: &[[f32; 2]], bits: u8) -> Vec<[i32; 2]> {
    let max_val = ((1i32 << bits) - 1) as f32;
    uvs.iter()
        .map(|uv| {
            [
                (uv[0].clamp(0.0, 1.0) * max_val).round() as i32,
                (uv[1].clamp(0.0, 1.0) * max_val).round() as i32,
            ]
        })
        .collect()
}

#[allow(dead_code)]
pub fn dequantize_uvs(quantized: &[[i32; 2]], bits: u8) -> Vec<[f32; 2]> {
    let max_val = ((1i32 << bits) - 1) as f32;
    quantized
        .iter()
        .map(|q| [q[0] as f32 / max_val, q[1] as f32 / max_val])
        .collect()
}

#[allow(dead_code)]
pub fn encode_indices_delta(indices: &[u32]) -> Vec<i32> {
    let mut out = Vec::with_capacity(indices.len());
    let mut prev = 0i32;
    for &idx in indices {
        let val = idx as i32;
        out.push(val - prev);
        prev = val;
    }
    out
}

#[allow(dead_code)]
pub fn decode_indices_delta(deltas: &[i32]) -> Vec<u32> {
    let mut out = Vec::with_capacity(deltas.len());
    let mut acc = 0i32;
    for &d in deltas {
        acc += d;
        out.push(acc as u32);
    }
    out
}

/// Type alias to avoid type_complexity clippy warning.
type CompressResult = (Vec<[i32; 3]>, Vec<[i32; 3]>, Vec<[i32; 2]>, Vec<i32>);

fn compress_attrs(
    positions: &[[f32; 3]],
    normals: &[[f32; 3]],
    uvs: &[[f32; 2]],
    indices: &[u32],
    cfg: &DracoConfig,
) -> (CompressResult, [f32; 3], f32) {
    let (qpos, mn, _mx, scale) = quantize_positions(positions, cfg.position_quantization);
    let qnrm = quantize_normals(normals, cfg.normal_quantization);
    let quvs = quantize_uvs(uvs, cfg.uv_quantization);
    let idx_delta = encode_indices_delta(indices);
    ((qpos, qnrm, quvs, idx_delta), mn, scale)
}

#[allow(dead_code)]
pub fn compress_mesh(
    positions: &[[f32; 3]],
    normals: &[[f32; 3]],
    uvs: &[[f32; 2]],
    indices: &[u32],
    cfg: &DracoConfig,
) -> CompressedMesh {
    let ((qpos, qnrm, quvs, idx_delta), _mn, _scale) =
        compress_attrs(positions, normals, uvs, indices, cfg);

    // Pack everything into bytes (simple little-endian i32 streams)
    let mut data: Vec<u8> = Vec::new();

    // Header
    data.extend_from_slice(&(positions.len() as u32).to_le_bytes());
    data.extend_from_slice(&(indices.len() as u32).to_le_bytes());
    data.push(cfg.position_quantization);

    // Positions
    for p in &qpos {
        for &v in p {
            data.extend_from_slice(&v.to_le_bytes());
        }
    }
    // Normals
    for n in &qnrm {
        for &v in n {
            data.extend_from_slice(&v.to_le_bytes());
        }
    }
    // UVs
    for uv in &quvs {
        for &v in uv {
            data.extend_from_slice(&v.to_le_bytes());
        }
    }
    // Index deltas
    for &d in &idx_delta {
        data.extend_from_slice(&d.to_le_bytes());
    }

    CompressedMesh {
        data,
        original_vertex_count: positions.len(),
        original_index_count: indices.len(),
        quantization_bits: cfg.position_quantization,
    }
}

#[allow(dead_code)]
pub fn estimate_compressed_size(
    vertex_count: usize,
    index_count: usize,
    cfg: &DracoConfig,
) -> usize {
    let pos_bits = (cfg.position_quantization as usize) * 3 * vertex_count;
    let nrm_bits = (cfg.normal_quantization as usize) * 3 * vertex_count;
    let uv_bits = (cfg.uv_quantization as usize) * 2 * vertex_count;
    let idx_bits = 32 * index_count; // delta, worst case same as original
    (pos_bits + nrm_bits + uv_bits + idx_bits) / 8 + 16
}

#[allow(dead_code)]
pub fn compression_ratio(original_bytes: usize, compressed: &CompressedMesh) -> f32 {
    if compressed.data.is_empty() {
        return 1.0;
    }
    original_bytes as f32 / compressed.data.len() as f32
}

#[allow(dead_code)]
pub fn quantize_mesh(
    positions: &[[f32; 3]],
    normals: &[[f32; 3]],
    uvs: &[[f32; 2]],
    indices: &[u32],
    bits: u8,
) -> DracoQuantizedMesh {
    let (qpos, mn, mx, scale) = quantize_positions(positions, bits);
    let qnrm = quantize_normals(normals, bits);
    let quvs = quantize_uvs(uvs, bits);
    DracoQuantizedMesh {
        positions: qpos,
        normals: qnrm,
        uvs: quvs,
        indices: indices.to_vec(),
        bounds_min: mn,
        bounds_max: mx,
        position_scale: scale,
    }
}

// ── Tests ─────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;

    fn sample_positions() -> Vec<[f32; 3]> {
        vec![
            [0.0, 0.0, 0.0],
            [1.0, 0.0, 0.0],
            [0.0, 1.0, 0.0],
            [1.0, 1.0, 1.0],
        ]
    }

    fn sample_normals() -> Vec<[f32; 3]> {
        vec![
            [0.0, 1.0, 0.0],
            [0.0, -1.0, 0.0],
            [1.0, 0.0, 0.0],
            [-1.0, 0.0, 0.0],
        ]
    }

    fn sample_uvs() -> Vec<[f32; 2]> {
        vec![[0.0, 0.0], [1.0, 0.0], [0.0, 1.0], [1.0, 1.0]]
    }

    fn sample_indices() -> Vec<u32> {
        vec![0, 1, 2, 1, 3, 2]
    }

    #[test]
    fn test_quantize_positions_count() {
        let pos = sample_positions();
        let (qpos, _mn, _mx, _scale) = quantize_positions(&pos, 11);
        assert_eq!(qpos.len(), pos.len());
    }

    #[test]
    fn test_dequantize_positions_roundtrip() {
        let pos = sample_positions();
        let (qpos, mn, _mx, scale) = quantize_positions(&pos, 11);
        let restored = dequantize_positions(&qpos, mn, scale);
        for (orig, rest) in pos.iter().zip(restored.iter()) {
            for k in 0..3 {
                assert!(
                    (orig[k] - rest[k]).abs() < 0.01,
                    "pos roundtrip failed at k={}",
                    k
                );
            }
        }
    }

    #[test]
    fn test_quantize_positions_empty() {
        let (qpos, mn, mx, scale) = quantize_positions(&[], 11);
        assert!(qpos.is_empty());
        assert_eq!(mn, [0.0; 3]);
        assert_eq!(mx, [0.0; 3]);
        assert!((scale - 1.0).abs() < 1e-6);
    }

    #[test]
    fn test_quantize_normals_count() {
        let nrm = sample_normals();
        let qnrm = quantize_normals(&nrm, 8);
        assert_eq!(qnrm.len(), nrm.len());
    }

    #[test]
    fn test_dequantize_normals_roundtrip() {
        let nrm = vec![[0.0f32, 1.0, 0.0], [1.0, 0.0, 0.0]];
        let q = quantize_normals(&nrm, 10);
        let r = dequantize_normals(&q, 10);
        for (orig, rest) in nrm.iter().zip(r.iter()) {
            for k in 0..3 {
                assert!((orig[k] - rest[k]).abs() < 0.02, "normal roundtrip failed");
            }
        }
    }

    #[test]
    fn test_quantize_uvs_count() {
        let uvs = sample_uvs();
        let quvs = quantize_uvs(&uvs, 10);
        assert_eq!(quvs.len(), uvs.len());
    }

    #[test]
    fn test_dequantize_uvs_roundtrip() {
        let uvs = vec![[0.0f32, 0.0], [1.0, 1.0], [0.5, 0.25]];
        let q = quantize_uvs(&uvs, 10);
        let r = dequantize_uvs(&q, 10);
        for (orig, rest) in uvs.iter().zip(r.iter()) {
            for k in 0..2 {
                assert!((orig[k] - rest[k]).abs() < 0.002, "uv roundtrip failed");
            }
        }
    }

    #[test]
    fn test_encode_decode_indices_delta() {
        let indices = sample_indices();
        let deltas = encode_indices_delta(&indices);
        let restored = decode_indices_delta(&deltas);
        assert_eq!(restored, indices);
    }

    #[test]
    fn test_index_delta_empty() {
        let d = encode_indices_delta(&[]);
        assert!(d.is_empty());
        let r = decode_indices_delta(&[]);
        assert!(r.is_empty());
    }

    #[test]
    fn test_compress_mesh_nonempty() {
        let pos = sample_positions();
        let nrm = sample_normals();
        let uvs = sample_uvs();
        let idx = sample_indices();
        let cfg = default_draco_config();
        let compressed = compress_mesh(&pos, &nrm, &uvs, &idx, &cfg);
        assert!(!compressed.data.is_empty());
        assert_eq!(compressed.original_vertex_count, pos.len());
        assert_eq!(compressed.original_index_count, idx.len());
    }

    #[test]
    fn test_compression_ratio_gt_zero() {
        let pos = sample_positions();
        let nrm = sample_normals();
        let uvs = sample_uvs();
        let idx = sample_indices();
        let cfg = default_draco_config();
        let compressed = compress_mesh(&pos, &nrm, &uvs, &idx, &cfg);
        let original_bytes = pos.len() * 12 + nrm.len() * 12 + uvs.len() * 8 + idx.len() * 4;
        let ratio = compression_ratio(original_bytes, &compressed);
        assert!(ratio > 0.0);
    }

    #[test]
    fn test_estimate_compressed_size() {
        let cfg = default_draco_config();
        let sz = estimate_compressed_size(100, 300, &cfg);
        assert!(sz > 0);
    }

    #[test]
    fn test_quantize_mesh_struct() {
        let pos = sample_positions();
        let nrm = sample_normals();
        let uvs = sample_uvs();
        let idx = sample_indices();
        let qm = quantize_mesh(&pos, &nrm, &uvs, &idx, 11);
        assert_eq!(qm.positions.len(), pos.len());
        assert_eq!(qm.normals.len(), nrm.len());
        assert_eq!(qm.uvs.len(), uvs.len());
        assert_eq!(qm.indices, idx);
    }

    #[test]
    fn test_default_draco_config() {
        let cfg = default_draco_config();
        assert_eq!(cfg.position_quantization, 11);
        assert_eq!(cfg.normal_quantization, 8);
        assert_eq!(cfg.uv_quantization, 10);
        assert!(cfg.use_edgebreaker);
    }
}