Skip to content

The native runtime for three.js: three.js, down to the metal. 45× smaller than Electron, on a Sony PS3, and path-traced at 60 fps on ray-tracing GPUs.

A tangent is a vertex's: interpolated at the hit, made for a model that has none (#197)

Yujia54d779f9dbef
diff --git a/docs/MATERIAL_FUNCTIONS.md b/docs/MATERIAL_FUNCTIONS.md
index 84d57a9..6487657 100644
--- a/docs/MATERIAL_FUNCTIONS.md
+++ b/docs/MATERIAL_FUNCTIONS.md
@@ -75,7 +75,7 @@ or only adjust a part.
|---|---|
| `wp` | world position (m) |
| `n`, `ng` | vertex / geometric normal, facing the viewer |
-| `t`, `b` | tangent (+u), bitangent (image up) |
+| `t`, `b` | tangent (+u), bitangent (image up): the surface's own at the point (a model's vertices', a file's or made for it) or, for geometry without tangents, its triangle's |
| `uv`, `uvd` | mesh UV0 (v down); `exp2(uvd)` = UV units per metre (pass it to `msample` for the mip) |
| `view` | unit vector toward the ray origin |
| `op`, `ob` | object pivot and world bounds size (UE `ObjectPositionWS` / `ObjectBounds`) |
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md
index 8da98e5..9b0a8c9 100644
--- a/docs/ROADMAP.md
+++ b/docs/ROADMAP.md
@@ -2776,6 +2776,30 @@ in-place tests' world, rows given back; two models in a shared pose posed again
(tests/render/data/arm.glb, a skinned strip of two materials); `geometry/emitter-model-live` (a model's emitting
section that is not its first, the model a unit under software traversal).
+**A tangent is a vertex's (2026-11-23).** A triangle had one tangent, its first corner's, and a model whose file
+had none had its frame made a triangle at a time where it was hit: a normal map's detail turned at every edge of a
+curved surface. Now each corner of a file's triangle carries its own through the build, corners that differ in
+tangent are vertices apart, and the kernel takes a hit's tangent from its three vertices at the hit (the hand from
+the first). A primitive of a file with UVs and no tangents has them made where it is loaded, as the glTF
+specification says, by MikkTSpace (`tangents.rs`, on `bevy_mikktspace`, a crate without dependencies), a corner
+each. Made for every such primitive, not only where a material reads a frame: 1.4 to 2.9 M triangles a second on
+one thread, and 0 to 0.4 % more vertices on the files measured, so a material that starts reading a frame needs
+no rebuild. Against the tangents two sample files carry themselves, 897,150 corners: 3 more than a degree off, none
+of the other hand. A scene's own geometries, which have no tangent attribute, keep the frame made at the hit.
+Pictures: offline at 8 samples against the build before, three scenes without normal-mapped models are the same
+bytes; the home showcase (models without tangents under normal maps) differs in 5.4 % of its pixels, by 0.08 steps
+in the mean; the museum in 1.2 %. A frame's GPU time in twelve scenes, one run against the build before: between
+-1.2 % and +0.6 %, which one run does not tell from none.
+Tests: a quad whose file has a tangent of its own on each side, by the gradient a function draws of it
+(`material/function-vertex-tangents`: 1 with one tangent a triangle); two quads whose file gives one hand each, by
+the side their bitangent points to (`material/function-file-hand`); the tangents made for a quad, upright and
+mirrored, and for a primitive whose texture mirrors along an edge (the edge's vertices twice, their joints and
+weights with them); corners apart by tangent or by hand, a skinned mesh's too; a model's triangles, its skin's
+corners and a placed triangle each with a tangent a corner, under a mirroring placement too.
+Mutations: 18 (15 of the build, 3 of the kernel). 15 failed a test there was; one, a hand never read at a hit, none,
+and has the hand's test now; one, a corner without a tangent that says it has one, none, and is asserted now; one
+changed nothing: a branch of the generator that its last pass repeats, removed.
+
**The kernel's loops are bounded (2026-11-23).** The kernel was the one shader compiled without wgpu's loop
bounding (every loop given a count its compiler can see the end of); every other pass has it. Its loops end on
sound data, which is no promise to a compiler that they end. Without the bound, the kernels Metal's compiler made
diff --git a/docs/RUNTIME.md b/docs/RUNTIME.md
index 59507a8..948b6d6 100644
--- a/docs/RUNTIME.md
+++ b/docs/RUNTIME.md
@@ -1555,7 +1555,7 @@ The kernel's read-only scene data other than triangles is two storage buffers, e
Vertices and indices, one layout for hardware and software traversal (`renderer/src/indexed.rs`):
- **Vertices.** `vertices` (binding 1): a record of 48 bytes a vertex, (position, u), (normal, v), (tangent, hand;
- zeros: none). The BLASes are built from this buffer too (stride 48).
+ a hand of 0: none). The BLASes are built from this buffer too (stride 48).
- **Triangles.** Three indices each, a section of `words` (`Stream::Indices`): what a hit reads, and the BLASes'
index buffer. A mesh's indices count from the mesh's first vertex, which its instances' records carry
(`info.z`); a world-space triangle's count from 0.
@@ -1573,12 +1573,16 @@ Vertices and indices, one layout for hardware and software traversal (`renderer/
the section (a tree has a mesh's triangles in its own order). Written at the build and where an edit places a
mesh; after the skinning pass a pass takes a posed mesh's again from its vertices (`leaf_gather.wgsl`).
- **A hit reads** its triangle's indices and its three vertices' records (`tri_data(triangle, instance, part)`).
-- **What shares.** Corners equal bit for bit in position, normal and UV are one vertex: the still world-space
- triangles among themselves, each mesh within itself, a skinned mesh by its model's corners. Triangles the CPU or
- a pass writes whole (those that move in world space, particles) keep three vertices each.
-- **Tangents.** A triangle's frame is its first vertex's tangent where its file has one (a first corner never
- shares a vertex with a triangle of another tangent), else made where it is hit, from its edges, its UVs and its
- first normal (`hit_tangent`), and placed by its instance there.
+- **What shares.** Corners equal bit for bit in position, normal, UV and tangent are one vertex: the still
+ world-space triangles among themselves, each mesh within itself, a skinned mesh by its model's corners. Triangles
+ the CPU or a pass writes whole (those that move in world space, particles) keep three vertices each.
+- **Tangents.** A vertex's own: the tangent at a hit is its triangle's three vertices' there, the hand its first
+ vertex's, placed by its instance (`hit_tangent`; read only where a frame is asked, by a normal map or a
+ function). A model's file gives them; a primitive of a file that has UVs and no tangents has them made where it
+ is loaded, a corner each, by the algorithm normal maps are baked against (`tangents.rs`, MikkTSpace; a vertex
+ whose corners come out apart, at a mirrored texture's seam, is a vertex for each). Geometry that is no file's and
+ has no tangents (a scene's own geometries, a light's card) has its frame made where it is hit, from its
+ triangle's edges, its UVs and its first normal.
- **Motion.** `prev_verts` (binding 6): the vertices that move as they were the previous frame, whole records (a
copy on the GPU has no stride; the kernel reads their positions): the moving world-space triangles' first, then
the deforming meshes', each where its record says (`n2.w`).
diff --git a/renderer/Cargo.lock b/renderer/Cargo.lock
index e5c1b83..d6df7e8 100644
--- a/renderer/Cargo.lock
+++ b/renderer/Cargo.lock
@@ -235,6 +235,12 @@ version = "0.23.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"
+[[package]]
+name = "bevy_mikktspace"
+version = "1.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bff34eb29ff4b8a8688bc7299f14fb6b597461ca80fec03ed7d22939ab33e48f"
+
[[package]]
name = "bindgen"
version = "0.73.2"
@@ -3303,6 +3309,7 @@ version = "0.1.0"
dependencies = [
"anyhow",
"base64 0.23.1",
+ "bevy_mikktspace",
"bytemuck",
"cc",
"cpal",
diff --git a/renderer/Cargo.toml b/renderer/Cargo.toml
index 081bf64..80790e7 100644
--- a/renderer/Cargo.toml
+++ b/renderer/Cargo.toml
@@ -26,6 +26,7 @@ sha2 = "0.10"
# The clock of a frame: std's natively (a re-export, nothing changes), the page's `performance.now()` in a browser,
# where std's `Instant` panics.
web-time = "1.1"
+bevy_mikktspace = "1.0.0"
# The native shell only: the window, the embedded script runtime, blocking on the GPU's futures, the denoiser. The
# engine's library builds without them for wasm32 (docs/RUNTIME.md "The engine's library in a browser"): there the
diff --git a/renderer/shaders/pathtrace.wgsl b/renderer/shaders/pathtrace.wgsl
index c1b9486..e25b285 100644
--- a/renderer/shaders/pathtrace.wgsl
+++ b/renderer/shaders/pathtrace.wgsl
@@ -143,7 +143,7 @@ struct Light { pos: vec4<f32>, dir: vec4<f32>, color: vec4<f32>, ext: vec4<f32>,
@group(0) @binding(0) var<uniform> P: Params;
// The scene's vertices (indexed.rs `Vertex`), each kept once, a record of three rows: (position, u), (normal, v),
-// (tangent, hand; zeros: it has none). A triangle is three of them, by its indices in `words` (`tri_data`).
+// (tangent, hand; a hand of 0: it has none). A triangle is three of them, by its indices in `words` (`tri_data`).
@group(0) @binding(1) var<storage, read> vertices: array<vec4<f32>>;
const VERTEX_VEC4: u32 = 3u;
// Software traversal's trees (hardware traversal has no binding for them): their nodes, and their leaves'
@@ -348,11 +348,11 @@ fn emitter_is_card(em: EmitterTri) -> bool {
return material_at(tri_row(em.part).x).tex1.z == MAT_EMITTER_CARD;
}
// A triangle read whole: its first corner and its edges, and its attributes as a hit has them: normals and UVs a
-// corner; `uv.w`: its section (an instance's: `part`) or its material; `t`: its first vertex's tangent, zeros where
-// that has none (`hit_tangent`); `x`: -, its object (an instance's: where its attributes are placed, `inst_x`), -,
-// its emitter entry + 1. `inst`, `part`: as a hit has them (`Hit`): with an instance its vertices count from the
-// mesh's first and `part` is its section; without, `part` is its row.
-struct TriData { a: TriAttr, v0: vec3<f32>, e1: vec3<f32>, e2: vec3<f32> }
+// corner; `uv.w`: its section (an instance's: `part`) or its material; `x`: -, its object (an instance's: where its
+// attributes are placed, `inst_x`), -, its emitter entry + 1. `vi`: where its three vertices are in `vertices`
+// (their tangents are read where a frame is asked: `hit_tangent`). `inst`, `part`: as a hit has them (`Hit`): with an
+// instance its vertices count from the mesh's first and `part` is its section; without, `part` is its row.
+struct TriData { a: TriAttr, v0: vec3<f32>, e1: vec3<f32>, e2: vec3<f32>, vi: vec3<u32> }
fn tri_data(ti: u32, inst: u32, part: u32) -> TriData {
var base = 0u;
var row = vec4<u32>(part, 0u, 0u, 0u);
@@ -376,15 +376,18 @@ fn tri_data(ti: u32, inst: u32, part: u32) -> TriData {
n1 = vec4<f32>(flat, n1.w);
n2 = vec4<f32>(flat, n2.w);
}
- return TriData(TriAttr(vec4<f32>(n0.xyz, p0.w), vec4<f32>(n1.xyz, n0.w), vec4<f32>(n2.xyz, p1.w), vec4<f32>(n1.w, p2.w, n2.w, bitcast<f32>(row.x)), vertices[i.x + 2u],
- vec4<f32>(0.0, bitcast<f32>(row.y), 0.0, bitcast<f32>(row.w))), p0.xyz, e1, e2);
-}
-// A triangle's tangent frame in the world: (tangent, hand). Its first vertex's where that has one (a file's, a
-// particle's); else the triangle's own, from its edges, its UVs and its first normal as `td` has them (its model's
-// space). Then placed by its instance, if one places it. Asked where a frame is read: a normal map, a function.
-fn hit_tangent(td: TriData, inst: u32) -> vec4<f32> {
- var t = td.a.t;
- if (all(t.xyz == vec3<f32>(0.0))) {
+ return TriData(TriAttr(vec4<f32>(n0.xyz, p0.w), vec4<f32>(n1.xyz, n0.w), vec4<f32>(n2.xyz, p1.w), vec4<f32>(n1.w, p2.w, n2.w, bitcast<f32>(row.x)),
+ vec4<f32>(0.0, bitcast<f32>(row.y), 0.0, bitcast<f32>(row.w))), p0.xyz, e1, e2, i);
+}
+// The tangent frame at a point of a triangle (barycentrics u, v), in the world: (tangent, hand). Its three vertices'
+// tangents there (a file's, a particle's), the hand its first vertex's; a triangle without tangents (a hand of 0)
+// has its own, from its edges, its UVs and its first normal as `td` has them (its model's space). Then placed by its
+// instance, if one places it. Not of unit length where it is its vertices': who asks makes it so against the
+// normal. Asked where a frame is read: a normal map, a function.
+fn hit_tangent(td: TriData, inst: u32, u: f32, v: f32) -> vec4<f32> {
+ let t0 = vertices[td.vi.x + 2u];
+ var t = vec4<f32>(t0.xyz * (1.0 - u - v) + vertices[td.vi.y + 2u].xyz * u + vertices[td.vi.z + 2u].xyz * v, t0.w);
+ if (t0.w == 0.0) {
let a = td.a;
let uv0 = vec2<f32>(a.n0.w, a.n1.w);
let d1 = vec2<f32>(a.n2.w, a.uv.x) - uv0;
@@ -408,13 +411,19 @@ fn hit_tangent(td: TriData, inst: u32) -> vec4<f32> {
}
if (has(F_INST) && inst != NO_INST) {
let r = instance_at(inst);
- t = vec4<f32>(normalize(inst_vec(r, t.xyz)), t.w * inst_sign(r));
+ t = vec4<f32>(unit_or_zero(inst_vec(r, t.xyz)), t.w * inst_sign(r));
}
return t;
}
+// A vector of unit length, or zeros where it has no direction (or is not finite).
+fn unit_or_zero(v: vec3<f32>) -> vec3<f32> {
+ let d = dot(v, v);
+ if (d > 0.0 && (bitcast<u32>(d) & 0x7f800000u) != 0x7f800000u) { return normalize(v); }
+ return vec3<f32>(0.0);
+}
-// A model-space triangle's shading attributes placed by instance r (scene::instance_attr). (Not its tangent, which
-// is placed where it is read: `hit_tangent`.)
+// A model-space triangle's shading attributes placed by instance r (scene::instance_attr). (Not its tangents, which
+// are placed where they are read: `hit_tangent`.)
fn inst_attr(r: Instance, a: TriAttr) -> TriAttr {
var b = a;
b.n0 = inst_normal(r, a.n0);
@@ -1306,7 +1315,7 @@ fn mat_in_at(ti: u32, inst: u32, part: u32, u: f32, v: f32, view: vec3<f32>, lod
// (Its frame placed as its attributes are: by F_IFUNC.)
var placed = NO_INST;
if (has(F_IFUNC)) { placed = inst; }
- let tw = hit_tangent(td, placed);
+ let tw = hit_tangent(td, placed, u, v);
let t = normalize(tw.xyz - n * dot(n, tw.xyz) + vec3<f32>(1e-9));
let oi = object_of(a);
return MatIn(p, n, ng, t, cross(n, t) * tw.w, mesh_uv(a, m, u, v), mesh_lod(mesh_density(e1, e2, a, m), 1.0, 1.0), view, object_at(oi * OBJECT_STRIDE).xyz, object_at(oi * OBJECT_STRIDE + 1u).xyz,
@@ -1440,7 +1449,7 @@ fn surface(o: vec3<f32>, d: vec3<f32>, h: Hit, width: f32) -> Surface {
let near = cur_depth == 0u || mirror_path;
if (has(F_TEX) && m.tex0.y >= 0 && near) {
let tn = tex(m.tex0.y, uv, lod).xyz * 2.0 - 1.0;
- let tw = hit_tangent(td, h.inst);
+ let tw = hit_tangent(td, h.inst, h.u, h.v);
let tp = tw.xyz - n * dot(n, tw.xyz);
if (dot(tp, tp) > 1e-12) {
let t = normalize(tp);
@@ -1451,7 +1460,7 @@ fn surface(o: vec3<f32>, d: vec3<f32>, h: Hit, width: f32) -> Surface {
}
if (has(F_FUNC) && m.tex1.w > 0) {
let oi = object_of(a);
- let tw = hit_tangent(td, h.inst);
+ let tw = hit_tangent(td, h.inst, h.u, h.v);
var t = normalize(tw.xyz - n * dot(n, tw.xyz) + vec3<f32>(1e-9));
let nv = normalize(a.n0.xyz * w + a.n1.xyz * h.u + a.n2.xyz * h.v) * select(-1.0, 1.0, front || dot(a.n0.xyz, ng) > 0.0);
let i = MatIn(p, select(-nv, nv, dot(nv, ng) >= 0.0), ng, t, cross(n, t) * tw.w, mesh_uv(a, m, h.u, h.v), mesh_lod(density, 1.0, 1.0), -d,
diff --git a/renderer/shaders/records.wgsl b/renderer/shaders/records.wgsl
index 795d95f..0f4e5b1 100644
--- a/renderer/shaders/records.wgsl
+++ b/renderer/shaders/records.wgsl
@@ -2,11 +2,13 @@
// of the particle passes (`particle_source`, `gpu_particle_source`) and of the live passes (live/targets.rs
// `live_source`, build.rs).
-// A triangle's shading attributes (scene.rs GpuTriAttr): normals (w: uv parts), uv parts (w: material index, bits),
-// tangent (w: bitangent sign), x: (a spare word, object (bits), a particle's area, its emitter entry + 1 (bits; 0: it
-// is not light-sampled)). (Its texel density is computed where it is hit: pathtrace.wgsl `mesh_density`.) A triangle of a mesh with sections: uv.w its section, x.w its index in it (its instance's
-// row has the material and where the section's emitters start: pathtrace.wgsl `material_of`, `row_word`).
-struct TriAttr { n0: vec4<f32>, n1: vec4<f32>, n2: vec4<f32>, uv: vec4<f32>, t: vec4<f32>, x: vec4<f32> };
+// A triangle's shading attributes as a hit reads them of its three vertices (pathtrace.wgsl `tri_data`): normals (w:
+// uv parts), uv parts (w: material index, bits), x: (a spare word, object (bits), a particle's area, its emitter
+// entry + 1 (bits; 0: it is not light-sampled)). (Its tangents are read where a frame is asked, `hit_tangent`; its
+// texel density is computed where it is hit, `mesh_density`.) A triangle of a mesh with sections: uv.w its section,
+// x.w its index in it (its instance's row has the material and where the section's emitters start: `material_of`,
+// `row_word`).
+struct TriAttr { n0: vec4<f32>, n1: vec4<f32>, n2: vec4<f32>, uv: vec4<f32>, x: vec4<f32> };
// A sample the kernel leaves in `accum`. Live: color = diffuse lighting at the first hit (w: first-hit distance, 0 =
// sky), emit = what the camera ray sees directly (emission, sky; kept out of the denoiser; w: first-hit roughness),
diff --git a/renderer/src/gpu.rs b/renderer/src/gpu.rs
index 61db92d..51d4c59 100644
--- a/renderer/src/gpu.rs
+++ b/renderer/src/gpu.rs
@@ -4076,7 +4076,7 @@ mod tests {
seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
((seed >> 40) as f32) / (1u64 << 24) as f32
};
- let (mut rows, mut want): (Vec<[f32; 36]>, Vec<f64>) = (vec![], vec![]);
+ let (mut rows, mut want): (Vec<[f32; 32]>, Vec<f64>) = (vec![], vec![]);
for k in 0..512 {
// Sizes from a millimetre to a hundred metres, UVs from a hundredth of the texture to a hundred repeats,
// footprints from a tenth of a millimetre to ten metres, a divisor from a thousandth to one.
@@ -4094,13 +4094,14 @@ mod tests {
8 => uv2 = [uv0[0] + (uv1[0] - uv0[0]) * 3.0, uv0[1] + (uv1[1] - uv0[1]) * 3.0],
_ => {}
}
- let mut row = [0f32; 36];
+ let mut row = [0f32; 32];
row[..3].copy_from_slice(&e1);
row[4..7].copy_from_slice(&e2);
(row[3], row[7]) = (fp2, over);
// (The attributes' UV words: n0.w, n1.w = uv0; n2.w, uv.x = uv1; uv.y, uv.z = uv2.)
(row[8 + 3], row[8 + 7], row[8 + 11], row[8 + 12], row[8 + 13], row[8 + 14]) = (uv0[0], uv0[1], uv1[0], uv1[1], uv2[0], uv2[1]);
- (row[32], row[33]) = (rep[0], rep[1]);
+ // (The attributes: five vec4s; then the material's.)
+ (row[28], row[29]) = (rep[0], rep[1]);
rows.push(row);
let d = |a: [f32; 3]| a.map(|x| x as f64);
let (a, b) = (d(e1), d(e2));
diff --git a/renderer/src/indexed.rs b/renderer/src/indexed.rs
index 7026437..86cb5d8 100644
--- a/renderer/src/indexed.rs
+++ b/renderer/src/indexed.rs
@@ -8,11 +8,7 @@ use glam::Vec3A;
use std::collections::HashMap;
use std::hash::Hash;
-/// `GpuTriAttr::x[0]` (bits): the triangle's tangent is its first corner's own (a file's, a particle's), not one made
-/// from the triangle's UVs.
-pub const OWN_TANGENT: u32 = 1;
-
-/// A vertex, one record: (position, u), (normal, v), (tangent, hand). A tangent of zeros: the vertex has none. What a
+/// A vertex, one record: (position, u), (normal, v), (tangent, hand). A hand of 0: the vertex has no tangent. What a
/// hit reads of each of its triangle's three; an acceleration structure is built from the records' positions.
pub type Vertex = [[f32; 4]; 3];
pub const VERTEX_BYTES: usize = std::mem::size_of::<Vertex>();
@@ -43,114 +39,69 @@ pub struct Scope {
pub indices: Vec<[u32; 3]>,
}
-/// What a vertex's tangent slot is so far: no triangle's first corner yet; the first corner of triangles without a
-/// tangent of their own (it stays zeros); the first corner of triangles with this one.
-#[derive(Clone, Copy, PartialEq)]
-enum Slot {
- Open,
- Without,
- Own([u32; 4]),
-}
-
-/// A triangle's corner `c` out of its attributes: (normal, uv).
-fn corner(a: &GpuTriAttr, c: usize) -> ([f32; 3], [f32; 2]) {
+/// A triangle's corner `c` out of its attributes: (normal, uv, tangent).
+fn corner(a: &GpuTriAttr, c: usize) -> ([f32; 3], [f32; 2], [f32; 4]) {
match c {
- 0 => ([a.n0[0], a.n0[1], a.n0[2]], [a.n0[3], a.n1[3]]),
- 1 => ([a.n1[0], a.n1[1], a.n1[2]], [a.n2[3], a.uv[0]]),
- _ => ([a.n2[0], a.n2[1], a.n2[2]], [a.uv[1], a.uv[2]]),
+ 0 => ([a.n0[0], a.n0[1], a.n0[2]], [a.n0[3], a.n1[3]], a.t),
+ 1 => ([a.n1[0], a.n1[1], a.n1[2]], [a.n2[3], a.uv[0]], a.t1),
+ _ => ([a.n2[0], a.n2[1], a.n2[2]], [a.uv[1], a.uv[2]], a.t2),
}
}
-/// The tangent a triangle's first corner carries, if it has one of its own.
-fn own_tangent(a: &GpuTriAttr) -> Option<[f32; 4]> {
- (a.x[0].to_bits() & OWN_TANGENT != 0).then_some(a.t)
-}
-
/// `n` triangles as shared vertices. `vertex(k, c)`: corner c of triangle k: what tells it from every other vertex,
-/// and its (position, u) and (normal, v). `tangent(k)`: triangle k's own tangent, which its first vertex is to
-/// carry. Two corners are one vertex where their keys are equal; a triangle's first corner is besides a vertex
-/// whose tangent slot is its own (the same tangent, or none for both).
-fn share<K: Hash + Eq>(n: usize, vertex: impl Fn(usize, usize) -> (K, [f32; 4], [f32; 4]), tangent: impl Fn(usize) -> Option<[f32; 4]>) -> Scope {
+/// and its record. Two corners are one vertex where their keys are equal.
+fn share<K: Hash + Eq>(n: usize, vertex: impl Fn(usize, usize) -> (K, Vertex)) -> Scope {
let mut s = Scope { indices: Vec::with_capacity(n), ..Default::default() };
- let mut slots: Vec<Slot> = vec![];
- // (A key's vertices: one, but where triangles disagree on the tangent of a first corner.)
- let mut seen: HashMap<K, Vec<u32>> = HashMap::with_capacity(n);
+ let mut seen: HashMap<K, u32> = HashMap::with_capacity(n);
// (A triangle with a corner that is not finite: three times one vertex at the origin, a triangle without size,
// which no ray meets. The BLASes are built from these positions.)
let mut nowhere = None;
for k in 0..n {
- if (0..3).any(|c| vertex(k, c).1[..3].iter().any(|x| !x.is_finite())) {
+ if (0..3).any(|c| vertex(k, c).1[0][..3].iter().any(|x| !x.is_finite())) {
let v = *nowhere.get_or_insert_with(|| {
s.vertices.push([[0.0; 4]; 3]);
- slots.push(Slot::Without);
- slots.len() as u32 - 1
+ s.vertices.len() as u32 - 1
});
s.indices.push([v; 3]);
continue;
}
let mut row = [0u32; 3];
for (c, at) in row.iter_mut().enumerate() {
- let (key, p, nv) = vertex(k, c);
- let want = match (c, tangent(k)) {
- (0, Some(t)) => Slot::Own(t.map(f32::to_bits)),
- (0, None) => Slot::Without,
- _ => Slot::Open,
- };
- let list = seen.entry(key).or_default();
- let found = match want {
- Slot::Open => list.first().copied(),
- _ => list.iter().copied().find(|&v| slots[v as usize] == want).or_else(|| list.iter().copied().find(|&v| slots[v as usize] == Slot::Open)),
- };
- let v = found.unwrap_or_else(|| {
- s.vertices.push([p, nv, [0.0; 4]]);
- slots.push(Slot::Open);
- list.push(slots.len() as u32 - 1);
- slots.len() as u32 - 1
+ let (key, record) = vertex(k, c);
+ *at = *seen.entry(key).or_insert_with(|| {
+ s.vertices.push(record);
+ s.vertices.len() as u32 - 1
});
- if want != Slot::Open {
- slots[v as usize] = want;
- if let Slot::Own(t) = want {
- s.vertices[v as usize][2] = t.map(f32::from_bits);
- }
- }
- *at = v;
}
s.indices.push(row);
}
s
}
-/// A scope's triangles as shared vertices: corners with the same position, normal and UV (bit for bit) are one
-/// vertex. (The attributes' tangent: see `share`.)
+/// A scope's triangles as shared vertices: corners with the same position, normal, UV and tangent (bit for bit) are
+/// one vertex.
pub fn shared(tris: &[[Vec3A; 3]], attrs: &[GpuTriAttr]) -> Scope {
- share(
- tris.len(),
- |k, c| {
- let (p, (n, uv)) = (tris[k][c], corner(&attrs[k], c));
- let key = [p.x, p.y, p.z, n[0], n[1], n[2], uv[0], uv[1]].map(f32::to_bits);
- (key, [p.x, p.y, p.z, uv[0]], [n[0], n[1], n[2], uv[1]])
- },
- |k| own_tangent(&attrs[k]),
- )
+ share(tris.len(), |k, c| {
+ let (p, (n, uv, t)) = (tris[k][c], corner(&attrs[k], c));
+ let key = [p.x, p.y, p.z, n[0], n[1], n[2], uv[0], uv[1], t[0], t[1], t[2], t[3]].map(f32::to_bits);
+ (key, [[p.x, p.y, p.z, uv[0]], [n[0], n[1], n[2], uv[1]], t])
+ })
}
/// A skinned mesh's triangles as shared vertices: corners are one vertex where the model's corners they are skinned
/// from are the same (`source`, a triangle's three in the mesh's order: position, normal, tangent, joints and
-/// weights, bit for bit) and their UVs are. A vertex's values are the build's pose's. One whose model has no normal
-/// has a normal of zeros (its triangle's is made where it is hit), and none has a tangent that is not its own.
+/// weights, bit for bit), their UVs are and their tangents' hands. A vertex's values are the build's pose's. One
+/// whose model has no normal has a normal of zeros (its triangle's is made where it is hit).
pub fn shared_skinned(source: &[[crate::skin::SkinCorner; 3]], tris: &[[Vec3A; 3]], attrs: &[GpuTriAttr]) -> Scope {
- share(
- tris.len(),
- |k, c| {
- let (p, (n, uv), from) = (tris[k][c], corner(&attrs[k], c), source[k][c]);
- let mut key = [0u32; 18];
- key[..16].copy_from_slice(bytemuck::cast_slice(&[from]));
- (key[16], key[17]) = (uv[0].to_bits(), uv[1].to_bits());
- let n = if from.t[3].to_bits() & crate::skin::CORNER_NORMAL != 0 { n } else { [0.0; 3] };
- (key, [p.x, p.y, p.z, uv[0]], [n[0], n[1], n[2], uv[1]])
- },
- |k| (source[k][0].t[3].to_bits() & crate::skin::CORNER_TANGENT != 0).then_some(attrs[k].t),
- )
+ share(tris.len(), |k, c| {
+ let (p, (n, uv, t), from) = (tris[k][c], corner(&attrs[k], c), source[k][c]);
+ let mut key = [0u32; 19];
+ key[..16].copy_from_slice(bytemuck::cast_slice(&[from]));
+ (key[16], key[17], key[18]) = (uv[0].to_bits(), uv[1].to_bits(), t[3].to_bits());
+ let n = if from.t[3].to_bits() & crate::skin::CORNER_NORMAL != 0 { n } else { [0.0; 3] };
+ let t = if from.t[3].to_bits() & crate::skin::CORNER_TANGENT != 0 { t } else { [0.0; 4] };
+ (key, [[p.x, p.y, p.z, uv[0]], [n[0], n[1], n[2], uv[1]], t])
+ })
}
/// The model's vertices a skinned mesh's are skinned from: for each vertex `scope` found (`shared_skinned`), the
@@ -172,11 +123,10 @@ pub fn source_vertices(source: &[[crate::skin::SkinCorner; 3]], scope: &Scope) -
pub fn apart(tris: &[[Vec3A; 3]], attrs: &[GpuTriAttr]) -> Scope {
let mut s = Scope::default();
for (k, (t, a)) in tris.iter().zip(attrs).enumerate() {
- let tangent = own_tangent(a).unwrap_or([0.0; 4]);
// (One with a corner that is not finite: its three vertices at the origin, as `share` has it.)
let finite = t.iter().all(|p| p.is_finite());
for (c, p) in t.iter().enumerate() {
- let (n, uv) = corner(a, c);
+ let (n, uv, tangent) = corner(a, c);
let p = if finite { *p } else { Vec3A::ZERO };
s.vertices.push([[p.x, p.y, p.z, uv[0]], [n[0], n[1], n[2], uv[1]], tangent]);
}
@@ -190,10 +140,9 @@ pub fn apart(tris: &[[Vec3A; 3]], attrs: &[GpuTriAttr]) -> Scope {
pub fn apart_vertices(corners: &[[f32; 3]], attrs: &[GpuTriAttr]) -> Vec<Vertex> {
let mut out = Vec::with_capacity(corners.len());
for (t, a) in corners.chunks_exact(3).zip(attrs) {
- let tangent = own_tangent(a).unwrap_or([0.0; 4]);
let finite = t.iter().flatten().all(|x| x.is_finite());
for (c, p) in t.iter().enumerate() {
- let (n, uv) = corner(a, c);
+ let (n, uv, tangent) = corner(a, c);
let p = if finite { *p } else { [0.0; 3] };
out.push([[p[0], p[1], p[2], uv[0]], [n[0], n[1], n[2], uv[1]], tangent]);
}
@@ -246,12 +195,13 @@ impl Indexed {
}
/// Triangle `k` as the build had it, its vertices counted from `base`: its corners, and its attributes' normals,
- /// UVs and tangent (its first vertex's: zeros where that has none).
- pub fn triangle(&self, k: usize, base: u32) -> ([[f32; 3]; 3], [[f32; 3]; 3], [[f32; 2]; 3], [f32; 4]) {
+ /// UVs and tangents (a hand of 0 where it has none).
+ #[allow(clippy::type_complexity)]
+ pub fn triangle(&self, k: usize, base: u32) -> ([[f32; 3]; 3], [[f32; 3]; 3], [[f32; 2]; 3], [[f32; 4]; 3]) {
let v = self.indices[k].map(|i| (base + i) as usize);
let [p, n] = [0, 1].map(|r| v.map(|i| [self.vertices[i][r][0], self.vertices[i][r][1], self.vertices[i][r][2]]));
let uv = v.map(|i| [self.vertices[i][0][3], self.vertices[i][1][3]]);
- (p, n, uv, self.vertices[v[0]][2])
+ (p, n, uv, v.map(|i| self.vertices[i][2]))
}
}
@@ -261,8 +211,7 @@ mod tests {
use glam::{Vec2, Vec3};
/// A sheet of `n` x `n` quads bent into a wave, as the build makes its triangles: every corner its own, with
- /// the normal and UV of its place on the sheet. `own`: each triangle has its first corner's tangent (a file's);
- /// else one made from its UVs.
+ /// the normal and UV of its place on the sheet, and with `own` its tangent there.
fn sheet(n: u32, own: bool) -> (Vec<[Vec3A; 3]>, Vec<GpuTriAttr>) {
let at = |x: u32, y: u32| {
let (u, v) = (x as f32 / n as f32, y as f32 / n as f32);
@@ -277,15 +226,15 @@ mod tests {
for q in [[(x, y), (x + 1, y), (x + 1, y + 1)], [(x + 1, y + 1), (x, y + 1), (x, y)]] {
let c = q.map(|(x, y)| at(x, y));
tris.push(c.map(|c| Vec3A::from(c.0)));
- attrs.push(crate::scene::tri_attr(c.map(|c| c.0), c.map(|c| c.1), c.map(|c| c.2), own.then_some((c[0].3, -1.0)), 3));
+ attrs.push(crate::scene::tri_attr(c.map(|c| c.1), c.map(|c| c.2), own.then_some(c.map(|c| (c.3, -1.0))), 3));
}
}
}
(tris, attrs)
}
- /// The scope's triangles are the build's, corner for corner and bit for bit: positions, normals, UVs, and the
- /// tangent of a triangle that has its own on its first vertex (zeros there for one that has none).
+ /// The scope's triangles are the build's, corner for corner and bit for bit: positions, normals, UVs, tangents
+ /// (zeros for a triangle that has none).
fn same(what: &str, s: &Scope, tris: &[[Vec3A; 3]], attrs: &[GpuTriAttr]) {
let all = Indexed { vertices: s.vertices.clone(), indices: s.indices.clone(), ..Default::default() };
assert_eq!(s.indices.len(), tris.len(), "{what}: a row of indices a triangle");
@@ -293,16 +242,15 @@ mod tests {
for (k, (t, a)) in tris.iter().zip(attrs).enumerate() {
let (p, n, uv, tangent) = all.triangle(k, 0);
for c in 0..3 {
- let (wn, wuv) = corner(a, c);
- assert_eq!((bits(&p[c]), bits(&n[c]), bits(&uv[c])), (bits(&t[c].to_array()), bits(&wn), bits(&wuv)), "{what}: triangle {k}, corner {c}");
+ let (wn, wuv, wt) = corner(a, c);
+ assert_eq!((bits(&p[c]), bits(&n[c]), bits(&uv[c]), bits(&tangent[c])), (bits(&t[c].to_array()), bits(&wn), bits(&wuv), bits(&wt)), "{what}: triangle {k}, corner {c}");
}
- assert_eq!(bits(&tangent), bits(&own_tangent(a).unwrap_or([0.0; 4])), "{what}: triangle {k}'s tangent on its first vertex");
}
}
- /// Triangles that the build made from a sheet of (n + 1)^2 vertices come back as that many, whether each has a
- /// tangent of its own (a file's: its first corner's) or none; and each triangle read through its indices is the
- /// build's. Written whole, they have three vertices each.
+ /// Triangles that the build made from a sheet of (n + 1)^2 vertices come back as that many, with tangents or
+ /// without; and each triangle read through its indices is the build's. Written whole, they have three vertices
+ /// each.
#[test]
fn a_scopes_triangles_share_their_vertices() {
for own in [false, true] {
@@ -316,17 +264,25 @@ mod tests {
}
}
- /// Two triangles along an edge share its two corners; with another UV on one's side (a texture's seam) or another
- /// normal (a crease) each keeps its own.
+ /// Two triangles along an edge share its two corners; with another UV on one's side (a texture's seam), another
+ /// normal (a crease), another tangent, or the other hand (a mirrored texture's seam), each keeps its own.
#[test]
fn a_seam_or_a_crease_keeps_its_vertices() {
let p = [Vec3::ZERO, Vec3::X, Vec3::Y, Vec3::new(1.0, 1.0, 0.0)];
let tris = vec![[p[0], p[1], p[2]].map(Vec3A::from), [p[2], p[1], p[3]].map(Vec3A::from)];
let uv = |v: Vec3| Vec2::new(v.x, v.y);
- for (what, shift, normal, vertices) in [("one sheet", Vec2::ZERO, Vec3::Z, 4), ("a seam", Vec2::new(0.5, 0.0), Vec3::Z, 6), ("a crease", Vec2::ZERO, Vec3::new(0.6, 0.0, 0.8), 6)] {
+ let one = Some([(Vec3::X, 1.0); 3]);
+ for (what, shift, normal, tangent, vertices) in [
+ ("one sheet", Vec2::ZERO, Vec3::Z, one, 4),
+ ("a seam", Vec2::new(0.5, 0.0), Vec3::Z, one, 6),
+ ("a crease", Vec2::ZERO, Vec3::new(0.6, 0.0, 0.8), one, 6),
+ ("another tangent", Vec2::ZERO, Vec3::Z, Some([(Vec3::Y, 1.0); 3]), 6),
+ ("the other hand", Vec2::ZERO, Vec3::Z, Some([(Vec3::X, -1.0); 3]), 6),
+ ("no tangent beside one", Vec2::ZERO, Vec3::Z, None, 6),
+ ] {
let attrs = vec![
- crate::scene::tri_attr([p[0], p[1], p[2]], [Vec3::Z; 3], [p[0], p[1], p[2]].map(uv), None, 3),
- crate::scene::tri_attr([p[2], p[1], p[3]], [normal; 3], [p[2], p[1], p[3]].map(|v| uv(v) + shift), None, 3),
+ crate::scene::tri_attr([Vec3::Z; 3], [p[0], p[1], p[2]].map(uv), one, 3),
+ crate::scene::tri_attr([normal; 3], [p[2], p[1], p[3]].map(|v| uv(v) + shift), tangent, 3),
];
let s = shared(&tris, &attrs);
same(what, &s, &tris, &attrs);
@@ -334,6 +290,27 @@ mod tests {
}
}
+ /// A skinned mesh's corners are one vertex where they are skinned from the same corner of the model and have the
+ /// same UV and the same hand: two triangles along an edge whose corners there are the model's same two, one
+ /// vertex each; with the other hand on one side, each side its own.
+ #[test]
+ fn a_skinned_meshs_corners_share_by_their_models_corner_and_their_hand() {
+ let p = [Vec3::ZERO, Vec3::X, Vec3::Y, Vec3::new(1.0, 1.0, 0.0)];
+ let (order, uv) = ([[0, 1, 2], [2, 1, 3]], |v: Vec3| Vec2::new(v.x, v.y));
+ let tris: Vec<[Vec3A; 3]> = order.iter().map(|o| o.map(|i| Vec3A::from(p[i]))).collect();
+ let from = |i: usize| crate::skin::SkinCorner { p: [p[i].x, p[i].y, p[i].z, 0.0], n: [0.0, 0.0, 1.0, 0.0], t: [1.0, 0.0, 0.0, f32::from_bits(crate::skin::CORNER_NORMAL | crate::skin::CORNER_TANGENT)], w: [1.0, 0.0, 0.0, 0.0] };
+ let source: Vec<[crate::skin::SkinCorner; 3]> = order.iter().map(|o| o.map(from)).collect();
+ for (what, hand, vertices) in [("one hand", 1.0, 4), ("the other hand on one side", -1.0, 6)] {
+ let attrs = vec![
+ crate::scene::tri_attr([Vec3::Z; 3], order[0].map(|i| uv(p[i])), Some([(Vec3::X, 1.0); 3]), 3),
+ crate::scene::tri_attr([Vec3::Z; 3], order[1].map(|i| uv(p[i])), Some([(Vec3::X, hand); 3]), 3),
+ ];
+ let s = shared_skinned(&source, &tris, &attrs);
+ same(what, &s, &tris, &attrs);
+ assert_eq!(s.vertices.len(), vertices, "{what}: its vertices");
+ }
+ }
+
/// A triangle with a corner that is not finite is three times one vertex at the origin (no ray meets it; a BLAS is
/// built from these positions), shared or apart; the others are as they were.
#[test]
@@ -355,36 +332,4 @@ mod tests {
let corners: Vec<[f32; 3]> = tris.iter().flatten().map(|p| p.to_array()).collect();
assert!(apart_vertices(&corners, &attrs).iter().flat_map(|v| v[0]).all(|x| x.is_finite()));
}
-
- /// Where triangles disagree about a first corner's tangent the corner is a vertex for each: a sheet whose
- /// triangles each have a tangent of their own that is no other's, one with and without a tangent by turns, and
- /// one where a corner is first met as a second corner and takes its tangent later.
- #[test]
- fn a_first_corner_has_its_triangles_tangent() {
- let (tris, mut attrs) = sheet(6, true);
- for (k, a) in attrs.iter_mut().enumerate() {
- a.t = [k as f32 + 1.0, 0.5, 0.25, 1.0];
- }
- let s = shared(&tris, &attrs);
- same("a tangent a triangle", &s, &tris, &attrs);
- // (Every vertex of the sheet but two corners is the first corner of one triangle or two.)
- assert!(s.vertices.len() > 7 * 7 && s.vertices.len() <= 7 * 7 + 6 * 6, "{} vertices", s.vertices.len());
- let (tris, mut attrs) = sheet(6, true);
- for (k, a) in attrs.iter_mut().enumerate() {
- if k % 2 == 1 {
- a.x[0] = 0.0;
- }
- }
- let s = shared(&tris, &attrs);
- same("with and without by turns", &s, &tris, &attrs);
- // Two triangles of one corner each way round: the corner is the first's second and the second's first.
- let p = [Vec3A::ZERO, Vec3A::X, Vec3A::Y];
- let a = |own: bool| crate::scene::tri_attr(p.map(Vec3::from), [Vec3::Z; 3], [Vec2::ZERO, Vec2::X, Vec2::Y], own.then_some((Vec3::X, 1.0)), 0);
- // (The same triangle begun at its second corner.)
- let turned = |a: GpuTriAttr| GpuTriAttr { n0: [a.n1[0], a.n1[1], a.n1[2], a.n2[3]], n1: [a.n2[0], a.n2[1], a.n2[2], a.uv[0]], n2: [a.n0[0], a.n0[1], a.n0[2], a.uv[1]], uv: [a.uv[2], a.n0[3], a.n1[3], a.uv[3]], ..a };
- let (tris, attrs) = (vec![p, [p[1], p[2], p[0]]], vec![a(false), turned(a(true))]);
- let s = shared(&tris, &attrs);
- same("a corner met as a second corner first", &s, &tris, &attrs);
- assert_eq!(s.vertices.len(), 3, "three vertices: the shared corner took its tangent when a triangle began at it");
- }
}
diff --git a/renderer/src/lib.rs b/renderer/src/lib.rs
index 5562c80..2cf9695 100644
--- a/renderer/src/lib.rs
+++ b/renderer/src/lib.rs
@@ -28,6 +28,7 @@ pub mod skin;
pub mod sample;
pub mod sky;
pub mod tables;
+pub mod tangents;
pub mod units;
#[cfg(not(target_arch = "wasm32"))]
pub mod userfiles;
@@ -1762,8 +1763,8 @@ mod units_tests {
/// `prepare`'s vertices and indices (indexed.rs) are its triangles: every triangle read through its indices (a
/// mesh's from the mesh's first vertex, a world-space one's from 0) has the corners, the edges, the normals and
- /// the UVs the kernel's arrays have for it, bit for bit, the tangent of one that has its own, and its row's four
- /// words. Flattened, with units, and as hardware traversal has the scene; with two posed skinned models. A mesh's
+ /// the UVs the kernel's arrays have for it, bit for bit, its corners' tangents (zeros: it has none), and its row's
+ /// four words. Flattened, with units, and as hardware traversal has the scene; with two posed skinned models. A mesh's
/// vertices are fewer than its triangles' corners (the ring: 82 for 80 triangles), and the vertices that move are
/// one run. No GPU.
#[test]
@@ -1793,8 +1794,7 @@ mod units_tests {
assert_eq!([bits(&n[0]), bits(&n[1]), bits(&n[2])], [bits(&a.n0[..3]), bits(&a.n1[..3]), bits(&a.n2[..3])], "{what}: triangle {k}'s normals");
}
assert_eq!(bits(&uv.concat()), bits(&[a.n0[3], a.n1[3], a.n2[3], a.uv[0], a.uv[1], a.uv[2]]), "{what}: triangle {k}'s UVs");
- let own = a.x[0].to_bits() & indexed::OWN_TANGENT != 0;
- assert_eq!(bits(&tangent), bits(&if own { a.t } else { [0.0; 4] }), "{what}: triangle {k}'s own tangent on its first vertex, or none");
+ assert_eq!(tangent.map(|t| bits(&t)), [a.t, a.t1, a.t2].map(|t| bits(&t)), "{what}: triangle {k}'s tangents, a corner each, or none");
// (A mesh's triangle: its section and its index in it, nothing else. One no instance places: its
// material, its object, its flags, its emitter + 1.)
let pool = (pool_first..pool_first + sc.pool_tris.len()).contains(&k);
@@ -1814,7 +1814,7 @@ mod units_tests {
}
// The ring's mesh: 80 triangles of 82 vertices. Each skinned model's mesh: its own vertices, as many as
// the other's (one model), fewer than its corners; and they are the vertices that move.
- assert!(sc.attrs.iter().any(|a| a.x[0].to_bits() & indexed::OWN_TANGENT != 0) && sc.attrs.iter().any(|a| a.x[0].to_bits() & indexed::OWN_TANGENT == 0), "{what}: triangles with a tangent of their own and without");
+ assert!(sc.attrs.iter().any(|a| a.t[3] != 0.0) && sc.attrs.iter().any(|a| a.t[3] == 0.0), "{what}: triangles with tangents and without");
let ring = sc.meshes.iter().zip(&x.meshes).find(|(m, _)| m.count == 80).expect("the ring's mesh");
assert_eq!(ring.1 .1, 82, "{what}: the ring's vertices");
let skinned: Vec<(u32, u32)> = sc.meshes.iter().zip(&x.meshes).filter(|(m, _)| m.deforms).map(|(_, v)| *v).collect();
diff --git a/renderer/src/live/edits.rs b/renderer/src/live/edits.rs
index e49388c..9b94f90 100644
--- a/renderer/src/live/edits.rs
+++ b/renderer/src/live/edits.rs
@@ -1846,7 +1846,7 @@ impl LiveCore {
let (first, verts, attrs, blas) = &mut self.sc.dynamic;
for (j, (node, p, n, uv, tg)) in r.rest_local.iter().enumerate() {
let (pw, nw, uvw, tw) = scene::placed_tri(scene::RigidModel::part_world(m, *node, &globals), p, n, uv, *tg);
- let a = scene::tri_attr(pw, nw, uvw, tw, d.mats[j]);
+ let a = scene::tri_attr(nw, uvw, tw, d.mats[j]);
let k = d.finals[j] as usize - *first;
let (e1, e2) = (pw[1] - pw[0], pw[2] - pw[0]);
verts[k * 3..k * 3 + 3].copy_from_slice(&[[pw[0].x, pw[0].y, pw[0].z, f32::from_bits(d.flags[j])], [e1.x, e1.y, e1.z, 0.0], [e2.x, e2.y, e2.z, 0.0]]);
@@ -2569,9 +2569,13 @@ impl LiveCore {
vertices[v][0] = [p.x, p.y, p.z, q.uv[c].x];
vertices[v][1] = [normal.x, normal.y, normal.z, q.uv[c].y];
}
- let v0 = index[j][0] as usize;
- if let Some((tangent, hand)) = q.tangent.filter(|_| model[v0].t[3].to_bits() & crate::skin::CORNER_TANGENT != 0) {
- vertices[v0][2] = [tangent.x, tangent.y, tangent.z, hand];
+ if let Some(tangent) = q.tangent {
+ for c in 0..3 {
+ let v = index[j][c] as usize;
+ if model[v].t[3].to_bits() & crate::skin::CORNER_TANGENT != 0 {
+ vertices[v][2] = [tangent[c].0.x, tangent[c].0.y, tangent[c].0.z, tangent[c].1];
+ }
+ }
}
t.push(q.p.map(glam::Vec3A::from));
}
diff --git a/renderer/src/live/inplace_tests.rs b/renderer/src/live/inplace_tests.rs
index 2021a67..e2b72d1 100644
--- a/renderer/src/live/inplace_tests.rs
+++ b/renderer/src/live/inplace_tests.rs
@@ -174,14 +174,12 @@ fn triangles_on_gpu(c: &LiveCore, first: u64, n: u64, base: u32, prev: Option<u3
let before: Vec<crate::indexed::Vertex> = prev.map_or(vec![], |_| read_back(c, &up.prev_vertices, 0, up.prev_vertices.size()));
let mut out = Triangles { rows, ..Default::default() };
for tri in index.chunks_exact(3) {
- for (k, &i) in tri.iter().enumerate() {
+ for &i in tri {
let v = &vertices[(base + i) as usize];
out.p.extend(&v[0][..3]);
out.n.extend(&v[1][..3]);
out.uv.extend([v[0][3], v[1][3]]);
- if k == 0 {
- out.t.extend(v[2]);
- }
+ out.t.extend(v[2]);
if let Some(p) = prev {
out.prev.extend(&before[(p + i) as usize][0][..3]);
}
@@ -191,7 +189,7 @@ fn triangles_on_gpu(c: &LiveCore, first: u64, n: u64, base: u32, prev: Option<u3
}
/// A skinned model's mesh as the CPU skin gives it for a pose, in the same form: a normal where the model has one
-/// (else zeros: the triangle's own is made where it is hit), a tangent where the model has its own.
+/// (else zeros: the triangle's own is made where it is hit), a tangent a corner where the model has them.
fn skinned_on_cpu(c: &LiveCore, sk: &scene::Skinned, a: &crate::desc::Animation) -> Triangles {
let tris = scene::model_gltf(&sk.uri, Path::new("..")).unwrap().triangles(glam::Mat4::IDENTITY, None, Some(a)).unwrap();
let (model, index) = &c.sc.skins[sk.source as usize];
@@ -203,11 +201,11 @@ fn skinned_on_cpu(c: &LiveCore, sk: &scene::Skinned, a: &crate::desc::Animation)
out.p.extend(q.p[corner].to_array());
out.n.extend(if has(j, corner, crate::skin::CORNER_NORMAL) { q.n[corner].to_array() } else { [0.0; 3] });
out.uv.extend(q.uv[corner].to_array());
+ out.t.extend(match q.tangent.filter(|_| has(j, corner, crate::skin::CORNER_TANGENT)) {
+ Some(t) => [t[corner].0.x, t[corner].0.y, t[corner].0.z, t[corner].1],
+ None => [0.0; 4],
+ });
}
- out.t.extend(match q.tangent.filter(|_| has(j, 0, crate::skin::CORNER_TANGENT)) {
- Some((t, hand)) => [t.x, t.y, t.z, hand],
- None => [0.0; 4],
- });
out.rows.extend([section, 0, 0, rank]);
}
out
@@ -234,7 +232,7 @@ fn skinned_is_the_cpus(what: &str, c: &LiveCore, sk: &scene::Skinned, name: &str
same_numbers(&format!("{what}: the corners"), &got.p, &want.p, 9);
same_numbers(&format!("{what}: the normals"), &got.n, &want.n, 9);
same_numbers(&format!("{what}: the UVs"), &got.uv, &want.uv, 6);
- same_numbers(&format!("{what}: the tangents"), &got.t, &want.t, 4);
+ same_numbers(&format!("{what}: the tangents"), &got.t, &want.t, 12);
assert!(record.n[1][3].to_bits() & scene::INST_DEFORMS != 0 && inst.bits & scene::INST_DEFORMS != 0, "{what}: the record says its mesh deforms");
if c.g.hwrt {
for (j, &(_, section, rank)) in sk.order.iter().enumerate() {
diff --git a/renderer/src/scene.rs b/renderer/src/scene.rs
index e5a9b96..64b0d86 100644
--- a/renderer/src/scene.rs
+++ b/renderer/src/scene.rs
@@ -260,20 +260,23 @@ impl Instance {
return (w, b, c);
}
// (The UVs are packed along the normals: uv0 in n0.w n1.w, uv1 in n2.w uv.x, uv2 in uv.y uv.z.)
- let swapped = GpuTriAttr { n1: [b.n2[0], b.n2[1], b.n2[2], b.n1[3]], n2: [b.n1[0], b.n1[1], b.n1[2], b.uv[1]], uv: [b.uv[2], b.n2[3], b.uv[0], b.uv[3]], ..b };
+ let swapped = GpuTriAttr { n1: [b.n2[0], b.n2[1], b.n2[2], b.n1[3]], n2: [b.n1[0], b.n1[1], b.n1[2], b.uv[1]], uv: [b.uv[2], b.n2[3], b.uv[0], b.uv[3]], t1: b.t2, t2: b.t1, ..b };
([w[0], w[2], w[1]], swapped, c.map(|c| [c[0], c[2], c[1]]))
}
}
-/// A triangle in a node's own space (vertices, normals, UVs, an authored tangent) placed by `w` as the build flattens
-/// it: under a mirroring `w` the second and third vertex change places, so that it faces as its mesh does, and an
-/// authored tangent's frame changes hand (`Instance::flat` does the same with a mesh's triangle; a tangent worked out
-/// from the placed triangle has the right hand by itself).
+/// A triangle's tangents, one a corner: the direction of u on the surface and the frame's hand (1 or -1). A file's,
+/// or generated (tangents.rs); a triangle without has none (`GpuTriAttr::t`'s hand is 0).
+pub type CornerTangents = [(Vec3, f32); 3];
+
+/// A triangle in a node's own space (vertices, normals, UVs, tangents) placed by `w` as the build flattens it: under
+/// a mirroring `w` the second and third vertex change places, so that it faces as its mesh does, and its tangents'
+/// frame changes hand (`Instance::flat` does the same with a mesh's triangle).
#[allow(clippy::type_complexity)]
-pub fn placed_tri(w: Mat4, p: &[Vec3; 3], n: &[Vec3; 3], uv: &[Vec2; 3], tangent: Option<(Vec3, f32)>) -> ([Vec3; 3], [Vec3; 3], [Vec2; 3], Option<(Vec3, f32)>) {
+pub fn placed_tri(w: Mat4, p: &[Vec3; 3], n: &[Vec3; 3], uv: &[Vec2; 3], tangent: Option<CornerTangents>) -> ([Vec3; 3], [Vec3; 3], [Vec2; 3], Option<CornerTangents>) {
let nm = Mat3::from_mat4(w).inverse().transpose();
let (k, hand) = if mirrors(w) { ([0, 2, 1], -1.0) } else { ([0, 1, 2], 1.0) };
- (k.map(|i| w.transform_point3(p[i])), k.map(|i| (nm * n[i]).normalize_or_zero()), k.map(|i| uv[i]), tangent.map(|(v, s)| (w.transform_vector3(v).normalize_or_zero(), s * hand)))
+ (k.map(|i| w.transform_point3(p[i])), k.map(|i| (nm * n[i]).normalize_or_zero()), k.map(|i| uv[i]), tangent.map(|t| k.map(|i| (w.transform_vector3(t[i].0).normalize_or_zero(), t[i].1 * hand))))
}
/// Bit of an instance record's n1.w, beside the units' flags there (units.rs `UNIT_*`): the instance mirrors its mesh
@@ -509,8 +512,8 @@ pub fn node_ranges<'a>(tri_nodes: &'a [(String, u32, u32)], id: &'a str) -> impl
tri_nodes.iter().filter(move |(n, _, _)| n == id).map(|(_, a, b)| *a as usize..*b as usize)
}
-/// Model-space shading attributes of a pool triangle placed by `w` (normals by the inverse transpose, tangent by the
-/// matrix, its frame's hand changed by a mirroring one), object `object`.
+/// Model-space shading attributes of a pool triangle placed by `w` (normals by the inverse transpose, tangents by
+/// the matrix, their frame's hand changed by a mirroring one), object `object`.
pub fn instance_attr(a: &GpuTriAttr, w: Mat4, object: u32) -> GpuTriAttr {
let m3 = glam::Mat3::from_mat4(w);
let nm = m3.inverse().transpose();
@@ -518,9 +521,12 @@ pub fn instance_attr(a: &GpuTriAttr, w: Mat4, object: u32) -> GpuTriAttr {
let r = (nm * Vec3::new(v[0], v[1], v[2])).normalize_or_zero();
[r.x, r.y, r.z, v[3]]
};
- let t = (m3 * Vec3::new(a.t[0], a.t[1], a.t[2])).normalize_or_zero();
- let hand = if mirrors(w) { -a.t[3] } else { a.t[3] };
- GpuTriAttr { n0: n(a.n0), n1: n(a.n1), n2: n(a.n2), uv: a.uv, t: [t.x, t.y, t.z, hand], x: [a.x[0], f32::from_bits(object), a.x[2], a.x[3]] }
+ let flip = if mirrors(w) { -1.0 } else { 1.0 };
+ let t = |v: [f32; 4]| {
+ let r = (m3 * Vec3::new(v[0], v[1], v[2])).normalize_or_zero();
+ [r.x, r.y, r.z, v[3] * flip]
+ };
+ GpuTriAttr { n0: n(a.n0), n1: n(a.n1), n2: n(a.n2), uv: a.uv, t: t(a.t), x: [a.x[0], f32::from_bits(object), a.x[2], a.x[3]], t1: t(a.t1), t2: t(a.t2) }
}
#[repr(C)]
@@ -530,8 +536,10 @@ pub struct GpuTriAttr {
pub n1: [f32; 4], // normal1, w = uv0.y
pub n2: [f32; 4], // normal2, w = uv1.x
pub uv: [f32; 4], // uv1.y, uv2.x, uv2.y, material (bits)
- pub t: [f32; 4], // tangent (dP/du), w = bitangent sign
- pub x: [f32; 4], // `indexed::OWN_TANGENT` (bits), object index (bits), a particle's area, its emitter entry + 1 (bits; 0: not light-sampled)
+ pub t: [f32; 4], // its first corner's tangent (dP/du), w = the frame's hand (0: the triangle has no tangents)
+ pub x: [f32; 4], // -, object index (bits), a particle's area, its emitter entry + 1 (bits; 0: not light-sampled)
+ pub t1: [f32; 4], // its second corner's tangent
+ pub t2: [f32; 4], // its third corner's
}
#[repr(C)]
@@ -943,7 +951,7 @@ pub struct RigidModel {
pub rest: DynamicModel,
/// Per `rest` triangle: its node (`STILL_NODES`: the model's own space) and its triangle there (positions,
/// normals, uvs, tangent).
- pub rest_local: Vec<(usize, [Vec3; 3], [Vec3; 3], [Vec2; 3], Option<(Vec3, f32)>)>,
+ pub rest_local: Vec<(usize, [Vec3; 3], [Vec3; 3], [Vec2; 3], Option<CornerTangents>)>,
/// `rigid_pose_key` of the pose its parts were made for: a pose with another is other parts (a build's to make).
pub pose: String,
}
@@ -980,7 +988,7 @@ impl RigidModel {
struct RigidPart {
node: usize,
mesh: Option<u32>,
- rest: Vec<([Vec3; 3], [Vec3; 3], [Vec2; 3], Option<(Vec3, f32)>, u32)>,
+ rest: Vec<([Vec3; 3], [Vec3; 3], [Vec2; 3], Option<CornerTangents>, u32)>,
}
/// A posed skinned model's mesh: the model's triangles in its own space, a mesh a model. The skinning pass skins it at
@@ -1801,7 +1809,7 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
for &(k, section, rank) in &order {
let t = &local[k];
pool_tris.push([t.p[0].into(), t.p[1].into(), t.p[2].into()]);
- pool_attrs.push(section_attr(t.p, t.n, t.uv, t.tangent, section, rank));
+ pool_attrs.push(section_attr(t.n, t.uv, t.tangent, section, rank));
}
meshes.push(InstMesh { sect_first: sections.len() as u32, sect_count: sects.len() as u32, ..own_inst_mesh(&pool_tris[first_pool as usize..], first_pool) });
sections.extend(sects);
@@ -1909,7 +1917,7 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
hi = hi.max(v.into());
}
pool_tris.push([t.p[0].into(), t.p[1].into(), t.p[2].into()]);
- pool_attrs.push(section_attr(t.p, t.n, t.uv, t.tangent, section, rank));
+ pool_attrs.push(section_attr(t.n, t.uv, t.tangent, section, rank));
}
// Other poses reach further (a stride, a swing): object bounds a quarter wider each way; one
// the game poses may take any pose (lie down): as far as its size each way.
@@ -1965,13 +1973,13 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
for &(k, section, rank) in &order {
let t = &local[k];
pool_tris.push([t.p[0].into(), t.p[1].into(), t.p[2].into()]);
- pool_attrs.push(section_attr(t.p, t.n, t.uv, t.tangent, section, rank));
+ pool_attrs.push(section_attr(t.n, t.uv, t.tangent, section, rank));
}
// (What leaves the mesh keeps its material on the triangle: each placement flattens it.)
for &(k, mat) in &classed[FLAT] {
let t = &local[k];
rest_tris.push([t.p[0].into(), t.p[1].into(), t.p[2].into()]);
- rest_attrs.push(tri_attr(t.p, t.n, t.uv, t.tangent, mat));
+ rest_attrs.push(tri_attr(t.n, t.uv, t.tangent, mat));
}
meshes.push(InstMesh { rest_first, rest_count: classed[FLAT].len() as u32, lo, hi, sect_first: sections.len() as u32, sect_count: sects.len() as u32, ..own_inst_mesh(&pool_tris[first as usize..], first) });
sections.extend(sects);
@@ -2119,7 +2127,7 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
let first = if translucent { trans_tris.len() as u32 } else { first };
for k in 0..*count {
for uv in corners {
- let mut a = tri_attr([pivot; 3], [Vec3::Z; 3], uv, Some((Vec3::X, 1.0)), mat);
+ let mut a = tri_attr([Vec3::Z; 3], uv, Some([(Vec3::X, 1.0); 3]), mat);
a.x[1] = f32::from_bits(object + k);
// Light sampling by a nominal area (half a quad per triangle; lib.rs prepare, emit_mis); -1: a
// particle not light-sampled (its emission reaches surfaces by their BSDF rays alone).
@@ -2154,7 +2162,7 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
let corners = [[Vec2::new(0.0, 1.0), Vec2::new(1.0, 1.0), Vec2::new(1.0, 0.0)], [Vec2::new(0.0, 1.0), Vec2::new(1.0, 0.0), Vec2::new(0.0, 0.0)]];
for k in 0..*capacity {
for uv in corners {
- let mut a = tri_attr([pivot; 3], [Vec3::Z; 3], uv, Some((Vec3::X, 1.0)), mat);
+ let mut a = tri_attr([Vec3::Z; 3], uv, Some([(Vec3::X, 1.0); 3]), mat);
a.x[1] = f32::from_bits(object + k);
a.x[2] = if *emitter_area > 0.0 { emitter_area * 0.5 } else { -1.0 };
tris.push([p; 3]);
@@ -2424,10 +2432,10 @@ pub fn dynamic_tris(w: &World, id: u32, d: &DynamicModel, assets: &Path) -> Resu
if tris.len() != d.mats.len() {
return Ok(None);
}
- Some(tris.iter().zip(&d.mats).map(|(t, &mat)| (t.p, tri_attr(t.p, t.n, t.uv, t.tangent, mat))).collect())
+ Some(tris.iter().zip(&d.mats).map(|(t, &mat)| (t.p, tri_attr(t.n, t.uv, t.tangent, mat))).collect())
}
Kind::Light(Light::Rect { width, height, visible: true, .. }) => {
- Some(card_tris(m, *width, *height).iter().zip(&d.mats).map(|((v, dir), &mat)| (*v, tri_attr(*v, [*dir; 3], [Vec2::ZERO; 3], None, mat))).collect())
+ Some(card_tris(m, *width, *height).iter().zip(&d.mats).map(|((v, dir), &mat)| (*v, tri_attr([*dir; 3], [Vec2::ZERO; 3], None, mat))).collect())
}
_ => None,
})
@@ -2609,8 +2617,8 @@ pub fn model_sections(kept: &[(usize, u32, u32)]) -> (Vec<(usize, u32, u32)>, Ve
}
/// A model's triangle as its mesh holds it: its attributes with its section and its index in it.
-pub fn section_attr(p: [Vec3; 3], n: [Vec3; 3], uv: [Vec2; 3], tangent: Option<(Vec3, f32)>, section: u32, rank: u32) -> GpuTriAttr {
- let mut a = tri_attr(p, n, uv, tangent, section);
+pub fn section_attr(n: [Vec3; 3], uv: [Vec2; 3], tangent: Option<CornerTangents>, section: u32, rank: u32) -> GpuTriAttr {
+ let mut a = tri_attr(n, uv, tangent, section);
a.x[3] = f32::from_bits(rank);
a
}
@@ -2717,43 +2725,28 @@ fn push_tri(
p: [Vec3; 3],
n: [Vec3; 3],
uv: [Vec2; 3],
- tangent: Option<(Vec3, f32)>,
+ tangent: Option<CornerTangents>,
mat: u32,
flags: u32,
) {
tris.push([p[0].into(), p[1].into(), p[2].into()]);
tri_flags.push(flags);
- attrs.push(tri_attr(p, n, uv, tangent, mat));
-}
-
-/// Shading attributes of a triangle (normals, UVs, tangent frame, texel density, material).
-pub fn tri_attr(p: [Vec3; 3], n: [Vec3; 3], uv: [Vec2; 3], tangent: Option<(Vec3, f32)>, mat: u32) -> GpuTriAttr {
- // (Whether the tangent is the first corner's own: `indexed::OWN_TANGENT`.)
- let own = if tangent.is_some() { crate::indexed::OWN_TANGENT } else { 0 };
- // Per-triangle tangent frame from UVs (glTF convention: v grows downward in the image).
- let (t, sign) = tangent.unwrap_or_else(|| {
- let (e1, e2) = (p[1] - p[0], p[2] - p[0]);
- let (d1, d2) = (uv[1] - uv[0], uv[2] - uv[0]);
- let det = d1.x * d2.y - d2.x * d1.y;
- if det.abs() < 1e-12 {
- let any = if n[0].x.abs() < 0.9 { Vec3::X } else { Vec3::Y };
- return (n[0].cross(any).normalize(), 1.0);
- }
- let r = 1.0 / det;
- let t = ((e1 * d2.y - e2 * d1.y) * r).normalize_or_zero();
- let b = (e2 * d1.x - e1 * d2.x) * r;
- // glTF/MikkTSpace: bitangent = cross(N, T) * w, pointing toward decreasing v (image "up").
- let w = if n[0].cross(t).dot(b) < 0.0 { 1.0 } else { -1.0 };
- (t, w)
- });
+ attrs.push(tri_attr(n, uv, tangent, mat));
+}
+
+/// Shading attributes of a triangle: normals, UVs, its tangents if it has them, its material.
+pub fn tri_attr(n: [Vec3; 3], uv: [Vec2; 3], tangent: Option<CornerTangents>, mat: u32) -> GpuTriAttr {
+ let t = |c: usize| tangent.map_or([0.0; 4], |t| [t[c].0.x, t[c].0.y, t[c].0.z, t[c].1]);
// (Its texel density, for the mip choice, is the hit's to compute: pathtrace.wgsl `mesh_density`.)
GpuTriAttr {
n0: [n[0].x, n[0].y, n[0].z, uv[0].x],
n1: [n[1].x, n[1].y, n[1].z, uv[0].y],
n2: [n[2].x, n[2].y, n[2].z, uv[1].x],
uv: [uv[1].y, uv[2].x, uv[2].y, f32::from_bits(mat)],
- t: [t.x, t.y, t.z, sign],
- x: [f32::from_bits(own), 0.0, 0.0, 0.0],
+ t: t(0),
+ x: [0.0; 4],
+ t1: t(1),
+ t2: t(2),
}
}
@@ -2831,7 +2824,8 @@ mod instance_tests {
/// An instance's placed triangle and attributes equal flattening the same triangle at the instance transform: as
/// the flattening path has them (`Instance::flat`) against the triangle built in world space as `append_arrays`
/// builds it, under a transform that keeps the hand and under one that mirrors (the second and third vertex
- /// change places, the tangent frame changes hand), with distinct normals, UVs and vertex colours a vertex.
+ /// change places, the tangent frame changes hand), with distinct normals, UVs, tangents and vertex colours a
+ /// vertex.
#[test]
fn instance_matches_flattening() {
let p = [Vec3::new(0.0, 0.0, 0.0), Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, 0.5, 0.2)];
@@ -2839,7 +2833,8 @@ mod instance_tests {
let uv = [Vec2::new(0.0, 0.0), Vec2::new(1.0, 0.25), Vec2::new(0.5, 1.0)];
let colors = [1, 2, 3];
let keeps = Mat4::from_scale_rotation_translation(Vec3::splat(2.0), glam::Quat::from_rotation_y(0.7) * glam::Quat::from_rotation_x(-0.3), Vec3::new(5.0, 1.0, -3.0));
- let local = tri_attr(p, n, uv, None, 7);
+ let tg = [(Vec3::new(1.0, 0.1, 0.0).normalize(), 1.0), (Vec3::new(0.9, 0.0, 0.3).normalize(), 1.0), (Vec3::new(0.8, -0.2, 0.1).normalize(), 1.0)];
+ let local = tri_attr(n, uv, Some(tg), 7);
for (w, mirrored) in [(keeps, false), (keeps * Mat4::from_scale(Vec3::new(-1.0, 1.0, 1.0)), true)] {
assert_eq!(mirrors(w), mirrored);
let inst = Instance { mesh: 0, world: w, object: 3, cast_shadow: true, name: "x".into(), sub: None, hidden: false, masked: false, first_emitter: 0, rows: 0, bits: 0, prev: 0, verts: 0 };
@@ -2849,16 +2844,23 @@ mod instance_tests {
let order = if mirrored { [0, 2, 1] } else { [0, 1, 2] };
let nm = glam::Mat3::from_mat4(w).inverse().transpose();
let wp = order.map(|k| w.transform_point3(p[k]));
- let flat = tri_attr(wp, order.map(|k| (nm * n[k]).normalize()), order.map(|k| uv[k]), None, 7);
+ let hand = if mirrored { -1.0 } else { 1.0 };
+ let flat = tri_attr(order.map(|k| (nm * n[k]).normalize()), order.map(|k| uv[k]), Some(order.map(|k| (w.transform_vector3(tg[k].0).normalize(), tg[k].1 * hand))), 7);
for k in 0..3 {
assert!((Vec3::from(placed[k]) - wp[k]).length() < 1e-5, "mirrored {mirrored}: vertex {k}");
}
assert!((placed[1] - placed[0]).cross(placed[2] - placed[0]).dot(Vec3A::from(nm * n[0])) > 0.0, "mirrored {mirrored}: it faces as its normals do");
- for (a, b) in [(got.n0, flat.n0), (got.n1, flat.n1), (got.n2, flat.n2), (got.t, flat.t)] {
+ for (a, b) in [(got.n0, flat.n0), (got.n1, flat.n1), (got.n2, flat.n2), (got.t, flat.t), (got.t1, flat.t1), (got.t2, flat.t2)] {
assert!((Vec3::new(a[0], a[1], a[2]) - Vec3::new(b[0], b[1], b[2])).length() < 1e-5, "mirrored {mirrored}: {a:?} vs {b:?}");
assert_eq!(a[3], b[3], "mirrored {mirrored}: the UV packed there, the tangent frame's hand");
}
assert_eq!(got.uv, flat.uv, "mirrored {mirrored}");
+ // (`placed_tri` places a triangle the same way.)
+ let (_, pn, puv, ptg) = placed_tri(w, &p, &n, &uv, Some(tg));
+ let by = tri_attr(pn, puv, ptg, 7);
+ for (a, b) in [(by.n0, flat.n0), (by.n1, flat.n1), (by.n2, flat.n2), (by.t, flat.t), (by.t1, flat.t1), (by.t2, flat.t2)] {
+ assert!((Vec3::new(a[0], a[1], a[2]) - Vec3::new(b[0], b[1], b[2])).length() < 1e-5 && a[3] == b[3], "mirrored {mirrored}, placed_tri: {a:?} vs {b:?}");
+ }
assert_eq!(got_colors, Some(order.map(|k| colors[k])), "mirrored {mirrored}: the vertex colours follow their vertices");
assert_eq!(got.x[1].to_bits(), 3);
}
@@ -2872,8 +2874,7 @@ mod instance_tests {
let mut cutout = GpuMaterial::default();
cutout.uv2[3] = 0.5;
let mats = [opaque, cutout];
- let p = [Vec3::ZERO, Vec3::X, Vec3::Y];
- let a = |m: u32| tri_attr(p, [Vec3::Z; 3], [Vec2::ZERO, Vec2::X, Vec2::Y], None, m);
+ let a = |m: u32| tri_attr([Vec3::Z; 3], [Vec2::ZERO, Vec2::X, Vec2::Y], None, m);
let inst = |shadow: bool| Instance { mesh: 0, world: Mat4::IDENTITY, object: 0, cast_shadow: shadow, name: "x".into(), sub: None, hidden: false, masked: false, first_emitter: 0, rows: 0, bits: 0, prev: 0, verts: 0 };
assert_eq!(instance_tri_flags(&inst(true), &a(0), &mats), 0);
assert_eq!(instance_tri_flags(&inst(true), &a(1), &mats), TRI_MASKED);
diff --git a/renderer/src/skin.rs b/renderer/src/skin.rs
index a46631b..3a19c86 100644
--- a/renderer/src/skin.rs
+++ b/renderer/src/skin.rs
@@ -25,6 +25,49 @@ struct Prim {
skin: Option<(Vec<[u16; 4]>, Vec<[f32; 4]>)>,
}
+impl Prim {
+ /// A primitive with UVs and without tangents has them made (tangents.rs): a corner each, so a vertex whose
+ /// corners come out with different tangents is a vertex for each afterwards (its position, normal, UV, joints
+ /// and weights with it), as a file with tangents has them. A triangle the algorithm gives no frame has none (a
+ /// hand of 0); a primitive none of whose triangles has one stays as it is. Without normals: by each triangle's
+ /// own.
+ fn make_tangents(&mut self) {
+ let face = |k: usize| [0, 1, 2].map(|c| self.indices[k * 3 + c] as usize);
+ let made = crate::tangents::generate(self.indices.len() / 3, |k, c| {
+ let v = face(k);
+ let normal = match &self.normals {
+ Some(n) => n[v[c]],
+ None => (self.positions[v[1]] - self.positions[v[0]]).cross(self.positions[v[2]] - self.positions[v[0]]).normalize_or_zero(),
+ };
+ (self.positions[v[c]].to_array(), normal.to_array(), self.uvs[v[c]].to_array())
+ });
+ if made.iter().all(|t| t.is_none()) {
+ return;
+ }
+ // (A vertex of the file and a tangent: a vertex. `from`: the file's vertex each is.)
+ let mut seen: HashMap<(u32, [u32; 4]), u32> = HashMap::new();
+ let (mut from, mut tangents, mut indices) = (vec![], vec![], Vec::with_capacity(self.indices.len()));
+ for (k, t) in made.iter().enumerate() {
+ for c in 0..3 {
+ let (v, tangent) = (self.indices[k * 3 + c], t.map_or([0.0; 4], |t| t[c]));
+ indices.push(*seen.entry((v, tangent.map(f32::to_bits))).or_insert_with(|| {
+ from.push(v as usize);
+ tangents.push(tangent);
+ from.len() as u32 - 1
+ }));
+ }
+ }
+ fn pick<T: Copy>(of: &[T], from: &[usize]) -> Vec<T> {
+ from.iter().map(|&v| of[v]).collect()
+ }
+ self.positions = pick(&self.positions, &from);
+ self.uvs = pick(&self.uvs, &from);
+ self.normals = self.normals.as_ref().map(|n| pick(n, &from));
+ self.skin = self.skin.as_ref().map(|(j, w)| (pick(j, &from), pick(w, &from)));
+ (self.tangents, self.indices) = (Some(tangents), indices);
+ }
+}
+
#[derive(Clone, Copy)]
enum Path {
Translation,
@@ -63,7 +106,7 @@ pub struct ModelTri {
pub p: [Vec3; 3],
pub n: [Vec3; 3],
pub uv: [Vec2; 3],
- pub tangent: Option<(Vec3, f32)>,
+ pub tangent: Option<crate::scene::CornerTangents>,
/// glTF material index.
pub material: Option<usize>,
}
@@ -144,16 +187,21 @@ impl Model {
(Some(_), Some(j), Some(w)) => Some((j.into_u16().collect(), w.into_f32().collect())),
_ => None,
};
- prims.push(Prim {
+ let uvs: Option<Vec<Vec2>> = r.read_tex_coords(0).map(|t| t.into_f32().map(Vec2::from).collect());
+ let mut p = Prim {
node: ni,
material: prim.material().index(),
normals: r.read_normals().map(|it| it.map(Vec3::from).collect()),
- uvs: r.read_tex_coords(0).map(|t| t.into_f32().map(Vec2::from).collect()).unwrap_or_else(|| vec![Vec2::ZERO; n]),
tangents: r.read_tangents().map(|t| t.collect()),
indices: r.read_indices().map(|i| i.into_u32().collect()).unwrap_or_else(|| (0..n as u32).collect()),
positions,
skin,
- });
+ uvs: uvs.clone().unwrap_or_else(|| vec![Vec2::ZERO; n]),
+ };
+ if uvs.is_some() && p.tangents.is_none() {
+ p.make_tangents();
+ }
+ prims.push(p);
}
}
let mut names = HashMap::new();
@@ -398,9 +446,9 @@ impl Model {
// (A node that mirrors: the winding stays front-facing, as `triangles` has it.)
for t in p.indices.chunks_exact(3) {
let (a, b, c) = if mirrored { (t[0], t[2], t[1]) } else { (t[0], t[1], t[2]) };
- // (A triangle's tangent is its first corner's.)
- let tangent = p.tangents.as_ref().map(|tv| tv[a as usize]);
- out.push([corner(a as usize, tangent), corner(b as usize, tangent), corner(c as usize, tangent)]);
+ // (A hand of 0: the vertex has none.)
+ let tangent = |v: u32| p.tangents.as_ref().map(|tv| tv[v as usize]).filter(|t| t[3] != 0.0);
+ out.push([corner(a as usize, tangent(a)), corner(b as usize, tangent(b)), corner(c as usize, tangent(c))]);
}
}
Ok(out)
@@ -424,7 +472,7 @@ impl Model {
let nm = Mat3::from_mat4(m).inverse().transpose();
let pos: Vec<Vec3> = p.positions.iter().map(|v| m.transform_point3(*v)).collect();
let nrm: Option<Vec<Vec3>> = p.normals.as_ref().map(|n| n.iter().map(|v| (nm * *v).normalize_or_zero()).collect());
- // (A mirroring placement: the winding stays front-facing, and an authored tangent's frame changes hand.)
+ // (A mirroring placement: the winding stays front-facing, and a tangent's frame changes hand.)
let flip = !local && m.determinant() < 0.0;
for t in p.indices.chunks_exact(3) {
let (a, b, c) = if flip { (t[0], t[2], t[1]) } else { (t[0], t[1], t[2]) };
@@ -432,10 +480,7 @@ impl Model {
let tp = [pos[a], pos[b], pos[c]];
let gn = (tp[1] - tp[0]).cross(tp[2] - tp[0]).normalize_or_zero();
let n = nrm.as_ref().map(|n| [n[a], n[b], n[c]]).unwrap_or([gn; 3]);
- let tangent = p.tangents.as_ref().map(|tv| {
- let tt = tv[a];
- (m.transform_vector3(Vec3::new(tt[0], tt[1], tt[2])).normalize_or_zero(), if flip { -tt[3] } else { tt[3] })
- });
+ let tangent = p.tangents.as_ref().map(|tv| [a, b, c].map(|v| (m.transform_vector3(Vec3::new(tv[v][0], tv[v][1], tv[v][2])).normalize_or_zero(), if flip { -tv[v][3] } else { tv[v][3] })));
out.push((p.node, ModelTri { p: tp, n, uv: [p.uvs[a], p.uvs[b], p.uvs[c]], tangent, material: p.material }));
}
}
@@ -505,9 +550,10 @@ impl Model {
let gn = (tp[1] - tp[0]).cross(tp[2] - tp[0]).normalize_or_zero();
let n = nrm.as_ref().map(|n| [n[a], n[b], n[c]]).unwrap_or([gn; 3]);
let tangent = p.tangents.as_ref().map(|tv| {
- let tt = tv[a];
- let by = blends.get(a).copied().unwrap_or(m);
- (by.transform_vector3(Vec3::new(tt[0], tt[1], tt[2])).normalize_or_zero(), if mirrored { -tt[3] } else { tt[3] })
+ [a, b, c].map(|v| {
+ let by = blends.get(v).copied().unwrap_or(m);
+ (by.transform_vector3(Vec3::new(tv[v][0], tv[v][1], tv[v][2])).normalize_or_zero(), if mirrored { -tv[v][3] } else { tv[v][3] })
+ })
});
out.push(ModelTri { p: tp, n, uv: [p.uvs[a], p.uvs[b], p.uvs[c]], tangent, material: p.material });
}
@@ -586,6 +632,46 @@ mod tests {
assert!(posed.iter().any(|t| (0..3).all(|k| (t.p[k] - w.transform_point3(local[0].1.p[k])).length() < 1e-5)));
}
+ /// A primitive with UVs and without tangents has them made, a corner each. Two quads along an edge, the texture
+ /// mirrored across it (the edge's two vertices have one UV for both sides): afterwards each of the two is a
+ /// vertex a side, with its side's tangent (u's direction there) and hand (the bitangent points up the image on
+ /// both), and with the file's position, normal, UV, joints and weights. One whose UVs have no area keeps none.
+ #[test]
+ fn a_primitive_without_tangents_has_them_made_a_corner_each() {
+ let at = [(-1.0, 0.0), (0.0, 0.0), (0.0, 1.0), (-1.0, 1.0), (1.0, 0.0), (1.0, 1.0)];
+ let prim = |uv: &dyn Fn(f32, f32) -> Vec2| Prim {
+ node: 0,
+ material: None,
+ positions: at.iter().map(|&(x, y)| Vec3::new(x, y, 0.0)).collect(),
+ normals: Some(vec![Vec3::Z; 6]),
+ uvs: at.iter().map(|&(x, y)| uv(x, y)).collect(),
+ tangents: None,
+ indices: vec![0, 1, 2, 0, 2, 3, 1, 4, 5, 1, 5, 2],
+ skin: Some(((0..6).map(|k| [k, 0, 0, 0]).collect(), (0..6).map(|k| [1.0 - k as f32 * 0.1, k as f32 * 0.1, 0.0, 0.0]).collect())),
+ };
+ let mut p = prim(&|x, y| Vec2::new(x.abs(), 1.0 - y));
+ p.make_tangents();
+ let tangents = p.tangents.as_ref().expect("tangents");
+ assert_eq!((p.positions.len(), tangents.len(), p.indices.len()), (8, 8, 12), "the edge's two vertices twice");
+ let (joints, weights) = p.skin.as_ref().unwrap();
+ for (k, tri) in p.indices.chunks_exact(3).enumerate() {
+ let side = if k < 2 { -1.0 } else { 1.0 };
+ for &v in tri {
+ let (v, from) = (v as usize, joints[v as usize][0] as usize);
+ assert_eq!(tangents[v], [side, 0.0, 0.0, side], "triangle {k}: its side's tangent and hand");
+ let up = Vec3::Z.cross(Vec3::new(tangents[v][0], tangents[v][1], tangents[v][2])) * tangents[v][3];
+ assert_eq!(up, Vec3::Y, "triangle {k}: the bitangent points up the image");
+ assert_eq!((p.positions[v], p.normals.as_ref().unwrap()[v], p.uvs[v]), (Vec3::new(at[from].0, at[from].1, 0.0), Vec3::Z, Vec2::new(at[from].0.abs(), 1.0 - at[from].1)), "triangle {k}: the file's vertex {from}");
+ assert_eq!(weights[v], [1.0 - from as f32 * 0.1, from as f32 * 0.1, 0.0, 0.0], "triangle {k}: its weights");
+ }
+ }
+ // (The file's triangles, in its order: each corner the vertex it was.)
+ assert_eq!(p.indices.iter().map(|&v| joints[v as usize][0]).collect::<Vec<_>>(), [0, 1, 2, 0, 2, 3, 1, 4, 5, 1, 5, 2]);
+ let mut flat = prim(&|_, _| Vec2::splat(0.5));
+ flat.make_tangents();
+ assert!(flat.tangents.is_none() && flat.positions.len() == 6, "UVs without area: no tangents, the primitive as it was");
+ }
+
/// An authored tangent's frame changes hand where a placement mirrors (the winding is swapped there too); in a
/// node's own space it is as authored (the instance that places the node says whether it mirrors).
#[test]
@@ -594,7 +680,7 @@ mod tests {
for p in &mut m.prims {
p.tangents = Some(vec![[1.0, 0.0, 0.0, 1.0]; p.positions.len()]);
}
- let hand = |t: &ModelTri| t.tangent.unwrap().1;
+ let hand = |t: &ModelTri| t.tangent.unwrap()[0].1;
let straight = Mat4::from_translation(Vec3::new(10.0, 0.0, 0.0));
let mirrored = straight * Mat4::from_scale(Vec3::new(-1.0, 1.0, 1.0));
assert!(m.triangles(straight, None, None).unwrap().iter().all(|t| hand(t) == 1.0));
@@ -620,12 +706,18 @@ mod tests {
/// primitives on nodes (`RIGID`), at rest and posed.
#[test]
fn corners_placed_by_the_palette_are_the_models_triangles() {
- let arm = Model::new(gltf::import("../tests/render/data/arm.glb").unwrap()).unwrap();
+ let mut arm = Model::new(gltf::import("../tests/render/data/arm.glb").unwrap()).unwrap();
// (Vertices two joints hold, weights that do not sum to one, a primitive with tangents and one without
// normals, a mesh on a node beside the skin that mirrors it; a joint turned about an axis that is neither
// the normals' nor the tangents'.)
- let blend = Model::new(gltf::import("../tests/render/data/skin-blend.glb").unwrap()).unwrap();
- let rigid = Model::new(gltf::import_slice(RIGID.as_bytes()).unwrap()).unwrap();
+ let mut blend = Model::new(gltf::import("../tests/render/data/skin-blend.glb").unwrap()).unwrap();
+ let mut rigid = Model::new(gltf::import_slice(RIGID.as_bytes()).unwrap()).unwrap();
+ // (Every vertex a tangent that is no other's, so a corner that took another vertex's is seen.)
+ for m in [&mut arm, &mut blend, &mut rigid] {
+ for p in &mut m.prims {
+ p.tangents = Some((0..p.positions.len()).map(|i| Vec3::new(1.0, 0.1 * i as f32, 0.03 * i as f32).normalize().extend(1.0).to_array()).collect());
+ }
+ }
let pose = |clip: &str, time| desc::Animation { clip: clip.into(), time, r#loop: true, nodes: Default::default() };
let mut seen = 0;
let bends = || vec![None, Some(pose("bend", 0.3)), Some(pose("bend", 0.8))];
@@ -642,15 +734,29 @@ mod tests {
if c.t[3].to_bits() & CORNER_NORMAL != 0 {
assert!((n - t.n[k]).length() < 1e-5, "normal {n} against {}", t.n[k]);
}
- if let (0, Some((tt, _))) = (k, t.tangent) {
- assert!((tg - tt).length() < 1e-5, "tangent {tg} against {tt}");
- }
+ let tc = t.tangent.expect("a tangent a corner");
+ assert!((tg - tc[k].0).length() < 1e-5, "tangent {tg} against {}", tc[k].0);
seen += 1;
}
}
}
}
assert_eq!(seen, 36 + 648 + 12, "corners compared");
+ // A vertex whose tangent has no hand has none: its corners do not say they have one, the others do.
+ rigid.prims[0].tangents.as_mut().unwrap()[0] = [0.0; 4];
+ let says: Vec<bool> = rigid.skin_source(None, None).unwrap().iter().flatten().map(|c| c.t[3].to_bits() & CORNER_TANGENT != 0).collect();
+ let without = rigid.prims.iter().enumerate().map(|(k, p)| if k == 0 { p.indices.iter().filter(|&&v| v == 0).count() } else { 0 }).sum::<usize>();
+ assert_eq!((says.iter().filter(|s| !**s).count(), without > 0), (without, true), "the corners at the vertex without a tangent");
+ rigid.prims[0].tangents.as_mut().unwrap()[0] = [1.0, 0.0, 0.0, 1.0];
+ // A model's triangles a node (`node_triangles`) are `triangles`', their tangents a corner each too.
+ for a in [None, Some(pose("move", 0.5))] {
+ let (by_node, whole) = (rigid.node_triangles(Mat4::IDENTITY, a.as_ref(), &|_| true, false).unwrap(), rigid.triangles(Mat4::IDENTITY, None, a.as_ref()).unwrap());
+ assert_eq!(by_node.len(), whole.len());
+ for ((_, t), w) in by_node.iter().zip(&whole) {
+ assert_eq!((t.p, t.tangent.unwrap()), (w.p, w.tangent.unwrap()));
+ assert!(t.tangent.unwrap()[0].0 != t.tangent.unwrap()[1].0, "a tangent a corner");
+ }
+ }
assert_eq!((blend.palette_len(), blend.skin_source(None, None).unwrap().len()), (4, 72), "the identity, two joints and the badge's node; 72 triangles");
// The badge's node mirrors it: its corners are in the order that keeps it front-facing, and a pose that does
// not mirror it has them in another.
@@ -747,7 +853,7 @@ mod bench {
let mut x = 0.0;
for _ in 0..100 {
for t in &tris {
- x += crate::scene::tri_attr(t.p, t.n, t.uv, t.tangent, 0).t[0];
+ x += crate::scene::tri_attr(t.n, t.uv, t.tangent, 0).t[0];
}
}
eprintln!("tri_attr: {:.3} ms per pose ({x})", t0.elapsed().as_secs_f64() * 1000.0 / 100.0);
diff --git a/renderer/src/tangents.rs b/renderer/src/tangents.rs
new file mode 100644
index 0000000..44009e7
--- /dev/null
+++ b/renderer/src/tangents.rs
@@ -0,0 +1,138 @@
+//! Tangents for geometry whose file has none: one a corner of each triangle, by the algorithm normal maps are baked
+//! against (MikkTSpace), from the corners' positions, normals and UVs. Corners of one vertex that come out with
+//! different tangents (a seam of a mirrored texture) are vertices apart afterwards (indexed.rs).
+
+/// The tangents of `n` triangles, a corner each: the direction of u on the surface and the frame's hand (the
+/// bitangent is cross(normal, tangent) x hand and points up the image). `corner(k, c)`: corner c of triangle k: its
+/// position, its normal and its UV (v growing down the image). None: a triangle the algorithm gives no frame (it has
+/// no area, on the surface or in the texture, and no neighbour to take one from), or one that is not finite.
+pub fn generate(n: usize, corner: impl Fn(usize, usize) -> ([f32; 3], [f32; 3], [f32; 2])) -> Vec<Option<[[f32; 4]; 3]>> {
+ struct Faces<F> {
+ corner: F,
+ out: Vec<Option<[[f32; 4]; 3]>>,
+ }
+ impl<F: Fn(usize, usize) -> ([f32; 3], [f32; 3], [f32; 2])> bevy_mikktspace::Geometry for Faces<F> {
+ fn num_faces(&self) -> usize {
+ self.out.len()
+ }
+ fn num_vertices_of_face(&self, _: usize) -> usize {
+ 3
+ }
+ fn position(&self, face: usize, vert: usize) -> [f32; 3] {
+ (self.corner)(face, vert).0
+ }
+ fn normal(&self, face: usize, vert: usize) -> [f32; 3] {
+ (self.corner)(face, vert).1
+ }
+ fn tex_coord(&self, face: usize, vert: usize) -> [f32; 2] {
+ (self.corner)(face, vert).2
+ }
+ fn set_tangent(&mut self, space: Option<bevy_mikktspace::TangentSpace>, face: usize, vert: usize) {
+ // (The algorithm's hand is for a v that grows up the image: ours is the other.)
+ let t = space.map(|s| s.tangent_encoded()).map(|t| [t[0], t[1], t[2], -t[3]]);
+ // (A corner without a frame, or with one that is not finite, keeps its hand of 0: see below.)
+ let whole = t.filter(|t| t.iter().all(|x| x.is_finite()) && t[..3].iter().any(|x| *x != 0.0));
+ if let (Some(t), Some(tri)) = (whole, &mut self.out[face]) {
+ tri[vert] = t;
+ }
+ }
+ }
+ let mut faces = Faces { corner, out: vec![Some([[0.0; 4]; 3]); n] };
+ // (Its error type has no value: it cannot fail.)
+ let _ = bevy_mikktspace::generate_tangents(&mut faces);
+ // (A triangle with a corner the algorithm gave nothing has none.)
+ for t in &mut faces.out {
+ if t.is_some_and(|t| t.iter().any(|c| c[3] == 0.0)) {
+ *t = None;
+ }
+ }
+ faces.out
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use glam::{Vec2, Vec3};
+
+ /// A quad in the xy plane facing +z, its texture upright (u along x, the image's top at the larger y): the
+ /// tangent is +x and the hand 1, the bitangent cross(n, t) x hand pointing up the image. With the texture
+ /// mirrored (u against x) the tangent is -x and the hand -1: the bitangent still points up the image.
+ #[test]
+ fn a_quads_tangent_is_along_u_and_its_bitangent_up_the_image() {
+ let p = [Vec3::ZERO, Vec3::X, Vec3::new(1.0, 1.0, 0.0), Vec3::Y];
+ let tris = [[0, 1, 2], [0, 2, 3]];
+ for (what, mirrored) in [("upright", false), ("mirrored", true)] {
+ let uv = |v: Vec3| Vec2::new(if mirrored { 1.0 - v.x } else { v.x }, 1.0 - v.y);
+ let got = generate(2, |k, c| (p[tris[k][c]].to_array(), [0.0, 0.0, 1.0], uv(p[tris[k][c]]).to_array()));
+ let along = if mirrored { -1.0 } else { 1.0 };
+ for t in got.iter().flat_map(|t| t.expect("a frame")) {
+ assert!((Vec3::new(t[0], t[1], t[2]) - Vec3::X * along).length() < 1e-5 && t[3] == along, "{what}: {t:?}");
+ let up = Vec3::Z.cross(Vec3::new(t[0], t[1], t[2])) * t[3];
+ assert!((up - Vec3::Y).length() < 1e-5, "{what}: the bitangent points up the image: {up}");
+ }
+ }
+ }
+
+ /// A triangle without area in the texture and with no neighbour has no frame; one beside it keeps its own.
+ #[test]
+ fn a_triangle_without_uvs_has_no_frame() {
+ let p = [Vec3::ZERO, Vec3::X, Vec3::Y, Vec3::new(5.0, 0.0, 0.0), Vec3::new(6.0, 0.0, 0.0), Vec3::new(5.0, 1.0, 0.0)];
+ let got = generate(2, |k, c| (p[k * 3 + c].to_array(), [0.0, 0.0, 1.0], if k == 0 { [p[c].x, 1.0 - p[c].y] } else { [0.5, 0.5] }));
+ assert!(got[0].is_some() && got[1].is_none(), "{got:?}");
+ }
+
+ /// (A measurement, not a test: `cargo test --release -- --ignored --nocapture tangents::tests::how_long`, with
+ /// THREERT_TANGENT_FILES=<a.glb,b.glb>.) The time to make tangents for every triangle of the files, and how many
+ /// vertices more they have afterwards.
+ #[test]
+ #[ignore]
+ fn how_long() {
+ let files = std::env::var("THREERT_TANGENT_FILES").unwrap_or_default();
+ for f in files.split(',').filter(|f| !f.is_empty()) {
+ let (doc, bufs, _) = gltf::import(f).unwrap();
+ let (mut tris, mut verts, mut split, mut none, mut secs) = (0usize, 0usize, 0usize, 0usize, 0.0);
+ let mut against = [0usize; 4];
+ for mesh in doc.meshes() {
+ for prim in mesh.primitives() {
+ let r = prim.reader(|b| Some(&bufs[b.index()]));
+ let p: Vec<[f32; 3]> = r.read_positions().unwrap().collect();
+ let Some(n) = r.read_normals().map(|n| n.collect::<Vec<[f32; 3]>>()) else { continue };
+ let uv: Vec<[f32; 2]> = r.read_tex_coords(0).map(|t| t.into_f32().collect()).unwrap_or_else(|| vec![[0.0; 2]; p.len()]);
+ let ix: Vec<u32> = r.read_indices().map(|i| i.into_u32().collect()).unwrap_or_else(|| (0..p.len() as u32).collect());
+ let t0 = std::time::Instant::now();
+ let made = generate(ix.len() / 3, |k, c| {
+ let v = ix[k * 3 + c] as usize;
+ (p[v], n[v], uv[v])
+ });
+ secs += t0.elapsed().as_secs_f64();
+ let mut seen = std::collections::HashSet::new();
+ for (k, t) in made.iter().enumerate() {
+ none += t.is_none() as usize;
+ for c in 0..3 {
+ seen.insert((ix[k * 3 + c], t.map_or([0u32; 4], |t| t[c].map(f32::to_bits))));
+ }
+ }
+ (tris, verts, split) = (tris + ix.len() / 3, verts + p.len(), split + seen.len());
+ // (Against the file's own, where it has them: the angle between the two and the hands.)
+ if let Some(own) = r.read_tangents().map(|t| t.collect::<Vec<[f32; 4]>>()) {
+ for (k, t) in made.iter().enumerate() {
+ let Some(t) = t else { continue };
+ for c in 0..3 {
+ let o = own[ix[k * 3 + c] as usize];
+ let cos = (t[c][0] * o[0] + t[c][1] * o[1] + t[c][2] * o[2]).clamp(-1.0, 1.0);
+ against[0] += 1;
+ against[1] += (cos.acos().to_degrees() > 1.0) as usize;
+ against[2] += (cos.acos().to_degrees() > 10.0) as usize;
+ against[3] += (t[c][3] != o[3]) as usize;
+ }
+ }
+ }
+ }
+ }
+ eprintln!("{f}: {tris} triangles in {secs:.2} s ({:.2} M a second); {verts} vertices -> {split} ({:+.1} %); {none} triangles without a frame", tris as f64 / secs / 1e6, (split as f64 / verts as f64 - 1.0) * 100.0);
+ if against[0] > 0 {
+ eprintln!(" against the file's tangents: {} corners, {} more than 1 degree off, {} more than 10, {} of the other hand", against[0], against[1], against[2], against[3]);
+ }
+ }
+ }
+}
diff --git a/renderer/web/Cargo.lock b/renderer/web/Cargo.lock
index a96a9ae..6f17b62 100644
--- a/renderer/web/Cargo.lock
+++ b/renderer/web/Cargo.lock
@@ -213,6 +213,12 @@ version = "0.23.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"
+[[package]]
+name = "bevy_mikktspace"
+version = "1.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bff34eb29ff4b8a8688bc7299f14fb6b597461ca80fec03ed7d22939ab33e48f"
+
[[package]]
name = "bit-set"
version = "0.10.0"
@@ -2677,6 +2683,7 @@ version = "0.1.0"
dependencies = [
"anyhow",
"base64 0.23.1",
+ "bevy_mikktspace",
"bytemuck",
"cc",
"glam 0.30.10",
diff --git a/tests/render/data/tangent-blend.glb b/tests/render/data/tangent-blend.glb
new file mode 100644
index 0000000..0e92c5a
Binary files /dev/null and b/tests/render/data/tangent-blend.glb differ
diff --git a/tests/render/data/tangent-hands.glb b/tests/render/data/tangent-hands.glb
new file mode 100644
index 0000000..feb06a9
Binary files /dev/null and b/tests/render/data/tangent-hands.glb differ
diff --git a/tests/render/material-function-file-hand.ts b/tests/render/material-function-file-hand.ts
new file mode 100644
index 0000000..4753538
--- /dev/null
+++ b/tests/render/material-function-file-hand.ts
@@ -0,0 +1,27 @@
+// The hand a file gives a tangent is the one a material's function sees. tests/render/data/tangent-hands.glb: two
+// quads of one material with TANGENT +x at every vertex, the left one's hand 1 (its bitangent, cross(normal,
+// tangent) x hand, points up), the right one's -1 (down). The function emits 5 nits where the bitangent it is given
+// points up and 2 where it points down.
+import { MaterialFunction, GLTFModel } from "@threert/scene";
+import { camera, result, sceneWithSky, type TestMeta } from "./lib.ts";
+
+const URI = "tests/render/data/tangent-hands.glb";
+
+export const test: TestMeta = {
+ id: "material/function-file-hand", features: ["material-function", "gltf", "instancing"], reference: "analytic", temporal: false,
+ metric: { kind: "ratio", a: [0.6, 0.4, 0.75, 0.6], b: [0.25, 0.4, 0.4, 0.6], expected: 0.4, tolerance: 0.01 },
+ requires: [URI],
+ note: "right quad (hand -1: the bitangent down) over left quad (hand 1: up): 2 / 5",
+};
+
+const UP = new MaterialFunction("bitangent_up", {
+ params: {},
+ code: `
+ o.base = vec3<f32>(0.0);
+ o.emissive = vec3<f32>(select(2.0, 5.0, i.b.y > 0.0));`,
+});
+
+export default () => {
+ const scene = sceneWithSky(0);
+ return result(scene, camera(scene, [0, 0, 8], [0, 0, 0]), [new GLTFModel(URI, { functions: { side: UP.with({}) } })]);
+};
diff --git a/tests/render/material-function-vertex-tangents.ts b/tests/render/material-function-vertex-tangents.ts
new file mode 100644
index 0000000..8a20a8c
--- /dev/null
+++ b/tests/render/material-function-vertex-tangents.ts
@@ -0,0 +1,27 @@
+// A hit's tangent is its triangle's three vertices' at the hit, not one of them. tests/render/data/tangent-blend.glb:
+// a quad whose file has TANGENT +x on its two left vertices and +y on its two right ones, so across it the tangent
+// turns from x to y: at a fraction s of its width it is (1 - s, s), made of unit length. The function emits
+// 1 + 4 |t.y| nits: 1.6 near the left edge, 4.9 near the right.
+import { MaterialFunction, GLTFModel } from "@threert/scene";
+import { camera, result, sceneWithSky, type TestMeta } from "./lib.ts";
+
+const URI = "tests/render/data/tangent-blend.glb";
+
+export const test: TestMeta = {
+ id: "material/function-vertex-tangents", features: ["material-function", "gltf", "instancing"], reference: "analytic", temporal: false,
+ metric: { kind: "ratio", a: [0.64, 0.4, 0.71, 0.6], b: [0.29, 0.4, 0.36, 0.6], expected: 3.097, tolerance: 0.04 },
+ requires: [URI],
+ note: "near the right edge (the tangent nearly +y) over near the left edge (nearly +x): one tangent a triangle would give 1",
+};
+
+const BY_Y = new MaterialFunction("tangent_by_y", {
+ params: {},
+ code: `
+ o.base = vec3<f32>(0.0);
+ o.emissive = vec3<f32>(1.0 + 4.0 * abs(i.t.y));`,
+});
+
+export default () => {
+ const scene = sceneWithSky(0);
+ return result(scene, camera(scene, [0, 0, 8], [0, 0, 0]), [new GLTFModel(URI, { functions: { side: BY_Y.with({}) } })]);
+};