ling-lang 2030.1.36

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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
// src/gfx/mod.rs — unified graphics state + sub-modules.
//
// Sub-modules
//   raster   — pixel-level fill_triangle / draw_line
//   camera   — Camera3D: rotation + world→screen projection
//   light    — Light struct + cel-shade quantiser
//   depth    — DepthQueue: deferred draw accumulator
//   poly     — EdgeSet (shared-edge dedup) + fan triangulation
//   material — LingMaterial: principled BSDF + toon quantisation
//   photon   — PhotonBuf: water-photon HDR accumulation
//   toon     — Screen-space post-process (outlines, shadow edges, highlights)
//   vtex     — vector texture primitives
//   webgl    — WebGL2 backend (wasm32 only)

pub mod camera;
pub mod color;
pub mod depth;
pub mod light;
pub mod material;
pub mod photon;
pub mod poly;
pub mod raster;
pub mod shapes;
pub mod toon;
pub mod vtex;
#[cfg(target_arch = "wasm32")]
pub mod audio_web;
#[cfg(target_arch = "wasm32")]
pub mod webgl;
#[cfg(feature = "gpu")]
pub mod wgpu_raster;

pub use camera::Camera3D;
pub use depth::DepthQueue;
pub use light::Light;
pub use material::LingMaterial;
pub use toon::ToonConfig;

/// Tunable mapping for `cast_shadow`: how a blob/contact shadow's size and
/// opacity change with the caster's height above the surface. Defaults give the
/// natural look — small/dark/sharp when the caster touches down, growing larger,
/// fainter and softer as it rises. Pass a negative `fade` to invert the opacity
/// ramp (fainter when close, more opaque when far).
#[derive(Clone, Copy)]
pub struct ShadowParams {
    /// Radius (px) when the caster sits on the surface (height 0).
    pub base: f32,
    /// Extra radius per unit of height — the shadow grows as the caster rises.
    pub grow: f32,
    /// Opacity at height 0 (0..1) — darkest/sharpest when touching the surface.
    pub alpha: f32,
    /// Opacity lost per unit of height — the shadow fades as the caster rises.
    pub fade: f32,
    /// Edge softness 0..1 at height 0 — feathering also widens with height.
    pub soft: f32,
}

impl Default for ShadowParams {
    fn default() -> Self {
        Self { base: 14.0, grow: 0.6, alpha: 0.55, fade: 0.012, soft: 0.45 }
    }
}

// ─── Native GfxState (minifb window + software framebuffer) ──────────────────

