ling-lang 2030.1.39

Ling - The Omniglot Systems Language
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
// src/gfx/material.rs — LingMaterial: principled BSDF with toon quantisation.
//
// "Photon-water" model
// ════════════════════
// Think of each pixel as a tiny pool. Every light source pours coloured photons
// in. The pool level (energy) is then snapped to discrete toon steps — like
// water settling into terraced channels on a hillside. This gives crisp cel
// bands whose boundaries follow the surface curvature instead of the triangle
// edges, so quads and hexagons look as clean as triangles.
//
// BSDF feature set (2030 baseline)
// ─────────────────────────────────
//   Core       — albedo · roughness · metallic
//   Emission   — emission colour + strength (self-lit surfaces, neon, fire)
//   Specular   — GGX lobe, quantised to a toon hotspot
//   Subsurface — cheap SSS: colour bleed at shadow boundaries (skin, wax)
//   Clearcoat  — secondary GGX layer (car paint, guitar lacquer)
//   Iridescence— thin-film angle-dependent hue (bubbles, beetle wings, CD)
//   Sheen      — retro-reflection for fabric (velvet, satin, felt)
//   Anisotropy — elongated specular (brushed metal, hair, records)
//   Transmission— simple glass/water: alpha-blends the background
//
// Toon overrides
// ──────────────
//   toon_bands        — number of discrete shading levels (2 = shadow+lit)
//   shadow_softness   — cross-fade width at band boundaries (0 = hard step)
//   outline_px        — ink-line thickness in pixels (0 = no outline)
//   outline_color     — ink colour
//   highlight_color   — colour of the brightest toon band (normally white)

use crate::gfx::light::Light;

// ── Material struct ───────────────────────────────────────────────────────────

#[derive(Debug, Clone)]
pub struct LingMaterial {
    // Core
    pub albedo: u32,    // 0x00RRGGBB
    pub roughness: f32, // 0 = mirror, 1 = diffuse
    pub metallic: f32,  // 0 = dielectric, 1 = conductor

    // Emission
    pub emission: u32,
    pub emission_strength: f32,

    // Specular
    pub specular: f32,      // base Fresnel reflectance at 0°
    pub specular_tint: f32, // 0 = white hotspot, 1 = albedo-tinted

    // Subsurface scattering (approximated)
    pub subsurface: f32,
    pub subsurface_color: u32,

    // Clearcoat
    pub clearcoat: f32,
    pub clearcoat_roughness: f32,

    // Transmission
    pub transmission: f32, // 0 = opaque, 1 = glass
    pub ior: f32,          // index of refraction

    // 2030 extras
    pub iridescence: f32,      // thin-film interference [0..1]
    pub sheen: f32,            // fabric retro-reflection [0..1]
    pub anisotropy: f32,       // specular elongation [0..1]
    pub anisotropy_angle: f32, // radians

    // Toon overrides
    pub toon_bands: u32,      // discrete shading levels (≥2)
    pub shadow_softness: f32, // band-boundary blend width [0..1]
    pub outline_px: f32,      // ink-line thickness (0 = off)
    pub outline_color: u32,
    pub highlight_color: u32,
}

impl Default for LingMaterial {
    fn default() -> Self {
        Self {
            albedo: 0x00FF_FFFF,
            roughness: 0.8,
            metallic: 0.0,
            emission: 0,
            emission_strength: 0.0,
            specular: 0.04,
            specular_tint: 0.0,
            subsurface: 0.0,
            subsurface_color: 0x00FF_C8A0,
            clearcoat: 0.0,
            clearcoat_roughness: 0.03,
            transmission: 0.0,
            ior: 1.5,
            iridescence: 0.0,
            sheen: 0.0,
            anisotropy: 0.0,
            anisotropy_angle: 0.0,
            toon_bands: 3,
            shadow_softness: 0.04,
            outline_px: 0.0,
            outline_color: 0x00_00_00,
            highlight_color: 0x00FF_FFFF,
        }
    }
}

// ── Helpers ───────────────────────────────────────────────────────────────────

