Skip to main content

vg_foliage_measure/
vg_foliage_measure.rs

1//! CPU foliage receipt from a caller-prepared binary mesh and alpha mask.
2//! Input: u32 vertex/index counts and mask width/height, packed f32 positions,
3//! packed f32 UVs, u32 indices, then tightly packed alpha bytes, little endian.
4#![allow(clippy::field_reassign_with_default)]
5use meshoptimizer_rs::{
6    clusterlod::{
7        self as cl,
8        cut::{self, CutView, Projection, Threshold},
9        page::QuantGrid,
10        v2::{self, AlphaCoverage, BuildMesh},
11    },
12    *,
13};
14use std::{error::Error, fs};
15
16fn main() -> Result<(), Box<dyn Error>> {
17    let data = fs::read(std::env::args().nth(1).ok_or("input required")?)?;
18    let mut at = 0;
19    let mut word = || {
20        let x = u32::from_le_bytes(data[at..at + 4].try_into().expect("input word"));
21        at += 4;
22        x
23    };
24    let n = word() as usize;
25    let ni = word() as usize;
26    let w = word();
27    let h = word();
28    let p: Vec<[f32; 3]> = (0..n)
29        .map(|_| {
30            [
31                f32::from_bits(word()),
32                f32::from_bits(word()),
33                f32::from_bits(word()),
34            ]
35        })
36        .collect();
37    let uv: Vec<f32> = (0..n * 2).map(|_| f32::from_bits(word())).collect();
38    let indices: Vec<u32> = (0..ni).map(|_| word()).collect();
39    let mask = AlphaMask::new(&data[at..], w, h)?;
40    let masks = [Some(mask)];
41    let attrs = Attributes::from_interleaved(&uv, n, 2, 2, 0)?;
42    let mut config = cl::default_config(32)?;
43    config.partition_size = 2;
44    config.optimize_clusters = false;
45    let grid = QuantGrid::new(-16)?;
46    let run = |alpha| {
47        let mut m = BuildMesh::new(&indices, &p);
48        m.attributes = Some(attrs);
49        m.attribute_weights = &[0., 0.];
50        if alpha {
51            m.alpha_coverage = Some(AlphaCoverage::new(&masks, 0));
52        }
53        v2::build(config, m, grid, &mut Workspace::default())
54    };
55    let mut off = run(false)?;
56    let mut on = run(true)?;
57    // Use the actual container's repaired spheres and quantisation error floor.
58    for b in [&mut off, &mut on] {
59        let source =
60            cl::dag_format::v2::Source::new(&b.groups, &b.clusters, &b.positions, &b.indices);
61        let (file, _) = cl::dag_format::v2::write(
62            &source,
63            &cl::dag_format::v2::WriteOptions::new(grid),
64            &mut Workspace::default(),
65        )?;
66        let reader = cl::dag_format::v2::Reader::read_all(&file, &mut Workspace::default())?;
67        let count = b.groups.len();
68        for (i, g) in b.groups.iter_mut().enumerate() {
69            let record = reader.group(count - 1 - i)?;
70            g.center = record.center;
71            g.radius = record.radius;
72            g.error = record.error;
73        }
74    }
75    let radius = p
76        .iter()
77        .map(|p| p.iter().map(|v| v * v).sum::<f32>().sqrt())
78        .fold(0f32, f32::max);
79    let bounds = ImpostorBounds::new([0.; 3], radius * 1.001)?;
80    let grid_views = ImpostorGrid::new(ImpostorLayout::Sphere, 3)?;
81    let render = |b: &v2::Built, idx: &[u32], resolution| {
82        let uvs: Vec<[f32; 2]> = b
83            .attributes
84            .chunks_exact(b.attribute_stride)
85            .map(|a| [a[0], a[1]])
86            .collect();
87        let sampler = |_: usize, uv: [f32; 2]| {
88            let x = ((uv[0] as f64).rem_euclid(1.0) * w as f64) as u32;
89            let y = ((uv[1] as f64).rem_euclid(1.0) * h as f64) as u32;
90            [
91                1.,
92                1.,
93                1.,
94                f32::from(mask.alpha(x.min(w - 1), y.min(h - 1)).unwrap_or(0)) / 255.,
95            ]
96        };
97        let mut options = ImpostorOptions::default();
98        options.grid = grid_views;
99        options.bounds = Some(bounds);
100        options.view_resolution = resolution;
101        options.dilation = 0;
102        options.coverage_threshold = 1.;
103        bake_impostor(
104            idx,
105            Positions::from_packed(&b.positions),
106            None,
107            ImpostorAlbedo::Texture {
108                uvs: &uvs,
109                sampler: &sampler,
110            },
111            options,
112            &mut Workspace::default(),
113        )
114    };
115    let leaf: Vec<u32> = off
116        .clusters
117        .iter()
118        .filter(|c| c.refined < 0)
119        .flat_map(|c| {
120            off.indices[c.first_index as usize..(c.first_index + c.index_count) as usize]
121                .iter()
122                .copied()
123        })
124        .collect();
125    println!("source_triangles={} off_stuck={} on_stuck={} alpha_stuck={} raised={} off_dag_triangles={} on_dag_triangles={}",ni/3,off.stuck_groups,on.stuck_groups,on.alpha_coverage_stuck_groups,on.alpha_coverage_raised_groups,off.indices.len()/3,on.indices.len()/3);
126    for distance in [4f32, 8., 16., 32., 64.] {
127        let view = CutView {
128            position: [0., 0., distance],
129            projection: Projection::Perspective {
130                proj_y: 1.0 / (0.5f32).tan(),
131                znear: 0.01,
132            },
133            viewport_height: 1080.,
134            scale: 1.0,
135        };
136        let resolution = ((2. * radius / distance * (1080. / (2. * (0.5f32).tan()))).round()
137            as u32)
138            .clamp(8, 512);
139        let reference = render(&off, &leaf, resolution)?;
140        for (name, b) in [("off", &off), ("on", &on)] {
141            let mut cut = vec![0u32; b.clusters.len()];
142            let count = cut::select_cut(
143                &b.groups,
144                &b.clusters,
145                &view,
146                Threshold::Pixels(1.0),
147                None,
148                &mut cut,
149            )?;
150            let chosen: Vec<u32> = cut[..count]
151                .iter()
152                .flat_map(|&c| {
153                    let c = &b.clusters[c as usize];
154                    b.indices[c.first_index as usize..(c.first_index + c.index_count) as usize]
155                        .iter()
156                        .copied()
157                })
158                .collect();
159            let atlas = render(b, &chosen, resolution)?;
160            let r = resolution as usize;
161            let size = r * 3;
162            let mut ratios = Vec::new();
163            let mut max_blur = 0f64;
164            for v in 0..9 {
165                let (ox, oy) = ((v % 3) * r, (v / 3) * r);
166                let mut sums = [0u64; 2];
167                let mut blur = 0.;
168                for y in 0..r {
169                    for x in 0..r {
170                        let i = (oy + y) * size + ox + x;
171                        sums[0] += u64::from(reference.albedo_alpha[i][3]);
172                        sums[1] += u64::from(atlas.albedo_alpha[i][3]);
173                        let mut d = 0i32;
174                        for dy in -1isize..=1 {
175                            for dx in -1isize..=1 {
176                                let j = (oy + y.saturating_add_signed(dy).min(r - 1)) * size
177                                    + ox
178                                    + x.saturating_add_signed(dx).min(r - 1);
179                                d += i32::from(reference.albedo_alpha[j][3])
180                                    - i32::from(atlas.albedo_alpha[j][3]);
181                            }
182                        }
183                        blur += f64::from(d.abs()) / (255. * 9.);
184                    }
185                }
186                ratios.push(if sums[0] == 0 {
187                    if sums[1] == 0 {
188                        1.
189                    } else {
190                        f64::INFINITY
191                    }
192                } else {
193                    sums[1] as f64 / sums[0] as f64
194                });
195                max_blur = max_blur.max(blur / (r * r) as f64);
196            }
197            println!("distance={distance} resolution={resolution} policy={name} triangles={} ratio_min={:.6} ratio_max={:.6} blurred_max={max_blur:.6}",chosen.len()/3,ratios.iter().copied().fold(f64::INFINITY,f64::min),ratios.iter().copied().fold(0.,f64::max));
198        }
199    }
200    for (name, b) in [("off", &off), ("on", &on)] {
201        let report =
202            v2::measure_fallback(b, &LodQualityOptions::default(), &mut Workspace::default())?;
203        println!(
204            "fallback={name} triangles={} sampled_max={} sampled_rms={}",
205            report.indices.len() / 3,
206            report.quality.symmetric.max,
207            report.quality.symmetric.rms
208        );
209    }
210    Ok(())
211}