#[cfg(not(target_arch = "wasm32"))]
pub struct GfxState {
    pub window: Option<minifb::Window>,
    pub buffer: Vec<u32>,
    /// Reusable scratch for `distort()` — avoids an 8 MB clone+alloc every frame.
    pub distort_buf: Vec<u32>,
    pub width: usize,
    pub height: usize,
    /// Current pen colour (0x00RRGGBB) set by `สีดินสอ` / `set_color`.
    pub color: u32,
    /// 3-D camera — set once per frame with `set_camera`.
    pub camera: Camera3D,
    /// Active point lights for this frame — cleared by `clear_lights`.
    pub lights: Vec<Light>,
    /// Ambient fill level [0..1].  Default 0.15.
    pub ambient: f32,
    /// Depth-sorted draw queue — flushed by `แสดงผล` / `present`.
    pub depth_queue: DepthQueue,
    /// Mouse position delta since last frame (pixels).
    pub mouse_dx: f32,
    pub mouse_dy: f32,
    /// Previous mouse position for delta computation; NaN = no prior sample.
    pub last_mx: f32,
    pub last_my: f32,
    /// When true: cursor is hidden and reset to center every frame for infinite rotation.
    pub mouse_captured: bool,
    /// Shading mode for 3-D shape meshes: 0 flat · 1 cel · 2 holo (default).
    pub shade_mode: u8,
    /// Tunable cel/holo parameters (bands, shadow tint, rim, …).
    pub shade: ling_graphics::shading::ShadeParams,
    /// Blend mode for pixel writes: 0 = normal (overwrite), 1 = additive.
    pub blend: u8,
    /// Pen opacity [0..1] for the alpha-blended fills (gradient surfaces,
    /// shadow blobs). Set by `set_alpha`; 1.0 = fully opaque.
    pub alpha: f32,
    /// Tunable height→size/opacity mapping for `cast_shadow`.
    pub shadow: ShadowParams,
    /// Gamma-correct compositing: blend alpha/gradients in linear light instead
    /// of sRGB. Set by `set_color_space`; default false (legacy sRGB).
    pub linear_blend: bool,
    /// Interpolate gradients perceptually through OkLab. Set by
    /// `set_gradient_space`; default true.
    pub grad_oklab: bool,
    /// Per-pixel depth test (true z-buffer) for the deferred queue instead of
    /// pure painter's sort. Set by `set_depth_test`; default false.
    pub depth_test: bool,
    /// Z-buffer (camera-space depth per pixel); sized to width*height when
    /// depth testing is on. Reset to +∞ on the next flush after a screen clear
    /// (`เติม`) so it persists across a frame's multiple flushes (like
    /// `glClear(DEPTH)`), then accumulates correct occlusion across all layers.
    pub depth_buf: Vec<f32>,
    /// True ⇒ the next depth flush clears the z-buffer first (set by `เติม` /
    /// `clear_depth`). Lets the z-buffer span a frame's many `flush_3d` calls.
    pub zbuf_needs_clear: bool,
    /// Distance fog: triangles/lines fade toward `fog_color` from `fog_start`
    /// to `fog_end` (camera-space depth). `fog_end <= 0` disables fog.
    pub fog_color: u32,
    pub fog_start: f32,
    pub fog_end: f32,
    /// Perf test: force flat *unlit* shading — triangle/mesh draws skip
    /// `compute_lit_color` and use the raw pen colour. Toggle via `set_flat_shade`.
    pub flat_shade: bool,
    /// Per-frame shared-edge dedup: `draw_line_3d` skips edges already drawn.
    pub edge_set: poly::EdgeSet,
    /// Active material override.  When `Some`, polygon draws use the BSDF
    /// instead of `compute_lit_color_linear`.  `None` = legacy path.
    pub material: Option<LingMaterial>,
    /// Toon post-processing configuration (outlines, shadow softness, highlight).
    pub toon: ToonConfig,
    /// Baked local-space triangle meshes (display lists) indexed by handle.
    /// Each entry is a flat run of `[ax,ay,az, bx,by,bz, cx,cy,cz]` local verts.
    pub meshes: Vec<Vec<([f32; 9], u32)>>,
    /// Active mesh capture buffer. While `Some`, `draw_triangle_3d` records raw
    /// local coords here instead of submitting to the depth queue.
    pub mesh_capture: Option<Vec<([f32; 9], u32)>>,
    /// Reclaimable mesh slots (freed on keyed-cache eviction) for `mesh_register`.
    pub mesh_free: Vec<usize>,
    /// Keyed display-list cache (e.g. world rooms): key → mesh handle, bounded.
    pub mesh_cache: std::collections::HashMap<i64, usize>,
}

#[cfg(not(target_arch = "wasm32"))]
impl GfxState {
    pub fn new() -> Self {
        Self {
            window: None,
            buffer: Vec::new(),
            distort_buf: Vec::new(),
            width: 0,
            height: 0,
            color: 0x00FF_FFFF,
            camera: Camera3D::default(),
            lights: Vec::new(),
            ambient: 0.15,
            depth_queue: DepthQueue::default(),
            mouse_dx: 0.0,
            mouse_dy: 0.0,
            last_mx: f32::NAN,
            last_my: f32::NAN,
            mouse_captured: false,
            shade_mode: 2,
            shade: ling_graphics::shading::ShadeParams::default(),
            blend: 0,
            alpha: 1.0,
            shadow: ShadowParams::default(),
            linear_blend: false,
            grad_oklab: true,
            depth_test: false,
            depth_buf: Vec::new(),
            zbuf_needs_clear: true,
            fog_color: 0x0000_0000,
            fog_start: 0.0,
            fog_end: 0.0,
            flat_shade: false,
            edge_set: poly::EdgeSet::default(),
            material: None,
            toon: ToonConfig::default(),
            meshes: Vec::new(),
            mesh_capture: None,
            mesh_free: Vec::new(),
            mesh_cache: std::collections::HashMap::new(),
        }
    }