#[inline]
fn unpack(c: u32) -> (f32, f32, f32) {
    (
        ((c >> 16) & 0xFF) as f32 / 255.0,
        ((c >> 8) & 0xFF) as f32 / 255.0,
        (c & 0xFF) as f32 / 255.0,
    )
}

#[inline]
fn pack01(r: f32, g: f32, b: f32) -> u32 {
    let (r, g, b) = tone_map_rgb(r, g, b);
    let r = (r * 255.0) as u32;
    let g = (g * 255.0) as u32;
    let b = (b * 255.0) as u32;
    (r << 16) | (g << 8) | b
}

#[inline]
fn tone_map_rgb(r: f32, g: f32, b: f32) -> (f32, f32, f32) {
    let r = r.max(0.0);
    let g = g.max(0.0);
    let b = b.max(0.0);
    let lum = r * 0.2126 + g * 0.7152 + b * 0.0722;
    if lum <= 1.0 {
        return (r.min(1.0), g.min(1.0), b.min(1.0));
    }

    let mapped = 1.0 - (-lum * 0.82).exp();
    let scale = mapped / lum.max(1e-6);
    ((r * scale).min(1.0), (g * scale).min(1.0), (b * scale).min(1.0))
}

/// Schlick Fresnel: f0 + (1-f0)*(1-cosθ)^5
#[inline]
fn schlick(cos_theta: f32, f0: f32) -> f32 {
    let c = (1.0 - cos_theta).clamp(0.0, 1.0);
    let c2 = c * c;
    f0 + (1.0 - f0) * c2 * c2 * c
}

/// GGX specular quantised to a toon hotspot: either 0 or 1.
/// Low roughness → large bright hotspot; high roughness → the lobe disappears.
#[inline]
fn ggx_toon(n_dot_h: f32, roughness: f32) -> f32 {
    let a2 = roughness * roughness * roughness * roughness; // α⁴
    let d = n_dot_h * n_dot_h * (a2 - 1.0) + 1.0;
    let ggx = a2 / (std::f32::consts::PI * d * d + 1e-6);
    // Normalise to [0,1] and use a soft toon shoulder. A binary hotspot creates
    // salt-and-pepper white flicker on dense tessellated floors under many lights.
    let t = (ggx * a2 * 3.0).clamp(0.0, 1.0);
    let s = ((t - 0.38) / 0.44).clamp(0.0, 1.0);
    s * s * (3.0 - 2.0 * s)
}

/// Smooth GGX specular: continuous [0,1], same normalisation as `ggx_toon`
/// but without the hard snap. Use for smooth (non-toon) shading.
#[inline]
fn ggx_smooth(n_dot_h: f32, roughness: f32) -> f32 {
    let a2 = roughness * roughness * roughness * roughness; // α⁴
    let d = n_dot_h * n_dot_h * (a2 - 1.0) + 1.0;
    let ggx = a2 / (std::f32::consts::PI * d * d + 1e-6);
    (ggx * a2 * 3.0).clamp(0.0, 1.0)
}


#[inline]
fn dot3(a: [f32; 3], b: [f32; 3]) -> f32 {
    a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
}

