Models and buildings are lit per vertex, the colour inside the clamp (#2899)

1.12.1 lights models and buildings per vertex and interpolates the result. benilla lit them per pixel, and clamped the light sum before the material colour multiplied it.

- **#509:** M2 lighting (the `Model2.bls` vertex programs under the stock `M2UseShaders` 1, `M2UsePixelShaders` 0) and WMO exterior T&L now run in the vertex stage.
- **#530:** the vertex and model colour is the lit material inside the one clamp. For WMO this is MOCV, through GL colour material (`0x59cfec`, `0x59cff3`). For M2 it is `c28`, the model colour times the batch's M2Color (`0x70c4d3`-`0x70c712`). The programs clamp E first only when a point light is bound.
- **#115:** the clutter grey (`0xffc0c0c0`, `0x6b2615`) sits inside the clamp.

Tests:
- an interpreter runs `Model2.bls` programs 135 and 136 against the shader's mirror;
- both program levels pin the clamp law per light count;
- per-vertex and clamp-order checks run on both shaders.

Fixes #509
Fixes #530
Fixes #115

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Sam Sung
2026-10-31 18:30:09 +07:00
committed by GitHub
parent 134f037600
commit 3bee60cb71
8 changed files with 932 additions and 348 deletions
+498
View File
@@ -459,6 +459,504 @@ mod tests {
);
}
/// The reference lights in the vertex stage: `Model2.bls` evaluates the SH lobe and writes the
/// colour to `oD0`, and WMO and clutter run FFP T&L, so the colour is clamped at each vertex
/// and interpolated. The light lanes live in `vertex_light`, the vertex stage writes its result
/// to the interpolated `primary`, and the fragment only modulates the texel by it.
#[test]
fn the_model_light_is_evaluated_per_vertex() {
let src = include_str!("shaders/wow_model.wgsl");
let at = |needle: &str| {
src.find(needle)
.unwrap_or_else(|| panic!("`{needle}` is gone"))
};
let light = &src[at("fn vertex_light(")..at("@vertex")];
let vertex = &src[at("@vertex")..at("@fragment")];
let fragment = &src[at("@fragment")..];
for (lane, term) in [
("the exterior SH lobe", "wow_light.sh_c10_r.w + sun_dc.x"),
("the FFP N·L", "let ndotl = max(dot(n_lit, L), 0.0);"),
(
"the interior probe",
"dot(wow_light.prop_probes[probe + 0u], n1)",
),
] {
assert!(light.contains(term), "{lane} left `vertex_light`");
}
assert!(
vertex.contains("out.primary = vertex_light(out.world_normal, point_lit, vcol,"),
"the vertex stage no longer lights its vertex"
);
assert!(
src.contains(" @location(8) primary: vec3<f32>,\n"),
"the lit colour must be interpolated across the triangle, never flat"
);
for term in [
"sh_c10",
"sh_c13",
"prop_probes",
"light_sun",
"light_diffuse",
"point_light_sum",
"vertex_light(",
] {
assert!(
!fragment.contains(term),
"the fragment evaluates `{term}` again — the reference lights per vertex"
);
}
assert!(
fragment.contains("var lit_rgb = base.rgb * in.primary;"),
"the fragment modulates the texel by the interpolated lit colour"
);
}
/// The vertex or model colour is the lit material, inside the one clamp, and the texel
/// multiplies the clamped result. The FFP takes it as GL_COLOR_MATERIAL on ambient and diffuse
/// (`0x59cfec`, `0x59cff3`-`0x59cffd`), so a WMO lights `clamp(MOCV·sum + emission)`.
/// `Model2.bls` takes it as `c28`, `[model+0x1a0]` × the batch's M2Color (`0x70c60a`-`0x70c654`,
/// written at `0x70c712`), and writes `c28·(E, 1) + c29` to the saturating `oD0`, clamping E
/// first only with a point light bound. The install tests below read that law in every lit
/// program and run two of them against the M2 lane.
#[test]
fn the_material_colour_is_lit_inside_the_one_clamp() {
let src = include_str!("shaders/wow_model.wgsl");
let at = |needle: &str| {
src.find(needle)
.unwrap_or_else(|| panic!("`{needle}` is gone"))
};
let light = &src[at("fn vertex_light(")..at("@vertex")];
let fragment = &src[at("@fragment")..];
for (why, line) in [
(
"the FFP sum is never clamped on its own",
"let sum_nl = wow_light.light_ambient.rgb + wow_light.light_diffuse.rgb * ndotl;",
),
(
"the window ambient saturates as its own byte add, never the sum",
"let sum_window = min(window_mid + vec3<f32>(16.0 / 255.0), vec3<f32>(1.0))\n \
+ window_mid * ndotl;",
),
(
"a WMO's MOCV multiplies the light sum inside the one clamp",
"return clamp(vcol.rgb * sum_wmo + sidn_e + highlight, vec3<f32>(0.0), vec3<f32>(1.0));",
),
(
"an M2's `c28` multiplies E inside the one clamp",
"return clamp(c * e + highlight, vec3<f32>(0.0), vec3<f32>(1.0));",
),
(
"E clamps first only with a point light bound",
"if (point_lit.w > 0.5) {\n e = clamp(e, vec3<f32>(0.0), vec3<f32>(1.0));\n }",
),
] {
assert!(light.contains(line), "{why}: `{line}` is gone");
}
assert!(
!light.contains("clamp(sun_lobe"),
"the SH lobe clamps before `c28` multiplies it again"
);
assert!(
src.contains("vo.color = vec4<f32>(1.0, 1.0, 1.0, in.color.a);"),
"Bevy folds the vertex colour into the texel again, outside the clamp"
);
assert!(
fragment
.contains("lit_rgb = base.rgb * m.tint.rgb * mix(vcol.rgb, in.primary, vcol.a);"),
"a TRANS batch is its clamped lit pass by MOCV.a over the unlit `tex × MOCV`"
);
}
/// A ground-clutter tuft's vertex colour, `0xffc0c0c0` on baked shadow and white elsewhere
/// (`0x6b260e`/`0x6b2615`), is the FFP's lit material: the detail-doodad pass commits the
/// chunk's lights (`0x681656`) and draws with colour material on ambient and diffuse
/// (`0x59cfec`), so the grey multiplies the light sum inside the one clamp.
#[test]
fn a_clutter_tufts_grey_is_lit_inside_the_clamp() {
let src = include_str!("shaders/wow_model.wgsl");
let at = |needle: &str| {
src.find(needle)
.unwrap_or_else(|| panic!("`{needle}` is gone"))
};
let light = &src[at("fn vertex_light(")..at("@vertex")];
let fragment = &src[at("@fragment")..];
assert!(
light.contains(
"return clamp(c * (sum_nl + point_lit.rgb) + highlight, vec3<f32>(0.0), vec3<f32>(1.0));"
),
"the tuft's grey left the clamp of its light sum"
);
assert!(
light.contains("let c = vcol.rgb * anim_tint * body_tint(fade_tag);"),
"the tuft's material colour is its vertex colour"
);
assert!(
!fragment.contains("albedo * in.primary"),
"the fragment multiplies the grey outside the clamp again"
);
}
/// The install's `Shaders\Vertex\Model2.bls`, or `None` (a skip) without an install.
fn model2_bls() -> Option<Vec<u8>> {
let data = benilla_formats::wow_data_or_skip!(None);
let mut chain = benilla_formats::open_chain(&data).expect("open chain");
let bls = chain
.read_file("Shaders\\Vertex\\Model2.bls")
.expect("read Model2.bls");
assert_eq!(
&bls[..8],
b"SVXG\x03\x00\x01\x00",
"a vertex shader file, version 0x10003"
);
Some(bls)
}
/// One level's 1800 programs in vertex shader id order: the level table holds a file offset
/// per level at `0xc` (`0x5951e6`), and each record is two empty parameter lists, the format
/// tag (2 Direct3D, 0 ARB), the code size and the code padded to 4 bytes (`0x598320`).
fn model2_level(bls: &[u8], level: usize) -> Vec<&[u8]> {
let word = |at: usize| u32::from_le_bytes(bls[at..at + 4].try_into().unwrap()) as usize;
let tag = if level == 1 { 2 } else { 0 };
let mut at = word(0xc + 4 * level);
let mut out = Vec::with_capacity(1800);
while out.len() < 1800 {
assert_eq!(
(word(at), word(at + 4), word(at + 8)),
(0, 0, tag),
"level {level} record {} at {at:#x}",
out.len()
);
let size = word(at + 12);
out.push(&bls[at + 16..at + 16 + size]);
at += 16 + size.next_multiple_of(4);
}
out
}
/// The reference fact `vertex_light` follows, read from the install's `Model2.bls` at both
/// levels, Direct3D (1, the default device, `vs_2_0`) and ARB (2): every lit program of the
/// vertex-lit set (digit L 1, P 0; `0x71de50` builds the id, `0x707cf6` adds the bound light
/// count as its last digit) ends `c28·(E, 1) + c29` into the primary colour, and clamps E
/// with `min`/`max` exactly when it binds a point light.
#[test]
fn model2_clamps_the_light_sum_only_with_a_point_light_bound() {
let Some(bls) = model2_bls() else { return };
let lit = |id: usize| id < 900 && (id / 90) & 1 == 1;
// Level 1: `vs_2_0` tokens. An instruction's length is bits 24-27; a register's type is
// bits 28-30 and 11-12, its number bits 0-10, a destination's write mask bits 16-19.
let reg = |t: u32| (((t >> 28) & 7) | ((t >> 8) & 0x18), t & 0x7ff);
for (id, code) in model2_level(&bls, 1).into_iter().enumerate() {
if !lit(id) {
continue;
}
let t: Vec<u32> = code
.as_chunks::<4>()
.0
.iter()
.map(|c| u32::from_le_bytes(*c))
.collect();
assert_eq!(t[0], 0xfffe_0200, "program {id} is vs_2_0");
let mut ops: Vec<(u32, &[u32])> = Vec::new();
let mut i = 1;
while t[i] & 0xffff != 0xffff {
let op = t[i] & 0xffff;
let len = if op == 0xfffe {
(t[i] >> 16) & 0x7fff
} else {
(t[i] >> 24) & 0xf
} as usize;
if op != 0xfffe {
ops.push((op, &t[i + 1..i + 1 + len]));
}
i += 1 + len;
}
// `mad oD0, c28, E, c29`: oD0 is type 5 register 0, c29 type 2 register 29.
let out = ops
.iter()
.position(|(op, a)| *op == 4 && reg(a[0]) == (5, 0))
.unwrap_or_else(|| panic!("program {id} writes no oD0 by mad"));
assert_eq!(reg(ops[out].1[3]), (2, 29), "program {id} adds c29");
// A clamp of E is `min` (10) and `max` (11) into a temp's xyz.
let clamps = |opcode: u32| {
ops[..out]
.iter()
.any(|(op, a)| *op == opcode && reg(a[0]).0 == 0 && (a[0] >> 16) & 0xf == 7)
};
assert_eq!(
clamps(10) && clamps(11),
id % 5 > 0,
"Direct3D program {id}, {} point lights bound",
id % 5
);
}
// Level 2: ARB text.
let mut seen = 0;
for (id, code) in model2_level(&bls, 2).into_iter().enumerate() {
if !lit(id) {
continue;
}
seen += 1;
let text = std::str::from_utf8(code).expect("ARB text");
let lines: Vec<&str> = text.lines().map(str::trim).collect();
let out = lines
.iter()
.find(|l| l.contains("result.color.front.primary"))
.unwrap_or_else(|| panic!("program {id} writes no primary colour"));
assert!(
out.starts_with("MAD result.color.front.primary,") && out.ends_with("c28[1];"),
"program {id} ends `{out}`"
);
let clamps = |op: &str| {
lines
.iter()
.any(|l| l.starts_with(op) && l.contains(".xyz, c0."))
};
assert_eq!(
clamps("MIN R") && clamps("MAX R"),
id % 5 > 0,
"ARB program {id}, {} point lights bound",
id % 5
);
}
assert_eq!(seen, 450, "the vertex-lit set's lit programs");
}
/// Runs one ARB vertex program on one vertex: `local` is `program.local[]`, `attribs` binds
/// `vertex.position` and `vertex.normal`. Returns the primary colour, which the GL clamps to
/// [0, 1] before it interpolates. Covers the instructions of the vertex-lit programs.
fn run_arb(text: &str, local: &[[f32; 4]; 96], attribs: &[(&str, [f32; 4])]) -> [f32; 3] {
use std::collections::HashMap;
enum Param {
Literal([f32; 4]),
Local(usize),
}
let mut params: HashMap<&str, Param> = HashMap::new();
let mut regs: HashMap<String, [f32; 4]> = HashMap::new();
let split_mask = |s: &str| -> (String, String) {
match s.rsplit_once('.') {
Some((name, m)) if !m.is_empty() && m.chars().all(|c| "xyzw".contains(c)) => {
(name.to_string(), m.to_string())
}
_ => (s.to_string(), "xyzw".to_string()),
}
};
for line in text.lines().map(str::trim) {
let line = line.trim_end_matches(';');
if line.is_empty()
|| line.starts_with("!!")
|| line == "END"
|| line.starts_with("TEMP")
{
continue;
}
if let Some(rest) = line.strip_prefix("PARAM ") {
let (name, value) = rest.split_once(" = ").unwrap();
let name = name.split('[').next().unwrap();
let value = value.trim_matches(|c| c == '{' || c == '}' || c == ' ');
let param = match value.strip_prefix("program.local[") {
Some(range) => Param::Local(range.split("..").next().unwrap().parse().unwrap()),
None => {
let v: Vec<f32> = value
.split(',')
.map(|x| x.trim().parse().unwrap())
.collect();
Param::Literal([v[0], v[1], v[2], v[3]])
}
};
params.insert(name, param);
continue;
}
if let Some(rest) = line.strip_prefix("ATTRIB ") {
let (name, binding) = rest.split_once(" = ").unwrap();
let v = attribs
.iter()
.find(|(b, _)| *b == binding)
.map_or([0.0; 4], |a| a.1);
regs.insert(name.to_string(), v);
continue;
}
let (op, operands) = line.split_once(char::is_whitespace).unwrap();
let operands: Vec<&str> = operands.trim().split(", ").collect();
let read = |s: &str| -> [f32; 4] {
let (neg, s) = s.strip_prefix('-').map_or((false, s), |r| (true, r));
let (name, swz) = split_mask(s);
let v = if let Some((base, idx)) = name.split_once('[') {
let idx: usize = idx.trim_end_matches(']').parse().unwrap();
match params[base] {
Param::Local(b) => local[b + idx],
Param::Literal(_) => panic!("an indexed literal `{s}`"),
}
} else if let Some(r) = regs.get(&name) {
*r
} else {
match params[name.as_str()] {
Param::Local(b) => local[b],
Param::Literal(v) => v,
}
};
let swz: Vec<usize> = swz.chars().map(|c| "xyzw".find(c).unwrap()).collect();
std::array::from_fn(|k| {
let x = v[swz[k.min(swz.len() - 1)]];
if neg {
-x
} else {
x
}
})
};
let src: Vec<[f32; 4]> = operands[1..].iter().map(|s| read(s)).collect();
let each = |f: &dyn Fn(usize) -> f32| -> [f32; 4] { std::array::from_fn(f) };
let r = match op {
"MOV" => src[0],
"ADD" => each(&|k| src[0][k] + src[1][k]),
"MUL" => each(&|k| src[0][k] * src[1][k]),
"MAD" => each(&|k| src[0][k] * src[1][k] + src[2][k]),
"MIN" => each(&|k| src[0][k].min(src[1][k])),
"MAX" => each(&|k| src[0][k].max(src[1][k])),
"DP3" => [(0..3).map(|k| src[0][k] * src[1][k]).sum::<f32>(); 4],
"DP4" => [(0..4).map(|k| src[0][k] * src[1][k]).sum::<f32>(); 4],
"RSQ" => [1.0 / src[0][0].abs().sqrt(); 4],
"RCP" => [1.0 / src[0][0]; 4],
_ => panic!("an instruction the vertex-lit programs do not use: `{line}`"),
};
let (dst, mask) = split_mask(operands[0]);
let slot = regs.entry(dst).or_insert([0.0; 4]);
for c in mask.chars() {
let k = "xyzw".find(c).unwrap();
slot[k] = r[k];
}
}
let c = regs["result.color.front.primary"];
[c[0], c[1], c[2]].map(|x| x.clamp(0.0, 1.0))
}
/// `vertex_light`'s M2 lane against the reference itself: Model2.bls programs 135 (lit, no
/// point light) and 136 (one bound) run on the same constants as a mirror of the lane. The
/// WGSL checks pin the shader to the mirror's shape: the SH basis, the point light's falloff,
/// E clamped only with a light bound, and `c28·E + c29` clamped once.
#[test]
fn vertex_light_runs_model2_programs_135_and_136() {
let src = include_str!("shaders/wow_model.wgsl");
for line in [
"let n_lit = wow_normalize(world_normal);",
"let quad = vec4<f32>(n_lit.x * n_lit.y, n_lit.y * n_lit.z, n_lit.z * n_lit.z, n_lit.x * n_lit.z);",
"let n1 = vec4<f32>(n_lit, 1.0);",
"let x2y2 = n_lit.x * n_lit.x - n_lit.y * n_lit.y;",
"let atten = 1.0 / (0.7 * d + 0.03 * d * d);",
"let nl = max(dot(N, to_light / max(d, 1e-4)), 0.0);",
"sum += vec4<f32>(wow_light.points[2u * sel[s] + 1u].rgb * (atten * nl), 1.0);",
"var e = select(e_exterior, e_probe, is_interior || is_rig) + point_lit.rgb;",
"if (point_lit.w > 0.5) {\n e = clamp(e, vec3<f32>(0.0), vec3<f32>(1.0));\n }",
"return clamp(c * e + highlight, vec3<f32>(0.0), vec3<f32>(1.0));",
] {
assert!(src.contains(line), "the M2 lane left its mirror: `{line}` is gone");
}
let Some(bls) = model2_bls() else { return };
let arb = model2_level(&bls, 2);
// The lit material colour `c28`, the highlight `c29`, the committed SH rows c10-c16
// (the sum passes 1 on the lit side) and one point light's colour and position.
let c28 = [0.5f32, 0.8, 1.0];
let c29 = [0.1f32, 0.0, 0.05];
let sh: [[f32; 4]; 7] = [
[0.30, 0.55, 0.20, 0.70],
[0.25, 0.45, 0.15, 0.55],
[0.10, 0.30, 0.05, 0.40],
[0.12, -0.05, 0.08, 0.10],
[0.09, -0.04, 0.06, 0.08],
[0.05, -0.02, 0.03, 0.04],
[0.07, 0.05, 0.03, 0.0],
];
let (light_pos, light_rgb) = ([2.0f32, 3.0, 1.0], [1.5f32, 1.0, 0.5]);
let mut local = [[0.0f32; 4]; 96];
local[2] = [1.0, 0.0, 0.0, 0.0]; // c2-c5: the projection, identity
local[3] = [0.0, 1.0, 0.0, 0.0];
local[4] = [0.0, 0.0, 1.0, 0.0];
local[5] = [0.0, 0.0, 0.0, 1.0];
local[10..17].copy_from_slice(&sh);
local[17] = [light_rgb[0], light_rgb[1], light_rgb[2], 0.0]; // c17: colour
local[21] = [light_pos[0], light_pos[1], light_pos[2], 1.0]; // c21: position
local[25] = [0.0; 4]; // c25-c27: constant, linear, quadratic falloff
local[26] = [0.7, 0.0, 0.0, 0.0];
local[27] = [0.03, 0.0, 0.0, 0.0];
local[28] = [c28[0], c28[1], c28[2], 1.0];
local[29] = [c29[0], c29[1], c29[2], 0.0];
local[31] = [1.0, 0.0, 0.0, 0.0]; // c31-c33: the bone, identity
local[32] = [0.0, 1.0, 0.0, 0.0];
local[33] = [0.0, 0.0, 1.0, 0.0];
/// `vertex_light`'s M2 lane, step for step, on committed SH rows.
fn lane(
sh: &[[f32; 4]; 7],
n: [f32; 3],
p: [f32; 3],
light: Option<([f32; 3], [f32; 3])>,
c: [f32; 3],
highlight: [f32; 3],
) -> [f32; 3] {
let len = (n[0] * n[0] + n[1] * n[1] + n[2] * n[2]).sqrt();
let n = n.map(|x| x / len);
let quad = [n[0] * n[1], n[1] * n[2], n[2] * n[2], n[0] * n[2]];
let x2y2 = n[0] * n[0] - n[1] * n[1];
let mut e: [f32; 3] = std::array::from_fn(|ch| {
let c10 = sh[ch];
let c13 = sh[3 + ch];
c10[3]
+ (c10[0] * n[0] + c10[1] * n[1] + c10[2] * n[2])
+ (0..4).map(|k| c13[k] * quad[k]).sum::<f32>()
+ sh[6][ch] * x2y2
});
if let Some((pos, rgb)) = light {
let to: [f32; 3] = std::array::from_fn(|k| pos[k] - p[k]);
let d = (to[0] * to[0] + to[1] * to[1] + to[2] * to[2]).sqrt();
let atten = 1.0 / (0.7 * d + 0.03 * d * d);
let nl = ((n[0] * to[0] + n[1] * to[1] + n[2] * to[2]) / d.max(1e-4)).max(0.0);
e = std::array::from_fn(|k| (e[k] + rgb[k] * atten * nl).clamp(0.0, 1.0));
}
std::array::from_fn(|k| (c[k] * e[k] + highlight[k]).clamp(0.0, 1.0))
}
let p = [0.5f32, -0.2, 0.3];
let mut order_shows = false;
for n in [
[0.3f32, 0.8, 0.5],
[0.9, 0.6, 1.2], // unnormalized: the program normalizes the bone-space normal
[-0.4, 0.2, -0.9],
[0.0, 0.0, 1.0],
] {
let attribs = [
("vertex.position", [p[0], p[1], p[2], 1.0]),
("vertex.normal", [n[0], n[1], n[2], 0.0]),
];
for (id, light) in [(135usize, None), (136, Some((light_pos, light_rgb)))] {
let text = std::str::from_utf8(arb[id]).expect("ARB text");
let want = run_arb(text, &local, &attribs);
let got = lane(&sh, n, p, light, c28, c29);
for k in 0..3 {
assert!(
(got[k] - want[k]).abs() < 1e-5,
"program {id}, n {n:?}, ch{k}: the lane gives {} where Model2.bls gives {}",
got[k],
want[k]
);
}
// The constants reach the clamps: with no light, clamping E before `c28` would
// have given another colour somewhere.
if light.is_none() {
let clamped_first =
lane(&sh, n, p, Some(([100.0, 0.0, 0.0], [0.0; 3])), c28, c29);
order_shows |= (0..3).any(|k| (clamped_first[k] - want[k]).abs() > 1e-3);
}
}
}
assert!(
order_shows,
"the sample never puts E past 1 under a c28 below 1"
);
}
/// A second texture stage samples `Model2.bls`'s generated coordinate: the program for a stage
/// whose coordinate lookup is above 2 reflects the view-space position about the normal
/// (`DP3`, `MUL 2`, `MAD −`), normalizes it (`RSQ`) and maps x, y by `MAD ·0.5 + 0.5`.
+208 -203
View File
@@ -1,12 +1,15 @@
// The model pass for M2, WMO and ground-clutter meshes, lit and fogged in gamma space:
// M2: color = clamp01(A + D·I·(4/17)(0.375 + 2μ + 1.875μ²)) × tex × tint, μ = N·L
// clutter, WMO: color = clamp(ambient + diffuse·max(N·L, 0)) × tex × tint
// stage 1: color = combine(color, tex1), tex1 at the generated coordinate (presets below)
// fog: color = mix(fog_color, color, fog_factor); out = color, raw gamma
// M2: color = clamp(C·E + highlight) × tex, E = A + D·I·(4/17)(0.375 + 2μ + 1.875μ²) + the
// point lights, μ = N·L, E clamped to [0, 1] first when a point light is bound
// WMO: color = clamp(MOCV·(ambient + diffuse·max(N·L, 0)) + emission) × tex
// clutter: color = clamp(grey·(ambient + diffuse·max(N·L, 0) + the point lights)) × tex
// stage 1: color = combine(color, tex1), tex1 at the generated coordinate (presets below)
// fog: color = mix(fog_color, color, fog_factor); out = color, raw gamma
// The M2 law is the order-2 SH lobe of `Shaders\Vertex\Model2.bls` (cvar `M2UseShaders`, default
// 1); M2's one FFP light site (`70bdf6`) runs only with that cvar off. Clutter and WMO are the FFP
// light (GL_LIGHTING, GL_LIGHT0, GL_COLOR_MATERIAL); clutter's normal is the terrain normal under
// the tuft, which the reference writes onto the clutter vertex.
// the tuft, which the reference writes onto the clutter vertex. Both light per vertex and the
// clamped colour is interpolated (`vertex_light`); the fragment multiplies the texel by it.
// Not built: a specular term (the M2 per-material shininess is only inferred) and the WMO
// per-group authored colour.
@@ -128,14 +131,12 @@ struct WowVsOut {
#ifdef VERTEX_OUTPUT_INSTANCE_INDEX
@location(6) @interpolate(flat) instance_index: u32,
#endif
// The point-light sum `Σ att·sat(N·L)·colour`, per vertex like the reference FFP.
@location(8) point_lit: vec3<f32>,
// The lit colour from `vertex_light`, clamped at the vertex and interpolated, as the
// reference interpolates its vertex program's `oD0` and the FFP's lit colour.
@location(8) primary: vec3<f32>,
#ifdef WOW_MERGED_FADE
// A merged blob's per-placement fade alpha, constant over the placement.
@location(9) merged_fade: f32,
#endif
#ifdef WOW_MERGED_SLOT
@location(10) @interpolate(flat) merged_slot: u32,
#endif
// Stage 1's generated coordinate, (0, 0) when the material binds no stage 1.
@location(11) env_uv: vec2<f32>,
@@ -197,7 +198,8 @@ fn wow_normalize(v: vec3<f32>) -> vec3<f32> {
// receiving unit's own position `anchor` (`0x71bf90` gathers by squared distance, `0x71c730` seats
// slots 1-3). Range bounds candidacy only; a selected light falls off as `1/(0.7·d + 0.03·d²)`,
// diffuse only, on the submitted normal (no GL_LIGHT_MODEL_TWO_SIDE). Mirrored in terrain.wgsl.
fn point_light_sum(P: vec3<f32>, N: vec3<f32>, anchor: vec3<f32>) -> vec3<f32> {
// `.w` is how many are bound, the light-count digit of the `Model2.bls` program (`0x707cf6`).
fn point_light_sum(P: vec3<f32>, N: vec3<f32>, anchor: vec3<f32>) -> vec4<f32> {
let count = u32(wow_light.point_count.x);
var sel = array<u32, 3>(0u, 0u, 0u);
var sd = array<f32, 3>(1e30, 1e30, 1e30);
@@ -219,7 +221,7 @@ fn point_light_sum(P: vec3<f32>, N: vec3<f32>, anchor: vec3<f32>) -> vec3<f32> {
sd[2] = d2; sel[2] = i;
}
}
var sum = vec3<f32>(0.0);
var sum = vec4<f32>(0.0);
for (var s = 0u; s < 3u; s = s + 1u) {
if (sd[s] > 9.9e29) {
break;
@@ -229,7 +231,7 @@ fn point_light_sum(P: vec3<f32>, N: vec3<f32>, anchor: vec3<f32>) -> vec3<f32> {
let d = length(to_light);
let atten = 1.0 / (0.7 * d + 0.03 * d * d);
let nl = max(dot(N, to_light / max(d, 1e-4)), 0.0);
sum += wow_light.points[2u * sel[s] + 1u].rgb * (atten * nl);
sum += vec4<f32>(wow_light.points[2u * sel[s] + 1u].rgb * (atten * nl), 1.0);
}
return sum;
}
@@ -355,6 +357,159 @@ fn wow_skin_normals(frame_from_local: mat4x4<f32>, normal: vec3<f32>) -> vec3<f3
}
#endif
// The body tint (an aura colouring the whole model) by the tag's rig slot, 0 = identity: the
// material ambient+diffuse colour (gx SetState(1), GL_COLOR_MATERIAL), so it multiplies the light
// sum inside the clamp, never the emission.
fn body_tint(fade_tag: u32) -> vec3<f32> {
let tint_word = wow_light.rig_tint[(fade_tag >> 19u) & 0x7ffu];
return select(
vec3<f32>(
f32((tint_word >> 16u) & 0xffu),
f32((tint_word >> 8u) & 0xffu),
f32(tint_word & 0xffu),
) * (1.0 / 255.0),
vec3<f32>(1.0),
tint_word == 0u,
);
}
// The hover/target highlight (tag bit 31): the scene's committed ambient
// (`0x614576`-`0x6145bd`), added to the batch colour inside the final clamp, lit or unlit
// (`c29`). Sampled live, where the reference holds the value sampled when the highlight
// began: a unit's tag has no slot to hold a colour, and the ambient moves slowly.
fn highlight_add(raw_tag: u32) -> vec3<f32> {
return select(vec3<f32>(0.0), wow_light.light_ambient.rgb, (raw_tag & 0x80000000u) != 0u);
}
// The lit colour at one vertex: the reference lights in the vertex stage (`Model2.bls` evaluates
// the SH and writes `oD0`; WMO and clutter run FFP T&L) and the rasterizer interpolates the
// clamped result. `world_normal` is the submitted one: the reference never enables
// GL_LIGHT_MODEL_TWO_SIDE (`0x59ce30`), so a back face lights from it too. `vcol` is the vertex
// colour (white without one), `point_lit` the bound point lights' sum and, in `.w`, their count.
// The colour is the lit material, inside the one clamp: GL_COLOR_MATERIAL on ambient and diffuse
// (`0x59cfec`, `0x59cff3`-`0x59cffd`) for the FFP, `c28` for `Model2.bls`.
fn vertex_light(
world_normal: vec3<f32>,
point_lit: vec4<f32>,
vcol: vec4<f32>,
probe_slot: u32,
raw_tag: u32,
) -> vec3<f32> {
let is_clutter = m.clutter_fade.w > 0.5;
let is_wmo = m.model_flags.x > 0.5;
let is_interior = m.model_flags.z > 0.5;
let interior_prop = is_interior && !is_wmo;
let fade_tag = raw_tag & 0x3fffffffu;
let highlight = highlight_add(raw_tag);
let L = -normalize(wow_light.light_sun.xyz);
// `wow_normalize`: an authored zero normal reaches here on the unskinned lane.
let n_lit = wow_normalize(world_normal);
let ndotl = max(dot(n_lit, L), 0.0);
// The FFP light sum, unclamped: GL clamps the lit colour once, after the material colour.
let sum_nl = wow_light.light_ambient.rgb + wow_light.light_diffuse.rgb * ndotl;
if (is_wmo) {
// WMO interior groups (`groupFlags & 0x48 == 0`) by batch class (`tint.w`): INT (1) is
// unlit, drawn in the fragment; TRANS (2) is the reference's two passes, this the lit one;
// EXT (0) is the FFP sum. A WINDOW batch (MOMT 0x20) on the interior drawer lights with the
// Direct/Ambient midpoint as diffuse and it +16/255 as ambient, that byte add saturating
// on its own (`0x6d37e0`).
let window_mid = 0.5 * (wow_light.light_ambient.rgb + wow_light.light_diffuse.rgb);
let sum_window = min(window_mid + vec3<f32>(16.0 / 255.0), vec3<f32>(1.0))
+ window_mid * ndotl;
var sum_wmo = sum_nl;
// SIDN night glow: the emissive × the night fraction (ramping 20:30→21:30, 06:00→07:00),
// a GL_EMISSION term beside MOCV inside the clamp; TRANS's blend weights its lit pass.
var sidn_w = 1.0;
if (is_interior) {
sum_wmo = select(sum_nl, sum_window, m.sidn.w > 0.5);
if (m.tint.w > 0.5 && m.tint.w < 1.5) {
// INT draws unlit: the bare texel without MOCV, no emission.
sum_wmo = vec3<f32>(1.0);
sidn_w = 0.0;
}
}
let sidn_e = m.sidn.rgb * (wow_light.grade.x * sidn_w);
return clamp(vcol.rgb * sum_wmo + sidn_e + highlight, vec3<f32>(0.0), vec3<f32>(1.0));
}
// `c28`, and the FFP's material colour: the vertex colour (an M2's static M2Color, a
// clutter tuft's MCSH grey `0xffc0c0c0` or white, `0x6b260e`/`0x6b2615`) × the animated
// M2Color (`m.tint` plus its mat-anim delta) × the body tint.
let anim_tint = m.tint.rgb + wow_light.matanim[u32(m.anim_slots.y)].xyz;
let c = vcol.rgb * anim_tint * body_tint(fade_tag);
if (is_clutter) {
// The detail-doodad pass lights by the FFP (`0x6813d0` commits the chunk's lights at
// `0x681656`), so the grey multiplies the whole light sum inside the one clamp.
return clamp(c * (sum_nl + point_lit.rgb) + highlight, vec3<f32>(0.0), vec3<f32>(1.0));
}
// The order-2 SH basis, shared by the exterior lobe and the interior probes.
let quad = vec4<f32>(n_lit.x * n_lit.y, n_lit.y * n_lit.z, n_lit.z * n_lit.z, n_lit.x * n_lit.z);
let n1 = vec4<f32>(n_lit, 1.0);
let x2y2 = n_lit.x * n_lit.x - n_lit.y * n_lit.y;
// Exterior doodads and entities: the header's `Model2.bls` lobe at the per-instance intensity
// I, `[node+0xa4]` (animator targets 2.5 lit and 0.5 shadowed, `0x69e4ad`/`0x69e280`; 1.0
// indoors, `0x69e36b`). `sun_scale.x` picks the family:
// ≥ 0.85: an entity M2, 2.5 mixed toward 0.5 by the tag's shade byte (ramped like `0x69e770`)
// 0.5..0.85: a doodad (ADT MDDF or WMO MODD, both `CMapDoodadDef`): 1.0, never 2.5
// < 0.5: a doodad on MCSH-shadowed ground: 0.5
// Deviation: `min(I, 1)`. The reference bakes I into the SH unclamped (`0x71c4e0`), so a lit
// entity commits ×2.5 there and ×1.0 here; lifting the cap takes sun-facing surfaces past 1.0.
// `entity_shade::LIT_T` aims the lit ramp at 1.0 because of it: lift the cap and set `LIT_T`
// back to 0.0 together.
let inst_shade = select(f32((fade_tag >> 6u) & 0xffu) / 255.0, 0.0, interior_prop);
let mat_shade = select(0.0, 1.0, m.sun_scale.x < 0.5);
let shade_t = max(mat_shade, inst_shade);
let mid_band = m.sun_scale.x >= 0.5 && m.sun_scale.x < 0.85;
let intensity = min(select(mix(2.5, 0.5, shade_t), 1.0, mid_band), 1.0);
// One `intensity` multiply covers every sun band (never I²); the c10 `.w` ambient does not
// scale. `pack_model_core_rows` packs the same closed form.
let sun_dc = wow_light.grade.yzw * intensity;
let sun_lobe = vec3<f32>(
wow_light.sh_c10_r.w + sun_dc.x
+ intensity
* (dot(wow_light.sh_c10_r.xyz, n_lit) + dot(wow_light.sh_c13_r, quad)
+ wow_light.sh_c16.x * x2y2),
wow_light.sh_c10_g.w + sun_dc.y
+ intensity
* (dot(wow_light.sh_c10_g.xyz, n_lit) + dot(wow_light.sh_c13_g, quad)
+ wow_light.sh_c16.y * x2y2),
wow_light.sh_c10_b.w + sun_dc.z
+ intensity
* (dot(wow_light.sh_c10_b.xyz, n_lit) + dot(wow_light.sh_c13_b, quad)
+ wow_light.sh_c16.z * x2y2),
);
// Interior M2 props (WMO MODD doodads): the reference commits the prop's MODD colour through a
// fixed-axis diffuse lobe plus its group's MOLR lights as an order-2 SH probe, folded at spawn
// by `lighting::prop_probe_coeffs`. Its soft wrap (≈ 0.088·C side-on) is the reference's
// response, not a max(N·L, 0). The authored-rig lane (`ShadeSel::Rig`, glue scenes) reads the
// scene's lights folded into probe slot 0 of the material's own buffer (tag 0).
let probe = 7u * probe_slot;
let e_probe = vec3<f32>(
dot(wow_light.prop_probes[probe + 0u], n1)
+ dot(wow_light.prop_probes[probe + 3u], quad)
+ wow_light.prop_probes[probe + 6u].x * x2y2,
dot(wow_light.prop_probes[probe + 1u], n1)
+ dot(wow_light.prop_probes[probe + 4u], quad)
+ wow_light.prop_probes[probe + 6u].y * x2y2,
dot(wow_light.prop_probes[probe + 2u], n1)
+ dot(wow_light.prop_probes[probe + 5u], quad)
+ wow_light.prop_probes[probe + 6u].z * x2y2,
);
// The lobe needs the directional light on (`light_sun.w`); off, the FFP sum stands in.
let e_exterior = select(sum_nl, sun_lobe, wow_light.light_sun.w > 0.5);
let is_rig = m.sun_scale.x >= 1.5;
var e = select(e_exterior, e_probe, is_interior || is_rig) + point_lit.rgb;
// `Model2.bls`, every lit program: with no point light bound it writes `c28·(E, 1) + c29`
// straight to `oD0`, which saturates; with one to four bound it clamps E to [0, 1] first
// (`MIN`/`MAX` before the `MAD` into `oD0`). The lobe's ringing (−0.037·D near μ ≈ −0.53)
// survives into the sum either way.
if (point_lit.w > 0.5) {
e = clamp(e, vec3<f32>(0.0), vec3<f32>(1.0));
}
// `c28` is the model colour `[model+0x1a0]` (the body tint) × the batch's M2Color
// (`0x70c60a`-`0x70c654`), written at `0x70c712`; `c29` holds the highlight.
return clamp(c * e + highlight, vec3<f32>(0.0), vec3<f32>(1.0));
}
// Bevy 0.18's `mesh.wgsl` vertex stage plus our skinning and point lights. A `MaterialExtension`
// replaces the whole stage, so this must track Bevy's on upgrades.
@vertex
@@ -418,9 +573,6 @@ fn vertex(vertex: WowVertex) -> WowVsOut {
if (out.merged_fade <= 0.0) {
out.position = vec4<f32>(0.0, 0.0, 2.0, 1.0);
}
#ifdef WOW_MERGED_SLOT
out.merged_slot = vertex.merged_slot;
#endif
#endif
#endif
@@ -460,15 +612,26 @@ fn vertex(vertex: WowVertex) -> WowVsOut {
// Point lights: none on WMO surfaces, none here on interior M2 props (their group's MOLR lights
// are in the SH probe), else the ≤3 nearest to the instance origin (clutter: its MCNK chunk).
if (m.model_flags.x > 0.5 || m.model_flags.z > 0.5) {
out.point_lit = vec3<f32>(0.0);
} else {
var point_lit = vec4<f32>(0.0);
if (m.model_flags.x < 0.5 && m.model_flags.z < 0.5) {
var anchor = mesh_world_from_local[3].xyz;
if (m.clutter_fade.w > 0.5) {
anchor = mcnk_cell_anchor(out.world_position.xyz);
}
out.point_lit = point_light_sum(out.world_position.xyz, out.world_normal, anchor);
point_lit = point_light_sum(out.world_position.xyz, out.world_normal, anchor);
}
var vcol = vec4<f32>(1.0);
#ifdef VERTEX_COLORS
vcol = vertex.color;
#endif
let raw_tag = mesh_functions::get_tag(vertex.instance_index);
#ifdef WOW_MERGED_SLOT
// A merged blob bakes the probe slot per vertex; its tag carries only fog and alpha.
let probe_slot = vertex.merged_slot;
#else
let probe_slot = ((raw_tag & 0x3fffffffu) >> 6u) & 0x1fffu;
#endif
out.primary = vertex_light(out.world_normal, point_lit, vcol, probe_slot, raw_tag);
return out;
}
@@ -529,7 +692,9 @@ fn fragment(in: WowVsOut, @builtin(front_facing) is_front: bool) -> WowFragOut {
vo.uv_b = in.uv_b;
#endif
#ifdef VERTEX_COLORS
vo.color = in.color;
// The vertex colour is the lit material, inside the clamp (`vertex_light`), so Bevy folds
// only its alpha into the texel.
vo.color = vec4<f32>(1.0, 1.0, 1.0, in.color.a);
#endif
#ifdef VERTEX_OUTPUT_INSTANCE_INDEX
vo.instance_index = in.instance_index;
@@ -558,8 +723,7 @@ fn fragment(in: WowVsOut, @builtin(front_facing) is_front: bool) -> WowFragOut {
// The detail-doodad LOD bias (`0x6813f4`): on the atlases whose alpha pyramid is binary below
// mip 0 it keeps every fragment below full alpha, so the fade erodes per pixel, not per leaf.
// wgpu has no sampler LOD bias and the sampler is shared with unbiased batches, so it goes on
// this sample. Clutter's tint is white and its vertex colour the MCSH grey, so `* vo.color`
// reproduces Bevy's fold.
// this sample. `* vo.color` reproduces Bevy's fold of the vertex alpha.
if (m.clutter_fade.w > 0.5) {
#ifdef VERTEX_UVS_A
var biased = textureSampleBias(
@@ -599,9 +763,7 @@ fn fragment(in: WowVsOut, @builtin(front_facing) is_front: bool) -> WowFragOut {
// The MeshTag (mesh_tag.rs): bit 31 = highlight, bit 30 = interior fog; payload bits 0-5 = the
// fade alpha (a zero payload is untagged, opaque), 19-29 = the rig slot, 6-13 = the ground
// shade (0 lit, 255 MCSH-shadowed) or, on an interior-prop material, 6-18 = the SH-probe slot.
let interior_prop = m.model_flags.z > 0.5 && m.model_flags.x < 0.5;
let raw_tag = mesh_functions::get_tag(in.instance_index);
let highlighted = (raw_tag & 0x80000000u) != 0u;
let interior_fogged = (raw_tag & 0x40000000u) != 0u;
let fade_tag = raw_tag & 0x3fffffffu;
let alpha6 = f32(fade_tag & 0x3fu) / 63.0;
@@ -610,19 +772,7 @@ fn fragment(in: WowVsOut, @builtin(front_facing) is_front: bool) -> WowFragOut {
// A merged blob's per-vertex fade composes where the tag fade does, so it feathers the same.
obj_fade = obj_fade * in.merged_fade;
#endif
// The body tint (an aura colouring the whole model), by rig slot, 0 = identity: the material
// ambient+diffuse colour (gx SetState(1), GL_COLOR_MATERIAL), so it multiplies the light sum
// inside the clamp, never the emission.
let tint_word = wow_light.rig_tint[(fade_tag >> 19u) & 0x7ffu];
let inst_tint = select(
vec3<f32>(
f32((tint_word >> 16u) & 0xffu),
f32((tint_word >> 8u) & 0xffu),
f32(tint_word & 0xffu),
) * (1.0 / 255.0),
vec3<f32>(1.0),
tint_word == 0u,
);
let inst_tint = body_tint(fade_tag);
// The blend twin re-applies its source's cutout: the reference scales ALPHAREF with the fade,
// so the cutoff stays tex.a < 224/255 on the unfaded alpha. Only for a source batch that
// alpha-tests (bit 10): ALPHAREF keys on the stored blend mode.
@@ -646,193 +796,48 @@ fn fragment(in: WowVsOut, @builtin(front_facing) is_front: bool) -> WowFragOut {
let base = alpha_discard(pbr_input.material, base_color);
// --- Lighting --------------------------------------------------------------------------------
let is_clutter = m.clutter_fade.w > 0.5;
let L = -normalize(wow_light.light_sun.xyz);
// `wow_normalize`: an authored zero normal reaches here on the unskinned lane.
let n_m2 = wow_normalize(pbr_input.world_normal);
// Bevy negates `world_normal` on back faces of double-sided materials (foliage, every WMO
// face); the reference never enables GL_LIGHT_MODEL_TWO_SIDE (`0x59ce30`), so undo it.
let n_lit = select(-n_m2, n_m2, is_front);
let ndotl = max(dot(n_lit, L), 0.0);
let lit_nl = clamp(wow_light.light_ambient.rgb + wow_light.light_diffuse.rgb * ndotl, vec3<f32>(0.0), vec3<f32>(1.0));
// The order-2 SH basis, shared by the exterior lobe and the interior probes.
let quad = vec4<f32>(n_lit.x * n_lit.y, n_lit.y * n_lit.z, n_lit.z * n_lit.z, n_lit.x * n_lit.z);
let n1 = vec4<f32>(n_lit, 1.0);
let x2y2 = n_lit.x * n_lit.x - n_lit.y * n_lit.y;
// Exterior doodads and entities: the header's `Model2.bls` lobe at the per-instance intensity
// I, `[node+0xa4]` (animator targets 2.5 lit and 0.5 shadowed, `0x69e4ad`/`0x69e280`; 1.0
// indoors, `0x69e36b`). `sun_scale.x` picks the family:
// ≥ 0.85: an entity M2, 2.5 mixed toward 0.5 by the tag's shade byte (ramped like `0x69e770`)
// 0.5..0.85: a doodad (ADT MDDF or WMO MODD, both `CMapDoodadDef`): 1.0, never 2.5
// < 0.5: a doodad on MCSH-shadowed ground: 0.5
// Deviation: `min(I, 1)`. The reference bakes I into the SH unclamped (`0x71c4e0`), so a lit
// entity commits ×2.5 there and ×1.0 here; lifting the cap takes sun-facing surfaces past 1.0.
// `entity_shade::LIT_T` aims the lit ramp at 1.0 because of it: lift the cap and set `LIT_T`
// back to 0.0 together.
let inst_shade = select(f32((fade_tag >> 6u) & 0xffu) / 255.0, 0.0, interior_prop);
let mat_shade = select(0.0, 1.0, m.sun_scale.x < 0.5);
let shade_t = max(mat_shade, inst_shade);
let mid_band = m.sun_scale.x >= 0.5 && m.sun_scale.x < 0.85;
let intensity = min(select(mix(2.5, 0.5, shade_t), 1.0, mid_band), 1.0);
// One `intensity` multiply covers every sun band (never I²); the c10 `.w` ambient does not
// scale. `pack_model_core_rows` packs the same closed form.
let sun_dc = wow_light.grade.yzw * intensity;
let sun_lobe = vec3<f32>(
wow_light.sh_c10_r.w + sun_dc.x
+ intensity
* (dot(wow_light.sh_c10_r.xyz, n_lit) + dot(wow_light.sh_c13_r, quad)
+ wow_light.sh_c16.x * x2y2),
wow_light.sh_c10_g.w + sun_dc.y
+ intensity
* (dot(wow_light.sh_c10_g.xyz, n_lit) + dot(wow_light.sh_c13_g, quad)
+ wow_light.sh_c16.y * x2y2),
wow_light.sh_c10_b.w + sun_dc.z
+ intensity
* (dot(wow_light.sh_c10_b.xyz, n_lit) + dot(wow_light.sh_c13_b, quad)
+ wow_light.sh_c16.z * x2y2),
);
// Clamp the sum, never a term: the lobe's own ringing dips to −0.037·C near μ ≈ −0.53, and a
// per-term clamp would erase it.
let lit_doodad = clamp(sun_lobe, vec3<f32>(0.0), vec3<f32>(1.0));
// WMO and clutter take the FFP N·L light with no terrain shade; the lobe needs the directional
// light on (`light_sun.w`).
// The stage-0 modulate: the texel times the lit colour `vertex_light` clamped per vertex.
let is_wmo = m.model_flags.x > 0.5;
let is_interior = m.model_flags.z > 0.5;
let use_doodad_shade = (wow_light.light_sun.w > 0.5) && !is_clutter && !is_wmo;
let lit_exterior = select(lit_nl, lit_doodad, use_doodad_shade);
// WMO interior groups (`groupFlags & 0x48 == 0`) by batch class (`tint.w`): INT (1) is unlit
// `tex × MOCV`; TRANS (2) is the reference's two passes, lit × MOCV.a + unlit × (1 − MOCV.a),
// as one lerp; EXT (0) is `lit_nl`. A WINDOW batch (MOMT 0x20) on the interior drawer lights
// with ambient = diffuse = the Direct/Ambient midpoint, ambient +16/255 (`0x6d37e0`).
var trans_a = 1.0;
var vcol = vec4<f32>(1.0);
#ifdef VERTEX_COLORS
trans_a = in.color.a;
vcol = in.color;
#endif
let window_mid = 0.5 * (wow_light.light_ambient.rgb + wow_light.light_diffuse.rgb);
let lit_window = clamp(
window_mid + vec3<f32>(16.0 / 255.0) + window_mid * ndotl,
vec3<f32>(0.0),
vec3<f32>(1.0),
);
let lit_int_base = select(lit_nl, lit_window, m.sidn.w > 0.5);
var lit_wmo_interior = vec3<f32>(1.0);
if (m.tint.w > 1.5) {
lit_wmo_interior = mix(vec3<f32>(1.0), lit_int_base, trans_a);
} else if (m.tint.w < 0.5) {
lit_wmo_interior = lit_int_base;
}
// Interior M2 props (WMO MODD doodads): the reference commits the prop's MODD colour through a
// fixed-axis diffuse lobe plus its group's MOLR lights as an order-2 SH probe, folded at spawn
// by `lighting::prop_probe_coeffs` and evaluated here per fragment (the reference: per vertex).
// Its soft wrap (≈ 0.088·C side-on) is the reference's response, not a max(N·L, 0).
#ifdef WOW_MERGED_SLOT
// A merged blob bakes the slot per vertex; its tag carries only fog and alpha.
let probe = 7u * in.merged_slot;
#else
let probe = 7u * ((fade_tag >> 6u) & 0x1fffu);
#endif
let lit_m2_interior = clamp(
vec3<f32>(
dot(wow_light.prop_probes[probe + 0u], n1)
+ dot(wow_light.prop_probes[probe + 3u], quad)
+ wow_light.prop_probes[probe + 6u].x * x2y2,
dot(wow_light.prop_probes[probe + 1u], n1)
+ dot(wow_light.prop_probes[probe + 4u], quad)
+ wow_light.prop_probes[probe + 6u].y * x2y2,
dot(wow_light.prop_probes[probe + 2u], n1)
+ dot(wow_light.prop_probes[probe + 5u], quad)
+ wow_light.prop_probes[probe + 6u].z * x2y2,
),
vec3<f32>(0.0),
vec3<f32>(1.0),
);
let lit_interior = select(lit_m2_interior, lit_wmo_interior, is_wmo);
// The authored-rig lane (`ShadeSel::Rig`, glue scenes): the scene's lights are folded into
// probe slot 0 of the material's own buffer, which `lit_m2_interior` already evaluated (tag 0).
let is_rig = m.sun_scale.x >= 1.5;
let lit = select(select(lit_exterior, lit_interior, is_interior), lit_m2_interior, is_rig);
// Gamma-space albedo: lighting runs on the authored byte values. `m.tint` plus its mat-anim
// delta is the animated M2Color tint.
// Gamma-space colours: lighting runs on the authored byte values. `m.tint` plus its mat-anim
// delta is the animated M2Color tint; `albedo` is a WMO's unlit `tex × MOCV`.
let anim_tint = m.tint.rgb + wow_light.matanim[u32(m.anim_slots.y)].xyz;
let albedo = base.rgb * anim_tint;
let albedo = base.rgb * vcol.rgb * anim_tint;
// An unlit batch replaces the lit path: fullbright, with only the highlight added (below).
let is_emissive = m.model_flags.w > 0.5;
// SIDN night glow: the emissive × the night fraction (ramping 20:30→21:30, 06:00→07:00), a
// GL_EMISSION term inside the clamped lit sum, on lit lanes only.
var sidn_w = 1.0;
if (is_interior && is_wmo) {
if (m.tint.w > 1.5) {
sidn_w = trans_a; // TRANS: weighted by its lit pass
} else if (m.tint.w > 0.5) {
sidn_w = 0.0; // INT: unlit, so no emission
}
}
let sidn_e = m.sidn.rgb * (wow_light.grade.x * sidn_w);
let point_diffuse = in.point_lit;
// The hover/target highlight (tag bit 31): the scene's committed ambient
// (`0x614576`-`0x6145bd`), added to the batch colour inside the final clamp, lit or unlit
// (`c29`). Sampled live, where the reference holds the value sampled when the highlight
// began: a unit's tag has no slot to hold a colour, and the ambient moves slowly.
let highlight = select(vec3<f32>(0.0), wow_light.light_ambient.rgb, highlighted);
// The FFP combine: the light sum (lit, point lights, emission) clamps first and the texture
// modulates it, `tex × clamp(C·sum + emission)`, with C the GL_COLOR_MATERIAL colour (MOCV on
// WMO, the body tint on M2). The WMO branch divides Bevy's MOCV fold back out, guarded; a dim
// channel's product is ~0 either way.
var lit_rgb: vec3<f32>;
#ifdef VERTEX_COLORS
let highlight = highlight_add(raw_tag);
var lit_rgb = base.rgb * in.primary;
if (is_wmo) {
let vc = in.color.rgb;
let primary = clamp(
vc * (lit + point_diffuse) + sidn_e + highlight,
vec3<f32>(0.0),
vec3<f32>(1.0),
);
let tex_rgb = base.rgb / max(vc, vec3<f32>(1.0 / 255.0));
lit_rgb = tex_rgb * m.tint.rgb * primary;
lit_rgb = base.rgb * m.tint.rgb * in.primary;
if (is_interior && m.tint.w > 1.5) {
// TRANS: the lit pass by MOCV.a (blend 9, SRCALPHA/ZERO) under the unlit `tex × MOCV`
// by 1 − MOCV.a (blend 7, INVSRCALPHA/ONE), `0x6b5190`, as one lerp.
lit_rgb = base.rgb * m.tint.rgb * mix(vcol.rgb, in.primary, vcol.a);
}
#ifdef VERTEX_COLORS
if (is_interior && m.tint.w > 0.5 && m.tint.w < 1.5) {
// INT: the reference's interior pixel shader, `tex·MOCV.rgb·(1 + 4·MOCV.a)` with only
// the framebuffer's final clamp.
lit_rgb = clamp(
tex_rgb * m.tint.rgb * vc * (1.0 + 4.0 * trans_a),
base.rgb * m.tint.rgb * vcol.rgb * (1.0 + 4.0 * vcol.a),
vec3<f32>(0.0),
vec3<f32>(1.0),
);
}
} else {
// An M2: the body tint multiplies the light terms as MOCV does above. A WMO surface has
// no tint slot, so the WMO branch leaves it out.
let primary = clamp(
inst_tint * (lit + point_diffuse) + sidn_e + highlight,
vec3<f32>(0.0),
vec3<f32>(1.0),
);
lit_rgb = albedo * primary;
}
#else
// A WMO batch without MOCV lands here too; its tint slot is the identity slot 0.
let primary = clamp(
inst_tint * (lit + point_diffuse) + sidn_e + highlight,
vec3<f32>(0.0),
vec3<f32>(1.0),
);
lit_rgb = albedo * primary;
#endif
}
// The unlit path: an M2's unlit program outputs `c28 + c29` (`0x70c663`-`0x70c693` fold the
// tint·M2Color term into `c29` beside the highlight), so the texel modulates
// `clamp(C·tint + highlight)`, C the M2Color. A WMO keeps the plain modulate.
var unlit_rgb = albedo * inst_tint;
if (!is_wmo) {
#ifdef VERTEX_COLORS
// The constant M2Color rides the vertex colour, which Bevy folded into `base`.
let unlit_c = in.color.rgb * anim_tint;
let unlit_tex = base.rgb / max(in.color.rgb, vec3<f32>(1.0 / 255.0));
#else
let unlit_c = anim_tint;
let unlit_tex = base.rgb;
#endif
let unlit_sum = unlit_c * inst_tint + highlight;
unlit_rgb = unlit_tex * clamp(unlit_sum, vec3<f32>(0.0), vec3<f32>(1.0));
// The constant M2Color rides the vertex colour.
let unlit_sum = vcol.rgb * anim_tint * inst_tint + highlight;
unlit_rgb = base.rgb * clamp(unlit_sum, vec3<f32>(0.0), vec3<f32>(1.0));
}
var rgb = select(lit_rgb, unlit_rgb, is_emissive);
// An M2 Mod or Mod2x batch draws the bare texel: the reference zeroes its tint·M2Color term and
+2 -4
View File
@@ -338,10 +338,8 @@ fn build_chunk_clutter(
let rot = Quat::from_rotation_y(d.yaw);
// The reference's random per-tuft scale, in [0.9, 1.1].
let inst_scale = d.scale;
// One tint per tuft. The reference makes the grey the lit material (colour material
// on ambient and diffuse, `0x59cfec`), `clamp(grey × light) × texture`; the shader
// multiplies it outside the clamp, `texture × grey × clamp(light)`, so under light
// above 1.0 a shadowed tuft comes out darker than the reference's.
// One tint per tuft, the lit material (colour material on ambient and diffuse,
// `0x59cfec`): `wow_model.wgsl` lights `clamp(grey × light) × texture`.
let tint = [sp.tint, sp.tint, sp.tint, 1.0];
for (i, p) in sub.positions.iter().enumerate() {
positions.push((rot * (wow_to_bevy(*p) * inst_scale) + origin).to_array());
@@ -476,9 +476,10 @@ mod tests {
assert!((rgb[2] - 0.4).abs() < 1e-4, "blue commits raw: {rgb:?}");
}
/// The packed SH block gives `Model2.bls`'s `clamp01(A + D·I·(3 + 16μ + 15μ²)/34)` at each
/// intensity rung (2.5 lit, 1.0 mid-band, 0.5 MCSH-shadowed), with ambient in the DC lanes and
/// the sun's DC on `grade.yzw`.
/// The packed SH block gives `Model2.bls`'s light sum `E = A + D·I·(3 + 16μ + 15μ²)/34` at
/// each intensity rung (2.5 lit, 1.0 mid-band, 0.5 MCSH-shadowed), with ambient in the DC lanes
/// and the sun's DC on `grade.yzw`. E is unclamped: the program clamps `c28·E + c29`, and E
/// itself only with a point light bound.
#[test]
fn exterior_lane_reproduces_the_closed_form_at_every_intensity_rung() {
let ambient = [0.30, 0.32, 0.38];
@@ -495,7 +496,7 @@ mod tests {
let lin = c10[0] * n.x + c10[1] * n.y + c10[2] * n.z;
let q: f32 = (0..4).map(|k| c13[k] * quad[k]).sum::<f32>()
+ rows[12][ch] * (n.x * n.x - n.y * n.y);
(c10[3] + rows[17][1 + ch] * i + i * (lin + q)).clamp(0.0, 1.0)
c10[3] + rows[17][1 + ch] * i + i * (lin + q)
})
};
let u = -sun_dir; // toward-light
@@ -509,7 +510,7 @@ mod tests {
let b = (3.0 + 16.0 * mu + 15.0 * mu * mu) / 34.0;
let got = eval(n, i);
for ch in 0..3 {
let want = (ambient[ch] + diffuse[ch] * i * b).clamp(0.0, 1.0);
let want = ambient[ch] + diffuse[ch] * i * b;
assert!(
(got[ch] - want).abs() < 1e-5,
"I={i} {who}: ch{ch} got {} want {want}",
+1 -1
View File
@@ -1,5 +1,5 @@
//! The order-2 SH light fold of the reference's `Model2.bls`: one closed form for the interior-prop
//! probes and the exterior sun rows, evaluated per fragment in `wow_model.wgsl`. There is no
//! probes and the exterior sun rows, evaluated per vertex in `wow_model.wgsl`. There is no
//! separate amplitude scalar; intensity lives entirely in the committed colour.
use bevy::math::{Vec3, Vec4};
+123 -133
View File
@@ -76,7 +76,7 @@ fn wow_normalize(v: vec3<f32>) -> vec3<f32> {
return select(vec3<f32>(0.0), normalize(v), l2 > 1e-12);
}
fn point_light_sum(P: vec3<f32>, N: vec3<f32>, anchor: vec3<f32>) -> vec3<f32> {
fn point_light_sum(P: vec3<f32>, N: vec3<f32>, anchor: vec3<f32>) -> vec4<f32> {
let count = u32(wow_light.point_count.x);
var sel = array<u32, 3>(0u, 0u, 0u);
var sd = array<f32, 3>(1e30, 1e30, 1e30);
@@ -98,7 +98,7 @@ fn point_light_sum(P: vec3<f32>, N: vec3<f32>, anchor: vec3<f32>) -> vec3<f32> {
sd[2] = d2; sel[2] = i;
}
}
var sum = vec3<f32>(0.0);
var sum = vec4<f32>(0.0);
for (var s = 0u; s < 3u; s = s + 1u) {
if (sd[s] > 9.9e29) {
break;
@@ -108,11 +108,112 @@ fn point_light_sum(P: vec3<f32>, N: vec3<f32>, anchor: vec3<f32>) -> vec3<f32> {
let d = length(to_light);
let atten = 1.0 / (0.7 * d + 0.03 * d * d);
let nl = max(dot(N, to_light / max(d, 1e-4)), 0.0);
sum += wow_light.points[2u * sel[s] + 1u].rgb * (atten * nl);
sum += vec4<f32>(wow_light.points[2u * sel[s] + 1u].rgb * (atten * nl), 1.0);
}
return sum;
}
// The lit colour at one vertex, `wow_model.wgsl`'s `vertex_light` over the flag words: the
// reference lights per vertex and interpolates the clamped colour, the vertex colour inside the
// clamp as the lit material. Both faces light from the submitted normal (no
// GL_LIGHT_MODEL_TWO_SIDE in the reference). `vc` is the vertex colour, white where the batch
// authors none; `point_lit.w` counts the bound point lights.
fn vertex_light(normal: vec3<f32>, point_lit: vec4<f32>, vc: vec4<f32>, word: u32) -> vec3<f32> {
let n_lit = wow_normalize(normal);
let L = -normalize(wow_light.light_sun.xyz);
let ndotl = max(dot(n_lit, L), 0.0);
// The FFP light sum, unclamped: GL clamps the lit colour once, after the material colour.
let sum_nl = wow_light.light_ambient.rgb + wow_light.light_diffuse.rgb * ndotl;
let rec = recs[word & 0xffffu];
if ((word & WORD_WMO) != 0u) {
// ---- WMO surfaces: wow_model.wgsl's is_wmo lane ----
// Interior batch classes: INT is unlit (the bake is the room's light), TRANS's lit pass
// and EXT take the FFP sum. Exterior groups take it at sun scale 1, no terrain shade and
// no SH lobe (prog 198/VS 151). WINDOW (MOMT 0x20), interior drawer only: GL_LIGHT0
// becomes the Direct/Ambient midpoint as diffuse and it +16/255 as ambient, that byte
// add saturating on its own (0x6d37e0).
let window_mid = 0.5 * (wow_light.light_ambient.rgb + wow_light.light_diffuse.rgb);
let sum_window = min(window_mid + vec3<f32>(16.0 / 255.0), vec3<f32>(1.0))
+ window_mid * ndotl;
var sum_wmo = sum_nl;
// SIDN night glow (MOMT 0x10): authored emissive × night fraction, an emission term
// inside the clamp and never MOCV-multiplied; zero on INT, and TRANS's blend weights it.
var sidn_w = 1.0;
if ((word & WORD_INTERIOR) != 0u) {
sum_wmo = select(sum_nl, sum_window, (word & WORD_WINDOW) != 0u);
if ((word & WORD_CLASS_INT) != 0u) {
sum_wmo = vec3<f32>(1.0);
sidn_w = 0.0;
}
}
let sidn_rgb = vec3<f32>(
f32(rec.z & 0xffu),
f32((rec.z >> 8u) & 0xffu),
f32((rec.z >> 16u) & 0xffu),
) / 255.0;
let sidn_e = sidn_rgb * (wow_light.grade.x * sidn_w);
// GL_COLOR_MATERIAL: MOCV multiplies the light sum inside the clamp; emission adds beside.
return clamp(vc.rgb * sum_wmo + sidn_e, vec3<f32>(0.0), vec3<f32>(1.0));
}
// Order-2 SH basis terms of the vertex normal, for the doodad lobe and the probe lane.
let quad = vec4<f32>(n_lit.x * n_lit.y, n_lit.y * n_lit.z, n_lit.z * n_lit.z, n_lit.x * n_lit.z);
let x2y2 = n_lit.x * n_lit.x - n_lit.y * n_lit.y;
var e: vec3<f32>;
if ((word & WORD_INTERIOR) != 0u) {
// ---- interior M2 props: wow_model.wgsl's interior-prop lane ----
// The spawn-folded SH probe (MODD ambient, fixed-axis diffuse, the group's MOLR lobes)
// over the vertex normal; its soft wrap is the reference's, not a hard max(N·L, 0).
let probe = 7u * ((rec.w >> 1u) & 0x1fffu);
let n1 = vec4<f32>(n_lit, 1.0);
e = vec3<f32>(
dot(wow_light.prop_probes[probe + 0u], n1)
+ dot(wow_light.prop_probes[probe + 3u], quad)
+ wow_light.prop_probes[probe + 6u].x * x2y2,
dot(wow_light.prop_probes[probe + 1u], n1)
+ dot(wow_light.prop_probes[probe + 4u], quad)
+ wow_light.prop_probes[probe + 6u].y * x2y2,
dot(wow_light.prop_probes[probe + 2u], n1)
+ dot(wow_light.prop_probes[probe + 5u], quad)
+ wow_light.prop_probes[probe + 6u].z * x2y2,
);
} else {
// ---- exterior ADT doodads and exterior MODD props ----
// Model2.bls order-2 SH sun lobe at intensity 0.5 Shaded (MCSH), 1.0 Matte, 2.5 Lit.
// Deviation: the `min(I, 1)` cap, as in wow_model.wgsl, because lifting it takes
// sun-facing surfaces past 1.0; Matte keeps its own bit so it stays 1.0 if the cap goes.
let shade_t = select(1.0, 0.0, (word & WORD_SHADE_LIT) != 0u);
let intensity = min(
select(mix(2.5, 0.5, shade_t), 1.0, (word & WORD_MATTE) != 0u),
1.0,
);
let sun_dc = wow_light.grade.yzw * intensity;
let sun_lobe = vec3<f32>(
wow_light.sh_c10_r.w + sun_dc.x
+ intensity
* (dot(wow_light.sh_c10_r.xyz, n_lit) + dot(wow_light.sh_c13_r, quad)
+ wow_light.sh_c16.x * x2y2),
wow_light.sh_c10_g.w + sun_dc.y
+ intensity
* (dot(wow_light.sh_c10_g.xyz, n_lit) + dot(wow_light.sh_c13_g, quad)
+ wow_light.sh_c16.y * x2y2),
wow_light.sh_c10_b.w + sun_dc.z
+ intensity
* (dot(wow_light.sh_c10_b.xyz, n_lit) + dot(wow_light.sh_c13_b, quad)
+ wow_light.sh_c16.z * x2y2),
);
// Sun disabled (light_sun.w) falls back to the FFP sum, like the entity path.
e = select(sum_nl, sun_lobe, wow_light.light_sun.w > 0.5);
}
// `Model2.bls`: with a point light bound the program clamps E to [0, 1] before `c28`
// multiplies it, with none it writes `c28·E` to the saturating `oD0`.
e += point_lit.rgb;
if (point_lit.w > 0.5) {
e = clamp(e, vec3<f32>(0.0), vec3<f32>(1.0));
}
// `c28`: the vertex colour, the M2Color baked constant, is the lit material.
return clamp(vc.rgb * e, vec3<f32>(0.0), vec3<f32>(1.0));
}
// ---- the pass ----
struct GxVertex {
@@ -128,10 +229,10 @@ struct GxVertex {
struct GxVsOut {
@builtin(position) position: vec4<f32>,
@location(0) world_position: vec4<f32>,
@location(1) world_normal: vec3<f32>,
@location(2) uv: vec2<f32>,
@location(3) @interpolate(flat) word: u32,
@location(4) point_lit: vec3<f32>,
// The lit colour from `vertex_light`, clamped at the vertex and interpolated.
@location(4) primary: vec3<f32>,
@location(5) color: vec4<f32>,
}
@@ -143,10 +244,9 @@ fn vertex(v: GxVertex) -> GxVsOut {
if ((recs[v.word & 0xffffu].w & 1u) != 0u) {
out.position = vec4<f32>(0.0, 0.0, 2.0, 1.0);
out.world_position = vec4<f32>(0.0);
out.world_normal = vec3<f32>(0.0, 1.0, 0.0);
out.uv = vec2<f32>(0.0);
out.word = v.word;
out.point_lit = vec3<f32>(0.0);
out.primary = vec3<f32>(0.0);
out.color = vec4<f32>(1.0);
return out;
}
@@ -163,17 +263,18 @@ fn vertex(v: GxVertex) -> GxVsOut {
// Authored MOBA batch order (record y, 0 on cells): a later coplanar batch wins reverse-Z
// GreaterEqual in any draw order, because the draw sort does not keep authored order.
out.position.z *= 1.0 + f32(recs[v.word & 0xffffu].y) * 1.1920929e-7;
out.world_normal = v.normal;
out.uv = v.uv;
out.word = v.word;
out.color = v.color;
// Up to 3 nearest point lights, chosen from the placement origin. WMO surfaces take none,
// as in the reference; interior props neither: the probe holds their group's MOLR lights.
if ((v.word & (WORD_WMO | WORD_INTERIOR)) != 0u) {
out.point_lit = vec3<f32>(0.0);
} else {
out.point_lit = point_light_sum(world, v.normal, v.anchor);
var point_lit = vec4<f32>(0.0);
if ((v.word & (WORD_WMO | WORD_INTERIOR)) == 0u) {
point_lit = point_light_sum(world, v.normal, v.anchor);
}
// A colour-less batch takes a constant 1.0 (WORD_HAS_VC).
let vc = select(vec4<f32>(1.0), v.color, (v.word & WORD_HAS_VC) != 0u);
out.primary = vertex_light(v.normal, point_lit, vc, v.word);
return out;
}
@@ -217,139 +318,28 @@ fn fragment(in: GxVsOut) -> @location(0) vec4<f32> {
discard;
}
#endif
// Both faces light from the submitted normal (no GL_LIGHT_MODEL_TWO_SIDE in the reference);
// this pipeline never negates back faces, so it has no front-face select like wow_model.wgsl.
let n_lit = wow_normalize(in.world_normal);
let L = -normalize(wow_light.light_sun.xyz);
let ndotl = max(dot(n_lit, L), 0.0);
let lit_nl = clamp(
wow_light.light_ambient.rgb + wow_light.light_diffuse.rgb * ndotl,
vec3<f32>(0.0),
vec3<f32>(1.0),
);
// Order-2 SH basis terms of the fragment normal, for the doodad lobe and the probe lane.
let quad = vec4<f32>(n_lit.x * n_lit.y, n_lit.y * n_lit.z, n_lit.z * n_lit.z, n_lit.x * n_lit.z);
let x2y2 = n_lit.x * n_lit.x - n_lit.y * n_lit.y;
// A colour-less batch takes a constant 1.0, not interpolated white: interpolating a constant
// attribute gives 1.0±ε, and base × 0.99999994 rounds about half the pixels one byte down.
let has_vc = (in.word & WORD_HAS_VC) != 0u;
let vc = select(vec4<f32>(1.0), in.color, has_vc);
let folded = select(base.rgb, base.rgb * vc.rgb, has_vc);
var rgb: vec3<f32>;
if ((in.word & WORD_WMO) != 0u) {
// ---- WMO surfaces: wow_model.wgsl's is_wmo branch ----
let interior = (in.word & WORD_INTERIOR) != 0u;
let class_int = (in.word & WORD_CLASS_INT) != 0u;
let class_trans = (in.word & WORD_CLASS_TRANS) != 0u;
let trans_a = vc.a; // 1.0 where no MOCV is authored
// WINDOW (MOMT 0x20), interior drawer only: GL_LIGHT0 becomes the Direct/Ambient
// midpoint pair, ambient +16/255 saturating (0x6d37e0).
let window_mid = 0.5 * (wow_light.light_ambient.rgb + wow_light.light_diffuse.rgb);
let lit_window = clamp(
window_mid + vec3<f32>(16.0 / 255.0) + window_mid * ndotl,
vec3<f32>(0.0),
vec3<f32>(1.0),
);
let lit_int_base = select(lit_nl, lit_window, (in.word & WORD_WINDOW) != 0u);
// Interior batch classes: INT is unlit (the bake is the room's light), TRANS lerps lit
// to bake by MOCV alpha, EXT is plain lit_nl. Exterior groups take lit_nl at sun scale 1,
// no terrain shade and no SH lobe (prog 198/VS 151).
var lit_wmo_interior = vec3<f32>(1.0);
if (class_trans) {
lit_wmo_interior = mix(vec3<f32>(1.0), lit_int_base, trans_a);
} else if (!class_int) {
lit_wmo_interior = lit_int_base;
}
let lit_wmo = select(lit_nl, lit_wmo_interior, interior);
// SIDN night glow (MOMT 0x10): authored emissive × night fraction, an emission term
// inside the clamp and never MOCV-multiplied; zero on INT, MOCV-alpha weighted on TRANS.
let rec = recs[in.word & 0xffffu];
let sidn_rgb = vec3<f32>(
f32(rec.z & 0xffu),
f32((rec.z >> 8u) & 0xffu),
f32((rec.z >> 16u) & 0xffu),
) / 255.0;
var sidn_w = 1.0;
if (interior) {
if (class_trans) {
sidn_w = trans_a;
} else if (class_int) {
sidn_w = 0.0;
}
}
let sidn_e = sidn_rgb * (wow_light.grade.x * sidn_w);
// GL_COLOR_MATERIAL: MOCV multiplies the lit terms inside the clamp; emission adds beside.
let primary = clamp(
vc.rgb * (lit_wmo + in.point_lit) + sidn_e,
vec3<f32>(0.0),
vec3<f32>(1.0),
);
// The entity path's algebra: (tex×vc)/max(vc, 1/255) is not tex in floats; keep it.
let tex_rgb = folded / max(vc.rgb, vec3<f32>(1.0 / 255.0));
rgb = tex_rgb * primary;
if (interior && class_int && has_vc) {
// The stage-0 modulate: the texel times the lit colour `vertex_light` clamped per vertex,
// whose vertex colour is inside its clamp.
var rgb = base.rgb * in.primary;
if ((in.word & WORD_WMO) != 0u && (in.word & WORD_INTERIOR) != 0u) {
if ((in.word & WORD_CLASS_TRANS) != 0u) {
// TRANS: the lit pass by MOCV.a (blend 9) under the unlit `tex × MOCV` by 1 − MOCV.a
// (blend 7), `0x6b5190`, as one lerp.
rgb = base.rgb * mix(vc.rgb, in.primary, vc.a);
} else if ((in.word & WORD_CLASS_INT) != 0u && has_vc) {
// INT self-illumination, the reference's interior pixel shader (literal 4.0):
// tex·MOCV·(1 + 4·MOCV.a), clamped once. A colour-less INT batch keeps tex × lit.
rgb = clamp(
tex_rgb * vc.rgb * (1.0 + 4.0 * trans_a),
base.rgb * vc.rgb * (1.0 + 4.0 * vc.a),
vec3<f32>(0.0),
vec3<f32>(1.0),
);
}
} else if ((in.word & WORD_INTERIOR) != 0u) {
// ---- interior M2 props: wow_model.wgsl's interior-prop branch ----
// The spawn-folded SH probe (MODD ambient, fixed-axis diffuse, the group's MOLR lobes)
// over the fragment normal; its soft wrap is the reference's, not a hard max(N·L, 0).
let probe = 7u * ((recs[in.word & 0xffffu].w >> 1u) & 0x1fffu);
let n1 = vec4<f32>(n_lit, 1.0);
let lit_prop = clamp(
vec3<f32>(
dot(wow_light.prop_probes[probe + 0u], n1)
+ dot(wow_light.prop_probes[probe + 3u], quad)
+ wow_light.prop_probes[probe + 6u].x * x2y2,
dot(wow_light.prop_probes[probe + 1u], n1)
+ dot(wow_light.prop_probes[probe + 4u], quad)
+ wow_light.prop_probes[probe + 6u].y * x2y2,
dot(wow_light.prop_probes[probe + 2u], n1)
+ dot(wow_light.prop_probes[probe + 5u], quad)
+ wow_light.prop_probes[probe + 6u].z * x2y2,
),
vec3<f32>(0.0),
vec3<f32>(1.0),
);
let primary = clamp(lit_prop + in.point_lit, vec3<f32>(0.0), vec3<f32>(1.0));
rgb = folded * primary;
} else {
// ---- exterior ADT doodads and exterior MODD props ----
// Model2.bls order-2 SH sun lobe at intensity 0.5 Shaded (MCSH), 1.0 Matte, 2.5 Lit.
// Deviation: the `min(I, 1)` cap, as in wow_model.wgsl, because lifting it takes sun-facing
// surfaces past 1.0; Matte keeps its own bit so it stays 1.0 if the cap goes.
let shade_t = select(1.0, 0.0, (in.word & WORD_SHADE_LIT) != 0u);
let intensity = min(
select(mix(2.5, 0.5, shade_t), 1.0, (in.word & WORD_MATTE) != 0u),
1.0,
);
let sun_dc = wow_light.grade.yzw * intensity;
let sun_lobe = vec3<f32>(
wow_light.sh_c10_r.w + sun_dc.x
+ intensity
* (dot(wow_light.sh_c10_r.xyz, n_lit) + dot(wow_light.sh_c13_r, quad)
+ wow_light.sh_c16.x * x2y2),
wow_light.sh_c10_g.w + sun_dc.y
+ intensity
* (dot(wow_light.sh_c10_g.xyz, n_lit) + dot(wow_light.sh_c13_g, quad)
+ wow_light.sh_c16.y * x2y2),
wow_light.sh_c10_b.w + sun_dc.z
+ intensity
* (dot(wow_light.sh_c10_b.xyz, n_lit) + dot(wow_light.sh_c13_b, quad)
+ wow_light.sh_c16.z * x2y2),
);
let lit_doodad = clamp(sun_lobe, vec3<f32>(0.0), vec3<f32>(1.0));
// Sun disabled (light_sun.w) falls back to the FFP matte, like the entity path.
let lit = select(lit_nl, lit_doodad, wow_light.light_sun.w > 0.5);
// FFP combine: the light sum saturates first, then the texture modulates it.
let primary = clamp(lit + in.point_lit, vec3<f32>(0.0), vec3<f32>(1.0));
rgb = folded * primary;
}
// Unlit (M2 UNLIT 0x01, WMO UNLIT on an exterior group): texture × vertex colour, no light.
if ((in.word & WORD_UNLIT) != 0u) {
+92
View File
@@ -782,6 +782,98 @@ mod tests {
use super::testkit::{batch, batch_of, object, tri};
use super::*;
/// The static pass lights as the entity pass does, per vertex: `vertex_light` holds every
/// lane, the vertex stage writes its clamped colour to the interpolated `primary`, and the
/// fragment only modulates the texel by it.
#[test]
fn the_static_light_is_evaluated_per_vertex() {
let src = include_str!("../shaders/static_gx.wgsl");
let at = |needle: &str| {
src.find(needle)
.unwrap_or_else(|| panic!("`{needle}` is gone"))
};
let light = &src[at("fn vertex_light(")..at("// ---- the pass ----")];
let vertex = &src[at("@vertex")..at("@fragment")];
let fragment = &src[at("@fragment")..];
for (lane, term) in [
("the exterior SH lobe", "wow_light.sh_c10_r.w + sun_dc.x"),
("the FFP N·L", "let ndotl = max(dot(n_lit, L), 0.0);"),
(
"the interior probe",
"dot(wow_light.prop_probes[probe + 0u], n1)",
),
] {
assert!(light.contains(term), "{lane} left `vertex_light`");
}
assert!(
vertex.contains("out.primary = vertex_light(v.normal, point_lit, vc, v.word);"),
"the vertex stage no longer lights its vertex"
);
assert!(
src.contains(" @location(4) primary: vec3<f32>,\n"),
"the lit colour must be interpolated across the triangle, never flat"
);
for term in [
"sh_c10",
"prop_probes",
"light_sun",
"light_diffuse",
"point_light_sum",
"vertex_light(",
] {
assert!(
!fragment.contains(term),
"the fragment evaluates `{term}` again — the reference lights per vertex"
);
}
}
/// The vertex colour is the lit material inside the one clamp, as in `wow_model.wgsl`: MOCV
/// under GL_COLOR_MATERIAL (`0x59cfec`), a doodad's baked M2Color as `Model2.bls`'s `c28`,
/// whose light sum clamps first only with a point light bound.
#[test]
fn the_static_vertex_colour_is_lit_inside_the_one_clamp() {
let src = include_str!("../shaders/static_gx.wgsl");
let at = |needle: &str| {
src.find(needle)
.unwrap_or_else(|| panic!("`{needle}` is gone"))
};
let light = &src[at("fn vertex_light(")..at("// ---- the pass ----")];
let fragment = &src[at("@fragment")..];
for (why, line) in [
(
"the FFP sum is never clamped on its own",
"let sum_nl = wow_light.light_ambient.rgb + wow_light.light_diffuse.rgb * ndotl;",
),
(
"a WMO's MOCV multiplies the light sum inside the one clamp",
"return clamp(vc.rgb * sum_wmo + sidn_e, vec3<f32>(0.0), vec3<f32>(1.0));",
),
(
"a doodad's colour multiplies E inside the one clamp",
"return clamp(vc.rgb * e, vec3<f32>(0.0), vec3<f32>(1.0));",
),
(
"E clamps first only with a point light bound",
"if (point_lit.w > 0.5) {\n e = clamp(e, vec3<f32>(0.0), vec3<f32>(1.0));\n }",
),
] {
assert!(light.contains(line), "{why}: `{line}` is gone");
}
assert!(
!light.contains("clamp(sun_lobe"),
"the SH lobe clamps before the colour multiplies it again"
);
assert!(
fragment.contains("var rgb = base.rgb * in.primary;"),
"the texel multiplies the vertex colour outside the clamp again"
);
assert!(
fragment.contains("rgb = base.rgb * mix(vc.rgb, in.primary, vc.a);"),
"a TRANS batch is its clamped lit pass by MOCV.a over the unlit `tex × MOCV`"
);
}
#[test]
fn a_collected_region_is_undrawn_until_it_publishes() {
let mut gx = StaticGx::default();
+2 -2
View File
@@ -531,7 +531,7 @@ Each entry is the first sentence of a `Deviation:` comment, linking to where it
#### shaders
- This is the `specular`/`pixelShaders` = 1 leg the reference install runs; both CVars (`0x6886a0`/`0x688712`) default to 0, where water has no program, no specular, a plain ADD combine and no blend. An active ARB program bypasses the texture environment. ([`src/shaders/liquid.wgsl:18`](../crates/benilla-assets/src/shaders/liquid.wgsl#L18))
- `min(I, 1)`. The reference bakes I into the SH unclamped (`0x71c4e0`), so a lit entity commits ×2.5 there and ×1.0 here; lifting the cap takes sun-facing surfaces past 1.0. `entity_shade::LIT_T` aims the lit ramp at 1.0 because of it: lift the cap and set `LIT_T` back to 0.0 together. ([`src/shaders/wow_model.wgsl:668`](../crates/benilla-assets/src/shaders/wow_model.wgsl#L668))
- `min(I, 1)`. The reference bakes I into the SH unclamped (`0x71c4e0`), so a lit entity commits ×2.5 there and ×1.0 here; lifting the cap takes sun-facing surfaces past 1.0. `entity_shade::LIT_T` aims the lit ramp at 1.0 because of it: lift the cap and set `LIT_T` back to 0.0 together. ([`src/shaders/wow_model.wgsl:454`](../crates/benilla-assets/src/shaders/wow_model.wgsl#L454))
#### wmo
@@ -928,7 +928,7 @@ Each entry is the first sentence of a `Deviation:` comment, linking to where it
#### shaders
- The `min(I, 1)` cap, as in wow\_model.wgsl, because lifting it takes sun-facing surfaces past 1.0; Matte keeps its own bit so it stays 1.0 if the cap goes. ([`src/shaders/static_gx.wgsl:325`](../crates/benilla-world/src/shaders/static_gx.wgsl#L325))
- The `min(I, 1)` cap, as in wow\_model.wgsl, because lifting it takes sun-facing surfaces past 1.0; Matte keeps its own bit so it stays 1.0 if the cap goes. ([`src/shaders/static_gx.wgsl:182`](../crates/benilla-world/src/shaders/static_gx.wgsl#L182))
#### sky_order