    /// Blend a colour toward the fog colour by camera-space `depth`.
    #[inline]
    pub fn fog_apply(&self, color: u32, depth: f32) -> u32 {
        if self.fog_end <= 0.0 {
            return color;
        }
        let span = self.fog_end - self.fog_start;
        if span <= 0.0 {
            return color;
        }
        let f = ((depth - self.fog_start) / span).clamp(0.0, 1.0);
        if f <= 0.0 {
            return color;
        }
        let lerp = |a: u32, b: u32| -> u32 { (a as f32 + (b as f32 - a as f32) * f) as u32 & 0xff };
        let r = lerp((color >> 16) & 0xff, (self.fog_color >> 16) & 0xff);
        let g = lerp((color >> 8) & 0xff, (self.fog_color >> 8) & 0xff);
        let b = lerp(color & 0xff, self.fog_color & 0xff);
        (r << 16) | (g << 8) | b
    }

    pub fn sync_projection(&mut self) {
        self.camera.cx = self.width as f32 / 2.0;
        self.camera.cy = self.height as f32 / 2.0;
        self.camera.focal = self.height as f32;
        self.camera.zdist = 5.0;
    }

    /// Run all enabled toon post-process passes on the pixel buffer.
    /// Call this after `depth_queue.flush()` and before presenting to screen.
    pub fn toon_post_process(&mut self) {
        let w = self.width;
        let h = self.height;
        if self.buffer.len() < w * h { return; }
        toon::apply(&self.toon, &mut self.buffer, &self.depth_buf, w, h);
    }
}

// ─── WASM keyboard state (thread-local, accessed from JS via wasm_bindgen) ────

#[cfg(target_arch = "wasm32")]
thread_local! {
    static WASM_KEYS_PRESSED: std::cell::RefCell<std::collections::HashSet<String>> =
        std::cell::RefCell::new(std::collections::HashSet::new());
    static WASM_KEYS_DOWN: std::cell::RefCell<std::collections::HashSet<String>> =
        std::cell::RefCell::new(std::collections::HashSet::new());
}

/// Called from JavaScript when a key is pressed down
#[cfg(target_arch = "wasm32")]
pub fn wasm_key_down(key: &str) {
    let key = normalize_key(key);
    WASM_KEYS_DOWN.with(|keys_down| {
        let mut down = keys_down.borrow_mut();
        if !down.contains(&key) {
            WASM_KEYS_PRESSED.with(|keys_pressed| {
                keys_pressed.borrow_mut().insert(key.clone());
            });
        }
        down.insert(key);
    });
}

/// Called from JavaScript when a key is released
#[cfg(target_arch = "wasm32")]
pub fn wasm_key_up(key: &str) {
    let key = normalize_key(key);
    WASM_KEYS_DOWN.with(|keys_down| {
        keys_down.borrow_mut().remove(&key);
    });
}

/// Resume the Web Audio AudioContext after a user gesture.
#[cfg(target_arch = "wasm32")]
pub fn audio_resume() {
    audio_web::resume();
}

/// Clear the per-frame pressed keys (call at start of each frame)
#[cfg(target_arch = "wasm32")]
pub fn wasm_clear_frame_keys() {
    WASM_KEYS_PRESSED.with(|keys| {
        keys.borrow_mut().clear();
    });
}

/// Check if a key was pressed this frame
#[cfg(target_arch = "wasm32")]
pub fn wasm_is_key_pressed(key: &str) -> bool {
    let key = normalize_key(key);
    WASM_KEYS_PRESSED.with(|keys| {
        keys.borrow().contains(&key)
    })
}

/// Normalize browser key names to match Ling's key naming convention
#[cfg(target_arch = "wasm32")]
fn normalize_key(key: &str) -> String {
    match key {
        " " => "space".to_string(),
        "ArrowUp" => "up".to_string(),
        "ArrowDown" => "down".to_string(),
        "ArrowLeft" => "left".to_string(),
        "ArrowRight" => "right".to_string(),
        "Enter" => "enter".to_string(),
        "Escape" => "escape".to_string(),
        "Shift" | "ShiftLeft" | "ShiftRight" => "shift".to_string(),
        "Control" | "ControlLeft" | "ControlRight" => "ctrl".to_string(),
        "Alt" | "AltLeft" | "AltRight" => "alt".to_string(),
        "Tab" => "tab".to_string(),
        "Backspace" => "backspace".to_string(),
        _ => key.to_lowercase(),
    }
}