#[inline]
fn norm3(v: [f32; 3]) -> [f32; 3] {
    let len = (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt();
    if len < 1e-7 {
        [0.0, 0.0, 1.0]
    } else {
        [v[0] / len, v[1] / len, v[2] / len]
    }
}

// ── Main shade function ───────────────────────────────────────────────────────

/// Evaluate LingMaterial at a surface point and return 0x00RRGGBB.
///
/// * `mat`       — material to evaluate
/// * `normal`    — world-space face normal (need not be normalised)
/// * `view_dir`  — direction from surface toward the camera (world space)
/// * `centroid`  — world-space surface point
/// * `lights`    — active point lights
/// * `ambient`   — ambient fill level [0..1]
pub fn shade(
    mat: &LingMaterial,
    normal: [f32; 3],
    view_dir: [f32; 3],
    centroid: [f32; 3],
    lights: &[Light],
    ambient: f32,
) -> u32 {
    let (ar, ag, ab) = unpack(mat.albedo);
    let n = norm3(normal);
    let v = norm3(view_dir);
    let n_dot_v = dot3(n, v).abs().clamp(1e-4, 1.0);

    // Ambient + emission
    let mut acc_r = ar * ambient;
    let mut acc_g = ag * ambient;
    let mut acc_b = ab * ambient;
    if mat.emission_strength > 0.0 {
        let (er, eg, eb) = unpack(mat.emission);
        acc_r += er * mat.emission_strength;
        acc_g += eg * mat.emission_strength;
        acc_b += eb * mat.emission_strength;
    }

    // Per-light contribution
    for l in lights {
        let dx = l.x - centroid[0];
        let dy = l.y - centroid[1];
        let dz = l.z - centroid[2];
        let dist = (dx * dx + dy * dy + dz * dz).sqrt().max(1e-6);
        let atten = if l.radius > 0.0 {
            (1.0 - dist / l.radius).max(0.0)
        } else {
            1.0
        };
        if atten <= 0.0 {
            continue;
        }

        let ld = [dx / dist, dy / dist, dz / dist];
        let n_dot_l = dot3(n, ld).abs(); // two-sided shading
        let h = norm3([ld[0] + v[0], ld[1] + v[1], ld[2] + v[2]]);
        let n_dot_h = dot3(n, h).clamp(0.0, 1.0);

        // ── Diffuse: always raw Lambertian here — toon quantisation happens
        // once, per pixel, on the interpolated Gouraud colour (see
        // `raster::posterize_span`). Quantising per vertex as well as per
        // pixel would double-band and, worse, lock band edges to shared
        // vertices — the tile-corner popping this replaces.
        let smooth_mode = mat.toon_bands == 0;
        let diff = n_dot_l;

        // Subsurface: tint the shadow zone toward subsurface_color
        let (eff_r, eff_g, eff_b) = if mat.subsurface > 0.0 {
            let (sr, sg, sb) = unpack(mat.subsurface_color);
            let zone = ((0.3 - n_dot_l) * 3.33).clamp(0.0, 1.0) * mat.subsurface;
            (
                ar + (sr - ar) * zone,
                ag + (sg - ag) * zone,
                ab + (sb - ab) * zone,
            )
        } else {
            (ar, ag, ab)
        };

        let dr = eff_r * diff;
        let dg = eff_g * diff;
        let db = eff_b * diff;

        // ── Specular: smooth GGX or binary toon hotspot ───────────────────────
        let f0_dielectric = mat.specular * 0.08; // maps [0,1] → [0,0.08]
        let f0 = f0_dielectric + mat.metallic * (ar - f0_dielectric);
        let fresnel = schlick(n_dot_v, f0.clamp(0.0, 1.0));
        let spec = if smooth_mode {
            ggx_smooth(n_dot_h, mat.roughness.max(0.01)) * fresnel
        } else {
            ggx_toon(n_dot_h, mat.roughness.max(0.01)) * fresnel
        };

        let spec_white = spec * (1.0 - mat.specular_tint);
        let sr = spec_white + spec * ar * mat.specular_tint;
        let sg = spec_white + spec * ag * mat.specular_tint;
        let sb = spec_white + spec * ab * mat.specular_tint;

        // ── Clearcoat (white GGX on top) ──────────────────────────────────────
        let coat = ggx_toon(n_dot_h, mat.clearcoat_roughness.max(0.01)) * mat.clearcoat;

        // ── Iridescence (thin-film angle-dependent hue) ───────────────────────
        // Phase-shifted cosines per channel → RGB rainbow at glancing angles
        let (ir, ig, ib) = if mat.iridescence > 0.0 {
            let p = n_dot_v * std::f32::consts::TAU * 2.0;
            let tau3 = std::f32::consts::FRAC_PI_3 * 2.0;
            let ir = (p.cos() * 0.5 + 0.5) * mat.iridescence;
            let ig = ((p + tau3).cos() * 0.5 + 0.5) * mat.iridescence;
            let ib = ((p + tau3 * 2.0).cos() * 0.5 + 0.5) * mat.iridescence;
            (ir, ig, ib)
        } else {
            (0.0, 0.0, 0.0)
        };

        // ── Sheen (retro-reflection: peak at 90° incidence) ───────────────────
        let sheen = if mat.sheen > 0.0 {
            (1.0 - n_dot_l).powi(3) * mat.sheen
        } else {
            0.0
        };

        let intensity = l.intensity * atten;
        acc_r += (dr + sr + coat + ir + sheen * ar) * l.r * intensity;
        acc_g += (dg + sg + coat + ig + sheen * ag) * l.g * intensity;
        acc_b += (db + sb + coat + ib + sheen * ab) * l.b * intensity;
    }

    pack01(acc_r, acc_g, acc_b)
}

/// Compute per-vertex material colours for a Gouraud-shaded triangle.
/// Returns three 0x00RRGGBB colours.
#[allow(clippy::too_many_arguments)]
pub fn shade_vertices(
    mat: &LingMaterial,
    normal: [f32; 3],
    va: [f32; 3],
    vb: [f32; 3],
    vc: [f32; 3],
    camera_pos: [f32; 3],
    lights: &[Light],
    ambient: f32,
) -> (u32, u32, u32) {
    let view = |v: [f32; 3]| {
        [
            camera_pos[0] - v[0],
            camera_pos[1] - v[1],
            camera_pos[2] - v[2],
        ]
    };
    (
        shade(mat, normal, view(va), va, lights, ambient),
        shade(mat, normal, view(vb), vb, lights, ambient),
        shade(mat, normal, view(vc), vc, lights, ambient),
    )
}

/// Compute per-vertex material colours for an n-gon (up to N vertices).
/// Writes results into `out[0..n]`.
#[allow(clippy::too_many_arguments)]
pub fn shade_polygon(
    mat: &LingMaterial,
    normal: [f32; 3],
    verts: &[[f32; 3]],
    n: usize,
    camera_pos: [f32; 3],
    lights: &[Light],
    ambient: f32,
    out: &mut [u32],
) {
    let view = |v: [f32; 3]| {
        [
            camera_pos[0] - v[0],
            camera_pos[1] - v[1],
            camera_pos[2] - v[2],
        ]
    };
    for i in 0..n.min(verts.len()).min(out.len()) {
        out[i] = shade(mat, normal, view(verts[i]), verts[i], lights, ambient);
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn default_material_no_crash_no_lights() {
        let mat = LingMaterial::default();
        let c = shade(
            &mat,
            [0.0, 0.0, 1.0],
            [0.0, 0.0, 1.0],
            [0.0, 0.0, 0.0],
            &[],
            0.5,
        );
        let lum = ((c >> 16 & 0xFF) as f32 * 0.299
            + (c >> 8 & 0xFF) as f32 * 0.587
            + (c & 0xFF) as f32 * 0.114)
            / 255.0;
        // With ambient=0.5 and white albedo the result should be non-zero
        assert!(lum > 0.1, "expected visible output, got lum={lum:.3}");
    }

    #[test]
    fn metallic_tints_specular() {
        let mat = LingMaterial {
            albedo: 0x00FF_0000, // red metal
            metallic: 1.0,
            specular_tint: 1.0,
            roughness: 0.1,
            ..Default::default()
        };

        let light = crate::gfx::light::Light {
            x: 0.0,
            y: 0.0,
            z: 10.0,
            r: 1.0,
            g: 1.0,
            b: 1.0,
            intensity: 2.0,
            radius: 0.0,
        };
        let c = shade(
            &mat,
            [0.0, 0.0, 1.0],
            [0.0, 0.0, 1.0], // view = straight ahead
            [0.0, 0.0, 0.0],
            &[light],
            0.05,
        );
        let r = (c >> 16) & 0xFF;
        let g = (c >> 8) & 0xFF;
        // Red metal should have more red than green
        assert!(r >= g, "metallic red should be reddish: r={r} g={g}");
    }
}