mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-28 14:18:32 -08:00
Merge pull request #1233 from dotCooCoo/feat/craft-mesh-ops
craft-mesh-ops: mesh operations, a BVH and primitives for the 3D apps
This commit is contained in:
17 files changed
+2782
No files matched your search
@@ -27,6 +27,7 @@ author, source and license. Library code and original assets are under the repos
|
||||
| `crates/text/assets/hyphen/en-us.pat` | DesignCraft contributors, trained from the Moby Hyphenator II list | `crates/text/examples/hyphgen.rs` | CC0-1.0 |
|
||||
| Patterns embedded through `hypher` (optional `craft-text` language features) | hyph-utf8 authors, per language | [tex-hyphen](https://github.com/hyphenation/tex-hyphen), as packaged in [hypher](https://github.com/typst/hypher/tree/main/patterns) | Per file header: LPPL, MIT, BSD-3-Clause, Unlicense or a permit-any-use notice (or a choice including one); Slovak (`hyph-sk.tex`, embedded whenever `hypher/slovak` is on: feature `slovak-gpl`, or another dependency through feature unification) is GPL-2.0-or-later; Spanish (`hyph-es.tex` 5.0, Javier Bezos, CervanTeX) is MIT |
|
||||
| Word-break dictionaries and LSTM models embedded through `icu_segmenter_data` (optional `craft-text` features `thai`, `lao`, `khmer`, `burmese`) | Unicode, Inc. and ICU4X contributors | [ICU4X](https://github.com/unicode-org/icu4x) | Unicode-3.0 |
|
||||
| MikkTSpace tangent generation compiled in through `mikktspace` (`craft-mesh-ops`) | Benjamin Wasty, David Harvey-Macaulay and Layl Bongers; translated from the C original by Morten S. Mikkelsen | [mikktspace 0.3.0](https://crates.io/crates/mikktspace/0.3.0), [gltf-rs/mikktspace](https://github.com/gltf-rs/mikktspace) | MIT OR Apache-2.0 (the package's `license` field); its `src/generated.rs` also carries the C original's 2011 notice, reproduced in [`crates/mesh-ops/ATTRIBUTION.md`](crates/mesh-ops/ATTRIBUTION.md) |
|
||||
| `crates/ui/tests/fonts/NotoSansArabic-test.ttf` (subset to the test strings, default weight set to 100, width axis dropped) | The Noto Project Authors | [google/fonts@7085eb8 `ofl/notosansarabic`](https://github.com/google/fonts/tree/7085eb89a950e85db5b166b7a58d414544b4140c/ofl/notosansarabic), via craft-fonts | OFL-1.1 (`licenses/ui-test-fonts/OFL-NotoSansArabic.txt`) |
|
||||
| `crates/ui/tests/fonts/NotoSansCJKsc-test.otf` (subset to the test strings) | The Noto Project Authors (Adobe, Google) | [notofonts/noto-cjk@f8d1575 `Sans/OTF/SimplifiedChinese`](https://github.com/notofonts/noto-cjk/tree/f8d157532fbfaeda587e826d4cd5b21a49186f7c/Sans/OTF/SimplifiedChinese), via craft-fonts | OFL-1.1 (`licenses/ui-test-fonts/OFL-NotoSansCJK.txt`) |
|
||||
| `crates/imaging/tests/fonts/NotoSansArabic-digits.ttf` (instance at weight 400 and width 100, subset to the Arabic-Indic digits and separators U+0660–U+066C) | The Noto Project Authors | [google/fonts@7085eb8 `ofl/notosansarabic`](https://github.com/google/fonts/tree/7085eb89a950e85db5b166b7a58d414544b4140c/ofl/notosansarabic), via craft-fonts | OFL-1.1 (`licenses/ui-test-fonts/OFL-NotoSansArabic.txt`) |
|
||||
|
||||
Generated
+30
@@ -1865,6 +1865,7 @@ dependencies = [
|
||||
"craft-media-source",
|
||||
"craft-menu",
|
||||
"craft-mesh",
|
||||
"craft-mesh-ops",
|
||||
"craft-metadata",
|
||||
"craft-metafile",
|
||||
"craft-midi",
|
||||
@@ -3445,6 +3446,17 @@ dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-mesh-ops"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"glam 0.30.10",
|
||||
"mikktspace",
|
||||
"rayon",
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-metadata"
|
||||
version = "0.1.0"
|
||||
@@ -6860,6 +6872,12 @@ dependencies = [
|
||||
"xml-rs",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "glam"
|
||||
version = "0.15.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3abb554f8ee44336b72d522e0a7fe86a29e09f839a36022fa869a7dfe941a54b"
|
||||
|
||||
[[package]]
|
||||
name = "glam"
|
||||
version = "0.25.0"
|
||||
@@ -6871,6 +6889,9 @@ name = "glam"
|
||||
version = "0.30.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "19fc433e8437a212d1b6f1e68c7824af3aed907da60afa994e7f542d18d12aa9"
|
||||
dependencies = [
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "glifo"
|
||||
@@ -8716,6 +8737,15 @@ version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c2a86d3146ed3995b5913c414f6664344b9617457320782e64f0bb44afd49d74"
|
||||
|
||||
[[package]]
|
||||
name = "mikktspace"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7d0b56b403871a8f992ca626d52cc0a690d4841baea8955dc4af6304ac62f8b0"
|
||||
dependencies = [
|
||||
"glam 0.15.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "mime"
|
||||
version = "0.3.17"
|
||||
|
||||
@@ -136,6 +136,7 @@ craft-gcode = { path = "crates/gcode" }
|
||||
craft-gif = { path = "crates/gif" }
|
||||
craft-hdr = { path = "crates/hdr" }
|
||||
craft-mesh = { path = "crates/mesh" }
|
||||
craft-mesh-ops = { path = "crates/mesh-ops" }
|
||||
craft-html = { path = "crates/html" }
|
||||
craft-ipp = { path = "crates/ipp" }
|
||||
craft-heif = { path = "crates/heif" }
|
||||
|
||||
@@ -63,6 +63,10 @@ craft-proof Language data, embedded at build time from craft-i18n's language-dat
|
||||
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
|
||||
OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
POSSIBILITY OF SUCH DAMAGE.
|
||||
mikktspace 0.3.0 (https://crates.io/crates/mikktspace/0.3.0), a dependency of crates/mesh-ops,
|
||||
is MIT OR Apache-2.0. Its src/generated.rs, a translation of Morten S. Mikkelsen's C
|
||||
MikkTSpace, carries that original's 2011 zlib-style notice, which must not be removed or
|
||||
altered; crates/mesh-ops/ATTRIBUTION.md reproduces it in full.
|
||||
crates/text/assets/hyphen/en-us.pat: CC0-1.0, trained from en-us.dic by DesignCraft's trainer.
|
||||
crates/text/assets/spell/en-us-scowl-50.txt.deflate: SCOWL (Spell Checker Oriented Word Lists)
|
||||
2020.12.07, size 50, American English, Copyright 2000-2018 by Kevin Atkinson, http://wordlist.aspell.net/.
|
||||
@@ -229,6 +233,17 @@ The colour management module in crates/cms is extracted from:
|
||||
Licensed MIT OR Apache-2.0. Its generated ICC profile is dedicated to the public domain
|
||||
(CC0-1.0); see ATTRIBUTION.md.
|
||||
|
||||
The mesh operations in crates/mesh-ops are moved from:
|
||||
- TextureCraft, crates/geom (src/mesh.rs, bvh.rs, primitives.rs, gbuffer.rs, unwrap.rs,
|
||||
camera.rs and their tests), revision 386630ee85cb22679295b24013575d1aecb39ad2.
|
||||
https://github.com/storytold/texturecraft
|
||||
Copyright (c) 2026 ArtCraft Team and the TextureCraft contributors.
|
||||
- MaterialCraft, crates/geom/src/mesh.rs (subdivision and its test), revision
|
||||
3133062968b8a1566eda12a357cb06062db16687.
|
||||
https://github.com/storytold/materialcraft
|
||||
Copyright (c) 2026 ArtCraft Team and the MaterialCraft contributors.
|
||||
All licensed MIT OR Apache-2.0.
|
||||
|
||||
The image-based lighting in crates/pbr (craft-pbr) is adapted from:
|
||||
- TextureCraft, crates/render/src/ibl.rs, revision fe8ee1bdb0243335560d3e726633cc0433ee99fc,
|
||||
copied without its tests to crates/pbr/tests/it/reference/texturecraft.rs.
|
||||
|
||||
@@ -329,6 +329,9 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit
|
||||
of polygons with per-corner indices, materials, a node hierarchy): STL, OBJ with MTL, PLY,
|
||||
glTF 2.0 / GLB, FBX and 3MF, one feature each. Readers are bounded by `Limits`, never open a file
|
||||
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, 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.
|
||||
|
||||
@@ -114,6 +114,7 @@ craft-material-graph = { workspace = true, optional = true }
|
||||
craft-materialx = { workspace = true, optional = true }
|
||||
craft-math = { workspace = true, optional = true }
|
||||
craft-mesh = { workspace = true, optional = true }
|
||||
craft-mesh-ops = { workspace = true, optional = true }
|
||||
craft-metadata = { workspace = true, optional = true }
|
||||
craft-metafile = { workspace = true, optional = true }
|
||||
craft-midi = { workspace = true, optional = true }
|
||||
@@ -675,6 +676,8 @@ mesh-ply = ["mesh", "craft-mesh/ply"]
|
||||
mesh-stl = ["mesh", "craft-mesh/stl"]
|
||||
mesh-threemf = ["mesh", "craft-mesh/threemf"]
|
||||
|
||||
mesh-ops = ["dep:craft-mesh-ops"]
|
||||
|
||||
metadata = ["dep:craft-metadata"]
|
||||
|
||||
metafile = ["dep:craft-metafile"]
|
||||
|
||||
@@ -251,6 +251,8 @@ pub use craft_media_source as media_source;
|
||||
pub use craft_menu as menu;
|
||||
#[cfg(feature = "mesh")]
|
||||
pub use craft_mesh as mesh;
|
||||
#[cfg(feature = "mesh-ops")]
|
||||
pub use craft_mesh_ops as mesh_ops;
|
||||
#[cfg(feature = "metadata")]
|
||||
pub use craft_metadata as metadata;
|
||||
#[cfg(feature = "metafile")]
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
# Attribution
|
||||
|
||||
`craft-mesh-ops` generates tangents with the `mikktspace` crate.
|
||||
|
||||
| Package | Authors | Source | License |
|
||||
|---|---|---|---|
|
||||
| `mikktspace` 0.3.0 | Benjamin Wasty, David Harvey-Macaulay, Layl Bongers | [crates.io](https://crates.io/crates/mikktspace/0.3.0), [gltf-rs/mikktspace](https://github.com/gltf-rs/mikktspace) | MIT OR Apache-2.0 (the package's `license` field) |
|
||||
|
||||
The package's `src/generated.rs` is a translation of Morten S. Mikkelsen's C implementation of
|
||||
the MikkTSpace algorithm and carries that implementation's notice, reproduced here unchanged:
|
||||
|
||||
```text
|
||||
Copyright (C) 2011 by Morten S. Mikkelsen
|
||||
|
||||
This software is provided 'as-is', without any express or implied
|
||||
warranty. In no event will the authors be held liable for any damages
|
||||
arising from the use of this software.
|
||||
|
||||
Permission is granted to anyone to use this software for any purpose,
|
||||
including commercial applications, and to alter it and redistribute it
|
||||
freely, subject to the following restrictions:
|
||||
|
||||
1. The origin of this software must not be misrepresented; you must not
|
||||
claim that you wrote the original software. If you use this software
|
||||
in a product, an acknowledgment in the product documentation would be
|
||||
appreciated but is not required.
|
||||
|
||||
2. Altered source versions must be plainly marked as such, and must not be
|
||||
misrepresented as being the original software.
|
||||
|
||||
3. This notice may not be removed or altered from any source distribution.
|
||||
```
|
||||
@@ -0,0 +1,20 @@
|
||||
[package]
|
||||
name = "craft-mesh-ops"
|
||||
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
|
||||
rust-version.workspace = true
|
||||
repository.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
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 }
|
||||
serde = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
@@ -0,0 +1,42 @@
|
||||
# craft-mesh-ops
|
||||
|
||||
Operations on triangle meshes, for apps that paint, bake or preview materials on 3D models. The
|
||||
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).
|
||||
|
||||
- **`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.
|
||||
- **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.
|
||||
- **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.
|
||||
|
||||
`GeomError::Invalid` is the one error type. `rayon` parallelizes the UV G-buffer, and `serde`
|
||||
serializes `OrbitCamera`; both are always on.
|
||||
|
||||
## Origin
|
||||
|
||||
| Part | Source |
|
||||
|---|---|
|
||||
| `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) |
|
||||
|
||||
MikkTSpace comes from the `mikktspace` crate; its notice is in [ATTRIBUTION.md](ATTRIBUTION.md).
|
||||
|
||||
## Migration
|
||||
|
||||
| App | Status |
|
||||
|---|---|
|
||||
| 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. |
|
||||
@@ -0,0 +1,678 @@
|
||||
//! 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).
|
||||
|
||||
use glam::{Vec3, Vec3A};
|
||||
|
||||
use crate::Mesh;
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct Node {
|
||||
lo: Vec3A,
|
||||
hi: Vec3A,
|
||||
/// Leaf: first triangle in `order`; inner: index of the left child (right = left + 1).
|
||||
first: u32,
|
||||
/// Triangles in a leaf; 0 for inner nodes.
|
||||
count: u32,
|
||||
}
|
||||
|
||||
/// A ray hit: distance, triangle and barycentrics (weights of vertices 1 and 2).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Hit {
|
||||
pub t: f32,
|
||||
pub tri: u32,
|
||||
pub u: f32,
|
||||
pub v: f32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Bvh {
|
||||
nodes: Vec<Node>,
|
||||
/// Triangle vertices in BVH order.
|
||||
tris: Vec<[Vec3; 3]>,
|
||||
/// Original triangle index of each entry in `tris`.
|
||||
order: Vec<u32>,
|
||||
}
|
||||
|
||||
const LEAF: usize = 4;
|
||||
|
||||
/// Traversal stack of (node, entry distance): inline for typical depths (no allocation per
|
||||
/// ray), spilling to the heap for degenerate trees.
|
||||
struct Stack {
|
||||
inline: [(u32, f32); 64],
|
||||
len: usize,
|
||||
spill: Vec<(u32, f32)>,
|
||||
}
|
||||
|
||||
impl Default for Stack {
|
||||
fn default() -> Self {
|
||||
Stack { inline: [(0, 0.0); 64], len: 0, spill: Vec::new() }
|
||||
}
|
||||
}
|
||||
|
||||
impl Stack {
|
||||
fn push(&mut self, v: (u32, f32)) {
|
||||
match self.inline.get_mut(self.len) {
|
||||
Some(slot) if self.spill.is_empty() => {
|
||||
*slot = v;
|
||||
self.len += 1;
|
||||
}
|
||||
_ => self.spill.push(v),
|
||||
}
|
||||
}
|
||||
|
||||
fn pop(&mut self) -> Option<(u32, f32)> {
|
||||
self.spill.pop().or_else(|| {
|
||||
self.len = self.len.checked_sub(1)?;
|
||||
self.inline.get(self.len).copied()
|
||||
})
|
||||
}
|
||||
}
|
||||
const BINS: usize = 12;
|
||||
|
||||
fn grow(lo: &mut Vec3, hi: &mut Vec3, p: Vec3) {
|
||||
*lo = lo.min(p);
|
||||
*hi = hi.max(p);
|
||||
}
|
||||
|
||||
fn area(lo: Vec3, hi: Vec3) -> f32 {
|
||||
let d = (hi - lo).max(Vec3::ZERO);
|
||||
d.x * d.y + d.y * d.z + d.z * d.x
|
||||
}
|
||||
|
||||
impl Bvh {
|
||||
pub fn new(mesh: &Mesh) -> Bvh {
|
||||
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 position = |i: usize| mesh.positions.get(i).copied().unwrap_or(Vec3::ZERO);
|
||||
tris.push([position(a), position(b), position(c)]);
|
||||
}
|
||||
|
||||
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();
|
||||
|
||||
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];
|
||||
let (start, count) = (first as usize, count as usize);
|
||||
let (mut bounds_min, mut bounds_max) = (Vec3::splat(f32::MAX), Vec3::splat(f32::MIN));
|
||||
let (mut centroid_min, mut centroid_max) = (Vec3::splat(f32::MAX), Vec3::splat(f32::MIN));
|
||||
|
||||
for &triangle in &order[start..start + count] {
|
||||
for position in tris[triangle as usize] {
|
||||
grow(&mut bounds_min, &mut bounds_max, position);
|
||||
}
|
||||
grow(&mut centroid_min, &mut centroid_max, centroids[triangle as usize]);
|
||||
}
|
||||
|
||||
nodes[node_index].lo = bounds_min.into();
|
||||
nodes[node_index].hi = bounds_max.into();
|
||||
|
||||
if count <= LEAF {
|
||||
continue;
|
||||
}
|
||||
|
||||
let centroid_extent = centroid_max - centroid_min;
|
||||
let bin_of = |triangle: u32, axis: usize| {
|
||||
let offset = centroids[triangle as usize][axis] - centroid_min[axis];
|
||||
((offset / centroid_extent[axis] * BINS as f32) as usize).min(BINS - 1)
|
||||
};
|
||||
|
||||
// Reuse each triangle's bounds across all three axes
|
||||
let mut axis_bins = [[(0u32, Vec3::splat(f32::MAX), Vec3::splat(f32::MIN)); BINS]; 3];
|
||||
|
||||
for &triangle in &order[start..start + count] {
|
||||
let [a, b, c] = tris[triangle as usize];
|
||||
let (triangle_min, triangle_max) = (a.min(b).min(c), a.max(b).max(c));
|
||||
|
||||
for axis in 0..3 {
|
||||
if centroid_extent[axis] <= 1e-12 {
|
||||
continue;
|
||||
}
|
||||
|
||||
let bin = &mut axis_bins[axis][bin_of(triangle, axis)];
|
||||
bin.0 += 1;
|
||||
bin.1 = bin.1.min(triangle_min);
|
||||
bin.2 = bin.2.max(triangle_max);
|
||||
}
|
||||
}
|
||||
|
||||
let mut best_axis = 0;
|
||||
let mut best_split = 0;
|
||||
let mut best_cost = f32::MAX;
|
||||
|
||||
for axis in 0..3 {
|
||||
if centroid_extent[axis] <= 1e-12 {
|
||||
continue;
|
||||
}
|
||||
|
||||
let bins = axis_bins[axis];
|
||||
|
||||
// Cache right bounds once and advance the left bounds per split
|
||||
let mut suffix = bins;
|
||||
for i in (0..BINS - 1).rev() {
|
||||
suffix[i] = (suffix[i].0 + suffix[i + 1].0, suffix[i].1.min(suffix[i + 1].1), suffix[i].2.max(suffix[i + 1].2));
|
||||
}
|
||||
|
||||
let (mut left_count, mut left_min, mut left_max) = (0u32, Vec3::splat(f32::MAX), Vec3::splat(f32::MIN));
|
||||
|
||||
for split in 1..BINS {
|
||||
let bin = bins[split - 1];
|
||||
left_count += bin.0;
|
||||
left_min = left_min.min(bin.1);
|
||||
left_max = left_max.max(bin.2);
|
||||
|
||||
let (right_count, right_min, right_max) = suffix[split];
|
||||
if left_count == 0 || right_count == 0 {
|
||||
continue;
|
||||
}
|
||||
|
||||
let cost = left_count as f32 * area(left_min, left_max) + right_count as f32 * area(right_min, right_max);
|
||||
if cost < best_cost {
|
||||
best_cost = cost;
|
||||
best_axis = axis;
|
||||
best_split = split;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let node_order = &mut order[start..start + count];
|
||||
let left_count = if best_split == 0 || best_cost >= count as f32 * area(bounds_min, bounds_max) {
|
||||
// Split by count when SAH cannot help, including tied centroids
|
||||
let axis = if centroid_extent.x >= centroid_extent.y && centroid_extent.x >= centroid_extent.z {
|
||||
0
|
||||
} else if centroid_extent.y >= centroid_extent.z {
|
||||
1
|
||||
} else {
|
||||
2
|
||||
};
|
||||
|
||||
let mid = count / 2;
|
||||
node_order.select_nth_unstable_by(mid, |&a, &b| centroids[a as usize][axis].total_cmp(¢roids[b as usize][axis]));
|
||||
mid
|
||||
} else {
|
||||
let mut left_count = 0;
|
||||
|
||||
for i in 0..node_order.len() {
|
||||
if bin_of(node_order[i], best_axis) < best_split {
|
||||
node_order.swap(left_count, i);
|
||||
left_count += 1;
|
||||
}
|
||||
}
|
||||
|
||||
left_count
|
||||
};
|
||||
|
||||
if left_count == 0 || left_count == count {
|
||||
continue;
|
||||
}
|
||||
|
||||
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 });
|
||||
|
||||
nodes[node_index].first = left_child as u32;
|
||||
nodes[node_index].count = 0;
|
||||
|
||||
stack.push(left_child);
|
||||
stack.push(left_child + 1);
|
||||
}
|
||||
|
||||
let tris = order.iter().map(|t| tris[*t as usize]).collect();
|
||||
Bvh { nodes, tris, order }
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.tris.is_empty()
|
||||
}
|
||||
|
||||
/// 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`.
|
||||
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))
|
||||
}
|
||||
|
||||
/// Triangle vertices in BVH order, and the original triangle index of each.
|
||||
pub fn triangles(&self) -> (&[[Vec3; 3]], &[u32]) {
|
||||
(&self.tris, &self.order)
|
||||
}
|
||||
|
||||
fn slab(lo: Vec3A, hi: Vec3A, o: Vec3A, inv: Vec3A, tmax: f32) -> Option<f32> {
|
||||
let t0 = (lo - o) * inv;
|
||||
let t1 = (hi - o) * inv;
|
||||
// A ray lying in a slab plane gives 0·∞ = NaN: it is inside that slab, so the axis does
|
||||
// not bound the hit.
|
||||
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);
|
||||
(tn <= tf).then_some(tn)
|
||||
}
|
||||
|
||||
/// Möller–Trumbore, double sided.
|
||||
fn hit_tri(t: &[Vec3; 3], o: Vec3, d: Vec3) -> Option<(f32, f32, f32)> {
|
||||
let e1 = t[1] - t[0];
|
||||
let e2 = t[2] - t[0];
|
||||
let p = d.cross(e2);
|
||||
let det = e1.dot(p);
|
||||
if det.abs() < 1e-12 {
|
||||
return None;
|
||||
}
|
||||
let inv = 1.0 / det;
|
||||
let s = o - t[0];
|
||||
// A little slack on the edges: rays through a shared edge must not slip between its
|
||||
// two triangles to a surface behind.
|
||||
const EDGE: f32 = 1e-5;
|
||||
let u = s.dot(p) * inv;
|
||||
if !(-EDGE..=1.0 + EDGE).contains(&u) {
|
||||
return None;
|
||||
}
|
||||
let q = s.cross(e1);
|
||||
let v = d.dot(q) * inv;
|
||||
if v < -EDGE || u + v > 1.0 + EDGE {
|
||||
return None;
|
||||
}
|
||||
let tt = e2.dot(q) * inv;
|
||||
(tt > 0.0).then_some((tt, u, v))
|
||||
}
|
||||
|
||||
fn traverse(&self, o: Vec3, d: Vec3, mut tmax: f32, any: bool, filter: &dyn Fn(u32) -> bool) -> Option<Hit> {
|
||||
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;
|
||||
let mut stack = Stack::default();
|
||||
stack.push((0, Self::slab(root.lo, root.hi, oa, inv, tmax)?));
|
||||
// Entries carry their entry distance: nodes behind a closer hit are skipped unopened.
|
||||
while let Some((ni, tn)) = stack.pop() {
|
||||
let Some(n) = self.nodes.get(ni as usize).filter(|_| tn <= tmax) else { continue };
|
||||
if n.count > 0 {
|
||||
let (f, c) = (n.first as usize, n.count as usize);
|
||||
for i in f..(f + c).min(self.tris.len()) {
|
||||
let (Some(tri), Some(&orig)) = (self.tris.get(i), self.order.get(i)) else { continue };
|
||||
if let Some((t, u, v)) = Self::hit_tri(tri, o, d)
|
||||
&& t < tmax
|
||||
&& filter(orig)
|
||||
{
|
||||
tmax = t;
|
||||
best = Some(Hit { t, tri: orig, u, v });
|
||||
if any {
|
||||
return best;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Visit the nearer child first.
|
||||
let (l, r) = (n.first, n.first + 1);
|
||||
let dl = self.nodes.get(l as usize).and_then(|c| Self::slab(c.lo, c.hi, oa, inv, tmax));
|
||||
let dr = self.nodes.get(r as usize).and_then(|c| Self::slab(c.lo, c.hi, oa, inv, tmax));
|
||||
match (dl, dr) {
|
||||
(Some(a), Some(b)) if a <= b => {
|
||||
stack.push((r, b));
|
||||
stack.push((l, a));
|
||||
}
|
||||
(Some(a), Some(b)) => {
|
||||
stack.push((l, a));
|
||||
stack.push((r, b));
|
||||
}
|
||||
(Some(a), None) => stack.push((l, a)),
|
||||
(None, Some(b)) => stack.push((r, b)),
|
||||
(None, None) => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
best
|
||||
}
|
||||
|
||||
/// Closest hit along `o + t·d` for `t` in (0, tmax).
|
||||
pub fn closest(&self, o: Vec3, d: Vec3, tmax: f32) -> Option<Hit> {
|
||||
self.traverse(o, d, tmax, false, &|_| true)
|
||||
}
|
||||
|
||||
/// Closest hit on triangles accepted by `filter` (original triangle index).
|
||||
pub fn closest_filtered(&self, o: Vec3, d: Vec3, tmax: f32, filter: &dyn Fn(u32) -> bool) -> Option<Hit> {
|
||||
self.traverse(o, d, tmax, false, filter)
|
||||
}
|
||||
|
||||
/// Whether anything is hit before `tmax` (occlusion rays).
|
||||
pub fn occluded(&self, o: Vec3, d: Vec3, tmax: f32) -> bool {
|
||||
self.traverse(o, d, tmax, true, &|_| true).is_some()
|
||||
}
|
||||
|
||||
/// 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> {
|
||||
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();
|
||||
let (mut best_d2, mut best) = (max_dist * max_dist, None);
|
||||
let mut stack = Stack::default();
|
||||
stack.push((0, box_d2(root)));
|
||||
while let Some((ni, d2)) = stack.pop() {
|
||||
let Some(n) = self.nodes.get(ni as usize).filter(|_| d2 <= best_d2) else { continue };
|
||||
if n.count > 0 {
|
||||
for i in n.first as usize..(n.first as usize + n.count as usize).min(self.tris.len()) {
|
||||
let (Some(tri), Some(&orig)) = (self.tris.get(i), self.order.get(i)) else { continue };
|
||||
if !filter(orig) {
|
||||
continue;
|
||||
}
|
||||
let (q, u, v) = closest_on_triangle(p, tri);
|
||||
let dd = (q - p).length_squared();
|
||||
if dd < best_d2 {
|
||||
best_d2 = dd;
|
||||
best = Some(Hit { t: dd.sqrt(), tri: orig, u, v });
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Push the farther child first so the nearer one is searched first.
|
||||
let child = |c: u32| self.nodes.get(c as usize).map(|n| (c, box_d2(n)));
|
||||
let (Some(l), Some(r)) = (child(n.first), child(n.first + 1)) else { continue };
|
||||
let (near, far) = if l.1 <= r.1 { (l, r) } else { (r, l) };
|
||||
stack.push(far);
|
||||
stack.push(near);
|
||||
}
|
||||
}
|
||||
best
|
||||
}
|
||||
|
||||
/// 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)) {
|
||||
let mut stack = vec![0u32];
|
||||
while let Some(i) = stack.pop() {
|
||||
let Some(n) = self.nodes.get(i as usize) else { continue };
|
||||
if self.tris.is_empty() || n.hi.cmplt(lo.into()).any() || n.lo.cmpgt(hi.into()).any() {
|
||||
continue;
|
||||
}
|
||||
if n.count > 0 {
|
||||
for k in n.first as usize..(n.first + n.count) as usize {
|
||||
let (Some(t), Some(o)) = (self.tris.get(k), self.order.get(k)) else { continue };
|
||||
let tlo = t[0].min(t[1]).min(t[2]);
|
||||
let thi = t[0].max(t[1]).max(t[2]);
|
||||
if !(thi.cmplt(lo).any() || tlo.cmpgt(hi).any()) {
|
||||
f(*o);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
stack.push(n.first);
|
||||
stack.push(n.first + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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). Degenerate triangles give
|
||||
/// a non-finite distance and are never nearest.
|
||||
fn closest_on_triangle(p: Vec3, t: &[Vec3; 3]) -> (Vec3, f32, f32) {
|
||||
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 {
|
||||
return (a, 0.0, 0.0);
|
||||
}
|
||||
let bp = p - b;
|
||||
let (d3, d4) = (ab.dot(bp), ac.dot(bp));
|
||||
if d3 >= 0.0 && d4 <= d3 {
|
||||
return (b, 1.0, 0.0);
|
||||
}
|
||||
let vc = d1 * d4 - d3 * d2;
|
||||
if vc <= 0.0 && d1 >= 0.0 && d3 <= 0.0 {
|
||||
let v = d1 / (d1 - d3);
|
||||
return (a + ab * v, v, 0.0);
|
||||
}
|
||||
let cp = p - c;
|
||||
let (d5, d6) = (ab.dot(cp), ac.dot(cp));
|
||||
if d6 >= 0.0 && d5 <= d6 {
|
||||
return (c, 0.0, 1.0);
|
||||
}
|
||||
let vb = d5 * d2 - d1 * d6;
|
||||
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 {
|
||||
let w = (d4 - d3) / ((d4 - d3) + (d5 - d6));
|
||||
return (b + (c - b) * w, 1.0 - w, w);
|
||||
}
|
||||
let denom = 1.0 / (va + vb + vc);
|
||||
let (v, w) = (vb * denom, vc * denom);
|
||||
(a + ab * v + ac * w, v, w)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::primitives;
|
||||
|
||||
#[test]
|
||||
fn nearest_point_matches_brute_force() {
|
||||
let m = primitives::builtin("torus").unwrap();
|
||||
let bvh = Bvh::new(&m);
|
||||
let mut seed = 7u32;
|
||||
let mut rnd = move || {
|
||||
seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
|
||||
(seed >> 8) as f32 / (1u32 << 24) as f32 * 4.0 - 2.0
|
||||
};
|
||||
for _ in 0..200 {
|
||||
let p = Vec3::new(rnd(), rnd(), rnd());
|
||||
let hit = bvh.nearest(p, f32::MAX, &|_| true).unwrap();
|
||||
let brute = (0..m.triangle_count())
|
||||
.map(|t| {
|
||||
let [a, b, c] = m.tri(t).unwrap().map(|i| m.positions[i]);
|
||||
(closest_on_triangle(p, &[a, b, c]).0 - p).length()
|
||||
})
|
||||
.fold(f32::MAX, f32::min);
|
||||
assert!((hit.t - brute).abs() < 1e-5, "{} vs {brute}", hit.t);
|
||||
let [a, b, c] = m.tri(hit.tri as usize).unwrap().map(|i| m.positions[i]);
|
||||
let q = a * (1.0 - hit.u - hit.v) + b * hit.u + c * hit.v;
|
||||
assert!(((q - p).length() - hit.t).abs() < 1e-4);
|
||||
}
|
||||
assert!(bvh.nearest(Vec3::splat(100.0), 1.0, &|_| true).is_none(), "out of range");
|
||||
assert!(bvh.nearest(Vec3::ZERO, f32::MAX, &|_| false).is_none(), "filtered out");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn traversal_stack_spills_in_lifo_order() {
|
||||
let mut st = Stack::default();
|
||||
for v in 0..200 {
|
||||
st.push((v, v as f32));
|
||||
}
|
||||
assert!((0..200).rev().all(|v| st.pop() == Some((v, v as f32))));
|
||||
assert_eq!(st.pop(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ray_hits_sphere_at_expected_distance() {
|
||||
let m = primitives::sphere(1.0, 64, 32);
|
||||
let bvh = Bvh::new(&m);
|
||||
let h = bvh.closest(Vec3::new(0.0, 0.0, 5.0), Vec3::NEG_Z, 100.0).unwrap();
|
||||
assert!((h.t - 4.0).abs() < 0.01, "{}", h.t);
|
||||
assert!(bvh.closest(Vec3::new(0.0, 3.0, 5.0), Vec3::NEG_Z, 100.0).is_none());
|
||||
// Rays lying exactly in a node's bounding plane (y = 0 is the equator) hit the front.
|
||||
// Axis-aligned rays lying in a node's bounding plane (y = 0) still find the front.
|
||||
for x in [-0.5f32, -0.4, 0.3] {
|
||||
let h = bvh.closest(Vec3::new(x, 0.0, 5.0), Vec3::NEG_Z, 100.0).unwrap();
|
||||
assert!(h.t < 5.0, "x {x}: hit the back at t {}", h.t);
|
||||
}
|
||||
// Rays through shared edges (the equator) hit the front, never slip through to the back.
|
||||
let m = primitives::sphere(1.0, 48, 24);
|
||||
let bvh = Bvh::new(&m);
|
||||
for i in 0..200 {
|
||||
let x = i as f32 / 100.0 - 1.0;
|
||||
let o = Vec3::new(0.0, 0.0, 5.0);
|
||||
let d = (Vec3::new(x * 0.9, 0.0, 0.0) - o).normalize();
|
||||
let h = bvh.closest(o, d, 100.0).unwrap();
|
||||
assert!(h.t < 5.0, "x {x}: hit the back at t {}", h.t);
|
||||
}
|
||||
assert!(bvh.occluded(Vec3::new(0.0, 0.0, 5.0), Vec3::NEG_Z, 10.0));
|
||||
assert!(!bvh.occluded(Vec3::new(0.0, 0.0, 5.0), Vec3::NEG_Z, 3.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn matches_brute_force() {
|
||||
let m = primitives::material_ball();
|
||||
let bvh = Bvh::new(&m);
|
||||
for i in 0..200 {
|
||||
let a = i as f32 * 0.731;
|
||||
let o = Vec3::new(a.cos() * 6.0, (i as f32 * 0.37).sin() * 3.0 + 1.0, a.sin() * 6.0);
|
||||
let d = (Vec3::new(0.0, 1.0, 0.0) + Vec3::new((a * 3.1).sin(), (a * 1.7).cos(), (a * 2.3).sin()) * 0.6 - o).normalize();
|
||||
let fast = bvh.closest(o, d, 1e9).map(|h| h.t);
|
||||
let mut slow: Option<f32> = None;
|
||||
for t in 0..m.triangle_count() {
|
||||
let [x, y, z] = m.tri(t).unwrap();
|
||||
if let Some((tt, _, _)) = Bvh::hit_tri(&[m.positions[x], m.positions[y], m.positions[z]], o, d) {
|
||||
slow = Some(slow.map_or(tt, |s: f32| s.min(tt)));
|
||||
}
|
||||
}
|
||||
match (fast, slow) {
|
||||
(Some(a), Some(b)) => assert!((a - b).abs() < 1e-4, "{a} {b}"),
|
||||
(None, None) => {}
|
||||
other => panic!("mismatch {other:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn box_query_finds_overlapping_triangles() {
|
||||
let m = primitives::plane(2.0, 4);
|
||||
let bvh = Bvh::new(&m);
|
||||
let mut found = Vec::new();
|
||||
bvh.query_box(Vec3::new(-0.1, -0.1, -0.1), Vec3::new(0.1, 0.1, 0.1), |t| found.push(t));
|
||||
assert!(!found.is_empty() && found.len() <= 8, "{found:?}");
|
||||
let empty = Bvh::new(&Mesh::default());
|
||||
assert!(empty.closest(Vec3::ZERO, Vec3::X, 1.0).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn large_coplanar_plate_does_not_degrade_leaf_sizes() {
|
||||
let mut positions = Vec::new();
|
||||
let mut indices = Vec::new();
|
||||
let w = 200.0f32;
|
||||
let h = 100.0f32;
|
||||
|
||||
// Large plate at z = 0
|
||||
let b = positions.len() as u32;
|
||||
positions.extend_from_slice(&[Vec3::new(0.0, 0.0, 0.0), Vec3::new(w, 0.0, 0.0), Vec3::new(w, h, 0.0), Vec3::new(0.0, h, 0.0)]);
|
||||
indices.extend_from_slice(&[b, b + 1, b + 2, b, b + 2, b + 3]);
|
||||
|
||||
// 500 small triangles sitting at z = 0.5
|
||||
for i in 0..500 {
|
||||
let x = 20.0 + (i % 160) as f32;
|
||||
let y = 10.0 + ((i / 160) % 80) as f32;
|
||||
let idx = positions.len() as u32;
|
||||
positions.push(Vec3::new(x, y, 0.5));
|
||||
positions.push(Vec3::new(x + 0.5, y, 0.5));
|
||||
positions.push(Vec3::new(x, y + 0.5, 0.6));
|
||||
indices.extend_from_slice(&[idx, idx + 1, idx + 2]);
|
||||
}
|
||||
|
||||
let mesh = Mesh {
|
||||
positions,
|
||||
normals: Vec::new(),
|
||||
uvs: Vec::new(),
|
||||
indices,
|
||||
tangents: Vec::new(),
|
||||
colors: Vec::new(),
|
||||
submeshes: Vec::new(),
|
||||
materials: Vec::new(),
|
||||
diagonals: Vec::new(),
|
||||
};
|
||||
|
||||
let bvh = Bvh::new(&mesh);
|
||||
|
||||
for (_, _, _, count) in bvh.nodes() {
|
||||
if count > 0 {
|
||||
assert!(count <= LEAF as u32, "leaf has too many triangles: {count}");
|
||||
}
|
||||
}
|
||||
|
||||
// The foreground triangle is the closest hit
|
||||
let hit = bvh.closest(Vec3::new(20.1, 10.1, 10.0), Vec3::NEG_Z, 100.0).unwrap();
|
||||
assert!((hit.t - 9.5).abs() < 0.1, "hit t: {}", hit.t);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clustered_coplanar_fallback_partitions_nodes() {
|
||||
let mut positions = Vec::new();
|
||||
let mut indices = Vec::new();
|
||||
let w = 200.0f32;
|
||||
let h = 100.0f32;
|
||||
|
||||
let b = positions.len() as u32;
|
||||
positions.extend_from_slice(&[Vec3::new(0.0, 0.0, 0.0), Vec3::new(w, 0.0, 0.0), Vec3::new(w, h, 0.0), Vec3::new(0.0, h, 0.0)]);
|
||||
indices.extend_from_slice(&[b, b + 1, b + 2, b, b + 2, b + 3]);
|
||||
|
||||
// Shared bins keep every SAH split as costly as an unsplit leaf
|
||||
for i in 0..500 {
|
||||
let x = 130.0 + (i % 10) as f32 * 0.1;
|
||||
let y = 64.0 + (i / 10) as f32 * 0.02;
|
||||
let idx = positions.len() as u32;
|
||||
positions.push(Vec3::new(x, y, 0.0));
|
||||
positions.push(Vec3::new(x + 0.01, y, 0.0));
|
||||
positions.push(Vec3::new(x, y + 0.01, 0.0));
|
||||
indices.extend_from_slice(&[idx, idx + 1, idx + 2]);
|
||||
}
|
||||
|
||||
let mesh = Mesh {
|
||||
positions,
|
||||
normals: Vec::new(),
|
||||
uvs: Vec::new(),
|
||||
indices,
|
||||
tangents: Vec::new(),
|
||||
colors: Vec::new(),
|
||||
submeshes: Vec::new(),
|
||||
materials: Vec::new(),
|
||||
diagonals: Vec::new(),
|
||||
};
|
||||
|
||||
let bvh = Bvh::new(&mesh);
|
||||
|
||||
for (_, _, _, count) in bvh.nodes() {
|
||||
if count > 0 {
|
||||
assert!(count <= LEAF as u32, "leaf has too many triangles: {count}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn coincident_centroids_still_partition_large_and_small_triangles() {
|
||||
let mut mesh = Mesh::default();
|
||||
|
||||
// Different triangle sizes share an exact centroid
|
||||
for i in 0..=500 {
|
||||
let size = if i == 0 { 100.0 } else { 0.01 + i as f32 * 0.0001 };
|
||||
let first = mesh.positions.len() as u32;
|
||||
mesh.positions.extend([Vec3::new(-size, -size, 0.0), Vec3::new(size, -size, 0.0), Vec3::new(0.0, 2.0 * size, 0.0)]);
|
||||
mesh.indices.extend([first, first + 1, first + 2]);
|
||||
}
|
||||
|
||||
mesh.normals.resize(mesh.positions.len(), Vec3::Z);
|
||||
mesh.uvs.resize(mesh.positions.len(), glam::Vec2::ZERO);
|
||||
mesh.tangents.resize(mesh.positions.len(), glam::Vec4::new(1.0, 0.0, 0.0, 1.0));
|
||||
mesh.validate().unwrap();
|
||||
|
||||
let bvh = Bvh::new(&mesh);
|
||||
|
||||
for (_, _, _, count) in bvh.nodes() {
|
||||
assert!(count <= LEAF as u32, "leaf has too many triangles: {count}");
|
||||
}
|
||||
|
||||
// The outer ray only hits the large triangle
|
||||
let origin = Vec3::new(50.0, 0.0, 10.0);
|
||||
let hit = bvh.closest(origin, Vec3::NEG_Z, 100.0).unwrap();
|
||||
assert_eq!(hit.tri, 0);
|
||||
assert_eq!(hit.t, 10.0);
|
||||
|
||||
assert!(bvh.occluded(origin, Vec3::NEG_Z, 100.0));
|
||||
assert!(!bvh.occluded(origin, Vec3::NEG_Z, 5.0));
|
||||
|
||||
// Median partitions preserve original triangle IDs
|
||||
let hit = bvh.closest_filtered(Vec3::new(0.0, 0.0, 10.0), Vec3::NEG_Z, 100.0, &|t| t == 500).unwrap();
|
||||
assert_eq!(hit.tri, 500);
|
||||
assert_eq!(hit.t, 10.0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
//! Orbit camera (texture painting navigation) and picking rays.
|
||||
|
||||
use glam::{Mat4, Vec2, Vec3, Vec4};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct OrbitCamera {
|
||||
pub target: Vec3,
|
||||
/// Radians around Y.
|
||||
pub yaw: f32,
|
||||
/// Radians above the horizon, clamped to ±89°.
|
||||
pub pitch: f32,
|
||||
pub distance: f32,
|
||||
/// Vertical field of view, degrees.
|
||||
pub fov: f32,
|
||||
/// Scene radius (sets the clip planes).
|
||||
pub scene_radius: f32,
|
||||
/// Orthographic projection instead of perspective.
|
||||
#[serde(default)]
|
||||
pub ortho: bool,
|
||||
}
|
||||
|
||||
impl Default for OrbitCamera {
|
||||
fn default() -> Self {
|
||||
OrbitCamera { target: Vec3::ZERO, yaw: 0.0, pitch: 0.12, distance: 5.0, fov: 40.0, scene_radius: 1.0, ortho: false }
|
||||
}
|
||||
}
|
||||
|
||||
/// A ray in world space.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Ray {
|
||||
pub origin: Vec3,
|
||||
pub dir: Vec3,
|
||||
}
|
||||
|
||||
impl OrbitCamera {
|
||||
pub fn eye(&self) -> Vec3 {
|
||||
let (sy, cy) = self.yaw.sin_cos();
|
||||
let (sp, cp) = self.pitch.sin_cos();
|
||||
self.target + Vec3::new(cp * sy, sp, cp * cy) * self.distance
|
||||
}
|
||||
|
||||
pub fn forward(&self) -> Vec3 {
|
||||
(self.target - self.eye()).try_normalize().unwrap_or(Vec3::NEG_Z)
|
||||
}
|
||||
|
||||
pub fn view(&self) -> Mat4 {
|
||||
Mat4::look_at_rh(self.eye(), self.target, Vec3::Y)
|
||||
}
|
||||
|
||||
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.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.clamp(5.0, 150.0).to_radians(), aspect, near, far)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn view_proj(&self, aspect: f32) -> Mat4 {
|
||||
self.proj(aspect) * self.view()
|
||||
}
|
||||
|
||||
/// Frame a bounding box, keeping the current angles.
|
||||
pub fn frame(&mut self, lo: Vec3, hi: Vec3) {
|
||||
self.target = (lo + hi) * 0.5;
|
||||
let r = ((hi - lo).length() * 0.5).max(1e-3);
|
||||
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) {
|
||||
self.yaw -= dx;
|
||||
self.pitch = (self.pitch + dy).clamp(-89f32.to_radians(), 89f32.to_radians());
|
||||
}
|
||||
|
||||
/// Pan by a screen fraction (dx, dy in viewport heights).
|
||||
pub fn pan(&mut self, dx: f32, dy: f32) {
|
||||
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.to_radians() * 0.5).tan() * 2.0;
|
||||
self.target += (-right * dx + up * dy) * scale;
|
||||
}
|
||||
|
||||
/// Dolly by a factor exponent (positive zooms in).
|
||||
pub fn zoom(&mut self, amount: f32) {
|
||||
let r = self.scene_radius.max(1e-3);
|
||||
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).
|
||||
pub fn ray(&self, ndc: Vec2, aspect: f32) -> Ray {
|
||||
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);
|
||||
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.
|
||||
pub fn project(&self, p: Vec3, aspect: f32) -> Option<Vec3> {
|
||||
let c = self.view_proj(aspect) * p.extend(1.0);
|
||||
(c.w > 1e-6).then(|| c.truncate() / c.w)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn center_ray_points_at_target_and_projection_inverts() {
|
||||
let mut c = OrbitCamera::default();
|
||||
c.frame(Vec3::splat(-1.0), Vec3::splat(1.0));
|
||||
let r = c.ray(Vec2::ZERO, 1.5);
|
||||
assert!((r.dir - c.forward()).length() < 1e-4);
|
||||
let p = Vec3::new(0.3, -0.2, 0.1);
|
||||
let ndc = c.project(p, 1.5).unwrap();
|
||||
let r = c.ray(ndc.truncate(), 1.5);
|
||||
let to_p = (p - r.origin).normalize();
|
||||
assert!(to_p.dot(r.dir) > 0.9999);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pitch_is_clamped_and_zoom_bounded() {
|
||||
let mut c = OrbitCamera::default();
|
||||
c.orbit(0.0, 10.0);
|
||||
assert!(c.pitch <= 89f32.to_radians() + 1e-6);
|
||||
for _ in 0..1000 {
|
||||
c.zoom(1.0);
|
||||
}
|
||||
assert!(c.distance > 0.0 && c.distance.is_finite());
|
||||
let _ = c.proj(f32::NAN);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
//! The UV-space G-buffer: which triangle (and where on it) each texel of a texture set maps
|
||||
//! to. Painting, compositing, baking and padding all work from this one buffer, so they agree
|
||||
//! on which texel is which surface point.
|
||||
|
||||
use glam::{Vec2, Vec3, Vec4};
|
||||
use rayon::prelude::*;
|
||||
|
||||
use crate::Mesh;
|
||||
|
||||
/// Texel not covered by any triangle.
|
||||
pub const NO_TRI: u32 = u32::MAX;
|
||||
|
||||
const BAND: u32 = 32;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct UvGBuffer {
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
/// Triangle under each texel center, [`NO_TRI`] when uncovered.
|
||||
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).
|
||||
pub overlaps: u32,
|
||||
}
|
||||
|
||||
/// Interpolated surface attributes at a texel.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Surface {
|
||||
pub pos: Vec3,
|
||||
/// Interpolated shading normal (normalized).
|
||||
pub nrm: Vec3,
|
||||
/// Flat triangle normal (for ray offsets).
|
||||
pub geo_nrm: Vec3,
|
||||
pub tangent: Vec4,
|
||||
pub uv: Vec2,
|
||||
pub tri: u32,
|
||||
}
|
||||
|
||||
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`.
|
||||
pub fn new(mesh: &Mesh, material: usize, width: u32, height: u32) -> UvGBuffer {
|
||||
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);
|
||||
}
|
||||
}
|
||||
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 {
|
||||
self.tri.get(i).is_some_and(|t| *t != NO_TRI)
|
||||
}
|
||||
|
||||
pub fn coverage_mask(&self) -> Vec<bool> {
|
||||
self.tri.iter().map(|t| *t != NO_TRI).collect()
|
||||
}
|
||||
|
||||
pub fn covered_count(&self) -> usize {
|
||||
self.tri.iter().filter(|t| **t != NO_TRI).count()
|
||||
}
|
||||
|
||||
/// Surface attributes at texel index `i` (None when uncovered).
|
||||
pub fn surface(&self, mesh: &Mesh, i: usize) -> Option<Surface> {
|
||||
let t = *self.tri.get(i)?;
|
||||
if t == NO_TRI {
|
||||
return None;
|
||||
}
|
||||
let [b1, b2] = *self.bary.get(i)?;
|
||||
surface_at(mesh, t, b1, b2)
|
||||
}
|
||||
}
|
||||
|
||||
/// 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)?;
|
||||
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 = 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 })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::primitives;
|
||||
|
||||
#[test]
|
||||
fn half_triangle_covers_texels_with_centers_inside() {
|
||||
// One triangle covering the lower-left half of UV space (v down: y = v·H).
|
||||
let m = Mesh::from_parts(
|
||||
vec![Vec3::ZERO, Vec3::X, Vec3::Y],
|
||||
None,
|
||||
vec![Vec2::new(0.0, 0.0), Vec2::new(0.0, 1.0), Vec2::new(1.0, 1.0)],
|
||||
vec![0, 1, 2],
|
||||
"m",
|
||||
)
|
||||
.unwrap();
|
||||
let g = UvGBuffer::new(&m, 0, 8, 8);
|
||||
for y in 0..8u32 {
|
||||
for x in 0..8u32 {
|
||||
let inside = (x as f32 + 0.5) <= (y as f32 + 0.5);
|
||||
assert_eq!(g.covered((y * 8 + x) as usize), inside, "({x},{y})");
|
||||
}
|
||||
}
|
||||
assert_eq!(g.overlaps, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlapping_and_degenerate_triangles() {
|
||||
let uv = vec![Vec2::new(0.0, 0.0), Vec2::new(1.0, 0.0), Vec2::new(0.0, 1.0), Vec2::new(0.5, 0.5)];
|
||||
let m = Mesh::from_parts(vec![Vec3::ZERO, Vec3::X, Vec3::Y, Vec3::Z], None, uv, vec![0, 1, 2, 0, 1, 2, 0, 3, 3], "m").unwrap();
|
||||
let g = UvGBuffer::new(&m, 0, 16, 16);
|
||||
assert!(g.overlaps > 0);
|
||||
assert!(g.covered_count() > 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sphere_surface_lies_on_the_sphere() {
|
||||
let m = primitives::sphere(2.0, 64, 32);
|
||||
let g = UvGBuffer::new(&m, 0, 128, 128);
|
||||
assert!(g.covered_count() > 128 * 128 * 9 / 10, "{}", g.covered_count());
|
||||
for i in (0..g.tri.len()).step_by(97) {
|
||||
if let Some(s) = g.surface(&m, i) {
|
||||
assert!((s.pos.length() - 2.0).abs() < 0.02);
|
||||
assert!(s.nrm.dot(s.pos.normalize()) > 0.99);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
//! # craft-mesh-ops
|
||||
//!
|
||||
//! 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)]
|
||||
|
||||
pub mod bvh;
|
||||
pub mod camera;
|
||||
pub mod gbuffer;
|
||||
pub mod mesh;
|
||||
pub mod primitives;
|
||||
pub mod unwrap;
|
||||
|
||||
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::{BaseColor, MAX_TRIANGLES, Mesh, SubMesh};
|
||||
|
||||
#[derive(Debug, thiserror::Error, Clone, PartialEq)]
|
||||
pub enum GeomError {
|
||||
#[error("invalid mesh: {0}")]
|
||||
Invalid(String),
|
||||
}
|
||||
|
||||
pub type Result<T> = std::result::Result<T, GeomError>;
|
||||
@@ -0,0 +1,647 @@
|
||||
//! The internal triangle mesh.
|
||||
|
||||
use glam::{Vec2, Vec3, Vec4};
|
||||
|
||||
use crate::{GeomError, Result};
|
||||
|
||||
/// An edge by the bits of its two end positions, the lower one first
|
||||
type EdgePositions = ([u32; 3], [u32; 3]);
|
||||
|
||||
/// A contiguous index range drawn with one material.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct SubMesh {
|
||||
pub name: String,
|
||||
pub material: usize,
|
||||
/// First index (into [`Mesh::indices`]) and index count.
|
||||
pub start: u32,
|
||||
pub count: u32,
|
||||
}
|
||||
|
||||
/// A material's base color (what a color-map bake transfers): `factor` (linear RGBA) times an
|
||||
/// optional texture sampled at the mesh UVs.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct BaseColor {
|
||||
pub factor: Vec4,
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
/// `width × height` RGBA8 texels (color sRGB-encoded, alpha linear), rows top → bottom like
|
||||
/// the UVs' v; empty without a texture.
|
||||
pub texels: Vec<[u8; 4]>,
|
||||
}
|
||||
|
||||
/// Triangle mesh in world space. UVs use the glTF convention (origin top-left, v down).
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct Mesh {
|
||||
pub positions: Vec<Vec3>,
|
||||
pub normals: Vec<Vec3>,
|
||||
/// xyz tangent, w bitangent sign.
|
||||
pub tangents: Vec<Vec4>,
|
||||
pub uvs: Vec<Vec2>,
|
||||
/// RGBA vertex colors in 0..1 (glTF: linear; OBJ, PLY: as stored): one per vertex, or empty.
|
||||
pub colors: Vec<Vec4>,
|
||||
pub indices: Vec<u32>,
|
||||
/// Index ranges per material and part (node / object); `name` is the part name.
|
||||
pub submeshes: Vec<SubMesh>,
|
||||
pub materials: Vec<String>,
|
||||
/// Per triangle, bit `i` set when edge `i` (corner `i` to corner `i + 1`) is a diagonal the
|
||||
/// importer added to split a polygon, which wireframes leave out. Empty: every edge is real.
|
||||
pub diagonals: Vec<u8>,
|
||||
}
|
||||
|
||||
/// Hard cap on mesh size accepted from files (triangles).
|
||||
pub const MAX_TRIANGLES: usize = 20_000_000;
|
||||
|
||||
impl Mesh {
|
||||
pub fn triangle_count(&self) -> usize {
|
||||
self.indices.len() / 3
|
||||
}
|
||||
|
||||
pub fn vertex_count(&self) -> usize {
|
||||
self.positions.len()
|
||||
}
|
||||
|
||||
/// Axis-aligned bounds (zero box for an empty mesh).
|
||||
pub fn bounds(&self) -> (Vec3, Vec3) {
|
||||
if self.positions.is_empty() {
|
||||
return (Vec3::ZERO, Vec3::ZERO);
|
||||
}
|
||||
self.positions.iter().fold((Vec3::splat(f32::MAX), Vec3::splat(f32::MIN)), |(lo, hi), p| (lo.min(*p), hi.max(*p)))
|
||||
}
|
||||
|
||||
/// Bounding-sphere radius around the bounds center (at least a small epsilon).
|
||||
pub fn radius(&self) -> f32 {
|
||||
let (lo, hi) = self.bounds();
|
||||
((hi - lo).length() * 0.5).max(1e-4)
|
||||
}
|
||||
|
||||
/// Vertex indices of triangle `t`.
|
||||
pub fn tri(&self, t: usize) -> Option<[usize; 3]> {
|
||||
let i = self.indices.get(t * 3..t * 3 + 3)?;
|
||||
Some([i[0] as usize, i[1] as usize, i[2] as usize])
|
||||
}
|
||||
|
||||
/// The edges wireframes draw: each vertex pair once (smaller index first), leaving out
|
||||
/// polygon diagonals ([`Mesh::diagonals`]) unless only one triangle has the edge (a UV seam
|
||||
/// split it from its twin), per material in `0..materials.len().max(1)`.
|
||||
pub fn wire_edges(&self) -> Vec<Vec<(u32, u32)>> {
|
||||
(0..self.materials.len().max(1))
|
||||
.map(|m| {
|
||||
// Edge → (real in some triangle, triangles using it), in first-seen order.
|
||||
let mut edges: Vec<((u32, u32), bool, u8)> = Vec::new();
|
||||
let mut at: std::collections::HashMap<(u32, u32), usize> = std::collections::HashMap::new();
|
||||
for t in self.triangles_of(m) {
|
||||
let Some(v) = self.indices.get(t * 3..t * 3 + 3) else { continue };
|
||||
let hidden = self.diagonals.get(t).copied().unwrap_or(0);
|
||||
for (i, (a, b)) in [(v[0], v[1]), (v[1], v[2]), (v[2], v[0])].into_iter().enumerate() {
|
||||
let key = (a.min(b), a.max(b));
|
||||
let real = hidden >> i & 1 == 0;
|
||||
let e = *at.entry(key).or_insert_with(|| {
|
||||
edges.push((key, false, 0));
|
||||
edges.len() - 1
|
||||
});
|
||||
if let Some((_, r, n)) = edges.get_mut(e) {
|
||||
*r |= real;
|
||||
*n = n.saturating_add(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
edges.into_iter().filter(|(_, real, n)| *real || *n == 1).map(|(k, ..)| k).collect()
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Edges where the UV layout splits: two triangles meet there in 3D but not in UV space, per material in `0..materials.len().max(1)`
|
||||
pub fn uv_seam_edges(&self) -> Vec<Vec<(u32, u32)>> {
|
||||
// Signed zero denotes the same position on either side of an imported seam
|
||||
let bits = |position: Vec3| position.to_array().map(|coordinate| if coordinate == 0.0 { 0 } else { coordinate.to_bits() });
|
||||
let mut seams = vec![Vec::new(); self.materials.len().max(1)];
|
||||
// Match across materials before grouping the lines for texture-set visibility
|
||||
let mut sides: std::collections::HashMap<EdgePositions, Vec<(u32, u32, usize)>> = std::collections::HashMap::new();
|
||||
for material in 0..seams.len() {
|
||||
for triangle in self.triangles_of(material) {
|
||||
let Some(corners) = self.indices.get(triangle * 3..triangle * 3 + 3) else { continue };
|
||||
|
||||
for (from, to) in [(corners[0], corners[1]), (corners[1], corners[2]), (corners[2], corners[0])] {
|
||||
let (Some(from_position), Some(to_position)) = (self.positions.get(from as usize), self.positions.get(to as usize)) else {
|
||||
continue;
|
||||
};
|
||||
|
||||
let (from_bits, to_bits) = (bits(*from_position), bits(*to_position));
|
||||
let (edge, pair) = if from_bits <= to_bits { ((from_bits, to_bits), (from, to)) } else { ((to_bits, from_bits), (to, from)) };
|
||||
sides.entry(edge).or_default().push((pair.0, pair.1, material));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let uv = |index: u32| self.uvs.get(index as usize).copied();
|
||||
for pairs in sides.into_values() {
|
||||
let Some(&(first_from, first_to, _)) = pairs.first() else { continue };
|
||||
|
||||
if pairs.iter().any(|&(from, to, _)| (uv(from), uv(to)) != (uv(first_from), uv(first_to))) {
|
||||
for (from, to, material) in pairs {
|
||||
if let Some(edges) = seams.get_mut(material) {
|
||||
edges.push((from.min(to), from.max(to)));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for edges in &mut seams {
|
||||
edges.sort_unstable();
|
||||
edges.dedup();
|
||||
}
|
||||
|
||||
seams
|
||||
}
|
||||
|
||||
/// Material of triangle `t`.
|
||||
pub fn material_of(&self, t: usize) -> Option<usize> {
|
||||
let idx = (t * 3) as u32;
|
||||
self.submeshes.iter().find(|s| idx >= s.start && idx < s.start.saturating_add(s.count)).map(|s| s.material)
|
||||
}
|
||||
|
||||
/// Triangle index range belonging to material `m` (all submeshes of that material).
|
||||
pub fn triangles_of(&self, m: usize) -> impl Iterator<Item = usize> + '_ {
|
||||
self.submeshes.iter().filter(move |s| s.material == m).flat_map(|s| (s.start / 3) as usize..((s.start + s.count) / 3) as usize)
|
||||
}
|
||||
|
||||
/// Check that attribute arrays agree and every index is in range.
|
||||
pub fn validate(&self) -> Result<()> {
|
||||
let n = self.positions.len();
|
||||
if self.normals.len() != n || self.uvs.len() != n || self.tangents.len() != n {
|
||||
return Err(GeomError::Invalid(format!(
|
||||
"attribute counts differ: {} positions, {} normals, {} uvs, {} tangents",
|
||||
n,
|
||||
self.normals.len(),
|
||||
self.uvs.len(),
|
||||
self.tangents.len()
|
||||
)));
|
||||
}
|
||||
if !self.colors.is_empty() && self.colors.len() != n {
|
||||
return Err(GeomError::Invalid(format!("{} vertex colors for {n} vertices", self.colors.len())));
|
||||
}
|
||||
if !self.indices.len().is_multiple_of(3) {
|
||||
return Err(GeomError::Invalid("index count is not a multiple of 3".into()));
|
||||
}
|
||||
if self.triangle_count() > MAX_TRIANGLES {
|
||||
return Err(GeomError::Invalid(format!("mesh has more than {MAX_TRIANGLES} triangles")));
|
||||
}
|
||||
if let Some(bad) = self.indices.iter().find(|i| **i as usize >= n) {
|
||||
return Err(GeomError::Invalid(format!("index {bad} out of range ({n} vertices)")));
|
||||
}
|
||||
if self.positions.iter().any(|p| !p.is_finite()) {
|
||||
return Err(GeomError::Invalid("mesh has non-finite positions".into()));
|
||||
}
|
||||
for s in &self.submeshes {
|
||||
if s.start as usize + s.count as usize > self.indices.len() || s.material >= self.materials.len().max(1) {
|
||||
return Err(GeomError::Invalid(format!("submesh {} is out of range", s.name)));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Area-weighted smooth normals over the index buffer.
|
||||
pub fn compute_normals(&mut self) {
|
||||
let mut normals = vec![Vec3::ZERO; self.positions.len()];
|
||||
for &[a, b, c] in self.indices.as_chunks::<3>().0 {
|
||||
let (a, b, c) = (a as usize, b as usize, c as usize);
|
||||
let (Some(pa), Some(pb), Some(pc)) = (self.positions.get(a), self.positions.get(b), self.positions.get(c)) else { continue };
|
||||
let face = (*pb - *pa).cross(*pc - *pa);
|
||||
for v in [a, b, c] {
|
||||
if let Some(x) = normals.get_mut(v) {
|
||||
*x += face;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
self.normals = normals.into_iter().map(|v| v.try_normalize().unwrap_or(Vec3::Y)).collect();
|
||||
}
|
||||
|
||||
/// MikkTSpace tangents (falls back to per-triangle tangents if generation fails).
|
||||
pub fn compute_tangents(&mut self) {
|
||||
self.tangents = vec![Vec4::new(1.0, 0.0, 0.0, 1.0); self.positions.len()];
|
||||
if self.normals.len() != self.positions.len() {
|
||||
self.compute_normals();
|
||||
}
|
||||
if self.uvs.len() != self.positions.len() {
|
||||
self.uvs = vec![Vec2::ZERO; self.positions.len()];
|
||||
}
|
||||
// mikktspace crashes (out-of-bounds) when every triangle is degenerate; skip it then.
|
||||
let usable = !crate::unwrap::all_triangles_degenerate(self);
|
||||
let mut g = Mikk { mesh: self };
|
||||
if !usable || !mikktspace::generate_tangents(&mut g) {
|
||||
self.simple_tangents();
|
||||
}
|
||||
for (t, n) in self.tangents.iter_mut().zip(&self.normals) {
|
||||
// Orthonormalize against the normal; repair degenerate results.
|
||||
let v = t.truncate();
|
||||
let o = (v - *n * n.dot(v)).try_normalize().unwrap_or_else(|| n.any_orthonormal_vector());
|
||||
*t = o.extend(if t.w < 0.0 { -1.0 } else { 1.0 });
|
||||
}
|
||||
}
|
||||
|
||||
fn simple_tangents(&mut self) {
|
||||
let mut tangents = vec![Vec3::ZERO; self.positions.len()];
|
||||
for &[a, b, c] in self.indices.as_chunks::<3>().0 {
|
||||
let (a, b, c) = (a as usize, b as usize, c as usize);
|
||||
let (Some(pa), Some(pb), Some(pc)) = (self.positions.get(a), self.positions.get(b), self.positions.get(c)) else { continue };
|
||||
let (Some(ua), Some(ub), Some(uc)) = (self.uvs.get(a), self.uvs.get(b), self.uvs.get(c)) else { continue };
|
||||
let (e1, e2) = (*pb - *pa, *pc - *pa);
|
||||
let (d1, d2) = (*ub - *ua, *uc - *ua);
|
||||
let determinant = d1.x * d2.y - d2.x * d1.y;
|
||||
if determinant.abs() < 1e-12 {
|
||||
continue;
|
||||
}
|
||||
|
||||
let tangent = (e1 * d2.y - e2 * d1.y) / determinant;
|
||||
for v in [a, b, c] {
|
||||
if let Some(x) = tangents.get_mut(v) {
|
||||
*x += tangent;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
self.tangents = tangents.into_iter().map(|t| t.try_normalize().unwrap_or(Vec3::X).extend(1.0)).collect();
|
||||
}
|
||||
|
||||
/// The UV tiles material `m` covers: integer parts of its triangles' UV centroids (v down),
|
||||
/// ascending. Non-finite UVs are skipped.
|
||||
pub fn uv_tiles(&self, m: usize) -> std::collections::BTreeSet<(i32, i32)> {
|
||||
self.triangles_of(m)
|
||||
.filter_map(|t| {
|
||||
let [a, b, c] = self.tri(t)?;
|
||||
let uv = (*self.uvs.get(a)? + *self.uvs.get(b)? + *self.uvs.get(c)?) / 3.0;
|
||||
uv.is_finite().then(|| (uv.x.floor() as i32, uv.y.floor() as i32))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Remap the UVs of material `m`'s triangles with `f`. Vertices they share with other
|
||||
/// materials are duplicated first, so the other triangles keep their UVs.
|
||||
pub fn map_material_uvs(&mut self, m: usize, f: impl Fn(Vec2) -> Vec2) {
|
||||
self.map_material_uvs_with(m, |_, uv| f(uv));
|
||||
}
|
||||
|
||||
/// [`Mesh::map_material_uvs`] where `f` also gets the UV centroid of the first of the
|
||||
/// material's triangles using the vertex: piecewise maps (UV tiles of different sizes) then
|
||||
/// place a vertex on a tile border with its own triangle's tile.
|
||||
pub fn map_material_uvs_with(&mut self, m: usize, f: impl Fn(Vec2, Vec2) -> Vec2) {
|
||||
let material_triangles: Vec<usize> = self.triangles_of(m).collect();
|
||||
let mut in_material = vec![false; self.triangle_count()];
|
||||
for t in &material_triangles {
|
||||
if let Some(x) = in_material.get_mut(*t) {
|
||||
*x = true;
|
||||
}
|
||||
}
|
||||
|
||||
let mut shared = vec![false; self.positions.len()];
|
||||
for (_, tri) in self.indices.as_chunks::<3>().0.iter().enumerate().filter(|(t, _)| !in_material.get(*t).copied().unwrap_or(false)) {
|
||||
for v in tri {
|
||||
if let Some(s) = shared.get_mut(*v as usize) {
|
||||
*s = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut duplicates = std::collections::HashMap::new();
|
||||
for k in material_triangles.iter().flat_map(|t| t * 3..t * 3 + 3) {
|
||||
let Some(&v) = self.indices.get(k) else { continue };
|
||||
let v = if shared.get(v as usize).copied().unwrap_or(false) {
|
||||
*duplicates.entry(v).or_insert_with(|| self.duplicate_vertex(v as usize))
|
||||
} else {
|
||||
v
|
||||
};
|
||||
if let Some(i) = self.indices.get_mut(k) {
|
||||
*i = v;
|
||||
}
|
||||
}
|
||||
|
||||
// (vertex, centroid of its first triangle), each vertex once
|
||||
let mut vertices = Vec::with_capacity(material_triangles.len() * 3);
|
||||
for t in &material_triangles {
|
||||
let Some(tri) = self.tri(*t) else { continue };
|
||||
let centroid = tri.iter().map(|v| self.uvs.get(*v).copied().unwrap_or_default()).sum::<Vec2>() / 3.0;
|
||||
vertices.extend(tri.map(|v| (v, centroid)));
|
||||
}
|
||||
|
||||
vertices.sort_by_key(|(v, _)| *v);
|
||||
vertices.dedup_by_key(|(v, _)| *v);
|
||||
for (v, centroid) in vertices {
|
||||
if let Some(uv) = self.uvs.get_mut(v) {
|
||||
*uv = f(centroid, *uv);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Append a copy of vertex `v`; returns its index.
|
||||
fn duplicate_vertex(&mut self, v: usize) -> u32 {
|
||||
let i = self.positions.len() as u32;
|
||||
self.positions.push(self.positions.get(v).copied().unwrap_or_default());
|
||||
self.normals.push(self.normals.get(v).copied().unwrap_or(Vec3::Y));
|
||||
self.tangents.push(self.tangents.get(v).copied().unwrap_or(Vec4::new(1.0, 0.0, 0.0, 1.0)));
|
||||
self.uvs.push(self.uvs.get(v).copied().unwrap_or_default());
|
||||
if !self.colors.is_empty() {
|
||||
self.colors.push(self.colors.get(v).copied().unwrap_or(Vec4::ONE));
|
||||
}
|
||||
i
|
||||
}
|
||||
|
||||
/// Append `other`, offsetting indices; its submeshes keep their material indices shifted by
|
||||
/// this mesh's material count.
|
||||
pub fn append(&mut self, other: &Mesh) {
|
||||
let base = self.positions.len() as u32;
|
||||
let ibase = self.indices.len() as u32;
|
||||
let mbase = self.materials.len();
|
||||
self.positions.extend_from_slice(&other.positions);
|
||||
self.normals.extend_from_slice(&other.normals);
|
||||
self.tangents.extend_from_slice(&other.tangents);
|
||||
self.uvs.extend_from_slice(&other.uvs);
|
||||
if !(self.colors.is_empty() && other.colors.is_empty()) {
|
||||
// Vertices of the side without colors become white.
|
||||
self.colors.resize(base as usize, Vec4::ONE);
|
||||
self.colors.extend(other.colors.iter().copied().chain(std::iter::repeat(Vec4::ONE)).take(other.positions.len()));
|
||||
}
|
||||
if !(self.diagonals.is_empty() && other.diagonals.is_empty()) {
|
||||
self.diagonals.resize(ibase as usize / 3, 0);
|
||||
self.diagonals.extend(other.diagonals.iter().copied().chain(std::iter::repeat(0)).take(other.triangle_count()));
|
||||
}
|
||||
self.indices.extend(other.indices.iter().map(|i| i + base));
|
||||
self.materials.extend(other.materials.iter().cloned());
|
||||
self.submeshes.extend(other.submeshes.iter().map(|s| SubMesh {
|
||||
name: s.name.clone(),
|
||||
material: s.material + mbase,
|
||||
start: s.start + ibase,
|
||||
count: s.count,
|
||||
}));
|
||||
}
|
||||
|
||||
/// Each triangle split into four at its edge midpoints (shared edges share their midpoint);
|
||||
/// attributes are interpolated and submesh ranges keep their triangles.
|
||||
pub fn subdivided(&self) -> Mesh {
|
||||
let mut m = Mesh { indices: Vec::with_capacity(self.indices.len() * 4), ..self.clone() };
|
||||
let has = |len: usize| len == self.positions.len();
|
||||
let (has_n, has_t, has_uv, has_c) = (has(self.normals.len()), has(self.tangents.len()), has(self.uvs.len()), has(self.colors.len()));
|
||||
let mut mids = std::collections::HashMap::new();
|
||||
let mut mid = |m: &mut Mesh, a: u32, b: u32| -> u32 {
|
||||
*mids.entry((a.min(b), a.max(b))).or_insert_with(|| {
|
||||
let (i, j) = (a as usize, b as usize);
|
||||
m.positions.push((self.positions[i] + self.positions[j]) * 0.5);
|
||||
if has_n {
|
||||
m.normals.push((self.normals[i] + self.normals[j]).normalize_or_zero());
|
||||
}
|
||||
if has_t {
|
||||
let (ti, tj) = (self.tangents[i], self.tangents[j]);
|
||||
m.tangents.push((ti.truncate() + tj.truncate()).normalize_or_zero().extend(ti.w));
|
||||
}
|
||||
if has_uv {
|
||||
m.uvs.push((self.uvs[i] + self.uvs[j]) * 0.5);
|
||||
}
|
||||
if has_c {
|
||||
m.colors.push((self.colors[i] + self.colors[j]) * 0.5);
|
||||
}
|
||||
(m.positions.len() - 1) as u32
|
||||
})
|
||||
};
|
||||
for t in self.indices.as_chunks::<3>().0 {
|
||||
if t.iter().any(|&i| i as usize >= self.positions.len()) {
|
||||
continue;
|
||||
}
|
||||
let (a, b, c) = (t[0], t[1], t[2]);
|
||||
let (ab, bc, ca) = (mid(&mut m, a, b), mid(&mut m, b, c), mid(&mut m, c, a));
|
||||
m.indices.extend_from_slice(&[a, ab, ca, ab, b, bc, ca, bc, c, ab, bc, ca]);
|
||||
}
|
||||
for s in &mut m.submeshes {
|
||||
s.start *= 4;
|
||||
s.count *= 4;
|
||||
}
|
||||
m
|
||||
}
|
||||
|
||||
/// Uniformly scale and translate so the mesh is centered with the given bounding radius.
|
||||
pub fn normalize_to(&mut self, radius: f32) {
|
||||
let (lo, hi) = self.bounds();
|
||||
let c = (lo + hi) * 0.5;
|
||||
let s = radius / self.radius();
|
||||
for p in &mut self.positions {
|
||||
*p = (*p - c) * s;
|
||||
}
|
||||
}
|
||||
|
||||
/// A single-material mesh from raw attributes; computes missing normals and tangents.
|
||||
pub fn from_parts(positions: Vec<Vec3>, normals: Option<Vec<Vec3>>, uvs: Vec<Vec2>, indices: Vec<u32>, material: &str) -> Result<Mesh> {
|
||||
let count = indices.len() as u32;
|
||||
let mut m = Mesh {
|
||||
normals: normals.unwrap_or_default(),
|
||||
uvs,
|
||||
positions,
|
||||
indices,
|
||||
tangents: Vec::new(),
|
||||
colors: Vec::new(),
|
||||
submeshes: vec![SubMesh { name: material.into(), material: 0, start: 0, count }],
|
||||
materials: vec![material.into()],
|
||||
diagonals: Vec::new(),
|
||||
};
|
||||
if m.normals.len() != m.positions.len() {
|
||||
m.compute_normals();
|
||||
}
|
||||
m.compute_tangents();
|
||||
m.validate()?;
|
||||
Ok(m)
|
||||
}
|
||||
}
|
||||
|
||||
struct Mikk<'a> {
|
||||
mesh: &'a mut Mesh,
|
||||
}
|
||||
|
||||
impl Mikk<'_> {
|
||||
fn vi(&self, face: usize, vert: usize) -> usize {
|
||||
self.mesh.indices.get(face * 3 + vert).copied().unwrap_or(0) as usize
|
||||
}
|
||||
}
|
||||
|
||||
impl mikktspace::Geometry for Mikk<'_> {
|
||||
fn num_faces(&self) -> usize {
|
||||
self.mesh.indices.len() / 3
|
||||
}
|
||||
fn num_vertices_of_face(&self, _face: usize) -> usize {
|
||||
3
|
||||
}
|
||||
fn position(&self, face: usize, vert: usize) -> [f32; 3] {
|
||||
self.mesh.positions.get(self.vi(face, vert)).copied().unwrap_or_default().to_array()
|
||||
}
|
||||
fn normal(&self, face: usize, vert: usize) -> [f32; 3] {
|
||||
self.mesh.normals.get(self.vi(face, vert)).copied().unwrap_or(Vec3::Y).to_array()
|
||||
}
|
||||
fn tex_coord(&self, face: usize, vert: usize) -> [f32; 2] {
|
||||
// MikkTSpace expects OpenGL texture coordinates (v up); our UVs are glTF (v down). With
|
||||
// v flipped, the bitangent `cross(N, T) * w` points up the image, as glTF requires.
|
||||
let uv = self.mesh.uvs.get(self.vi(face, vert)).copied().unwrap_or_default();
|
||||
[uv.x, 1.0 - uv.y]
|
||||
}
|
||||
fn set_tangent_encoded(&mut self, tangent: [f32; 4], face: usize, vert: usize) {
|
||||
let i = self.vi(face, vert);
|
||||
if let Some(t) = self.mesh.tangents.get_mut(i) {
|
||||
*t = Vec4::from_array(tangent);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn quad() -> Mesh {
|
||||
Mesh::from_parts(
|
||||
vec![Vec3::new(0.0, 0.0, 0.0), Vec3::new(1.0, 0.0, 0.0), Vec3::new(1.0, 1.0, 0.0), Vec3::new(0.0, 1.0, 0.0)],
|
||||
None,
|
||||
vec![Vec2::new(0.0, 1.0), Vec2::new(1.0, 1.0), Vec2::new(1.0, 0.0), Vec2::new(0.0, 0.0)],
|
||||
vec![0, 1, 2, 0, 2, 3],
|
||||
"Default",
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normals_and_tangents_of_a_quad() {
|
||||
let m = quad();
|
||||
for n in &m.normals {
|
||||
assert!((*n - Vec3::Z).length() < 1e-5);
|
||||
}
|
||||
for t in &m.tangents {
|
||||
assert!((t.truncate() - Vec3::X).length() < 1e-4, "{t:?}");
|
||||
}
|
||||
assert_eq!(m.material_of(1), Some(0));
|
||||
assert_eq!(m.triangles_of(0).collect::<Vec<_>>(), vec![0, 1]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wire_edges_leave_out_polygon_diagonals() {
|
||||
let mut m = quad();
|
||||
assert_eq!(m.wire_edges(), vec![vec![(0, 1), (1, 2), (0, 2), (2, 3), (0, 3)]], "triangles show every edge");
|
||||
// Edge 2 of (0, 1, 2) and edge 0 of (0, 2, 3) split the quad.
|
||||
m.diagonals = vec![0b100, 0b001];
|
||||
assert_eq!(m.wire_edges(), vec![vec![(0, 1), (1, 2), (2, 3), (0, 3)]]);
|
||||
// A diagonal whose twin a seam split off (vertex 4 copies vertex 0) stays.
|
||||
let mut seam = m.clone();
|
||||
seam.indices[3] = 4;
|
||||
assert_eq!(seam.wire_edges()[0].len(), 6);
|
||||
// Appending keeps each side's diagonals on its own triangles.
|
||||
let mut a = Mesh::from_parts(m.positions.clone(), None, m.uvs.clone(), vec![0, 1, 2], "A").unwrap();
|
||||
a.append(&m);
|
||||
assert_eq!(a.diagonals, vec![0, 0b100, 0b001]);
|
||||
assert_eq!(crate::primitives::plane(1.0, 2).wire_edges()[0].len(), 12, "a 2×2 grid of quads has 12 edges");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uv_seams_are_where_the_uv_layout_splits() {
|
||||
let mesh = quad();
|
||||
assert_eq!(mesh.uv_seam_edges(), vec![Vec::<(u32, u32)>::new()], "one UV island has no seam");
|
||||
|
||||
// Vertex 4 copies vertex 0's position with another UV: the diagonal (0, 2) / (4, 2) is cut
|
||||
let mut seam = mesh.clone();
|
||||
seam.positions.push(seam.positions[0]);
|
||||
seam.normals.push(seam.normals[0]);
|
||||
seam.tangents.push(seam.tangents[0]);
|
||||
seam.uvs.push(Vec2::new(0.9, 0.9));
|
||||
seam.indices[3] = 4;
|
||||
assert_eq!(seam.uv_seam_edges(), vec![vec![(0, 2), (2, 4)]]);
|
||||
|
||||
// The same split with the same UV is a hard edge, not a seam
|
||||
let mut hard = seam.clone();
|
||||
hard.uvs[4] = hard.uvs[0];
|
||||
assert_eq!(hard.uv_seam_edges(), vec![Vec::<(u32, u32)>::new()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uv_seams_join_positions_with_opposite_signed_zero() {
|
||||
let mut mesh = quad();
|
||||
mesh.positions.push(Vec3::new(-0.0, 0.0, 0.0));
|
||||
mesh.normals.push(mesh.normals[0]);
|
||||
mesh.tangents.push(mesh.tangents[0]);
|
||||
mesh.uvs.push(Vec2::new(0.9, 0.9));
|
||||
mesh.indices[3] = 4;
|
||||
assert_eq!(mesh.positions[0], mesh.positions[4]);
|
||||
assert_eq!(mesh.uv_seam_edges(), vec![vec![(0, 2), (2, 4)]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uv_seams_between_materials_belong_to_both_materials() {
|
||||
let mut mesh = quad();
|
||||
mesh.positions.push(mesh.positions[0]);
|
||||
mesh.normals.push(mesh.normals[0]);
|
||||
mesh.tangents.push(mesh.tangents[0]);
|
||||
mesh.uvs.push(Vec2::new(0.9, 0.9));
|
||||
mesh.indices[3] = 4;
|
||||
mesh.materials.push("second".into());
|
||||
mesh.submeshes[0].count = 3;
|
||||
mesh.submeshes.push(SubMesh { name: "second".into(), material: 1, start: 3, count: 3 });
|
||||
|
||||
assert_eq!(mesh.uv_seam_edges(), vec![vec![(0, 2)], vec![(2, 4)]]);
|
||||
mesh.uvs[4] = mesh.uvs[0];
|
||||
assert_eq!(mesh.uv_seam_edges(), vec![Vec::<(u32, u32)>::new(); 2], "a material boundary alone is not a UV seam");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn subdivision_shares_edge_midpoints() {
|
||||
let m = quad().subdivided();
|
||||
// 4 corners + 5 edge midpoints (the diagonal is shared), 8 triangles.
|
||||
assert_eq!((m.positions.len(), m.triangle_count()), (9, 8));
|
||||
assert_eq!(m.uvs.len(), 9);
|
||||
assert_eq!((m.submeshes[0].start, m.submeshes[0].count), (0, 24));
|
||||
m.validate().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_catches_bad_indices() {
|
||||
let mut m = quad();
|
||||
m.indices[0] = 99;
|
||||
assert!(m.validate().is_err());
|
||||
let mut m = quad();
|
||||
m.uvs.pop();
|
||||
assert!(m.validate().is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn append_offsets_indices_and_materials() {
|
||||
let mut a = quad();
|
||||
let b = quad();
|
||||
a.append(&b);
|
||||
assert_eq!(a.indices[6], 4);
|
||||
assert_eq!(a.submeshes[1].material, 1);
|
||||
assert_eq!(a.submeshes[1].start, 6);
|
||||
a.validate().unwrap();
|
||||
// Colors on one side only: the other side's vertices become white.
|
||||
let mut red = quad();
|
||||
red.colors = vec![Vec4::new(1.0, 0.0, 0.0, 1.0); 4];
|
||||
a.append(&red);
|
||||
assert_eq!(a.colors.len(), 12);
|
||||
assert_eq!((a.colors[0], a.colors[8]), (Vec4::ONE, Vec4::new(1.0, 0.0, 0.0, 1.0)));
|
||||
a.append(&quad());
|
||||
assert_eq!(a.colors[15], Vec4::ONE);
|
||||
a.validate().unwrap();
|
||||
a.colors.pop();
|
||||
assert!(a.validate().is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn material_uvs_remap_and_split_shared_vertices() {
|
||||
// quad(): two triangles sharing an edge; put the second in its own material.
|
||||
let mut m = quad();
|
||||
m.materials = vec!["a".into(), "b".into()];
|
||||
m.submeshes =
|
||||
vec![SubMesh { name: "a".into(), material: 0, start: 0, count: 3 }, SubMesh { name: "b".into(), material: 1, start: 3, count: 3 }];
|
||||
let before = m.clone();
|
||||
m.map_material_uvs(1, |uv| uv + Vec2::X);
|
||||
m.validate().unwrap();
|
||||
assert_eq!(m.vertex_count(), 6, "the two shared vertices are split");
|
||||
assert_eq!(&m.indices[..3], &before.indices[..3]);
|
||||
for k in 0..3 {
|
||||
let (old, new) = (before.indices[k] as usize, m.indices[k] as usize);
|
||||
assert_eq!(m.uvs[new], before.uvs[old], "material a keeps its UVs");
|
||||
let (old, new) = (before.indices[3 + k] as usize, m.indices[3 + k] as usize);
|
||||
assert_eq!((m.uvs[new], m.positions[new]), (before.uvs[old] + Vec2::X, before.positions[old]));
|
||||
}
|
||||
assert_eq!(m.uv_tiles(1).into_iter().collect::<Vec<_>>(), vec![(1, 0)]);
|
||||
assert_eq!(m.uv_tiles(0).into_iter().collect::<Vec<_>>(), vec![(0, 0)]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,556 @@
|
||||
//! 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.
|
||||
|
||||
use std::f32::consts::{PI, TAU};
|
||||
|
||||
use glam::{Vec2, Vec3};
|
||||
|
||||
use crate::mesh::{Mesh, SubMesh};
|
||||
|
||||
/// A UV-space rectangle: origin and size.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct UvRect {
|
||||
o: Vec2,
|
||||
s: Vec2,
|
||||
}
|
||||
|
||||
impl UvRect {
|
||||
const FULL: UvRect = UvRect { o: Vec2::ZERO, s: Vec2::ONE };
|
||||
fn map(&self, u: f32, v: f32) -> Vec2 {
|
||||
self.o + self.s * Vec2::new(u, v)
|
||||
}
|
||||
fn inset(&self, m: f32) -> UvRect {
|
||||
UvRect { o: self.o + Vec2::splat(m), s: self.s - Vec2::splat(2.0 * m) }
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Builder {
|
||||
p: Vec<Vec3>,
|
||||
n: Vec<Vec3>,
|
||||
uv: Vec<Vec2>,
|
||||
idx: Vec<u32>,
|
||||
/// Per triangle: its [`Mesh::diagonals`] bits.
|
||||
diag: Vec<u8>,
|
||||
}
|
||||
|
||||
impl Builder {
|
||||
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));
|
||||
self.uv.push(uv);
|
||||
(self.p.len() - 1) as u32
|
||||
}
|
||||
|
||||
/// 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 base = self.p.len() as u32;
|
||||
for i in 0..=rows {
|
||||
for j in 0..=cols {
|
||||
let (p, n, uv) = f(i, j);
|
||||
self.vert(p, n, uv);
|
||||
}
|
||||
}
|
||||
let w = (cols + 1) as u32;
|
||||
for i in 0..rows as u32 {
|
||||
for j in 0..cols as u32 {
|
||||
let a = base + i * w + j;
|
||||
let (b, c, d) = (a + 1, a + w, a + w + 1);
|
||||
self.idx.extend_from_slice(&[a, c, d, a, d, b]);
|
||||
// Edge d-a of the first triangle and a-d of the second split the quad.
|
||||
self.diag.extend_from_slice(&[0b100, 0b001]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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) -> Mesh {
|
||||
let count = self.idx.len() as u32;
|
||||
Mesh {
|
||||
positions: self.p,
|
||||
normals: self.n,
|
||||
uvs: self.uv,
|
||||
indices: self.idx,
|
||||
tangents: Vec::new(),
|
||||
colors: Vec::new(),
|
||||
submeshes: vec![SubMesh { name: material.into(), material: 0, start: 0, count }],
|
||||
materials: vec![material.into()],
|
||||
diagonals: self.diag,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// UV sphere of `radius` centred at `center`.
|
||||
pub fn sphere(radius: f32, segments: usize, rings: usize) -> Mesh {
|
||||
let mut b = Builder::default();
|
||||
sphere_into(&mut b, Vec3::ZERO, radius, segments.max(3), rings.max(2), UvRect::FULL);
|
||||
b.finish("Sphere")
|
||||
}
|
||||
|
||||
fn sphere_into(b: &mut Builder, center: Vec3, radius: f32, segs: usize, rings: usize, r: UvRect) {
|
||||
b.grid(rings, segs, |i, j| {
|
||||
let (u, v) = (j as f32 / segs as f32, i as f32 / rings as f32);
|
||||
let (theta, phi) = (v * PI, u * TAU + PI * 1.5);
|
||||
let n = Vec3::new(theta.sin() * phi.cos(), theta.cos(), -theta.sin() * phi.sin());
|
||||
(center + n * radius, n, r.map(u, v))
|
||||
});
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
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 {
|
||||
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();
|
||||
}
|
||||
m
|
||||
}
|
||||
|
||||
fn rounded_box_into(b: &mut Builder, center: Vec3, half: Vec3, bevel: f32, r: UvRect) {
|
||||
let bevel = bevel.clamp(0.0, half.min_element() * 0.95);
|
||||
// (normal, U = right, V = down) per face, seen from outside.
|
||||
let faces = [
|
||||
(Vec3::Z, Vec3::X, -Vec3::Y),
|
||||
(Vec3::X, -Vec3::Z, -Vec3::Y),
|
||||
(-Vec3::Z, -Vec3::X, -Vec3::Y),
|
||||
(-Vec3::X, Vec3::Z, -Vec3::Y),
|
||||
(Vec3::Y, Vec3::X, Vec3::Z),
|
||||
(-Vec3::Y, Vec3::X, -Vec3::Z),
|
||||
];
|
||||
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;
|
||||
let mut v = Vec::new();
|
||||
for i in 0..kb {
|
||||
v.push(-h + bevel * i as f32 / kb as f32);
|
||||
}
|
||||
for i in 0..=kc {
|
||||
v.push(-inner + 2.0 * inner * i as f32 / kc as f32);
|
||||
}
|
||||
for i in 1..=kb {
|
||||
v.push(inner + bevel * i as f32 / kb as f32);
|
||||
}
|
||||
v
|
||||
};
|
||||
let inner = half - Vec3::splat(bevel);
|
||||
for (f, (n, u, v)) in faces.iter().enumerate() {
|
||||
let cell = UvRect { o: r.map((f % 3) as f32 / 3.0, (f / 3) as f32 / 2.0), s: r.s * Vec2::new(1.0 / 3.0, 0.5) }.inset(0.01 * r.s.x);
|
||||
let (hu, hv, hn) = ((*u * half).abs().max_element(), (*v * half).abs().max_element(), (*n * half).abs().max_element());
|
||||
let (cu, cv) = (coords(hu), coords(hv));
|
||||
let (cols, rows) = (cu.len() - 1, cv.len() - 1);
|
||||
b.grid(rows, cols, |i, j| {
|
||||
let (a, c) = (cu[j], cv[i]);
|
||||
let q = *n * hn + *u * a + *v * c;
|
||||
let clamped = q.clamp(-inner, inner);
|
||||
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)))
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Surface of revolution of a profile `(radius, y)` listed top → bottom, mapped into `r`
|
||||
/// (u around, v down the profile by arc length).
|
||||
fn lathe_into(b: &mut Builder, center: Vec3, profile: &[(f32, f32)], segs: usize, r: UvRect) {
|
||||
if profile.len() < 2 {
|
||||
return;
|
||||
}
|
||||
let mut len = vec![0.0f32];
|
||||
for w in profile.windows(2) {
|
||||
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);
|
||||
}
|
||||
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 = 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))
|
||||
});
|
||||
}
|
||||
|
||||
/// [`preview_orb`]: half-size of the cube that cuts the unit sphere flat (each face rim is the
|
||||
/// circle where they meet).
|
||||
const ORB_CUT: f32 = 0.8;
|
||||
/// [`preview_orb`] domed panels: where the valley sits, as a fraction of the face rim radius.
|
||||
const ORB_PANEL_VALLEY: f32 = 0.88;
|
||||
|
||||
/// The preview orb of the smart mask and smart material previews: a sphere cut flat by a cube on six sides, on a thin round base
|
||||
/// Each feature gives one kind of mask something to show: sharp face rims (edges), a softly
|
||||
/// blended left face (soft edges), domed panels inside the front, left and top faces whose valleys
|
||||
/// hold dirt (cavities), a slot around the middle (cavity), the base (thin part, the seam where it
|
||||
/// meets the body) and plain rounded corners (gradients). Faces +Z (front), -X (left) and +Y (top)
|
||||
/// carry the panels, so the shape is made to be seen from the front left, slightly from above.
|
||||
/// The body takes the top 79 % of the UV square, the base the bottom 19 %.
|
||||
pub fn preview_orb() -> Mesh {
|
||||
// Grid rows (columns: twice as many); fewer blur the panel walls, more cost bake time
|
||||
const ROWS: usize = 300;
|
||||
const BODY_UV_HEIGHT: f32 = 0.79;
|
||||
const BASE_UV: UvRect = UvRect { o: Vec2::new(0.0, 0.81), s: Vec2::new(1.0, 0.19) };
|
||||
const BASE_RADIUS: f32 = 0.95;
|
||||
const BASE_HALF_HEIGHT: f32 = 0.025;
|
||||
const BASE_Y: f32 = -0.6;
|
||||
const BASE_RIM_STEPS: usize = 12;
|
||||
const BASE_SEGMENTS: usize = 256;
|
||||
|
||||
let mut b = Builder::default();
|
||||
b.grid(ROWS, ROWS * 2, |i, j| {
|
||||
let (u, v) = (j as f32 / (ROWS * 2) as f32, i as f32 / ROWS as f32);
|
||||
let (theta, phi) = (v * PI, u * TAU + PI * 1.5);
|
||||
let dir = Vec3::new(theta.sin() * phi.cos(), theta.cos(), -theta.sin() * phi.sin());
|
||||
(dir * preview_orb_radius(dir), dir, Vec2::new(u, v * BODY_UV_HEIGHT))
|
||||
});
|
||||
|
||||
// Base: a thin disc with a rounded rim (a half circle from its top face to its bottom face)
|
||||
let mut profile = vec![(0.0, BASE_HALF_HEIGHT)];
|
||||
for k in 0..=BASE_RIM_STEPS {
|
||||
let a = k as f32 / BASE_RIM_STEPS as f32 * PI;
|
||||
profile.push((BASE_RADIUS - BASE_HALF_HEIGHT + BASE_HALF_HEIGHT * a.sin(), BASE_HALF_HEIGHT * a.cos()));
|
||||
}
|
||||
profile.push((0.0, -BASE_HALF_HEIGHT));
|
||||
lathe_into(&mut b, Vec3::Y * BASE_Y, &profile, BASE_SEGMENTS, BASE_UV);
|
||||
|
||||
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
|
||||
// fraction of the cost of the general tangent pass on this many triangles)
|
||||
m.tangents = m
|
||||
.positions
|
||||
.iter()
|
||||
.zip(&m.normals)
|
||||
.map(|(p, n)| {
|
||||
let around = Vec3::new(p.z, 0.0, -p.x).try_normalize().unwrap_or(Vec3::X);
|
||||
(around - *n * n.dot(around)).try_normalize().unwrap_or_else(|| n.any_orthonormal_vector()).extend(1.0)
|
||||
})
|
||||
.collect();
|
||||
m
|
||||
}
|
||||
|
||||
/// 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;
|
||||
const SOFT_BLEND: f32 = 0.18;
|
||||
// Domed panels: valley depth below the face, dome rise past it; the left panel is smaller
|
||||
const PANEL_DEPTH: f32 = 0.11;
|
||||
const PANEL_BULGE: f32 = 0.04;
|
||||
const LEFT_PANEL_SCALE: f32 = 0.9;
|
||||
// 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;
|
||||
const SLOT_ROUNDING: f32 = 0.015;
|
||||
const SLOT_DEPTH: f32 = 0.12;
|
||||
const SLOT_FADE: f32 = 0.04;
|
||||
|
||||
let rim = (1.0 - ORB_CUT * ORB_CUT).sqrt() / ORB_CUT;
|
||||
let smooth = |a: f32, b: f32, x: f32| {
|
||||
let t = ((x - a) / (b - a)).clamp(0.0, 1.0);
|
||||
t * t * (3.0 - 2.0 * t)
|
||||
};
|
||||
// Polynomial smooth minimum with blend radius k
|
||||
let smin = |a: f32, b: f32, k: f32| {
|
||||
let h = (0.5 + 0.5 * (b - a) / k).clamp(0.0, 1.0);
|
||||
b + (a - b) * h - k * h * (1.0 - h)
|
||||
};
|
||||
// Domed panel at `rho` (radius in face units) inside a face of rim `rim`: a steep wall from
|
||||
// the rim into a valley, then a dome rising slightly past the face over the middle
|
||||
let panel = |rho: f32, rim: f32| {
|
||||
let valley = rim * ORB_PANEL_VALLEY;
|
||||
if rho < valley {
|
||||
PANEL_BULGE - (PANEL_BULGE + PANEL_DEPTH) * (rho / valley).powi(3)
|
||||
} else {
|
||||
-PANEL_DEPTH * (1.0 - ((rho - valley) / (rim - valley)).min(1.0))
|
||||
}
|
||||
};
|
||||
let face_rho = |along: f32, u: f32, v: f32| (u * u + v * v).sqrt() / along.max(1e-3);
|
||||
|
||||
// The cut: sharp rims except the softly blended left face
|
||||
let mut radius = 1.0f32;
|
||||
for (along, blend) in [(d.x, SHARP_BLEND), (-d.x, SOFT_BLEND), (d.y, SHARP_BLEND), (-d.y, SHARP_BLEND), (d.z, SHARP_BLEND), (-d.z, SHARP_BLEND)] {
|
||||
// Directions facing away from a face stay on the sphere (9 = far past it)
|
||||
let to_face = if along > 1e-3 { ORB_CUT / along } else { 9.0 };
|
||||
radius = smin(radius, to_face, blend);
|
||||
}
|
||||
|
||||
let a = d.abs();
|
||||
let left_rim = rim * LEFT_PANEL_SCALE;
|
||||
let mut relief = 0.0;
|
||||
if d.z > 0.0 && a.z >= a.x && a.z >= a.y {
|
||||
relief += panel(face_rho(d.z, d.x, d.y), rim);
|
||||
}
|
||||
if d.x < 0.0 && a.x >= a.y && a.x >= a.z {
|
||||
relief += panel(face_rho(-d.x, d.y, d.z), left_rim);
|
||||
}
|
||||
if d.y > 0.0 && a.y >= a.x && a.y >= a.z {
|
||||
relief += panel(face_rho(d.y, d.x, d.z), rim);
|
||||
}
|
||||
|
||||
// Slot around the middle, stopping at the left panel
|
||||
let in_left_panel =
|
||||
if d.x < 0.0 { 1.0 - smooth(left_rim * (1.0 - SLOT_FADE), left_rim * (1.0 + SLOT_FADE), face_rho(-d.x, d.y, d.z)) } else { 0.0 };
|
||||
let slot_band = 1.0 - smooth(SLOT_HALF_WIDTH - SLOT_ROUNDING, SLOT_HALF_WIDTH + SLOT_ROUNDING, (d.y - SLOT_Y).abs());
|
||||
relief -= SLOT_DEPTH * slot_band * (1.0 - in_left_panel);
|
||||
|
||||
radius + relief
|
||||
}
|
||||
|
||||
/// 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) {
|
||||
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;
|
||||
for j in 0..segs {
|
||||
let a = j as f32 / segs as f32 * TAU;
|
||||
let (x, z) = (a.cos(), a.sin());
|
||||
// Top view: +X right, +Z down the texture; bottom view mirrors X.
|
||||
let uv = if up { r.map(0.5 + x * 0.5, 0.5 + z * 0.5) } else { r.map(0.5 + x * 0.5, 0.5 - z * 0.5) };
|
||||
b.vert(center + Vec3::new(x, 0.0, z) * radius, n, uv);
|
||||
}
|
||||
for j in 0..segs as u32 {
|
||||
let (a, bb) = (first + j, first + (j + 1) % segs as u32);
|
||||
if up {
|
||||
b.idx.extend_from_slice(&[c, bb, a]);
|
||||
} else {
|
||||
b.idx.extend_from_slice(&[c, a, bb]);
|
||||
}
|
||||
b.diag.push(0);
|
||||
}
|
||||
}
|
||||
|
||||
/// A capped cylinder along Y.
|
||||
pub fn cylinder(radius: f32, height: f32, segs: usize) -> Mesh {
|
||||
let mut b = Builder::default();
|
||||
let h = height * 0.5;
|
||||
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 {
|
||||
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;
|
||||
let theta = v * TAU;
|
||||
let dir = Vec3::new(phi.cos(), 0.0, -phi.sin());
|
||||
let n = dir * theta.cos() - Vec3::Y * theta.sin();
|
||||
(dir * major + n * minor, n, Vec2::new(u, v))
|
||||
});
|
||||
b.finish("Torus")
|
||||
}
|
||||
|
||||
/// A subdivided plane facing +Y.
|
||||
pub fn plane(size: f32, subdivisions: usize) -> Mesh {
|
||||
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))
|
||||
});
|
||||
b.finish("Plane")
|
||||
}
|
||||
|
||||
/// Two planes side by side on UV tiles 1001 and 1002 (UDIM): one material, 4 × 2 units.
|
||||
pub fn udim_plane() -> Mesh {
|
||||
let mut m = plane(2.0, 16);
|
||||
let mut right = m.clone();
|
||||
for p in &mut m.positions {
|
||||
p.x -= 1.0;
|
||||
}
|
||||
for p in &mut right.positions {
|
||||
p.x += 1.0;
|
||||
}
|
||||
for uv in &mut right.uvs {
|
||||
uv.x += 1.0;
|
||||
}
|
||||
right.materials.clear();
|
||||
right.submeshes.clear();
|
||||
m.append(&right);
|
||||
let count = m.indices.len() as u32;
|
||||
if let Some(s) = m.submeshes.first_mut() {
|
||||
s.count = count;
|
||||
}
|
||||
m
|
||||
}
|
||||
|
||||
/// The default project mesh: a ball on a beveled pedestal, two materials ("Ball", "Base").
|
||||
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 mut ball = ball.finish("Ball");
|
||||
|
||||
let mut base = Builder::default();
|
||||
let (r, top, bot, bev) = (1.05f32, 0.32f32, 0.0f32, 0.07f32);
|
||||
let mut profile = vec![(0.42, top + 0.06), (0.62, top + 0.06)];
|
||||
// Collar bevel and the ring the ball sits on, then the beveled drum.
|
||||
for k in 1..=6 {
|
||||
let a = k as f32 / 6.0 * PI * 0.5;
|
||||
profile.push((0.62 + 0.06 * a.sin(), top + 0.06 * a.cos()));
|
||||
}
|
||||
profile.push((r - bev, top));
|
||||
for k in 1..=6 {
|
||||
let a = k as f32 / 6.0 * PI * 0.5;
|
||||
profile.push((r - bev + bev * a.sin(), top - bev + bev * a.cos()));
|
||||
}
|
||||
profile.push((r, bot + bev));
|
||||
for k in 1..=6 {
|
||||
let a = k as f32 / 6.0 * PI * 0.5;
|
||||
profile.push((r - bev + bev * a.cos(), bot + bev - bev * a.sin()));
|
||||
}
|
||||
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 base = base.finish("Base");
|
||||
ball.append(&base);
|
||||
ball
|
||||
}
|
||||
|
||||
/// A small showcase scene: a beveled crate with a rounded lid and a cylinder handle, in three
|
||||
/// materials (used for demo projects and tests of multiple texture sets).
|
||||
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 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);
|
||||
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);
|
||||
}
|
||||
for n in &mut handle.normals {
|
||||
*n = Vec3::new(n.x, n.z, -n.y);
|
||||
}
|
||||
handle.materials = vec!["Handle".into()];
|
||||
if let Some(s) = handle.submeshes.first_mut() {
|
||||
s.name = "Handle".into();
|
||||
}
|
||||
handle.compute_tangents();
|
||||
m.append(&handle);
|
||||
m
|
||||
}
|
||||
|
||||
/// Built-in mesh by id (`builtin:<id>` in project files).
|
||||
pub fn builtin(id: &str) -> Option<Mesh> {
|
||||
Some(match id {
|
||||
"material_ball" | "materialball" | "ball" => material_ball(),
|
||||
"sphere" => sphere(1.0, 128, 64),
|
||||
"cube" => cube(2.0),
|
||||
"rounded_cube" | "roundedcube" | "box" => rounded_box(Vec3::ONE, 0.15),
|
||||
"cylinder" => cylinder(1.0, 2.0, 96),
|
||||
"torus" => torus(1.0, 0.35, 128, 48),
|
||||
"plane" => plane(2.0, 16),
|
||||
"crate" => crate_scene(),
|
||||
"udim_plane" | "udimplane" => udim_plane(),
|
||||
// Not offered for new projects (not in BUILTINS): the smart mask preview session's mesh
|
||||
"preview_orb" => preview_orb(),
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Ids accepted by [`builtin`], in menu order.
|
||||
pub const BUILTINS: [(&str, &str); 9] = [
|
||||
("material_ball", "Material ball"),
|
||||
("sphere", "Sphere"),
|
||||
("cube", "Cube"),
|
||||
("rounded_cube", "Rounded cube"),
|
||||
("cylinder", "Cylinder"),
|
||||
("torus", "Torus"),
|
||||
("plane", "Plane"),
|
||||
("crate", "Crate"),
|
||||
("udim_plane", "UDIM plane"),
|
||||
];
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Every triangle's winding agrees with its vertex normals, UVs stay in 0..1 (u in 0..max_u),
|
||||
/// and the UV mapping is not mirrored (tangent handedness +1).
|
||||
fn check(m: &Mesh, max_u: f32) {
|
||||
m.validate().unwrap();
|
||||
let mut bad = 0;
|
||||
for t in 0..m.triangle_count() {
|
||||
let [a, b, c] = m.tri(t).unwrap();
|
||||
let face = (m.positions[b] - m.positions[a]).cross(m.positions[c] - m.positions[a]);
|
||||
if face.length() < 1e-9 {
|
||||
continue;
|
||||
}
|
||||
let n = m.normals[a] + m.normals[b] + m.normals[c];
|
||||
if face.dot(n) <= 0.0 {
|
||||
bad += 1;
|
||||
}
|
||||
}
|
||||
assert_eq!(bad, 0, "{} triangles wound against their normals", bad);
|
||||
for uv in &m.uvs {
|
||||
assert!((0.0..=max_u).contains(&uv.x) && (0.0..=1.0).contains(&uv.y), "{uv:?}");
|
||||
}
|
||||
let mirrored = m.tangents.iter().filter(|t| t.w < 0.0).count();
|
||||
assert!(mirrored * 50 < m.tangents.len().max(1), "{mirrored} mirrored tangents");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn primitives_are_well_formed() {
|
||||
for (id, _) in BUILTINS {
|
||||
let m = builtin(id).unwrap();
|
||||
assert!(m.triangle_count() > 0, "{id}");
|
||||
check(&m, if id == "udim_plane" { 2.0 } else { 1.0 });
|
||||
}
|
||||
assert!(builtin("nope").is_none());
|
||||
assert_eq!(udim_plane().uv_tiles(0).into_iter().collect::<Vec<_>>(), vec![(0, 0), (1, 0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preview_orb_is_well_formed_with_domed_panels() {
|
||||
let m = preview_orb();
|
||||
check(&m, 1.0);
|
||||
|
||||
// Above the middle slot, the front panel's dome rises past the cut face and its valley
|
||||
// sits below it
|
||||
let front_depth = |rho: f32| {
|
||||
let d = Vec3::new(0.0, rho, 1.0).normalize();
|
||||
preview_orb_radius(d) * d.z
|
||||
};
|
||||
let rim = (1.0 - ORB_CUT * ORB_CUT).sqrt() / ORB_CUT;
|
||||
let (dome, valley) = (front_depth(0.2), front_depth(rim * ORB_PANEL_VALLEY));
|
||||
assert!(dome > ORB_CUT && valley < ORB_CUT - 0.05, "dome {dome}, valley {valley}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn material_ball_has_two_materials() {
|
||||
let m = material_ball();
|
||||
assert_eq!(m.materials, vec!["Ball".to_string(), "Base".to_string()]);
|
||||
assert!(m.triangles_of(0).count() > 0 && m.triangles_of(1).count() > 0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,384 @@
|
||||
//! Automatic UV unwrapping for meshes imported without texture coordinates.
|
||||
//!
|
||||
//! Triangles are grouped into charts by flood fill across shared (welded) edges while each face
|
||||
//! normal stays within 60° of the chart's seed face, so every chart is a height field over its
|
||||
//! seed plane and projects onto it without flipping. Charts are rotated to their principal axes
|
||||
//! and shelf-packed per material into 0..1 with one uniform scale, so texel density is the same
|
||||
//! everywhere within a material.
|
||||
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
|
||||
use glam::{Vec2, Vec3};
|
||||
|
||||
use crate::{GeomError, Mesh, Result};
|
||||
|
||||
/// Faces of a chart stay within this angle of the seed face normal (cos 60°).
|
||||
const CHART_COS: f32 = 0.5;
|
||||
/// Packing never goes beyond this virtual resolution (texels per side).
|
||||
const MAX_PACK_RES: f32 = 65_536.0;
|
||||
|
||||
/// Welded vertex id per vertex: vertices at the same position (snapped to a grid of 1e-6 of
|
||||
/// the bounding diagonal) share an id. Ids are dense, in order of first appearance.
|
||||
pub fn weld_ids(positions: &[Vec3]) -> Vec<u32> {
|
||||
let (lo, hi) = positions.iter().fold((Vec3::splat(f32::MAX), Vec3::splat(f32::MIN)), |(lo, hi), p| (lo.min(*p), hi.max(*p)));
|
||||
let cell = ((hi - lo).length() * 1e-6).max(1e-12);
|
||||
let mut map: HashMap<[i64; 3], u32> = HashMap::with_capacity(positions.len());
|
||||
positions
|
||||
.iter()
|
||||
.map(|p| {
|
||||
let q = ((*p - lo) / cell).round();
|
||||
let next = map.len() as u32;
|
||||
*map.entry([q.x as i64, q.y as i64, q.z as i64]).or_insert(next)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// True when the mesh has triangles and every one of them has two corners at the same position.
|
||||
/// MikkTSpace (and so [`Mesh::compute_tangents`]) crashes on such meshes, so callers reject them.
|
||||
pub fn all_triangles_degenerate(mesh: &Mesh) -> bool {
|
||||
let p = |i: &u32| mesh.positions.get(*i as usize);
|
||||
!mesh.indices.is_empty()
|
||||
&& mesh.indices.chunks(3).all(|t| match t {
|
||||
[a, b, c] => p(a) == p(b) || p(a) == p(c) || p(b) == p(c),
|
||||
_ => true,
|
||||
})
|
||||
}
|
||||
|
||||
struct Chart {
|
||||
material: usize,
|
||||
/// Projection basis (right-handed with the seed normal).
|
||||
t: Vec3,
|
||||
b: Vec3,
|
||||
/// Rotation to the chart's principal axes (cos, sin).
|
||||
rot: Vec2,
|
||||
lo: Vec2,
|
||||
hi: Vec2,
|
||||
/// Texel offset of the chart's packed rectangle and the material's scale and resolution.
|
||||
offset: Vec2,
|
||||
}
|
||||
|
||||
impl Chart {
|
||||
fn local(&self, p: Vec3) -> Vec2 {
|
||||
let q = Vec2::new(p.dot(self.t), p.dot(self.b));
|
||||
Vec2::new(q.x * self.rot.x - q.y * self.rot.y, q.x * self.rot.y + q.y * self.rot.x)
|
||||
}
|
||||
fn size(&self) -> Vec2 {
|
||||
(self.hi - self.lo).max(Vec2::ZERO)
|
||||
}
|
||||
}
|
||||
|
||||
/// Replace the UVs of `mesh` with an automatic non-overlapping layout: each material gets its
|
||||
/// own 0..1 space with charts at least `padding_texels` (minimum 1) away from each other and
|
||||
/// the borders at `resolution`. Vertices are split at chart borders; tangents are recomputed.
|
||||
/// Returns the number of charts.
|
||||
pub fn auto_unwrap(mesh: &mut Mesh, padding_texels: f32, resolution: u32) -> Result<usize> {
|
||||
mesh.validate_indices()?;
|
||||
if all_triangles_degenerate(mesh) {
|
||||
return Err(GeomError::Invalid("every triangle of the mesh is degenerate".into()));
|
||||
}
|
||||
if mesh.normals.len() != mesh.positions.len() {
|
||||
mesh.compute_normals();
|
||||
}
|
||||
let n = mesh.triangle_count();
|
||||
let weld = weld_ids(&mesh.positions);
|
||||
let pos = |v: usize| mesh.positions.get(v).copied().unwrap_or_default();
|
||||
let wid = |v: usize| weld.get(v).copied().unwrap_or(u32::MAX);
|
||||
|
||||
// Face normals (None for degenerate faces) and materials.
|
||||
let mut normal: Vec<Option<Vec3>> = Vec::with_capacity(n);
|
||||
let mut area = Vec::with_capacity(n);
|
||||
for t in 0..n {
|
||||
let [a, b, c] = mesh.tri(t).unwrap_or([0; 3]);
|
||||
let cr = (pos(b) - pos(a)).cross(pos(c) - pos(a));
|
||||
area.push(cr.length() * 0.5);
|
||||
normal.push(cr.try_normalize());
|
||||
}
|
||||
let mut material = vec![0usize; n];
|
||||
for s in &mesh.submeshes {
|
||||
for t in (s.start / 3) as usize..((s.start as usize + s.count as usize) / 3) {
|
||||
if let Some(m) = material.get_mut(t) {
|
||||
*m = s.material;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Manifold edge adjacency over welded vertices: edge → (face, face, count).
|
||||
let mut edges: HashMap<(u32, u32), (u32, u32, u8)> = HashMap::with_capacity(n * 2);
|
||||
let tri_edges = |t: usize| -> [(u32, u32); 3] {
|
||||
let [a, b, c] = mesh.tri(t).unwrap_or([0; 3]);
|
||||
let key = |x: usize, y: usize| {
|
||||
let (p, q) = (wid(x), wid(y));
|
||||
(p.min(q), p.max(q))
|
||||
};
|
||||
[key(a, b), key(b, c), key(c, a)]
|
||||
};
|
||||
for t in 0..n {
|
||||
for e in tri_edges(t) {
|
||||
if e.0 == e.1 {
|
||||
continue;
|
||||
}
|
||||
let slot = edges.entry(e).or_insert((t as u32, u32::MAX, 0));
|
||||
if slot.2 == 1 {
|
||||
slot.1 = t as u32;
|
||||
}
|
||||
slot.2 = slot.2.saturating_add(1);
|
||||
}
|
||||
}
|
||||
|
||||
// Grow charts from the largest unassigned faces.
|
||||
let mut order: Vec<usize> = (0..n).collect();
|
||||
order.sort_by(|a, b| area[*b].total_cmp(&area[*a]));
|
||||
let mut chart_of = vec![u32::MAX; n];
|
||||
let mut charts: Vec<Chart> = Vec::new();
|
||||
let mut queue = VecDeque::new();
|
||||
for &seed in &order {
|
||||
if chart_of[seed] != u32::MAX {
|
||||
continue;
|
||||
}
|
||||
let id = charts.len() as u32;
|
||||
let sn = normal[seed].unwrap_or(Vec3::Z);
|
||||
let t = sn.any_orthonormal_vector();
|
||||
charts.push(Chart { material: material[seed], t, b: sn.cross(t), rot: Vec2::X, lo: Vec2::ZERO, hi: Vec2::ZERO, offset: Vec2::ZERO });
|
||||
chart_of[seed] = id;
|
||||
queue.push_back(seed);
|
||||
while let Some(f) = queue.pop_front() {
|
||||
for e in tri_edges(f) {
|
||||
let Some(&(f0, f1, 2)) = edges.get(&e) else { continue };
|
||||
let g = if f0 as usize == f { f1 } else { f0 } as usize;
|
||||
let ok = normal.get(g).is_some_and(|nn| nn.is_none_or(|nn| nn.dot(sn) >= CHART_COS));
|
||||
if ok && chart_of.get(g) == Some(&u32::MAX) && material.get(g) == Some(&material[seed]) {
|
||||
chart_of[g] = id;
|
||||
queue.push_back(g);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Principal axes and bounds of every chart.
|
||||
let mut cov = vec![(Vec2::ZERO, [0.0f64; 3], 0usize); charts.len()];
|
||||
for (t, &c) in chart_of.iter().enumerate() {
|
||||
let c = c as usize;
|
||||
for v in mesh.tri(t).unwrap_or([0; 3]) {
|
||||
if let (Some(ch), Some(acc)) = (charts.get(c), cov.get_mut(c)) {
|
||||
let q = ch.local(pos(v));
|
||||
acc.0 += q;
|
||||
acc.1[0] += (q.x * q.x) as f64;
|
||||
acc.1[1] += (q.y * q.y) as f64;
|
||||
acc.1[2] += (q.x * q.y) as f64;
|
||||
acc.2 += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
for (ch, (sum, m, k)) in charts.iter_mut().zip(&cov) {
|
||||
let k = (*k).max(1) as f64;
|
||||
let (mx, my) = (sum.x as f64 / k, sum.y as f64 / k);
|
||||
let (cxx, cyy, cxy) = (m[0] / k - mx * mx, m[1] / k - my * my, m[2] / k - mx * my);
|
||||
let angle = 0.5 * (2.0 * cxy).atan2(cxx - cyy);
|
||||
// Rotate so the principal axis lies along x.
|
||||
ch.rot = Vec2::new((-angle).cos() as f32, (-angle).sin() as f32);
|
||||
ch.lo = Vec2::splat(f32::MAX);
|
||||
ch.hi = Vec2::splat(f32::MIN);
|
||||
}
|
||||
for (t, &c) in chart_of.iter().enumerate() {
|
||||
let c = c as usize;
|
||||
for v in mesh.tri(t).unwrap_or([0; 3]) {
|
||||
if let Some(ch) = charts.get_mut(c) {
|
||||
let q = ch.local(pos(v));
|
||||
ch.lo = ch.lo.min(q);
|
||||
ch.hi = ch.hi.max(q);
|
||||
}
|
||||
}
|
||||
}
|
||||
for ch in &mut charts {
|
||||
if ch.size().y > ch.size().x {
|
||||
// Quarter turn (x, y) → (y, −x) so shelves stay low.
|
||||
ch.rot = Vec2::new(ch.rot.y, -ch.rot.x);
|
||||
let (lo, hi) = (ch.lo, ch.hi);
|
||||
ch.lo = Vec2::new(lo.y, -hi.x);
|
||||
ch.hi = Vec2::new(hi.y, -lo.x);
|
||||
}
|
||||
}
|
||||
|
||||
// Pack each material's charts into its own 0..1 square.
|
||||
let pad = padding_texels.max(1.0);
|
||||
let mut scale = HashMap::new();
|
||||
let mats: std::collections::BTreeSet<usize> = charts.iter().map(|c| c.material).collect();
|
||||
for m in mats {
|
||||
let ids: Vec<usize> = (0..charts.len()).filter(|i| charts[*i].material == m).collect();
|
||||
let sizes: Vec<Vec2> = ids.iter().map(|i| charts[*i].size()).collect();
|
||||
let (s, res, offsets) = pack(&sizes, resolution.max(16) as f32, pad)?;
|
||||
for (i, o) in ids.iter().zip(offsets) {
|
||||
charts[*i].offset = o;
|
||||
}
|
||||
scale.insert(m, (s, res));
|
||||
}
|
||||
|
||||
// Rebuild vertices: one per (vertex, chart).
|
||||
let mut remap: HashMap<(u32, u32), u32> = HashMap::with_capacity(mesh.positions.len() * 2);
|
||||
let (mut positions, mut normals, mut uvs, mut colors) = (Vec::new(), Vec::new(), Vec::new(), Vec::new());
|
||||
let mut indices = Vec::with_capacity(mesh.indices.len());
|
||||
for (t, &c) in chart_of.iter().enumerate() {
|
||||
let Some(ch) = charts.get(c as usize) else { continue };
|
||||
let (s, res) = scale.get(&ch.material).copied().unwrap_or((0.0, 1.0));
|
||||
for v in mesh.tri(t).unwrap_or([0; 3]) {
|
||||
let idx = *remap.entry((v as u32, c)).or_insert_with(|| {
|
||||
let q = ch.local(pos(v));
|
||||
// Chart y points up; UV v points down the image.
|
||||
let texel = ch.offset + Vec2::splat(pad) + Vec2::new(q.x - ch.lo.x, ch.hi.y - q.y) * s;
|
||||
positions.push(pos(v));
|
||||
normals.push(mesh.normals.get(v).copied().unwrap_or(Vec3::Y));
|
||||
if let Some(c) = mesh.colors.get(v) {
|
||||
colors.push(*c);
|
||||
}
|
||||
uvs.push((texel / res).clamp(Vec2::ZERO, Vec2::ONE));
|
||||
(positions.len() - 1) as u32
|
||||
});
|
||||
indices.push(idx);
|
||||
}
|
||||
}
|
||||
mesh.positions = positions;
|
||||
mesh.normals = normals;
|
||||
mesh.uvs = uvs;
|
||||
mesh.colors = colors;
|
||||
mesh.indices = indices;
|
||||
mesh.compute_tangents();
|
||||
mesh.validate()?;
|
||||
Ok(charts.len())
|
||||
}
|
||||
|
||||
/// Shelf-pack rectangles of world `sizes` (each grown by `pad` texels per side) into a square of
|
||||
/// `res` texels with the largest uniform scale that fits. Returns (texels per world unit,
|
||||
/// resolution used, texel offset per rectangle). The resolution doubles when the padding alone
|
||||
/// cannot fit (very many charts), so the result always fits in 0..1.
|
||||
fn pack(sizes: &[Vec2], mut res: f32, pad: f32) -> Result<(f32, f32, Vec<Vec2>)> {
|
||||
let mut order: Vec<usize> = (0..sizes.len()).collect();
|
||||
order.sort_by(|a, b| sizes[*b].y.total_cmp(&sizes[*a].y));
|
||||
let place = |s: f32, res: f32| -> Option<Vec<Vec2>> {
|
||||
let mut out = vec![Vec2::ZERO; sizes.len()];
|
||||
let (mut x, mut y, mut shelf) = (0.0f32, 0.0f32, 0.0f32);
|
||||
for &i in &order {
|
||||
let r = sizes[i] * s + Vec2::splat(2.0 * pad);
|
||||
if r.x > res {
|
||||
return None;
|
||||
}
|
||||
if x + r.x > res {
|
||||
y += shelf;
|
||||
x = 0.0;
|
||||
shelf = 0.0;
|
||||
}
|
||||
if y + r.y > res {
|
||||
return None;
|
||||
}
|
||||
out[i] = Vec2::new(x, y);
|
||||
x += r.x;
|
||||
shelf = shelf.max(r.y);
|
||||
}
|
||||
Some(out)
|
||||
};
|
||||
while place(0.0, res).is_none() {
|
||||
res *= 2.0;
|
||||
if res > MAX_PACK_RES {
|
||||
return Err(GeomError::Invalid("too many UV charts to pack".into()));
|
||||
}
|
||||
}
|
||||
let largest = sizes.iter().map(|s| s.max_element()).fold(0.0f32, f32::max);
|
||||
if largest <= 0.0 {
|
||||
return Ok((0.0, res, place(0.0, res).unwrap_or_default()));
|
||||
}
|
||||
let (mut lo, mut hi) = (0.0f32, (res - 2.0 * pad).max(0.0) / largest);
|
||||
if place(hi, res).is_some() {
|
||||
lo = hi;
|
||||
}
|
||||
for _ in 0..40 {
|
||||
if hi - lo <= lo * 1e-4 {
|
||||
break;
|
||||
}
|
||||
let mid = 0.5 * (lo + hi);
|
||||
if place(mid, res).is_some() { lo = mid } else { hi = mid }
|
||||
}
|
||||
Ok((lo, res, place(lo, res).unwrap_or_default()))
|
||||
}
|
||||
|
||||
impl Mesh {
|
||||
/// Index-range checks only (attribute arrays may be incomplete before unwrapping).
|
||||
fn validate_indices(&self) -> Result<()> {
|
||||
let n = self.positions.len();
|
||||
if !self.indices.len().is_multiple_of(3) || self.indices.iter().any(|i| *i as usize >= n) {
|
||||
return Err(GeomError::Invalid("mesh indices are out of range".into()));
|
||||
}
|
||||
if self.triangle_count() > crate::MAX_TRIANGLES {
|
||||
return Err(GeomError::Invalid(format!("mesh has more than {} triangles", crate::MAX_TRIANGLES)));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{UvGBuffer, primitives};
|
||||
|
||||
fn check(mut m: Mesh, min_coverage: f32) {
|
||||
m.uvs.clear();
|
||||
let charts = auto_unwrap(&mut m, 4.0, 512).unwrap();
|
||||
assert!(charts >= 1);
|
||||
m.validate().unwrap();
|
||||
assert!(m.uvs.iter().all(|uv| (0.0..=1.0).contains(&uv.x) && (0.0..=1.0).contains(&uv.y)));
|
||||
let g = UvGBuffer::new(&m, 0, 512, 512);
|
||||
let covered = g.covered_count() as f32;
|
||||
let coverage = covered / (512.0 * 512.0);
|
||||
assert!(coverage > min_coverage, "coverage {coverage} with {charts} charts");
|
||||
assert!((g.overlaps as f32) < covered * 0.005, "overlaps {} of {covered}", g.overlaps);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sphere_unwraps_without_overlaps() {
|
||||
check(primitives::sphere(1.0, 48, 24), 0.3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cube_unwraps_without_overlaps() {
|
||||
check(primitives::cube(2.0), 0.3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn torus_and_material_ball_unwrap() {
|
||||
check(primitives::torus(1.0, 0.3, 48, 24), 0.2);
|
||||
let mut ball = primitives::material_ball();
|
||||
ball.uvs.clear();
|
||||
auto_unwrap(&mut ball, 2.0, 1024).unwrap();
|
||||
for m in 0..ball.materials.len() {
|
||||
let g = UvGBuffer::new(&ball, m, 512, 512);
|
||||
assert!((g.overlaps as f32) < g.covered_count() as f32 * 0.005 + 1.0, "material {m}: {} overlaps", g.overlaps);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn many_tiny_charts_still_fit() {
|
||||
// 2000 disconnected triangles: the packer grows its virtual resolution.
|
||||
let mut p = Vec::new();
|
||||
let mut idx = Vec::new();
|
||||
for i in 0..2000u32 {
|
||||
let o = Vec3::new(i as f32 * 3.0, 0.0, 0.0);
|
||||
p.extend([o, o + Vec3::X, o + Vec3::Y]);
|
||||
idx.extend([i * 3, i * 3 + 1, i * 3 + 2]);
|
||||
}
|
||||
let mut m = Mesh::from_parts(p, None, Vec::new(), idx, "m").unwrap();
|
||||
auto_unwrap(&mut m, 4.0, 128).unwrap();
|
||||
assert!(m.uvs.iter().all(|uv| (0.0..=1.0).contains(&uv.x) && (0.0..=1.0).contains(&uv.y)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn degenerate_and_empty_meshes_do_not_fail() {
|
||||
let mut empty = Mesh::default();
|
||||
assert_eq!(auto_unwrap(&mut empty, 4.0, 256).unwrap(), 0);
|
||||
// A sliver (zero-area) triangle next to a real one.
|
||||
let p = vec![Vec3::ZERO, Vec3::X, Vec3::Y, Vec3::X * 2.0];
|
||||
let mut m = Mesh::from_parts(p, None, Vec::new(), vec![0, 1, 2, 0, 1, 3], "m").unwrap();
|
||||
auto_unwrap(&mut m, 4.0, 256).unwrap();
|
||||
m.validate().unwrap();
|
||||
let mut point = Mesh { positions: vec![Vec3::ONE; 3], indices: vec![0, 1, 2], ..Mesh::default() };
|
||||
assert!(all_triangles_degenerate(&point));
|
||||
assert!(auto_unwrap(&mut point, 4.0, 256).is_err());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user