craft-mesh-ops: the crate is the TextureCraft geometry code moved as it is

Replace the crate's sources with TextureCraft crates/geom at 386630e and
MaterialCraft Mesh::subdivided at 3133062, with their tests, so this pull
request is the move alone. The crate keeps the sources' dependencies and
behavior; rustfmt is applied at this repository's 150 columns. Fixes to the
moved code go in separate pull requests.
This commit is contained in:
dotCooCoo committed 2026-11-25 23:11:13 -08:00
1 parent b5cfc7cf1a
commit 795d798def
11 files changed
+555 -4516

No files matched your search

-3
View File
@@ -242,9 +242,6 @@ The mesh operations in crates/mesh-ops are moved from:
3133062968b8a1566eda12a357cb06062db16687.
https://github.com/storytold/materialcraft
Copyright (c) 2026 ArtCraft Team and the MaterialCraft contributors.
The index check before tangent generation and its two tests are from TextureCraft pull
request #386 by simonhull, revision faa4548a6f34bb61d43f56b3500edb73dd71981b
(https://github.com/storytold/texturecraft/pull/386).
All licensed MIT OR Apache-2.0.
The image-based lighting in crates/pbr (craft-pbr) is adapted from:
+1 -2
View File
@@ -320,8 +320,7 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit
themselves and never panic. Carved from EffectCraft, SolidCraft, TextureCraft and MaterialCraft.
- [`craft-mesh-ops`](crates/mesh-ops/README.md): operations on triangle meshes: smooth normals,
MikkTSpace tangents, welding, UV unwrapping, a UV-space G-buffer, primitives with UVs and a
BVH for ray casts (feature `bvh`), with slice functions checked against `Limits`. From
TextureCraft and MaterialCraft.
BVH for ray casts, and an orbit camera. From TextureCraft and MaterialCraft.
- [`craft-midi`](crates/midi/README.md): Standard MIDI Files: a bounded reader for formats 0, 1 and
2 and a format-1 writer, over a neutral model of notes and channel events in ticks at 960 per
quarter note. From SoundCraft.
+4 -10
View File
@@ -1,6 +1,6 @@
[package]
name = "craft-mesh-ops"
description = "Triangle mesh operations: smooth normals, MikkTSpace tangents, welding, UV unwrapping, a UV-space G-buffer, primitives with UVs and a BVH, bounded on hostile input"
description = "Triangle mesh operations: smooth normals, MikkTSpace tangents, welding, UV unwrapping, a UV-space G-buffer, primitives with UVs, a BVH and an orbit camera"
version.workspace = true
edition.workspace = true
license.workspace = true
@@ -10,17 +10,11 @@ repository.workspace = true
[lints]
workspace = true
[features]
default = []
bvh = []
parallel = ["dep:rayon"]
serde = ["dep:serde", "glam/serde"]
[dependencies]
glam = "0.30"
glam = { version = "0.30", features = ["serde"] }
# MIT OR Apache-2.0; its src/generated.rs also carries the zlib-style notice of the C original,
# reproduced in ATTRIBUTION.md.
mikktspace = { version = "0.3", default-features = false, features = ["glam"] }
rayon = { workspace = true, optional = true }
serde = { workspace = true, optional = true }
rayon = { workspace = true }
serde = { workspace = true }
thiserror = { workspace = true }
+15 -130
View File
@@ -4,104 +4,26 @@ Operations on triangle meshes, for apps that paint, bake or preview materials on
crate has no UI, does no file or network I/O and has no `unsafe` code. File formats stay in
[`craft-mesh`](../mesh/README.md).
- **Slice functions.** `bounds`, `smooth_normals`, `tangents`, `weld` and `unwrap_uvs` at the crate
root, `UvGBuffer::from_slices` and `Bvh::from_slices` take plain slices: positions and normals
as `[f32; 3]`, UVs as `[f32; 2]`, triangle indices as `u32`. They check the counts against
`Limits`, every index and every value (finite) before any work, and return a `MeshOpsError`.
Values are `f32`; a caller that holds `f64` converts first and rejects values outside the `f32`
range.
- **`Mesh`.** Positions, normals, tangents, UVs, vertex colors, indices, per-material submeshes
and polygon-diagonal flags, with `validate`, `append`, `subdivided`, `normalize_to`, wireframe
and UV-seam edges, and UV-tile helpers.
- **Normals and tangents.** Smooth normals are area weighted. Tangents come from MikkTSpace, which
glTF 2.0 recommends for meshes without tangents
(<https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html>): `w` holds the bitangent sign, and
UVs have `(0, 0)` at the upper-left corner with `v` increasing downward. A mesh MikkTSpace
cannot handle (every triangle degenerate, no UV area, more than
`mesh::MAX_MIKKTSPACE_VALENCE` (2,048) triangles around one vertex, or so many corners at one
position that welding them would take more than `mesh::MAX_MIKKTSPACE_WELD_WORK` (2^27)
comparisons) gets per-vertex tangents, with `w` set as MikkTSpace sets it.
MikkTSpace gives each triangle corner its own frame: `Mesh::compute_tangents` splits a vertex
whose corners get different frames (UVs mirrored across it), and `tangents` returns an
`Invalid` error for such a vertex, since it returns one tangent per input vertex. When the
largest coordinate is above 1e6 or below 1e-6 in magnitude, normals and tangents are computed
from the positions divided by it, and finite input gives finite output. UVs passed to
`tangents` are divided the same way, and normals when their largest component is above 2 or
below 0.5. Normals are unit vectors, as glTF 2.0 stores them.
- **UV unwrapping.** `unwrap_uvs` and `unwrap::auto_unwrap` make a non-overlapping layout per
material, splitting vertices where charts meet. A face joins a chart only when its projection
onto the chart's plane does not overlap the chart's other faces, and every chart is packed at
a scale above zero. The charts are projected, measured and packed in `f64` from the positions
as given, so a small chart far from the origin keeps its shape. A mesh whose submeshes put one
triangle in two materials is an `Invalid` error. `weld`
gives vertices at the same position (on a grid of 1e-6 of the bounding diagonal) the same id,
numbered in order of first appearance.
(<https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html>): `w` holds the bitangent sign.
- **UV unwrapping.** `unwrap::auto_unwrap` makes a non-overlapping layout per material, splitting
vertices where charts meet.
- **UV G-buffer.** `UvGBuffer` records, for each texel of one material's UV space, the triangle
and barycentrics under the texel center; `surface_at` turns them into a position, normal and
tangent frame. A triangle with a corner more than 1e18 texels from the UV origin is skipped.
A texel center counts as inside a triangle when it is no more than 1e-6 texel outside each
edge, plus the `f64` rounding of the edge function at the triangle's coordinates, and at most
1e-3 of the triangle's smallest height.
- **Primitives.** `sphere`, `rounded_box`, `cube`, `cylinder`, `torus` and `plane`, and the
built-in scenes in `primitives::BUILTINS`, all with UVs and tangents. The `try_` forms return an
error for a non-finite or non-positive size, a size so large that a coordinate overflows `f32`,
or a segment count over `Limits::max_segments`; the other forms clamp the segment count and
return an empty mesh for an invalid size.
- **BVH** (feature `bvh`). Binned SAH on all three axes, with a median split on the widest
centroid axis when no split beats a leaf. Closest-hit, any-hit and filtered ray casts, the
nearest point within a distance, and box queries. Triangles with a non-finite corner are left
out of the tree. A ray with a non-finite origin or direction, a zero direction or a NaN
distance, a NaN box and a negative or NaN search distance find nothing. Ray casts find hits on
triangles with coordinates between about 1e-12 and 1e12; outside that range the products in
the triangle test overflow or underflow `f32`. The nearest-point
search does not find a point more than about 1.8e19 away, where the squared distance overflows
`f32`.
- **`Mesh`.** Positions, normals, tangents, UVs, vertex colors, indices, per-material submeshes
and polygon-diagonal flags, with `validate`, `append` and `try_append`, `subdivided` and
`try_subdivided`, wireframe and UV-seam edges, and UV-tile helpers. `OrbitCamera` and `Ray`
give an orbit view and picking rays; `OrbitCamera::frame` ignores a box whose center or framing
distance is not finite, and `OrbitCamera::zoom` ignores a distance at which the eye rounds to
the target. `OrbitCamera::ray` unprojects in `f64`.
tangent frame.
- **Primitives.** Sphere, rounded box, cube, cylinder, torus and plane with UVs and tangents, and
the built-in scenes in `primitives::BUILTINS`.
- **BVH.** `Bvh` is a binned SAH tree on all three axes with a median split when no split beats a
leaf. It answers closest-hit, any-hit and filtered ray casts, nearest-point queries and box
queries.
- **Camera.** `OrbitCamera` and `Ray` give an orbit view and picking rays.
Triangulation with holes, extrusion of 2D outlines and conversion from `craft_mesh::Mesh` are not
in the crate yet.
## Cargo features
No default features.
| Feature | Provides | Pulls in |
|---|---|---|
| `bvh` | `Bvh`, `Hit` | nothing |
| `parallel` | the UV G-buffer rasterizes bands of rows on several threads; the result is the same | `rayon` |
| `serde` | `Serialize` and `Deserialize` for `OrbitCamera` | `serde`, `glam/serde` |
Without `parallel` the crate builds for `wasm32-unknown-unknown`.
## Limits
| Field | Default | Checked by |
|---|---|---|
| `max_vertices` | 20,000,000 | every slice function, `try_subdivided`, the `try_` primitives (also after their tangents split vertices), `UvGBuffer::try_new`, `unwrap::auto_unwrap` (input and output), `Mesh::map_material_uvs` (the mesh's vertices and the copies of the vertices it shares with other materials) |
| `max_triangles` | 20,000,000 | the same except `auto_unwrap`, and `Bvh::from_slices`; the UV G-buffer also counts a triangle again each time another submesh of the material lists it; `Mesh::wire_edges`, `Mesh::uv_seam_edges`, `Mesh::uv_tiles` and `Mesh::map_material_uvs` count the triangles the submeshes list in the same way |
| `max_segments` | 2,048 | the `try_` primitives (segments, rings or subdivisions along one direction, after a count under the primitive's minimum is raised to it; a box face has 12, or 22 with a bevel) |
| `max_gbuffer_side` | 8,192 | `UvGBuffer::try_new`, `UvGBuffer::from_slices`; `UvGBuffer::new` clamps each side to `1..=8192` |
| `max_gbuffer_texels` | 2^26 (8,192 × 8,192) | the same |
| `max_gbuffer_work` | 2^32 | the same: the texels the rasterizer visits, summed over each triangle's bounding box clipped to the buffer |
| `max_gbuffer_bin_entries` | 2^26 | the same: one entry per triangle for each band of 32 rows its clipped box reaches |
| `max_unwrap_triangles` | 4,000,000 | `unwrap_uvs` and `unwrap::auto_unwrap`, for the mesh's triangles and for the triangles its submeshes list |
A BVH holds at most `bvh::MAX_BVH_TRIANGLES` (2^31 − 1) triangles.
`Bvh::from_slices`, `Bvh::try_new`, `UvGBuffer::try_new` and `UvGBuffer::from_slices` reserve all
their memory before using it. The other slice functions, `weld`, `Mesh::try_compute_normals`,
`Mesh::try_compute_tangents`, `Mesh::try_subdivided`, the `try_` primitives, `unwrap::weld_ids`
and the unwrap functions reserve their working memory and their results as they grow. Each
returns `MeshOpsError::OutOfMemory` when a reservation fails. `Bvh::new` then returns an empty
tree, `UvGBuffer::new` a 1 × 1 uncovered buffer, and `compute_normals` and `compute_tangents`
leave the mesh unchanged. `UvGBuffer::new` also returns that buffer when the input is over a
default limit. The UV G-buffer checks its work and band entries in a first pass over the
triangles, before it reserves its band lists (in one piece) or its texel buffers, so a request
over those limits returns `MeshOpsError::TooLarge`. The working memory of the `mikktspace` crate
is allocated inside it and is not reserved this way; it is a fixed multiple of the input the
limits allow.
`GeomError::Invalid` is the one error type. `rayon` parallelizes the UV G-buffer, and `serde`
serializes `OrbitCamera`; both are always on.
## Origin
@@ -109,8 +31,6 @@ limits allow.
|---|---|
| `mesh.rs`, `bvh.rs`, `primitives.rs`, `gbuffer.rs`, `unwrap.rs`, `camera.rs` and their tests | TextureCraft `crates/geom` at [386630e](https://github.com/storytold/texturecraft/commit/386630ee85cb22679295b24013575d1aecb39ad2) |
| `Mesh::subdivided` and `subdivision_shares_edge_midpoints` | MaterialCraft `crates/geom/src/mesh.rs` at [3133062](https://github.com/storytold/materialcraft/commit/3133062968b8a1566eda12a357cb06062db16687) |
| The index check in `Mesh::from_parts` and `compute_tangents`, and its two tests | TextureCraft [#386](https://github.com/storytold/texturecraft/pull/386) by simonhull, at `faa4548a` |
| `Limits`, `MeshOpsError::TooLarge` and `OutOfMemory`, the slice functions, the `try_` forms, the finite-value and overflow checks, the `bvh`, `parallel` and `serde` features | written here |
MikkTSpace comes from the `mikktspace` crate; its notice is in [ATTRIBUTION.md](ATTRIBUTION.md).
@@ -120,38 +40,3 @@ MikkTSpace comes from the `mikktspace` crate; its notice is in [ATTRIBUTION.md](
|---|---|
| TextureCraft | `texturecraft-geom` is the source. The app switches to this crate in its own pull request. |
| MaterialCraft | `materialcraft-geom` is the source of `subdivided`. The app switches in its own pull request. |
For both apps:
| `*-geom` | craft-mesh-ops |
| --- | --- |
| `GeomError::Invalid` | `MeshOpsError::Invalid`, plus `TooLarge` and `OutOfMemory` |
| `BaseColor` | not moved; it stays in the app |
| `Bvh`, `Hit` always built | the `bvh` feature |
| `rayon` and `serde` always on | the `parallel` and `serde` features |
| `Mesh::bounds` with a NaN position | NaN positions are left out of the box |
| `Mesh::append` with a mismatched attribute | the missing normals, UVs or tangents are filled in; `try_append` returns an error on overflow or a bad index |
| `Mesh::append` with submeshes and no material list on either side | that side gets one unnamed material |
| `Mesh::validate` | also rejects a submesh that does not start and end on a triangle, and a non-finite normal, UV, tangent or color |
| `Mesh::subdivided` with an invalid mesh | returns a copy; `try_subdivided` returns the error |
| `primitives::*` with a NaN or negative size | an empty mesh; the `try_` forms return the error |
| `auto_unwrap` with a non-finite position, normal or color, a bad submesh or colors for some vertices only | an error, with the mesh unchanged |
| `Bvh::nearest` skips a point exactly `max_dist` away | the point is found |
| Rays miss a triangle whose two edge lengths multiply to under 1e-12 | the cutoff follows the triangle's size, so the ray hits |
| `Mesh::normalize_to` with a radius that overflows a coordinate | the mesh is unchanged |
| `Mesh::normalize_to` leaves a mesh with a radius under 1e-4 too small | the mesh gets the requested radius |
| `weld_ids` on a grid of 1e-12 when the bounding diagonal is under 1e-6 | a grid of 1e-6 of the diagonal at every size |
| `OrbitCamera::frame` with a box whose center or distance is not finite | the camera is unchanged |
| `OrbitCamera::project` in orthographic mode returns points behind the camera | it returns `None` for them |
| The orthographic projection and `pan` use the field of view as it is | they clamp it to 5° to 150°, as the perspective projection does |
| `Mesh::compute_tangents` keeps the last corner's frame at a shared vertex | the vertex is split where its corners' frames differ |
| The per-vertex tangent fallback always sets `w` to +1 | `w` is -1 where the UVs are mirrored, as MikkTSpace sets it |
| `auto_unwrap` packs a triangle that submeshes of two materials list with only the last one | an `Invalid` error, with the mesh unchanged |
| `OrbitCamera::zoom` close to a target far from the origin gives a view that is not finite | the camera is unchanged |
| `Bvh::nearest` misses points inside very thin triangles and near a triangle with a zero-length edge | the nearest point is found |
| `Bvh::nodes` with no triangles lists one node | it lists none |
| `surface_at` and the rounded box replace a vector whose squared length overflows `f32` with a fallback direction | they keep its direction |
| The cylinder's side UVs shrink for a profile shorter than 1e-6, and a profile longer than `f32::MAX` is an error | the side UVs are the same at every size |
| `auto_unwrap` joins faces whose projections overlap into one chart | such a face starts another chart |
| `auto_unwrap` accepts a layout that fits only at scale zero | the packing square grows until the charts fit at a positive scale |
| `weld_ids` returns the ids | it returns `Result`, with `OutOfMemory` when the ids or the grid cannot be reserved |
+28 -332
View File
@@ -1,18 +1,9 @@
//! Bounding volume hierarchy over a mesh's triangles: closest-hit and any-hit ray casts, and
//! box queries (used by picking, baking and brush stamps).
//!
//! The tree is built by binned SAH on all three axes, falling back to a median split on the
//! widest centroid axis when no SAH split beats a leaf. Triangles with a non-finite corner are
//! left out, and a query with a non-finite origin, direction or point, a zero direction, a NaN
//! distance or a NaN box finds nothing.
//!
//! Ray casts find hits on triangles with coordinates between about 1e-12 and 1e12. Outside that
//! range the products in the triangle test overflow or underflow `f32`, and a ray can miss a
//! triangle it crosses.
use glam::{DVec3, Vec3, Vec3A};
use glam::{Vec3, Vec3A};
use crate::{Limits, Mesh, MeshOpsError, Result, check_limit, try_vec};
use crate::Mesh;
#[derive(Clone, Copy, Debug)]
struct Node {
@@ -44,9 +35,6 @@ pub struct Bvh {
const LEAF: usize = 4;
/// Most triangles one tree holds: its node indices (up to twice the triangle count) are `u32`.
pub const MAX_BVH_TRIANGLES: usize = (u32::MAX / 2) as usize;
/// Traversal stack of (node, entry distance): inline for typical depths (no allocation per
/// ray), spilling to the heap for degenerate trees.
struct Stack {
@@ -91,79 +79,22 @@ fn area(lo: Vec3, hi: Vec3) -> f32 {
d.x * d.y + d.y * d.z + d.z * d.x
}
/// The centroid of a triangle; thirds first when the sum would overflow.
fn centroid(t: &[Vec3; 3]) -> Vec3 {
let c = (t[0] + t[1] + t[2]) / 3.0;
if c.is_finite() { c } else { t[0] / 3.0 + t[1] / 3.0 + t[2] / 3.0 }
}
impl Bvh {
/// The tree over a mesh's triangles. Triangles with a non-finite corner or an index out of
/// range are left out, as is every triangle past [`MAX_BVH_TRIANGLES`]. When the memory for
/// the tree cannot be reserved, the tree is empty.
pub fn new(mesh: &Mesh) -> Bvh {
Bvh::try_new(mesh).unwrap_or(Bvh { nodes: Vec::new(), tris: Vec::new(), order: Vec::new() })
}
/// [`Bvh::new`], or `OutOfMemory` when the memory for the tree cannot be reserved.
pub fn try_new(mesh: &Mesh) -> Result<Bvh> {
let triangle_count = mesh.triangle_count().min(MAX_BVH_TRIANGLES);
let mut tris = try_vec(triangle_count, "BVH triangles")?;
let mut ids = try_vec(triangle_count, "BVH triangles")?;
let triangle_count = mesh.triangle_count();
let mut tris = Vec::with_capacity(triangle_count);
for triangle in 0..triangle_count {
let Some([a, b, c]) = mesh.tri(triangle) else { continue };
let (Some(a), Some(b), Some(c)) = (mesh.positions.get(a), mesh.positions.get(b), mesh.positions.get(c)) else { continue };
if a.is_finite() && b.is_finite() && c.is_finite() {
tris.push([*a, *b, *c]);
ids.push(triangle as u32);
}
let position = |i: usize| mesh.positions.get(i).copied().unwrap_or(Vec3::ZERO);
tris.push([position(a), position(b), position(c)]);
}
Bvh::build(tris, ids)
}
/// The tree over the triangles of `indices`, after checking the counts against `limits`
/// and [`MAX_BVH_TRIANGLES`], every index and every position (finite).
pub fn from_slices(positions: &[[f32; 3]], indices: &[u32], limits: &Limits) -> Result<Bvh> {
check_limit("vertex count", positions.len(), limits.max_vertices)?;
if !indices.len().is_multiple_of(3) {
return Err(MeshOpsError::Invalid("index count is not a multiple of 3".into()));
}
let triangles = indices.len() / 3;
check_limit("triangle count", triangles, limits.max_triangles.min(MAX_BVH_TRIANGLES))?;
if let Some(bad) = indices.iter().find(|&&i| i as usize >= positions.len()) {
return Err(MeshOpsError::Invalid(format!("index {bad} out of range ({} vertices)", positions.len())));
}
if !positions.iter().flatten().all(|v| v.is_finite()) {
return Err(MeshOpsError::Invalid("non-finite position".into()));
}
let mut tris = try_vec(triangles, "BVH triangles")?;
let mut ids = try_vec(triangles, "BVH triangles")?;
for (t, &[a, b, c]) in indices.as_chunks::<3>().0.iter().enumerate() {
let p = |i: u32| positions.get(i as usize).map_or(Vec3::ZERO, |p| Vec3::from_array(*p));
tris.push([p(a), p(b), p(c)]);
ids.push(t as u32);
}
Bvh::build(tris, ids)
}
let mut order: Vec<u32> = (0..tris.len() as u32).collect();
let centroids: Vec<Vec3> = tris.iter().map(|t| (t[0] + t[1] + t[2]) / 3.0).collect();
/// Build over `tris`, whose original triangle indices are `ids`; at most
/// [`MAX_BVH_TRIANGLES`] finite triangles. Every list reserves its memory before it grows.
/// Without triangles the tree has no nodes.
fn build(tris: Vec<[Vec3; 3]>, ids: Vec<u32>) -> Result<Bvh> {
if tris.is_empty() {
return Ok(Bvh { nodes: Vec::new(), tris, order: Vec::new() });
}
let out_of_memory = |_| MeshOpsError::OutOfMemory("BVH nodes");
let mut order: Vec<u32> = try_vec(tris.len(), "BVH triangles")?;
order.extend(0..tris.len() as u32);
let mut centroids: Vec<Vec3> = try_vec(tris.len(), "BVH triangles")?;
centroids.extend(tris.iter().map(centroid));
let mut nodes = try_vec(1, "BVH nodes")?;
nodes.push(Node { lo: Vec3A::ZERO, hi: Vec3A::ZERO, first: 0, count: tris.len() as u32 });
let mut stack = try_vec(1, "BVH nodes")?;
stack.push(0usize);
let mut nodes = vec![Node { lo: Vec3A::ZERO, hi: Vec3A::ZERO, first: 0, count: tris.len() as u32 }];
let mut stack = vec![0usize];
while let Some(node_index) = stack.pop() {
let Node { first, count, .. } = nodes[node_index];
@@ -280,8 +211,6 @@ impl Bvh {
continue;
}
nodes.try_reserve(2).map_err(out_of_memory)?;
stack.try_reserve(2).map_err(out_of_memory)?;
let left_child = nodes.len();
nodes.push(Node { lo: Vec3A::ZERO, hi: Vec3A::ZERO, first, count: left_count as u32 });
nodes.push(Node { lo: Vec3A::ZERO, hi: Vec3A::ZERO, first: first + left_count as u32, count: (count - left_count) as u32 });
@@ -293,13 +222,8 @@ impl Bvh {
stack.push(left_child + 1);
}
let mut sorted = try_vec(order.len(), "BVH triangles")?;
sorted.extend(order.iter().map(|t| tris[*t as usize]));
// The triangle indices replace the positions in `order` one by one.
for t in &mut order {
*t = ids[*t as usize];
}
Ok(Bvh { nodes, tris: sorted, order })
let tris = order.iter().map(|t| tris[*t as usize]).collect();
Bvh { nodes, tris, order }
}
pub fn is_empty(&self) -> bool {
@@ -308,7 +232,7 @@ impl Bvh {
/// The flattened tree (for GPU traversal), root first: bounds, then for a leaf the range
/// `first..first + count` of [`Bvh::triangles`], for an inner node (`count` 0) the children
/// `first` and `first + 1`. A tree without triangles has no nodes.
/// `first` and `first + 1`.
pub fn nodes(&self) -> impl ExactSizeIterator<Item = (Vec3, Vec3, u32, u32)> + '_ {
self.nodes.iter().map(|n| (n.lo.into(), n.hi.into(), n.first, n.count))
}
@@ -326,9 +250,7 @@ impl Bvh {
let open = t0.is_nan_mask() | t1.is_nan_mask();
let tn = Vec3A::select(open, Vec3A::NEG_INFINITY, t0.min(t1)).max_element().max(0.0);
let tf = Vec3A::select(open, Vec3A::INFINITY, t0.max(t1)).min_element().min(tmax);
// A box whose entry distance is +∞ (where 1/d overflows) is not reached, even when `tmax`
// is unbounded; no triangle can be hit at that distance.
(tn <= tf && tn.is_finite()).then_some(tn)
(tn <= tf).then_some(tn)
}
/// Möller–Trumbore, double sided.
@@ -337,10 +259,7 @@ impl Bvh {
let e2 = t[2] - t[0];
let p = d.cross(e2);
let det = e1.dot(p);
// A ray in the triangle's plane, or a triangle without area. The determinant is the
// product of the two edge lengths, the direction's length and the sines of the angles
// between them, so the cutoff shrinks with that product for small triangles.
if det.abs() < 1e-12 && (det == 0.0 || det.abs() < 1e-12 * (e1.length() * e2.length() * d.length()).min(1.0)) {
if det.abs() < 1e-12 {
return None;
}
let inv = 1.0 / det;
@@ -362,9 +281,6 @@ impl Bvh {
}
fn traverse(&self, o: Vec3, d: Vec3, mut tmax: f32, any: bool, filter: &dyn Fn(u32) -> bool) -> Option<Hit> {
if !o.is_finite() || !d.is_finite() || d == Vec3::ZERO || tmax.is_nan() {
return None;
}
let root = self.nodes.first().filter(|_| !self.tris.is_empty())?;
let (oa, inv) = (Vec3A::from(o), Vec3A::ONE / Vec3A::from(d));
let mut best = None;
@@ -426,14 +342,9 @@ impl Bvh {
self.traverse(o, d, tmax, true, &|_| true).is_some()
}
/// The point nearest to `p` at most `max_dist` (zero or more) away on a triangle accepted by
/// `filter` (original index): a [`Hit`] with the distance in `t` and the barycentrics of
/// vertices 1 and 2. A point whose squared distance overflows `f32` (a distance above about
/// 1.8e19) is not found.
/// The point nearest to `p` within `max_dist` on a triangle accepted by `filter` (original
/// index): a [`Hit`] with the distance in `t` and the barycentrics of vertices 1 and 2.
pub fn nearest(&self, p: Vec3, max_dist: f32, filter: &dyn Fn(u32) -> bool) -> Option<Hit> {
if max_dist.is_nan() || max_dist < 0.0 {
return None;
}
let root = self.nodes.first().filter(|_| !self.tris.is_empty() && p.is_finite())?;
let pa = Vec3A::from(p);
let box_d2 = |n: &Node| (n.lo - pa).max(pa - n.hi).max(Vec3A::ZERO).length_squared();
@@ -450,9 +361,7 @@ impl Bvh {
}
let (q, u, v) = closest_on_triangle(p, tri);
let dd = (q - p).length_squared();
// The first point found may lie exactly at `max_dist`. A squared distance that
// overflows is not comparable with a squared `max_dist` that overflows too.
if dd.is_finite() && (dd < best_d2 || (best.is_none() && dd <= best_d2)) {
if dd < best_d2 {
best_d2 = dd;
best = Some(Hit { t: dd.sqrt(), tri: orig, u, v });
}
@@ -469,12 +378,8 @@ impl Bvh {
best
}
/// Call `f` with every triangle (original index) whose bounds overlap the box. A box with a
/// NaN coordinate, or a lower corner past the upper corner on any axis, overlaps nothing.
/// Call `f` with every triangle (original index) whose bounds overlap the box.
pub fn query_box(&self, lo: Vec3, hi: Vec3, mut f: impl FnMut(u32)) {
if lo.is_nan() || hi.is_nan() || lo.cmpgt(hi).any() {
return;
}
let mut stack = vec![0u32];
while let Some(i) = stack.pop() {
let Some(n) = self.nodes.get(i as usize) else { continue };
@@ -499,16 +404,10 @@ impl Bvh {
}
/// The point of triangle `t` nearest to `p` and its barycentrics (weights of vertices 1 and 2),
/// by Voronoi region (Ericson, Real-Time Collision Detection, 5.1.5), in `f64`: in `f32` the
/// region tests round to zero inside thin triangles. A triangle without area is measured as the
/// point or segment it is, and can be the nearest. An edge of zero length is skipped: the
/// denominator of its parameter is its squared length.
/// by Voronoi region (Ericson, Real-Time Collision Detection, 5.1.5). Degenerate triangles give
/// a non-finite distance and are never nearest.
fn closest_on_triangle(p: Vec3, t: &[Vec3; 3]) -> (Vec3, f32, f32) {
let (q, v, w) = closest_on_triangle_f64(p.as_dvec3(), t.map(|c| c.as_dvec3()));
(q.as_vec3(), v as f32, w as f32)
}
fn closest_on_triangle_f64(p: DVec3, [a, b, c]: [DVec3; 3]) -> (DVec3, f64, f64) {
let [a, b, c] = *t;
let (ab, ac, ap) = (b - a, c - a, p - a);
let (d1, d2) = (ab.dot(ap), ac.dot(ap));
if d1 <= 0.0 && d2 <= 0.0 {
@@ -519,9 +418,8 @@ fn closest_on_triangle_f64(p: DVec3, [a, b, c]: [DVec3; 3]) -> (DVec3, f64, f64)
if d3 >= 0.0 && d4 <= d3 {
return (b, 1.0, 0.0);
}
// d1 - d3 = |ab|², d2 - d6 = |ac|² and (d4 - d3) + (d5 - d6) = |bc|².
let vc = d1 * d4 - d3 * d2;
if vc <= 0.0 && d1 >= 0.0 && d3 <= 0.0 && d1 - d3 > 0.0 {
if vc <= 0.0 && d1 >= 0.0 && d3 <= 0.0 {
let v = d1 / (d1 - d3);
return (a + ab * v, v, 0.0);
}
@@ -531,36 +429,18 @@ fn closest_on_triangle_f64(p: DVec3, [a, b, c]: [DVec3; 3]) -> (DVec3, f64, f64)
return (c, 0.0, 1.0);
}
let vb = d5 * d2 - d1 * d6;
if vb <= 0.0 && d2 >= 0.0 && d6 <= 0.0 && d2 - d6 > 0.0 {
if vb <= 0.0 && d2 >= 0.0 && d6 <= 0.0 {
let w = d2 / (d2 - d6);
return (a + ac * w, 0.0, w);
}
let va = d3 * d6 - d5 * d4;
if va <= 0.0 && d4 - d3 >= 0.0 && d5 - d6 >= 0.0 && (d4 - d3) + (d5 - d6) > 0.0 {
if va <= 0.0 && d4 - d3 >= 0.0 && d5 - d6 >= 0.0 {
let w = (d4 - d3) / ((d4 - d3) + (d5 - d6));
return (b + (c - b) * w, 1.0 - w, w);
}
let sum = va + vb + vc;
if sum > 0.0 {
let (v, w) = (vb / sum, vc / sum);
// Project p onto the plane instead of rebuilding a + ab v + ac w, whose rounding moves a
// point that lies on the plane off it. A point whose height above the plane is 0 stays p.
let n = ab.cross(ac);
let nn = n.length_squared();
let q = if nn > 0.0 { p - n * (n.dot(ap) / nn) } else { a + ab * v + ac * w };
return (q, v, w);
}
// No area and no region matched: the nearest of the three edges.
let on_edge = |from: DVec3, to: DVec3| {
let d = to - from;
let s = if d.length_squared() > 0.0 { ((p - from).dot(d) / d.length_squared()).clamp(0.0, 1.0) } else { 0.0 };
(from + d * s, s)
};
let ((qab, s), (qac, r), (qbc, k)) = (on_edge(a, b), on_edge(a, c), on_edge(b, c));
[(qab, s, 0.0), (qac, 0.0, r), (qbc, 1.0 - k, k)]
.into_iter()
.min_by(|x, y| (x.0 - p).length_squared().total_cmp(&(y.0 - p).length_squared()))
.unwrap_or((a, 0.0, 0.0))
let denom = 1.0 / (va + vb + vc);
let (v, w) = (vb * denom, vc * denom);
(a + ab * v + ac * w, v, w)
}
#[cfg(test)]
@@ -568,24 +448,6 @@ mod tests {
use super::*;
use crate::primitives;
#[test]
fn a_box_first_reached_at_infinity_is_missed() {
let (lo, hi) = (Vec3A::ZERO, Vec3A::ONE);
// 1/d overflows on every axis: x, where the direction is subnormal, as well as y and z.
for d in [Vec3A::new(1e-39, 0.0, 0.0), Vec3A::new(1e-39, -0.0, -0.0)] {
let inv = Vec3A::ONE / d;
for o in [Vec3A::new(0.5, -1.0, 0.5), Vec3A::new(0.5, 2.0, 0.5), Vec3A::new(-1.0, 0.5, 0.5)] {
assert_eq!(Bvh::slab(lo, hi, o, inv, f32::INFINITY), None, "d {d}, origin {o}");
}
assert_eq!(Bvh::slab(lo, hi, Vec3A::splat(0.5), inv, f32::INFINITY), Some(0.0), "d {d}, inside");
}
// A ray parallel to a slab outside it, with a finite exit on another axis.
let inv = Vec3A::ONE / Vec3A::new(1.0, 0.0, 0.0);
assert_eq!(Bvh::slab(lo, hi, Vec3A::new(0.5, -1.0, 0.5), inv, f32::INFINITY), None);
assert_eq!(Bvh::slab(lo, hi, Vec3A::new(-1.0, 0.5, 0.5), inv, f32::INFINITY), Some(1.0));
assert_eq!(Bvh::slab(lo, hi, Vec3A::new(0.5, 0.0, 0.5), inv, f32::INFINITY), Some(0.0), "in the plane");
}
#[test]
fn nearest_point_matches_brute_force() {
let m = primitives::builtin("torus").unwrap();
@@ -613,61 +475,6 @@ mod tests {
assert!(bvh.nearest(Vec3::ZERO, f32::MAX, &|_| false).is_none(), "filtered out");
}
#[test]
fn nearest_finds_a_point_inside_a_thin_triangle() {
let l = Limits::default();
let bvh = Bvh::from_slices(&[[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.0, 1e-4, 0.0]], &[0, 1, 2], &l).unwrap();
// p = a + 0.5 (b - a) + 0.25 (c - a) lies on the triangle.
let p = Vec3::new(0.75, 2.5e-5, 0.0);
let hit = bvh.nearest(p, 0.0, &|_| true).unwrap();
assert_eq!(hit.t, 0.0);
assert!((hit.u - 0.5).abs() < 1e-4 && (hit.v - 0.25).abs() < 1e-4, "{hit:?}");
}
#[test]
fn nearest_finds_a_coplanar_point_inside_a_triangle_at_distance_zero() {
let l = Limits::default();
let bvh = Bvh::from_slices(&[[-1.0, -1.0, 0.0], [2.0, 0.0, 0.0], [0.0, 3.0, 0.0]], &[0, 1, 2], &l).unwrap();
// The origin is a + 3/11 (b - a) + 2/11 (c - a); rebuilding it from those weights in
// floating point gives x of about -5.6e-17 instead of 0.
let hit = bvh.nearest(Vec3::ZERO, 0.0, &|_| true).unwrap();
assert_eq!(hit.t, 0.0);
assert!((hit.u - 3.0 / 11.0).abs() < 1e-6 && (hit.v - 2.0 / 11.0).abs() < 1e-6, "{hit:?}");
}
#[test]
fn nearest_measures_a_triangle_with_a_collapsed_edge() {
let l = Limits::default();
let p = Vec3::new(0.5, 1.0, 0.0);
let (o, x) = ([0.0, 0.0, 0.0], [1.0, 0.0, 0.0]);
// The surviving segment runs from the origin to +X; its point nearest p is (0.5, 0, 0).
for (positions, indices) in [(vec![o, o, x], vec![0, 1, 2]), (vec![x, x, o], vec![0, 1, 2]), (vec![o, x], vec![0, 0, 1])] {
let bvh = Bvh::from_slices(&positions, &indices, &l).unwrap();
let hit = bvh.nearest(p, 10.0, &|_| true);
let hit = hit.unwrap_or_else(|| panic!("{positions:?} {indices:?}: no point found"));
assert!((hit.t - 1.0).abs() < 1e-6, "{positions:?} {indices:?}: {hit:?}");
let [a, b, c] = [0, 1, 2].map(|k| Vec3::from_array(positions[indices[k] as usize]));
let q = a * (1.0 - hit.u - hit.v) + b * hit.u + c * hit.v;
assert!((q - Vec3::new(0.5, 0.0, 0.0)).length() < 1e-6, "{positions:?} {indices:?}: {q}");
}
}
#[test]
fn a_tree_without_triangles_has_no_nodes() {
let l = Limits::default();
assert_eq!(Bvh::from_slices(&[], &[], &l).unwrap().nodes().len(), 0);
// Every triangle is left out: one corner is not finite.
let rejected = Mesh { positions: vec![Vec3::ZERO, Vec3::X, Vec3::new(f32::NAN, 0.0, 0.0)], indices: vec![0, 1, 2], ..Mesh::default() };
let bvh = Bvh::try_new(&rejected).unwrap();
assert_eq!(bvh.nodes().len(), 0);
assert!(bvh.is_empty());
assert!(bvh.closest(Vec3::Z, Vec3::NEG_Z, 10.0).is_none());
assert!(bvh.nearest(Vec3::ZERO, 10.0, &|_| true).is_none());
let mut found = 0;
bvh.query_box(Vec3::splat(-1.0), Vec3::ONE, |_| found += 1);
assert_eq!(found, 0);
}
#[test]
fn traversal_stack_spills_in_lifo_order() {
let mut st = Stack::default();
@@ -868,115 +675,4 @@ mod tests {
assert_eq!(hit.tri, 500);
assert_eq!(hit.t, 10.0);
}
#[test]
fn bvh_rejects_non_finite_queries_without_callbacks() {
let m = primitives::plane(2.0, 4);
let bvh = Bvh::new(&m);
let mut calls = 0;
bvh.query_box(Vec3::new(f32::NAN, -1.0, -1.0), Vec3::ONE, |_| calls += 1);
bvh.query_box(Vec3::splat(-1.0), Vec3::new(1.0, f32::NAN, 1.0), |_| calls += 1);
// A box whose lower corner is past its upper corner on one axis is empty, even where a
// triangle spans both values.
bvh.query_box(Vec3::new(0.3, -1.0, -1.0), Vec3::new(0.2, 1.0, 1.0), |_| calls += 1);
bvh.query_box(Vec3::new(-1.0, -1.0, 0.3), Vec3::new(1.0, 1.0, 0.2), |_| calls += 1);
assert_eq!(calls, 0);
// An infinite box is a valid query and finds everything.
bvh.query_box(Vec3::NEG_INFINITY, Vec3::INFINITY, |_| calls += 1);
assert_eq!(calls, m.triangle_count());
let (o, d) = (Vec3::new(0.0, 1.0, 0.0), Vec3::NEG_Y);
assert!(bvh.closest(o, d, 10.0).is_some());
let counted = std::cell::Cell::new(0);
let filter = |_: u32| {
counted.set(counted.get() + 1);
true
};
for (o, d, tmax) in
[(Vec3::NAN, d, 10.0), (o, Vec3::new(0.0, f32::NAN, 0.0), 10.0), (o, Vec3::ZERO, 10.0), (o, Vec3::NEG_INFINITY, 10.0), (o, d, f32::NAN)]
{
assert!(bvh.closest_filtered(o, d, tmax, &filter).is_none(), "{o} {d} {tmax}");
assert!(!bvh.occluded(o, d, tmax));
}
assert_eq!(counted.get(), 0);
// A negative or NaN distance finds nothing, not the points within its magnitude.
assert!(bvh.nearest(Vec3::new(0.0, 0.5, 0.0), 1.0, &|_| true).is_some());
assert!(bvh.nearest(Vec3::new(0.0, 0.5, 0.0), -1.0, &|_| true).is_none());
assert!(bvh.nearest(Vec3::new(0.0, 0.5, 0.0), f32::NAN, &|_| true).is_none());
}
#[test]
fn ray_hits_do_not_depend_on_the_size_of_the_triangle() {
for exponent in [-10, -7, -3, 0, 3, 7, 10] {
let s = 10f32.powi(exponent);
let bvh = Bvh::from_slices(&[[0.0, 0.0, 0.0], [s, 0.0, 0.0], [0.0, 0.0, s]], &[0, 1, 2], &Limits::default()).unwrap();
// Straight down onto the triangle, from one triangle size above it.
let o = Vec3::new(0.25 * s, s, 0.25 * s);
let hit = bvh.closest(o, Vec3::NEG_Y, f32::MAX).unwrap_or_else(|| panic!("no hit at 1e{exponent}"));
assert!((hit.t / s - 1.0).abs() < 1e-4, "1e{exponent}: {hit:?}");
assert!((hit.u - 0.25).abs() < 1e-4 && (hit.v - 0.25).abs() < 1e-4, "1e{exponent}: {hit:?}");
assert!(bvh.occluded(o, Vec3::NEG_Y, 2.0 * s), "1e{exponent}");
// Beside the triangle, and along its plane.
assert!(bvh.closest(Vec3::new(0.75 * s, s, 0.75 * s), Vec3::NEG_Y, f32::MAX).is_none(), "1e{exponent}");
assert!(bvh.closest(Vec3::new(-s, 0.0, 0.25 * s), Vec3::X, f32::MAX).is_none(), "1e{exponent}");
}
}
#[test]
fn nearest_includes_points_exactly_at_the_distance() {
let m = primitives::plane(2.0, 4);
let bvh = Bvh::new(&m);
// A vertex of the plane, and a point 0.5 above it.
let corner = m.positions[6];
assert_eq!(bvh.nearest(corner, 0.0, &|_| true).map(|h| h.t), Some(0.0));
let above = corner + Vec3::new(0.0, 0.5, 0.0);
assert_eq!(bvh.nearest(above, 0.5, &|_| true).map(|h| h.t), Some(0.5));
assert!(bvh.nearest(above, 0.499, &|_| true).is_none());
// A triangle 1e30 away is outside a distance of 1e20, though both squares overflow.
let far = Mesh {
positions: vec![Vec3::new(1e30, 0.0, 0.0), Vec3::new(1e30, 1.0, 0.0), Vec3::new(1e30, 0.0, 1.0)],
indices: vec![0, 1, 2],
..Mesh::default()
};
assert!(Bvh::new(&far).nearest(Vec3::ZERO, 1e20, &|_| true).is_none());
}
#[test]
fn bvh_leaves_out_non_finite_triangles() {
let mut m = primitives::plane(2.0, 4);
// Vertex 0 is the corner of one triangle only.
m.positions[0] = Vec3::new(f32::NAN, 0.0, 0.0);
m.positions[24] = Vec3::new(0.0, f32::INFINITY, 0.0);
let affected = m.indices.chunks(3).filter(|t| t.contains(&0) || t.contains(&24)).count();
let bvh = Bvh::new(&m);
let mut found = Vec::new();
bvh.query_box(Vec3::splat(-10.0), Vec3::splat(10.0), |t| found.push(t));
assert_eq!(found.len(), m.triangle_count() - affected);
for (lo, hi, _, _) in bvh.nodes() {
assert!(lo.is_finite() && hi.is_finite(), "{lo} {hi}");
}
let (_, order) = bvh.triangles();
assert!(order.iter().all(|t| m.tri(*t as usize).is_some_and(|c| !c.contains(&0) && !c.contains(&24))));
}
#[test]
fn bvh_slices_check_limits_indices_and_positions() {
let m = primitives::plane(2.0, 4);
let positions: Vec<[f32; 3]> = m.positions.iter().map(|p| p.to_array()).collect();
let l = Limits::default();
let bvh = Bvh::from_slices(&positions, &m.indices, &l).unwrap();
assert_eq!(bvh.triangles().1.len(), m.triangle_count());
let hit = bvh.closest(Vec3::new(0.3, 1.0, 0.2), Vec3::NEG_Y, 10.0).unwrap();
assert_eq!(Some(hit), Bvh::new(&m).closest(Vec3::new(0.3, 1.0, 0.2), Vec3::NEG_Y, 10.0));
assert_eq!(Bvh::try_new(&m).unwrap().triangles(), bvh.triangles());
let few = Limits { max_triangles: m.triangle_count() - 1, ..l };
assert!(matches!(Bvh::from_slices(&positions, &m.indices, &few), Err(MeshOpsError::TooLarge { .. })));
assert!(Bvh::from_slices(&positions, &[0, 1, positions.len() as u32], &l).is_err());
assert!(Bvh::from_slices(&positions, &[0, 1], &l).is_err());
let mut nan = positions.clone();
nan[3][2] = f32::NAN;
assert!(Bvh::from_slices(&nan, &m.indices, &l).is_err());
assert!(Bvh::from_slices(&[], &[], &l).unwrap().is_empty());
}
}
+20 -159
View File
@@ -1,9 +1,9 @@
//! Orbit camera (texture painting navigation) and picking rays.
use glam::{DVec4, Mat4, Vec2, Vec3};
use glam::{Mat4, Vec2, Vec3, Vec4};
use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct OrbitCamera {
pub target: Vec3,
/// Radians around Y.
@@ -16,7 +16,7 @@ pub struct OrbitCamera {
/// Scene radius (sets the clip planes).
pub scene_radius: f32,
/// Orthographic projection instead of perspective.
#[cfg_attr(feature = "serde", serde(default))]
#[serde(default)]
pub ortho: bool,
}
@@ -48,22 +48,16 @@ impl OrbitCamera {
Mat4::look_at_rh(self.eye(), self.target, Vec3::Y)
}
/// The vertical field of view in radians, with `fov` clamped to 5° to 150°. Perspective and
/// orthographic projection, [`OrbitCamera::pan`] and [`OrbitCamera::frame`] all use it.
fn fov_radians(&self) -> f32 {
self.fov.clamp(5.0, 150.0).to_radians()
}
pub fn proj(&self, aspect: f32) -> Mat4 {
let r = self.scene_radius.max(1e-3);
let near = (self.distance - r * 4.0).max(r * 0.01).max(1e-4);
let far = self.distance + r * 50.0;
let aspect = if aspect.is_finite() && aspect > 1e-4 { aspect } else { 1.0 };
if self.ortho {
let h = self.distance * (self.fov_radians() * 0.5).tan();
let h = self.distance * (self.fov.to_radians() * 0.5).tan();
Mat4::orthographic_rh(-h * aspect, h * aspect, -h, h, near.min(0.01), far)
} else {
Mat4::perspective_rh(self.fov_radians(), aspect, near, far)
Mat4::perspective_rh(self.fov.clamp(5.0, 150.0).to_radians(), aspect, near, far)
}
}
@@ -71,20 +65,12 @@ impl OrbitCamera {
self.proj(aspect) * self.view()
}
/// Frame a bounding box, keeping the current angles. A box whose center or framing distance
/// is not finite, or whose framed view-projection at aspect 1 is not finite (an eye that
/// rounds to the target, or terms past the `f32` range), leaves the camera unchanged.
/// Frame a bounding box, keeping the current angles.
pub fn frame(&mut self, lo: Vec3, hi: Vec3) {
let target = lo * 0.5 + hi * 0.5;
self.target = (lo + hi) * 0.5;
let r = ((hi - lo).length() * 0.5).max(1e-3);
let distance = r / (self.fov_radians() * 0.5).sin() * 1.1;
if !(target.is_finite() && distance.is_finite()) {
return;
}
let framed = OrbitCamera { target, scene_radius: r, distance, ..*self };
if framed.view_proj(1.0).is_finite() {
*self = framed;
}
self.scene_radius = r;
self.distance = r / (self.fov.clamp(5.0, 150.0).to_radians() * 0.5).sin() * 1.1;
}
pub fn orbit(&mut self, dx: f32, dy: f32) {
@@ -97,46 +83,28 @@ impl OrbitCamera {
let f = self.forward();
let right = f.cross(Vec3::Y).try_normalize().unwrap_or(Vec3::X);
let up = right.cross(f);
let scale = self.distance * (self.fov_radians() * 0.5).tan() * 2.0;
let scale = self.distance * (self.fov.to_radians() * 0.5).tan() * 2.0;
self.target += (-right * dx + up * dy) * scale;
}
/// Dolly by a factor exponent (positive zooms in). A distance whose view-projection at aspect 1
/// is not finite (an eye that rounds to a target far from the origin) leaves the camera
/// unchanged.
/// Dolly by a factor exponent (positive zooms in).
pub fn zoom(&mut self, amount: f32) {
let r = self.scene_radius.max(1e-3);
let distance = (self.distance * (-amount).exp()).clamp(r * 0.05, r * 200.0);
let zoomed = OrbitCamera { distance, ..*self };
if zoomed.eye() != zoomed.target && zoomed.view_proj(1.0).is_finite() {
*self = zoomed;
}
self.distance = (self.distance * (-amount).exp()).clamp(r * 0.05, r * 200.0);
}
/// Ray through a viewport point given in normalized device coordinates (-1..1, y up). It
/// starts on the near plane: [`OrbitCamera::proj`] has a depth range of 0 to 1. The
/// view-projection is inverted and the points unprojected in `f64`, where the determinant of
/// a large scene's matrix and the squared length of the ray do not leave the range.
/// Ray through a viewport point given in normalized device coordinates (-1..1, y up).
pub fn ray(&self, ndc: Vec2, aspect: f32) -> Ray {
let inv = self.view_proj(aspect).as_dmat4().inverse();
let (x, y) = (f64::from(ndc.x), f64::from(ndc.y));
let a = inv * DVec4::new(x, y, 0.0, 1.0);
let b = inv * DVec4::new(x, y, 1.0, 1.0);
let inv = self.view_proj(aspect).inverse();
let a = inv * Vec4::new(ndc.x, ndc.y, 0.0, 1.0);
let b = inv * Vec4::new(ndc.x, ndc.y, 1.0, 1.0);
let (a, b) = (a.truncate() / a.w, b.truncate() / b.w);
let origin = a.as_vec3();
let dir = (b - a).try_normalize().map(|d| d.as_vec3()).filter(|d| d.is_finite()).unwrap_or(self.forward());
Ray { origin, dir }
Ray { origin: a, dir: (b - a).try_normalize().unwrap_or(self.forward()) }
}
/// Project a world point to NDC (x, y in -1..1, y up; z depth). None behind the camera, in
/// both projections: the point's depth in front of the eye must be over 1e-6.
/// Project a world point to NDC (x, y in -1..1, y up; z depth). None behind the camera.
pub fn project(&self, p: Vec3, aspect: f32) -> Option<Vec3> {
let in_view = self.view() * p.extend(1.0);
// The view looks down -Z.
if -in_view.z <= 1e-6 {
return None;
}
let c = self.proj(aspect) * in_view;
let c = self.view_proj(aspect) * p.extend(1.0);
(c.w > 1e-6).then(|| c.truncate() / c.w)
}
}
@@ -169,111 +137,4 @@ mod tests {
assert!(c.distance > 0.0 && c.distance.is_finite());
let _ = c.proj(f32::NAN);
}
#[test]
fn orthographic_projection_finds_nothing_behind_the_camera() {
for ortho in [false, true] {
let c = OrbitCamera { ortho, ..OrbitCamera::default() };
assert!(c.project(c.eye() - c.forward(), 1.5).is_none(), "ortho {ortho}");
assert!(c.project(c.eye() - c.forward() * 1e-3, 1.5).is_none(), "ortho {ortho}");
assert!(c.project(c.target, 1.5).is_some(), "ortho {ortho}");
}
}
#[test]
fn field_of_view_is_clamped_the_same_way_in_every_mode() {
for fov in [0.0, -10.0, 1.0, 179.0, 500.0] {
let c = OrbitCamera { fov, ortho: true, ..OrbitCamera::default() };
let clamped = OrbitCamera { fov: fov.clamp(5.0, 150.0), ..c };
assert!(c.proj(1.5).to_cols_array().iter().all(|v| v.is_finite()), "fov {fov}");
assert_eq!(c.proj(1.5), clamped.proj(1.5), "fov {fov}");
let (mut panned, mut expected) = (c, clamped);
panned.pan(0.25, -0.5);
expected.pan(0.25, -0.5);
assert_eq!(panned.target, expected.target, "fov {fov}");
assert_ne!(panned.target, c.target, "fov {fov}");
}
}
#[test]
fn frame_leaves_the_camera_unchanged_for_a_box_it_cannot_frame() {
let mut c = OrbitCamera::default();
c.frame(Vec3::splat(-1.0), Vec3::splat(1.0));
let framed = c;
for (lo, hi) in [
(Vec3::new(f32::NAN, 0.0, 0.0), Vec3::ONE),
(Vec3::ZERO, Vec3::new(1.0, f32::INFINITY, 1.0)),
(Vec3::NEG_INFINITY, Vec3::INFINITY),
(Vec3::splat(-3e38), Vec3::splat(3e38)),
] {
c.frame(lo, hi);
assert_eq!(c, framed, "{lo} {hi}");
}
}
#[test]
fn frame_keeps_the_view_finite() {
let mut c = OrbitCamera::default();
c.frame(Vec3::splat(-1e15), Vec3::splat(1e15));
assert!(c.view_proj(1.0).is_finite());
assert!((c.scene_radius / (1e15 * 3f32.sqrt()) - 1.0).abs() < 1e-4, "{}", c.scene_radius);
let framed = c;
for (lo, hi) in [
// A finite center and distance, with an eye whose distance from the target squares
// past the f32 range.
(Vec3::splat(-5e18), Vec3::splat(5e18)),
// An eye that rounds to a target this far out.
(Vec3::splat(1e30), Vec3::splat(1e30)),
// Corners whose sum overflows f32.
(Vec3::new(1.7e38, -1.0, -1.0), Vec3::new(1.8e38, 1.0, 1.0)),
] {
c.frame(lo, hi);
assert_eq!(c, framed, "{lo} {hi}");
assert!(c.view_proj(1.0).is_finite(), "{lo} {hi}");
}
}
#[test]
fn zoom_keeps_the_view_finite_near_a_far_target() {
// At the closest zoom the eye is 0.69 from the target, where coordinates of 1e8 are 8 apart.
let mut c = OrbitCamera::default();
c.frame(Vec3::splat(1e8 - 8.0), Vec3::splat(1e8 + 8.0));
assert!(c.view().is_finite());
c.zoom(10.0);
assert!(c.view().is_finite(), "distance {}", c.distance);
assert_ne!(c.eye(), c.target);
// Zooming out from there works as before.
let before = c.distance;
c.zoom(-1.0);
assert!(c.distance > before);
}
#[test]
fn orthographic_rays_of_a_large_scene_are_finite() {
// The view-projection of this scene has a determinant that underflows f32.
let mut c = OrbitCamera { ortho: true, ..OrbitCamera::default() };
c.frame(Vec3::splat(-1e15), Vec3::splat(1e15));
let r = c.ray(Vec2::ZERO, 1.0);
assert!(r.origin.is_finite() && r.dir.is_finite(), "{r:?}");
assert!((r.dir - c.forward()).length() < 1e-4, "{r:?}");
let p = Vec3::new(3e14, -2e14, 1e14);
let ndc = c.project(p, 1.0).unwrap();
let r = c.ray(ndc.truncate(), 1.0);
// The ray passes the point within a millionth of the scene's size.
let to_p = p - r.origin;
assert!((to_p - r.dir * to_p.dot(r.dir)).length() < 1e9, "{r:?}");
}
#[test]
fn off_center_rays_of_a_large_scene_leave_the_center() {
// The near and far points are finite, while the square of their distance overflows f32.
let mut c = OrbitCamera { pitch: 0.0, ..OrbitCamera::default() };
c.frame(Vec3::splat(-1e18), Vec3::splat(1e18));
let r = c.ray(Vec2::new(0.5, 0.0), 1.0);
assert!(r.origin.is_finite() && r.dir.is_finite(), "{r:?}");
assert!((r.dir.length() - 1.0).abs() < 1e-5, "{r:?}");
assert!(r.dir.dot(c.forward()) < 0.999, "{r:?}");
let ndc = c.project(r.origin + r.dir * c.distance, 1.0).unwrap();
assert!((ndc.x - 0.5).abs() < 1e-3 && ndc.y.abs() < 1e-3, "{ndc}");
}
}
+75 -533
View File
@@ -2,22 +2,16 @@
//! to. Painting, compositing, baking and padding all work from this one buffer, so they agree
//! on which texel is which surface point.
use glam::{DVec2, Vec2, Vec3, Vec4};
#[cfg(feature = "parallel")]
use glam::{Vec2, Vec3, Vec4};
use rayon::prelude::*;
use crate::mesh::unit;
use crate::{Limits, Mesh, MeshOpsError, Result, check_limit, try_vec};
use crate::Mesh;
/// Texel not covered by any triangle.
pub const NO_TRI: u32 = u32::MAX;
const BAND: u32 = 32;
/// A triangle with a corner farther than this many texels from the UV origin is not rasterized:
/// within it, the products of two texel coordinates in the edge functions stay finite.
const MAX_TEXEL_COORDINATE: f32 = 1e18;
#[derive(Clone, Debug, PartialEq)]
pub struct UvGBuffer {
pub width: u32,
@@ -26,8 +20,7 @@ pub struct UvGBuffer {
pub tri: Vec<u32>,
/// Barycentric weights of the triangle's second and third vertices.
pub bary: Vec<[f32; 2]>,
/// Texels written by more than one triangle (overlapping UVs). A texel whose center lies on
/// an edge two triangles share is written by both and counts; the later triangle keeps it.
/// Texels written by more than one triangle (overlapping UVs).
pub overlaps: u32,
}
@@ -44,110 +37,78 @@ pub struct Surface {
pub tri: u32,
}
/// The edge function of `a → b` at `p`, `(b - a) × (p - a)`, rounded once from the exact value
/// of its six products. Each product is split into its rounded value and its rounding error,
/// and the twelve parts are added with Neumaier's compensation, so corners far from `p` do not
/// cancel the digits that place `p` against the edge.
fn edge(a: DVec2, b: DVec2, p: DVec2) -> f64 {
let products = [(b.x, p.y), (-b.x, a.y), (-a.x, p.y), (-b.y, p.x), (b.y, a.x), (a.y, p.x)];
let (mut sum, mut compensation) = (0.0f64, 0.0f64);
for (x, y) in products {
let high = x * y;
for part in [high, x.mul_add(y, -high)] {
let next = sum + part;
compensation += if sum.abs() >= part.abs() { (sum - next) + part } else { (part - next) + sum };
sum = next;
}
}
sum + compensation
}
/// Vertex indices of triangle `t` of an index buffer.
fn corners(indices: &[u32], t: usize) -> Option<[usize; 3]> {
let start = t.checked_mul(3)?;
let i = indices.get(start..start.checked_add(3)?)?;
Some([i[0] as usize, i[1] as usize, i[2] as usize])
}
/// Texel count of a `width × height` buffer, checked against `limits`. A count whose
/// barycentric array would be over `isize::MAX` bytes, which no allocation can hold, is
/// `OutOfMemory`.
fn texels(width: u32, height: u32, limits: &Limits) -> Result<usize> {
if width == 0 || height == 0 {
return Err(MeshOpsError::Invalid(format!("G-buffer size {width} × {height} is empty")));
}
let side = limits.max_gbuffer_side as usize;
check_limit("G-buffer width", width as usize, side)?;
check_limit("G-buffer height", height as usize, side)?;
let n = u64::from(width) * u64::from(height);
if n > limits.max_gbuffer_texels {
return Err(MeshOpsError::TooLarge { what: "G-buffer texel count", got: n, limit: limits.max_gbuffer_texels });
}
let n = usize::try_from(n).map_err(|_| MeshOpsError::TooLarge { what: "G-buffer texel count", got: n, limit: usize::MAX as u64 })?;
match n.checked_mul(size_of::<[f32; 2]>()) {
Some(bytes) if bytes <= isize::MAX as usize => Ok(n),
_ => Err(MeshOpsError::OutOfMemory("G-buffer")),
}
fn edge(a: Vec2, b: Vec2, p: Vec2) -> f32 {
(b.x - a.x) * (p.y - a.y) - (b.y - a.y) * (p.x - a.x)
}
impl UvGBuffer {
/// Rasterize the triangles of material `material` at `width × height`, each side clamped to
/// `1..=8192` (the default [`Limits::max_gbuffer_side`]). When the mesh is over another
/// default [`Limits`] field or the memory for that size cannot be reserved, the buffer is
/// 1 × 1 and uncovered.
/// Rasterize the triangles of material `material` at `width × height`.
pub fn new(mesh: &Mesh, material: usize, width: u32, height: u32) -> UvGBuffer {
let side = Limits::default().max_gbuffer_side;
let (w, h) = (width.clamp(1, side), height.clamp(1, side));
UvGBuffer::try_new(mesh, material, w, h, &Limits::default()).unwrap_or_else(|_| UvGBuffer {
width: 1,
height: 1,
tri: vec![NO_TRI],
bary: vec![[0.0; 2]],
overlaps: 0,
})
}
/// [`UvGBuffer::new`] with the size checked against `limits` instead of clamped: a zero
/// side is an error. The mesh's vertex and triangle counts and the rasterizer's work and band
/// lists are checked before the texel buffers are reserved.
pub fn try_new(mesh: &Mesh, material: usize, width: u32, height: u32, limits: &Limits) -> Result<UvGBuffer> {
let n = texels(width, height, limits)?;
check_limit("vertex count", mesh.positions.len(), limits.max_vertices)?;
check_limit("triangle count", mesh.triangle_count(), limits.max_triangles)?;
let bins = Bins::new(&mesh.uvs, &mesh.indices, || mesh.triangles_of(material), (width, height), limits)?;
UvGBuffer::rasterize(&mesh.uvs, &mesh.indices, &bins, (width, height), n)
}
/// Rasterize every triangle of `indices` over `uvs` at `width × height`. The size, the
/// triangle count, every index and every UV (finite) are checked first, and the
/// rasterizer's work and band lists before the texel buffers are reserved.
pub fn from_slices(uvs: &[[f32; 2]], indices: &[u32], width: u32, height: u32, limits: &Limits) -> Result<UvGBuffer> {
let n = texels(width, height, limits)?;
check_limit("vertex count", uvs.len(), limits.max_vertices)?;
if !indices.len().is_multiple_of(3) {
return Err(MeshOpsError::Invalid("index count is not a multiple of 3".into()));
let (w, h) = (width.max(1), height.max(1));
let size = Vec2::new(w as f32, h as f32);
let bands = h.div_ceil(BAND) as usize;
let mut bins: Vec<Vec<u32>> = vec![Vec::new(); bands];
for t in mesh.triangles_of(material) {
let Some([a, b, c]) = mesh.tri(t) else { continue };
let (Some(ua), Some(ub), Some(uc)) = (mesh.uvs.get(a), mesh.uvs.get(b), mesh.uvs.get(c)) else { continue };
let y0 = (ua.y.min(ub.y).min(uc.y) * size.y).floor().max(0.0) as i64;
let y1 = (ua.y.max(ub.y).max(uc.y) * size.y).ceil().min(size.y) as i64;
if y1 <= y0 || !ua.is_finite() || !ub.is_finite() || !uc.is_finite() {
continue;
}
let (b0, b1) = ((y0 / BAND as i64) as usize, ((y1 - 1).max(0) / BAND as i64) as usize);
for bin in bins.iter_mut().take(b1 + 1).skip(b0) {
bin.push(t as u32);
}
}
check_limit("triangle count", indices.len() / 3, limits.max_triangles)?;
if let Some(bad) = indices.iter().find(|&&i| i as usize >= uvs.len()) {
return Err(MeshOpsError::Invalid(format!("index {bad} out of range ({} vertices)", uvs.len())));
}
if !uvs.iter().flatten().all(|v| v.is_finite()) {
return Err(MeshOpsError::Invalid("non-finite UV".into()));
}
let mut points = try_vec(uvs.len(), "UVs")?;
points.extend(uvs.iter().map(|uv| Vec2::from_array(*uv)));
let bins = Bins::new(&points, indices, || 0..indices.len() / 3, (width, height), limits)?;
UvGBuffer::rasterize(&points, indices, &bins, (width, height), n)
}
/// Reserve the `n` texels of a `width × height` buffer and draw the triangles that `bins`
/// lists.
fn rasterize(uvs: &[Vec2], indices: &[u32], bins: &Bins, (width, height): (u32, u32), n: usize) -> Result<UvGBuffer> {
let (mut tri, mut bary) = (try_vec(n, "G-buffer")?, try_vec(n, "G-buffer")?);
tri.resize(n, NO_TRI);
bary.resize(n, [0.0f32; 2]);
let overlaps = bins.draw(uvs, indices, (width, height), &mut tri, &mut bary);
Ok(UvGBuffer { width, height, tri, bary, overlaps })
let n = w as usize * h as usize;
let mut tri = vec![NO_TRI; n];
let mut bary = vec![[0.0f32; 2]; n];
let band_len = (BAND * w) as usize;
let overlaps: u32 = tri
.par_chunks_mut(band_len)
.zip(bary.par_chunks_mut(band_len))
.enumerate()
.map(|(bi, (tri, bary))| {
let mut overlaps = 0u32;
let row0 = bi as u32 * BAND;
let rows = (tri.len() as u32) / w;
for &t in bins.get(bi).map(Vec::as_slice).unwrap_or(&[]) {
let Some([a, b, c]) = mesh.tri(t as usize) else { continue };
let (Some(&ua), Some(&ub), Some(&uc)) = (mesh.uvs.get(a), mesh.uvs.get(b), mesh.uvs.get(c)) else { continue };
let (pa, pb, pc) = (ua * size, ub * size, uc * size);
let area = edge(pa, pb, pc);
if area.abs() < 1e-12 {
continue;
}
let eps = -1e-6 * area.abs();
let x0 = pa.x.min(pb.x).min(pc.x).floor().max(0.0) as u32;
let x1 = (pa.x.max(pb.x).max(pc.x).ceil().min(w as f32) as u32).min(w);
let y0 = (pa.y.min(pb.y).min(pc.y).floor().max(row0 as f32) as u32).max(row0);
let y1 = (pa.y.max(pb.y).max(pc.y).ceil() as u32).min(row0 + rows);
for y in y0..y1 {
for x in x0..x1 {
let p = Vec2::new(x as f32 + 0.5, y as f32 + 0.5);
let (w0, w1, w2) = (edge(pb, pc, p) * area.signum(), edge(pc, pa, p) * area.signum(), edge(pa, pb, p) * area.signum());
if w0 < eps || w1 < eps || w2 < eps {
continue;
}
let i = ((y - row0) * w + x) as usize;
if let (Some(slot), Some(bw)) = (tri.get_mut(i), bary.get_mut(i)) {
if *slot != NO_TRI {
overlaps += 1;
}
*slot = t;
let inv = 1.0 / area.abs();
*bw = [w1 * inv, w2 * inv];
}
}
}
}
overlaps
})
.sum();
UvGBuffer { width: w, height: h, tri, bary, overlaps }
}
pub fn covered(&self, i: usize) -> bool {
@@ -173,199 +134,18 @@ impl UvGBuffer {
}
}
/// `total + add`, or `TooLarge` naming `what` when that is over `limit` (`got` is `u64::MAX`
/// when the sum overflows).
fn add_within(what: &'static str, total: u64, add: u64, limit: u64) -> Result<u64> {
let got = total.saturating_add(add);
if got > limit { Err(MeshOpsError::TooLarge { what, got, limit }) } else { Ok(got) }
}
/// Triangle `t` in the texels of a `size` buffer: its corners (in `f64`), its signed doubled
/// area and its bounding box clipped to the buffer as `[x0, x1, y0, y1]` (ends exclusive).
/// `None` when a corner is missing, not finite or farther than [`MAX_TEXEL_COORDINATE`], when
/// the triangle has no area or when the clipped box is empty.
fn texel_triangle(uvs: &[Vec2], indices: &[u32], t: usize, size: Vec2) -> Option<([DVec2; 3], f64, [u32; 4])> {
let [a, b, c] = corners(indices, t)?;
let p = [*uvs.get(a)? * size, *uvs.get(b)? * size, *uvs.get(c)? * size];
if !p.iter().all(|q| q.is_finite() && q.abs().max_element() <= MAX_TEXEL_COORDINATE) {
return None;
}
let corners = p.map(|q| q.as_dvec2());
let area = edge(corners[0], corners[1], corners[2]);
if area.abs() < 1e-12 {
return None;
}
let lo = p[0].min(p[1]).min(p[2]).floor().clamp(Vec2::ZERO, size);
let hi = p[0].max(p[1]).max(p[2]).ceil().clamp(Vec2::ZERO, size);
let [x0, x1, y0, y1] = [lo.x as u32, hi.x as u32, lo.y as u32, hi.y as u32];
(x1 > x0 && y1 > y0).then_some((corners, area, [x0, x1, y0, y1]))
}
/// The bands of rows of a G-buffer (each [`BAND`] rows high), each with the triangles whose
/// clipped boxes reach it, in triangle order.
struct Bins {
/// Band `b`'s triangles are `ids[offsets[b]..offsets[b + 1]]`.
offsets: Vec<usize>,
ids: Vec<u32>,
}
impl Bins {
/// Bin the triangles that `triangles` returns (the same ones on every call) for a `w × h`
/// buffer. A first pass checks the triangles visited against [`Limits::max_triangles`], the
/// box texels against [`Limits::max_gbuffer_work`] and the band entries against
/// [`Limits::max_gbuffer_bin_entries`] and reserves nothing. A second pass counts each band's
/// entries, so the lists are reserved in one piece before a third pass fills them.
fn new<I: Iterator<Item = usize>>(uvs: &[Vec2], indices: &[u32], triangles: impl Fn() -> I, (w, h): (u32, u32), limits: &Limits) -> Result<Bins> {
let size = Vec2::new(w as f32, h as f32);
let bands = h.div_ceil(BAND) as usize;
// NO_TRI marks an uncovered texel, so it cannot name a triangle.
let triangles = || triangles().take_while(|t| *t < NO_TRI as usize);
let band_range = |y0: u32, y1: u32| (y0 / BAND) as usize..=((y1 - 1) / BAND) as usize;
let (mut visited, mut work, mut entries) = (0usize, 0u64, 0u64);
// Every entry count and offset below then fits in a usize.
let entry_limit = limits.max_gbuffer_bin_entries.min(usize::MAX as u64);
for t in triangles() {
visited = visited.saturating_add(1);
check_limit("triangle count", visited, limits.max_triangles)?;
let Some((_, _, [x0, x1, y0, y1])) = texel_triangle(uvs, indices, t, size) else { continue };
work = add_within("G-buffer work", work, u64::from(x1 - x0) * u64::from(y1 - y0), limits.max_gbuffer_work)?;
let reach = band_range(y0, y1);
entries = add_within("G-buffer band entries", entries, (reach.end() - reach.start() + 1) as u64, entry_limit)?;
}
// offsets[b + 1] counts band b's entries, then becomes the end of its run in `ids`.
let mut offsets = try_vec(bands + 1, "G-buffer bands")?;
offsets.resize(bands + 1, 0usize);
for t in triangles() {
let Some((_, _, [_, _, y0, y1])) = texel_triangle(uvs, indices, t, size) else { continue };
for b in band_range(y0, y1) {
if let Some(n) = offsets.get_mut(b + 1) {
*n += 1;
}
}
}
let mut run = 0;
for n in &mut offsets {
run += *n;
*n = run;
}
let entries = usize::try_from(entries).map_err(|_| MeshOpsError::OutOfMemory("G-buffer bands"))?;
let mut ids = try_vec(entries, "G-buffer bands")?;
ids.resize(entries, NO_TRI);
let mut next = try_vec(offsets.len(), "G-buffer bands")?;
next.extend_from_slice(&offsets);
for t in triangles() {
let Some((_, _, [_, _, y0, y1])) = texel_triangle(uvs, indices, t, size) else { continue };
for b in band_range(y0, y1) {
if let Some(at) = next.get_mut(b) {
if let Some(id) = ids.get_mut(*at) {
*id = t as u32;
}
*at += 1;
}
}
}
Ok(Bins { offsets, ids })
}
/// Write the triangle and barycentrics under each texel center of `w × h` buffers (`tri`
/// and `bary` hold `w × h` entries) for the binned triangles; returns the overlap count.
fn draw(&self, uvs: &[Vec2], indices: &[u32], (w, h): (u32, u32), tri: &mut [u32], bary: &mut [[f32; 2]]) -> u32 {
let size = Vec2::new(w as f32, h as f32);
let band_len = band_texels(w, tri.len());
let band = |(bi, (tri, bary)): (usize, (&mut [u32], &mut [[f32; 2]]))| {
let mut overlaps = 0u32;
let row0 = bi as u32 * BAND;
let rows = (tri.len() / w as usize) as u32;
let list = match (self.offsets.get(bi), self.offsets.get(bi + 1)) {
(Some(&start), Some(&end)) => self.ids.get(start..end).unwrap_or(&[]),
_ => &[],
};
for &t in list {
let Some(([pa, pb, pc], area, [x0, x1, y0, y1])) = texel_triangle(uvs, indices, t as usize, size) else { continue };
let (y0, y1) = (y0.max(row0), y1.min(row0 + rows));
if y0 >= y1 {
continue;
}
// Each edge function is taken in full at the first texel center of the box and
// stepped from there along its gradient, so its rounding at the other centers is
// a few `f64` steps of the box's size rather than of the corners' coordinates.
// Each edge function is its distance times the edge's length. A texel center
// within 1e-6 texel of an edge, plus that rounding, counts as inside: both
// triangles that share the edge write it. The slack is at most 1e-3 of the
// triangle's smallest height, so a thin triangle is not widened.
let start = DVec2::new(f64::from(x0) + 0.5, f64::from(y0) + 0.5);
let edges = [(pb, pc), (pc, pa), (pa, pb)];
let base = edges.map(|(a, b)| edge(a, b, start) * area.signum());
let step = edges.map(|(a, b)| DVec2::new(a.y - b.y, b.x - a.x) * area.signum());
let lengths = edges.map(|(a, b)| (b - a).length());
let lowest = area.abs() / lengths.iter().copied().fold(0.0, f64::max);
let slack = (1e-6 + 8.0 * f64::EPSILON * f64::from(size.max_element())).min(1e-3 * lowest);
let eps = lengths.map(|length| -slack * length);
for y in y0..y1 {
for x in x0..x1 {
let d = DVec2::new(f64::from(x - x0), f64::from(y - y0));
let [w0, w1, w2] = [0, 1, 2].map(|i| base[i] + (step[i].x * d.x + step[i].y * d.y));
if w0 < eps[0] || w1 < eps[1] || w2 < eps[2] {
continue;
}
let i = (y - row0) as usize * w as usize + x as usize;
if let (Some(slot), Some(bw)) = (tri.get_mut(i), bary.get_mut(i)) {
if *slot != NO_TRI {
overlaps = overlaps.saturating_add(1);
}
*slot = t;
let inv = 1.0 / area.abs();
*bw = [(w1 * inv) as f32, (w2 * inv) as f32];
}
}
}
}
overlaps
};
each_band(tri, bary, band_len, band)
}
}
/// Texels in one [`BAND`] of a `width`-wide buffer of `texels` texels, at most `texels` and at
/// least 1. The product is taken in `u64` and capped at `texels`, so a band of a wide buffer fits
/// a 32-bit `usize`.
fn band_texels(width: u32, texels: usize) -> usize {
let band = u64::from(BAND) * u64::from(width);
usize::try_from(band).map_or(texels, |band| band.min(texels)).max(1)
}
/// Run `band` on each band of `len` texels (on several threads with `parallel`) and add up the
/// overlap counts.
#[cfg(feature = "parallel")]
fn each_band(tri: &mut [u32], bary: &mut [[f32; 2]], len: usize, band: impl Fn((usize, (&mut [u32], &mut [[f32; 2]]))) -> u32 + Sync + Send) -> u32 {
tri.par_chunks_mut(len).zip(bary.par_chunks_mut(len)).enumerate().map(band).reduce(|| 0, u32::saturating_add)
}
/// Run `band` on each band of `len` texels (on several threads with `parallel`) and add up the
/// overlap counts.
#[cfg(not(feature = "parallel"))]
fn each_band(tri: &mut [u32], bary: &mut [[f32; 2]], len: usize, band: impl Fn((usize, (&mut [u32], &mut [[f32; 2]]))) -> u32) -> u32 {
tri.chunks_mut(len).zip(bary.chunks_mut(len)).enumerate().map(band).fold(0, u32::saturating_add)
}
/// Interpolate triangle `t` at barycentrics (weights of vertices 1 and 2). The tangent keeps the
/// direction of the interpolated vertex tangents and is not made perpendicular to the
/// interpolated normal: MikkTSpace bakers and shaders use the interpolated vectors as they are.
/// The bitangent sign is the one of the triangle's first vertex.
/// Interpolate triangle `t` at barycentrics (weights of vertices 1 and 2).
pub fn surface_at(mesh: &Mesh, t: u32, b1: f32, b2: f32) -> Option<Surface> {
let [a, b, c] = mesh.tri(t as usize)?;
let b0 = 1.0 - b1 - b2;
let p = |v: &[Vec3]| -> Option<Vec3> { Some(*v.get(a)? * b0 + *v.get(b)? * b1 + *v.get(c)? * b2) };
let pos = p(&mesh.positions)?;
// `unit` divides by the largest component first, so a long finite vector keeps its direction.
let nrm = unit(p(&mesh.normals)?).unwrap_or(Vec3::Y);
let (pa, pb, pc) = (mesh.positions.get(a)?.as_dvec3(), mesh.positions.get(b)?.as_dvec3(), mesh.positions.get(c)?.as_dvec3());
// The edges and their cross product are taken in `f64`, where the difference and the cross
// product of any two finite `f32` positions neither overflow nor round to zero.
let geo_nrm = (pb - pa).cross(pc - pa).try_normalize().map_or(nrm, |n| n.as_vec3());
let nrm = p(&mesh.normals)?.try_normalize().unwrap_or(Vec3::Y);
let (pa, pb, pc) = (*mesh.positions.get(a)?, *mesh.positions.get(b)?, *mesh.positions.get(c)?);
let geo_nrm = (pb - pa).cross(pc - pa).try_normalize().unwrap_or(nrm);
let tan = *mesh.tangents.get(a)? * b0 + *mesh.tangents.get(b)? * b1 + *mesh.tangents.get(c)? * b2;
let uv = *mesh.uvs.get(a)? * b0 + *mesh.uvs.get(b)? * b1 + *mesh.uvs.get(c)? * b2;
let tdir = unit(tan.truncate()).unwrap_or_else(|| nrm.any_orthonormal_vector());
let tdir = tan.truncate().try_normalize().unwrap_or_else(|| nrm.any_orthonormal_vector());
let w = mesh.tangents.get(a).map(|t| if t.w < 0.0 { -1.0 } else { 1.0 }).unwrap_or(1.0);
Some(Surface { pos, nrm, geo_nrm, tangent: tdir.extend(w), uv, tri: t })
}
@@ -417,242 +197,4 @@ mod tests {
}
}
}
#[test]
fn surface_keeps_the_direction_of_long_finite_vectors() {
// Squaring 1e30 overflows f32: the normal, the tangent and the face normal come out along
// the vectors all the same.
let s = 1e30;
let m = Mesh {
positions: vec![Vec3::ZERO, Vec3::X * s, Vec3::Y * s],
normals: vec![Vec3::X * s; 3],
tangents: vec![Vec4::new(0.0, s, 0.0, -1.0); 3],
uvs: vec![Vec2::ZERO, Vec2::X, Vec2::Y],
indices: vec![0, 1, 2],
..Mesh::default()
};
let surface = surface_at(&m, 0, 0.25, 0.25).unwrap();
assert!((surface.nrm - Vec3::X).length() < 1e-6, "{}", surface.nrm);
assert!((surface.tangent - Vec4::new(0.0, 1.0, 0.0, -1.0)).length() < 1e-6, "{}", surface.tangent);
assert!((surface.geo_nrm - Vec3::Z).length() < 1e-6, "{}", surface.geo_nrm);
}
#[test]
fn surface_face_normal_of_corners_whose_differences_overflow_f32() {
// pb - pa is 6e38, past f32::MAX: the face normal is still +Z, not the +Y shading normal.
let m = Mesh {
positions: vec![Vec3::new(-3e38, 0.0, 0.0), Vec3::new(3e38, 0.0, 0.0), Vec3::new(0.0, 3e38, 0.0)],
normals: vec![Vec3::Y; 3],
tangents: vec![Vec4::new(1.0, 0.0, 0.0, 1.0); 3],
uvs: vec![Vec2::ZERO, Vec2::X, Vec2::Y],
indices: vec![0, 1, 2],
..Mesh::default()
};
m.validate().unwrap();
let surface = surface_at(&m, 0, 0.25, 0.25).unwrap();
assert!((surface.nrm - Vec3::Y).length() < 1e-6, "{}", surface.nrm);
assert!((surface.geo_nrm - Vec3::Z).length() < 1e-6, "{}", surface.geo_nrm);
// A triangle one subnormal step wide keeps its face normal too.
let tiny = f32::from_bits(1);
let m = Mesh { positions: vec![Vec3::ZERO, Vec3::X * tiny, Vec3::Y * tiny], ..m };
let surface = surface_at(&m, 0, 0.25, 0.25).unwrap();
assert!((surface.geo_nrm - Vec3::Z).length() < 1e-6, "{}", surface.geo_nrm);
}
#[test]
fn gbuffer_rejects_huge_dimensions() {
let m = primitives::plane(1.0, 2);
let l = Limits::default();
for (w, h) in [(u32::MAX, u32::MAX), (l.max_gbuffer_side + 1, 1), (1, 0), (0, 1)] {
assert!(UvGBuffer::try_new(&m, 0, w, h, &l).is_err(), "{w} × {h}");
assert!(UvGBuffer::from_slices(&[[0.0, 0.0]; 3], &[0, 1, 2], w, h, &l).is_err(), "{w} × {h}");
}
let few = Limits { max_gbuffer_texels: 63, ..l };
assert!(UvGBuffer::try_new(&m, 0, 8, 8, &few).is_err());
// The infallible form clamps each side.
let g = UvGBuffer::new(&m, 0, u32::MAX, 0);
assert_eq!((g.width, g.height, g.tri.len()), (l.max_gbuffer_side, 1, l.max_gbuffer_side as usize));
// The checked forms rasterize as the clamped one does.
assert_eq!(UvGBuffer::try_new(&m, 0, 16, 16, &l).unwrap(), UvGBuffer::new(&m, 0, 16, 16));
let uvs: Vec<[f32; 2]> = m.uvs.iter().map(|uv| uv.to_array()).collect();
assert_eq!(UvGBuffer::from_slices(&uvs, &m.indices, 16, 16, &l).unwrap(), UvGBuffer::new(&m, 0, 16, 16));
}
#[test]
fn gbuffer_band_stays_within_the_buffer() {
assert_eq!(band_texels(8, 8 * 100), BAND as usize * 8);
// A buffer shorter than a band is one band, even when 32 rows of its width would not fit a
// 32-bit usize (custom limits allow a side of 1 << 27).
assert_eq!(band_texels(1 << 27, 1 << 27), 1 << 27);
assert_eq!(band_texels(u32::MAX, u32::MAX as usize), u32::MAX as usize);
assert_eq!(band_texels(4, 3), 3);
// A wide one-row buffer is drawn as one band; the triangle covers its left half.
let l = Limits { max_gbuffer_side: 1 << 12, ..Limits::default() };
let uvs = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]];
let g = UvGBuffer::from_slices(&uvs, &[0, 1, 2], 1 << 12, 1, &l).unwrap();
assert_eq!(g.covered_count(), 1 << 11);
}
#[test]
fn gbuffer_slices_reject_bad_indices_and_uvs() {
let l = Limits::default();
assert!(UvGBuffer::from_slices(&[[0.0, 0.0]; 3], &[0, 1, 3], 4, 4, &l).is_err());
assert!(UvGBuffer::from_slices(&[[0.0, 0.0]; 3], &[0, 1], 4, 4, &l).is_err());
assert!(UvGBuffer::from_slices(&[[0.0, 0.0], [f32::NAN, 0.0], [0.0, 1.0]], &[0, 1, 2], 4, 4, &l).is_err());
let empty = UvGBuffer::from_slices(&[], &[], 4, 4, &l).unwrap();
assert_eq!((empty.covered_count(), empty.overlaps), (0, 0));
}
#[test]
fn gbuffer_skips_triangles_whose_texel_coordinates_overflow() {
let l = Limits::default();
// Corners that become infinite in texels, and corners whose products overflow.
for far in [1e38f32, 1e30] {
let g = UvGBuffer::from_slices(&[[far, 0.0], [-far, 0.0], [0.0, far]], &[0, 1, 2], 8, 8, &l).unwrap();
assert_eq!(g.covered_count(), 0, "{far}");
assert!(g.bary.iter().flatten().all(|w| w.is_finite()), "{far}");
}
// A large triangle within reach covers every texel with weights that add up to one.
let g = UvGBuffer::from_slices(&[[-1e6, -1e6], [1e6, -1e6], [0.0, 1e6]], &[0, 1, 2], 8, 8, &l).unwrap();
assert_eq!(g.covered_count(), 64);
assert!(g.bary.iter().all(|[b1, b2]| (0.0..=1.0).contains(b1) && (0.0..=1.0).contains(b2) && b1 + b2 <= 1.0 + 1e-6), "{:?}", g.bary);
}
#[test]
fn gbuffer_edge_tolerance_is_a_texel_distance() {
// The triangle covers u + v <= 0, so no texel center is inside it, while its box covers
// every texel of the buffer and its area is about 2.8e14 square texels.
let m = 1_048_576.0;
let g = UvGBuffer::from_slices(&[[-m, -m], [m, -m], [-m, m]], &[0, 1, 2], 8, 8, &Limits::default()).unwrap();
assert_eq!(g.covered_count(), 0);
// A sliver 0.1 texel high whose corners lie 8e14 texels to either side: the rounding at
// those coordinates does not widen it to the texel centers at y = 0.5.
let g = UvGBuffer::from_slices(&[[-1e14, 0.0], [1e14, 0.0], [0.0, 0.0125]], &[0, 1, 2], 8, 8, &Limits::default()).unwrap();
assert_eq!(g.covered_count(), 0);
// The same triangle mirrored to cover u + v >= 0 covers every texel center.
let g = UvGBuffer::from_slices(&[[m, m], [-m, m], [m, -m]], &[0, 1, 2], 8, 8, &Limits::default()).unwrap();
assert_eq!(g.covered_count(), 64);
// The same triangles with corners up to 1e18 texels away, the farthest that is drawn.
for m in [1e15_f32, 1.25e17] {
let g = UvGBuffer::from_slices(&[[-m, -m], [m, -m], [-m, m]], &[0, 1, 2], 8, 8, &Limits::default()).unwrap();
assert_eq!(g.covered_count(), 0, "{m}");
let g = UvGBuffer::from_slices(&[[m, m], [-m, m], [m, -m]], &[0, 1, 2], 8, 8, &Limits::default()).unwrap();
assert_eq!(g.covered_count(), 64, "{m}");
assert!(g.bary.iter().all(|[b1, b2]| (0.0..=1.0).contains(b1) && (0.0..=1.0).contains(b2)), "{m}: {:?}", g.bary);
let g = UvGBuffer::from_slices(&[[-m, 0.0], [m, 0.0], [0.0, 0.0125]], &[0, 1, 2], 8, 8, &Limits::default()).unwrap();
assert_eq!(g.covered_count(), 0, "{m}");
}
}
/// The `what`, `got` and `limit` of a `TooLarge` error, `None` for any other result.
fn too_large(r: Result<UvGBuffer>) -> Option<(&'static str, u64, u64)> {
match r {
Err(MeshOpsError::TooLarge { what, got, limit }) => Some((what, got, limit)),
_ => None,
}
}
#[test]
fn gbuffer_rejects_overlapping_box_work_before_rasterization() {
// Five triangles whose boxes each cover the whole 8 × 8 buffer: 320 texel visits.
let uvs = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]];
let indices = [0, 1, 2].repeat(5);
let l = Limits::default();
let four = Limits { max_gbuffer_work: 4 * 64, ..l };
assert_eq!(too_large(UvGBuffer::from_slices(&uvs, &indices, 8, 8, &four)), Some(("G-buffer work", 320, 256)));
let five = Limits { max_gbuffer_work: 5 * 64, ..l };
assert_eq!(UvGBuffer::from_slices(&uvs, &indices, 8, 8, &five).unwrap(), UvGBuffer::from_slices(&uvs, &indices, 8, 8, &l).unwrap());
}
#[test]
fn gbuffer_rejects_excess_band_entries() {
// Three triangles that each reach the four bands of a 128-row buffer: 12 entries.
let uvs = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]];
let indices = [0, 1, 2].repeat(3);
let l = Limits::default();
let under = Limits { max_gbuffer_bin_entries: 11, ..l };
assert_eq!(too_large(UvGBuffer::from_slices(&uvs, &indices, 16, 128, &under)), Some(("G-buffer band entries", 12, 11)));
let exact = Limits { max_gbuffer_bin_entries: 12, ..l };
let g = UvGBuffer::from_slices(&uvs, &indices, 16, 128, &exact).unwrap();
assert_eq!(g, UvGBuffer::from_slices(&uvs, &indices, 16, 128, &l).unwrap());
// Every band draws the triangles in order: the last one keeps each texel.
let covered = g.covered_count();
assert!(covered > 16 * 128 / 3, "{covered}");
assert!(g.tri.iter().all(|t| *t == 2 || *t == NO_TRI));
assert_eq!(g.overlaps as usize, 2 * covered);
}
#[test]
fn gbuffer_mesh_constructor_respects_count_limits() {
let m = primitives::plane(1.0, 2);
let l = Limits::default();
let (v, t) = (m.vertex_count(), m.triangle_count());
let few_triangles = Limits { max_triangles: t - 1, ..l };
assert_eq!(too_large(UvGBuffer::try_new(&m, 0, 16, 16, &few_triangles)), Some(("triangle count", t as u64, t as u64 - 1)));
let few_vertices = Limits { max_vertices: v - 1, ..l };
assert_eq!(too_large(UvGBuffer::try_new(&m, 0, 16, 16, &few_vertices)), Some(("vertex count", v as u64, v as u64 - 1)));
let exact = Limits { max_vertices: v, max_triangles: t, ..l };
assert_eq!(UvGBuffer::try_new(&m, 0, 16, 16, &exact).unwrap(), UvGBuffer::new(&m, 0, 16, 16));
// Submeshes that list the same triangles again count every time they are visited.
let mut twice = m.clone();
twice.submeshes.push(twice.submeshes[0].clone());
assert_eq!(too_large(UvGBuffer::try_new(&twice, 0, 16, 16, &exact)), Some(("triangle count", t as u64 + 1, t as u64)));
}
#[test]
fn gbuffer_work_counts_clipped_boxes_and_skips_off_image() {
let uvs = [
// A 2 × 2 texel box.
[0.5, 0.5],
[0.75, 0.5],
[0.5, 0.75],
// Entirely past the right and bottom edges.
[2.0, 2.0],
[3.0, 2.0],
[2.0, 3.0],
// Infinite once scaled to texels.
[1e38, 0.0],
[-1e38, 0.0],
[0.0, 1e38],
// A triangle over the whole image whose box is clipped to its 64 texels.
[-1.0, -1.0],
[3.0, -1.0],
[-1.0, 3.0],
];
let indices: Vec<u32> = (0..12).collect();
let l = Limits::default();
let under = Limits { max_gbuffer_work: 67, ..l };
assert_eq!(too_large(UvGBuffer::from_slices(&uvs, &indices, 8, 8, &under)), Some(("G-buffer work", 68, 67)));
let exact = Limits { max_gbuffer_work: 68, ..l };
let g = UvGBuffer::from_slices(&uvs, &indices, 8, 8, &exact).unwrap();
assert_eq!(g, UvGBuffer::from_slices(&uvs, &indices, 8, 8, &l).unwrap());
// The small triangle covers 3 texels, which the large one draws over.
assert_eq!((g.covered_count(), g.overlaps), (64, 3));
}
/// Texel buffers of `2^28 × 2^28` (2^58 and 2^59 bytes) are past every 64-bit address space,
/// so their reservation fails, and a work or band-entry rejection shows that the budgets are
/// checked first.
#[cfg(target_pointer_width = "64")]
#[test]
fn gbuffer_budgets_are_checked_before_the_texels_are_reserved() {
let huge = Limits { max_gbuffer_side: u32::MAX, max_gbuffer_texels: u64::MAX, max_gbuffer_work: u64::MAX, ..Limits::default() };
let uvs = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]];
let m = primitives::plane(1.0, 2);
let side = 1 << 28;
let cases =
[(Limits { max_gbuffer_work: 0, ..huge }, "G-buffer work"), (Limits { max_gbuffer_bin_entries: 0, ..huge }, "G-buffer band entries")];
for (limits, what) in cases {
let slices = too_large(UvGBuffer::from_slices(&uvs, &[0, 1, 2], side, side, &limits));
assert_eq!(slices.map(|(w, _, l)| (w, l)), Some((what, 0)));
let mesh = too_large(UvGBuffer::try_new(&m, 0, side, side, &limits));
assert_eq!(mesh.map(|(w, _, l)| (w, l)), Some((what, 0)));
}
// A size whose texel arrays no allocation can hold is refused before the band lists are
// reserved, even with no triangles.
for (w, h) in [(u32::MAX, u32::MAX), (1 << 31, 1 << 30)] {
assert!(matches!(UvGBuffer::from_slices(&[], &[], w, h, &huge), Err(MeshOpsError::OutOfMemory("G-buffer"))), "{w} × {h}");
assert!(matches!(UvGBuffer::try_new(&m, 0, w, h, &huge), Err(MeshOpsError::OutOfMemory("G-buffer"))), "{w} × {h}");
}
}
}
+6 -178
View File
@@ -1,19 +1,11 @@
//! # craft-mesh-ops
//!
//! Operations on triangle meshes: area-weighted smooth normals, MikkTSpace tangents, welding,
//! automatic UV unwrapping, the UV-space [`UvGBuffer`] that maps texels to surface points,
//! built-in [`primitives`] with UVs, a [`Bvh`] for ray casts and box queries (feature `bvh`) and
//! the [`OrbitCamera`].
//!
//! The functions at the crate root take plain slices: positions and normals as `[f32; 3]`, UVs as
//! `[f32; 2]` in the glTF convention (origin top-left, v down), tangents as `[f32; 4]` with the
//! bitangent sign in `w`, and triangle indices as `u32`. They check the input against
//! [`Limits`] and reject a non-finite value or an index past the last vertex before any work.
//! The [`Mesh`] type holds the same arrays for callers that keep several materials together.
//! Triangle mesh operations: the [`Mesh`] type with normals and MikkTSpace tangents, built-in
//! [`primitives`] (material ball, sphere, cube, …), a [`Bvh`] for ray casts and box queries,
//! the UV-space [`UvGBuffer`] that maps texels to surface points, and the [`OrbitCamera`].
#![forbid(unsafe_code)]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#[cfg(feature = "bvh")]
pub mod bvh;
pub mod camera;
pub mod gbuffer;
@@ -21,180 +13,16 @@ pub mod mesh;
pub mod primitives;
pub mod unwrap;
#[cfg(feature = "bvh")]
pub use bvh::{Bvh, Hit};
pub use camera::{OrbitCamera, Ray};
pub use gbuffer::{NO_TRI, Surface, UvGBuffer, surface_at};
pub use glam;
pub use mesh::{MAX_TRIANGLES, Mesh, SubMesh};
pub use mesh::{BaseColor, MAX_TRIANGLES, Mesh, SubMesh};
use glam::Vec3;
/// Why an operation did not run.
#[derive(Debug, thiserror::Error, Clone, PartialEq)]
pub enum MeshOpsError {
/// The input is malformed: mismatched array lengths, an index out of range, a non-finite
/// value or an invalid parameter.
pub enum GeomError {
#[error("invalid mesh: {0}")]
Invalid(String),
/// A count is over its [`Limits`] field.
#[error("{what} {got} is over the limit of {limit}")]
TooLarge { what: &'static str, got: u64, limit: u64 },
/// Memory for the result could not be reserved.
#[error("out of memory for {0}")]
OutOfMemory(&'static str),
}
pub type Result<T> = std::result::Result<T, MeshOpsError>;
/// Caps on the work one call does. Every slice function and `try_` constructor checks its input
/// against these before allocating. A UV G-buffer has three budgets: the texels it outputs, the
/// texels its rasterizer visits and the entries of its per-band triangle lists. The defaults
/// follow `craft-mesh` for whole meshes and are this crate's own values for the rest.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Limits {
/// Vertices in one input or output mesh. Default 20,000,000.
pub max_vertices: usize,
/// Triangles in one input or output mesh. Default 20,000,000.
pub max_triangles: usize,
/// Segments, rings or subdivisions along one direction of a primitive. Default 2,048.
pub max_segments: usize,
/// Width or height of a UV G-buffer. Default 8,192.
pub max_gbuffer_side: u32,
/// Texels in a UV G-buffer. Default 2^26 (8,192 × 8,192).
pub max_gbuffer_texels: u64,
/// Texels a UV G-buffer's rasterizer visits: the sum over its triangles of the texels in
/// each one's bounding box clipped to the buffer, covered or not. Default 2^32.
pub max_gbuffer_work: u64,
/// Entries in a UV G-buffer's per-band triangle lists: one per band of 32 rows that a
/// triangle's clipped bounding box reaches. Default 2^26; a value over `usize::MAX` counts
/// as `usize::MAX`.
pub max_gbuffer_bin_entries: u64,
/// Triangles one UV unwrap processes. Default 4,000,000.
pub max_unwrap_triangles: usize,
}
impl Default for Limits {
fn default() -> Self {
Limits {
max_vertices: 20_000_000,
max_triangles: 20_000_000,
max_segments: 2_048,
max_gbuffer_side: 8_192,
max_gbuffer_texels: 1 << 26,
max_gbuffer_work: 1 << 32,
max_gbuffer_bin_entries: 1 << 26,
max_unwrap_triangles: 4_000_000,
}
}
}
/// `Err(TooLarge)` when `got` is over `limit`.
pub(crate) fn check_limit(what: &'static str, got: usize, limit: usize) -> Result<()> {
if got > limit { Err(MeshOpsError::TooLarge { what, got: got as u64, limit: limit as u64 }) } else { Ok(()) }
}
/// An empty vector with room for `len` elements, or `OutOfMemory`.
pub(crate) fn try_vec<T>(len: usize, what: &'static str) -> Result<Vec<T>> {
let mut v = Vec::new();
v.try_reserve_exact(len).map_err(|_| MeshOpsError::OutOfMemory(what))?;
Ok(v)
}
/// `len` copies of `value`, or `OutOfMemory`.
pub(crate) fn try_filled<T: Clone>(len: usize, value: T, what: &'static str) -> Result<Vec<T>> {
let mut v = try_vec(len, what)?;
v.resize(len, value);
Ok(v)
}
/// `OutOfMemory` for `what` in place of a failed reservation.
pub(crate) fn reserved(r: std::result::Result<(), std::collections::TryReserveError>, what: &'static str) -> Result<()> {
r.map_err(|_| MeshOpsError::OutOfMemory(what))
}
/// The result of [`unwrap_uvs`]: vertices are split where charts meet, so the output has its own
/// vertex list.
#[derive(Clone, Debug, PartialEq)]
pub struct Unwrapped {
/// The input vertex each output vertex copies.
pub source: Vec<u32>,
/// One UV per output vertex, in 0..1.
pub uvs: Vec<[f32; 2]>,
/// Triangles over the output vertices, in the input's triangle order.
pub indices: Vec<u32>,
/// Number of charts.
pub charts: usize,
}
/// Axis-aligned bounds of `positions`, or `None` when there are none. A non-finite coordinate is
/// an error.
pub fn bounds(positions: &[[f32; 3]]) -> Result<Option<([f32; 3], [f32; 3])>> {
let mut found: Option<(Vec3, Vec3)> = None;
for p in positions {
let p = Vec3::from_array(*p);
if !p.is_finite() {
return Err(MeshOpsError::Invalid("non-finite position".into()));
}
found = Some(found.map_or((p, p), |(lo, hi)| (lo.min(p), hi.max(p))));
}
Ok(found.map(|(lo, hi)| (lo.to_array(), hi.to_array())))
}
/// Area-weighted smooth normals, one per vertex. A vertex no triangle uses gets +Y.
pub fn smooth_normals(positions: &[[f32; 3]], indices: &[u32], limits: &Limits) -> Result<Vec<[f32; 3]>> {
let mut mesh = Mesh::from_slices(positions, None, None, indices, limits)?;
mesh.try_compute_normals()?;
let mut out = try_vec(mesh.normals.len(), "normals")?;
out.extend(mesh.normals.iter().map(|n| n.to_array()));
Ok(out)
}
/// MikkTSpace tangents, one per vertex: xyz tangent and the bitangent sign in `w`, so that
/// `cross(normal, tangent) * w` points up the image (glTF 2.0). Meshes MikkTSpace cannot handle
/// (every triangle degenerate, no UV area, more than [`mesh::MAX_MIKKTSPACE_VALENCE`] triangles
/// around one vertex, corners at one position whose welding would take more than
/// [`mesh::MAX_MIKKTSPACE_WELD_WORK`] comparisons) get per-vertex tangents instead, with `w` set
/// the same way. The normals are unit vectors, as glTF
/// 2.0 stores them: each tangent is made perpendicular to its normal with a projection that is
/// exact only at unit length.
///
/// A vertex whose triangles need different tangent frames (UVs mirrored across it) cannot have
/// one tangent: that is an `Invalid` error naming the vertex. [`Mesh::compute_tangents`] splits
/// such vertices instead.
pub fn tangents(positions: &[[f32; 3]], normals: &[[f32; 3]], uvs: &[[f32; 2]], indices: &[u32], limits: &Limits) -> Result<Vec<[f32; 4]>> {
let mut mesh = Mesh::from_slices(positions, Some(normals), Some(uvs), indices, limits)?;
mesh.try_compute_tangents_splitting(mesh::Split::Refuse)?;
let mut out = try_vec(mesh.tangents.len(), "tangents")?;
out.extend(mesh.tangents.iter().map(|t| t.to_array()));
Ok(out)
}
/// Welded vertex id per vertex, as [`unwrap::weld_ids`] gives it, for finite positions.
pub fn weld(positions: &[[f32; 3]], limits: &Limits) -> Result<Vec<u32>> {
check_limit("vertex count", positions.len(), limits.max_vertices)?;
let mut p = try_vec(positions.len(), "positions")?;
for q in positions {
let q = Vec3::from_array(*q);
if !q.is_finite() {
return Err(MeshOpsError::Invalid("non-finite position".into()));
}
p.push(q);
}
unwrap::weld_ids(&p)
}
/// An automatic non-overlapping UV layout for one material, as [`unwrap::auto_unwrap`] makes it.
/// The vertex limit applies to the input and to the output, which has more vertices where
/// charts meet. A padding that is not finite is an error; one under 1 texel counts as 1.
pub fn unwrap_uvs(positions: &[[f32; 3]], indices: &[u32], padding_texels: f32, resolution: u32, limits: &Limits) -> Result<Unwrapped> {
if !padding_texels.is_finite() {
return Err(MeshOpsError::Invalid(format!("padding {padding_texels} is not finite")));
}
check_limit("triangle count", indices.len() / 3, limits.max_unwrap_triangles)?;
let mut mesh = Mesh::from_slices(positions, None, None, indices, limits)?;
let (charts, source) = unwrap::unwrap_core(&mut mesh, padding_texels, resolution, limits)?;
let mut uvs = try_vec(mesh.uvs.len(), "UVs")?;
uvs.extend(mesh.uvs.iter().map(|uv| uv.to_array()));
Ok(Unwrapped { source, uvs, indices: mesh.indices, charts })
}
pub type Result<T> = std::result::Result<T, GeomError>;
+228 -2018
View File
File diff suppressed because it is too large. Load diff
+39 -346
View File
@@ -1,17 +1,11 @@
//! Built-in meshes with clean, non-overlapping UVs: material ball, sphere, (rounded) cube,
//! cylinder, torus and plane. Y is up; triangles are counter-clockwise seen from outside.
//!
//! Each `try_` builder checks its sizes (finite and positive) and its segment counts against
//! [`Limits`] and returns an error instead of building. A size so large that a coordinate
//! overflows `f32` is an error too. The builders without `try_` clamp the segment counts to the
//! default [`Limits::max_segments`] and return an empty mesh for an invalid size.
use std::f32::consts::{PI, TAU};
use glam::{DVec2, Vec2, Vec3};
use glam::{Vec2, Vec3};
use crate::mesh::{Mesh, Split, SubMesh, unit};
use crate::{Limits, MeshOpsError, Result};
use crate::mesh::{Mesh, SubMesh};
/// A UV-space rectangle: origin and size.
#[derive(Clone, Copy, Debug)]
@@ -38,42 +32,9 @@ struct Builder {
idx: Vec<u32>,
/// Per triangle: its [`Mesh::diagonals`] bits.
diag: Vec<u8>,
limits: Limits,
/// Set when a part would pass the limits; later parts are skipped.
error: Option<MeshOpsError>,
}
impl Builder {
fn new(limits: &Limits) -> Builder {
Builder { limits: *limits, ..Builder::default() }
}
/// Whether `vertices` and `triangles` more fit the limits and `u32` indices, with the memory
/// for them reserved; records the error when they do not.
fn room(&mut self, vertices: Option<usize>, triangles: Option<usize>) -> bool {
if self.error.is_some() {
return false;
}
let total_vertices = vertices.and_then(|v| v.checked_add(self.p.len())).unwrap_or(usize::MAX);
let total_triangles = triangles.and_then(|t| t.checked_add(self.idx.len() / 3)).unwrap_or(usize::MAX);
let error = if total_vertices > self.limits.max_vertices || u32::try_from(total_vertices).is_err() {
Some(MeshOpsError::TooLarge { what: "vertex count", got: total_vertices as u64, limit: self.limits.max_vertices as u64 })
} else if total_triangles > self.limits.max_triangles || total_triangles.checked_mul(3).and_then(|i| u32::try_from(i).ok()).is_none() {
Some(MeshOpsError::TooLarge { what: "triangle count", got: total_triangles as u64, limit: self.limits.max_triangles as u64 })
} else {
// Both counts fit the limits, so they and three times the triangles are finite.
let (v, t) = (vertices.unwrap_or(0), triangles.unwrap_or(0));
let reserved = self.p.try_reserve(v).is_ok()
&& self.n.try_reserve(v).is_ok()
&& self.uv.try_reserve(v).is_ok()
&& self.idx.try_reserve(t * 3).is_ok()
&& self.diag.try_reserve(t).is_ok();
(!reserved).then_some(MeshOpsError::OutOfMemory("primitive"))
};
self.error = error;
self.error.is_none()
}
fn vert(&mut self, p: Vec3, n: Vec3, uv: Vec2) -> u32 {
self.p.push(p);
self.n.push(n.try_normalize().unwrap_or(Vec3::Y));
@@ -83,10 +44,6 @@ impl Builder {
/// A grid of (rows+1)×(cols+1) vertices from `f(row, col)`, rows going "down" the texture.
fn grid(&mut self, rows: usize, cols: usize, mut f: impl FnMut(usize, usize) -> (Vec3, Vec3, Vec2)) {
let vertices = rows.checked_add(1).zip(cols.checked_add(1)).and_then(|(r, c)| r.checked_mul(c));
if !self.room(vertices, rows.checked_mul(cols).and_then(|q| q.checked_mul(2))) {
return;
}
let base = self.p.len() as u32;
for i in 0..=rows {
for j in 0..=cols {
@@ -106,26 +63,17 @@ impl Builder {
}
}
/// The mesh of one material, with tangents. Computing them can split vertices; a copy that
/// would take the vertex count over the limit is `TooLarge` before it is made.
fn finish(self, material: &str) -> Result<Mesh> {
let max_vertices = self.limits.max_vertices;
let mut m = self.into_mesh(material)?;
m.try_compute_tangents_splitting(Split::UpTo(max_vertices))?;
Ok(m)
/// The mesh of one material, with tangents.
fn finish(self, material: &str) -> Mesh {
let mut m = self.into_mesh(material);
m.compute_tangents();
m
}
/// The mesh of one material, without tangents.
fn into_mesh(self, material: &str) -> Result<Mesh> {
if let Some(e) = self.error {
return Err(e);
}
// A finite size near f32::MAX can overflow where the builders add or scale coordinates.
if !(self.p.iter().all(|p| p.is_finite()) && self.n.iter().all(|n| n.is_finite()) && self.uv.iter().all(|uv| uv.is_finite())) {
return Err(MeshOpsError::Invalid("the primitive's coordinates overflow f32".into()));
}
fn into_mesh(self, material: &str) -> Mesh {
let count = self.idx.len() as u32;
Ok(Mesh {
Mesh {
positions: self.p,
normals: self.n,
uvs: self.uv,
@@ -135,49 +83,14 @@ impl Builder {
submeshes: vec![SubMesh { name: material.into(), material: 0, start: 0, count }],
materials: vec![material.into()],
diagonals: self.diag,
})
}
}
}
/// A mesh of one material with no vertices: what the builders without `try_` return for an
/// invalid size.
fn empty(material: &str) -> Mesh {
Mesh { submeshes: vec![SubMesh { name: material.into(), material: 0, start: 0, count: 0 }], materials: vec![material.into()], ..Mesh::default() }
}
/// `value` when it is finite and greater than zero.
fn positive(what: &str, value: f32) -> Result<f32> {
if value.is_finite() && value > 0.0 { Ok(value) } else { Err(MeshOpsError::Invalid(format!("{what} {value} is not a finite positive number"))) }
}
/// `count`, raised to `min`, when the raised count is within the segment limit.
fn segments(what: &'static str, count: usize, min: usize, limits: &Limits) -> Result<usize> {
let count = count.max(min);
crate::check_limit(what, count, limits.max_segments)?;
Ok(count)
}
/// Segments along one axis of a box face: in each of the two bevels, and between them.
fn box_segments(bevel: f32) -> (usize, usize) {
if bevel > 0.0 { (6, 10) } else { (0, 12) }
}
/// A segment count clamped to the default limit, for the builders without `try_`.
fn clamped(count: usize) -> usize {
count.min(Limits::default().max_segments)
}
/// UV sphere of `radius` around the origin.
/// UV sphere of `radius` centred at `center`.
pub fn sphere(radius: f32, segments: usize, rings: usize) -> Mesh {
try_sphere(radius, clamped(segments), clamped(rings), &Limits::default()).unwrap_or_else(|_| empty("Sphere"))
}
/// [`sphere`] with its parameters checked.
pub fn try_sphere(radius: f32, segs: usize, rings: usize, limits: &Limits) -> Result<Mesh> {
let radius = positive("sphere radius", radius)?;
let (segs, rings) = (segments("sphere segments", segs, 3, limits)?, segments("sphere rings", rings, 2, limits)?);
let mut b = Builder::new(limits);
sphere_into(&mut b, Vec3::ZERO, radius, segs, rings, UvRect::FULL);
let mut b = Builder::default();
sphere_into(&mut b, Vec3::ZERO, radius, segments.max(3), rings.max(2), UvRect::FULL);
b.finish("Sphere")
}
@@ -193,39 +106,19 @@ fn sphere_into(b: &mut Builder, center: Vec3, radius: f32, segs: usize, rings: u
/// A box with rounded edges (`bevel` = edge radius; 0 gives a plain cube). Faces are laid out
/// in a 3×2 UV atlas.
pub fn rounded_box(half: Vec3, bevel: f32) -> Mesh {
try_rounded_box(half, bevel, &Limits::default()).unwrap_or_else(|_| empty("Box"))
}
/// [`rounded_box`] with its parameters checked: every half size finite and positive, the bevel
/// finite (it is clamped to 0..0.95 of the smallest half size). A face has 12 segments along
/// each axis, or 22 with a bevel, which [`Limits::max_segments`] has to allow.
pub fn try_rounded_box(half: Vec3, bevel: f32, limits: &Limits) -> Result<Mesh> {
for v in half.to_array() {
positive("box half size", v)?;
}
if !bevel.is_finite() {
return Err(MeshOpsError::Invalid(format!("box bevel {bevel} is not finite")));
}
let (in_bevel, between) = box_segments(bevel);
crate::check_limit("box segments", 2 * in_bevel + between, limits.max_segments)?;
let mut b = Builder::new(limits);
let mut b = Builder::default();
rounded_box_into(&mut b, Vec3::ZERO, half, bevel, UvRect::FULL);
b.finish("Box")
}
/// The cube primitive (sharp edges).
pub fn cube(size: f32) -> Mesh {
try_cube(size, &Limits::default()).unwrap_or_else(|_| empty("Cube"))
}
/// [`cube`] with its size checked.
pub fn try_cube(size: f32, limits: &Limits) -> Result<Mesh> {
let mut m = try_rounded_box(Vec3::splat(positive("cube size", size)? * 0.5), 0.0, limits)?;
let mut m = rounded_box(Vec3::splat(size * 0.5), 0.0);
m.materials = vec!["Cube".into()];
if let Some(s) = m.submeshes.first_mut() {
s.name = "Cube".into();
}
Ok(m)
m
}
fn rounded_box_into(b: &mut Builder, center: Vec3, half: Vec3, bevel: f32, r: UvRect) {
@@ -239,7 +132,7 @@ fn rounded_box_into(b: &mut Builder, center: Vec3, half: Vec3, bevel: f32, r: Uv
(Vec3::Y, Vec3::X, Vec3::Z),
(-Vec3::Y, Vec3::X, -Vec3::Z),
];
let (kb, kc) = box_segments(bevel);
let (kb, kc) = if bevel > 0.0 { (6usize, 10usize) } else { (0, 12) };
// Coordinates along one face axis from -h to h, dense in the bevels.
let coords = |h: f32| -> Vec<f32> {
let inner = h - bevel;
@@ -265,9 +158,7 @@ fn rounded_box_into(b: &mut Builder, center: Vec3, half: Vec3, bevel: f32, r: Uv
let (a, c) = (cu[j], cv[i]);
let q = *n * hn + *u * a + *v * c;
let clamped = q.clamp(-inner, inner);
// `unit` gives the same direction where the squared offset overflows, so faces that
// share a bevel edge place its vertices at the same positions.
let dir = unit(q - clamped).unwrap_or(*n);
let dir = (q - clamped).try_normalize().unwrap_or(*n);
let p = if bevel > 0.0 { clamped + dir * bevel } else { q };
let nn = if bevel > 0.0 { dir } else { *n };
(center + p, nn, cell.map((a + hu) / (2.0 * hu), (c + hv) / (2.0 * hv)))
@@ -281,30 +172,26 @@ fn lathe_into(b: &mut Builder, center: Vec3, profile: &[(f32, f32)], segs: usize
if profile.len() < 2 {
return;
}
// Arc lengths and profile directions in `f64`, where the steps between finite `f32` points
// and their squares neither overflow nor round to zero, whatever the radius and height.
let point = |(r, y): (f32, f32)| DVec2::new(f64::from(r), f64::from(y));
let mut len = vec![0.0f64];
let mut len = vec![0.0f32];
for w in profile.windows(2) {
let d = (point(w[1]) - point(w[0])).length();
let d = Vec2::new(w[1].0 - w[0].0, w[1].1 - w[0].1).length();
len.push(len.last().copied().unwrap_or(0.0) + d);
}
// A profile of zero length maps every row to the top of `r`.
let total = len.last().copied().filter(|t| *t > 0.0 && t.is_finite()).unwrap_or(1.0);
let total = len.last().copied().unwrap_or(1.0).max(1e-6);
let rows = profile.len() - 1;
b.grid(rows, segs, |i, j| {
let (rad, y) = profile[i];
// Profile tangent (downwards) → outward normal in the (r, y) plane.
let prev = profile[i.saturating_sub(1)];
let next = profile[(i + 1).min(rows)];
let t = (point(next) - point(prev)).try_normalize().map_or(Vec2::NEG_Y, |t| t.as_vec2());
let t = Vec2::new(next.0 - prev.0, next.1 - prev.1).try_normalize().unwrap_or(Vec2::NEG_Y);
let n2 = Vec2::new(-t.y, t.x);
let u = j as f32 / segs as f32;
let phi = u * TAU + PI * 1.5;
let dir = Vec3::new(phi.cos(), 0.0, -phi.sin());
let p = center + dir * rad + Vec3::Y * y;
let n = dir * n2.x + Vec3::Y * n2.y;
(p, n, r.map(u, (len[i] / total) as f32))
(p, n, r.map(u, len[i] / total))
});
}
@@ -349,7 +236,7 @@ pub fn preview_orb() -> Mesh {
profile.push((0.0, -BASE_HALF_HEIGHT));
lathe_into(&mut b, Vec3::Y * BASE_Y, &profile, BASE_SEGMENTS, BASE_UV);
let Ok(mut m) = b.into_mesh("Preview") else { return empty("Preview") };
let mut m = b.into_mesh("Preview");
// Normals from the triangles: the panel walls are too steep for the sphere's directions
m.compute_normals();
// Body and base both run U around the vertical axis, so the tangent is that direction (a
@@ -366,7 +253,7 @@ pub fn preview_orb() -> Mesh {
m
}
/// Distance from the center of the [`preview_orb`] body along unit direction `d`.
/// Distance from the centre of the [`preview_orb`] body along unit direction `d`.
fn preview_orb_radius(d: Vec3) -> f32 {
// Rim blends: the sharp faces, and the softly blended left face
const SHARP_BLEND: f32 = 0.035;
@@ -375,7 +262,7 @@ fn preview_orb_radius(d: Vec3) -> f32 {
const PANEL_DEPTH: f32 = 0.11;
const PANEL_BULGE: f32 = 0.04;
const LEFT_PANEL_SCALE: f32 = 0.9;
// Slot around the middle: center height, half-width, edge rounding, depth; it fades out over
// Slot around the middle: centre height, half-width, edge rounding, depth; it fades out over
// this fraction of the left panel's rim
const SLOT_Y: f32 = -0.03;
const SLOT_HALF_WIDTH: f32 = 0.05;
@@ -437,9 +324,6 @@ fn preview_orb_radius(d: Vec3) -> f32 {
/// A flat disk facing up (+Y) or down, with planar UVs inside `r`.
fn disk_into(b: &mut Builder, center: Vec3, radius: f32, up: bool, segs: usize, r: UvRect) {
if !b.room(segs.checked_add(1), Some(segs)) {
return;
}
let n = if up { Vec3::Y } else { Vec3::NEG_Y };
let c = b.vert(center, n, r.map(0.5, 0.5));
let first = b.p.len() as u32;
@@ -463,31 +347,18 @@ fn disk_into(b: &mut Builder, center: Vec3, radius: f32, up: bool, segs: usize,
/// A capped cylinder along Y.
pub fn cylinder(radius: f32, height: f32, segs: usize) -> Mesh {
try_cylinder(radius, height, clamped(segs), &Limits::default()).unwrap_or_else(|_| empty("Cylinder"))
}
/// [`cylinder`] with its parameters checked.
pub fn try_cylinder(radius: f32, height: f32, segs: usize, limits: &Limits) -> Result<Mesh> {
let (radius, height) = (positive("cylinder radius", radius)?, positive("cylinder height", height)?);
let segs = segments("cylinder segments", segs, 3, limits)?;
let mut b = Builder::new(limits);
let mut b = Builder::default();
let h = height * 0.5;
lathe_into(&mut b, Vec3::ZERO, &[(radius, h), (radius, -h)], segs, UvRect { o: Vec2::ZERO, s: Vec2::new(1.0, 0.5) }.inset(0.01));
disk_into(&mut b, Vec3::Y * h, radius, true, segs, UvRect { o: Vec2::new(0.0, 0.5), s: Vec2::splat(0.5) }.inset(0.01));
disk_into(&mut b, -Vec3::Y * h, radius, false, segs, UvRect { o: Vec2::new(0.5, 0.5), s: Vec2::splat(0.5) }.inset(0.01));
lathe_into(&mut b, Vec3::ZERO, &[(radius, h), (radius, -h)], segs.max(3), UvRect { o: Vec2::ZERO, s: Vec2::new(1.0, 0.5) }.inset(0.01));
disk_into(&mut b, Vec3::Y * h, radius, true, segs.max(3), UvRect { o: Vec2::new(0.0, 0.5), s: Vec2::splat(0.5) }.inset(0.01));
disk_into(&mut b, -Vec3::Y * h, radius, false, segs.max(3), UvRect { o: Vec2::new(0.5, 0.5), s: Vec2::splat(0.5) }.inset(0.01));
b.finish("Cylinder")
}
/// A torus around Y.
pub fn torus(major: f32, minor: f32, segs: usize, sides: usize) -> Mesh {
try_torus(major, minor, clamped(segs), clamped(sides), &Limits::default()).unwrap_or_else(|_| empty("Torus"))
}
/// [`torus`] with its parameters checked.
pub fn try_torus(major: f32, minor: f32, segs: usize, sides: usize, limits: &Limits) -> Result<Mesh> {
let (major, minor) = (positive("torus major radius", major)?, positive("torus minor radius", minor)?);
let (segs, sides) = (segments("torus segments", segs, 3, limits)?, segments("torus sides", sides, 3, limits)?);
let mut b = Builder::new(limits);
let mut b = Builder::default();
let (segs, sides) = (segs.max(3), sides.max(3));
b.grid(sides, segs, |i, j| {
let (u, v) = (j as f32 / segs as f32, i as f32 / sides as f32);
let phi = u * TAU + PI * 1.5;
@@ -501,14 +372,8 @@ pub fn try_torus(major: f32, minor: f32, segs: usize, sides: usize, limits: &Lim
/// A subdivided plane facing +Y.
pub fn plane(size: f32, subdivisions: usize) -> Mesh {
try_plane(size, clamped(subdivisions), &Limits::default()).unwrap_or_else(|_| empty("Plane"))
}
/// [`plane`] with its parameters checked.
pub fn try_plane(size: f32, subdivisions: usize, limits: &Limits) -> Result<Mesh> {
let size = positive("plane size", size)?;
let s = segments("plane subdivisions", subdivisions, 1, limits)?;
let mut b = Builder::new(limits);
let mut b = Builder::default();
let s = subdivisions.max(1);
b.grid(s, s, |i, j| {
let (u, v) = (j as f32 / s as f32, i as f32 / s as f32);
(Vec3::new((u - 0.5) * size, 0.0, (v - 0.5) * size), Vec3::Y, Vec2::new(u, v))
@@ -543,7 +408,7 @@ pub fn udim_plane() -> Mesh {
pub fn material_ball() -> Mesh {
let mut ball = Builder::default();
sphere_into(&mut ball, Vec3::new(0.0, 1.32, 0.0), 1.0, 128, 64, UvRect::FULL);
let Ok(mut ball) = ball.finish("Ball") else { return empty("Ball") };
let mut ball = ball.finish("Ball");
let mut base = Builder::default();
let (r, top, bot, bev) = (1.05f32, 0.32f32, 0.0f32, 0.07f32);
@@ -566,7 +431,7 @@ pub fn material_ball() -> Mesh {
lathe_into(&mut base, Vec3::ZERO, &profile, 128, UvRect { o: Vec2::ZERO, s: Vec2::new(1.0, 0.5) }.inset(0.01));
disk_into(&mut base, Vec3::new(0.0, top + 0.06, 0.0), 0.42, true, 128, UvRect { o: Vec2::new(0.0, 0.5), s: Vec2::splat(0.5) }.inset(0.01));
disk_into(&mut base, Vec3::new(0.0, bot, 0.0), r - bev, false, 128, UvRect { o: Vec2::new(0.5, 0.5), s: Vec2::splat(0.5) }.inset(0.01));
let Ok(base) = base.finish("Base") else { return ball };
let base = base.finish("Base");
ball.append(&base);
ball
}
@@ -576,12 +441,10 @@ pub fn material_ball() -> Mesh {
pub fn crate_scene() -> Mesh {
let mut body = Builder::default();
rounded_box_into(&mut body, Vec3::new(0.0, 0.8, 0.0), Vec3::new(1.2, 0.8, 0.8), 0.12, UvRect::FULL);
let Ok(mut m) = body.finish("Crate") else { return empty("Crate") };
let mut m = body.finish("Crate");
let mut lid = Builder::default();
rounded_box_into(&mut lid, Vec3::new(0.0, 1.72, 0.0), Vec3::new(1.28, 0.12, 0.88), 0.08, UvRect::FULL);
if let Ok(lid) = lid.finish("Lid") {
m.append(&lid);
}
m.append(&lid.finish("Lid"));
let mut handle = torus(0.32, 0.07, 64, 24);
for p in &mut handle.positions {
*p = Vec3::new(p.x, p.z, -p.y) + Vec3::new(0.0, 1.84, 0.0);
@@ -665,7 +528,7 @@ mod tests {
check(&m, if id == "udim_plane" { 2.0 } else { 1.0 });
}
assert!(builtin("nope").is_none());
assert_eq!(udim_plane().uv_tiles(0, &Limits::default()).unwrap().into_iter().collect::<Vec<_>>(), vec![(0, 0), (1, 0)]);
assert_eq!(udim_plane().uv_tiles(0).into_iter().collect::<Vec<_>>(), vec![(0, 0), (1, 0)]);
}
#[test]
@@ -690,174 +553,4 @@ mod tests {
assert_eq!(m.materials, vec!["Ball".to_string(), "Base".to_string()]);
assert!(m.triangles_of(0).count() > 0 && m.triangles_of(1).count() > 0);
}
#[test]
fn primitives_reject_non_finite_parameters() {
let l = Limits::default();
for bad in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
assert!(try_sphere(bad, 16, 8, &l).is_err(), "sphere {bad}");
assert!(try_rounded_box(Vec3::new(1.0, bad, 1.0), 0.1, &l).is_err(), "box {bad}");
assert!(try_rounded_box(Vec3::ONE, bad, &l).is_err(), "bevel {bad}");
assert!(try_cube(bad, &l).is_err(), "cube {bad}");
assert!(try_cylinder(bad, 1.0, 16, &l).is_err() && try_cylinder(1.0, bad, 16, &l).is_err(), "cylinder {bad}");
assert!(try_torus(bad, 0.3, 16, 8, &l).is_err() && try_torus(1.0, bad, 16, 8, &l).is_err(), "torus {bad}");
assert!(try_plane(bad, 4, &l).is_err(), "plane {bad}");
for m in [sphere(bad, 16, 8), cube(bad), cylinder(1.0, bad, 16), torus(bad, 0.3, 16, 8), plane(bad, 4)] {
assert_eq!(m.triangle_count(), 0);
m.validate().unwrap();
}
}
}
#[test]
fn box_rejects_negative_nan_and_zero_half_size() {
let l = Limits::default();
for half in [Vec3::new(-1.0, 1.0, 1.0), Vec3::new(1.0, 1.0, f32::NAN), Vec3::ZERO, Vec3::new(1.0, 0.0, 1.0)] {
assert!(try_rounded_box(half, 0.0, &l).is_err(), "{half}");
assert!(try_rounded_box(half, 0.2, &l).is_err(), "{half}");
let m = rounded_box(half, 0.2);
assert_eq!(m.triangle_count(), 0, "{half}");
}
for size in [-2.0, 0.0] {
assert!(try_cube(size, &l).is_err(), "{size}");
assert!(cube(size).uvs.iter().all(|uv| uv.is_finite()));
}
// A negative bevel is clamped to none, as before.
assert_eq!(try_rounded_box(Vec3::ONE, -1.0, &l).unwrap(), try_rounded_box(Vec3::ONE, 0.0, &l).unwrap());
}
#[test]
fn primitives_reject_sizes_that_overflow() {
let l = Limits::default();
// The torus's two radii and the box's doubled half size pass f32::MAX.
assert!(try_torus(3e38, 3e38, 16, 8, &l).is_err());
assert!(try_rounded_box(Vec3::splat(3e38), 0.0, &l).is_err());
assert_eq!(torus(3e38, 3e38, 16, 8).triangle_count(), 0);
// The cylinder's profile length is measured on the divided profile, so a height whose
// length alone would pass f32::MAX builds.
let tall = try_cylinder(1.0, 3e38, 16, &l).unwrap();
tall.validate().unwrap();
assert!(tall.uvs.iter().all(|uv| (0.0..=1.0).contains(&uv.x) && (0.0..=1.0).contains(&uv.y)));
// Large sizes that stay finite build.
let large = [
try_sphere(1e30, 16, 8, &l).unwrap(),
try_cylinder(1e18, 1e18, 16, &l).unwrap(),
try_cube(1e30, &l).unwrap(),
try_torus(1e30, 1e29, 16, 8, &l).unwrap(),
try_plane(1e30, 4, &l).unwrap(),
];
for m in large {
assert!(m.triangle_count() > 0);
m.validate().unwrap();
}
}
#[test]
fn a_scaled_primitive_is_the_unit_primitive_scaled() {
let l = Limits::default();
let close = |a: &Mesh, b: &Mesh, scale: f32| {
assert_eq!(a.positions.len(), b.positions.len());
for (i, (p, q)) in a.positions.iter().zip(&b.positions).enumerate() {
assert!((*p / scale - *q).length() < 1e-5, "position {i}: {} vs {q}", *p / scale);
}
for (i, (u, v)) in a.uvs.iter().zip(&b.uvs).enumerate() {
assert!((*u - *v).length() < 1e-5, "UV {i}: {u} vs {v}");
}
};
// Squared bevel offsets overflow at this size: adjacent faces still meet.
close(&try_rounded_box(Vec3::splat(1e30), 1e29, &l).unwrap(), &try_rounded_box(Vec3::ONE, 0.1, &l).unwrap(), 1e30);
// A profile far shorter than 1e-6 keeps its share of the UV height.
close(&try_cylinder(1e-8, 1e-8, 16, &l).unwrap(), &try_cylinder(1.0, 1.0, 16, &l).unwrap(), 1e-8);
close(&try_cylinder(1e-30, 2e-30, 16, &l).unwrap(), &try_cylinder(1.0, 2.0, 16, &l).unwrap(), 1e-30);
}
#[test]
fn primitives_reject_oversized_segment_counts() {
let l = Limits::default();
assert!(try_sphere(1.0, l.max_segments + 1, 8, &l).is_err());
assert!(try_sphere(1.0, 8, usize::MAX, &l).is_err());
assert!(try_torus(1.0, 0.3, usize::MAX, 8, &l).is_err());
assert!(try_cylinder(1.0, 1.0, usize::MAX, &l).is_err());
assert!(try_plane(1.0, usize::MAX, &l).is_err());
// Within the segment limit, the vertex limit still applies.
let few = Limits { max_vertices: 100, ..l };
assert!(matches!(try_plane(1.0, 10, &few), Err(MeshOpsError::TooLarge { .. })));
assert!(try_plane(1.0, 8, &few).is_ok());
// A count under the builder's minimum is raised first, and the raised count is checked.
let two = Limits { max_segments: 2, ..l };
assert!(try_sphere(1.0, 1, 2, &two).is_err(), "a sphere has at least 3 segments");
assert!(try_plane(1.0, 0, &two).is_ok());
// A box face has 12 segments along each axis, or 22 with a bevel.
let eleven = Limits { max_segments: 11, ..l };
assert!(try_cube(1.0, &eleven).is_err());
let twelve = Limits { max_segments: 12, ..l };
assert!(try_cube(1.0, &twelve).is_ok());
assert!(try_rounded_box(Vec3::ONE, 0.1, &twelve).is_err());
// The builders without `try_` clamp to the limit.
assert_eq!(clamped(usize::MAX), l.max_segments);
assert_eq!(clamped(7), 7);
}
#[test]
fn vertex_copies_from_tangents_count_against_the_vertex_limit() {
// A quad whose second triangle has mirrored UVs: the two shared vertices get one frame
// per triangle, so the tangents copy them.
let quad = |max_vertices: usize| {
let mut b = Builder::new(&Limits { max_vertices, ..Limits::default() });
assert!(b.room(Some(4), Some(2)));
for (p, uv) in [(Vec3::ZERO, Vec2::ZERO), (Vec3::X, Vec2::X), (Vec3::Y, Vec2::Y), (Vec3::new(1.0, 1.0, 0.0), Vec2::ZERO)] {
b.vert(p, Vec3::Z, uv);
}
b.idx.extend_from_slice(&[0, 1, 2, 1, 3, 2]);
b.diag.extend_from_slice(&[0, 0]);
b.finish("Quad")
};
let m = quad(usize::MAX).unwrap();
let copies = m.positions.len() - 4;
assert!(copies > 0, "the mirrored triangle's corners get their own vertices");
// The error comes at the first copy past the limit, before any later copy is made.
assert!(matches!(quad(4), Err(MeshOpsError::TooLarge { what: "vertex count", got: 5, limit: 4 })));
let under = m.positions.len() - 1;
assert!(
matches!(quad(under), Err(MeshOpsError::TooLarge { what: "vertex count", got, limit }) if got == m.positions.len() as u64 && limit == under as u64)
);
assert_eq!(quad(m.positions.len()).unwrap().positions.len(), m.positions.len());
}
#[test]
fn primitives_count_the_vertices_tangents_split() {
type Build = fn(&Limits) -> Result<Mesh>;
// A torus whose minor radius is larger than its major radius folds through its axis.
let builds: [(&str, Build); 6] = [
("folded torus", |l| try_torus(0.5, 2.0, 16, 8, l)),
("torus", |l| try_torus(1.0, 0.3, 16, 8, l)),
("sphere", |l| try_sphere(1.0, 16, 8, l)),
("cylinder", |l| try_cylinder(1.0, 2.0, 16, l)),
("rounded box", |l| try_rounded_box(Vec3::ONE, 0.2, l)),
("plane", |l| try_plane(1.0, 4, l)),
];
let l = Limits::default();
for (name, build) in builds {
let full = build(&l).unwrap().vertex_count();
let under = Limits { max_vertices: full - 1, ..l };
match build(&under) {
Ok(m) => panic!("{name}: {} vertices with a limit of {}", m.vertex_count(), full - 1),
Err(e) => assert!(matches!(e, MeshOpsError::TooLarge { what: "vertex count", .. }), "{name}: {e:?}"),
}
assert_eq!(build(&Limits { max_vertices: full, ..l }).unwrap().vertex_count(), full, "{name}");
}
}
#[test]
fn lathe_uvs_span_the_rectangle_at_any_radius_and_height() {
// With the radius 1e30 times the height, the profile step divided by the radius squares to
// zero in f32.
for (radius, height) in [(1e30f32, 1.0f32), (1.0, 1e30), (1e-30, 1.0)] {
let m = try_cylinder(radius, height, 16, &Limits::default()).unwrap();
// The side is the first grid: 17 vertices on the top row, 17 on the bottom one.
let (top, bottom) = (&m.uvs[..17], &m.uvs[17..34]);
assert!(top.iter().all(|uv| (uv.y - 0.01).abs() < 1e-6), "{radius} {height}: {top:?}");
assert!(bottom.iter().all(|uv| (uv.y - 0.49).abs() < 1e-6), "{radius} {height}: {bottom:?}");
}
}
}
File diff suppressed because it is too large. Load diff