// ─── WASM GfxState (no window, no software framebuffer) ──────────────────────

#[cfg(target_arch = "wasm32")]
pub struct GfxState {
    pub width: usize,
    pub height: usize,
    /// Current pen colour (0x00RRGGBB).
    pub color: u32,
    /// Fill / clear colour components [0..1].
    pub fill_r: f32,
    pub fill_g: f32,
    pub fill_b: f32,
    pub camera: Camera3D,
    pub lights: Vec<Light>,
    pub ambient: f32,
    /// Accumulates projected screen-space draw calls; flushed to WebGL by present().
    pub depth_queue: DepthQueue,
    pub shade_mode: u8,
    pub shade: ling_graphics::shading::ShadeParams,
    /// Software framebuffer — the same CPU raster path as native. On the web,
    /// `present()` uploads this to the canvas, so 2-D builtins render identically.
    pub buffer: Vec<u32>,
    /// Reusable scratch for `distort()` — avoids a per-frame clone.
    pub distort_buf: Vec<u32>,
    /// Blend mode for pixel writes: 0 = normal (overwrite), 1 = additive.
    pub blend: u8,
    /// Pen opacity [0..1] for the alpha-blended fills (mirrors native).
    pub alpha: f32,
    /// Tunable height→size/opacity mapping for `cast_shadow`.
    pub shadow: ShadowParams,
    /// Gamma-correct (linear-light) compositing — mirrors native.
    pub linear_blend: bool,
    /// Perceptual OkLab gradient interpolation — mirrors native.
    pub grad_oklab: bool,
    /// Per-pixel depth test (z-buffer) for the deferred queue — mirrors native.
    pub depth_test: bool,
    /// Z-buffer (camera-space depth per pixel).
    pub depth_buf: Vec<f32>,
    /// Mirrors native: next depth flush clears the z-buffer first.
    pub zbuf_needs_clear: bool,
    /// Distance fog (mirrors native): fade toward `fog_color` from `fog_start`
    /// to `fog_end`. `fog_end <= 0` disables fog.
    pub fog_color: u32,
    pub fog_start: f32,
    pub fog_end: f32,
    /// Perf test: force flat *unlit* shading (mirrors native).
    pub flat_shade: bool,
    /// Keyboard state: keys pressed this frame (cleared each frame)
    pub keys_pressed: std::collections::HashSet<String>,
    /// Keyboard state: keys currently held down
    pub keys_down: std::collections::HashSet<String>,
    /// Per-frame shared-edge dedup (mirrors native).
    pub edge_set: poly::EdgeSet,
    /// Active material override (mirrors native).
    pub material: Option<LingMaterial>,
    /// Toon post-processing configuration (mirrors native).
    pub toon: ToonConfig,
    /// Baked local-space triangle meshes (mirrors native).
    pub meshes: Vec<Vec<([f32; 9], u32)>>,
    /// Active mesh capture buffer (mirrors native).
    pub mesh_capture: Option<Vec<([f32; 9], u32)>>,
    /// Reclaimable mesh slots (mirrors native).
    pub mesh_free: Vec<usize>,
    /// Keyed display-list cache (mirrors native).
    pub mesh_cache: std::collections::HashMap<i64, usize>,
}

