Skip to main content

character_compare/
character_compare.rs

1//! Reproduce character comparisons using a packed little-endian input file.
2//! Header: vertex/index/bone/blend/pose counts (five u32s); positions (3f),
3//! indices (u32), joints (4u32), weights (4f), blend deltas (3f), pose matrices (3x4f).
4use meshoptimizer_rs::*;
5use std::{error::Error as StdError, time::Instant};
6struct Reader<'a>(&'a [u8]);
7impl Reader<'_> {
8    fn u(&mut self) -> u32 {
9        let (v, rest) = self.0.split_at(4);
10        self.0 = rest;
11        u32::from_le_bytes(v.try_into().expect("four bytes"))
12    }
13    fn f(&mut self) -> f32 {
14        f32::from_bits(self.u())
15    }
16}
17fn main() -> Result<(), Box<dyn StdError>> {
18    let path = std::env::args().nth(1).ok_or("input file required")?;
19    let bytes = std::fs::read(&path)?;
20    let mut r = Reader(&bytes);
21    let [n, ni, nb, ns, np] = core::array::from_fn::<_, 5, _>(|_| r.u() as usize);
22    let p: Vec<[f32; 3]> = (0..n).map(|_| core::array::from_fn(|_| r.f())).collect();
23    let indices: Vec<u32> = (0..ni).map(|_| r.u()).collect();
24    let joints: Vec<u32> = (0..n * 4).map(|_| r.u()).collect();
25    let weights: Vec<f32> = (0..n * 4).map(|_| r.f()).collect();
26    let shapes: Vec<Vec<[f32; 3]>> = (0..ns)
27        .map(|_| (0..n).map(|_| core::array::from_fn(|_| r.f())).collect())
28        .collect();
29    let poses: Vec<Vec<[[f32; 4]; 3]>> = (0..np)
30        .map(|_| {
31            (0..nb)
32                .map(|_| core::array::from_fn(|_| core::array::from_fn(|_| r.f())))
33                .collect()
34        })
35        .collect();
36    assert!(r.0.is_empty());
37    let importance = vec![1.; nb];
38    let mut data = CharacterInputs::new();
39    if nb > 0 {
40        data.skin = Some(CharacterSkin::new(&joints, &weights, 4, &importance));
41    }
42    let shapes_ref: Vec<_> = shapes.iter().map(Vec::as_slice).collect();
43    let poses_ref: Vec<_> = poses.iter().map(Vec::as_slice).collect();
44    data.blend_shapes = &shapes_ref;
45    data.joint_poses = &poses_ref;
46    let mut samples = vec![p.clone()];
47    for s in &shapes {
48        samples.push(
49            p.iter()
50                .zip(s)
51                .map(|(p, s)| core::array::from_fn(|k| p[k] + s[k]))
52                .collect(),
53        );
54    }
55    for pose in &poses {
56        samples.push(
57            (0..n)
58                .map(|i| {
59                    core::array::from_fn(|k| {
60                        (0..4)
61                            .map(|j| {
62                                let m = pose[joints[i * 4 + j] as usize][k];
63                                weights[i * 4 + j]
64                                    * (m[0] * p[i][0] + m[1] * p[i][1] + m[2] * p[i][2] + m[3])
65                            })
66                            .sum()
67                    })
68                })
69                .collect(),
70        );
71    }
72    let mut ws = Workspace::default();
73    println!("ratio,method,triangles,bind,max_pose,milliseconds");
74    for ratio in [0.5, 0.25, 0.1] {
75        let settings = SimplifySettings {
76            target_index_count: ((ni / 3) as f64 * ratio) as usize * 3,
77            target_error: 100.,
78            options: SimplifyOptions::EMPTY,
79        };
80        for (method, blend_weight, skin_weight) in [
81            ("plain", 0., 0.),
82            ("character", 1., 1.),
83            ("skin_only", 0., 1.),
84        ] {
85            let mut options = CharacterOptions::default();
86            options.blend_shape_weight = blend_weight;
87            options.skin_weight = skin_weight;
88            let mut timings = Vec::new();
89            let mut output = None;
90            for repeat in 0..8 {
91                let start = Instant::now();
92                let mesh = if method == "plain" {
93                    simplify(&indices, Positions::from_packed(&p), settings, &mut ws)
94                        .map_err(|e| e.to_string())?
95                } else {
96                    simplify_character(
97                        &indices,
98                        Positions::from_packed(&p),
99                        &data,
100                        &options,
101                        settings,
102                        &mut ws,
103                    )
104                    .map_err(|e| e.to_string())?
105                };
106                if repeat > 0 {
107                    timings.push(start.elapsed().as_secs_f64() * 1000.);
108                }
109                if let Some(previous) = &output {
110                    let previous: &SimplifiedMesh = previous;
111                    assert_eq!(mesh.indices, previous.indices);
112                    assert_eq!(mesh.error.to_bits(), previous.error.to_bits());
113                }
114                output = Some(mesh);
115            }
116            timings.sort_by(f64::total_cmp);
117            let ms = timings[timings.len() / 2];
118            let mesh = output.ok_or("missing output")?;
119            let mut maxima = Vec::new();
120            let mut qo = LodQualityOptions::default();
121            qo.samples_per_unit_area = 0.;
122            for sample in &samples {
123                let p = Positions::from_packed(sample);
124                maxima.push(
125                    measure_lod_quality(
126                        LodQualityMesh::new(&indices, p),
127                        LodQualityMesh::new(&mesh.indices, p),
128                        &qo,
129                        &mut ws,
130                    )
131                    .map_err(|e| e.to_string())?
132                    .symmetric
133                    .max,
134                );
135            }
136            println!(
137                "{ratio},{method},{},{:.9},{:.9},{ms:.3}",
138                mesh.indices.len() / 3,
139                maxima[0],
140                maxima.iter().copied().fold(0., f64::max)
141            );
142        }
143    }
144    // Exercise chain pose evaluation on the same public model as well.
145    let co = LodChainOptions::new(
146        LodTargets::Ratios(&[0.5, 0.25, 0.1]),
147        LodErrors::Uniform(100.),
148    )
149    .with_independent(true);
150    let mut qo = LodQualityOptions::default();
151    qo.samples_per_unit_area = 0.;
152    let chain = build_character_lod_chain(
153        &indices,
154        Positions::from_packed(&p),
155        &data,
156        &CharacterOptions::default(),
157        &co,
158        &qo,
159        &mut ws,
160    )
161    .map_err(|e| e.to_string())?;
162    assert_eq!(chain.quality.len(), samples.len());
163    Ok(())
164}