ifc_lite_geometry/resource/
mesh.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5//! Audited mesh copy/merge admission. These helpers account requested backing
6//! storage, not allocator overhead or opaque numerical producer allocations.
7
8use super::{Cost, ProgramStop, Reservation};
9use crate::mesh::{Mesh, PlaneTag};
10
11/// Length-only input permits overflow qualification without huge allocations.
12#[derive(Clone, Copy, Debug, Default)]
13pub(crate) struct MeshLengths {
14    pub positions: usize,
15    pub normals: usize,
16    pub indices: usize,
17    pub planes: usize,
18}
19
20#[derive(Clone, Copy, Debug, PartialEq, Eq)]
21pub(crate) enum MeshAdmissionError {
22    Representation,
23    Allocation,
24}
25
26impl MeshLengths {
27    pub(crate) fn of(mesh: &Mesh) -> Self {
28        Self {
29            positions: mesh.positions.len(),
30            normals: mesh.normals.len(),
31            indices: mesh.indices.len(),
32            planes: mesh.plane_tags.as_ref().map_or(0, Vec::len),
33        }
34    }
35
36    pub(crate) fn bytes(self) -> Result<u64, MeshAdmissionError> {
37        self.bytes_with_limit(isize::MAX as usize)
38    }
39
40    fn bytes_with_limit(self, maximum_bytes: usize) -> Result<u64, MeshAdmissionError> {
41        u32::try_from(self.positions / 3).map_err(|_| MeshAdmissionError::Representation)?;
42        let mut bytes = 0u64;
43        for count in [self.positions, self.normals, self.indices] {
44            bytes = bytes
45                .checked_add(checked_buffer_with_limit(count, 4, maximum_bytes)?)
46                .ok_or(MeshAdmissionError::Representation)?;
47        }
48        bytes
49            .checked_add(checked_buffer_with_limit(
50                self.planes,
51                std::mem::size_of::<PlaneTag>(),
52                maximum_bytes,
53            )?)
54            .ok_or(MeshAdmissionError::Representation)
55    }
56}
57
58/// Backing retained when an existing mesh moves into a cache. Deep copies use
59/// logical lengths instead; spare Vec capacity is resident but is not copied.
60pub(crate) fn resident_bytes(mesh: &Mesh) -> Result<u64, MeshAdmissionError> {
61    MeshLengths::of(mesh).bytes()?;
62    [
63        (mesh.positions.capacity(), 4),
64        (mesh.normals.capacity(), 4),
65        (mesh.indices.capacity(), 4),
66        (
67            mesh.plane_tags.as_ref().map_or(0, Vec::capacity),
68            std::mem::size_of::<PlaneTag>(),
69        ),
70    ]
71    .into_iter()
72    .try_fold(0u64, |sum, (count, width)| {
73        sum.checked_add(checked_buffer(count, width)?)
74            .ok_or(MeshAdmissionError::Representation)
75    })
76}
77
78/// Every individual vector must fit the executing target's signed Vec extent.
79/// The pure limit parameter also qualifies wasm32 arithmetic on native hosts.
80fn checked_buffer(count: usize, width: usize) -> Result<u64, MeshAdmissionError> {
81    checked_buffer_with_limit(count, width, isize::MAX as usize)
82}
83
84fn checked_buffer_with_limit(
85    count: usize,
86    width: usize,
87    maximum_bytes: usize,
88) -> Result<u64, MeshAdmissionError> {
89    let bytes = count
90        .checked_mul(width)
91        .ok_or(MeshAdmissionError::Representation)?;
92    if bytes > maximum_bytes {
93        return Err(MeshAdmissionError::Representation);
94    }
95    u64::try_from(bytes).map_err(|_| MeshAdmissionError::Representation)
96}
97
98pub(crate) fn preflight_merge(
99    target: MeshLengths,
100    incoming: MeshLengths,
101    maximum_index: Option<u32>,
102) -> Result<MeshLengths, MeshAdmissionError> {
103    preflight_merge_with_limit(target, incoming, maximum_index, isize::MAX as usize)
104}
105
106fn preflight_merge_with_limit(
107    target: MeshLengths,
108    incoming: MeshLengths,
109    maximum_index: Option<u32>,
110    maximum_bytes: usize,
111) -> Result<MeshLengths, MeshAdmissionError> {
112    let positions = target
113        .positions
114        .checked_add(incoming.positions)
115        .ok_or(MeshAdmissionError::Representation)?;
116    let normals = target
117        .normals
118        .checked_add(incoming.normals)
119        .ok_or(MeshAdmissionError::Representation)?;
120    let indices = target
121        .indices
122        .checked_add(incoming.indices)
123        .ok_or(MeshAdmissionError::Representation)?;
124    let offset =
125        u32::try_from(target.positions / 3).map_err(|_| MeshAdmissionError::Representation)?;
126    if positions / 3 > u32::MAX as usize {
127        return Err(MeshAdmissionError::Representation);
128    }
129    if let Some(index) = maximum_index {
130        offset
131            .checked_add(index)
132            .ok_or(MeshAdmissionError::Representation)?;
133    }
134    for count in [positions, normals, indices] {
135        checked_buffer_with_limit(count, 4, maximum_bytes)?;
136    }
137    Ok(MeshLengths {
138        positions,
139        normals,
140        indices,
141        planes: target.planes,
142    })
143}
144
145#[cfg(test)]
146thread_local! { static RESERVE_EVENTS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; }
147
148fn reached_reservation() {
149    #[cfg(test)]
150    RESERVE_EVENTS.with(|events| events.set(events.get() + 1));
151}
152
153/// Prepare replacements together so a later allocation failure cannot leave
154/// grown, unowned backing capacity attached to the surviving destination.
155fn replacement<T: Copy>(
156    source: &Vec<T>,
157    additional: usize,
158) -> Result<Option<Vec<T>>, MeshAdmissionError> {
159    let length = source
160        .len()
161        .checked_add(additional)
162        .ok_or(MeshAdmissionError::Representation)?;
163    if source.capacity() >= length {
164        return Ok(None);
165    }
166    let mut result = Vec::new();
167    result
168        .try_reserve_exact(length)
169        .map_err(|_| MeshAdmissionError::Allocation)?;
170    result.extend_from_slice(source);
171    Ok(Some(result))
172}
173
174/// Reserve every destination before touching geometry, origin or RTC state.
175/// Failed preparation drops its temporary replacements and leaves target intact.
176/// The caller must admit cost and retain its permit BEFORE calling this helper.
177pub(crate) fn reserve_merge(target: &mut Mesh, incoming: &Mesh) -> Result<(), MeshAdmissionError> {
178    if incoming.is_empty() {
179        return Ok(());
180    }
181    preflight_merge(
182        MeshLengths::of(target),
183        MeshLengths::of(incoming),
184        incoming.indices.iter().copied().max(),
185    )?;
186    reached_reservation();
187    let positions = replacement(&target.positions, incoming.positions.len())?;
188    let normals = replacement(&target.normals, incoming.normals.len())?;
189    let indices = replacement(&target.indices, incoming.indices.len())?;
190    if let Some(buffer) = positions {
191        target.positions = buffer;
192    }
193    if let Some(buffer) = normals {
194        target.normals = buffer;
195    }
196    if let Some(buffer) = indices {
197        target.indices = buffer;
198    }
199    Ok(())
200}
201
202/// Clone via fallible reservations. Metadata has no deep-owned allocations;
203/// the optional plane vector does, and is included in both preflight and copy.
204pub(crate) fn clone_reserved(source: &Mesh) -> Result<Mesh, MeshAdmissionError> {
205    let lengths = MeshLengths::of(source);
206    lengths.bytes()?;
207    let mut target = Mesh::new();
208    reached_reservation();
209    target
210        .positions
211        .try_reserve_exact(lengths.positions)
212        .map_err(|_| MeshAdmissionError::Allocation)?;
213    target
214        .normals
215        .try_reserve_exact(lengths.normals)
216        .map_err(|_| MeshAdmissionError::Allocation)?;
217    target
218        .indices
219        .try_reserve_exact(lengths.indices)
220        .map_err(|_| MeshAdmissionError::Allocation)?;
221    let mut planes = Vec::new();
222    planes
223        .try_reserve_exact(lengths.planes)
224        .map_err(|_| MeshAdmissionError::Allocation)?;
225    target.positions.extend_from_slice(&source.positions);
226    target.normals.extend_from_slice(&source.normals);
227    target.indices.extend_from_slice(&source.indices);
228    if let Some(tags) = &source.plane_tags {
229        planes.extend_from_slice(tags);
230        target.plane_tags = Some(planes);
231    }
232    target.rtc_applied = source.rtc_applied;
233    target.origin = source.origin;
234    target.instance_meta = source.instance_meta.clone();
235    target.local_bounds = source.local_bounds;
236    target.local_to_world = source.local_to_world;
237    target.welded_in_object_frame = source.welded_in_object_frame;
238    Ok(target)
239}
240
241fn terminal(error: MeshAdmissionError) -> ProgramStop {
242    match error {
243        MeshAdmissionError::Representation => super::overflow(),
244        MeshAdmissionError::Allocation => super::allocation_failure(),
245    }
246}
247
248/// The returned unique reservation must move with the clone's actual owner.
249/// Shared raster payloads are not copied here; this helper operates on Mesh.
250pub(crate) fn clone_mesh(source: &Mesh) -> Result<(Mesh, Reservation), ProgramStop> {
251    let bytes = MeshLengths::of(source).bytes().map_err(terminal)?;
252    let permit = super::charge(Cost {
253        work: bytes / 4,
254        copy_bytes: bytes,
255        output_bytes: bytes,
256        live_bytes: bytes,
257        ..Cost::default()
258    })?;
259    let mesh = clone_reserved(source).map_err(terminal)?;
260    Ok((mesh, permit))
261}
262
263/// Admission precedes reserve/copy, preserving the existing origin/RTC merge
264/// algorithm and ordered triangle stream. No output mutation on refusal.
265/// The permit covers each replacement backing while the old owner is alive.
266pub(crate) fn merge_mesh(target: &mut Mesh, incoming: &Mesh) -> Result<Reservation, ProgramStop> {
267    if incoming.is_empty() {
268        return super::charge(Cost::default());
269    }
270    // Canonical merge does not copy the incoming optional plane metadata.
271    let incoming_lengths = MeshLengths {
272        planes: 0,
273        ..MeshLengths::of(incoming)
274    };
275    let result =
276        preflight_merge(MeshLengths::of(target), incoming_lengths, None).map_err(terminal)?;
277    let bytes = incoming_lengths.bytes().map_err(terminal)?;
278    let (live_bytes, moved_bytes) = [
279        (
280            target.positions.capacity(),
281            target.positions.len(),
282            result.positions,
283        ),
284        (
285            target.normals.capacity(),
286            target.normals.len(),
287            result.normals,
288        ),
289        (
290            target.indices.capacity(),
291            target.indices.len(),
292            result.indices,
293        ),
294    ]
295    .into_iter()
296    .try_fold((0u64, 0u64), |(live, moved), (capacity, old, length)| {
297        if capacity >= length {
298            return Ok((live, moved));
299        }
300        Ok((
301            live.checked_add(checked_buffer(length, 4)?)
302                .ok_or(MeshAdmissionError::Representation)?,
303            moved
304                .checked_add(checked_buffer(old, 4)?)
305                .ok_or(MeshAdmissionError::Representation)?,
306        ))
307    })
308    .map_err(terminal)?;
309    let copy_bytes = bytes.checked_add(moved_bytes).ok_or_else(super::overflow)?;
310    // reserve_merge's index preflight visits every incoming index before the
311    // canonical copy loop. Charge that repeated scan before doing the walk.
312    let work = (copy_bytes / 4)
313        .checked_add(incoming.indices.len() as u64)
314        .ok_or_else(super::overflow)?;
315    let permit = super::charge(Cost {
316        work,
317        copy_bytes,
318        output_bytes: bytes,
319        live_bytes,
320        ..Cost::default()
321    })?;
322    reserve_merge(target, incoming).map_err(terminal)?;
323    target.merge(incoming);
324    Ok(permit)
325}
326
327#[cfg(test)]
328#[path = "mesh_tests.rs"]
329mod tests;