#[cfg(target_arch = "wasm32")]
impl GfxState {
    pub fn new() -> Self {
        Self {
            width: 800,
            height: 600,
            color: 0x00FF_FFFF,
            fill_r: 0.0,
            fill_g: 0.0,
            fill_b: 0.0,
            camera: Camera3D::default(),
            lights: Vec::new(),
            ambient: 0.15,
            depth_queue: DepthQueue::default(),
            shade_mode: 2,
            shade: ling_graphics::shading::ShadeParams::default(),
            buffer: vec![0u32; 800 * 600],
            distort_buf: Vec::new(),
            blend: 0,
            alpha: 1.0,
            shadow: ShadowParams::default(),
            linear_blend: false,
            grad_oklab: true,
            depth_test: false,
            depth_buf: Vec::new(),
            zbuf_needs_clear: true,
            fog_color: 0x0000_0000,
            fog_start: 0.0,
            fog_end: 0.0,
            flat_shade: false,
            keys_pressed: std::collections::HashSet::new(),
            keys_down: std::collections::HashSet::new(),
            edge_set: poly::EdgeSet::default(),
            material: None,
            toon: ToonConfig::default(),
            meshes: Vec::new(),
            mesh_capture: None,
            mesh_free: Vec::new(),
            mesh_cache: std::collections::HashMap::new(),
        }
    }

    /// Clear the keys_pressed set at the start of each frame
    pub fn clear_frame_keys(&mut self) {
        self.keys_pressed.clear();
    }

    /// Register a key press (called from JS)
    pub fn on_key_down(&mut self, key: String) {
        if !self.keys_down.contains(&key) {
            self.keys_pressed.insert(key.clone());
        }
        self.keys_down.insert(key);
    }

    /// Register a key release (called from JS)
    pub fn on_key_up(&mut self, key: String) {
        self.keys_down.remove(&key);
    }

    /// Blend a colour toward the fog colour by camera-space `depth`
    /// (identical to the native path).
    #[inline]
    pub fn fog_apply(&self, color: u32, depth: f32) -> u32 {
        if self.fog_end <= 0.0 {
            return color;
        }
        let span = self.fog_end - self.fog_start;
        if span <= 0.0 {
            return color;
        }
        let f = ((depth - self.fog_start) / span).clamp(0.0, 1.0);
        if f <= 0.0 {
            return color;
        }
        let lerp = |a: u32, b: u32| -> u32 { (a as f32 + (b as f32 - a as f32) * f) as u32 & 0xff };
        let r = lerp((color >> 16) & 0xff, (self.fog_color >> 16) & 0xff);
        let g = lerp((color >> 8) & 0xff, (self.fog_color >> 8) & 0xff);
        let b = lerp(color & 0xff, self.fog_color & 0xff);
        (r << 16) | (g << 8) | b
    }

    pub fn sync_projection(&mut self) {
        self.camera.cx = self.width as f32 / 2.0;
        self.camera.cy = self.height as f32 / 2.0;
        self.camera.focal = self.height as f32;
        self.camera.zdist = 5.0;
    }

    /// Run all enabled toon post-process passes (mirrors native).
    pub fn toon_post_process(&mut self) {
        let w = self.width;
        let h = self.height;
        if self.buffer.len() < w * h { return; }
        toon::apply(&self.toon, &mut self.buffer, &self.depth_buf, w, h);
    }
}

