Skip to main content

IndexEncoding

Struct IndexEncoding 

Source
pub struct IndexEncoding { /* private fields */ }
Expand description

Index buffer and index sequence format version (the setting of meshopt_encodeIndexVersion).

Implementations§

Source§

impl IndexEncoding

Source

pub const DEFAULT: Self

Upstream default: version 1.

Source

pub const fn new(version: u8) -> Result<Self, Error>

Check a version: 0 (decodable by all versions) or 1.

§Errors

UnsupportedVersion if the version is not 0 or 1;

Examples found in repository?
examples/page_codec_measure.rs (line 96)
13fn main() {
14    println!("mesh,grid_exponent,dag_triangles,clusters,pages,meshlet_bytes,index_sequence_bytes,memory_bytes,disk_bytes,memory_b_per_triangle,disk_b_per_triangle");
15    for path in std::env::args().skip(1) {
16        let b = fs::read(&path).unwrap();
17        let nv = u32_at(&b, 0) as usize;
18        let ni = u32_at(&b, 4) as usize;
19        let mut positions: Vec<[f32; 3]> = (0..nv)
20            .map(|i| core::array::from_fn(|k| f32::from_bits(u32_at(&b, 8 + i * 12 + k * 4))))
21            .collect();
22        let indices: Vec<_> = (0..ni).map(|i| u32_at(&b, 8 + nv * 12 + i * 4)).collect();
23        drop(b);
24        let (mut min, mut max) = ([f32::MAX; 3], [f32::MIN; 3]);
25        for p in &positions {
26            for ((lo, hi), &x) in min.iter_mut().zip(&mut max).zip(p) {
27                *lo = lo.min(x);
28                *hi = hi.max(x);
29            }
30        }
31        let grid = QuantGrid::from_bounds(min, max, 16).unwrap();
32        grid.snap_positions(&mut positions).unwrap();
33        let mut source = vec![0; ni * 8];
34        let mut vp = vec![[0.; 3]; ni * 8];
35        let mut ix = vec![0; ni * 8];
36        let mut cl = vec![FlatDagCluster::default(); ni / 3];
37        let mut gr = vec![FlatDagGroup::default(); ni / 3];
38        let mut nodes = vec![Node::default(); ni / 3 + 128];
39        let mut ws = Workspace::default();
40        let counts = build_dag_into(
41            default_config(128).unwrap(),
42            Mesh {
43                indices: &indices,
44                positions: &mut positions,
45                attributes: None,
46                vertex_lock: None,
47                attribute_weights: &[],
48                attribute_protect_mask: 0,
49            },
50            8,
51            DagBuffers {
52                vertex_source: &mut source,
53                vertex_positions: &mut vp,
54                indices: &mut ix,
55                clusters: &mut cl,
56                groups: &mut gr,
57                nodes: &mut nodes,
58            },
59            &mut ws,
60        )
61        .unwrap();
62        drop(source);
63        drop(nodes);
64        let (mut meshlet, mut sequence, mut memory, mut disk, mut pages) = (0, 0, 0, 0, 0);
65        let mut locals = Vec::new();
66        for c in &cl[..counts.clusters] {
67            let tri = &ix[c.first_index as usize..][..c.index_count as usize];
68            let (mut local, mut ids, mut pos) = (Vec::new(), Vec::new(), Vec::new());
69            for &v in tri {
70                let k = ids.iter().position(|&x| x == v).unwrap_or_else(|| {
71                    ids.push(v);
72                    pos.push(vp[v as usize]);
73                    ids.len() - 1
74                });
75                local.push(k as u32);
76            }
77            locals.push((c.group, c.refined, pos, local));
78        }
79        for chunk in locals.chunks(CLUSTERS_PER_PAGE) {
80            let clusters: Vec<_> = chunk
81                .iter()
82                .map(|(g, r, p, i)| PageCluster::new(*g, *r, p, i))
83                .collect();
84            let page = encode_page(grid, &clusters, 0, &mut ws).unwrap();
85            let view = PageView::new(&page, grid).unwrap();
86            for c in 0..view.cluster_count() {
87                let mut t = [[0u8; 3]; 256];
88                let n = view.decode_triangles(c, &mut t).unwrap();
89                let nv = view.cluster(c).unwrap().vertex_count;
90                let refs: Vec<u32> = (0..nv).collect();
91                let flat: Vec<u8> = t[..n].iter().flatten().copied().collect();
92                meshlet += codec::encode_meshlet(&refs, &flat, &mut ws).unwrap().len();
93                let wide: Vec<u32> = flat.iter().map(|&i| u32::from(i)).collect();
94                sequence += codec::encode_index_sequence(
95                    &wide,
96                    codec::IndexEncoding::new(1).unwrap(),
97                    &mut ws,
98                )
99                .unwrap()
100                .len();
101            }
102            memory += page.len() * 4;
103            disk += encode_disk_page(&page, grid, DiskCodec::Compressed, &mut ws)
104                .unwrap()
105                .len();
106            pages += 1;
107        }
108        let triangles = counts.indices / 3;
109        println!(
110            "{path},{},{triangles},{},{pages},{meshlet},{sequence},{memory},{disk},{:.3},{:.3}",
111            grid.exponent(),
112            counts.clusters,
113            memory as f64 / triangles as f64,
114            disk as f64 / triangles as f64,
115        );
116    }
117}
More examples
Hide additional examples
examples/buffer_stream_bench.rs (line 69)
32fn main() {
33    let n = 65536;
34    let stride = 32;
35    // Smooth per-vertex attributes with small deterministic noise.
36    let mut rng = 1u32;
37    let vertices: Vec<u8> = (0..n)
38        .flat_map(|v| {
39            (0..stride / 4)
40                .flat_map(|k| {
41                    rng ^= rng << 13;
42                    rng ^= rng >> 17;
43                    rng ^= rng << 5;
44                    let value = (v * (k + 1) * 3) as u32 + (rng & 7);
45                    value.to_le_bytes()
46                })
47                .collect::<Vec<_>>()
48        })
49        .collect();
50    // A 256 x 256 vertex grid of quads, two triangles each, in row order.
51    let indices: Vec<u32> = (0..255u32)
52        .flat_map(|y| (0..255u32).map(move |x| (x, y)))
53        .flat_map(|(x, y)| {
54            let a = y * 256 + x;
55            [a, a + 1, a + 256, a + 1, a + 257, a + 256]
56        })
57        .collect();
58    for version in 0..=1 {
59        let v = encode_vertex_buffer(
60            &vertices,
61            n,
62            stride,
63            VertexEncoding::new(version, 2).unwrap(),
64            &mut Workspace::default(),
65        )
66        .unwrap();
67        let t = encode_index_buffer(
68            &indices,
69            IndexEncoding::new(version).unwrap(),
70            &mut Workspace::default(),
71        )
72        .unwrap();
73        let mut vo = vec![0; vertices.len()];
74        let mut to = vec![0; indices.len() * 4];
75        let vb = vo.len();
76        let tb = to.len();
77        let vm = measure(
78            &format!("v{version}:vertex:oneshot"),
79            || {
80                decode_vertex_buffer_into(
81                    black_box(&mut vo),
82                    n,
83                    stride,
84                    &v,
85                    &mut Workspace::default(),
86                )
87                .unwrap()
88            },
89            vb,
90        );
91        let tm = measure(
92            &format!("v{version}:tri:oneshot"),
93            || {
94                decode_index_buffer_into(
95                    black_box(&mut to),
96                    indices.len(),
97                    4,
98                    &t,
99                    &mut Workspace::default(),
100                )
101                .unwrap()
102            },
103            tb,
104        );
105        println!("v{version} one-shot vertex={vm:.2} triangle={tm:.2} MB/s decoded");
106        for chunk in [4096, 65536] {
107            let tail = (stride + if version == 0 { 0 } else { stride / 4 }).max(if version == 0 {
108                32
109            } else {
110                24
111            });
112            let end = v.len() - tail;
113            let size = vo.len();
114            let rate = measure(
115                &format!("v{version}:vertex:{chunk}"),
116                || {
117                    let mut d = VertexBufferDecoder::new(
118                        n,
119                        stride,
120                        v[0],
121                        &v[end..],
122                        end - 1,
123                        Limits::default(),
124                    )
125                    .unwrap();
126                    let (mut at, mut out) = (1, 0);
127                    loop {
128                        let p = d
129                            .push(&v[at..(at + chunk).min(end)], &mut vo[out..])
130                            .unwrap();
131                        at += p.consumed;
132                        out += p.written;
133                        if p.status == Status::Done {
134                            break;
135                        }
136                    }
137                    d.finish().unwrap();
138                    black_box(&vo);
139                },
140                size,
141            );
142            let mut output = vec![0u32; indices.len()];
143            let rate_t = measure(
144                &format!("v{version}:tri:{chunk}"),
145                || {
146                    let start = 1 + indices.len() / 3;
147                    let end = t.len() - 16;
148                    let mut d = IndexBufferDecoder::new(
149                        indices.len(),
150                        &t[..start],
151                        &t[end..],
152                        end - start,
153                        Limits::default(),
154                    )
155                    .unwrap();
156                    let (mut at, mut out) = (start, 0);
157                    loop {
158                        let p = d
159                            .push(&t[at..(at + chunk).min(end)], &mut output[out..])
160                            .unwrap();
161                        at += p.consumed;
162                        out += p.written;
163                        if p.status == Status::Done {
164                            break;
165                        }
166                    }
167                    d.finish().unwrap();
168                    black_box(&output);
169                },
170                to.len(),
171            );
172            println!(
173                "v{version} chunk={chunk} vertex={rate:.2} ({:.3}x) triangle={rate_t:.2} ({:.3}x)",
174                rate / vm,
175                rate_t / tm
176            );
177        }
178    }
179}
Source

pub const fn version(self) -> u8

Format version.

Trait Implementations§

Source§

impl Clone for IndexEncoding

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Copy for IndexEncoding

Source§

impl Debug for IndexEncoding

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for IndexEncoding

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl Eq for IndexEncoding

Source§

impl Hash for IndexEncoding

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl PartialEq for IndexEncoding

Source§

fn eq(&self, other: &Self) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl StructuralPartialEq for IndexEncoding

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.