Skip to main content

bread_format/
mesh_v2.rs

1/*
2 * SPDX-FileCopyrightText: 2026 SynrgStudio
3 * SPDX-License-Identifier: Apache-2.0
4 */
5
6//! Mesh chunk version 2 (`SPEC.md`, sections 6.6 to 6.9): the same mesh as
7//! version 1, kept as exactly, in fewer bytes.
8//!
9//! Triangles go in their own order (connectivity A) or in the order the
10//! triangle codec compresses best, with the way back (connectivity B).
11//! Vertices go through meshoptimizer's vertex codec, or are predicted from
12//! the triangles around them and only the difference is stored: entropy-coded
13//! with rANS, or as byte planes for the chunk's zstd.
14//!
15//! ```text
16//! metadata      as in version 1
17//! counts        u32 vertices, u32 triangles
18//! codings       u8 connectivity (0 A, 1 B), u8 vertex coding
19//!               (0 meshopt, 1 predicted + rANS, 2 predicted + planes)
20//! parts         u32 length + bytes each:
21//!               A: index buffer, corners
22//!               B: index buffer, permutation, corners
23//!               then meshopt: vertex buffer; rANS: tables, stream, raw
24//!               bits; planes: 12 byte planes
25//! ```
26
27use crate::bytes::{In, Out, fits_u32};
28use crate::mesh::{DecodeMeshError, EncodeMeshError, Mesh};
29use crate::meta::{read_meta, write_meta};
30use crate::parallel;
31
32/// The first byte of a vertex buffer: attribute codec version 1.
33const VERTEX_HEADER: u8 = 0xa1;
34/// The first byte of an index buffer: triangle codec version 1.
35const INDEX_HEADER: u8 = 0xe1;
36const VERTEX_VERSION: i32 = 1;
37const VERTEX_LEVEL: i32 = 2;
38const VERTICES_PER_BLOCK: usize = 256;
39const BLOCK_HEADER_BYTES: usize = 3;
40const INDEX_BUFFER_OVERHEAD: usize = 17;
41
42/// How a version 2 mesh stores its triangles.
43#[derive(Clone, Copy, Debug, PartialEq, Eq)]
44pub enum Connectivity {
45    /// In their own order, through the triangle codec, with each first
46    /// corner in 2 bits.
47    InOrder,
48    /// Reordered for the triangle codec, with the permutation back to their
49    /// order and each first corner.
50    Reordered,
51}
52
53/// How a version 2 mesh stores its vertices.
54#[derive(Clone, Copy, Debug, PartialEq, Eq)]
55pub enum VertexCoding {
56    /// meshoptimizer's vertex codec, version 1.
57    Meshopt,
58    /// Predicted from the triangles, the differences coded with rANS.
59    Rans,
60    /// Predicted from the triangles, the differences as 12 byte planes.
61    Planes,
62}
63
64/// The codings a version 2 mesh payload uses.
65#[derive(Clone, Copy, Debug, PartialEq, Eq)]
66pub struct MeshCoding {
67    pub connectivity: Connectivity,
68    pub vertices: VertexCoding,
69}
70
71// ---------------------------------------------------------------- bits
72
73/// Writes values least significant bit first.
74#[derive(Default)]
75struct BitWriter {
76    bytes: Vec<u8>,
77    acc: u64,
78    count: u32,
79}
80
81impl BitWriter {
82    fn put(&mut self, value: u32, bits: u32) {
83        if bits == 0 {
84            return;
85        }
86        self.acc |= (u64::from(value) & ((1u64 << bits) - 1)) << self.count;
87        self.count += bits;
88        while self.count >= 8 {
89            self.bytes.push(self.acc as u8);
90            self.acc >>= 8;
91            self.count -= 8;
92        }
93    }
94
95    fn finish(mut self) -> Vec<u8> {
96        if self.count > 0 {
97            self.bytes.push(self.acc as u8);
98        }
99        self.bytes
100    }
101}
102
103/// Reads what a [`BitWriter`] wrote, and nothing else: [`BitReader::done`]
104/// checks that every byte was needed and the padding is zero.
105struct BitReader<'a> {
106    bytes: &'a [u8],
107    pos: usize,
108}
109
110impl<'a> BitReader<'a> {
111    fn new(bytes: &'a [u8]) -> Self {
112        Self { bytes, pos: 0 }
113    }
114
115    fn get(&mut self, bits: u32) -> Option<u32> {
116        if bits == 0 {
117            return Some(0);
118        }
119        let byte = self.pos >> 3;
120        let value = match self.bytes.get(byte..byte + 8) {
121            // Eight whole bytes ahead: read them at once.
122            Some(word) => {
123                let word = u64::from_le_bytes(word.try_into().ok()?);
124                (word >> (self.pos & 7)) as u32 & ((1u64 << bits) - 1) as u32
125            }
126            // Near the end: bit by bit, so running out is noticed.
127            None => {
128                let mut value = 0u32;
129                for i in 0..bits {
130                    let byte = *self.bytes.get((self.pos + i as usize) >> 3)?;
131                    value |= u32::from((byte >> ((self.pos + i as usize) & 7)) & 1) << i;
132                }
133                value
134            }
135        };
136        self.pos += bits as usize;
137        Some(value)
138    }
139
140    fn done(&self) -> bool {
141        let used = self.pos.div_ceil(8);
142        used == self.bytes.len()
143            && (self.pos & 7 == 0 || self.bytes[used - 1] >> (self.pos & 7) == 0)
144    }
145}
146
147/// The number of bits each permutation entry takes: enough for `n - 1`, and
148/// at least 1.
149fn permutation_bits(triangles: usize) -> u32 {
150    usize::BITS - (triangles.max(2) - 1).leading_zeros()
151}
152
153// ---------------------------------------------------------------- prediction
154
155/// `f32` bits mapped to a `u32` that orders as the values do.
156fn ord(value: f32) -> u32 {
157    let bits = value.to_bits();
158    if bits & 0x8000_0000 != 0 {
159        !bits
160    } else {
161        bits | 0x8000_0000
162    }
163}
164
165fn unord(ordered: u32) -> f32 {
166    f32::from_bits(if ordered & 0x8000_0000 != 0 {
167        ordered & 0x7fff_ffff
168    } else {
169        !ordered
170    })
171}
172
173fn zigzag(value: u32) -> u32 {
174    let value = value as i32;
175    ((value << 1) ^ (value >> 31)) as u32
176}
177
178fn unzigzag(value: u32) -> u32 {
179    (value >> 1) ^ (value & 1).wrapping_neg()
180}
181
182/// The triangles around each vertex, and across each edge, of a triangle
183/// list. Built in linear time whatever the triangles, so a damaged or hostile
184/// mesh cannot make prediction slow.
185struct Topology {
186    /// For vertex `v`, `around[start[v]..start[v + 1]]` lists the triangles
187    /// that have it as a corner, each once, in increasing order.
188    start: Vec<u32>,
189    around: Vec<u32>,
190    /// For corner `k` of triangle `t`, at `3 t + k`: the first triangle other
191    /// than `t`, in increasing order, with an edge between the other two
192    /// corners, or `u32::MAX`.
193    across: Vec<u32>,
194}
195
196const NONE: u32 = u32::MAX;
197
198fn topology(triangles: &[[u32; 3]], vertex_count: usize) -> Topology {
199    // The two halves do not depend on each other.
200    let ((start, around), across) = parallel::join(
201        || around_vertices(triangles, vertex_count),
202        || across_edges(triangles, vertex_count),
203    );
204    Topology {
205        start,
206        around,
207        across,
208    }
209}
210
211/// `Topology::start` and `Topology::around`.
212fn around_vertices(triangles: &[[u32; 3]], vertex_count: usize) -> (Vec<u32>, Vec<u32>) {
213    // Triangles around each vertex, a triangle with a repeated corner once.
214    let mut start = vec![0u32; vertex_count + 1];
215    for t in triangles {
216        for (k, &v) in t.iter().enumerate() {
217            if !t[..k].contains(&v) {
218                start[v as usize + 1] += 1;
219            }
220        }
221    }
222    for v in 0..vertex_count {
223        start[v + 1] += start[v];
224    }
225    let mut fill = start.clone();
226    let mut around = vec![0u32; start[vertex_count] as usize];
227    for (i, t) in triangles.iter().enumerate() {
228        for (k, &v) in t.iter().enumerate() {
229            if !t[..k].contains(&v) {
230                around[fill[v as usize] as usize] = i as u32;
231                fill[v as usize] += 1;
232            }
233        }
234    }
235    (start, around)
236}
237
238/// `Topology::across`.
239fn across_edges(triangles: &[[u32; 3]], vertex_count: usize) -> Vec<u32> {
240    // Edges grouped by their lower vertex, then sorted by their higher one:
241    // the per-vertex lists are short in any mesh, and the total work is
242    // bounded by the triangle count whatever their degrees.
243    let mut edge_start = vec![0u32; vertex_count + 1];
244    for t in triangles {
245        for k in 0..3 {
246            let low = t[(k + 1) % 3].min(t[(k + 2) % 3]);
247            edge_start[low as usize + 1] += 1;
248        }
249    }
250    for v in 0..vertex_count {
251        edge_start[v + 1] += edge_start[v];
252    }
253    let mut fill = edge_start.clone();
254    // The higher vertex in the top half, the triangle's corner `3 t + k` in
255    // the bottom one, so sorting orders by edge, then by triangle.
256    let mut edges = vec![0u64; 3 * triangles.len()];
257    for (i, t) in triangles.iter().enumerate() {
258        for k in 0..3 {
259            let (a, b) = (t[(k + 1) % 3], t[(k + 2) % 3]);
260            let slot = &mut fill[a.min(b) as usize];
261            edges[*slot as usize] = (u64::from(a.max(b)) << 32) | (3 * i + k) as u64;
262            *slot += 1;
263        }
264    }
265    let mut across = vec![NONE; 3 * triangles.len()];
266    for v in 0..vertex_count {
267        let list = &mut edges[edge_start[v] as usize..edge_start[v + 1] as usize];
268        list.sort_unstable();
269        for group in list.chunk_by(|x, y| x >> 32 == y >> 32) {
270            let triangle = |e: &u64| (*e as u32) / 3;
271            // The first triangle on the edge, and the first one after it:
272            // a triangle meets an edge at most three times.
273            let first = triangle(&group[0]);
274            let second = group
275                .iter()
276                .map(triangle)
277                .find(|&t| t != first)
278                .unwrap_or(NONE);
279            for e in group {
280                let t = triangle(e);
281                across[*e as u32 as usize] = if t == first { second } else { first };
282            }
283        }
284    }
285    across
286}
287
288/// The prediction of vertex `v` from the vertices before it (`SPEC.md`,
289/// section 6.8). Every step is in `f64`, and the result is rounded to `f32`
290/// once; a result that is not finite becomes `+0.0`.
291fn predict(v: u32, triangles: &[[u32; 3]], topo: &Topology, vertices: &[[f32; 3]]) -> [f32; 3] {
292    let at = |i: u32| vertices[i as usize].map(f64::from);
293    let (mut para, mut para_n) = ([0f64; 3], 0u32);
294    let (mut mid, mut mid_n) = ([0f64; 3], 0u32);
295    let (mut near, mut near_n) = ([0f64; 3], 0u32);
296    let list = &topo.around[topo.start[v as usize] as usize..topo.start[v as usize + 1] as usize];
297    for &t in list {
298        let tri = triangles[t as usize];
299        let k = tri.iter().position(|&c| c == v).unwrap_or(0);
300        let (a, b) = (tri[(k + 1) % 3], tri[(k + 2) % 3]);
301        let (known_a, known_b) = (a < v, b < v);
302        if known_a {
303            let p = at(a);
304            (0..3).for_each(|i| near[i] += p[i]);
305            near_n += 1;
306        }
307        if known_b {
308            let p = at(b);
309            (0..3).for_each(|i| near[i] += p[i]);
310            near_n += 1;
311        }
312        if known_a && known_b {
313            let (pa, pb) = (at(a), at(b));
314            (0..3).for_each(|i| mid[i] += 0.5 * (pa[i] + pb[i]));
315            mid_n += 1;
316            let other = topo.across[3 * t as usize + k];
317            if other != NONE {
318                let opposite = triangles[other as usize]
319                    .into_iter()
320                    .find(|&c| c != a && c != b);
321                if let Some(c) = opposite.filter(|&c| c < v) {
322                    let pc = at(c);
323                    (0..3).for_each(|i| para[i] += (pa[i] + pb[i]) - pc[i]);
324                    para_n += 1;
325                }
326            }
327        }
328    }
329    let (sum, n) = if para_n > 0 {
330        (para, para_n)
331    } else if mid_n > 0 {
332        (mid, mid_n)
333    } else if near_n > 0 {
334        (near, near_n)
335    } else if v > 0 {
336        (at(v - 1), 1)
337    } else {
338        ([0.0; 3], 1)
339    };
340    sum.map(|s| {
341        let p = (s / f64::from(n)) as f32;
342        if p.is_finite() { p } else { 0.0 }
343    })
344}
345
346/// The residuals of `vertices`, in vertex order, each component zigzagged.
347fn residuals(vertices: &[[f32; 3]], triangles: &[[u32; 3]]) -> Vec<[u32; 3]> {
348    let topo = topology(triangles, vertices.len());
349    (0..vertices.len())
350        .map(|v| {
351            let p = predict(v as u32, triangles, &topo, vertices);
352            std::array::from_fn(|i| zigzag(ord(vertices[v][i]).wrapping_sub(ord(p[i]))))
353        })
354        .collect()
355}
356
357fn rebuild(residuals: &[[u32; 3]], triangles: &[[u32; 3]], topo: &Topology) -> Vec<[f32; 3]> {
358    let mut vertices = vec![[0f32; 3]; residuals.len()];
359    for v in 0..residuals.len() {
360        let p = predict(v as u32, triangles, topo, &vertices);
361        vertices[v] =
362            std::array::from_fn(|i| unord(ord(p[i]).wrapping_add(unzigzag(residuals[v][i]))));
363    }
364    vertices
365}
366
367// ---------------------------------------------------------------- rANS
368
369const PROB_BITS: u32 = 12;
370const PROB_TOTAL: u32 = 1 << PROB_BITS;
371const RANS_LOW: u32 = 1 << 23;
372/// High bits of a residual folded into its symbol, besides its bit length.
373const TOP_BITS: u32 = 2;
374const SYMBOLS: usize = 33 << TOP_BITS;
375const BUCKETS: usize = 34;
376const CONTEXTS: usize = 3 * BUCKETS;
377
378fn bit_length(r: u32) -> u32 {
379    u32::BITS - r.leading_zeros()
380}
381
382/// The context of component `comp` of a residual: the bit lengths of what
383/// came before it.
384fn context(comp: usize, current: &[u32; 3], previous: &[u32; 3]) -> usize {
385    let bucket = match comp {
386        0 => previous.iter().map(|&r| bit_length(r)).max().unwrap_or(0),
387        1 => bit_length(current[0]),
388        _ => (bit_length(current[0]) + bit_length(current[1])).div_ceil(2),
389    };
390    comp * BUCKETS + bucket as usize
391}
392
393/// A residual as a symbol (its bit length and up to two bits under the top
394/// one) and the raw bits below those.
395fn symbol(r: u32) -> (u32, u32, u32) {
396    let length = bit_length(r);
397    if length <= 1 {
398        return (length << TOP_BITS, 0, 0);
399    }
400    let low = length - 1;
401    let top = low.min(TOP_BITS);
402    let raw_bits = low - top;
403    let high = ((r >> raw_bits) & ((1 << top) - 1)) << (TOP_BITS - top);
404    let raw = r & ((1u64 << raw_bits) - 1) as u32;
405    ((length << TOP_BITS) | high, raw, raw_bits)
406}
407
408/// The residual a symbol and its raw bits stand for, or `None` for a symbol
409/// no writer produces.
410fn residual(symbol: u32, raw: &mut BitReader<'_>) -> Option<u32> {
411    let length = symbol >> TOP_BITS;
412    let high = symbol & ((1 << TOP_BITS) - 1);
413    if length <= 1 {
414        return (high == 0).then_some(length);
415    }
416    let low = length - 1;
417    let top = low.min(TOP_BITS);
418    if high & ((1 << (TOP_BITS - top)) - 1) != 0 {
419        return None;
420    }
421    let raw_bits = low - top;
422    Some((1 << low) | ((high >> (TOP_BITS - top)) << raw_bits) | raw.get(raw_bits)?)
423}
424
425/// Symbol frequencies summing to `PROB_TOTAL`, each used symbol at least 1.
426fn normalize(counts: &[u64]) -> Vec<u32> {
427    let total: u64 = counts.iter().sum();
428    let mut freq: Vec<u32> = counts
429        .iter()
430        .map(|&c| {
431            if c == 0 {
432                0
433            } else {
434                ((c * u64::from(PROB_TOTAL)) / total).max(1) as u32
435            }
436        })
437        .collect();
438    let mut sum: i64 = freq.iter().map(|&f| i64::from(f)).sum();
439    while sum != i64::from(PROB_TOTAL) {
440        let (i, _) = freq
441            .iter()
442            .enumerate()
443            .max_by_key(|&(i, &f)| (f, std::cmp::Reverse(i)))
444            .expect("a used context has a symbol");
445        if sum > i64::from(PROB_TOTAL) {
446            let take = (sum - i64::from(PROB_TOTAL)).min(i64::from(freq[i]) - 1);
447            freq[i] -= take as u32;
448            sum -= take;
449        } else {
450            freq[i] += (i64::from(PROB_TOTAL) - sum) as u32;
451            sum = i64::from(PROB_TOTAL);
452        }
453    }
454    freq
455}
456
457/// A context's table: frequencies, their running sums, and the symbol of
458/// every slot.
459struct Table {
460    freq: Vec<u32>,
461    cum: Vec<u32>,
462    slots: Vec<u16>,
463}
464
465fn table(freq: Vec<u32>) -> Table {
466    let mut cum = vec![0u32; freq.len() + 1];
467    for s in 0..freq.len() {
468        cum[s + 1] = cum[s] + freq[s];
469    }
470    let mut slots = vec![0u16; PROB_TOTAL as usize];
471    for s in 0..freq.len() {
472        slots[cum[s] as usize..cum[s + 1] as usize].fill(s as u16);
473    }
474    Table { freq, cum, slots }
475}
476
477/// Codes residuals as (tables, stream, raw bits).
478fn encode_rans(residuals: &[[u32; 3]]) -> [Vec<u8>; 3] {
479    let mut counts = vec![0u64; CONTEXTS * SYMBOLS];
480    let mut items = Vec::with_capacity(3 * residuals.len());
481    let mut raw = BitWriter::default();
482    let mut previous = [0u32; 3];
483    for r in residuals {
484        for comp in 0..3 {
485            let c = context(comp, r, &previous);
486            let (s, bits, n) = symbol(r[comp]);
487            counts[c * SYMBOLS + s as usize] += 1;
488            items.push((c, s as usize));
489            raw.put(bits, n);
490        }
491        previous = *r;
492    }
493    let mut tables_out = BitWriter::default();
494    let mut tables = Vec::with_capacity(CONTEXTS);
495    for c in 0..CONTEXTS {
496        let counts = &counts[c * SYMBOLS..(c + 1) * SYMBOLS];
497        if counts.iter().all(|&n| n == 0) {
498            tables_out.put(0, 1);
499            tables.push(None);
500            continue;
501        }
502        tables_out.put(1, 1);
503        let freq = normalize(counts);
504        for &f in &freq {
505            if f == 0 {
506                tables_out.put(0, 1);
507            } else {
508                tables_out.put(1, 1);
509                tables_out.put(f - 1, PROB_BITS);
510            }
511        }
512        tables.push(Some(table(freq)));
513    }
514    // rANS codes backwards, so the decoder reads forwards.
515    let mut x = RANS_LOW;
516    let mut stream = Vec::with_capacity(items.len());
517    for &(c, s) in items.iter().rev() {
518        let t = tables[c].as_ref().expect("a used context has a table");
519        let (f, start) = (t.freq[s], t.cum[s]);
520        let limit = ((RANS_LOW >> PROB_BITS) << 8) * f;
521        while x >= limit {
522            stream.push(x as u8);
523            x >>= 8;
524        }
525        x = ((x / f) << PROB_BITS) + (x % f) + start;
526    }
527    stream.extend(x.to_le_bytes());
528    stream.reverse();
529    [tables_out.finish(), stream, raw.finish()]
530}
531
532fn decode_rans(
533    tables: &[u8],
534    stream: &[u8],
535    raw: &[u8],
536    vertex_count: usize,
537) -> Option<Vec<[u32; 3]>> {
538    let mut bits = BitReader::new(tables);
539    let mut parsed: Vec<Option<Table>> = Vec::with_capacity(CONTEXTS);
540    for _ in 0..CONTEXTS {
541        if bits.get(1)? == 0 {
542            parsed.push(None);
543            continue;
544        }
545        let mut freq = Vec::with_capacity(SYMBOLS);
546        for _ in 0..SYMBOLS {
547            freq.push(if bits.get(1)? == 0 {
548                0
549            } else {
550                bits.get(PROB_BITS)? + 1
551            });
552        }
553        if freq.iter().sum::<u32>() != PROB_TOTAL {
554            return None;
555        }
556        parsed.push(Some(table(freq)));
557    }
558    if !bits.done() {
559        return None;
560    }
561    let (head, mut rest) = stream.split_first_chunk::<4>()?;
562    let mut x = u64::from(u32::from_be_bytes(*head));
563    let mut raw = BitReader::new(raw);
564    let mut out = Vec::with_capacity(vertex_count);
565    let mut previous = [0u32; 3];
566    for _ in 0..vertex_count {
567        let mut r = [0u32; 3];
568        for comp in 0..3 {
569            let t = parsed[context(comp, &r, &previous)].as_ref()?;
570            let slot = (x & u64::from(PROB_TOTAL - 1)) as u32;
571            let s = usize::from(t.slots[slot as usize]);
572            x = u64::from(t.freq[s]) * (x >> PROB_BITS) + u64::from(slot - t.cum[s]);
573            while x < u64::from(RANS_LOW) {
574                let (&byte, next) = rest.split_first()?;
575                x = (x << 8) | u64::from(byte);
576                rest = next;
577            }
578            r[comp] = residual(s as u32, &mut raw)?;
579        }
580        out.push(r);
581        previous = r;
582    }
583    (x == u64::from(RANS_LOW) && rest.is_empty() && raw.done()).then_some(out)
584}
585
586// ---------------------------------------------------------------- planes
587
588fn encode_planes(residuals: &[[u32; 3]]) -> Vec<u8> {
589    let mut out = Vec::with_capacity(12 * residuals.len());
590    for comp in 0..3 {
591        for byte in 0..4 {
592            out.extend(residuals.iter().map(|r| (r[comp] >> (8 * byte)) as u8));
593        }
594    }
595    out
596}
597
598fn decode_planes(planes: &[u8], vertex_count: usize) -> Option<Vec<[u32; 3]>> {
599    if Some(planes.len()) != vertex_count.checked_mul(12) {
600        return None;
601    }
602    let mut out = vec![[0u32; 3]; vertex_count];
603    for comp in 0..3 {
604        for byte in 0..4 {
605            let plane = &planes[(4 * comp + byte) * vertex_count..][..vertex_count];
606            for (r, &b) in out.iter_mut().zip(plane) {
607                r[comp] |= u32::from(b) << (8 * byte);
608            }
609        }
610    }
611    Some(out)
612}
613
614// ---------------------------------------------------------------- triangles
615
616/// The corner a stored triangle has to start from to be `original`: 0, 1 or
617/// 2, with `original[k] == stored[(k + r) % 3]`.
618fn corner(stored: &[u32], original: &[u32; 3]) -> u32 {
619    (0..3u32)
620        .find(|&r| (0..3).all(|k| stored[(k + r as usize) % 3] == original[k]))
621        .expect("the codec only rotates triangles")
622}
623
624fn encode_corners(stored: &[u32], triangles: &[[u32; 3]]) -> Vec<u8> {
625    let mut out = BitWriter::default();
626    for (s, t) in stored.as_chunks::<3>().0.iter().zip(triangles) {
627        out.put(corner(s, t), 2);
628    }
629    out.finish()
630}
631
632/// The stored triangles, each turned to start from its corner.
633fn apply_corners(stored: &[u32], corners: &[u8]) -> Option<Vec<[u32; 3]>> {
634    let mut bits = BitReader::new(corners);
635    let mut out = Vec::with_capacity(stored.len() / 3);
636    for s in stored.as_chunks::<3>().0 {
637        let r = bits.get(2)? as usize;
638        if r > 2 {
639            return None;
640        }
641        out.push(std::array::from_fn(|k| s[(k + r) % 3]));
642    }
643    bits.done().then_some(out)
644}
645
646fn encode_index_buffer(triangles: &[[u32; 3]], vertex_count: usize) -> (Vec<u8>, Vec<u32>) {
647    let encoded = meshopt::encode_index_buffer(triangles.as_flattened(), vertex_count)
648        .expect("whole triangles encode");
649    assert_eq!(
650        encoded.first(),
651        Some(&INDEX_HEADER),
652        "the triangle codec writes version 1"
653    );
654    let stored = meshopt::decode_index_buffer(&encoded, 3 * triangles.len())
655        .expect("the codec reads its own output");
656    (encoded, stored)
657}
658
659/// Whether connectivity B can store `mesh`: its vertices are numbered in the
660/// order its triangles first use them, and every vertex is used.
661pub(crate) fn in_first_use_order(mesh: &Mesh) -> bool {
662    let mut next = 0u32;
663    for &v in mesh.triangles.as_flattened() {
664        if v == next {
665            next += 1;
666        } else if v > next {
667            return false;
668        }
669    }
670    next as usize == mesh.vertices.len()
671}
672
673/// Connectivity B's order: the triangles reordered for the codec, with the
674/// vertices renumbered by first use in that order. Returns the reordered
675/// triangles (their own first corners) and vertices, and the original index
676/// of each reordered triangle.
677fn reorder(mesh: &Mesh) -> (Vec<[u32; 3]>, Vec<[f32; 3]>, Vec<u32>) {
678    let n = mesh.vertices.len();
679    // Match each reordered triangle to an original one by a key that does
680    // not depend on the first corner (the smallest of its three rotations);
681    // equal triangles match in any order.
682    let key = |t: &[u32]| -> (u32, u32, u32) {
683        (0..3)
684            .map(|r| (t[r], t[(r + 1) % 3], t[(r + 2) % 3]))
685            .min()
686            .unwrap_or_default()
687    };
688    // The originals' keys do not need the new order, so they are sorted
689    // while the optimizer finds it.
690    let (reordered, originals) = parallel::join(
691        || {
692            let order = meshopt::optimize_vertex_cache(mesh.triangles.as_flattened(), n);
693            let mut reordered: Vec<_> = order
694                .as_chunks::<3>()
695                .0
696                .iter()
697                .enumerate()
698                .map(|(j, t)| (key(t), j as u32))
699                .collect();
700            reordered.sort_unstable();
701            reordered
702        },
703        || {
704            let mut originals: Vec<_> = mesh
705                .triangles
706                .iter()
707                .enumerate()
708                .map(|(i, t)| (key(t), i as u32))
709                .collect();
710            originals.sort_unstable();
711            originals
712        },
713    );
714    let mut permutation = vec![0u32; mesh.triangles.len()];
715    for (o, r) in originals.iter().zip(&reordered) {
716        debug_assert_eq!(o.0, r.0);
717        permutation[r.1 as usize] = o.1;
718    }
719    let mut renumber = vec![NONE; n];
720    let mut vertices = Vec::with_capacity(n);
721    let triangles = permutation
722        .iter()
723        .map(|&p| {
724            mesh.triangles[p as usize].map(|v| {
725                let new = &mut renumber[v as usize];
726                if *new == NONE {
727                    *new = vertices.len() as u32;
728                    vertices.push(mesh.vertices[v as usize]);
729                }
730                *new
731            })
732        })
733        .collect();
734    (triangles, vertices, permutation)
735}
736
737// ---------------------------------------------------------------- payload
738
739/// The triangles and vertices of `mesh` as the vertex coding sees them, and
740/// the connectivity parts.
741struct Prepared {
742    parts: Vec<Vec<u8>>,
743    triangles: Vec<[u32; 3]>,
744    vertices: Vec<[f32; 3]>,
745}
746
747fn prepare(mesh: &Mesh, connectivity: Connectivity) -> Prepared {
748    let n = mesh.vertices.len();
749    match connectivity {
750        Connectivity::InOrder => {
751            let (index, stored) = encode_index_buffer(&mesh.triangles, n);
752            let corners = encode_corners(&stored, &mesh.triangles);
753            Prepared {
754                parts: vec![index, corners],
755                triangles: mesh.triangles.clone(),
756                vertices: mesh.vertices.clone(),
757            }
758        }
759        Connectivity::Reordered => {
760            let (triangles, vertices, permutation) = reorder(mesh);
761            let (index, stored) = encode_index_buffer(&triangles, n);
762            let bits = permutation_bits(triangles.len());
763            let mut perm = BitWriter::default();
764            for &p in &permutation {
765                perm.put(p, bits);
766            }
767            let corners = encode_corners(&stored, &triangles);
768            Prepared {
769                parts: vec![index, perm.finish(), corners],
770                triangles,
771                vertices,
772            }
773        }
774    }
775}
776
777fn vertex_parts(prepared: &Prepared, coding: VertexCoding, residuals: &[[u32; 3]]) -> Vec<Vec<u8>> {
778    match coding {
779        VertexCoding::Meshopt => vec![
780            meshopt::encode_vertex_buffer_level(
781                &prepared.vertices,
782                VERTEX_LEVEL,
783                Some(VERTEX_VERSION),
784            )
785            .expect("12-byte vertices encode"),
786        ],
787        VertexCoding::Rans => encode_rans(residuals).into(),
788        VertexCoding::Planes => vec![encode_planes(residuals)],
789    }
790}
791
792fn assemble(
793    mesh: &Mesh,
794    coding: MeshCoding,
795    parts: &[Vec<u8>],
796) -> Result<Vec<u8>, EncodeMeshError> {
797    if parts.iter().any(|part| !fits_u32(part.len())) {
798        return Err(EncodeMeshError::TooLarge);
799    }
800    let mut out = Out::default();
801    write_meta(&mut out, mesh.meta.as_ref());
802    out.len(mesh.vertices.len());
803    out.len(mesh.triangles.len());
804    out.u8(match coding.connectivity {
805        Connectivity::InOrder => 0,
806        Connectivity::Reordered => 1,
807    });
808    out.u8(match coding.vertices {
809        VertexCoding::Meshopt => 0,
810        VertexCoding::Rans => 1,
811        VertexCoding::Planes => 2,
812    });
813    for part in parts {
814        out.bytes(part);
815    }
816    Ok(out.0)
817}
818
819/// What every coding needs of a mesh, and whether `coding` can store it.
820fn check(mesh: &Mesh, coding: MeshCoding) -> Result<(), EncodeMeshError> {
821    let n = mesh.vertices.len();
822    if !fits_u32(n) || !fits_u32(mesh.triangles.len()) {
823        return Err(EncodeMeshError::TooLarge);
824    }
825    if mesh
826        .triangles
827        .as_flattened()
828        .iter()
829        .any(|&v| v as usize >= n)
830    {
831        return Err(EncodeMeshError::VertexOutOfRange);
832    }
833    if coding.connectivity == Connectivity::Reordered && !in_first_use_order(mesh) {
834        return Err(EncodeMeshError::Unsupported);
835    }
836    if coding.vertices == VertexCoding::Rans && n > 3 * mesh.triangles.len() {
837        return Err(EncodeMeshError::Unsupported);
838    }
839    Ok(())
840}
841
842/// Encodes `mesh` as a mesh chunk payload of version 2 with the given
843/// codings.
844///
845/// Connectivity B needs the vertices in first-use order, every one used; the
846/// rANS coding needs no more than three vertices per triangle.
847pub fn encode_mesh_v2_with(mesh: &Mesh, coding: MeshCoding) -> Result<Vec<u8>, EncodeMeshError> {
848    check(mesh, coding)?;
849    let prepared = prepare(mesh, coding.connectivity);
850    let residuals = match coding.vertices {
851        VertexCoding::Meshopt => Vec::new(),
852        _ => residuals(&prepared.vertices, &prepared.triangles),
853    };
854    let mut parts = prepared.parts.clone();
855    parts.extend(vertex_parts(&prepared, coding.vertices, &residuals));
856    assemble(mesh, coding, &parts)
857}
858
859/// The zstd level the container compresses chunks at, to compare candidates
860/// as they will be stored.
861const STORED_LEVEL: i32 = 3;
862
863fn stored_size(parts: &[Vec<u8>]) -> usize {
864    zstd::bulk::compress(&parts.concat(), STORED_LEVEL).map_or(usize::MAX, |s| s.len())
865}
866
867/// Encodes `mesh` as a mesh chunk payload of version 2, choosing the codings
868/// that store it smallest.
869///
870/// Connectivity B is tried only when the triangle codec needs more than 2
871/// bytes a triangle in the mesh's own order, which is when exporters wrote
872/// the triangles scattered. The three vertex codings are then compared in the
873/// winning order. Every choice is made on the sizes the container stores.
874pub fn encode_mesh_v2(mesh: &Mesh) -> Result<Vec<u8>, EncodeMeshError> {
875    let a = MeshCoding {
876        connectivity: Connectivity::InOrder,
877        vertices: VertexCoding::Meshopt,
878    };
879    check(mesh, a)?;
880    let in_order = prepare(mesh, Connectivity::InOrder);
881    let nt = mesh.triangles.len();
882    let (prepared, connectivity) =
883        if nt > 0 && in_order.parts[0].len() > 2 * nt && in_first_use_order(mesh) {
884            // B's order takes long to find: A's size is measured meanwhile.
885            let (reordered, in_order_size) = parallel::join(
886                || prepare(mesh, Connectivity::Reordered),
887                || stored_size(&in_order.parts),
888            );
889            if stored_size(&reordered.parts) < in_order_size {
890                (reordered, Connectivity::Reordered)
891            } else {
892                (in_order, Connectivity::InOrder)
893            }
894        } else {
895            (in_order, Connectivity::InOrder)
896        };
897    let try_coding = |vertices: VertexCoding, residuals: &[[u32; 3]]| {
898        let coding = MeshCoding {
899            connectivity,
900            vertices,
901        };
902        check(mesh, coding).ok()?;
903        let mut parts = prepared.parts.clone();
904        parts.extend(vertex_parts(&prepared, vertices, residuals));
905        Some((stored_size(&parts), coding, parts))
906    };
907    // The vertex codings are tried side by side: meshopt on its own, and the
908    // two that code the prediction's residuals once they are computed.
909    let (meshopt, predicted) = parallel::join(
910        || try_coding(VertexCoding::Meshopt, &[]),
911        || {
912            let residuals = residuals(&prepared.vertices, &prepared.triangles);
913            let (rans, planes) = parallel::join(
914                || try_coding(VertexCoding::Rans, &residuals),
915                || try_coding(VertexCoding::Planes, &residuals),
916            );
917            [rans, planes]
918        },
919    );
920    // The smallest wins; on a tie, the first in the order meshopt, rANS,
921    // planes.
922    let (_, coding, parts) = [meshopt]
923        .into_iter()
924        .chain(predicted)
925        .flatten()
926        .reduce(|best, next| if next.0 < best.0 { next } else { best })
927        .expect("the meshopt coding stores any mesh");
928    assemble(mesh, coding, &parts)
929}
930
931/// Decodes a mesh chunk payload of version 2.
932pub fn decode_mesh_v2(payload: &[u8]) -> Result<Mesh, DecodeMeshError> {
933    decode(&mut In(payload)).ok_or(DecodeMeshError::Malformed)?
934}
935
936fn decode(input: &mut In<'_>) -> Option<Result<Mesh, DecodeMeshError>> {
937    let meta = read_meta(input)?;
938    let n = input.len()?;
939    let nt = input.len()?;
940    let connectivity = match input.u8()? {
941        0 => Connectivity::InOrder,
942        1 => Connectivity::Reordered,
943        _ => return None,
944    };
945    let coding = match input.u8()? {
946        0 => VertexCoding::Meshopt,
947        1 => VertexCoding::Rans,
948        2 => VertexCoding::Planes,
949        _ => return None,
950    };
951    let index = input.bytes()?;
952    if index.first() != Some(&INDEX_HEADER)
953        || nt > index.len().checked_sub(INDEX_BUFFER_OVERHEAD)?
954    {
955        return None;
956    }
957    let permutation = match connectivity {
958        Connectivity::InOrder => None,
959        Connectivity::Reordered => Some(input.bytes()?),
960    };
961    let corners = input.bytes()?;
962    // Bound the vertex count by the coding before reserving anything.
963    let vertex_parts: Vec<&[u8]> = match coding {
964        VertexCoding::Meshopt => {
965            let buffer = input.bytes()?;
966            if buffer.first() != Some(&VERTEX_HEADER)
967                || n.checked_mul(BLOCK_HEADER_BYTES)?
968                    >= buffer.len().checked_mul(VERTICES_PER_BLOCK)?
969            {
970                return None;
971            }
972            vec![buffer]
973        }
974        VertexCoding::Rans => {
975            if n > nt.checked_mul(3)? {
976                return None;
977            }
978            vec![input.bytes()?, input.bytes()?, input.bytes()?]
979        }
980        VertexCoding::Planes => {
981            let planes = input.bytes()?;
982            if Some(planes.len()) != n.checked_mul(12) {
983                return None;
984            }
985            vec![planes]
986        }
987    };
988    if !input.is_empty() {
989        return None;
990    }
991
992    // The triangles, with the topology the prediction walks, and the vertex
993    // parts do not depend on each other, so they are decoded side by side.
994    // The triangles' faults still come first, as if decoded one after the
995    // other.
996    let predicted = coding != VertexCoding::Meshopt;
997    let (connectivity_part, vertex_part) = parallel::join(
998        || {
999            let stored: Vec<u32> = meshopt::decode_index_buffer(index, nt.checked_mul(3)?).ok()?;
1000            let triangles = apply_corners(&stored, corners)?;
1001            if triangles.as_flattened().iter().any(|&v| v as usize >= n) {
1002                return Some(Err(DecodeMeshError::VertexOutOfRange));
1003            }
1004            let topo = predicted.then(|| topology(&triangles, n));
1005            Some(Ok((triangles, topo)))
1006        },
1007        || match coding {
1008            VertexCoding::Meshopt => meshopt::decode_vertex_buffer(vertex_parts[0], n)
1009                .ok()
1010                .map(VertexPart::Vertices),
1011            VertexCoding::Rans => decode_rans(vertex_parts[0], vertex_parts[1], vertex_parts[2], n)
1012                .map(VertexPart::Residuals),
1013            VertexCoding::Planes => decode_planes(vertex_parts[0], n).map(VertexPart::Residuals),
1014        },
1015    );
1016    let (triangles, topo) = match connectivity_part? {
1017        Ok(decoded) => decoded,
1018        Err(err) => return Some(Err(err)),
1019    };
1020    let vertices = match (vertex_part?, topo) {
1021        (VertexPart::Vertices(vertices), _) => vertices,
1022        (VertexPart::Residuals(residuals), Some(topo)) => rebuild(&residuals, &triangles, &topo),
1023        (VertexPart::Residuals(_), None) => unreachable!("predicted codings build the topology"),
1024    };
1025    let mesh = match permutation {
1026        None => Mesh {
1027            meta: None,
1028            vertices,
1029            triangles,
1030        },
1031        Some(bytes) => restore_order(bytes, vertices, &triangles)?,
1032    };
1033    Some(Ok(Mesh { meta, ..mesh }))
1034}
1035
1036/// The vertex part of a mesh, decoded: the vertices themselves, or the
1037/// prediction's residuals.
1038enum VertexPart {
1039    Vertices(Vec<[f32; 3]>),
1040    Residuals(Vec<[u32; 3]>),
1041}
1042
1043/// Connectivity B: puts the triangles back in their order, and numbers the
1044/// vertices by first use in it.
1045fn restore_order(bytes: &[u8], vertices: Vec<[f32; 3]>, triangles: &[[u32; 3]]) -> Option<Mesh> {
1046    let nt = triangles.len();
1047    let bits = permutation_bits(nt);
1048    let mut reader = BitReader::new(bytes);
1049    let mut original = vec![None; nt];
1050    for t in triangles {
1051        let p = reader.get(bits)? as usize;
1052        let slot = original.get_mut(p)?;
1053        if slot.is_some() {
1054            return None;
1055        }
1056        *slot = Some(*t);
1057    }
1058    if !reader.done() {
1059        return None;
1060    }
1061    let mut renumber = vec![NONE; vertices.len()];
1062    let mut ordered = Vec::with_capacity(vertices.len());
1063    let triangles = original
1064        .into_iter()
1065        .map(|t| {
1066            t.map(|t| {
1067                t.map(|v| {
1068                    let new = &mut renumber[v as usize];
1069                    if *new == NONE {
1070                        *new = ordered.len() as u32;
1071                        ordered.push(vertices[v as usize]);
1072                    }
1073                    *new
1074                })
1075            })
1076        })
1077        .collect::<Option<Vec<_>>>()?;
1078    (ordered.len() == vertices.len()).then_some(Mesh {
1079        meta: None,
1080        vertices: ordered,
1081        triangles,
1082    })
1083}