// Mesh display lists + the shared world-space triangle pipeline. Field names
// match on both the native and wasm `GfxState`, so one impl serves both targets.
impl GfxState {
    /// Light, near-plane clip, project, and fan-push a world-space triangle to
    /// the depth queue. Shared by `draw_triangle_3d` and `mesh_draw`.
    #[inline]
    pub fn submit_triangle(
        &mut self,
        ax: f32, ay: f32, az: f32,
        bx: f32, by: f32, bz: f32,
        cx: f32, cy: f32, cz: f32,
    ) {
        let ux = bx - ax;
        let uy = by - ay;
        let uz = bz - az;
        let vx = cx - ax;
        let vy = cy - ay;
        let vz = cz - az;
        let normal = [uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx];

        let (c0, c1, c2) = if self.flat_shade {
            (self.color, self.color, self.color)
        } else {
            crate::gfx::light::compute_lit_color_vertices(
                self.color,
                normal,
                [ax, ay, az],
                [bx, by, bz],
                [cx, cy, cz],
                &self.lights,
                self.ambient,
            )
        };

        let near = -self.camera.zdist + 0.05;
        let vw = [
            (ax, ay, az, self.camera.depth(ax, ay, az), c0),
            (bx, by, bz, self.camera.depth(bx, by, bz), c1),
            (cx, cy, cz, self.camera.depth(cx, cy, cz), c2),
        ];
        let mut poly: [(f32, f32, f32, u32); 4] = [(0.0, 0.0, 0.0, 0); 4];
        let mut pn = 0usize;
        let mut ei = 0;
        while ei < 3 {
            let a = vw[ei];
            let b = vw[(ei + 1) % 3];
            let ain = a.3 > near;
            let bin = b.3 > near;
            if ain && pn < 4 {
                poly[pn] = (a.0, a.1, a.2, a.4);
                pn += 1;
            }
            if ain != bin && pn < 4 {
                let tt = (near - a.3) / (b.3 - a.3);
                poly[pn] = (
                    a.0 + (b.0 - a.0) * tt,
                    a.1 + (b.1 - a.1) * tt,
                    a.2 + (b.2 - a.2) * tt,
                    crate::gfx::light::lerp_color(a.4, b.4, tt),
                );
                pn += 1;
            }
            ei += 1;
        }
        if pn < 3 {
            return;
        }
        let mut proj: [(f32, f32, f32, u32); 4] = [(0.0, 0.0, 0.0, 0); 4];
        let mut pi = 0;
        while pi < pn {
            let (sx, sy, sz) = self.camera.project(poly[pi].0, poly[pi].1, poly[pi].2);
            let fc = self.fog_apply(poly[pi].3, sz);
            proj[pi] = (sx, sy, sz, fc);
            pi += 1;
        }
        let mut fk = 1;
        while fk + 1 < pn {
            self.depth_queue.push_triangle_g_zv(
                proj[0].0, proj[0].1, proj[0].2, proj[0].3,
                proj[fk].0, proj[fk].1, proj[fk].2, proj[fk].3,
                proj[fk + 1].0, proj[fk + 1].1, proj[fk + 1].2, proj[fk + 1].3,
                3,
            );
            fk += 1;
        }
    }

    /// Bake captured local geometry (per-triangle coords + pen colour) into a
    /// mesh, returning its handle.
    pub fn mesh_register(&mut self, tris: Vec<([f32; 9], u32)>) -> usize {
        if let Some(id) = self.mesh_free.pop() {
            self.meshes[id] = tris;
            id
        } else {
            let id = self.meshes.len();
            self.meshes.push(tris);
            id
        }
    }

    /// Draw a baked mesh transformed by origin `o`, right `r`, up `u`, scale `s`.
    /// Forward axis is `r × u` so 3-D meshes baked at identity reconstruct exactly.
    /// `use_baked_color` replays each triangle's captured colour (multi-colour
    /// models); otherwise the current pen colour applies (e.g. tinted glyphs).
    pub fn mesh_draw(
        &mut self,
        id: usize,
        ox: f32, oy: f32, oz: f32,
        rx: f32, ry: f32, rz: f32,
        ux: f32, uy: f32, uz: f32,
        s: f32,
        use_baked_color: bool,
    ) {
        if id >= self.meshes.len() {
            return;
        }
        let fx = ry * uz - rz * uy;
        let fy = rz * ux - rx * uz;
        let fz = rx * uy - ry * ux;
        let pen = self.color;
        let mesh = std::mem::take(&mut self.meshes[id]);
        for (t, col) in &mesh {
            if use_baked_color {
                self.color = *col;
            }
            let wx0 = ox + s * (t[0] * rx + t[1] * ux + t[2] * fx);
            let wy0 = oy + s * (t[0] * ry + t[1] * uy + t[2] * fy);
            let wz0 = oz + s * (t[0] * rz + t[1] * uz + t[2] * fz);
            let wx1 = ox + s * (t[3] * rx + t[4] * ux + t[5] * fx);
            let wy1 = oy + s * (t[3] * ry + t[4] * uy + t[5] * fy);
            let wz1 = oz + s * (t[3] * rz + t[4] * uz + t[5] * fz);
            let wx2 = ox + s * (t[6] * rx + t[7] * ux + t[8] * fx);
            let wy2 = oy + s * (t[6] * ry + t[7] * uy + t[8] * fy);
            let wz2 = oz + s * (t[6] * rz + t[7] * uz + t[8] * fz);
            self.submit_triangle(wx0, wy0, wz0, wx1, wy1, wz1, wx2, wy2, wz2);
        }
        self.color = pen;
        self.meshes[id] = mesh;
    }
}