Repository navigation
Conversation
The bake takes a triangle's bitangent sign from its first corner, the viewport interpolates tan.w; they agree only when the corners agree. compute_tangents wrote MikkTSpace's per-corner tangents into the vertex, so the last face won: where mirrored UVs meet at a shared vertex, the other face's triangles mixed signs (127 of 4096 triangles on a sphere with mirrored UVs). MikkTSpace also gives a vertex used only by zero-area triangles its fallback frame with w = -1, which mixed the UV sphere's pole triangle on the seam. compute_tangents now collects the tangents per corner and gives each distinct tangent of a vertex its own copy of the vertex (same position, normal, UV, color), as MikkTSpace expects. Corners of a triangle that still disagree, only possible in zero-area triangles, take the first corner's sign. Meshes without such vertices come out unchanged. Tests: every corner keeps MikkTSpace's frame and every triangle one sign (bowtie with a mirrored half, UV sphere); a bowtie baked from a tilted plane decodes in the viewport's frame within 0.1 degrees, 40.7 before.
|
Important Draft PR not reviewedDraft PRs are not automatically reviewed by default.
To automatically review draft PRs, update your CodeRabbit configuration: reviews:
auto_review:
drafts: true
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. CodeRabbit Verify
|
|
I'm taking this one for review. |
|
Review notes (prepared with Claude Code) PR #277Verdict: merge after a small rework. The fix is correct and follows the published MikkTSpace algorithm: each triangle corner gets its own frame, and a vertex is split where its corners disagree. Three things to change. What I checked
Changes requested
The patch below does all three (its own cost is about +5-8% over main, estimated from noisy runs, against +3-5% for the PR as submitted) and adds two tests ( Notes
Patch: reached-corner sign rule, as_chunks and a 17-byte corner bufferThe changes described above, as a patch you can apply ( Show the patchFrom 491eb427e2cb34ca01031b20c978bb41ea5bfa9a Mon Sep 17 00:00:00 2001
From: SteamSmith <341182916+SteamSmith@users.noreply.github.com>
Date: Tue, 10 Nov 2026 09:47:13 -0500
Subject: [PATCH] fix(#277): sign of reached corners, as_chunks, 16-byte corner
buffer
A triangle MikkTSpace cannot orient is not only a zero-area one: a
triangle with area but collapsed UVs keeps mikktspace's untouched frame
(w = -1) on every corner no neighbour group reaches. Neither the first
corner's sign nor the majority sign picks the neighbours' sign in every
case (first corner fails when the untouched corner comes first; majority
fails when two corners are untouched), and each wrong pick splits the
shared vertices and shows hidden polygon diagonals. Record which corners
mikktspace reached (set_tangent sees the untouched frame) and take their
sign.
Store corners as Vec<Vec4> (16 bytes) plus a reached flag instead of
Option<Vec4> (32 bytes): mikktspace writes every corner when it succeeds.
Use as_chunks, which clippy on current stable requires.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---
crates/geom/src/mesh.rs | 128 +++++++++++++++++++++++++++++++++-------
1 file changed, 106 insertions(+), 22 deletions(-)
diff --git a/crates/geom/src/mesh.rs b/crates/geom/src/mesh.rs
index 1c121ec..0e19cf9 100644
--- a/crates/geom/src/mesh.rs
+++ b/crates/geom/src/mesh.rs
@@ -223,9 +223,10 @@ impl Mesh {
/// then build the same frame. Copies keep the vertex's position, normal, UV and color, so
/// nothing but the vertex count changes.
///
- /// A zero-area triangle can still get corners of both signs: a vertex no other triangle
- /// uses gets MikkTSpace's fallback frame (w = −1), e.g. at a UV sphere's pole on the seam.
- /// Such corners take the sign of the triangle's first corner.
+ /// A triangle MikkTSpace cannot orient can still get corners of both signs: a zero-area
+ /// triangle, or one with area but collapsed UVs. A corner MikkTSpace never reaches keeps
+ /// its untouched frame (w = −1), e.g. at a UV sphere's pole on the seam. Such a triangle's
+ /// corners all take the sign of its reached corners ([`triangle_sign`]).
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() {
@@ -236,13 +237,12 @@ impl Mesh {
}
// 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, corners: vec![None; self.indices.len()] };
+ let mut g = Mikk { mesh: self, corners: vec![UNTOUCHED_CORNER; self.indices.len()], reached: vec![false; self.indices.len()] };
if usable && mikktspace::generate_tangents(&mut g) {
- let mut corners = g.corners;
- for triangle in corners.chunks_exact_mut(3) {
- if let Some(Some(first)) = triangle.first().copied() {
- triangle.iter_mut().flatten().for_each(|t| t.w = first.w);
- }
+ let (mut corners, reached) = (g.corners, g.reached);
+ for (triangle, reached) in corners.as_chunks_mut::<3>().0.iter_mut().zip(reached.as_chunks::<3>().0) {
+ let w = triangle_sign(triangle, reached);
+ triangle.iter_mut().for_each(|t| t.w = w);
}
self.split_by_corner_tangents(&corners);
} else {
@@ -257,13 +257,12 @@ impl Mesh {
}
/// Give every index its corner's tangent: the first corner of a vertex sets its tangent,
- /// and each further distinct tangent gets a copy of the vertex. Corners without a tangent
- /// keep their vertex.
- fn split_by_corner_tangents(&mut self, corners: &[Option<Vec4>]) {
+ /// and each further distinct tangent gets a copy of the vertex.
+ fn split_by_corner_tangents(&mut self, corners: &[Vec4]) {
let mut first: Vec<Option<Vec4>> = vec![None; self.positions.len()];
let mut copies: std::collections::HashMap<(u32, [u32; 4]), u32> = std::collections::HashMap::new();
for (k, tangent) in corners.iter().enumerate() {
- let (Some(tangent), Some(&v)) = (tangent, self.indices.get(k)) else { continue };
+ let Some(&v) = self.indices.get(k) else { continue };
let Some(seen) = first.get_mut(v as usize) else { continue };
let vertex = match seen {
None => {
@@ -447,10 +446,39 @@ impl Mesh {
}
}
+/// The tangent frame mikktspace 0.3 gives a corner it never reaches (`genTangSpace` fills its
+/// frames with this before grouping): tangent +X, bitangent +Y, both magnitudes 1, not
+/// orientation preserving, so w = −1.
+const UNTOUCHED_TANGENT: [f32; 3] = [1.0, 0.0, 0.0];
+/// The untouched frame's bitangent; see [`UNTOUCHED_TANGENT`].
+const UNTOUCHED_BITANGENT: [f32; 3] = [0.0, 1.0, 0.0];
+/// The untouched frame's tangent and bitangent magnitudes; see [`UNTOUCHED_TANGENT`].
+const UNTOUCHED_MAGNITUDE: f32 = 1.0;
+/// The untouched frame as `set_tangent_encoded` would see it.
+const UNTOUCHED_CORNER: Vec4 = Vec4::new(1.0, 0.0, 0.0, -1.0);
+
+/// The bitangent sign all corners of a triangle take: the sign most of the corners MikkTSpace
+/// reached carry (the first reached corner's on a tie), or the first corner's when it reached
+/// none. Only a triangle MikkTSpace cannot orient (zero area, or collapsed UVs) mixes signs;
+/// its unreached corners carry the untouched w = −1, which says nothing about its neighbours.
+fn triangle_sign(corners: &[Vec4; 3], reached: &[bool; 3]) -> f32 {
+ let signs: Vec<f32> = corners.iter().zip(reached).filter(|(_, r)| **r).map(|(t, _)| t.w).collect();
+ let Some(&first) = signs.first() else { return corners[0].w };
+ let positive = signs.iter().filter(|w| **w >= 0.0).count();
+ match positive.cmp(&(signs.len() - positive)) {
+ std::cmp::Ordering::Greater => 1.0,
+ std::cmp::Ordering::Less => -1.0,
+ std::cmp::Ordering::Equal => first,
+ }
+}
+
/// MikkTSpace's view of a mesh; it writes each triangle corner's tangent to `corners`.
struct Mikk<'a> {
mesh: &'a Mesh,
- corners: Vec<Option<Vec4>>,
+ /// Each triangle corner's tangent, w the bitangent sign (16 bytes per corner)
+ corners: Vec<Vec4>,
+ /// Whether MikkTSpace gave the corner a frame (false: it kept the untouched one)
+ reached: Vec<bool>,
}
impl Mikk<'_> {
@@ -478,9 +506,19 @@ impl mikktspace::Geometry for Mikk<'_> {
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) {
- if let Some(t) = face.checked_mul(3).and_then(|k| k.checked_add(vert)).and_then(|k| self.corners.get_mut(k)) {
- *t = Some(Vec4::from_array(tangent));
+ /// Record the corner's tangent with its sign, and whether MikkTSpace reached it.
+ fn set_tangent(&mut self, tangent: [f32; 3], bi_tangent: [f32; 3], f_mag_s: f32, f_mag_t: f32, preserves_orientation: bool, face: usize, vert: usize) {
+ let Some(k) = face.checked_mul(3).and_then(|k| k.checked_add(vert)) else { return };
+ if let Some(t) = self.corners.get_mut(k) {
+ *t = Vec3::from_array(tangent).extend(if preserves_orientation { 1.0 } else { -1.0 });
+ }
+ let untouched = tangent == UNTOUCHED_TANGENT
+ && bi_tangent == UNTOUCHED_BITANGENT
+ && f_mag_s == UNTOUCHED_MAGNITUDE
+ && f_mag_t == UNTOUCHED_MAGNITUDE
+ && !preserves_orientation;
+ if let Some(r) = self.reached.get_mut(k) {
+ *r = !untouched;
}
}
}
@@ -531,13 +569,59 @@ mod tests {
Mesh { indices, ..mesh.clone() }
}
+ /// MikkTSpace's tangent for every triangle corner of `mesh`, and whether it reached the corner
+ fn mikktspace_frames(mesh: &Mesh) -> (Vec<Vec4>, Vec<bool>) {
+ let mut g = Mikk { mesh, corners: vec![UNTOUCHED_CORNER; mesh.indices.len()], reached: vec![false; mesh.indices.len()] };
+ assert!(mikktspace::generate_tangents(&mut g));
+ (g.corners, g.reached)
+ }
+
/// MikkTSpace's tangent for every triangle corner of `mesh`
fn mikktspace_corners(mesh: &Mesh) -> Vec<Vec4> {
- let mut g = Mikk { mesh, corners: vec![None; mesh.indices.len()] };
- assert!(mikktspace::generate_tangents(&mut g));
- g.corners.into_iter().map(Option::unwrap).collect()
+ mikktspace_frames(mesh).0
+ }
+
+ /// A triangle A = (0, 1, 2) with real UVs, and two triangles with area whose UVs collapse
+ /// onto the line v = 0.5: C1 = (3, 1, 0) shares A's edge 0-1, C2 = (0, 4, 3) shares C1's
+ /// edge 0-3. MikkTSpace reaches C1 at 0 and 1 (from A) and C2 at 0 only; vertices 3 and 4
+ /// belong to no triangle it can orient. A's UVs are mirrored, so A has w = +1 and the
+ /// untouched corners w = −1: C1's first corner is untouched, C2's only reached one is first.
+ fn collapsed_uv_fan() -> Mesh {
+ let positions = vec![Vec3::ZERO, Vec3::X, Vec3::Z, Vec3::new(0.5, 0.0, -1.0), Vec3::new(-1.0, 0.0, -0.5)];
+ let uvs = vec![Vec2::new(0.0, 0.5), Vec2::new(0.5, 0.5), Vec2::new(0.0, 0.0), Vec2::new(0.25, 0.5), Vec2::new(0.75, 0.5)];
+ Mesh::from_parts(positions, Some(vec![Vec3::Y; 5]), uvs, vec![0, 1, 2, 3, 1, 0, 0, 4, 3], "Fan").unwrap()
+ }
+
+ /// Triangles with area but collapsed UVs take the sign MikkTSpace gave their reached
+ /// corners, whichever corner comes first and however many corners it left untouched, so
+ /// no vertex they share with a real triangle is split and no polygon diagonal shows.
+ #[test]
+ fn collapsed_uv_triangles_take_their_reached_corners_sign() {
+ let m = collapsed_uv_fan();
+ let (raw, reached) = mikktspace_frames(&m);
+ assert_eq!(raw.iter().map(|t| t.w).collect::<Vec<_>>(), [1.0, 1.0, 1.0, -1.0, 1.0, 1.0, 1.0, -1.0, -1.0], "MikkTSpace mixes C1 and C2");
+ assert_eq!(reached, [true, true, true, false, true, true, true, false, false]);
+ assert!(m.indices.iter().all(|v| m.tangents[*v as usize].w == 1.0), "every corner takes A's sign: {:?}", m.tangents);
+ assert_eq!(m.vertex_count(), 5, "no vertex is split");
+ let mut shown = m.clone();
+ shown.diagonals = vec![0b001, 0b010, 0];
+ assert!(!shown.wire_edges()[0].contains(&(0, 1)), "the diagonal A and C1 share stays hidden");
+ }
+
+ /// The sign of most reached corners wins, the first reached one on a tie; untouched
+ /// corners count only when no corner was reached.
+ #[test]
+ fn triangle_sign_follows_the_reached_corners() {
+ let t = |w: f32| Vec4::new(1.0, 0.0, 0.0, w);
+ assert_eq!(triangle_sign(&[t(-1.0), t(1.0), t(1.0)], &[false, true, true]), 1.0);
+ assert_eq!(triangle_sign(&[t(1.0), t(-1.0), t(-1.0)], &[true, false, false]), 1.0);
+ assert_eq!(triangle_sign(&[t(-1.0), t(1.0), t(-1.0)], &[true, true, true]), -1.0);
+ assert_eq!(triangle_sign(&[t(-1.0), t(1.0), t(-1.0)], &[false, true, true]), 1.0);
+ assert_eq!(triangle_sign(&[t(1.0), t(-1.0), t(-1.0)], &[false, false, false]), 1.0);
}
+ /// After `compute_tangents`, every triangle corner of a bowtie with a mirrored half and of a
+ /// UV sphere carries MikkTSpace's own frame for that corner, and no triangle mixes signs.
#[test]
fn every_triangle_corner_keeps_its_mikktspace_frame() {
for (name, split) in [("bowtie", bowtie()), ("UV sphere", crate::primitives::sphere(1.0, 32, 16))] {
@@ -545,12 +629,12 @@ mod tests {
let corners = mikktspace_corners(&unsplit);
let shared = || unsplit.indices.iter().zip(&corners);
let vertex_needs_two_signs = shared().any(|(v, t)| shared().any(|(u, s)| u == v && s.w != t.w));
- let triangle_mixes_signs = corners.chunks_exact(3).any(|c| c.iter().any(|t| t.w != c[0].w));
+ let triangle_mixes_signs = corners.as_chunks::<3>().0.iter().any(|c| c.iter().any(|t| t.w != c[0].w));
assert!(vertex_needs_two_signs || triangle_mixes_signs, "{name}: one tangent per vertex would mix signs in a triangle");
let mut m = unsplit.clone();
m.compute_tangents();
m.validate().unwrap();
- for (t, (tri, wanted)) in m.indices.chunks_exact(3).zip(corners.chunks_exact(3)).enumerate() {
+ for (t, (tri, wanted)) in m.indices.as_chunks::<3>().0.iter().zip(corners.as_chunks::<3>().0).enumerate() {
let w = tri.iter().map(|v| m.tangents[*v as usize].w).collect::<Vec<_>>();
assert!(w.iter().all(|sign| Some(sign) == w.first()), "{name}: triangle {t} mixes bitangent signs {w:?}");
let [a, b, c] = unsplit.tri(t).unwrap().map(|v| unsplit.positions[v]);
--
2.55.0.windows.5🤖 Generated with Claude Code |
Clippy on current stable rejects chunks_exact with a constant chunk size; main moved to as_chunks in storytold#234. The three chunks_exact calls this change added now use as_chunks. The older ones elsewhere in the file are left for main's version to replace.
Zero-area triangles are not the only ones whose corners can mix bitangent signs. A triangle with area but collapsed UVs can too: MikkTSpace cannot orient it, so it gets a frame only at the corners a neighbouring group reaches. Every other corner keeps the initial frame (tangent +X, w = -1). Taking the first corner's sign spreads that placeholder when the unreached corner comes first. Taking the majority fails when two corners are unreached. Either way the triangle's vertices split away from the real neighbours and a hidden polygon diagonal shows in the wireframe. For a real triangle with two collapsed-UV neighbours, the first-corner rule gives 8 vertices and the majority rule 7, where 5 is right. Implement set_tangent instead of set_tangent_encoded, so the initial frame is visible, and record whether each corner was reached. A triangle then takes the sign most of its reached corners carry, the first reached corner's sign on a tie, and its first corner's sign when none was reached. The vote does not allocate. MikkTSpace writes every corner when it succeeds, so corners are stored as Vec<Vec4> plus a reached flag (17 bytes per corner) instead of Option<Vec4> (32 bytes). Tests: collapsed-UV triangles keep their neighbour's sign, split no vertex and keep the shared diagonal hidden (fails under the first-corner and majority rules), and a unit test of the sign vote.
|
Thanks @SteamSmith. I checked each point against
Timing: on a 1M-triangle sphere (5 rounds of 7 runs, shared machine), main took 656 ms, the PR as submitted 666 ms and the PR now 652 ms. That's within noise, so the description no longer claims +5%. Your notes:
I ran the geom and bake tests (81 passed), the engine package with |
|
The |
Main hands MikkTSpace the importer's quads as four-corner faces. Each face now knows its first triangle, and a quad corner's frame goes to every triangle corner it stands for (both triangles' copies of the shared corners), so the corner signs and vertex splits work for quads too.
Cause
The bake and the viewport build a triangle's tangent frame from the same per-vertex tangents, but they take the bitangent sign
wdifferently.geom::surface_at, and so the bake and both path tracers, takes it from the triangle's first corner.shade_meshinterpolatestan.w, which shortens the bitangent and flips it past the midpoint. They agree only when a triangle's three corners carry the same sign, andMesh::compute_tangentsdid not guarantee that, in two ways:set_tangent_encodedwrote it into the vertex, so the last face written won. Where faces with opposite UV orientation share a vertex (the line where mirrored UVs meet, the common case for symmetric models), the shared vertex kept one face's sign, and the other face's triangles came out with mixed corners. On a 64 × 32 sphere with its UVs mirrored about the middle, 127 of 4096 triangles were mixed.(1, 0, 0, −1)instead. The UV sphere's pole vertex on the u seam is one: the pole triangle holding it has corners (+1, +1, −1). This triangle covers 64 texels of a 256² map. It has zero area on the mesh, but it has UV area, so the bake fills those texels. The material ball has the same case.(1, 0, 0, −1).On a minimal mixed triangle the viewport decoded the bake up to 40.7° off; on the sphere's seam texels, 0.67°.
Fix
compute_tangentskeeps MikkTSpace's frame per corner, then splits vertices so that every corner keeps it:set_tangentrecords which corners MikkTSpace reached. Taking the first corner's sign, or the majority over all corners, would spread the placeholder sign of an unreached corner and split vertices that the triangle shares with real triangles. On a small repro (one real triangle and two collapsed-UV triangles), first-corner gives 8 vertices, majority 7 and reached corners 5.Vec<Vec4>plus a reached flag (17 bytes per corner). MikkTSpace writes every corner when it succeeds.I fixed the data rather than the shader. A flat per-triangle sign in the viewport (
@interpolate(flat)onw) would make the viewport agree with the bake on any data. But the exported mesh and normal map would still disagree with tools that recompute MikkTSpace per corner, and flat interpolation's provoking vertex is not portable to the WebGL backend the web build uses. With consistent data, the bake, the viewport, the path tracers and the subdivided displacement mesh all build the same frame, and the existing interpolation is exact.Verified
New test in
crates/geom/src/mesh.rs:every_triangle_corner_keeps_its_mikktspace_frame. It runs on a "bowtie" (two coplanar triangles sharing only their apex, the second with mirrored UVs) and on the 32 × 16 UV sphere, each welded back to its unsplit layout. Every triangle's corners must agree on the sign, every corner must keep its position, normal and UV, and every corner of a triangle with area must have exactly MikkTSpace's tangent and sign. Runningcompute_tangentsagain must not split anything more.New test in
crates/bake/src/tests.rs:mirrored_triangles_sharing_a_vertex_decode_in_the_viewport_as_baked. It bakes the bowtie from a tilted plane and decodes every covered texel in the viewport's frame (interpolated normal, tangent andw). Every texel must be within 0.1° of the plane's normal. Before the fix: 40.72° off.The reference suite from Bake: analytic reference scenes for the mesh-map baker #279, run here on top of this branch but not committed:
mixed_tangent_signs_decode_like_the_viewportbuilds the bowtie and takes its tangents fromcompute_tangents. It fails onmain(40.72° on the CPU and the GPU tracer) and passes here on both at 0.00°.Vertex counts:
The zero-area pole triangles only change sign, so they add no vertices.
New tests:
collapsed_uv_triangles_take_their_reached_corners_signandtriangle_sign_follows_the_reached_corners. Both fail under the first-corner rule and under the majority rule.compute_tangentson a 1M-triangle sphere (release, 5 rounds of 7 runs on a shared machine): 656 ms on main, 652 ms with this PR. That is within noise, so I can't claim a difference either way.Ran: geom and bake tests, the engine package with
panic_hunt, fmt,cargo xtask wasmandcargo xtask layers. I haven't re-runcargo +1.96.0 xtask cisince the review changes.Not changed
Meshkeeps one tangent per vertex; only the vertex count can grow, and only where frames differ..tcraftstores the source mesh file and imports it again on load, so existing projects get the split layout when they open. Painted data is per texel, and most of the code that relates meshes works from positions, UVs or triangle corners, not vertex numbers: UV-island fill, preserve strokes on reimport, the custom cage (matched by triangle), and the bake's welded ray normals. None of it changes. The exception is polygon fill's Polygon mode on main, which keys diagonals by vertex index. Where a split crosses a polygon diagonal (a quad whose two triangles have opposite UV orientation), that polygon fills as two groups. Keyingpolygon_edgesby position, asposition_edgesalready does, would fix it in a few lines once this lands.wire_edgesdraws it even if it is a polygon diagonal, the same as for an edge on a UV seam (and polygon fill groups across it, see above). On mirrored models that boundary is the mirror line, which is usually made of real edges.tan.w. On consistent data that is exact.