Skip to main content

ling/runtime/
mod.rs

1// src/runtime/mod.rs — tree-walking interpreter with graphics support
2#[cfg(not(target_arch = "wasm32"))]
3mod net;
4#[cfg(not(target_arch = "wasm32"))]
5mod ai;
6use std::cell::RefCell;
7use std::collections::HashMap;
8use crate::parser::ast::*;
9use crate::gfx::{GfxState, Light};
10#[cfg(not(target_arch = "wasm32"))]
11use crate::gfx::raster::{fill_triangle, draw_line};
12#[cfg(not(target_arch = "wasm32"))]
13use ling_audio::{AudioEngine, ToneParams, Wave};
14
15#[cfg(not(target_arch = "wasm32"))]
16use ling_audio::FftAnalyzer;
17
18#[cfg(not(target_arch = "wasm32"))]
19use ling_mic;
20
21// ─── Values ──────────────────────────────────────────────────────────────────
22
23#[derive(Debug, Clone)]
24pub enum Value {
25    Str(String),
26    Number(f64),
27    Bool(bool),
28    Unit,
29    List(Vec<Value>),
30    Ok(Box<Value>),
31    Err(Box<Value>),
32    Fn(Vec<String>, Vec<Stmt>, Env),
33    /// `form` record instance — ordered named fields.
34    Struct { name: String, fields: Vec<(String, Value)> },
35    /// `choose` enum instance — variant tag plus ordered payload.
36    Variant { enum_name: String, variant: String, payload: Vec<Value> },
37}
38
39type Env = HashMap<String, Value>;
40
41impl std::fmt::Display for Value {
42    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
43        match self {
44            Value::Str(s)    => write!(f, "{s}"),
45            Value::Number(n) => {
46                if n.fract() == 0.0 && n.abs() < 1e15 { write!(f, "{}", *n as i64) }
47                else { write!(f, "{n}") }
48            }
49            Value::Bool(b)   => write!(f, "{b}"),
50            Value::Unit      => write!(f, "()"),
51            Value::List(v)   => {
52                write!(f, "[")?;
53                for (i, x) in v.iter().enumerate() {
54                    if i > 0 { write!(f, ", ")?; }
55                    write!(f, "{x}")?;
56                }
57                write!(f, "]")
58            }
59            Value::Ok(v)     => write!(f, "Ok({v})"),
60            Value::Err(v)    => write!(f, "Err({v})"),
61            Value::Fn(_, _, _) => write!(f, "<fn>"),
62            Value::Struct { name, fields } => {
63                write!(f, "{name} {{ ")?;
64                for (i, (k, v)) in fields.iter().enumerate() {
65                    if i > 0 { write!(f, ", ")?; }
66                    write!(f, "{k}: {v}")?;
67                }
68                write!(f, " }}")
69            }
70            Value::Variant { variant, payload, .. } => {
71                write!(f, "{variant}")?;
72                if !payload.is_empty() {
73                    write!(f, "(")?;
74                    for (i, v) in payload.iter().enumerate() {
75                        if i > 0 { write!(f, ", ")?; }
76                        write!(f, "{v}")?;
77                    }
78                    write!(f, ")")?;
79                }
80                Ok(())
81            }
82        }
83    }
84}
85
86// ─── Control flow ────────────────────────────────────────────────────────────
87
88#[derive(Debug)]
89enum EvalErr {
90    Runtime(String),
91    Return(Value),
92    #[allow(dead_code)] // reserved for future `break` statement support
93    Break,
94}
95
96impl From<String> for EvalErr {
97    fn from(s: String) -> Self { EvalErr::Runtime(s) }
98}
99
100type EvalResult = Result<Value, EvalErr>;
101
102// GfxState is now defined in crate::gfx — see src/gfx/mod.rs.
103
104// ─── SVG writer ───────────────────────────────────────────────────────────────
105
106struct SvgWriter {
107    path:     String,
108    width:    f64,
109    height:   f64,
110    elements: Vec<String>,
111}
112
113impl SvgWriter {
114    fn new(path: String, width: f64, height: f64) -> Self {
115        let bg = format!(
116            "<rect width=\"{width}\" height=\"{height}\" fill=\"#0a0a0a\"/>"
117        );
118        Self { path, width, height, elements: vec![bg] }
119    }
120
121    fn save(&self) -> std::io::Result<()> {
122        let w = self.width;
123        let h = self.height;
124        let mut out = format!(
125            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\
126             <svg xmlns=\"http://www.w3.org/2000/svg\" \
127             width=\"{w}\" height=\"{h}\" viewBox=\"0 0 {w} {h}\">\n"
128        );
129        for elem in &self.elements {
130            out.push_str("  ");
131            out.push_str(elem);
132            out.push('\n');
133        }
134        out.push_str("</svg>\n");
135        // Create parent directory if it doesn't exist.
136        if let Some(parent) = std::path::Path::new(&self.path).parent() {
137            if !parent.as_os_str().is_empty() {
138                let _ = std::fs::create_dir_all(parent);
139            }
140        }
141        std::fs::write(&self.path, out.as_bytes())
142    }
143}
144
145fn hsl_to_hex(h: f64, s: f64, l: f64) -> String {
146    let s = s / 100.0;
147    let l = l / 100.0;
148    let c = (1.0 - (2.0 * l - 1.0).abs()) * s;
149    let x = c * (1.0 - ((h / 60.0) % 2.0 - 1.0).abs());
150    let m = l - c / 2.0;
151    let (r1, g1, b1) = if h < 60.0       { (c, x, 0.0) }
152                       else if h < 120.0  { (x, c, 0.0) }
153                       else if h < 180.0  { (0.0, c, x) }
154                       else if h < 240.0  { (0.0, x, c) }
155                       else if h < 300.0  { (x, 0.0, c) }
156                       else               { (c, 0.0, x) };
157    let r = ((r1 + m) * 255.0).round() as u8;
158    let g = ((g1 + m) * 255.0).round() as u8;
159    let b = ((b1 + m) * 255.0).round() as u8;
160    format!("#{r:02x}{g:02x}{b:02x}")
161}
162
163// ─── Procedural texture helpers ───────────────────────────────────────────────
164
165fn tex_hash(x: i32, y: i32, seed: u32) -> f32 {
166    let mut h = (x as u32).wrapping_add((y as u32).wrapping_mul(2654435769)).wrapping_add(seed.wrapping_mul(1234567891));
167    h ^= h >> 16; h = h.wrapping_mul(0x45d9f3b); h ^= h >> 16;
168    h as f32 / u32::MAX as f32
169}
170
171fn tex_vnoise(x: f32, y: f32, seed: u32) -> f32 {
172    let xi = x.floor() as i32; let yi = y.floor() as i32;
173    let sm = |t: f32| t * t * (3.0 - 2.0 * t);
174    let xf = sm(x - xi as f32); let yf = sm(y - yi as f32);
175    let a = tex_hash(xi, yi, seed); let b = tex_hash(xi+1, yi, seed);
176    let c = tex_hash(xi, yi+1, seed); let d = tex_hash(xi+1, yi+1, seed);
177    a + (b-a)*xf + (c-a)*yf + (a-b-c+d)*xf*yf
178}
179
180fn tex_fbm(x: f32, y: f32, octaves: u32, seed: u32) -> f32 {
181    let mut v = 0.0f32; let mut amp = 0.5f32; let mut f = 1.0f32;
182    for i in 0..octaves {
183        v += tex_vnoise(x * f, y * f, seed.wrapping_add(i * 7919)) * amp;
184        amp *= 0.5; f *= 2.0;
185    }
186    v
187}
188
189fn tex_palette(name: &str, t: f32) -> [f32; 3] {
190    let (a, b, c, d): ([f32;3],[f32;3],[f32;3],[f32;3]) = match name {
191        "fire"        => ([0.8,0.4,0.1],[0.7,0.3,0.1],[1.0,0.5,0.3],[0.0,0.5,0.8]),
192        "ocean"       => ([0.1,0.4,0.7],[0.3,0.3,0.4],[0.8,1.0,0.5],[0.3,0.0,0.6]),
193        "psychedelic" => ([0.5,0.5,0.5],[0.8,0.8,0.8],[1.0,1.3,0.7],[0.0,0.15,0.3]),
194        "neon"        => ([0.5,0.5,0.5],[0.5,0.5,0.5],[2.0,1.0,0.0],[0.5,0.2,0.25]),
195        "forest"      => ([0.3,0.5,0.2],[0.2,0.3,0.1],[1.0,0.5,0.8],[0.1,0.3,0.6]),
196        _             => ([0.5,0.5,0.5],[0.5,0.5,0.5],[1.0,1.0,1.0],[0.0,0.333,0.667]),
197    };
198    [0,1,2].map(|i| (a[i] + b[i] * (std::f32::consts::TAU * (c[i] * t + d[i])).cos()).clamp(0.0, 1.0))
199}
200
201/// Map a physical key to a typed character for ling-ui text input (lowercase).
202#[cfg(not(target_arch = "wasm32"))]
203fn key_char(k: minifb::Key) -> Option<char> {
204    use minifb::Key::*;
205    Some(match k {
206        A=>'a',B=>'b',C=>'c',D=>'d',E=>'e',F=>'f',G=>'g',H=>'h',I=>'i',J=>'j',K=>'k',L=>'l',M=>'m',
207        N=>'n',O=>'o',P=>'p',Q=>'q',R=>'r',S=>'s',T=>'t',U=>'u',V=>'v',W=>'w',X=>'x',Y=>'y',Z=>'z',
208        Key0=>'0',Key1=>'1',Key2=>'2',Key3=>'3',Key4=>'4',Key5=>'5',Key6=>'6',Key7=>'7',Key8=>'8',Key9=>'9',
209        Space=>' ', Minus=>'-', Period=>'.',
210        _ => return None,
211    })
212}
213
214/// Lowercase-hex encode bytes (the wire format for crypto values in Ling).
215fn hex_encode(bytes: &[u8]) -> String {
216    let mut s = String::with_capacity(bytes.len() * 2);
217    for b in bytes { s.push_str(&format!("{b:02x}")); }
218    s
219}
220
221/// Decode a `ling convert` blob: base64 → zlib-inflate → raw little-endian bytes.
222#[cfg(not(target_arch = "wasm32"))]
223fn decode_blob(s: &str) -> Result<Vec<u8>, String> {
224    use base64::Engine as _;
225    use std::io::Read as _;
226    let comp = base64::engine::general_purpose::STANDARD
227        .decode(s.trim())
228        .map_err(|e| format!("base64: {e}"))?;
229    let mut out = Vec::new();
230    flate2::read::ZlibDecoder::new(&comp[..])
231        .read_to_end(&mut out)
232        .map_err(|e| format!("inflate: {e}"))?;
233    Ok(out)
234}
235
236/// Decode a lowercase/uppercase hex string to bytes (ignores malformed tail).
237fn hex_decode(s: &str) -> Vec<u8> {
238    let s = s.trim();
239    (0..s.len() / 2)
240        .filter_map(|i| u8::from_str_radix(s.get(i * 2..i * 2 + 2)?, 16).ok())
241        .collect()
242}
243
244/// Decode a hex string into a fixed 32-byte key (zero-padded / truncated).
245fn hex_to_32(s: &str) -> [u8; 32] {
246    let v = hex_decode(s);
247    let mut out = [0u8; 32];
248    let n = v.len().min(32);
249    out[..n].copy_from_slice(&v[..n]);
250    out
251}
252
253fn tex_rgb(r: f32, g: f32, b: f32) -> u32 {
254    ((r * 255.0) as u32) << 16 | ((g * 255.0) as u32) << 8 | (b * 255.0) as u32
255}
256
257// ─── 3D Perlin Noise (Improved Perlin 2002) ───────────────────────────────────
258
259const PERM: [u8; 512] = [
260    151,160,137,91,90,15,131,13,201,95,96,53,194,233,7,225,
261    140,36,103,30,69,142,8,99,37,240,21,10,23,190,6,148,
262    247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,
263    57,177,33,88,237,149,56,87,174,35,63,189,114,56,42,123,
264    165,38,72,93,69,139,138,78,149,159,56,89,152,78,61,140,
265    63,26,142,76,124,132,72,11,90,44,82,59,96,41,148,126,
266    157,13,49,27,176,33,47,14,97,78,71,40,87,183,4,122,
267    92,7,72,3,246,17,225,87,91,106,203,190,57,74,76,88,
268    207,208,239,170,251,67,77,51,133,69,249,2,127,80,60,159,
269    168,81,163,64,143,146,157,56,245,188,182,218,33,16,255,243,
270    210,205,12,19,236,95,151,68,23,196,167,126,61,100,93,25,
271    115,96,129,79,220,34,42,144,136,70,238,184,20,222,94,11,
272    219,224,50,58,10,73,6,36,92,194,211,172,98,145,149,228,
273    121,231,200,55,109,141,213,78,169,108,86,244,234,101,122,174,
274    8,186,120,37,46,28,166,180,198,232,221,116,31,75,189,139,
275    138,112,62,181,102,72,3,246,14,97,53,87,185,134,193,29,
276    158,225,248,152,17,105,217,142,148,155,30,135,233,206,85,40,
277    223,140,161,137,13,191,230,66,104,153,199,167,147,99,179,92,
278    // Duplicate for wrap-around indexing
279    151,160,137,91,90,15,131,13,201,95,96,53,194,233,7,225,
280    140,36,103,30,69,142,8,99,37,240,21,10,23,190,6,148,
281    247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,
282    57,177,33,88,237,149,56,87,174,35,63,189,114,56,42,123,
283    165,38,72,93,69,139,138,78,149,159,56,89,152,78,61,140,
284    63,26,142,76,124,132,72,11,90,44,82,59,96,41,148,126,
285    157,13,49,27,176,33,47,14,97,78,71,40,87,183,4,122,
286    92,7,72,3,246,17,225,87,91,106,203,190,57,74,76,88,
287    207,208,239,170,251,67,77,51,133,69,249,2,127,80,60,159,
288    168,81,163,64,143,146,157,56,245,188,182,218,33,16,255,243,
289    210,205,12,19,236,95,151,68,23,196,167,126,61,100,93,25,
290    115,96,129,79,220,34,42,144,136,70,238,184,20,222,94,11,
291    219,224,50,58,10,73,6,36,92,194,211,172,98,145,149,228,
292    121,231,200,55,109,141,213,78,169,108,86,244,234,101,122,174,
293];
294
295fn fade(t: f32) -> f32 {
296    t * t * t * (t * (t * 6.0 - 15.0) + 10.0)
297}
298
299fn grad(hash: u8, x: f32, y: f32, z: f32) -> f32 {
300    let h = hash & 15;
301    let u = if h < 8 { x } else { y };
302    let v = if h < 8 { y } else { z };
303    (if (h & 1) == 0 { u } else { -u }) + (if (h & 2) == 0 { v } else { -v })
304}
305
306fn perlin3(x: f32, y: f32, z: f32) -> f32 {
307    let xi = (x.floor() as i32) & 255;
308    let yi = (y.floor() as i32) & 255;
309    let zi = (z.floor() as i32) & 255;
310
311    let xf = x - x.floor();
312    let yf = y - y.floor();
313    let zf = z - z.floor();
314
315    let u = fade(xf);
316    let v = fade(yf);
317    let w = fade(zf);
318
319    let p0 = PERM[xi as usize] as usize;
320    let p1 = PERM[((xi + 1) & 255) as usize] as usize;
321    let pa = PERM[(p0 + yi as usize) & 255] as usize;
322    let pb = PERM[(p0 + ((yi + 1) & 255) as usize) & 255] as usize;
323    let pc = PERM[(p1 + yi as usize) & 255] as usize;
324    let pd = PERM[(p1 + ((yi + 1) & 255) as usize) & 255] as usize;
325
326    let g000 = grad(PERM[(pa + zi as usize) & 255], xf, yf, zf);
327    let g001 = grad(PERM[(pa + ((zi + 1) & 255) as usize) & 255], xf, yf, zf - 1.0);
328    let g010 = grad(PERM[(pb + zi as usize) & 255], xf, yf - 1.0, zf);
329    let g011 = grad(PERM[(pb + ((zi + 1) & 255) as usize) & 255], xf, yf - 1.0, zf - 1.0);
330    let g100 = grad(PERM[(pc + zi as usize) & 255], xf - 1.0, yf, zf);
331    let g101 = grad(PERM[(pc + ((zi + 1) & 255) as usize) & 255], xf - 1.0, yf, zf - 1.0);
332    let g110 = grad(PERM[(pd + zi as usize) & 255], xf - 1.0, yf - 1.0, zf);
333    let g111 = grad(PERM[(pd + ((zi + 1) & 255) as usize) & 255], xf - 1.0, yf - 1.0, zf - 1.0);
334
335    let l00 = g000 + u * (g100 - g000);
336    let l01 = g001 + u * (g101 - g001);
337    let l10 = g010 + u * (g110 - g010);
338    let l11 = g011 + u * (g111 - g011);
339
340    let l0 = l00 + v * (l10 - l00);
341    let l1 = l01 + v * (l11 - l01);
342
343    l0 + w * (l1 - l0)
344}
345
346fn fast_rand_f64(state: &mut u64) -> f64 {
347    *state = state.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
348    ((*state >> 32) as u32) as f64 / 4294967296.0
349}
350
351// ─── Circle Drawing Primitives ────────────────────────────────────────────────
352
353/// Write one pixel into the framebuffer (normal or additive blend).
354#[inline]
355fn put_px(buf: &mut [u32], idx: usize, color: u32, blend: u8) {
356    if idx >= buf.len() { return; }
357    if blend == 0 {
358        buf[idx] = color;
359    } else {
360        let old = buf[idx];
361        let r = (((old >> 16) & 255) + ((color >> 16) & 255)).min(255);
362        let g = (((old >> 8) & 255) + ((color >> 8) & 255)).min(255);
363        let b = ((old & 255) + (color & 255)).min(255);
364        buf[idx] = (r << 16) | (g << 8) | b;
365    }
366}
367
368fn draw_circle_outline(buf: &mut [u32], w: i32, h: i32, cx: i32, cy: i32, r: i32, color: u32, blend: u8) {
369    let r = r.clamp(0, 20000); // guard against overflow / runaway from tiny depths
370    if r == 0 { return; }
371    let mut x = 0;
372    let mut y = r;
373    let mut d = 3 - 2 * r;
374    while x <= y {
375        plot_circle_points(buf, w, h, cx, cy, x, y, color, blend);
376        if d < 0 {
377            d += 4 * x + 6;
378        } else {
379            d += 4 * (x - y) + 10;
380            y -= 1;
381        }
382        x += 1;
383    }
384}
385
386fn plot_circle_points(buf: &mut [u32], w: i32, h: i32, cx: i32, cy: i32, x: i32, y: i32, color: u32, blend: u8) {
387    let points = [(cx+x, cy+y), (cx-x, cy+y), (cx+x, cy-y), (cx-x, cy-y),
388                  (cx+y, cy+x), (cx-y, cy+x), (cx+y, cy-x), (cx-y, cy-x)];
389    for &(px, py) in &points {
390        if px >= 0 && px < w && py >= 0 && py < h {
391            put_px(buf, (py * w + px) as usize, color, blend);
392        }
393    }
394}
395
396fn draw_circle_filled(buf: &mut [u32], w: i32, h: i32, cx: i32, cy: i32, r: i32, color: u32, blend: u8) {
397    if r <= 0 { return; }
398    for dy in -r..=r {
399        let dx_max = ((r*r - dy*dy) as f64).sqrt() as i32;
400        let py = cy + dy;
401        if py < 0 || py >= h { continue; }
402        for dx in -dx_max..=dx_max {
403            let px = cx + dx;
404            if px >= 0 && px < w {
405                put_px(buf, (py * w + px) as usize, color, blend);
406            }
407        }
408    }
409}
410
411#[cfg(test)]
412mod draw_tests {
413    use super::*;
414
415    #[test]
416    fn filled_circle_actually_writes_pixels() {
417        let mut buf = vec![0u32; 100 * 100];
418        draw_circle_filled(&mut buf, 100, 100, 50, 50, 10, 0xFF00FF, 0);
419        assert_eq!(buf[50 * 100 + 50], 0xFF00FF, "centre pixel must be filled");
420        assert_eq!(buf[0], 0, "far corner must stay clear");
421        let n = buf.iter().filter(|&&p| p != 0).count();
422        assert!(n > 200 && n < 500, "r=10 disc area ≈ 314, got {n}");
423    }
424
425    #[test]
426    fn circle_outline_writes_a_ring() {
427        let mut buf = vec![0u32; 100 * 100];
428        draw_circle_outline(&mut buf, 100, 100, 50, 50, 20, 0x00FF00, 0);
429        assert_eq!(buf[50 * 100 + 50], 0, "outline must NOT fill the centre");
430        assert!(buf.iter().any(|&p| p == 0x00FF00), "outline must draw a ring");
431    }
432
433    #[test]
434    fn additive_blend_accumulates_channels() {
435        let mut buf = vec![0x202020u32; 1];
436        put_px(&mut buf, 0, 0x404040, 1);
437        assert_eq!(buf[0], 0x606060);
438    }
439}
440
441// ─── Interpreter ─────────────────────────────────────────────────────────────
442
443/// Customizable colour palette for the vector UI toolkit (packed 0x00RRGGBB).
444/// `ui_theme(...)` sets it; every widget falls back to these and accepts a
445/// trailing `r,g,b` override.
446#[derive(Clone, Copy)]
447pub struct UiTheme {
448    pub primary: u32,
449    pub accent:  u32,
450    pub track:   u32,
451    pub warn:    u32,
452    pub text:    u32,
453    pub bg:      u32,
454}
455
456impl Default for UiTheme {
457    fn default() -> Self {
458        Self {
459            primary: 0x00D2FF, // holographic cyan
460            accent:  0x28FFB4, // mint
461            track:   0x2C3E64, // dim slate
462            warn:    0xFF5A5A, // alert red
463            text:    0xBEEBFF, // pale cyan
464            bg:      0x0A1018, // near-black panel
465        }
466    }
467}
468
469pub struct Interpreter {
470    globals:   HashMap<String, Expr>,
471    /// Globals evaluated ONCE at program start (immutable after load).
472    /// call_named clones this instead of re-evaluating every global per call.
473    global_seed: Env,
474    functions: HashMap<String, FnDef>,
475    /// `form` definitions: struct name → ordered field names.
476    structs:   HashMap<String, Vec<String>>,
477    /// `choose` variants: variant name (bare and `Enum::Variant`) → (enum name, arity).
478    enum_variants: HashMap<String, (String, usize)>,
479    _modules:  HashMap<String, Vec<FnDef>>,
480    gfx:       RefCell<GfxState>,
481    svg:       RefCell<Option<SvgWriter>>,
482    /// Directory of the primary source file, for relative `use` resolution.
483    pub source_dir: Option<std::path::PathBuf>,
484    /// Files already loaded — prevents circular imports.
485    loaded_files: std::collections::HashSet<String>,
486    /// Optional audio engine — `None` if no audio device is available.
487    #[cfg(not(target_arch = "wasm32"))]
488    audio:     Option<AudioEngine>,
489    #[cfg(not(target_arch = "wasm32"))]
490    fft:       RefCell<FftAnalyzer>,
491    fft_bands_cache: RefCell<Vec<f32>>,
492    /// Real-time clock — initialized at startup
493    start_time: std::time::Instant,
494    /// Frame counter — incremented at each present()
495    frame_num: u64,
496    /// Random state for rand() builtin (xorshift)
497    rand_state: u64,
498    /// Microphone input (Phase 1 audio reactivity)
499    #[cfg(not(target_arch = "wasm32"))]
500    mic: Option<ling_mic::MicInput>,
501    /// Persistent KEM keypairs (knot / hybrid identities), referenced by handle.
502    #[cfg(not(target_arch = "wasm32"))]
503    crypto_ids: Vec<ling_crypto::KnotIdentity>,
504    /// Editable text-input buffer (ling-ui text fields).
505    text_buffer: String,
506    /// Frame counter for record_frame().
507    record_n: u32,
508    /// Accumulated microphone samples (for turning sound into crypto donuts).
509    #[cfg(not(target_arch = "wasm32"))]
510    mic_buffer: Vec<f32>,
511    /// Loaded vector UI fonts, referenced by handle (index) from `font_load`.
512    #[cfg(not(target_arch = "wasm32"))]
513    fonts: Vec<ling_graphics::VectorFont>,
514    /// Customizable UI colour palette (set via `ui_theme`).
515    ui_theme: UiTheme,
516    /// Left-mouse state on the previous frame — for widget click-edge detection.
517    mouse_was_down: bool,
518    /// Live music engine (decode playback + GM synth) — lazily initialised.
519    #[cfg(not(target_arch = "wasm32"))]
520    music: Option<ling_music::MusicEngine>,
521    #[cfg(not(target_arch = "wasm32"))]
522    music_init: bool,
523    /// Decoded tracks (for analysis + playback), by `music_load` handle.
524    #[cfg(not(target_arch = "wasm32"))]
525    tracks: Vec<ling_music::DecodedAudio>,
526    /// Parsed `.lrc` lyrics, by `music_lrc` handle.
527    #[cfg(not(target_arch = "wasm32"))]
528    lyrics: Vec<ling_music::Lyrics>,
529    /// Parsed MIDI songs, by `music_midi_load` handle.
530    #[cfg(not(target_arch = "wasm32"))]
531    midis: Vec<ling_music::MidiSong>,
532    /// Soft bodies (deformable balls), by `soft_ball` handle.
533    soft_bodies: Vec<ling_physics::soft::SoftBody>,
534    /// Rigid-body world (angular dynamics), shared by `rb_*`.
535    rigid_world: ling_physics::rigid::PhysicsWorld,
536    /// Liquid grids (water/oil), by `liquid_new` handle.
537    liquids: Vec<ling_physics::liquid::LiquidGrid>,
538    /// Active cinematic dialog box (Ocarina/Majora-style), if any.
539    dialog: Option<ling_game::dialog::Dialog>,
540    /// Dialog highlight colours by role: text, name, place, item (0x00RRGGBB).
541    dialog_colors: [u32; 4],
542    /// Active user-function call frames (names), for error tracebacks.
543    frames: Vec<String>,
544    /// Snapshot of `frames` captured the moment a runtime error first arose
545    /// (the deepest call). Consumed by `take_error_trace`.
546    error_trace: Option<Vec<String>>,
547}
548
549impl Interpreter {
550    pub fn new() -> Self {
551        #[cfg(not(target_arch = "wasm32"))]
552        let audio = AudioEngine::new()
553            .map_err(|e| eprintln!("audio init failed (no sound): {e}"))
554            .ok();
555        Self {
556            globals:   HashMap::new(),
557            global_seed: HashMap::new(),
558            functions: HashMap::new(),
559            structs:   HashMap::new(),
560            enum_variants: HashMap::new(),
561            _modules:  HashMap::new(),
562            gfx:       RefCell::new(GfxState::new()),
563            svg:       RefCell::new(None),
564            source_dir: None,
565            loaded_files: std::collections::HashSet::new(),
566            #[cfg(not(target_arch = "wasm32"))]
567            audio,
568            #[cfg(not(target_arch = "wasm32"))]
569            fft: RefCell::new(FftAnalyzer::new(2048, 44100)),
570            fft_bands_cache: RefCell::new(vec![]),
571            start_time: std::time::Instant::now(),
572            frame_num: 0,
573            rand_state: 0x123456789ABCDEF,
574            #[cfg(not(target_arch = "wasm32"))]
575            mic: None,
576            #[cfg(not(target_arch = "wasm32"))]
577            crypto_ids: Vec::new(),
578            text_buffer: String::new(),
579            record_n: 0,
580            #[cfg(not(target_arch = "wasm32"))]
581            mic_buffer: Vec::new(),
582            #[cfg(not(target_arch = "wasm32"))]
583            fonts: Vec::new(),
584            ui_theme: UiTheme::default(),
585            mouse_was_down: false,
586            #[cfg(not(target_arch = "wasm32"))]
587            music: None,
588            #[cfg(not(target_arch = "wasm32"))]
589            music_init: false,
590            #[cfg(not(target_arch = "wasm32"))]
591            tracks: Vec::new(),
592            #[cfg(not(target_arch = "wasm32"))]
593            lyrics: Vec::new(),
594            #[cfg(not(target_arch = "wasm32"))]
595            midis: Vec::new(),
596            soft_bodies: Vec::new(),
597            rigid_world: ling_physics::rigid::PhysicsWorld::new(),
598            liquids: Vec::new(),
599            dialog: None,
600            dialog_colors: [0xE6F2FF, 0xFFD24A, 0x4AD2FF, 0x6CFF8C], // text · name · place · item
601            frames: Vec::new(),
602            error_trace: None,
603        }
604    }
605
606    /// Take the call-stack snapshot captured at the deepest runtime error, if any.
607    /// Frames are ordered outermost-first (entry point first, failing call last).
608    pub fn take_error_trace(&mut self) -> Vec<String> {
609        self.error_trace.take().unwrap_or_default()
610    }
611
612    /// Run `body`, recording `name` as a call frame and snapshotting the stack on
613    /// the first runtime error so a traceback can be reported.
614    fn framed<T, F>(&mut self, name: &str, body: F) -> Result<T, EvalErr>
615    where
616        F: FnOnce(&mut Self) -> Result<T, EvalErr>,
617    {
618        self.frames.push(name.to_string());
619        let result = body(self);
620        if matches!(result, Err(EvalErr::Runtime(_))) && self.error_trace.is_none() {
621            self.error_trace = Some(self.frames.clone());
622        }
623        self.frames.pop();
624        result
625    }
626
627    /// Render the active dialog box: beveled frame + dark fill, then the visible
628    /// (typewriter-revealed) text word-wrapped with colour-coded runs, plus a
629    /// blinking advance arrow once the page is fully typed.
630    #[cfg(not(target_arch = "wasm32"))]
631    fn render_dialog(&mut self, x: f32, y: f32, w: f32, h: f32, font: i64, t: f32) {
632        let (runs, typing) = match &self.dialog {
633            Some(d) if !d.is_closed() => {
634                let runs: Vec<(String, usize, bool)> = d.visible_runs().into_iter()
635                    .map(|r| (r.text, r.role.index(), r.newline_before)).collect();
636                (runs, d.is_typing())
637            }
638            _ => return,
639        };
640        let colors = self.dialog_colors;
641        // ── frame + fill ──
642        let b = 12.0;
643        let corners: Vec<[f32; 2]> = vec![
644            [x+b,y],[x+w-b,y],[x+w,y+b],[x+w,y+h-b],[x+w-b,y+h],[x+b,y+h],[x,y+h-b],[x,y+b],[x+b,y],
645        ];
646        {
647            let mut gfx = self.gfx.borrow_mut();
648            let (bw, bh) = (gfx.width, gfx.height);
649            crate::gfx::raster::fill_contours_aa(&mut gfx.buffer, bw, bh, 0x0A1018, false, std::slice::from_ref(&corners));
650            for seg in corners.windows(2) {
651                crate::gfx::raster::draw_line_aa(&mut gfx.buffer, bw, bh, 0x00D2FF, false, seg[0][0], seg[0][1], seg[1][0], seg[1][1]);
652            }
653        }
654        // ── word-wrapped, colour-coded text ──
655        let px = 22.0f32;
656        let pad = 20.0f32;
657        let line_h = px * 1.45;
658        let mut cx = x + pad;
659        let mut cy = y + pad;
660        let use_font = font >= 0 && (font as usize) < self.fonts.len();
661        for (text, role, nl) in &runs {
662            if *nl { cx = x + pad; cy += line_h; }
663            for word in text.split_inclusive(' ') {
664                let wpx = if use_font { self.fonts[font as usize].measure(word, px) }
665                          else { ling_ui::holo::text_width(word, px * 0.6, px * 0.24) };
666                if cx + wpx > x + w - pad && cx > x + pad + 1.0 { cx = x + pad; cy += line_h; }
667                if cy + line_h > y + h { break; }
668                let col = colors[(*role).min(3)];
669                if use_font {
670                    let glyphs = self.font_layout_2d_glyphs(font as usize, cx, cy, px, word);
671                    let mut gfx = self.gfx.borrow_mut();
672                    let (bw, bh, add) = (gfx.width, gfx.height, gfx.blend == 1);
673                    for contours in &glyphs {
674                        crate::gfx::raster::fill_contours_aa(&mut gfx.buffer, bw, bh, col, add, contours);
675                    }
676                } else {
677                    let segs = ling_ui::holo::text_lines(word, cx, cy, px * 0.6, px, px * 0.24);
678                    let mut gfx = self.gfx.borrow_mut();
679                    let (bw, bh) = (gfx.width, gfx.height);
680                    for s in segs { draw_line(&mut gfx.buffer, bw, bh, col, s[0], s[1], s[2], s[3]); }
681                }
682                cx += wpx;
683            }
684        }
685        // ── blinking advance arrow when fully typed ──
686        if !typing && (t * 3.0).sin() > 0.0 {
687            let ax = x + w - 26.0; let ay = y + h - 22.0;
688            let mut gfx = self.gfx.borrow_mut();
689            let (bw, bh) = (gfx.width, gfx.height);
690            crate::gfx::raster::fill_contours_aa(&mut gfx.buffer, bw, bh, 0x00D2FF, false,
691                std::slice::from_ref(&vec![[ax-7.0,ay],[ax+7.0,ay],[ax,ay+9.0],[ax-7.0,ay]]));
692        }
693    }
694
695    /// Lazily start the music engine on first use (playback/synth need a device;
696    /// analysis/decoding do not). Returns `false` if no audio device is available.
697    #[cfg(not(target_arch = "wasm32"))]
698    fn ensure_music(&mut self) -> bool {
699        if self.music.is_some() { return true; }
700        if self.music_init { return false; }
701        self.music_init = true;
702        match ling_music::MusicEngine::new() {
703            Ok(m) => { self.music = Some(m); true }
704            Err(e) => { eprintln!("music engine init failed (no music playback): {e}"); false }
705        }
706    }
707
708    /// Lay out `text` for font `id` at size `px`, returning every glyph contour as
709    /// a screen-space polyline (x→right, y→down). `(x, y)` is the text box top-left;
710    /// the baseline is placed `ascent*px` below it. Curves are flattened to 0.3 px.
711    #[cfg(not(target_arch = "wasm32"))]
712    fn font_layout_2d(&mut self, id: usize, x: f32, y: f32, px: f32, text: &str) -> Vec<Vec<[f32; 2]>> {
713        let mut out = Vec::new();
714        for g in self.font_layout_2d_glyphs(id, x, y, px, text) { out.extend(g); }
715        out
716    }
717
718    /// Same as [`font_layout_2d`] but grouped per glyph (so a fill can apply the
719    /// non-zero winding rule within each glyph, preserving interior holes).
720    #[cfg(not(target_arch = "wasm32"))]
721    fn font_layout_2d_glyphs(&mut self, id: usize, x: f32, y: f32, px: f32, text: &str) -> Vec<Vec<Vec<[f32; 2]>>> {
722        let font = &mut self.fonts[id];
723        let asc = font.ascent();
724        let tol = 0.3 / px;
725        let mut pen = 0.0f32;
726        let mut glyphs = Vec::new();
727        for ch in text.chars() {
728            let go = font.glyph_outline(ch, tol);
729            let mut contours = Vec::with_capacity(go.polylines.len());
730            for pl in &go.polylines {
731                let mapped: Vec<[f32; 2]> = pl.iter()
732                    .map(|p| [x + (pen + p[0]) * px, y + (asc - p[1]) * px])
733                    .collect();
734                contours.push(mapped);
735            }
736            glyphs.push(contours);
737            pen += go.advance;
738        }
739        glyphs
740    }
741
742    pub fn run_program(&mut self, program: &Program) -> Result<(), String> {
743        for item in &program.items {
744            self.register_item("", item)?;
745        }
746        let entry = self.find_entry()
747            .ok_or("no entry point — need `bind start = do {...}` or `ผูก เริ่ม = ทำ {...}`")?;
748        // Seed the entry env with non-Do globals so top-level `令` bindings
749        // are visible in the main Do block (same two-pass logic as call_named).
750        let mut env = Env::new();
751        let non_do: Vec<_> = self.globals.iter()
752            .filter(|(_, e)| !matches!(e, Expr::Do(_)))
753            .map(|(k, e)| (k.clone(), e.clone()))
754            .collect();
755        let mut pending: Vec<(String, Expr)> = Vec::new();
756        for (k, expr) in &non_do {
757            let mut tmp = Env::new();
758            if let Ok(v) = self.eval_expr(expr, &mut tmp) {
759                env.insert(k.clone(), v);
760            } else {
761                pending.push((k.clone(), expr.clone()));
762            }
763        }
764        for (k, expr) in &pending {
765            let mut tmp = env.clone();
766            if let Ok(v) = self.eval_expr(expr, &mut tmp) {
767                env.insert(k.clone(), v);
768            }
769        }
770        // Cache the evaluated globals so every user-function call can clone this
771        // seed instead of re-evaluating all globals (see call_named).
772        self.global_seed = env.clone();
773        self.framed("start", |me| me.eval_expr(&entry, &mut env)).map(|_| ()).map_err(|e| match e {
774            EvalErr::Runtime(s) => s,
775            EvalErr::Return(_)  => "unexpected top-level return".to_string(),
776            EvalErr::Break      => "unexpected break at top level".to_string(),
777        })
778    }
779
780    fn register_item(&mut self, ns: &str, item: &Item) -> Result<(), String> {
781        match item {
782            Item::Bind(name, expr) => {
783                let key = if ns.is_empty() { name.clone() } else { format!("{ns}::{name}") };
784                self.globals.insert(key, expr.clone());
785            }
786            Item::Fn(def) => {
787                let key = if ns.is_empty() { def.name.clone() } else { format!("{ns}::{}", def.name) };
788                self.functions.insert(key, def.clone());
789            }
790            Item::Mod(name, body) => {
791                let child_ns = if ns.is_empty() { name.clone() } else { format!("{ns}::{name}") };
792                for child in body {
793                    self.register_item(&child_ns, child)?;
794                }
795            }
796            Item::TypeAlias(_, _) => {}
797            Item::Struct(name, fields) => {
798                self.structs.insert(name.clone(), fields.clone());
799                if !ns.is_empty() { self.structs.insert(format!("{ns}::{name}"), fields.clone()); }
800            }
801            Item::Enum(name, variants) => {
802                for v in variants {
803                    self.enum_variants.insert(v.name.clone(), (name.clone(), v.arity));
804                    self.enum_variants.insert(format!("{name}::{}", v.name), (name.clone(), v.arity));
805                    if !ns.is_empty() {
806                        self.enum_variants.insert(format!("{ns}::{name}::{}", v.name), (name.clone(), v.arity));
807                    }
808                }
809            }
810            Item::Use { path, alias } => {
811                self.load_module(path, alias.as_deref(), ns)?;
812            }
813        }
814        Ok(())
815    }
816
817    /// Resolve `path` relative to `source_dir`, load and parse it, then
818    /// register all its definitions.  If `alias` is given, every name is
819    /// prefixed with `<parent_ns>::<alias>`.  Circular imports are silently
820    /// skipped.
821    fn load_module(&mut self, path: &str, alias: Option<&str>, parent_ns: &str) -> Result<(), String> {
822        // Build candidate file paths (.ling extension variants)
823        let base_dir = self.source_dir.clone().unwrap_or_else(|| std::path::PathBuf::from("."));
824        let raw = std::path::Path::new(path);
825        let candidates: Vec<std::path::PathBuf> = vec![
826            base_dir.join(format!("{}.ling", path)),
827            base_dir.join(format!("{}.灵", path)),
828            base_dir.join(format!("{}.령", path)),
829            base_dir.join(format!("{}.霊", path)),
830            base_dir.join(format!("{}.ลิง", path)),
831            // exact path if already has extension
832            base_dir.join(raw),
833            std::path::PathBuf::from(format!("{}.ling", path)),
834            std::path::PathBuf::from(path),
835        ];
836
837        let resolved = candidates.into_iter().find(|p| p.exists())
838            .ok_or_else(|| format!("use: cannot find module '{path}'"))?;
839
840        let canonical = resolved.canonicalize()
841            .unwrap_or_else(|_| resolved.clone())
842            .to_string_lossy()
843            .to_string();
844
845        // Skip if already loaded (circular import guard)
846        if self.loaded_files.contains(&canonical) {
847            return Ok(());
848        }
849        self.loaded_files.insert(canonical.clone());
850
851        let source = std::fs::read_to_string(&resolved)
852            .map_err(|e| format!("use: failed to read '{path}': {e}"))?;
853
854        // Save/restore source_dir for nested relative imports
855        let prev_dir = self.source_dir.clone();
856        self.source_dir = resolved.parent().map(|p| p.to_path_buf());
857
858        let program = crate::parser::parse(&source)
859            .map_err(|e| format!("use: parse error in '{path}': {e}"))?;
860
861        // Compute target namespace: parent_ns :: alias (or just alias, or just parent_ns)
862        let target_ns = match (parent_ns.is_empty(), alias) {
863            (_, Some(a)) if !parent_ns.is_empty() => format!("{parent_ns}::{a}"),
864            (_, Some(a)) => a.to_string(),
865            (false, None) => parent_ns.to_string(),
866            (true,  None) => String::new(),
867        };
868
869        for item in &program.items {
870            self.register_item(&target_ns, item)?;
871        }
872
873        self.source_dir = prev_dir;
874        Ok(())
875    }
876
877    fn find_entry(&self) -> Option<Expr> {
878        // Try all known entry-point names in multiple human languages
879        for key in &[
880            "start", "main",
881            "启",
882            "เริ่ม",           // Thai
883            "시작",
884            "начать", "начало",
885            "inicio", "comenzar",
886            "début", "commencer",
887            "anfang", "starten",
888            "início",
889            "शुरू",
890            "ابدأ",
891        ] {
892            if let Some(e) = self.globals.get(*key) { return Some(e.clone()); }
893        }
894        self.globals.values().find(|e| matches!(e, Expr::Do(_))).cloned()
895    }
896
897    // ─── Expression evaluation ────────────────────────────────────────────────
898
899    fn eval_expr(&mut self, expr: &Expr, env: &mut Env) -> EvalResult {
900        match expr {
901            Expr::Str(s)    => Ok(Value::Str(s.clone())),
902            Expr::Number(n) => Ok(Value::Number(*n)),
903            Expr::Bool(b)   => Ok(Value::Bool(*b)),
904            Expr::Unit      => Ok(Value::Unit),
905            Expr::Array(elems) => {
906                let vs: Vec<_> = elems.iter()
907                    .map(|e| self.eval_expr(e, env))
908                    .collect::<Result<_,_>>()?;
909                Ok(Value::List(vs))
910            }
911
912            Expr::Ident(name) => self.lookup(name, env),
913
914            Expr::Path(segs) => {
915                if segs.len() == 1 { return self.lookup(&segs[0], env); }
916                Ok(Value::Str(segs.join("::")))
917            }
918
919            Expr::Ref(inner) => self.eval_expr(inner, env),
920            Expr::Await(inner) => self.eval_expr(inner, env),
921
922            Expr::Do(stmts) => {
923                let mut local = env.clone();
924                Ok(self.exec_block(stmts, &mut local)?.unwrap_or(Value::Unit))
925            }
926
927            Expr::BinOp(op, lhs, rhs) => {
928                let l = self.eval_expr(lhs, env)?;
929                let r = self.eval_expr(rhs, env)?;
930                self.apply_binop(op, l, r)
931            }
932
933            Expr::If { cond, then, elseifs, else_body } => {
934                let cond_val = self.eval_expr(cond, env)?;
935                if self.is_truthy(&cond_val) {
936                    return Ok(self.exec_block(then, env)?.unwrap_or(Value::Unit));
937                }
938                for (ei_cond, ei_body) in elseifs {
939                    let ei_cond_val = self.eval_expr(ei_cond, env)?;
940                    if self.is_truthy(&ei_cond_val) {
941                        return Ok(self.exec_block(ei_body, env)?.unwrap_or(Value::Unit));
942                    }
943                }
944                if let Some(eb) = else_body {
945                    return Ok(self.exec_block(eb, env)?.unwrap_or(Value::Unit));
946                }
947                Ok(Value::Unit)
948            }
949
950            Expr::While { cond, body } => {
951                // Run the body directly in the *outer* env so that
952                // `bind counter = counter + 1` persists across iterations,
953                // which is the expected behaviour in a scripting language.
954                loop {
955                    let cv = self.eval_expr(cond, env)?;
956                    if !self.is_truthy(&cv) { break; }
957                    match self.exec_block(body, env) {
958                        Ok(_) => {}
959                        Err(EvalErr::Break) => break,
960                        Err(e) => return Err(e),
961                    }
962                }
963                Ok(Value::Unit)
964            }
965
966            Expr::For { var, iter, body } => {
967                let iter_val = self.eval_expr(iter, env)?;
968                let items = self.value_to_iter(iter_val)?;
969                for item in items {
970                    let mut local = env.clone();
971                    local.insert(var.clone(), item);
972                    match self.exec_block(body, &mut local) {
973                        Ok(_) => {}
974                        Err(EvalErr::Break) => break,
975                        Err(e) => return Err(e),
976                    }
977                }
978                Ok(Value::Unit)
979            }
980
981            Expr::Match(subject, arms) => {
982                let subj = self.eval_expr(subject, env)?;
983                for arm in arms {
984                    if let Some(bindings) = self.match_pattern(&arm.pattern, &subj) {
985                        let mut local = env.clone();
986                        local.extend(bindings);
987                        return self.eval_expr(&arm.body, &mut local);
988                    }
989                }
990                Ok(Value::Unit)
991            }
992
993            Expr::Range(lo, hi) => {
994                let lo_v = self.eval_expr(lo, env)?;
995                let hi_v = self.eval_expr(hi, env)?;
996                let lo_n = self.to_number(&lo_v)? as i64;
997                let hi_n = self.to_number(&hi_v)? as i64;
998                Ok(Value::List((lo_n..hi_n).map(|i| Value::Number(i as f64)).collect()))
999            }
1000
1001            Expr::Index(base, idx) => {
1002                let b = self.eval_expr(base, env)?;
1003                let i = self.eval_expr(idx, env)?;
1004                let n = self.to_number(&i)? as usize;
1005                match b {
1006                    Value::List(v) => v.get(n).cloned()
1007                        .ok_or_else(|| EvalErr::from(format!("index {n} out of bounds"))),
1008                    Value::Str(s)  => s.chars().nth(n)
1009                        .map(|c| Value::Str(c.to_string()))
1010                        .ok_or_else(|| EvalErr::from(format!("index {n} out of bounds"))),
1011                    other => Err(EvalErr::from(format!("cannot index {:?}", other))),
1012                }
1013            }
1014
1015            Expr::Call(callee, args) => {
1016                let arg_vals: Vec<Value> = args.iter()
1017                    .map(|a| self.eval_expr(a, env))
1018                    .collect::<Result<_,_>>()?;
1019                match callee.as_ref() {
1020                    Expr::Ident(name) => self.call_named(name, arg_vals, env),
1021                    Expr::Path(segs)  => self.call_named(&segs.join("::"), arg_vals, env),
1022                    _ => {
1023                        let v = self.eval_expr(callee, env)?;
1024                        self.call_value(v, arg_vals)
1025                    }
1026                }
1027            }
1028
1029            Expr::MethodCall { receiver, method, args } => {
1030                let recv = self.eval_expr(receiver, env)?;
1031                let arg_vals: Vec<Value> = args.iter()
1032                    .map(|a| self.eval_expr(a, env))
1033                    .collect::<Result<_,_>>()?;
1034                self.call_method(recv, method, arg_vals)
1035            }
1036
1037            Expr::Closure(params, body) => {
1038                Ok(Value::Fn(params.clone(), vec![Stmt::Expr(*body.clone())], env.clone()))
1039            }
1040        }
1041    }
1042
1043    // ─── Block execution ─────────────────────────────────────────────────────
1044
1045    fn exec_block(&mut self, stmts: &[Stmt], env: &mut Env) -> Result<Option<Value>, EvalErr> {
1046        let mut last: Option<Value> = None;
1047        for stmt in stmts {
1048            match stmt {
1049                Stmt::Bind(name, expr) => {
1050                    let v = self.eval_expr(expr, env)?;
1051                    env.insert(name.clone(), v);
1052                    last = None;
1053                }
1054                Stmt::Return(expr) => {
1055                    let v = self.eval_expr(expr, env)?;
1056                    return Err(EvalErr::Return(v));
1057                }
1058                Stmt::Expr(expr) => {
1059                    last = Some(self.eval_expr(expr, env)?);
1060                }
1061            }
1062        }
1063        Ok(last)
1064    }
1065
1066    // ─── Dispatch helpers ─────────────────────────────────────────────────────
1067
1068    fn lookup(&self, name: &str, env: &Env) -> EvalResult {
1069        if let Some(v) = env.get(name) { return Ok(v.clone()); }
1070        if self.functions.contains_key(name) {
1071            let def = &self.functions[name];
1072            return Ok(Value::Fn(def.params.clone(), def.body.clone(), Env::new()));
1073        }
1074        // Bare nullary enum variant used as a value (e.g. `bind p = Origin`).
1075        if let Some((enum_name, 0)) = self.enum_variants.get(name).cloned() {
1076            let variant = name.rsplit("::").next().unwrap_or(name).to_string();
1077            return Ok(Value::Variant { enum_name, variant, payload: Vec::new() });
1078        }
1079        // Math constants usable as plain identifiers (e.g. `sin(pi)`)
1080        match name {
1081            "pi" | "π" | "พาย" | "圆周率" | "円周率" | "파이" => return Ok(Value::Number(std::f64::consts::PI)),
1082            "tau" | "τ" | "双周率" | "タウ" | "타우" | "ทาว"        => return Ok(Value::Number(std::f64::consts::TAU)),
1083            _ => {}
1084        }
1085        Err(EvalErr::from(format!("undefined: '{name}'")))
1086    }
1087
1088    fn call_named(&mut self, name: &str, args: Vec<Value>, env: &Env) -> EvalResult {
1089        match name {
1090            // ── Print ──
1091            "print" | "println" | "印" | "打印" | "印刷" | "พิมพ์" | "출력" | "вывести" | "imprimir" | "afficher" => {
1092                let s = args.iter().map(|v| v.to_string()).collect::<Vec<_>>().join("");
1093                println!("{s}");
1094                return Ok(Value::Unit);
1095            }
1096            // print_color(colorIdx, text...) — ANSI-coloured console line.
1097            //   colorIdx 0..7 → bright fg (90+idx): 1=red 2=green 3=yellow 4=blue 6=cyan 7=white.
1098            "print_color" | "พิมพ์สี" => {
1099                #[cfg(windows)]
1100                {
1101                    use std::sync::Once;
1102                    static VT: Once = Once::new();
1103                    VT.call_once(|| {
1104                        extern "system" {
1105                            fn GetStdHandle(n: u32) -> *mut std::ffi::c_void;
1106                            fn GetConsoleMode(h: *mut std::ffi::c_void, m: *mut u32) -> i32;
1107                            fn SetConsoleMode(h: *mut std::ffi::c_void, m: u32) -> i32;
1108                        }
1109                        unsafe {
1110                            let h = GetStdHandle(0xFFFF_FFF5u32); // STD_OUTPUT_HANDLE (-11)
1111                            let mut mode = 0u32;
1112                            if GetConsoleMode(h, &mut mode) != 0 {
1113                                SetConsoleMode(h, mode | 0x0004); // ENABLE_VIRTUAL_TERMINAL_PROCESSING
1114                            }
1115                        }
1116                    });
1117                }
1118                let col = self.arg_num(&args, 0, 7.0)? as i64;
1119                let s = args.iter().skip(1).map(|v| v.to_string()).collect::<Vec<_>>().join("");
1120                let code = 90 + col.clamp(0, 7);
1121                println!("\x1b[1;{code}m{s}\x1b[0m");
1122                return Ok(Value::Unit);
1123            }
1124            // ── Format ──
1125            "format" | "格式" | "フォーマット" | "서식" | "รูปแบบ" | "форматировать" | "formatear" | "formater" => {
1126                return Ok(Value::Str(self.builtin_format(&args)?));
1127            }
1128            // ── String join / concatenation ──
1129            "格式::拼接" | "format::join" => {
1130                match args.first() {
1131                    Some(Value::List(items)) => {
1132                        return Ok(Value::Str(items.iter().map(|v| v.to_string()).collect()));
1133                    }
1134                    _ => return Ok(Value::Str(self.builtin_format(&args)?)),
1135                }
1136            }
1137            // ── Result constructors ──
1138            "ok" | "好" | "良し" | "좋아" | "โอเค" => {
1139                let val = args.into_iter().next().unwrap_or(Value::Unit);
1140                return Ok(Value::Ok(Box::new(val)));
1141            }
1142            "bad" | "坏" | "err" | "悪い" | "나쁨" | "ผิด" => {
1143                let val = args.into_iter().next().unwrap_or(Value::Unit);
1144                return Ok(Value::Err(Box::new(val)));
1145            }
1146            // ── Vec constructors ──
1147            "向量::从" | "Vec::from" => {
1148                if let Some(Value::List(v)) = args.first() {
1149                    return Ok(Value::List(v.clone()));
1150                }
1151                return Ok(Value::List(args));
1152            }
1153            "向量::有容量" | "Vec::with_capacity" => return Ok(Value::List(Vec::new())),
1154            // ── Timer stubs ──
1155            "计时::获取当前小时" | "Timer::hour" => return Ok(Value::Number(14.0)),
1156            "计时::现在" | "Timer::now"          => return Ok(Value::Number(1000.0)),
1157            // ── Sleep ──
1158            "sleep" | "หยุด" | "นอน" | "sleep_ms" | "睡眠" | "眠る" | "スリープ" | "잠자기" | "잠" | "流水::睡眠" | "Flow::sleep" => {
1159                if let Some(ms_val) = args.first() {
1160                    if let Ok(ms) = self.to_number(ms_val) {
1161                        std::thread::sleep(std::time::Duration::from_millis(ms as u64));
1162                    }
1163                }
1164                return Ok(Value::Unit);
1165            }
1166            // ── Flow::parallel stub ──
1167            "流水::并行" | "Flow::parallel" => {
1168                if let Some(Value::Fn(params, body, mut cap)) = args.first().cloned() {
1169                    let _ = params;
1170                    match self.exec_block(&body, &mut cap) {
1171                        Ok(Some(v)) => return Ok(v),
1172                        Ok(None) => return Ok(Value::Unit),
1173                        Err(EvalErr::Return(v)) => return Ok(v),
1174                        Err(e) => return Err(e),
1175                    }
1176                }
1177                return Ok(Value::Unit);
1178            }
1179
1180            // ══════════════════════════════════════════════════════════════════
1181            // MATH BUILTINS  (all args and results are f64)
1182            // Thai aliases: ไซน์ โคไซน์ แทนเจนต์ รากที่สอง ค่าสัมบูรณ์
1183            //               ปัดลง ปัดขึ้น ปัดเศษ ตัดทศนิยม ต่ำสุด สูงสุด
1184            //               จำกัด ยกกำลัง ลอการิทึม พาย
1185            // ══════════════════════════════════════════════════════════════════
1186
1187            // ── Trigonometry (input in radians) ──
1188            "sin" | "ไซน์" | "正弦" | "サイン" | "사인" => {
1189                return Ok(Value::Number(self.arg_num(&args, 0, 0.0)?.sin()));
1190            }
1191            "cos" | "โคไซน์" | "余弦" | "コサイン" | "코사인" => {
1192                return Ok(Value::Number(self.arg_num(&args, 0, 0.0)?.cos()));
1193            }
1194
1195            // ── Hyperbolic functions ──
1196            // Hyperbolic tangent
1197            "tanh" | "tanhf" | "双曲正切" | "双曲線正接" | "쌍곡탄젠트" => {
1198                return Ok(Value::Number(self.arg_num(&args, 0, 0.0)?.tanh()));
1199            }
1200
1201
1202            "tan" | "แทนเจนต์" | "正切" | "タンジェント" | "탄젠트" => {
1203                return Ok(Value::Number(self.arg_num(&args, 0, 0.0)?.tan()));
1204            }
1205            "asin" | "arcsin" | "反正弦" | "アークサイン" | "아크사인" | "อาร์กไซน์" => {
1206                return Ok(Value::Number(self.arg_num(&args, 0, 0.0)?.asin()));
1207            }
1208            "acos" | "arccos" | "反余弦" | "アークコサイン" | "아크코사인" | "อาร์กโคไซน์" => {
1209                return Ok(Value::Number(self.arg_num(&args, 0, 0.0)?.acos()));
1210            }
1211            "atan" | "arctan" | "反正切" | "アークタンジェント" | "아크탄젠트" | "อาร์กแทนเจนต์" => {
1212                return Ok(Value::Number(self.arg_num(&args, 0, 0.0)?.atan()));
1213            }
1214            "atan2" | "arctan2" | "反正切2" | "アークタンジェント2" | "아크탄젠트2" => {
1215                let y = self.arg_num(&args, 0, 0.0)?;
1216                let x = self.arg_num(&args, 1, 1.0)?;
1217                return Ok(Value::Number(y.atan2(x)));
1218            }
1219
1220            // ── Roots / powers ──
1221            "sqrt" | "รากที่สอง" | "平方根" | "根" | "제곱근" => {
1222                return Ok(Value::Number(self.arg_num(&args, 0, 0.0)?.sqrt()));
1223            }
1224            "cbrt" | "立方根" | "세제곱근" | "รากที่สาม" => {
1225                return Ok(Value::Number(self.arg_num(&args, 0, 0.0)?.cbrt()));
1226            }
1227            "pow" | "ยกกำลัง" | "幂" | "べき乗" | "거듭제곱" => {
1228                let base = self.arg_num(&args, 0, 0.0)?;
1229                let exp  = self.arg_num(&args, 1, 1.0)?;
1230                return Ok(Value::Number(base.powf(exp)));
1231            }
1232            "exp" | "指数" | "指数関数" | "지수" => {
1233                return Ok(Value::Number(self.arg_num(&args, 0, 0.0)?.exp()));
1234            }
1235            "hypot" | "斜边" | "斜辺" | "빗변" => {
1236                let x = self.arg_num(&args, 0, 0.0)?;
1237                let y = self.arg_num(&args, 1, 0.0)?;
1238                return Ok(Value::Number(x.hypot(y)));
1239            }
1240
1241            // ── Logarithms ──
1242            "ln" | "log" | "ลอการิทึม" | "对数" | "対数" | "로그" => {
1243                return Ok(Value::Number(self.arg_num(&args, 0, 1.0)?.ln()));
1244            }
1245            "log2" | "对数2" | "対数2" | "로그2" => {
1246                return Ok(Value::Number(self.arg_num(&args, 0, 1.0)?.log2()));
1247            }
1248            "log10" | "对数10" | "対数10" | "로그10" => {
1249                return Ok(Value::Number(self.arg_num(&args, 0, 1.0)?.log10()));
1250            }
1251
1252            // ── Rounding / truncation ──
1253            "abs" | "ค่าสัมบูรณ์" | "绝对值" | "绝对" | "絶対値" | "절댓값" | "절대값" => {
1254                return Ok(Value::Number(self.arg_num(&args, 0, 0.0)?.abs()));
1255            }
1256            "floor" | "ปัดลง" | "向下取整" | "下整" | "床関数" | "내림" => {
1257                return Ok(Value::Number(self.arg_num(&args, 0, 0.0)?.floor()));
1258            }
1259            "ceil" | "ปัดขึ้น" | "向上取整" | "上整" | "天井関数" | "올림" => {
1260                return Ok(Value::Number(self.arg_num(&args, 0, 0.0)?.ceil()));
1261            }
1262            "round" | "ปัดเศษ" | "四舍五入" | "四舍" | "四捨五入" | "반올림" => {
1263                return Ok(Value::Number(self.arg_num(&args, 0, 0.0)?.round()));
1264            }
1265            "trunc" | "int" | "ตัดทศนิยม" | "取整" | "整数化" | "整数" | "截整"
1266                    | "정수화" | "정수" | "切り捨て" | "버림" => {
1267                return Ok(Value::Number(self.arg_num(&args, 0, 0.0)?.trunc()));
1268            }
1269            "fract" | "小数部分" | "小数部" | "소수부" => {
1270                return Ok(Value::Number(self.arg_num(&args, 0, 0.0)?.fract()));
1271            }
1272
1273            // ── min / max / clamp ──
1274            "min" | "ต่ำสุด" | "最小" | "최솟값" => {
1275                let a = self.arg_num(&args, 0, 0.0)?;
1276                let b = self.arg_num(&args, 1, 0.0)?;
1277                return Ok(Value::Number(a.min(b)));
1278            }
1279            "max" | "สูงสุด" | "最大" | "최댓값" => {
1280                let a = self.arg_num(&args, 0, 0.0)?;
1281                let b = self.arg_num(&args, 1, 0.0)?;
1282                return Ok(Value::Number(a.max(b)));
1283            }
1284            "clamp" | "จำกัด" | "截取" | "範囲制限" | "범위제한" => {
1285                let x  = self.arg_num(&args, 0, 0.0)?;
1286                let lo = self.arg_num(&args, 1, 0.0)?;
1287                let hi = self.arg_num(&args, 2, 1.0)?;
1288                return Ok(Value::Number(x.clamp(lo, hi)));
1289            }
1290
1291            // ── Constants (also accessible as plain identifiers via lookup) ──
1292            "pi" | "π" | "พาย" | "圆周率" | "円周率" | "파이" => return Ok(Value::Number(std::f64::consts::PI)),
1293            "tau" | "τ" | "双周率" | "タウ" | "타우" | "ทาว"        => return Ok(Value::Number(std::f64::consts::TAU)),
1294
1295            // ══════════════════════════════════════════════════════════════════
1296            // PHASE 1: DMT TRIP CODER FEATURES
1297            // ══════════════════════════════════════════════════════════════════
1298
1299            // ── Step 1: Noise Functions ──
1300            "vnoise" | "noise2" | "นอยส์2ดี" | "柏林噪声2D" | "バリューノイズ2D" | "값노이즈2D" => {
1301                let x = self.arg_num(&args, 0, 0.0)? as f32;
1302                let y = self.arg_num(&args, 1, 0.0)? as f32;
1303                let seed = self.arg_num(&args, 2, 0.0)? as u32;
1304                return Ok(Value::Number(tex_vnoise(x, y, seed) as f64));
1305            }
1306
1307            "fbm" | "นอยส์ออร์แกนิก" | "分形噪声" | "フラクタルノイズ" | "프랙탈노이즈" => {
1308                let x = self.arg_num(&args, 0, 0.0)? as f32;
1309                let y = self.arg_num(&args, 1, 0.0)? as f32;
1310                let octaves = self.arg_num(&args, 2, 4.0)? as u32;
1311                let seed = self.arg_num(&args, 3, 0.0)? as u32;
1312                return Ok(Value::Number(tex_fbm(x, y, octaves, seed) as f64));
1313            }
1314
1315            "perlin" | "perlin3" | "เพอร์ลิน3ดี" | "柏林噪声3D" | "パーリンノイズ3D" | "펄린노이즈3D" => {
1316                let x = self.arg_num(&args, 0, 0.0)? as f32;
1317                let y = self.arg_num(&args, 1, 0.0)? as f32;
1318                let z = self.arg_num(&args, 2, 0.0)? as f32;
1319                return Ok(Value::Number(perlin3(x, y, z) as f64));
1320            }
1321
1322            // ── Step 2: Math Ergonomics ──
1323            "lerp" | "ค่าระหว่าง" | "线性插值" | "線形補間" | "선형보간" => {
1324                let a = self.arg_num(&args, 0, 0.0)?;
1325                let b = self.arg_num(&args, 1, 1.0)?;
1326                let t = self.arg_num(&args, 2, 0.0)?;
1327                return Ok(Value::Number(a + (b - a) * t));
1328            }
1329
1330            "smoothstep" | "เปลี่ยนแบบนุ่ม" | "平滑步进" | "スムーズステップ" | "스무스스텝" => {
1331                let lo = self.arg_num(&args, 0, 0.0)?;
1332                let hi = self.arg_num(&args, 1, 1.0)?;
1333                let x = self.arg_num(&args, 2, 0.5)?;
1334                let t = ((x - lo) / (hi - lo)).clamp(0.0, 1.0);
1335                return Ok(Value::Number(t * t * (3.0 - 2.0 * t)));
1336            }
1337
1338            "rand" | "สุ่ม" | "随机" | "乱数" | "난수" => {
1339                let val = fast_rand_f64(&mut self.rand_state);
1340                return Ok(Value::Number(val));
1341            }
1342
1343            "sign" | "เครื่องหมาย" | "符号" | "符号関数" | "부호" => {
1344                let x = self.arg_num(&args, 0, 0.0)?;
1345                return Ok(Value::Number(x.signum()));
1346            }
1347
1348            "hsv_to_rgb" | "เอชเอสวีเป็นRGB" | "HSV转RGB" | "HSV変換RGB" | "HSV변환RGB" => {
1349                let h = self.arg_num(&args, 0, 0.0)?; // 0-360
1350                let s = self.arg_num(&args, 1, 1.0)?; // 0-1
1351                let v = self.arg_num(&args, 2, 1.0)?; // 0-1
1352                let c = v * s;
1353                let x = c * (1.0 - (((h / 60.0) % 2.0) - 1.0).abs());
1354                let m = v - c;
1355                let (r1, g1, b1) = if h < 60.0       { (c, x, 0.0) }
1356                                    else if h < 120.0  { (x, c, 0.0) }
1357                                    else if h < 180.0  { (0.0, c, x) }
1358                                    else if h < 240.0  { (0.0, x, c) }
1359                                    else if h < 300.0  { (x, 0.0, c) }
1360                                    else               { (c, 0.0, x) };
1361                let r = ((r1 + m) * 255.0).round();
1362                let g = ((g1 + m) * 255.0).round();
1363                let b = ((b1 + m) * 255.0).round();
1364                return Ok(Value::List(vec![Value::Number(r), Value::Number(g), Value::Number(b)]));
1365            }
1366
1367            "lerp_color" | "ไล่สี" | "颜色插值" | "色補間" | "색보간" => {
1368                let r1 = self.arg_num(&args, 0, 0.0)?;
1369                let g1 = self.arg_num(&args, 1, 0.0)?;
1370                let b1 = self.arg_num(&args, 2, 0.0)?;
1371                let r2 = self.arg_num(&args, 3, 255.0)?;
1372                let g2 = self.arg_num(&args, 4, 255.0)?;
1373                let b2 = self.arg_num(&args, 5, 255.0)?;
1374                let t = self.arg_num(&args, 6, 0.0)?;
1375                let r = r1 + (r2 - r1) * t;
1376                let g = g1 + (g2 - g1) * t;
1377                let b = b1 + (b2 - b1) * t;
1378                let c = ((r as u32) << 16) | ((g as u32) << 8) | (b as u32);
1379                self.gfx.borrow_mut().color = c;
1380                return Ok(Value::Unit);
1381            }
1382
1383            // ── Step 3: Real-Time Clock ──
1384            "time_now" | "เวลาปัจจุบัน" | "当前时间" | "経過時間" | "현재시간" => {
1385                return Ok(Value::Number(self.start_time.elapsed().as_secs_f64()));
1386            }
1387
1388            "frame_count" | "เฟรม" | "帧数" | "フレーム数" | "프레임수" => {
1389                return Ok(Value::Number(self.frame_num as f64));
1390            }
1391
1392            // ── Step 4: Microphone Input ──
1393            "mic_open" | "เปิดไมค์" | "开麦克风" | "マイク開く" | "마이크열기" => {
1394                #[cfg(not(target_arch = "wasm32"))]
1395                {
1396                    match ling_mic::MicInput::open(Default::default()) {
1397                        Ok(mic) => {
1398                            let _ = mic.start(|_samples: &[f32]| {});  // No-op callback
1399                            self.mic = Some(mic);
1400                            return Ok(Value::Unit);
1401                        }
1402                        Err(e) => return Err(EvalErr::from(format!("mic_open failed: {e}"))),
1403                    }
1404                }
1405                #[cfg(target_arch = "wasm32")]
1406                return Ok(Value::Unit);
1407            }
1408
1409            "mic_rms" | "เสียงRMS" | "麦克风音量" | "マイクRMS" | "마이크RMS" => {
1410                #[cfg(not(target_arch = "wasm32"))]
1411                {
1412                    let rms = self.mic.as_ref().map(|m: &ling_mic::MicInput| m.rms()).unwrap_or(0.0);
1413                    return Ok(Value::Number(rms as f64));
1414                }
1415                #[cfg(target_arch = "wasm32")]
1416                return Ok(Value::Number(0.0));
1417            }
1418
1419            "mic_peak" | "เสียงพีค" | "麦克风峰值" | "マイクピーク" | "마이크피크" => {
1420                #[cfg(not(target_arch = "wasm32"))]
1421                {
1422                    let peak = self.mic.as_ref().map(|m: &ling_mic::MicInput| m.peak()).unwrap_or(0.0);
1423                    return Ok(Value::Number(peak as f64));
1424                }
1425                #[cfg(target_arch = "wasm32")]
1426                return Ok(Value::Number(0.0));
1427            }
1428
1429            "mic_fft" | "วิเคราะห์เสียงสด" | "实时频谱" | "リアルタイムFFT" | "실시간FFT" => {
1430                #[cfg(not(target_arch = "wasm32"))]
1431                {
1432                    let n = self.arg_num(&args, 0, 8.0)? as usize;
1433                    if let Some(mic) = self.mic.as_ref() {
1434                        let samples = mic.latest_samples();
1435                        self.fft.borrow_mut().push_samples(&samples);
1436                    }
1437                    let bands = self.fft.borrow().freq_bands(n);
1438                    let result = bands.iter().map(|&v| Value::Number(v as f64)).collect();
1439                    return Ok(Value::List(result));
1440                }
1441                #[cfg(target_arch = "wasm32")]
1442                return Ok(Value::List(vec![]));
1443            }
1444
1445            // ── Step 5: Additive Blend Mode ──
1446            "set_blend" | "โหมดผสม" | "混合模式" | "ブレンドモード" | "블렌드모드" => {
1447                let mode = self.arg_num(&args, 0, 0.0)? as u8;
1448                self.gfx.borrow_mut().blend = mode;
1449                return Ok(Value::Unit);
1450            }
1451
1452            // ── Step 6: Circle Primitives ──
1453            "draw_circle" | "วาดวงกลม" | "画圆" | "円描画" | "원그리기" => {
1454                let cx = self.arg_num(&args, 0, 0.0)? as i32;
1455                let cy = self.arg_num(&args, 1, 0.0)? as i32;
1456                let r = self.arg_num(&args, 2, 10.0)? as i32;
1457                let mut gfx = self.gfx.borrow_mut();
1458                let (w, h, color, blend) = (gfx.width as i32, gfx.height as i32, gfx.color, gfx.blend);
1459                draw_circle_outline(&mut gfx.buffer, w, h, cx, cy, r, color, blend);
1460                return Ok(Value::Unit);
1461            }
1462
1463            "draw_filled_circle" | "draw_disc" | "วาดวงกลมทึบ" | "画实心圆" | "塗りつぶし円" | "원채우기" => {
1464                let cx = self.arg_num(&args, 0, 0.0)? as i32;
1465                let cy = self.arg_num(&args, 1, 0.0)? as i32;
1466                let r = self.arg_num(&args, 2, 10.0)? as i32;
1467                let mut gfx = self.gfx.borrow_mut();
1468                let (w, h, color, blend) = (gfx.width as i32, gfx.height as i32, gfx.color, gfx.blend);
1469                draw_circle_filled(&mut gfx.buffer, w, h, cx, cy, r, color, blend);
1470                return Ok(Value::Unit);
1471            }
1472
1473            // ══════════════════════════════════════════════════════════════════
1474            // GRAPHICS BUILTINS
1475            // Thai names first, then English aliases.
1476            // ══════════════════════════════════════════════════════════════════
1477
1478            // ── เปิดหน้าต่าง(width, height, title) — open_window ──
1479            "เปิดหน้าต่าง" | "open_window" | "gfx_window" | "开窗" | "ウィンドウ開く" | "창열기" => {
1480                let w = self.arg_num(&args, 0, 800.0)? as usize;
1481                let h = self.arg_num(&args, 1, 600.0)? as usize;
1482                #[cfg(not(target_arch = "wasm32"))]
1483                {
1484                    let title = args.get(2).map(|v| v.to_string()).unwrap_or_else(|| "Ling".into());
1485                    let mut gfx = self.gfx.borrow_mut();
1486                    let mut win = minifb::Window::new(
1487                        &title, w, h,
1488                        minifb::WindowOptions {
1489                            resize: false,
1490                            scale: minifb::Scale::X1,
1491                            ..Default::default()
1492                        },
1493                    ).map_err(|e| EvalErr::from(format!("cannot open window: {e}")))?;
1494                    #[allow(deprecated)]
1495                    win.limit_update_rate(Some(std::time::Duration::from_millis(8)));
1496                    gfx.buffer = vec![0u32; w * h];
1497                    gfx.width  = w;
1498                    gfx.height = h;
1499                    gfx.window = Some(win);
1500                    gfx.sync_projection();
1501                    hide_console_window();
1502                }
1503                #[cfg(target_arch = "wasm32")]
1504                {
1505                    let mut gfx = self.gfx.borrow_mut();
1506                    gfx.width  = w;
1507                    gfx.height = h;
1508                    gfx.sync_projection();
1509                    crate::gfx::webgl::resize(w as u32, h as u32);
1510                }
1511                return Ok(Value::Unit);
1512            }
1513
1514            // ── เติม(r, g, b) — fill / clear screen with colour ──
1515            "เติม" | "fill" | "gfx_fill" | "clear" | "填" | "塗り潰し" | "채우기" | "清" | "消去" | "지우기" => {
1516                let r = self.arg_num(&args, 0, 0.0)? as u32;
1517                let g = self.arg_num(&args, 1, 0.0)? as u32;
1518                let b = self.arg_num(&args, 2, 0.0)? as u32;
1519                #[cfg(not(target_arch = "wasm32"))]
1520                {
1521                    let c = (r << 16) | (g << 8) | b;
1522                    self.gfx.borrow_mut().buffer.fill(c);
1523                }
1524                #[cfg(target_arch = "wasm32")]
1525                {
1526                    let mut gfx = self.gfx.borrow_mut();
1527                    gfx.fill_r = r as f32 / 255.0;
1528                    gfx.fill_g = g as f32 / 255.0;
1529                    gfx.fill_b = b as f32 / 255.0;
1530                }
1531                return Ok(Value::Unit);
1532            }
1533
1534            // ── set_color_hsl(h, s, l) — set drawing colour from HSL ──
1535            // h: 0–360 degrees, s: 0–100 saturation, l: 0–100 lightness
1536            "set_color_hsl" | "颜色HSL" | "色相" | "HSL色" | "HSL색설정" | "สีHSLวาด" => {
1537                let h = self.arg_num(&args, 0, 0.0)?;
1538                let s = self.arg_num(&args, 1, 70.0)?;
1539                let l = self.arg_num(&args, 2, 50.0)?;
1540                let hex = hsl_to_hex(h, s, l);
1541                let r = u32::from_str_radix(&hex[1..3], 16).unwrap_or(255);
1542                let g = u32::from_str_radix(&hex[3..5], 16).unwrap_or(255);
1543                let b = u32::from_str_radix(&hex[5..7], 16).unwrap_or(255);
1544                self.gfx.borrow_mut().color = (r << 16) | (g << 8) | b;
1545                return Ok(Value::Unit);
1546            }
1547
1548            // ── สีดินสอ(r, g, b) — set drawing colour ──
1549            "สีดินสอ" | "set_color" | "gfx_color" | "color" | "设色" | "色設定" | "색설정" => {
1550                let r = self.arg_num(&args, 0, 255.0)? as u32;
1551                let g = self.arg_num(&args, 1, 255.0)? as u32;
1552                let b = self.arg_num(&args, 2, 255.0)? as u32;
1553                self.gfx.borrow_mut().color = (r << 16) | (g << 8) | b;
1554                return Ok(Value::Unit);
1555            }
1556
1557            // ── วาดสามเหลี่ยม(x1,y1, x2,y2, x3,y3) — draw filled triangle ──
1558            "วาดสามเหลี่ยม" | "draw_triangle" | "gfx_triangle" | "triangle" | "画三角" | "三角形描画" | "삼각형그리기" => {
1559                let x0 = self.arg_num(&args, 0, 0.0)? as f32;
1560                let y0 = self.arg_num(&args, 1, 0.0)? as f32;
1561                let x1 = self.arg_num(&args, 2, 0.0)? as f32;
1562                let y1 = self.arg_num(&args, 3, 0.0)? as f32;
1563                let x2 = self.arg_num(&args, 4, 0.0)? as f32;
1564                let y2 = self.arg_num(&args, 5, 0.0)? as f32;
1565                let mut gfx = self.gfx.borrow_mut();
1566                let color = gfx.color;
1567                #[cfg(not(target_arch = "wasm32"))]
1568                {
1569                    let w = gfx.width;
1570                    let h = gfx.height;
1571                    fill_triangle(&mut gfx.buffer, w, h, color, x0, y0, x1, y1, x2, y2);
1572                }
1573                #[cfg(target_arch = "wasm32")]
1574                gfx.depth_queue.push_triangle(0.0, color, x0, y0, x1, y1, x2, y2);
1575                return Ok(Value::Unit);
1576            }
1577
1578            // ── วาดเส้น(x1,y1, x2,y2) — draw line ──
1579            "วาดเส้น" | "draw_line" | "gfx_line" | "line" | "画线" | "線描く" | "선그리기" => {
1580                let x0 = self.arg_num(&args, 0, 0.0)? as f32;
1581                let y0 = self.arg_num(&args, 1, 0.0)? as f32;
1582                let x1 = self.arg_num(&args, 2, 0.0)? as f32;
1583                let y1 = self.arg_num(&args, 3, 0.0)? as f32;
1584                let mut gfx = self.gfx.borrow_mut();
1585                let color = gfx.color;
1586                #[cfg(not(target_arch = "wasm32"))]
1587                {
1588                    let w = gfx.width;
1589                    let h = gfx.height;
1590                    draw_line(&mut gfx.buffer, w, h, color, x0, y0, x1, y1);
1591                }
1592                #[cfg(target_arch = "wasm32")]
1593                gfx.depth_queue.push_line(0.0, color, x0, y0, x1, y1);
1594                return Ok(Value::Unit);
1595            }
1596
1597            // ── วาดจุด(x, y) — plot a single pixel ──
1598            "วาดจุด" | "draw_pixel" | "gfx_pixel" | "pixel" | "画点" | "点描く" | "점그리기" => {
1599                let px = self.arg_num(&args, 0, 0.0)? as i32;
1600                let py = self.arg_num(&args, 1, 0.0)? as i32;
1601                #[cfg(not(target_arch = "wasm32"))]
1602                {
1603                    let mut gfx = self.gfx.borrow_mut();
1604                    let color = gfx.color;
1605                    let w = gfx.width;
1606                    let h = gfx.height;
1607                    if px >= 0 && py >= 0 && (px as usize) < w && (py as usize) < h {
1608                        gfx.buffer[py as usize * w + px as usize] = color;
1609                    }
1610                }
1611                #[cfg(target_arch = "wasm32")]
1612                {
1613                    // Render pixel as a 1×1 square via two triangles.
1614                    let mut gfx = self.gfx.borrow_mut();
1615                    let color = gfx.color;
1616                    let x = px as f32; let y = py as f32;
1617                    gfx.depth_queue.push_triangle(0.0, color, x, y, x+1.0, y, x+1.0, y+1.0);
1618                    gfx.depth_queue.push_triangle(0.0, color, x, y, x+1.0, y+1.0, x, y+1.0);
1619                }
1620                return Ok(Value::Unit);
1621            }
1622
1623            // ── แสดงผล() — flush depth queue, then present frame to screen ──
1624            "แสดงผล" | "present" | "gfx_present" | "show" | "显" | "呈现" | "表示" | "표시" => {
1625                #[cfg(not(target_arch = "wasm32"))]
1626                {
1627                    // Flush depth queue and present — release borrow before reading mouse.
1628                    {
1629                        let mut gfx = self.gfx.borrow_mut();
1630                        if !gfx.depth_queue.is_empty() {
1631                            let w = gfx.width;
1632                            let h = gfx.height;
1633                            let queue = std::mem::take(&mut gfx.depth_queue);
1634                            queue.flush(&mut gfx.buffer, w, h);
1635                        }
1636                        let buf = gfx.buffer.clone();
1637                        let w   = gfx.width;
1638                        let h   = gfx.height;
1639                        if let Some(win) = gfx.window.as_mut() {
1640                            win.update_with_buffer(&buf, w, h)
1641                                .map_err(|e| EvalErr::from(format!("present error: {e}")))?;
1642                        }
1643                    }
1644                    // Read mouse AFTER update_with_buffer so events are processed.
1645                    let mouse_pos = {
1646                        let gfx = self.gfx.borrow();
1647                        gfx.window.as_ref()
1648                            .and_then(|w| w.get_mouse_pos(minifb::MouseMode::Clamp))
1649                    };
1650                    let mut gfx = self.gfx.borrow_mut();
1651                    if gfx.mouse_captured {
1652                        let mut cur_my = gfx.last_my;
1653                        if let Some((mx, my)) = mouse_pos {
1654                            cur_my = my;
1655                            if gfx.last_mx.is_nan() {
1656                                gfx.mouse_dx = 0.0; gfx.mouse_dy = 0.0;
1657                            } else {
1658                                gfx.mouse_dx = mx - gfx.last_mx;
1659                                gfx.mouse_dy = my - gfx.last_my;
1660                            }
1661                        } else {
1662                            gfx.mouse_dx = 0.0; gfx.mouse_dy = 0.0;
1663                        }
1664                        // Recenter only the X axis each frame → INFINITE yaw (no 0-360
1665                        // edge clamp) while leaving Y free so the camera can still tilt.
1666                        #[cfg(windows)]
1667                        unsafe {
1668                            #[repr(C)]
1669                            struct RECT { left: i32, top: i32, right: i32, bottom: i32 }
1670                            #[repr(C)]
1671                            struct POINT { x: i32, y: i32 }
1672                            extern "system" {
1673                                fn ClipCursor(lpRect: *const std::ffi::c_void) -> i32;
1674                                fn GetForegroundWindow() -> isize;
1675                                fn GetWindowRect(hwnd: isize, lpRect: *mut RECT) -> i32;
1676                                fn SetCursorPos(x: i32, y: i32) -> i32;
1677                                fn GetCursorPos(lpPoint: *mut POINT) -> i32;
1678                            }
1679                            let hwnd = GetForegroundWindow();
1680                            let mut rect = RECT { left: 0, top: 0, right: 0, bottom: 0 };
1681                            if GetWindowRect(hwnd, &mut rect) != 0 {
1682                                ClipCursor(&rect as *const RECT as *const std::ffi::c_void);
1683                                let mid_x = (rect.left + rect.right) / 2;
1684                                let mut p = POINT { x: 0, y: 0 };
1685                                GetCursorPos(&mut p);
1686                                SetCursorPos(mid_x, p.y); // keep current Y → vertical tilt works
1687                            }
1688                        }
1689                        // X resets to framebuffer centre; Y keeps its real position.
1690                        gfx.last_mx = gfx.width as f32 / 2.0;
1691                        gfx.last_my = cur_my;
1692                    } else if let Some((mx, my)) = mouse_pos {
1693                        if gfx.last_mx.is_nan() {
1694                            gfx.mouse_dx = 0.0; gfx.mouse_dy = 0.0;
1695                        } else {
1696                            gfx.mouse_dx = mx - gfx.last_mx;
1697                            gfx.mouse_dy = my - gfx.last_my;
1698                        }
1699                        gfx.last_mx = mx; gfx.last_my = my;
1700                    } else {
1701                        gfx.mouse_dx = 0.0; gfx.mouse_dy = 0.0;
1702                    }
1703                }
1704                #[cfg(target_arch = "wasm32")]
1705                {
1706                    let mut gfx = self.gfx.borrow_mut();
1707                    let w  = gfx.width;
1708                    let h  = gfx.height;
1709                    let fr = gfx.fill_r;
1710                    let fg = gfx.fill_g;
1711                    let fb = gfx.fill_b;
1712                    let queue = std::mem::take(&mut gfx.depth_queue);
1713                    queue.flush_to_webgl(fr, fg, fb, w, h);
1714                }
1715                // Update the click-edge latch for interactive UI widgets.
1716                #[cfg(not(target_arch = "wasm32"))]
1717                {
1718                    let (_, _, down) = self.mouse_now();
1719                    self.mouse_was_down = down;
1720                }
1721                // Increment frame counter
1722                self.frame_num += 1;
1723                return Ok(Value::Unit);
1724            }
1725
1726            // ── เปิดหน้าต่างเต็มจอ(title) — true native-res fullscreen window ──
1727            "เปิดหน้าต่างเต็มจอ" | "open_fullscreen" | "fullscreen" | "全屏" | "全画面" | "전체화면" => {
1728                // In WASM the canvas defines the viewport; use its current size
1729                // as the default so the projection matches what's actually visible.
1730                #[cfg(target_arch = "wasm32")]
1731                let (default_w, default_h) = {
1732                    let (cw, ch) = crate::gfx::webgl::canvas_size();
1733                    (cw as f64, ch as f64)
1734                };
1735                // On native: query the actual primary monitor resolution.
1736                #[cfg(all(not(target_arch = "wasm32"), windows))]
1737                let (default_w, default_h) = unsafe {
1738                    extern "system" { fn GetSystemMetrics(nIndex: i32) -> i32; }
1739                    (GetSystemMetrics(0) as f64, GetSystemMetrics(1) as f64)
1740                };
1741                #[cfg(all(not(target_arch = "wasm32"), not(windows)))]
1742                let (default_w, default_h) = native_screen_size();
1743
1744                let w = args.get(1).map(|v| self.to_number(v).unwrap_or(default_w) as usize).unwrap_or(default_w as usize);
1745                let h = args.get(2).map(|v| self.to_number(v).unwrap_or(default_h) as usize).unwrap_or(default_h as usize);
1746                #[cfg(not(target_arch = "wasm32"))]
1747                {
1748                    let title = args.get(0).map(|v| v.to_string()).unwrap_or_else(|| "Ling".into());
1749                    let mut gfx = self.gfx.borrow_mut();
1750                    let mut win = minifb::Window::new(
1751                        &title, w, h,
1752                        minifb::WindowOptions {
1753                            borderless: true,
1754                            title:      false,
1755                            resize:     false,
1756                            topmost:    true,
1757                            scale:      minifb::Scale::X1,
1758                            ..Default::default()
1759                        },
1760                    ).map_err(|e| EvalErr::from(format!("cannot open fullscreen: {e}")))?;
1761                    // Drive the loop at the monitor's real refresh rate instead of
1762                    // a hard-coded cap, so a 144 Hz panel runs at 144 fps.
1763                    win.set_target_fps(monitor_info().2.max(30) as usize);
1764                    // Grab the native handle *before* moving the window into gfx.
1765                    #[cfg(windows)]
1766                    let hwnd = win.get_window_handle() as isize;
1767                    gfx.buffer = vec![0u32; w * h];
1768                    gfx.width  = w;
1769                    gfx.height = h;
1770                    gfx.window = Some(win);
1771                    gfx.sync_projection();
1772                    // Strip all chrome and cover the full screen, above the taskbar.
1773                    #[cfg(windows)]
1774                    make_borderless_fullscreen(hwnd, w as i32, h as i32);
1775                    hide_console_window();
1776                }
1777                #[cfg(target_arch = "wasm32")]
1778                {
1779                    let mut gfx = self.gfx.borrow_mut();
1780                    gfx.width  = w;
1781                    gfx.height = h;
1782                    gfx.sync_projection();
1783                    crate::gfx::webgl::resize(w as u32, h as u32);
1784                }
1785                return Ok(Value::Unit);
1786            }
1787
1788            // ── ความกว้าง() / ความสูง() — current framebuffer size ──
1789            "get_width" | "ความกว้าง" | "宽" | "幅取得" | "너비" => {
1790                return Ok(Value::Number(self.gfx.borrow().width as f64));
1791            }
1792            "get_height" | "ความสูง" | "高" | "高取得" | "높이" => {
1793                return Ok(Value::Number(self.gfx.borrow().height as f64));
1794            }
1795
1796            // ── monitor detection: physical display, not the framebuffer ──────
1797            // monitor_width() → primary-monitor pixel width
1798            "monitor_width" | "screen_width" | "屏宽" | "画面幅" | "화면너비" | "ความกว้างจอ" => {
1799                return Ok(Value::Number(monitor_info().0 as f64));
1800            }
1801            // monitor_height() → primary-monitor pixel height
1802            "monitor_height" | "screen_height" | "屏高" | "画面高" | "화면높이" | "ความสูงจอ" => {
1803                return Ok(Value::Number(monitor_info().1 as f64));
1804            }
1805            // monitor_refresh() → refresh rate in Hz (a.k.a. the monitor framerate)
1806            "monitor_refresh" | "monitor_hz" | "monitor_fps" | "refresh_rate"
1807                | "刷新率" | "リフレッシュレート" | "주사율" | "อัตรารีเฟรช" => {
1808                return Ok(Value::Number(monitor_info().2 as f64));
1809            }
1810            // monitor_info() → [width, height, refresh_hz]
1811            "monitor_info" | "screen_info" | "屏幕信息" | "画面情報" | "화면정보" | "ข้อมูลจอ" => {
1812                let (w, h, hz) = monitor_info();
1813                return Ok(Value::List(vec![
1814                    Value::Number(w as f64),
1815                    Value::Number(h as f64),
1816                    Value::Number(hz as f64),
1817                ]));
1818            }
1819            // set_fps(n) → cap the render loop at n frames per second
1820            "set_fps" | "set_target_fps" | "target_fps" | "设帧率" | "フレームレート設定" | "프레임설정" | "ตั้งเฟรมเรต" => {
1821                let fps = self.arg_num(&args, 0, 60.0)?.max(1.0) as usize;
1822                #[cfg(not(target_arch = "wasm32"))]
1823                {
1824                    let mut gfx = self.gfx.borrow_mut();
1825                    if let Some(win) = gfx.window.as_mut() {
1826                        win.set_target_fps(fps);
1827                    }
1828                }
1829                return Ok(Value::Unit);
1830            }
1831
1832            // ── หน้าต่างเปิดอยู่() → bool — is the window still open? ──
1833            "หน้าต่างเปิดอยู่" | "window_is_open" | "gfx_is_open" | "is_open" | "窗开" | "開いている" | "창열림" => {
1834                #[cfg(not(target_arch = "wasm32"))]
1835                {
1836                    let gfx = self.gfx.borrow();
1837                    let open = gfx.window.as_ref()
1838                        .map(|w| w.is_open() && !w.is_key_down(minifb::Key::Escape))
1839                        .unwrap_or(false);
1840                    return Ok(Value::Bool(open));
1841                }
1842                #[cfg(target_arch = "wasm32")]
1843                return Ok(Value::Bool(true));
1844            }
1845
1846            // ── key_down(name) → bool — is a key held? ──
1847            "key_down" | "กดค้าง" | "按键" | "キー押す" | "키누름" => {
1848                #[cfg(not(target_arch = "wasm32"))]
1849                {
1850                    let name = self.arg_str(&args, 0, "");
1851                    let gfx  = self.gfx.borrow();
1852                    let down = gfx.window.as_ref()
1853                        .and_then(|w| str_to_minifb_key(&name).map(|k| w.is_key_down(k)))
1854                        .unwrap_or(false);
1855                    return Ok(Value::Bool(down));
1856                }
1857                #[cfg(target_arch = "wasm32")]
1858                return Ok(Value::Bool(false));
1859            }
1860
1861            // ── key_pressed(name) → bool — was a key pressed this frame? ──
1862            "key_pressed" | "กดปุ่ม" | "键按" | "キー押した" | "키눌림" => {
1863                #[cfg(not(target_arch = "wasm32"))]
1864                {
1865                    let name = self.arg_str(&args, 0, "");
1866                    let gfx  = self.gfx.borrow();
1867                    let pressed = gfx.window.as_ref()
1868                        .and_then(|w| str_to_minifb_key(&name)
1869                            .map(|k| w.is_key_pressed(k, minifb::KeyRepeat::No)))
1870                        .unwrap_or(false);
1871                    return Ok(Value::Bool(pressed));
1872                }
1873                #[cfg(target_arch = "wasm32")]
1874                return Ok(Value::Bool(false));
1875            }
1876
1877            // ── mouse_dx() / mouse_dy() → f64 — delta since last frame ──
1878            "mouse_dx" | "เมาส์X" | "鼠ΔX" | "マウスΔX" | "마우스ΔX" => {
1879                #[cfg(not(target_arch = "wasm32"))]
1880                return Ok(Value::Number(self.gfx.borrow().mouse_dx as f64));
1881                #[cfg(target_arch = "wasm32")]
1882                return Ok(Value::Number(0.0));
1883            }
1884            // ── mouse_scroll() → f64 — vertical scroll-wheel delta this frame ──
1885            #[cfg(not(target_arch = "wasm32"))]
1886            "mouse_scroll" | "ล้อเมาส์" | "滚轮" | "ホイール" | "스크롤" => {
1887                let gfx = self.gfx.borrow();
1888                let s = gfx.window.as_ref()
1889                    .and_then(|w| w.get_scroll_wheel())
1890                    .map(|(_, y)| y as f64).unwrap_or(0.0);
1891                return Ok(Value::Number(s));
1892            }
1893            "mouse_dy" | "เมาส์Y" | "鼠ΔY" | "マウスΔY" | "마우스ΔY" => {
1894                #[cfg(not(target_arch = "wasm32"))]
1895                return Ok(Value::Number(self.gfx.borrow().mouse_dy as f64));
1896                #[cfg(target_arch = "wasm32")]
1897                return Ok(Value::Number(0.0));
1898            }
1899
1900            // ── set_camera_pos(x, y, z) — move camera to world position ──
1901            "set_camera_pos" | "ตั้งตำแหน่งกล้อง" | "镜坐标" | "カメラ座標" | "카메라좌표" => {
1902                let x = self.arg_num(&args, 0, 0.0)? as f32;
1903                let y = self.arg_num(&args, 1, 0.0)? as f32;
1904                let z = self.arg_num(&args, 2, 0.0)? as f32;
1905                let mut gfx = self.gfx.borrow_mut();
1906                gfx.camera.tx = x; gfx.camera.ty = y; gfx.camera.tz = z;
1907                return Ok(Value::Unit);
1908            }
1909
1910            // ── move_camera(dx, dy, dz) — translate camera by delta ──
1911            "move_camera" => {
1912                let dx = self.arg_num(&args, 0, 0.0)? as f32;
1913                let dy = self.arg_num(&args, 1, 0.0)? as f32;
1914                let dz = self.arg_num(&args, 2, 0.0)? as f32;
1915                let mut gfx = self.gfx.borrow_mut();
1916                gfx.camera.tx += dx; gfx.camera.ty += dy; gfx.camera.tz += dz;
1917                return Ok(Value::Unit);
1918            }
1919
1920            // ── set_zdist(d) — set perspective z-offset (field-of-view taper) ──
1921            "set_zdist" | "ตั้งระยะห่าง" | "镜距" | "Z距離設定" | "Z거리설정" => {
1922                let d = self.arg_num(&args, 0, 5.0)? as f32;
1923                self.gfx.borrow_mut().camera.zdist = d;
1924                return Ok(Value::Unit);
1925            }
1926
1927            // ── capture_mouse() — hide cursor and warp to centre each frame ──
1928            "capture_mouse" | "จับเมาส์" | "捕鼠" | "マウス捕捉" | "마우스잡기" => {
1929                #[cfg(not(target_arch = "wasm32"))]
1930                {
1931                    let mut gfx = self.gfx.borrow_mut();
1932                    gfx.mouse_captured = true;
1933                    gfx.last_mx = f32::NAN;
1934                    if let Some(win) = gfx.window.as_mut() {
1935                        win.set_cursor_visibility(false);
1936                    }
1937                }
1938                return Ok(Value::Unit);
1939            }
1940
1941            // ── release_mouse() — restore cursor and remove clip region ──
1942            "release_mouse" => {
1943                #[cfg(not(target_arch = "wasm32"))]
1944                {
1945                    let mut gfx = self.gfx.borrow_mut();
1946                    gfx.mouse_captured = false;
1947                    gfx.last_mx = f32::NAN;
1948                    if let Some(win) = gfx.window.as_mut() {
1949                        win.set_cursor_visibility(true);
1950                    }
1951                    #[cfg(windows)]
1952                    unsafe {
1953                        // Null releases the clip; reuse the RECT-typed declaration above.
1954                        extern "system" { fn ClipCursor(lpRect: *const std::ffi::c_void) -> i32; }
1955                        ClipCursor(std::ptr::null());
1956                    }
1957                }
1958                return Ok(Value::Unit);
1959            }
1960
1961            // ══════════════════════════════════════════════════════════════════
1962            // 3-D / 4-D DRAWING — camera, lights, depth-sorted geometry
1963            // ══════════════════════════════════════════════════════════════════
1964
1965            // ── set_camera(cry, sry, crx, srx) — store precomputed camera trig ──
1966            // Call once per frame after computing cos/sin of your rotation angles.
1967            "set_camera" | "ตั้งกล้อง" | "设镜" | "设置摄像机" | "カメラ設定" | "카메라설정" => {
1968                let cry = self.arg_num(&args, 0, 1.0)? as f32;
1969                let sry = self.arg_num(&args, 1, 0.0)? as f32;
1970                let crx = self.arg_num(&args, 2, 1.0)? as f32;
1971                let srx = self.arg_num(&args, 3, 0.0)? as f32;
1972                let mut gfx = self.gfx.borrow_mut();
1973                gfx.camera.cry = cry; gfx.camera.sry = sry;
1974                gfx.camera.crx = crx; gfx.camera.srx = srx;
1975                return Ok(Value::Unit);
1976            }
1977
1978            // ── set_projection(cx, cy, focal, zdist) — override projection params ──
1979            // Automatically set when the window opens; override only if needed.
1980            "set_projection" | "ตั้งโปรเจกชัน" | "投影" | "投影設定" | "투영설정" => {
1981                let cx    = self.arg_num(&args, 0, 960.0)? as f32;
1982                let cy    = self.arg_num(&args, 1, 540.0)? as f32;
1983                let focal = self.arg_num(&args, 2, 1080.0)? as f32;
1984                let zdist = self.arg_num(&args, 3, 5.0)? as f32;
1985                let mut gfx = self.gfx.borrow_mut();
1986                gfx.camera.cx    = cx;
1987                gfx.camera.cy    = cy;
1988                gfx.camera.focal = focal;
1989                gfx.camera.zdist = zdist;
1990                return Ok(Value::Unit);
1991            }
1992
1993            // ── draw_mesh(pos, idx, ox, oy, oz, scale, mode) ──
1994            //   Native batched triangle mesh. pos = flat [x,y,z,…], idx = flat tri indices.
1995            //   mode 0 = lit with current pen colour; 1 = per-face hue cycle.
1996            //   Vertices are batch-projected via ling-gpu (CPU fallback, or CUDA when the
1997            //   `cuda` feature is on); the per-triangle loop runs natively (not in the
1998            //   interpreter) so dense meshes (imported glTF, grids) stay fast.
1999            "draw_mesh" | "วาดเมช" => {
2000                let pos = match args.first() { Some(Value::List(v)) => v, _ => return Ok(Value::Unit) };
2001                let idx = match args.get(1)   { Some(Value::List(v)) => v, _ => return Ok(Value::Unit) };
2002                let ox = self.arg_num(&args,2,0.0)? as f32;
2003                let oy = self.arg_num(&args,3,0.0)? as f32;
2004                let oz = self.arg_num(&args,4,0.0)? as f32;
2005                let scale = self.arg_num(&args,5,1.0)? as f32;
2006                let mode = self.arg_num(&args,6,0.0)? as i64;
2007                let nv = pos.len() / 3;
2008                if nv == 0 { return Ok(Value::Unit); }
2009                let mut world = vec![0.0f32; nv*3];
2010                for i in 0..nv {
2011                    world[i*3]   = ox + self.to_number(&pos[i*3]).unwrap_or(0.0)   as f32 * scale;
2012                    world[i*3+1] = oy + self.to_number(&pos[i*3+1]).unwrap_or(0.0) as f32 * scale;
2013                    world[i*3+2] = oz + self.to_number(&pos[i*3+2]).unwrap_or(0.0) as f32 * scale;
2014                }
2015                let mut gfx = self.gfx.borrow_mut();
2016                let cp = {
2017                    let c = &gfx.camera;
2018                    ling_gpu::CameraParams { cry:c.cry, sry:c.sry, crx:c.crx, srx:c.srx, cx:c.cx, cy:c.cy, focal:c.focal, zdist:c.zdist, tx:c.tx, ty:c.ty, tz:c.tz }
2019                };
2020                let near = -gfx.camera.zdist + 0.02;
2021                let base = gfx.color;
2022                let ambient = gfx.ambient;
2023                let mut proj = vec![0.0f32; nv*3];   // (sx, sy, depth) per vertex
2024                ling_gpu::backend().project_points(&world, &cp, &mut proj);
2025                let nt = idx.len() / 3;
2026                for t in 0..nt {
2027                    let ia = self.to_number(&idx[t*3]).unwrap_or(0.0)   as usize;
2028                    let ib = self.to_number(&idx[t*3+1]).unwrap_or(0.0) as usize;
2029                    let ic = self.to_number(&idx[t*3+2]).unwrap_or(0.0) as usize;
2030                    if ia>=nv || ib>=nv || ic>=nv { continue; }
2031                    let (da, db, dc) = (proj[ia*3+2], proj[ib*3+2], proj[ic*3+2]);
2032                    if (da+db+dc)/3.0 <= near { continue; }   // near-plane cull (centroid)
2033                    let col = if mode == 1 {
2034                        let h = t as f32 * 0.6;
2035                        let r = ((h.sin()*0.5+0.5)*150.0+55.0) as u32;
2036                        let g = (((h+2.094).sin()*0.5+0.5)*150.0+55.0) as u32;
2037                        let b = (((h+4.189).sin()*0.5+0.5)*150.0+55.0) as u32;
2038                        (r<<16)|(g<<8)|b
2039                    } else {
2040                        let (ax,ay,az)=(world[ia*3],world[ia*3+1],world[ia*3+2]);
2041                        let (bx,by,bz)=(world[ib*3],world[ib*3+1],world[ib*3+2]);
2042                        let (px,py,pz)=(world[ic*3],world[ic*3+1],world[ic*3+2]);
2043                        let (ux,uy,uz)=(bx-ax,by-ay,bz-az);
2044                        let (vx,vy,vz)=(px-ax,py-ay,pz-az);
2045                        let normal=[uy*vz-uz*vy, uz*vx-ux*vz, ux*vy-uy*vx];
2046                        let centroid=[(ax+bx+px)/3.0,(ay+by+py)/3.0,(az+bz+pz)/3.0];
2047                        crate::gfx::light::compute_lit_color(base, normal, centroid, &gfx.lights, ambient)
2048                    };
2049                    let depth = (da+db+dc)/3.0;
2050                    let col = gfx.fog_apply(col, depth);
2051                    gfx.depth_queue.push_triangle(depth, col, proj[ia*3], proj[ia*3+1], proj[ib*3], proj[ib*3+1], proj[ic*3], proj[ic*3+1]);
2052                }
2053                return Ok(Value::Unit);
2054            }
2055
2056            // ── add_light(x, y, z, r, g, b, intensity, radius) ──
2057            // Adds a point light in world space.  r/g/b in [0..1].
2058            // radius == 0 → no distance falloff.
2059            "add_light" | "เพิ่มแสง" | "加灯" | "ライト追加" | "조명추가" => {
2060                let x   = self.arg_num(&args, 0, 0.0)? as f32;
2061                let y   = self.arg_num(&args, 1, -3.0)? as f32;
2062                let z   = self.arg_num(&args, 2, 3.0)? as f32;
2063                let mut r   = self.arg_num(&args, 3, 1.0)? as f32;
2064                let mut g   = self.arg_num(&args, 4, 1.0)? as f32;
2065                let mut b   = self.arg_num(&args, 5, 1.0)? as f32;
2066                // Forgive 0-255 colour values: if any channel is clearly > 1,
2067                // treat the triple as 0-255 and normalise. Keeps 0-1 callers exact.
2068                if r > 1.5 || g > 1.5 || b > 1.5 { r/=255.0; g/=255.0; b/=255.0; }
2069                let intensity = self.arg_num(&args, 6, 1.0)? as f32;
2070                let radius    = self.arg_num(&args, 7, 0.0)? as f32;
2071                self.gfx.borrow_mut().lights.push(Light { x, y, z, r, g, b, intensity, radius });
2072                return Ok(Value::Unit);
2073            }
2074
2075            // ── clear_lights() — remove all lights ──
2076            "clear_lights" | "ล้างแสง" | "清灯" | "ライト消去" | "조명초기화" => {
2077                self.gfx.borrow_mut().lights.clear();
2078                return Ok(Value::Unit);
2079            }
2080
2081            // ── set_ambient(v) — ambient light level [0..1] ──
2082            "set_ambient" | "ตั้งแสงรอบข้าง" | "环境光" | "環境光設定" | "환경광설정" => {
2083                let v = self.arg_num(&args, 0, 0.15)? as f32;
2084                self.gfx.borrow_mut().ambient = v;
2085                return Ok(Value::Unit);
2086            }
2087
2088            // ── set_fog(r,g,b, start, end) — distance fog toward (r,g,b).
2089            //    triangles/lines fade from `start`..`end` camera depth. end<=0 = off.
2090            "set_fog" | "ตั้งหมอก" | "雾" | "霧設定" | "안개설정" => {
2091                let r = self.arg_num(&args, 0, 0.0)?.clamp(0.0, 255.0) as u32;
2092                let g = self.arg_num(&args, 1, 0.0)?.clamp(0.0, 255.0) as u32;
2093                let b = self.arg_num(&args, 2, 0.0)?.clamp(0.0, 255.0) as u32;
2094                let start = self.arg_num(&args, 3, 0.0)? as f32;
2095                let end   = self.arg_num(&args, 4, 0.0)? as f32;
2096                let mut gfx = self.gfx.borrow_mut();
2097                gfx.fog_color = (r << 16) | (g << 8) | b;
2098                gfx.fog_start = start;
2099                gfx.fog_end   = end;
2100                return Ok(Value::Unit);
2101            }
2102
2103            // ── วาดสามเหลี่ยม3มิติ(ax,ay,az, bx,by,bz, cx,cy,cz) ──
2104            // Computes lighting from world-space normal + active lights (cel shading),
2105            // projects via the stored camera, and pushes to the depth queue.
2106            "วาดสามเหลี่ยม3มิติ" | "draw_triangle_3d" | "triangle3d" => {
2107                let ax = self.arg_num(&args, 0, 0.0)? as f32;
2108                let ay = self.arg_num(&args, 1, 0.0)? as f32;
2109                let az = self.arg_num(&args, 2, 0.0)? as f32;
2110                let bx = self.arg_num(&args, 3, 0.0)? as f32;
2111                let by = self.arg_num(&args, 4, 0.0)? as f32;
2112                let bz = self.arg_num(&args, 5, 0.0)? as f32;
2113                let cx = self.arg_num(&args, 6, 0.0)? as f32;
2114                let cy = self.arg_num(&args, 7, 0.0)? as f32;
2115                let cz = self.arg_num(&args, 8, 0.0)? as f32;
2116
2117                let mut gfx = self.gfx.borrow_mut();
2118
2119                // World-space face normal  N = (B−A) × (C−A)
2120                let ux = bx-ax; let uy = by-ay; let uz = bz-az;
2121                let vx = cx-ax; let vy = cy-ay; let vz = cz-az;
2122                let normal = [
2123                    uy*vz - uz*vy,
2124                    uz*vx - ux*vz,
2125                    ux*vy - uy*vx,
2126                ];
2127                // World-space centroid
2128                let centroid = [
2129                    (ax+bx+cx)/3.0,
2130                    (ay+by+cy)/3.0,
2131                    (az+bz+cz)/3.0,
2132                ];
2133
2134                // Cel-shaded colour
2135                let lit_color = crate::gfx::light::compute_lit_color(
2136                    gfx.color, normal, centroid, &gfx.lights, gfx.ambient,
2137                );
2138
2139                // ── Near-plane CLIP (Sutherland–Hodgman) ──
2140                // A vertex just in front of the eye divides by ~0 in the perspective
2141                // projection and smears the triangle into a screen-filling fan. The old
2142                // "cull if any vertex past near" still let a vertex sitting just inside
2143                // near blow up. Clipping the triangle to the near plane keeps only the
2144                // in-front portion (finite projection — no fan, no over-cull).
2145                let near = -gfx.camera.zdist + 0.05;
2146                let vw = [
2147                    (ax, ay, az, gfx.camera.depth(ax, ay, az)),
2148                    (bx, by, bz, gfx.camera.depth(bx, by, bz)),
2149                    (cx, cy, cz, gfx.camera.depth(cx, cy, cz)),
2150                ];
2151                let mut poly: Vec<(f32, f32, f32)> = Vec::with_capacity(4);
2152                let mut ei = 0;
2153                while ei < 3 {
2154                    let a = vw[ei];
2155                    let b = vw[(ei + 1) % 3];
2156                    let ain = a.3 > near;
2157                    let bin = b.3 > near;
2158                    if ain { poly.push((a.0, a.1, a.2)); }
2159                    if ain != bin {
2160                        let tt = (near - a.3) / (b.3 - a.3);
2161                        poly.push((a.0 + (b.0 - a.0) * tt, a.1 + (b.1 - a.1) * tt, a.2 + (b.2 - a.2) * tt));
2162                    }
2163                    ei += 1;
2164                }
2165                if poly.len() < 3 { return Ok(Value::Unit); }
2166                // Project the clipped polygon, painter-depth = mean, fan-triangulate.
2167                let proj: Vec<(f32, f32, f32)> =
2168                    poly.iter().map(|p| gfx.camera.project(p.0, p.1, p.2)).collect();
2169                let mut dsum = 0.0f32;
2170                for p in &proj { dsum += p.2; }
2171                let depth = dsum / proj.len() as f32;
2172                let lit_color = gfx.fog_apply(lit_color, depth);
2173                let mut fk = 1;
2174                while fk + 1 < proj.len() {
2175                    gfx.depth_queue.push_triangle(
2176                        depth, lit_color,
2177                        proj[0].0, proj[0].1, proj[fk].0, proj[fk].1, proj[fk + 1].0, proj[fk + 1].1,
2178                    );
2179                    fk += 1;
2180                }
2181                return Ok(Value::Unit);
2182            }
2183
2184            // ── วาดเส้น3มิติ(ax,ay,az, bx,by,bz) ──
2185            // Projects two world-space points via the stored camera and pushes
2186            // a line to the depth queue.
2187            "วาดเส้น3มิติ" | "draw_line_3d" | "line3d" | "画3D线" | "3D線描く" | "3D선그리기" => {
2188                let ax = self.arg_num(&args, 0, 0.0)? as f32;
2189                let ay = self.arg_num(&args, 1, 0.0)? as f32;
2190                let az = self.arg_num(&args, 2, 0.0)? as f32;
2191                let bx = self.arg_num(&args, 3, 0.0)? as f32;
2192                let by = self.arg_num(&args, 4, 0.0)? as f32;
2193                let bz = self.arg_num(&args, 5, 0.0)? as f32;
2194
2195                let mut gfx = self.gfx.borrow_mut();
2196                let color = gfx.color;
2197                // Near-plane clip in 3-D before perspective divide
2198                let near = -gfx.camera.zdist + 0.05;
2199                let mut lax = ax; let mut lay = ay; let mut laz = az;
2200                let mut lbx = bx; let mut lby = by; let mut lbz = bz;
2201                let da_raw = gfx.camera.depth(lax, lay, laz);
2202                let db_raw = gfx.camera.depth(lbx, lby, lbz);
2203                if da_raw <= near && db_raw <= near {
2204                    return Ok(Value::Unit);
2205                }
2206                if da_raw <= near {
2207                    let t = (near - da_raw) / (db_raw - da_raw);
2208                    lax += t * (lbx - lax);
2209                    lay += t * (lby - lay);
2210                    laz += t * (lbz - laz);
2211                } else if db_raw <= near {
2212                    let t = (near - da_raw) / (db_raw - da_raw);
2213                    lbx = lax + t * (lbx - lax);
2214                    lby = lay + t * (lby - lay);
2215                    lbz = laz + t * (lbz - laz);
2216                }
2217                let (sax, say, da) = gfx.camera.project(lax, lay, laz);
2218                let (sbx, sby, db) = gfx.camera.project(lbx, lby, lbz);
2219                let depth = (da + db) / 2.0;
2220                let color = gfx.fog_apply(color, depth);
2221                gfx.depth_queue.push_line(depth, color, sax, say, sbx, sby);
2222                return Ok(Value::Unit);
2223            }
2224
2225            // orb_shell(cx,cy,cz, radius, rot_y, rot_x, density, r,g,b)
2226            //   A single trippy, grayscale, depth-faded vector pattern wound around
2227            //   a sphere — two families of interleaved spherical spirals (a guilloché
2228            //   weave), NOT a lat/long cage. Each segment's brightness follows its
2229            //   facing (front bright, back dim), so it reads as a translucent
2230            //   grayscale "texture" with alpha rather than a hard wireframe; the
2231            //   inner marble shows through. `rot_y`/`rot_x` roll the texture around
2232            //   the orb; `density` = spirals per winding direction. r,g,b tint it
2233            //   (pass a gray like 230,230,230 for pure grayscale).
2234            #[cfg(not(target_arch = "wasm32"))]
2235            "orb_shell" | "球壳" | "オーブ殻" | "오브껍질" | "เปลือกทรงกลม" => {
2236                let cx=self.arg_num(&args,0,0.)? as f32; let cy=self.arg_num(&args,1,0.)? as f32; let cz=self.arg_num(&args,2,0.)? as f32;
2237                let radius=self.arg_num(&args,3,1.0)? as f32;
2238                let ry=self.arg_num(&args,4,0.)? as f32; let rx=self.arg_num(&args,5,0.)? as f32;
2239                let density=(self.arg_num(&args,6,10.)? as i32).clamp(1, 48);
2240                let tr=(self.arg_num(&args,7,230.)? as f32).clamp(0.,255.);
2241                let tg=(self.arg_num(&args,8,230.)? as f32).clamp(0.,255.);
2242                let tb=(self.arg_num(&args,9,235.)? as f32).clamp(0.,255.);
2243                let (cyr, syr) = (ry.cos(), ry.sin());
2244                let (cxr, sxr) = (rx.cos(), rx.sin());
2245                let tau = std::f32::consts::TAU;
2246                let pi = std::f32::consts::PI;
2247                let turns = 6.0_f32;            // how many times each spiral wraps pole→pole
2248                let nseg  = 96;                 // segments per spiral (smoothness)
2249                let inv_r = if radius.abs() > 1e-5 { 1.0 / radius } else { 0.0 };
2250                // a point along a spiral (param u 0..1, start angle theta0, winding dir),
2251                // spun by ry/rx — returns (world point, facing 0..1 where 1 = toward camera)
2252                let pt = |u: f32, theta0: f32, dir: f32| -> ([f32;3], f32) {
2253                    let phi = pi * u;                       // 0..pi  (north → south)
2254                    let th  = dir * turns * tau * u + theta0;
2255                    let (mut x, y, mut z) = (phi.sin()*th.cos()*radius, phi.cos()*radius, phi.sin()*th.sin()*radius);
2256                    let x1 =  x*cyr + z*syr;                // yaw about Y
2257                    let z1 = -x*syr + z*cyr;
2258                    x = x1; z = z1;
2259                    let y2 = y*cxr - z*sxr;                 // pitch about X
2260                    let z2 = y*sxr + z*cxr;
2261                    // facing: camera sits at -zdist looking +z, so smaller z2 = nearer = brighter
2262                    let facing = (0.5 - 0.5 * z2 * inv_r).clamp(0.0, 1.0);
2263                    ([cx + x, cy + y2, cz + z2], facing)
2264                };
2265                let mut gfx = self.gfx.borrow_mut();
2266                let near = -gfx.camera.zdist + 0.05;
2267                // draw one segment (near-clipped) in a grayscale tint scaled by `lum`
2268                let seg = |gfx: &mut crate::gfx::GfxState, a: [f32;3], b: [f32;3], lum: f32| {
2269                    let (mut lax,mut lay,mut laz)=(a[0],a[1],a[2]);
2270                    let (mut lbx,mut lby,mut lbz)=(b[0],b[1],b[2]);
2271                    let da=gfx.camera.depth(lax,lay,laz); let db=gfx.camera.depth(lbx,lby,lbz);
2272                    if da<=near && db<=near { return; }
2273                    if da<=near { let t=(near-da)/(db-da); lax+=t*(lbx-lax); lay+=t*(lby-lay); laz+=t*(lbz-laz); }
2274                    else if db<=near { let t=(near-da)/(db-da); lbx=lax+t*(lbx-lax); lby=lay+t*(lby-lay); lbz=laz+t*(lbz-laz); }
2275                    let (sax,say,da2)=gfx.camera.project(lax,lay,laz);
2276                    let (sbx,sby,db2)=gfx.camera.project(lbx,lby,lbz);
2277                    // grayscale-alpha: front-facing bright, back faded toward black
2278                    let l = (0.12 + 0.88 * lum).clamp(0.0, 1.0);
2279                    let cr=(tr*l) as u32; let cg=(tg*l) as u32; let cb=(tb*l) as u32;
2280                    let color=(cr<<16)|(cg<<8)|cb;
2281                    gfx.depth_queue.push_line((da2+db2)*0.5, color, sax,say, sbx,sby);
2282                };
2283                // two opposite winding directions → a soft guilloché weave (not a cage)
2284                for &dir in &[1.0_f32, -1.0_f32] {
2285                    for s in 0..density {
2286                        let theta0 = s as f32 * tau / density as f32;
2287                        let mut prev = pt(0.0, theta0, dir);
2288                        for k in 1..=nseg {
2289                            let cur = pt(k as f32 / nseg as f32, theta0, dir);
2290                            seg(&mut gfx, prev.0, cur.0, (prev.1 + cur.1) * 0.5);
2291                            prev = cur;
2292                        }
2293                    }
2294                }
2295                return Ok(Value::Unit);
2296            }
2297
2298            // orb_particles(cx,cy,cz, radius, count, t, r,g,b)
2299            //   Fills the VOLUME of a sphere with `count` swirling vector points —
2300            //   like motes suspended inside a snow-globe orb. Points are distributed
2301            //   uniformly through the ball, slowly tumble as a cloud + wobble
2302            //   individually over time `t`, and are depth-shaded (near = bright,
2303            //   far = dim) so the cloud has real volume. Additive, so it layers under
2304            //   a shell / over a liquid marble.
2305            #[cfg(not(target_arch = "wasm32"))]
2306            "orb_particles" | "球内粒子" | "オーブ粒子" | "오브입자" | "อนุภาคทรงกลม" => {
2307                let cx=self.arg_num(&args,0,0.)? as f32; let cy=self.arg_num(&args,1,0.)? as f32; let cz=self.arg_num(&args,2,0.)? as f32;
2308                let radius=self.arg_num(&args,3,1.0)? as f32;
2309                let count=(self.arg_num(&args,4,160.)? as i32).clamp(1, 4000);
2310                let t=self.arg_num(&args,5,0.)? as f32;
2311                let tr=(self.arg_num(&args,6,255.)? as f32).clamp(0.,255.);
2312                let tg=(self.arg_num(&args,7,255.)? as f32).clamp(0.,255.);
2313                let tb=(self.arg_num(&args,8,255.)? as f32).clamp(0.,255.);
2314                let inv_r = if radius.abs() > 1e-5 { 1.0/radius } else { 0.0 };
2315                // cheap deterministic hash → [0,1)
2316                let h = |mut x: u32| -> f32 {
2317                    x = x.wrapping_mul(747796405).wrapping_add(2891336453);
2318                    x = ((x >> ((x >> 28).wrapping_add(4))) ^ x).wrapping_mul(277803737);
2319                    (((x >> 22) ^ x) & 0xFFFFFF) as f32 / 16_777_216.0
2320                };
2321                let tau = std::f32::consts::TAU;
2322                // slow tumble of the whole cloud
2323                let (cyr, syr) = ((t*0.5).cos(), (t*0.5).sin());
2324                let (cxr, sxr) = ((t*0.23).cos(), (t*0.23).sin());
2325                let mut gfx = self.gfx.borrow_mut();
2326                let near = -gfx.camera.zdist + 0.05;
2327                let (sw, sh) = (gfx.width as i32, gfx.height as i32);
2328                for i in 0..count {
2329                    let i = i as u32;
2330                    // uniform-in-volume: r = cbrt(u) * radius; direction from two hashes
2331                    let u  = h(i.wrapping_mul(3) + 1);
2332                    let rr = u.cbrt() * radius * (0.85 + 0.15 * (t*1.3 + i as f32).sin()); // gentle pulse
2333                    let th = h(i.wrapping_mul(3) + 2) * tau + t * (0.3 + 0.5 * h(i*7+5)); // per-mote orbit
2334                    let ph = (h(i.wrapping_mul(3) + 3) * 2.0 - 1.0).acos();               // uniform cos(phi)
2335                    let (mut x, y, mut z) = (rr*ph.sin()*th.cos(), rr*ph.cos(), rr*ph.sin()*th.sin());
2336                    // tumble the cloud (yaw then pitch)
2337                    let x1 = x*cyr + z*syr; let z1 = -x*syr + z*cyr; x = x1; z = z1;
2338                    let y2 = y*cxr - z*sxr; let z2 = y*sxr + z*cxr;
2339                    let (wx, wy, wz) = (cx + x, cy + y2, cz + z2);
2340                    if gfx.camera.depth(wx, wy, wz) <= near { continue; }
2341                    let (sx, sy, dep) = gfx.camera.project(wx, wy, wz);
2342                    let sxi = sx as i32; let syi = sy as i32;
2343                    if sxi < 0 || syi < 0 || sxi >= sw || syi >= sh { continue; }
2344                    // depth-shade: nearer (smaller z2) = brighter
2345                    let facing = (0.5 - 0.5 * z2 * inv_r).clamp(0.15, 1.0);
2346                    let l = facing;
2347                    let cr=(tr*l) as u32; let cg=(tg*l) as u32; let cb=(tb*l) as u32;
2348                    let color=(cr<<16)|(cg<<8)|cb;
2349                    // a 1–2px dot (bigger when near) as a short segment in the depth queue
2350                    let len = if facing > 0.7 { 1.0 } else { 0.0 };
2351                    gfx.depth_queue.push_line(dep, color, sx, sy, sx + len, sy);
2352                }
2353                return Ok(Value::Unit);
2354            }
2355
2356            // project_3d(x,y,z) -> [screen_x, screen_y, depth]; behind the camera
2357            // returns a sentinel ([-99999,-99999, depth]) so scripts can skip it.
2358            // Lets scripts place 2-D overlays (e.g. filled teardrop flames) onto 3-D points.
2359            "project_3d" | "投影3D" | "3D投影" | "3D투영" | "ฉาย3มิติ" => {
2360                let x = self.arg_num(&args,0,0.0)? as f32;
2361                let y = self.arg_num(&args,1,0.0)? as f32;
2362                let z = self.arg_num(&args,2,0.0)? as f32;
2363                let gfx = self.gfx.borrow();
2364                let near = -gfx.camera.zdist + 0.05;
2365                let d = gfx.camera.depth(x, y, z);
2366                if d <= near {
2367                    return Ok(Value::List(vec![Value::Number(-99999.0), Value::Number(-99999.0), Value::Number(d as f64)]));
2368                }
2369                let (sx, sy, depth) = gfx.camera.project(x, y, z);
2370                return Ok(Value::List(vec![Value::Number(sx as f64), Value::Number(sy as f64), Value::Number(depth as f64)]));
2371            }
2372            // draw_poly([x0,y0,x1,y1,…]) — filled 2-D polygon in the current colour,
2373            // honouring the blend mode (additive → translucent glow). Auto-closes.
2374            #[cfg(not(target_arch = "wasm32"))]
2375            "draw_poly" | "填充多边形" | "ポリゴン塗り" | "다각형채우기" | "เติมรูปหลายเหลี่ยม" => {
2376                let mut pts: Vec<[f32; 2]> = Vec::new();
2377                if let Some(Value::List(v)) = args.first() {
2378                    let mut i = 0;
2379                    while i + 1 < v.len() {
2380                        let x = self.to_number(&v[i]).unwrap_or(0.0) as f32;
2381                        let y = self.to_number(&v[i + 1]).unwrap_or(0.0) as f32;
2382                        pts.push([x, y]);
2383                        i += 2;
2384                    }
2385                }
2386                if pts.len() >= 3 {
2387                    if pts[0] != pts[pts.len() - 1] { let p0 = pts[0]; pts.push(p0); } // close
2388                    let mut gfx = self.gfx.borrow_mut();
2389                    let (w, h, color, add) = (gfx.width, gfx.height, gfx.color, gfx.blend == 1);
2390                    crate::gfx::raster::fill_contours_aa(&mut gfx.buffer, w, h, color, add, std::slice::from_ref(&pts));
2391                }
2392                return Ok(Value::Unit);
2393            }
2394
2395            // ══════════════════════════════════════════════════════════════════
2396            // VECTOR TEXTURE BUILTINS  (src/gfx/vtex.rs)
2397            // All patterns are depth-biased so they appear on top of surfaces.
2398            // Plane defined by: centre (cx,cy,cz) + U tangent + V tangent.
2399            // Last two args always: fr (frame f32), hue (phase offset f32).
2400            // ══════════════════════════════════════════════════════════════════
2401
2402            // vtex_grid(cx,cy,cz, ux,uy,uz, vx,vy,vz, cols,rows, cw,ch, fr,hue)
2403            "vtex_grid" | "ลายตาราง" | "纹格" | "格子模様" | "격자무늬" => {
2404                let cx=self.arg_num(&args,0,0.)?as f32; let cy=self.arg_num(&args,1,0.)?as f32; let cz=self.arg_num(&args,2,0.)?as f32;
2405                let ux=self.arg_num(&args,3,1.)?as f32; let uy=self.arg_num(&args,4,0.)?as f32; let uz=self.arg_num(&args,5,0.)?as f32;
2406                let vx=self.arg_num(&args,6,0.)?as f32; let vy=self.arg_num(&args,7,0.)?as f32; let vz=self.arg_num(&args,8,1.)?as f32;
2407                let cols=self.arg_num(&args,9,10.)?as usize; let rows=self.arg_num(&args,10,10.)?as usize;
2408                let cw=self.arg_num(&args,11,1.)?as f32;  let ch=self.arg_num(&args,12,1.)?as f32;
2409                let fr=self.arg_num(&args,13,0.)?as f32;  let hue=self.arg_num(&args,14,0.)?as f32;
2410                let mut gfx = self.gfx.borrow_mut();
2411                let cam = gfx.camera.clone();
2412                crate::gfx::vtex::draw_grid(&mut gfx.depth_queue,&cam, cx,cy,cz, ux,uy,uz, vx,vy,vz, cols,rows,cw,ch, fr,hue);
2413                return Ok(Value::Unit);
2414            }
2415
2416            // vtex_rings(cx,cy,cz, ux,uy,uz, vx,vy,vz, n_rings,n_sides, max_r,twist, fr,hue)
2417            "vtex_rings" | "ลายวงซ้อน" | "纹环" | "同心円" | "동심원" => {
2418                let cx=self.arg_num(&args,0,0.)?as f32; let cy=self.arg_num(&args,1,0.)?as f32; let cz=self.arg_num(&args,2,0.)?as f32;
2419                let ux=self.arg_num(&args,3,1.)?as f32; let uy=self.arg_num(&args,4,0.)?as f32; let uz=self.arg_num(&args,5,0.)?as f32;
2420                let vx=self.arg_num(&args,6,0.)?as f32; let vy=self.arg_num(&args,7,0.)?as f32; let vz=self.arg_num(&args,8,1.)?as f32;
2421                let nr=self.arg_num(&args,9,6.)?as usize; let ns=self.arg_num(&args,10,6.)?as usize;
2422                let mr=self.arg_num(&args,11,3.)?as f32;  let tw=self.arg_num(&args,12,0.)?as f32;
2423                let fr=self.arg_num(&args,13,0.)?as f32;  let hue=self.arg_num(&args,14,0.)?as f32;
2424                let mut gfx = self.gfx.borrow_mut();
2425                let cam = gfx.camera.clone();
2426                crate::gfx::vtex::draw_rings(&mut gfx.depth_queue,&cam, cx,cy,cz, ux,uy,uz, vx,vy,vz, nr,ns,mr,tw, fr,hue);
2427                return Ok(Value::Unit);
2428            }
2429
2430            // vtex_star(cx,cy,cz, ux,uy,uz, vx,vy,vz, n_pts,r_out,r_in, rot_speed, fr,hue)
2431            "vtex_star" | "ลายดาว" | "纹星" | "星模様" | "별무늬" => {
2432                let cx=self.arg_num(&args,0,0.)?as f32; let cy=self.arg_num(&args,1,0.)?as f32; let cz=self.arg_num(&args,2,0.)?as f32;
2433                let ux=self.arg_num(&args,3,1.)?as f32; let uy=self.arg_num(&args,4,0.)?as f32; let uz=self.arg_num(&args,5,0.)?as f32;
2434                let vx=self.arg_num(&args,6,0.)?as f32; let vy=self.arg_num(&args,7,0.)?as f32; let vz=self.arg_num(&args,8,1.)?as f32;
2435                let np=self.arg_num(&args,9,6.)?as usize;
2436                let ro=self.arg_num(&args,10,2.)?as f32; let ri=self.arg_num(&args,11,1.)?as f32;
2437                let rs=self.arg_num(&args,12,0.01)?as f32;
2438                let fr=self.arg_num(&args,13,0.)?as f32; let hue=self.arg_num(&args,14,0.)?as f32;
2439                let mut gfx = self.gfx.borrow_mut();
2440                let cam = gfx.camera.clone();
2441                crate::gfx::vtex::draw_star(&mut gfx.depth_queue,&cam, cx,cy,cz, ux,uy,uz, vx,vy,vz, np,ro,ri,rs, fr,hue);
2442                return Ok(Value::Unit);
2443            }
2444
2445            // vtex_spiral(cx,cy,cz, ux,uy,uz, vx,vy,vz, n_turns,max_r,steps, fr,hue)
2446            "vtex_spiral" | "ลายเกลียว" | "纹螺" | "螺旋" | "나선" => {
2447                let cx=self.arg_num(&args,0,0.)?as f32; let cy=self.arg_num(&args,1,0.)?as f32; let cz=self.arg_num(&args,2,0.)?as f32;
2448                let ux=self.arg_num(&args,3,1.)?as f32; let uy=self.arg_num(&args,4,0.)?as f32; let uz=self.arg_num(&args,5,0.)?as f32;
2449                let vx=self.arg_num(&args,6,0.)?as f32; let vy=self.arg_num(&args,7,0.)?as f32; let vz=self.arg_num(&args,8,1.)?as f32;
2450                let nt=self.arg_num(&args,9,3.)?as f32; let mr=self.arg_num(&args,10,3.)?as f32;
2451                let st=self.arg_num(&args,11,120.)?as usize;
2452                let fr=self.arg_num(&args,12,0.)?as f32; let hue=self.arg_num(&args,13,0.)?as f32;
2453                let mut gfx = self.gfx.borrow_mut();
2454                let cam = gfx.camera.clone();
2455                crate::gfx::vtex::draw_spiral(&mut gfx.depth_queue,&cam, cx,cy,cz, ux,uy,uz, vx,vy,vz, nt,mr,st, fr,hue);
2456                return Ok(Value::Unit);
2457            }
2458
2459            // vtex_flower(cx,cy,cz, ux,uy,uz, vx,vy,vz, radius,n_sides, fr,hue)
2460            "vtex_flower" | "ลายดอก" | "纹花" | "花模様" | "꽃무늬" => {
2461                let cx=self.arg_num(&args,0,0.)?as f32; let cy=self.arg_num(&args,1,0.)?as f32; let cz=self.arg_num(&args,2,0.)?as f32;
2462                let ux=self.arg_num(&args,3,1.)?as f32; let uy=self.arg_num(&args,4,0.)?as f32; let uz=self.arg_num(&args,5,0.)?as f32;
2463                let vx=self.arg_num(&args,6,0.)?as f32; let vy=self.arg_num(&args,7,0.)?as f32; let vz=self.arg_num(&args,8,1.)?as f32;
2464                let r=self.arg_num(&args,9,1.)?as f32; let ns=self.arg_num(&args,10,24.)?as usize;
2465                let fr=self.arg_num(&args,11,0.)?as f32; let hue=self.arg_num(&args,12,0.)?as f32;
2466                let mut gfx = self.gfx.borrow_mut();
2467                let cam = gfx.camera.clone();
2468                crate::gfx::vtex::draw_flower(&mut gfx.depth_queue,&cam, cx,cy,cz, ux,uy,uz, vx,vy,vz, r,ns, fr,hue);
2469                return Ok(Value::Unit);
2470            }
2471
2472            // vtex_letter_rain(cx,cy,cz, ux,uy,uz, vx,vy,vz, n_cols,n_vis, col_w,row_h, speed, fr,hue)
2473            "vtex_letter_rain" | "ลายอักษรไหล" | "纹字雨" | "文字雨" | "글자비" => {
2474                let cx=self.arg_num(&args,0,0.)?as f32; let cy=self.arg_num(&args,1,0.)?as f32; let cz=self.arg_num(&args,2,0.)?as f32;
2475                let ux=self.arg_num(&args,3,1.)?as f32; let uy=self.arg_num(&args,4,0.)?as f32; let uz=self.arg_num(&args,5,0.)?as f32;
2476                let vx=self.arg_num(&args,6,0.)?as f32; let vy=self.arg_num(&args,7,0.)?as f32; let vz=self.arg_num(&args,8,1.)?as f32;
2477                let nc=self.arg_num(&args,9,16.)?as usize; let nv=self.arg_num(&args,10,14.)?as usize;
2478                let cw=self.arg_num(&args,11,0.65)?as f32; let rh=self.arg_num(&args,12,0.60)?as f32;
2479                let sp=self.arg_num(&args,13,0.025)?as f32;
2480                let fr=self.arg_num(&args,14,0.)?as f32; let hue=self.arg_num(&args,15,0.)?as f32;
2481                let mut gfx = self.gfx.borrow_mut();
2482                let cam = gfx.camera.clone();
2483                crate::gfx::vtex::draw_letter_rain(&mut gfx.depth_queue,&cam, cx,cy,cz, ux,uy,uz, vx,vy,vz, nc,nv,cw,rh,sp, fr,hue);
2484                return Ok(Value::Unit);
2485            }
2486
2487            // vtex_hyperbolic_uv(cx,cy,cz, ux,uy,uz, vx,vy,vz, max_r,n_circles,n_rays, fr,hue)
2488            "vtex_hyperbolic_uv" | "ลายไฮเพอร์โบลิก" | "纹曲面" | "双曲線" | "쌍곡선" => {
2489                let cx=self.arg_num(&args,0,0.)?as f32; let cy=self.arg_num(&args,1,0.)?as f32; let cz=self.arg_num(&args,2,0.)?as f32;
2490                let ux=self.arg_num(&args,3,1.)?as f32; let uy=self.arg_num(&args,4,0.)?as f32; let uz=self.arg_num(&args,5,0.)?as f32;
2491                let vx=self.arg_num(&args,6,0.)?as f32; let vy=self.arg_num(&args,7,0.)?as f32; let vz=self.arg_num(&args,8,1.)?as f32;
2492                let mr=self.arg_num(&args,9,5.)?as f32;
2493                let nc=self.arg_num(&args,10,12.)?as usize; let nr=self.arg_num(&args,11,18.)?as usize;
2494                let fr=self.arg_num(&args,12,0.)?as f32; let hue=self.arg_num(&args,13,0.)?as f32;
2495                let mut gfx = self.gfx.borrow_mut();
2496                let cam = gfx.camera.clone();
2497                crate::gfx::vtex::draw_hyperbolic_uv(&mut gfx.depth_queue,&cam, cx,cy,cz, ux,uy,uz, vx,vy,vz, mr,nc,nr, fr,hue);
2498                return Ok(Value::Unit);
2499            }
2500
2501            // vtex_halftone(cx,cy,cz, ux,uy,uz, vx,vy,vz, cols,rows, cell_w,cell_h, density, fr,hue)
2502            "vtex_halftone" | "ลายจุด" | "纹半调" | "網点模様" | "망점" => {
2503                let cx=self.arg_num(&args,0,0.)?as f32; let cy=self.arg_num(&args,1,0.)?as f32; let cz=self.arg_num(&args,2,0.)?as f32;
2504                let ux=self.arg_num(&args,3,1.)?as f32; let uy=self.arg_num(&args,4,0.)?as f32; let uz=self.arg_num(&args,5,0.)?as f32;
2505                let vx=self.arg_num(&args,6,0.)?as f32; let vy=self.arg_num(&args,7,0.)?as f32; let vz=self.arg_num(&args,8,1.)?as f32;
2506                let cols=self.arg_num(&args,9,16.)?as usize; let rows=self.arg_num(&args,10,12.)?as usize;
2507                let cw=self.arg_num(&args,11,0.5)?as f32; let ch=self.arg_num(&args,12,0.5)?as f32;
2508                let dens=self.arg_num(&args,13,0.4)?as f32;
2509                let fr=self.arg_num(&args,14,0.)?as f32; let hue=self.arg_num(&args,15,0.)?as f32;
2510                let mut gfx = self.gfx.borrow_mut();
2511                let cam = gfx.camera.clone();
2512                crate::gfx::vtex::draw_halftone(&mut gfx.depth_queue,&cam, cx,cy,cz, ux,uy,uz, vx,vy,vz, cols,rows,cw,ch,dens, fr,hue);
2513                return Ok(Value::Unit);
2514            }
2515
2516            // vtex_tessellated(cx,cy,cz, ux,uy,uz, vx,vy,vz, cols,rows, cell, amplitude,freq, fr,hue)
2517            "vtex_tessellated" | "ลายตาข่าย" | "纹镶嵌" | "網目模様" | "격자망" => {
2518                let cx=self.arg_num(&args,0,0.)?as f32; let cy=self.arg_num(&args,1,0.)?as f32; let cz=self.arg_num(&args,2,0.)?as f32;
2519                let ux=self.arg_num(&args,3,1.)?as f32; let uy=self.arg_num(&args,4,0.)?as f32; let uz=self.arg_num(&args,5,0.)?as f32;
2520                let vx=self.arg_num(&args,6,0.)?as f32; let vy=self.arg_num(&args,7,0.)?as f32; let vz=self.arg_num(&args,8,1.)?as f32;
2521                let cols=self.arg_num(&args,9,14.)?as usize; let rows=self.arg_num(&args,10,10.)?as usize;
2522                let cell=self.arg_num(&args,11,0.6)?as f32;
2523                let amp=self.arg_num(&args,12,0.25)?as f32; let freq=self.arg_num(&args,13,4.)?as f32;
2524                let fr=self.arg_num(&args,14,0.)?as f32; let hue=self.arg_num(&args,15,0.)?as f32;
2525                let mut gfx = self.gfx.borrow_mut();
2526                let cam = gfx.camera.clone();
2527                crate::gfx::vtex::draw_tessellated(&mut gfx.depth_queue,&cam, cx,cy,cz, ux,uy,uz, vx,vy,vz, cols,rows,cell,amp,freq, fr,hue);
2528                return Ok(Value::Unit);
2529            }
2530
2531            // vtex_lotus(cx,cy,cz, ux,uy,uz, vx,vy,vz, r_inner,r_outer,n_petals, fr,hue)
2532            "vtex_lotus" | "ลายดอกบัว" | "纹莲" | "蓮模様" | "연꽃무늬" => {
2533                let cx=self.arg_num(&args,0,0.)?as f32; let cy=self.arg_num(&args,1,0.)?as f32; let cz=self.arg_num(&args,2,0.)?as f32;
2534                let ux=self.arg_num(&args,3,1.)?as f32; let uy=self.arg_num(&args,4,0.)?as f32; let uz=self.arg_num(&args,5,0.)?as f32;
2535                let vx=self.arg_num(&args,6,0.)?as f32; let vy=self.arg_num(&args,7,0.)?as f32; let vz=self.arg_num(&args,8,1.)?as f32;
2536                let ri=self.arg_num(&args,9,1.)?as f32; let ro=self.arg_num(&args,10,2.)?as f32;
2537                let np=self.arg_num(&args,11,12.)?as usize;
2538                let fr=self.arg_num(&args,12,0.)?as f32; let hue=self.arg_num(&args,13,0.)?as f32;
2539                let mut gfx = self.gfx.borrow_mut();
2540                let cam = gfx.camera.clone();
2541                crate::gfx::vtex::draw_lotus(&mut gfx.depth_queue,&cam, cx,cy,cz, ux,uy,uz, vx,vy,vz, ri,ro,np, fr,hue);
2542                return Ok(Value::Unit);
2543            }
2544
2545            // vtex_chakra(cx,cy,cz, ux,uy,uz, vx,vy,vz, r,n_spokes, fr,hue)
2546            "vtex_chakra" | "ลายจักร" | "纹轮" | "輪模様" | "바퀴무늬" => {
2547                let cx=self.arg_num(&args,0,0.)?as f32; let cy=self.arg_num(&args,1,0.)?as f32; let cz=self.arg_num(&args,2,0.)?as f32;
2548                let ux=self.arg_num(&args,3,1.)?as f32; let uy=self.arg_num(&args,4,0.)?as f32; let uz=self.arg_num(&args,5,0.)?as f32;
2549                let vx=self.arg_num(&args,6,0.)?as f32; let vy=self.arg_num(&args,7,0.)?as f32; let vz=self.arg_num(&args,8,1.)?as f32;
2550                let r=self.arg_num(&args,9,2.)?as f32; let ns=self.arg_num(&args,10,8.)?as usize;
2551                let fr=self.arg_num(&args,11,0.)?as f32; let hue=self.arg_num(&args,12,0.)?as f32;
2552                let mut gfx = self.gfx.borrow_mut();
2553                let cam = gfx.camera.clone();
2554                crate::gfx::vtex::draw_chakra(&mut gfx.depth_queue,&cam, cx,cy,cz, ux,uy,uz, vx,vy,vz, r,ns, fr,hue);
2555                return Ok(Value::Unit);
2556            }
2557
2558            // vtex_yantra(cx,cy,cz, ux,uy,uz, vx,vy,vz, n_layers,max_r, fr,hue)
2559            "vtex_yantra" | "ลายยันต์" | "纹咒" | "護符模様" | "부적무늬" => {
2560                let cx=self.arg_num(&args,0,0.)?as f32; let cy=self.arg_num(&args,1,0.)?as f32; let cz=self.arg_num(&args,2,0.)?as f32;
2561                let ux=self.arg_num(&args,3,1.)?as f32; let uy=self.arg_num(&args,4,0.)?as f32; let uz=self.arg_num(&args,5,0.)?as f32;
2562                let vx=self.arg_num(&args,6,0.)?as f32; let vy=self.arg_num(&args,7,0.)?as f32; let vz=self.arg_num(&args,8,1.)?as f32;
2563                let nl=self.arg_num(&args,9,4.)?as usize; let mr=self.arg_num(&args,10,3.)?as f32;
2564                let fr=self.arg_num(&args,11,0.)?as f32; let hue=self.arg_num(&args,12,0.)?as f32;
2565                let mut gfx = self.gfx.borrow_mut();
2566                let cam = gfx.camera.clone();
2567                crate::gfx::vtex::draw_yantra(&mut gfx.depth_queue,&cam, cx,cy,cz, ux,uy,uz, vx,vy,vz, nl,mr, fr,hue);
2568                return Ok(Value::Unit);
2569            }
2570
2571            // vtex_spiked_cog(cx,cy,cz, ux,uy,uz, vx,vy,vz, n_teeth,r_body,r_spike,r_hub,n_spokes, fr,hue)
2572            "vtex_spiked_cog" | "ฟันเฟืองหนาม" | "纹棘轮" | "歯車模様" | "톱니바퀴" => {
2573                let cx=self.arg_num(&args,0,0.)?as f32; let cy=self.arg_num(&args,1,0.)?as f32; let cz=self.arg_num(&args,2,0.)?as f32;
2574                let ux=self.arg_num(&args,3,1.)?as f32; let uy=self.arg_num(&args,4,0.)?as f32; let uz=self.arg_num(&args,5,0.)?as f32;
2575                let vx=self.arg_num(&args,6,0.)?as f32; let vy=self.arg_num(&args,7,0.)?as f32; let vz=self.arg_num(&args,8,1.)?as f32;
2576                let nt=self.arg_num(&args,9,12.)?as usize; let rb=self.arg_num(&args,10,1.)?as f32;
2577                let rs=self.arg_num(&args,11,1.3)?as f32; let rh=self.arg_num(&args,12,0.2)?as f32;
2578                let ns=self.arg_num(&args,13,6.)?as usize;
2579                let fr=self.arg_num(&args,14,0.)?as f32; let hue=self.arg_num(&args,15,0.)?as f32;
2580                let mut gfx = self.gfx.borrow_mut();
2581                let cam = gfx.camera.clone();
2582                crate::gfx::vtex::draw_spiked_cog(&mut gfx.depth_queue,&cam, cx,cy,cz, ux,uy,uz, vx,vy,vz, nt,rb,rs,rh,ns, fr,hue);
2583                return Ok(Value::Unit);
2584            }
2585
2586            // vtex_torii(cx,cy,cz, ux,uy,uz, vx,vy,vz, width,height, fr,hue)
2587            "vtex_torii" | "ประตูโทริอิ" | "纹鸟居" | "鳥居" | "도리이" => {
2588                let cx=self.arg_num(&args,0,0.)?as f32; let cy=self.arg_num(&args,1,0.)?as f32; let cz=self.arg_num(&args,2,0.)?as f32;
2589                let ux=self.arg_num(&args,3,1.)?as f32; let uy=self.arg_num(&args,4,0.)?as f32; let uz=self.arg_num(&args,5,0.)?as f32;
2590                let vx=self.arg_num(&args,6,0.)?as f32; let vy=self.arg_num(&args,7,0.)?as f32; let vz=self.arg_num(&args,8,1.)?as f32;
2591                let w=self.arg_num(&args,9,4.)?as f32; let h=self.arg_num(&args,10,5.)?as f32;
2592                let fr=self.arg_num(&args,11,0.)?as f32; let hue=self.arg_num(&args,12,0.)?as f32;
2593                let mut gfx = self.gfx.borrow_mut();
2594                let cam = gfx.camera.clone();
2595                crate::gfx::vtex::draw_torii(&mut gfx.depth_queue,&cam, cx,cy,cz, ux,uy,uz, vx,vy,vz, w,h, fr,hue);
2596                return Ok(Value::Unit);
2597            }
2598
2599            // vtex_pagoda(cx,cy,cz, ux,uy,uz, vx,vy,vz, n_tiers,base_w,tier_h,taper,eave_out, fr,hue)
2600            "vtex_pagoda" | "เจดีย์" | "纹塔" | "塔" | "탑" => {
2601                let cx=self.arg_num(&args,0,0.)?as f32; let cy=self.arg_num(&args,1,0.)?as f32; let cz=self.arg_num(&args,2,0.)?as f32;
2602                let ux=self.arg_num(&args,3,1.)?as f32; let uy=self.arg_num(&args,4,0.)?as f32; let uz=self.arg_num(&args,5,0.)?as f32;
2603                let vx=self.arg_num(&args,6,0.)?as f32; let vy=self.arg_num(&args,7,0.)?as f32; let vz=self.arg_num(&args,8,1.)?as f32;
2604                let nt=self.arg_num(&args,9,5.)?as usize; let bw=self.arg_num(&args,10,2.)?as f32;
2605                let th=self.arg_num(&args,11,1.)?as f32; let tp=self.arg_num(&args,12,0.72)?as f32;
2606                let eo=self.arg_num(&args,13,0.28)?as f32;
2607                let fr=self.arg_num(&args,14,0.)?as f32; let hue=self.arg_num(&args,15,0.)?as f32;
2608                let mut gfx = self.gfx.borrow_mut();
2609                let cam = gfx.camera.clone();
2610                crate::gfx::vtex::draw_pagoda(&mut gfx.depth_queue,&cam, cx,cy,cz, ux,uy,uz, vx,vy,vz, nt,bw,th,tp,eo, fr,hue);
2611                return Ok(Value::Unit);
2612            }
2613
2614            // ══════════════════════════════════════════════════════════════════
2615            // AUDIO BUILTINS
2616            // ══════════════════════════════════════════════════════════════════
2617
2618            // audio_tone(idx, x, y, z, w, freq, amp, lfo_rate, lfo_depth)
2619            #[cfg(not(target_arch = "wasm32"))]
2620            "audio_tone" | "เสียงโทน" | "音调" | "音調" | "음조" | "空间音" | "空間音" | "공간음" => {
2621                let idx  = self.arg_num(&args, 0, 0.0)? as usize;
2622                let x    = self.arg_num(&args, 1, 0.0)? as f32;
2623                let y    = self.arg_num(&args, 2, 0.0)? as f32;
2624                let z    = self.arg_num(&args, 3, 0.0)? as f32;
2625                let w    = self.arg_num(&args, 4, 1.0)? as f32;
2626                let freq = self.arg_num(&args, 5, 220.0)? as f32;
2627                let amp  = self.arg_num(&args, 6, 0.15)? as f32;
2628                let lfo_rate  = self.arg_num(&args, 7, 0.5)? as f32;
2629                let lfo_depth = self.arg_num(&args, 8, 0.02)? as f32;
2630                if let Some(audio) = &self.audio {
2631                    audio.set_tone(idx, ToneParams { x, y, z, w, freq, amp, lfo_rate, lfo_depth });
2632                }
2633                return Ok(Value::Unit);
2634            }
2635
2636            #[cfg(not(target_arch = "wasm32"))]
2637            "audio_listener" | "ผู้ฟัง" | "音频监听" | "音声リスナー" | "오디오리스너" => {
2638                let cry = self.arg_num(&args, 0, 1.0)? as f32;
2639                let sry = self.arg_num(&args, 1, 0.0)? as f32;
2640                let crx = self.arg_num(&args, 2, 1.0)? as f32;
2641                let srx = self.arg_num(&args, 3, 0.0)? as f32;
2642                if let Some(audio) = &self.audio {
2643                    audio.set_listener(cry, sry, crx, srx);
2644                }
2645                return Ok(Value::Unit);
2646            }
2647
2648            #[cfg(not(target_arch = "wasm32"))]
2649            "audio_bgm" | "เพลงพื้นหลัง" | "เพลงประกอบ" | "背景乐" | "BGM" | "배경음악" => {
2650                let path = match args.first() {
2651                    Some(Value::Str(s)) => s.clone(),
2652                    _ => return Ok(Value::Unit),
2653                };
2654                let vol = self.arg_num(&args, 1, 0.5)? as f32;
2655                if let Some(audio) = &self.audio {
2656                    audio.load_bgm(&path, vol);
2657                }
2658                return Ok(Value::Unit);
2659            }
2660
2661            #[cfg(not(target_arch = "wasm32"))]
2662            "audio_bgm_volume" | "ระดับเสียงพื้นหลัง" | "ระดับเพลงประกอบ" | "背景乐音量" | "BGM音量" | "배경음악음량" => {
2663                let vol = self.arg_num(&args, 0, 0.5)? as f32;
2664                if let Some(audio) = &self.audio {
2665                    audio.set_bgm_volume(vol);
2666                }
2667                return Ok(Value::Unit);
2668            }
2669
2670            #[cfg(not(target_arch = "wasm32"))]
2671            "audio_volume" | "ระดับเสียง" | "音量" | "음량" => {
2672                let vol = self.arg_num(&args, 0, 0.7)? as f32;
2673                if let Some(audio) = &self.audio {
2674                    audio.set_master_volume(vol);
2675                }
2676                return Ok(Value::Unit);
2677            }
2678
2679            // WASM audio builtins — delegate to Web Audio API
2680            #[cfg(target_arch = "wasm32")]
2681            "audio_tone" | "เสียงโทน" | "音调" | "音調" | "음조" | "空间音" | "空間音" | "공간음" => {
2682                let idx  = self.arg_num(&args, 0, 0.0)? as usize;
2683                let x    = self.arg_num(&args, 1, 0.0)? as f32;
2684                let y    = self.arg_num(&args, 2, 0.0)? as f32;
2685                let z    = self.arg_num(&args, 3, 0.0)? as f32;
2686                let w    = self.arg_num(&args, 4, 1.0)? as f32;
2687                let freq = self.arg_num(&args, 5, 220.0)? as f32;
2688                let amp  = self.arg_num(&args, 6, 0.15)? as f32;
2689                let lfo_rate  = self.arg_num(&args, 7, 0.5)? as f32;
2690                let lfo_depth = self.arg_num(&args, 8, 0.02)? as f32;
2691                crate::gfx::audio_web::set_tone(idx, x, y, z, w, freq, amp, lfo_rate, lfo_depth);
2692                return Ok(Value::Unit);
2693            }
2694
2695            #[cfg(target_arch = "wasm32")]
2696            "audio_listener" | "ผู้ฟัง" | "音频监听" | "音声リスナー" | "오디오리스너" => {
2697                let cry = self.arg_num(&args, 0, 1.0)? as f32;
2698                let sry = self.arg_num(&args, 1, 0.0)? as f32;
2699                let crx = self.arg_num(&args, 2, 1.0)? as f32;
2700                let srx = self.arg_num(&args, 3, 0.0)? as f32;
2701                crate::gfx::audio_web::set_listener(cry, sry, crx, srx);
2702                return Ok(Value::Unit);
2703            }
2704
2705            #[cfg(target_arch = "wasm32")]
2706            "audio_bgm" | "เพลงพื้นหลัง" | "เพลงประกอบ" | "背景乐" | "BGM" | "배경음악" => {
2707                let path = self.arg_str(&args, 0, "");
2708                let vol  = self.arg_num(&args, 1, 0.5)? as f32;
2709                crate::gfx::audio_web::load_bgm(&path, vol);
2710                return Ok(Value::Unit);
2711            }
2712
2713            #[cfg(target_arch = "wasm32")]
2714            "audio_bgm_volume" | "ระดับเสียงพื้นหลัง" | "ระดับเพลงประกอบ" | "背景乐音量" | "BGM音量" | "배경음악음량" => {
2715                let vol = self.arg_num(&args, 0, 0.5)? as f32;
2716                crate::gfx::audio_web::set_bgm_volume(vol);
2717                return Ok(Value::Unit);
2718            }
2719
2720            #[cfg(target_arch = "wasm32")]
2721            "audio_volume" | "ระดับเสียง" | "音量" | "음량" => {
2722                let vol = self.arg_num(&args, 0, 0.7)? as f32;
2723                crate::gfx::audio_web::set_master_volume(vol);
2724                return Ok(Value::Unit);
2725            }
2726
2727            // ── รอหน้าต่าง() — block until window closed / Escape ──
2728            "รอหน้าต่าง" | "wait_window" | "gfx_wait" => {
2729                #[cfg(not(target_arch = "wasm32"))]
2730                loop {
2731                    let still_open = {
2732                        let gfx = self.gfx.borrow();
2733                        gfx.window.as_ref()
2734                            .map(|w| w.is_open() && !w.is_key_down(minifb::Key::Escape))
2735                            .unwrap_or(false)
2736                    };
2737                    if !still_open { break; }
2738                    let (buf, w, h) = {
2739                        let gfx = self.gfx.borrow();
2740                        (gfx.buffer.clone(), gfx.width, gfx.height)
2741                    };
2742                    let mut gfx = self.gfx.borrow_mut();
2743                    if let Some(win) = gfx.window.as_mut() {
2744                        if win.update_with_buffer(&buf, w, h).is_err() { break; }
2745                    }
2746                }
2747                return Ok(Value::Unit);
2748            }
2749
2750            // ── File I/O ──────────────────────────────────────────────────────
2751            "read_file" | "อ่านไฟล์" => {
2752                let path = self.arg_str(&args, 0, "");
2753                return std::fs::read_to_string(&path)
2754                    .map(Value::Str)
2755                    .map_err(|e| EvalErr::from(format!("read_file '{path}': {e}")));
2756            }
2757            // ── networking (TCP, 2-peer co-op) ───────────────────────────────
2758            #[cfg(not(target_arch = "wasm32"))]
2759            "net_host" | "เน็ตโฮสต์" => {
2760                let port = self.arg_num(&args, 0, 7777.0)? as u16;
2761                net::host(port);
2762                return Ok(Value::Unit);
2763            }
2764            #[cfg(not(target_arch = "wasm32"))]
2765            "net_join" | "เน็ตจอย" => {
2766                let ip   = self.arg_str(&args, 0, "127.0.0.1");
2767                let port = self.arg_num(&args, 1, 7777.0)? as u16;
2768                net::join(&ip, port);
2769                return Ok(Value::Unit);
2770            }
2771            #[cfg(not(target_arch = "wasm32"))]
2772            "net_send" | "เน็ตส่ง" => {
2773                let s = self.arg_str(&args, 0, "");
2774                net::send(&s);
2775                return Ok(Value::Unit);
2776            }
2777            #[cfg(not(target_arch = "wasm32"))]
2778            "net_recv" | "เน็ตรับ" => {
2779                return Ok(Value::Str(net::recv()));
2780            }
2781            #[cfg(not(target_arch = "wasm32"))]
2782            "net_status" | "เน็ตสถานะ" => {
2783                return Ok(Value::Number(net::status() as f64));
2784            }
2785
2786            // ── game AI: neural networks ─────────────────────────────────────
2787            // nn_new(inputs[, seed]) → handle
2788            #[cfg(not(target_arch = "wasm32"))]
2789            "nn_new" | "建神经网" | "ニューラル作成" | "신경망생성" | "สร้างโครงข่าย" => {
2790                let n_in = self.arg_num(&args, 0, 1.0)?.max(0.0) as usize;
2791                let seed = self.arg_num(&args, 1, 1.0)? as u64;
2792                return Ok(Value::Number(ai::nn_new(n_in, seed) as f64));
2793            }
2794            // nn_dense(handle, units[, activation]) — append a layer
2795            #[cfg(not(target_arch = "wasm32"))]
2796            "nn_dense" | "密集层" | "密層追加" | "밀집층" | "ชั้นหนาแน่น" => {
2797                let id    = self.arg_num(&args, 0, -1.0)? as i64;
2798                let units = self.arg_num(&args, 1, 1.0)?.max(1.0) as usize;
2799                let act   = self.arg_str(&args, 2, "relu");
2800                ai::nn_dense(id, units, &act);
2801                return Ok(Value::Unit);
2802            }
2803            // nn_forward(handle, [inputs]) → [outputs]
2804            #[cfg(not(target_arch = "wasm32"))]
2805            "nn_forward" | "神经前向" | "順伝播" | "순전파" | "ส่งต่อโครงข่าย" => {
2806                let id = self.arg_num(&args, 0, -1.0)? as i64;
2807                let input = self.arg_list_f32(&args, 1);
2808                let out = ai::nn_forward(id, &input);
2809                return Ok(Value::List(out.into_iter().map(|v| Value::Number(v as f64)).collect()));
2810            }
2811            // nn_train(handle, [inputs], [targets][, lr]) → loss
2812            #[cfg(not(target_arch = "wasm32"))]
2813            "nn_train" | "训练网" | "ニューラル学習" | "신경망학습" | "ฝึกโครงข่าย" => {
2814                let id     = self.arg_num(&args, 0, -1.0)? as i64;
2815                let input  = self.arg_list_f32(&args, 1);
2816                let target = self.arg_list_f32(&args, 2);
2817                let lr     = self.arg_num(&args, 3, 0.01)? as f32;
2818                return Ok(Value::Number(ai::nn_train(id, &input, &target, lr) as f64));
2819            }
2820            // nn_save(handle, path) → bool
2821            #[cfg(not(target_arch = "wasm32"))]
2822            "nn_save" | "保存网" | "網保存" | "신경망저장" | "บันทึกโครงข่าย" => {
2823                let id   = self.arg_num(&args, 0, -1.0)? as i64;
2824                let path = self.arg_str(&args, 1, "model.lnn");
2825                return Ok(Value::Bool(ai::nn_save(id, &path)));
2826            }
2827            // nn_load(path) → handle (-1 on failure)
2828            #[cfg(not(target_arch = "wasm32"))]
2829            "nn_load" | "载入网" | "網読込" | "신경망불러오기" | "โหลดโครงข่าย" => {
2830                let path = self.arg_str(&args, 0, "model.lnn");
2831                return Ok(Value::Number(ai::nn_load(&path) as f64));
2832            }
2833
2834            // ── game AI: behavior trees ──────────────────────────────────────
2835            // bt_build(dsl_string) → handle
2836            #[cfg(not(target_arch = "wasm32"))]
2837            "bt_build" | "建行为树" | "行動木構築" | "행동트리구성" | "สร้างต้นไม้พฤติกรรม" => {
2838                let spec = self.arg_str(&args, 0, "");
2839                return Ok(Value::Number(ai::bt_build(&spec) as f64));
2840            }
2841            // bt_set(handle, key, value) — set a blackboard fact
2842            #[cfg(not(target_arch = "wasm32"))]
2843            "bt_set" | "设事实" | "事実設定" | "사실설정" | "ตั้งข้อเท็จจริง" => {
2844                let id  = self.arg_num(&args, 0, -1.0)? as i64;
2845                let key = self.arg_str(&args, 1, "");
2846                let val = self.arg_num(&args, 2, 0.0)? as f32;
2847                ai::bt_set(id, &key, val);
2848                return Ok(Value::Unit);
2849            }
2850            // bt_tick(handle) → chosen action name ("" if none)
2851            #[cfg(not(target_arch = "wasm32"))]
2852            "bt_tick" | "行为树滴答" | "行動木更新" | "행동트리틱" | "เดินต้นไม้พฤติกรรม" => {
2853                let id = self.arg_num(&args, 0, -1.0)? as i64;
2854                return Ok(Value::Str(ai::bt_tick(id)));
2855            }
2856            // bt_status(handle) → 0 fail / 1 success / 2 running
2857            #[cfg(not(target_arch = "wasm32"))]
2858            "bt_status" | "行为树状态" | "行動木状態" | "행동트리상태" | "สถานะต้นไม้พฤติกรรม" => {
2859                let id = self.arg_num(&args, 0, -1.0)? as i64;
2860                return Ok(Value::Number(ai::bt_status(id) as f64));
2861            }
2862
2863            // ── game AI: miniature dialog LLM ────────────────────────────────
2864            // dialog_new([ctx, embed, hidden, seed]) → handle
2865            #[cfg(not(target_arch = "wasm32"))]
2866            "dialog_new" | "建对话模型" | "対話モデル作成" | "대화모델생성" | "สร้างโมเดลสนทนา" => {
2867                let ctx    = self.arg_num(&args, 0, 3.0)?.max(1.0) as usize;
2868                let embed  = self.arg_num(&args, 1, 32.0)?.max(1.0) as usize;
2869                let hidden = self.arg_num(&args, 2, 64.0)?.max(1.0) as usize;
2870                let seed   = self.arg_num(&args, 3, 1.0)? as u64;
2871                return Ok(Value::Number(ai::dialog_new(ctx, embed, hidden, seed) as f64));
2872            }
2873            // dialog_learn(handle, text) — add one utterance to the corpus
2874            #[cfg(not(target_arch = "wasm32"))]
2875            "dialog_learn" | "对话学习" | "対話学習" | "대화학습" | "เรียนรู้สนทนา" => {
2876                let id   = self.arg_num(&args, 0, -1.0)? as i64;
2877                let text = self.arg_str(&args, 1, "");
2878                ai::dialog_learn(id, &text);
2879                return Ok(Value::Unit);
2880            }
2881            // dialog_load(handle, path) → lines added (-1 on error)
2882            #[cfg(not(target_arch = "wasm32"))]
2883            "dialog_load" | "对话载入" | "対話読込" | "대화불러오기" | "โหลดชุดสนทนา" => {
2884                let id   = self.arg_num(&args, 0, -1.0)? as i64;
2885                let path = self.arg_str(&args, 1, "");
2886                return Ok(Value::Number(ai::dialog_load(id, &path) as f64));
2887            }
2888            // dialog_train(handle[, epochs, lr]) → loss
2889            #[cfg(not(target_arch = "wasm32"))]
2890            "dialog_train" | "对话训练" | "対話訓練" | "대화훈련" | "ฝึกสนทนา" => {
2891                let id     = self.arg_num(&args, 0, -1.0)? as i64;
2892                let epochs = self.arg_num(&args, 1, 20.0)?.max(1.0) as usize;
2893                let lr     = self.arg_num(&args, 2, 0.1)? as f32;
2894                return Ok(Value::Number(ai::dialog_train(id, epochs, lr) as f64));
2895            }
2896            // dialog_say(handle, prompt[, max_tokens, temperature]) → reply text
2897            #[cfg(not(target_arch = "wasm32"))]
2898            "dialog_say" | "对话生成" | "対話生成" | "대화생성" | "พูดสนทนา" => {
2899                let id     = self.arg_num(&args, 0, -1.0)? as i64;
2900                let prompt = self.arg_str(&args, 1, "");
2901                let max    = self.arg_num(&args, 2, 24.0)?.max(1.0) as usize;
2902                let temp   = self.arg_num(&args, 3, 0.8)? as f32;
2903                return Ok(Value::Str(ai::dialog_say(id, &prompt, max, temp)));
2904            }
2905            // dialog_save(handle, path) → bool
2906            #[cfg(not(target_arch = "wasm32"))]
2907            "dialog_save" | "对话存模" | "対話モデル保存" | "대화모델저장" | "บันทึกโมเดลสนทนา" => {
2908                let id   = self.arg_num(&args, 0, -1.0)? as i64;
2909                let path = self.arg_str(&args, 1, "model.llm");
2910                return Ok(Value::Bool(ai::dialog_save(id, &path)));
2911            }
2912            // dialog_load_model(path) → handle (-1 on failure)
2913            #[cfg(not(target_arch = "wasm32"))]
2914            "dialog_load_model" | "对话载模" | "対話モデル読込" | "대화모델불러오기" | "โหลดโมเดลสนทนา" => {
2915                let path = self.arg_str(&args, 0, "model.llm");
2916                return Ok(Value::Number(ai::dialog_load_model(&path) as f64));
2917            }
2918
2919            "write_file" | "เขียนไฟล์" => {
2920                let path    = self.arg_str(&args, 0, "");
2921                let content = self.arg_str(&args, 1, "");
2922                std::fs::write(&path, content.as_bytes())
2923                    .map_err(|e| EvalErr::from(format!("write_file '{path}': {e}")))?;
2924                return Ok(Value::Unit);
2925            }
2926            "print_file" | "พิมพ์ไฟล์" => {
2927                let content = self.arg_str(&args, 0, "");
2928                print!("{content}");
2929                return Ok(Value::Unit);
2930            }
2931
2932            // ── CLI arguments ─────────────────────────────────────────────────
2933            "get_args" | "รับอาร์กิวเมนต์" => {
2934                let v: Vec<Value> = std::env::args().map(Value::Str).collect();
2935                return Ok(Value::List(v));
2936            }
2937
2938            // ── String utilities ──────────────────────────────────────────────
2939            "split" | "str_split" | "แยก" => {
2940                let s   = self.arg_str(&args, 0, "");
2941                let sep = self.arg_str(&args, 1, "\n");
2942                let sep = if sep.is_empty() { "\n".into() } else { sep };
2943                let parts: Vec<Value> = s.split(sep.as_str())
2944                    .map(|p| Value::Str(p.to_string())).collect();
2945                return Ok(Value::List(parts));
2946            }
2947            "trim" | "str_trim" | "ตัดช่องว่าง" => {
2948                let s = self.arg_str(&args, 0, "");
2949                return Ok(Value::Str(s.trim().to_string()));
2950            }
2951            "starts_with" | "str_starts_with" | "เริ่มด้วย" => {
2952                let s      = self.arg_str(&args, 0, "");
2953                let prefix = self.arg_str(&args, 1, "");
2954                return Ok(Value::Bool(s.starts_with(prefix.as_str())));
2955            }
2956            "ends_with" | "str_ends_with" | "ลงท้ายด้วย" => {
2957                let s      = self.arg_str(&args, 0, "");
2958                let suffix = self.arg_str(&args, 1, "");
2959                return Ok(Value::Bool(s.ends_with(suffix.as_str())));
2960            }
2961            "str_replace" | "แทนสตริง" => {
2962                let s    = self.arg_str(&args, 0, "");
2963                let from = self.arg_str(&args, 1, "");
2964                let to   = self.arg_str(&args, 2, "");
2965                return Ok(Value::Str(s.replace(from.as_str(), to.as_str())));
2966            }
2967            "str_find" | "หาในสตริง" => {
2968                let s      = self.arg_str(&args, 0, "");
2969                let needle = self.arg_str(&args, 1, "");
2970                // Return char index (not byte index) for consistency with substr
2971                let pos = s.find(needle.as_str())
2972                    .map(|byte_i| s[..byte_i].chars().count() as f64)
2973                    .unwrap_or(-1.0);
2974                return Ok(Value::Number(pos));
2975            }
2976            "substr" | "str_slice" | "ส่วนสตริง" => {
2977                let s     = self.arg_str(&args, 0, "");
2978                let start = self.arg_num(&args, 1, 0.0)? as usize;
2979                let len   = args.get(2)
2980                    .map(|v| self.to_number(v).unwrap_or(999999.0) as usize)
2981                    .unwrap_or_else(|| s.chars().count().saturating_sub(start));
2982                let chars: Vec<char> = s.chars().collect();
2983                let end   = (start + len).min(chars.len());
2984                let slice: String = chars.get(start..end).unwrap_or(&[]).iter().collect();
2985                return Ok(Value::Str(slice));
2986            }
2987            "to_str" | "str" | "num_str" | "แปลงสตริง" => {
2988                let v = args.into_iter().next().unwrap_or(Value::Unit);
2989                return Ok(Value::Str(v.to_string()));
2990            }
2991            "str_repeat" | "ทำซ้ำสตริง" => {
2992                let s = self.arg_str(&args, 0, "");
2993                let n = self.arg_num(&args, 1, 1.0)? as usize;
2994                return Ok(Value::Str(s.repeat(n)));
2995            }
2996            "str_upper" => {
2997                let s = self.arg_str(&args, 0, "");
2998                return Ok(Value::Str(s.to_uppercase()));
2999            }
3000            "str_lower" => {
3001                let s = self.arg_str(&args, 0, "");
3002                return Ok(Value::Str(s.to_lowercase()));
3003            }
3004            "str_len" | "len" | "ความยาว" | "长度" | "長さ" | "길이" => {
3005                match args.first() {
3006                    Some(Value::Str(s))  => return Ok(Value::Number(s.chars().count() as f64)),
3007                    Some(Value::List(v)) => return Ok(Value::Number(v.len() as f64)),
3008                    _ => return Ok(Value::Number(0.0)),
3009                }
3010            }
3011
3012            // ── FNV-1a hash (deterministic, normalized 0.0–1.0) ──────────────
3013            "hash_str" | "แฮช" => {
3014                let s = self.arg_str(&args, 0, "");
3015                let mut h: u64 = 14695981039346656037_u64;
3016                for b in s.bytes() { h ^= b as u64; h = h.wrapping_mul(1099511628211); }
3017                return Ok(Value::Number((h & 0xFFFFFF) as f64 / 16777215.0));
3018            }
3019            "hash_int" | "แฮชจำนวน" => {
3020                let s = self.arg_str(&args, 0, "");
3021                let n = self.arg_num(&args, 1, 100.0)? as u64;
3022                let mut h: u64 = 14695981039346656037_u64;
3023                for b in s.bytes() { h ^= b as u64; h = h.wrapping_mul(1099511628211); }
3024                return Ok(Value::Number((h % n.max(1)) as f64));
3025            }
3026
3027            // ── List utilities ────────────────────────────────────────────────
3028            "list_new" | "รายการใหม่" | "新建列表" | "新規リスト" | "새목록" => {
3029                return Ok(Value::List(Vec::new()));
3030            }
3031            "list_push" | "เพิ่มรายการ" | "列表添加" | "リスト追加" | "목록추가" => {
3032                let lst = args.first().cloned().unwrap_or(Value::List(vec![]));
3033                let val = args.get(1).cloned().unwrap_or(Value::Unit);
3034                if let Value::List(mut v) = lst { v.push(val); return Ok(Value::List(v)); }
3035                return Ok(Value::List(vec![val]));
3036            }
3037            "list_get" | "รับรายการ" | "取元素" | "要素取得" | "요소가져오기" => {
3038                let lst = args.first().cloned().unwrap_or(Value::List(vec![]));
3039                let i   = self.arg_num(&args, 1, 0.0)? as usize;
3040                if let Value::List(v) = lst {
3041                    return Ok(v.get(i).cloned().unwrap_or(Value::Str(String::new())));
3042                }
3043                return Ok(Value::Str(String::new()));
3044            }
3045            "list_join" | "join" | "รวมรายการ" | "连接" | "連結" | "연결" => {
3046                let lst = args.first().cloned().unwrap_or(Value::List(vec![]));
3047                let sep = args.get(1).map(|v| v.to_string()).unwrap_or_default();
3048                if let Value::List(v) = lst {
3049                    return Ok(Value::Str(v.iter().map(|x| x.to_string())
3050                        .collect::<Vec<_>>().join(&sep)));
3051                }
3052                return Ok(Value::Str(String::new()));
3053            }
3054            // blob_f32("<deflate+base64>") / blob_i32(...) — decode an embedded,
3055            // losslessly-compressed numeric blob into a list. Produced by
3056            // `ling convert`; lets converted assets carry geometry/PCM/etc. compactly.
3057            #[cfg(not(target_arch = "wasm32"))]
3058            "blob_f32" | "blob_i32" => {
3059                let s = self.arg_str(&args, 0, "");
3060                let is_i32 = name == "blob_i32";
3061                match decode_blob(&s) {
3062                    Ok(bytes) => {
3063                        let mut out = Vec::with_capacity(bytes.len() / 4);
3064                        for ch in bytes.chunks_exact(4) {
3065                            let arr = [ch[0], ch[1], ch[2], ch[3]];
3066                            let n = if is_i32 {
3067                                i32::from_le_bytes(arr) as f64
3068                            } else {
3069                                f32::from_le_bytes(arr) as f64
3070                            };
3071                            out.push(Value::Number(n));
3072                        }
3073                        return Ok(Value::List(out));
3074                    }
3075                    Err(e) => {
3076                        eprintln!("blob decode failed: {e}");
3077                        return Ok(Value::List(vec![]));
3078                    }
3079                }
3080            }
3081
3082            // ══════════════════════════════════════════════════════════════════
3083            // SVG EXPORT  (svg_begin / svg_rect / svg_circle / svg_line /
3084            //              svg_polyline / svg_text / svg_end / hsl_color)
3085            // Chinese aliases: 开始SVG 结束SVG SVG矩形 SVG圆形 SVG线段 SVG折线 SVG文本 HSL颜色
3086            // Thai aliases:    เริ่มSVG จบSVG SVGสี่เหลี่ยม SVGวงกลม SVGเส้น SVGเส้นหัก SVGข้อความ สีHSL
3087            // ══════════════════════════════════════════════════════════════════
3088
3089            "svg_begin" | "开始SVG" | "เริ่มSVG" => {
3090                let path   = self.arg_str(&args, 0, "output.svg");
3091                let width  = self.arg_num(&args, 1, 800.0)?;
3092                let height = self.arg_num(&args, 2, 600.0)?;
3093                *self.svg.borrow_mut() = Some(SvgWriter::new(path, width, height));
3094                return Ok(Value::Unit);
3095            }
3096
3097            "svg_rect" | "SVG矩形" | "SVGสี่เหลี่ยม" => {
3098                let x    = self.arg_num(&args, 0, 0.0)?;
3099                let y    = self.arg_num(&args, 1, 0.0)?;
3100                let w    = self.arg_num(&args, 2, 10.0)?;
3101                let h    = self.arg_num(&args, 3, 10.0)?;
3102                let fill = self.arg_str(&args, 4, "#ffffff");
3103                if let Some(svg) = self.svg.borrow_mut().as_mut() {
3104                    svg.elements.push(format!(
3105                        "<rect x=\"{x:.1}\" y=\"{y:.1}\" width=\"{w:.1}\" \
3106                         height=\"{h:.1}\" fill=\"{fill}\"/>"));
3107                }
3108                return Ok(Value::Unit);
3109            }
3110
3111            "svg_circle" | "SVG圆形" | "SVGวงกลม" => {
3112                let cx   = self.arg_num(&args, 0, 0.0)?;
3113                let cy   = self.arg_num(&args, 1, 0.0)?;
3114                let r    = self.arg_num(&args, 2, 5.0)?;
3115                let fill = self.arg_str(&args, 3, "#ffffff");
3116                if let Some(svg) = self.svg.borrow_mut().as_mut() {
3117                    svg.elements.push(format!(
3118                        "<circle cx=\"{cx:.1}\" cy=\"{cy:.1}\" r=\"{r:.1}\" fill=\"{fill}\"/>"));
3119                }
3120                return Ok(Value::Unit);
3121            }
3122
3123            "svg_line" | "SVG线段" | "SVGเส้น" => {
3124                let x1     = self.arg_num(&args, 0, 0.0)?;
3125                let y1     = self.arg_num(&args, 1, 0.0)?;
3126                let x2     = self.arg_num(&args, 2, 0.0)?;
3127                let y2     = self.arg_num(&args, 3, 0.0)?;
3128                let stroke = self.arg_str(&args, 4, "#ffffff");
3129                let sw     = self.arg_num(&args, 5, 1.0)?;
3130                if let Some(svg) = self.svg.borrow_mut().as_mut() {
3131                    svg.elements.push(format!(
3132                        "<line x1=\"{x1:.1}\" y1=\"{y1:.1}\" x2=\"{x2:.1}\" y2=\"{y2:.1}\" \
3133                         stroke=\"{stroke}\" stroke-width=\"{sw:.1}\"/>"));
3134                }
3135                return Ok(Value::Unit);
3136            }
3137
3138            "svg_polyline" | "SVG折线" | "SVGเส้นหัก" => {
3139                let pts    = self.arg_str(&args, 0, "");
3140                let stroke = self.arg_str(&args, 1, "#ffffff");
3141                let sw     = self.arg_num(&args, 2, 1.0)?;
3142                if let Some(svg) = self.svg.borrow_mut().as_mut() {
3143                    svg.elements.push(format!(
3144                        "<polyline points=\"{pts}\" fill=\"none\" \
3145                         stroke=\"{stroke}\" stroke-width=\"{sw:.1}\"/>"));
3146                }
3147                return Ok(Value::Unit);
3148            }
3149
3150            "svg_text" | "SVG文本" | "SVGข้อความ" => {
3151                let x    = self.arg_num(&args, 0, 0.0)?;
3152                let y    = self.arg_num(&args, 1, 0.0)?;
3153                let text = self.arg_str(&args, 2, "");
3154                let fill = self.arg_str(&args, 3, "#ffffff");
3155                let size = self.arg_num(&args, 4, 12.0)?;
3156                if let Some(svg) = self.svg.borrow_mut().as_mut() {
3157                    let safe = text.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;");
3158                    svg.elements.push(format!(
3159                        "<text x=\"{x:.1}\" y=\"{y:.1}\" fill=\"{fill}\" \
3160                         font-family=\"monospace\" font-size=\"{size:.0}\">{safe}</text>"));
3161                }
3162                return Ok(Value::Unit);
3163            }
3164
3165            "svg_end" | "结束SVG" | "จบSVG" => {
3166                {
3167                    let borrow = self.svg.borrow();
3168                    if let Some(svg) = borrow.as_ref() {
3169                        svg.save().map_err(|e| EvalErr::from(format!("svg_end: {e}")))?;
3170                    }
3171                }
3172                *self.svg.borrow_mut() = None;
3173                return Ok(Value::Unit);
3174            }
3175
3176            "hsl_color" | "HSL颜色" | "สีHSL" => {
3177                let h = self.arg_num(&args, 0, 0.0)?;
3178                let s = self.arg_num(&args, 1, 70.0)?;
3179                let l = self.arg_num(&args, 2, 50.0)?;
3180                return Ok(Value::Str(hsl_to_hex(h, s, l)));
3181            }
3182
3183            // ══════════════════════════════════════════════════════════════════
3184            // FFT / AUDIO ANALYSIS BUILTINS  (native only)
3185            // ══════════════════════════════════════════════════════════════════
3186
3187            // fft_push(samples_list) — feed raw audio samples and run FFT
3188            #[cfg(not(target_arch = "wasm32"))]
3189            "fft_push" | "วิเคราะห์เสียง" | "频谱输入" | "FFT入力" | "FFT입력" => {
3190                if let Some(Value::List(v)) = args.first() {
3191                    let samples: Vec<f32> = v.iter()
3192                        .filter_map(|x| if let Value::Number(n) = x { Some(*n as f32) } else { None })
3193                        .collect();
3194                    self.fft.borrow_mut().push_samples(&samples);
3195                }
3196                return Ok(Value::Unit);
3197            }
3198
3199            // fft_bands(n) → list of n log-spaced magnitude bands (0..1)
3200            #[cfg(not(target_arch = "wasm32"))]
3201            "fft_bands" | "แถบความถี่" | "频段" | "周波数帯" | "주파수대" => {
3202                let n = self.arg_num(&args, 0, 32.0)? as usize;
3203                let bands = self.fft.borrow().freq_bands(n);
3204                *self.fft_bands_cache.borrow_mut() = bands.clone();
3205                return Ok(Value::List(bands.into_iter().map(|v| Value::Number(v as f64)).collect()));
3206            }
3207
3208            // fft_beat() → bool
3209            #[cfg(not(target_arch = "wasm32"))]
3210            "fft_beat" | "จังหวะเสียง" | "节拍检测" | "ビート検出" | "비트" => {
3211                return Ok(Value::Bool(self.fft.borrow().is_beat()));
3212            }
3213
3214            // fft_beat_ratio() → f64  (1.0 = at threshold, >1 = strong beat)
3215            #[cfg(not(target_arch = "wasm32"))]
3216            "fft_beat_ratio" | "อัตราจังหวะ" | "节拍比" | "ビート比" | "비트비율" => {
3217                return Ok(Value::Number(self.fft.borrow().beat_ratio() as f64));
3218            }
3219
3220            // fft_rms() → f64
3221            #[cfg(not(target_arch = "wasm32"))]
3222            "fft_rms" | "ระดับRMS" | "均方根" | "二乗平均" | "RMS레벨" => {
3223                return Ok(Value::Number(self.fft.borrow().rms() as f64));
3224            }
3225
3226            // fft_dominant_freq() → f64  in Hz
3227            #[cfg(not(target_arch = "wasm32"))]
3228            "fft_dominant_freq" | "ความถี่หลัก" | "主频" | "主要周波数" | "주파수" => {
3229                return Ok(Value::Number(self.fft.borrow().dominant_freq() as f64));
3230            }
3231
3232            // ── wasm32 stubs: fft builtins are no-ops on web ───────────────
3233            #[cfg(target_arch = "wasm32")]
3234            "fft_push" | "วิเคราะห์เสียง" | "频谱输入" | "FFT入力" | "FFT입력" => { return Ok(Value::Unit); }
3235            #[cfg(target_arch = "wasm32")]
3236            "fft_bands" | "แถบความถี่" | "频段" | "周波数帯" | "주파수대" => {
3237                let n = self.arg_num(&args, 0, 32.0)? as usize;
3238                return Ok(Value::List(vec![Value::Number(0.0); n]));
3239            }
3240            #[cfg(target_arch = "wasm32")]
3241            "fft_beat" | "จังหวะเสียง" | "节拍检测" | "ビート検出" | "비트" => { return Ok(Value::Bool(false)); }
3242            #[cfg(target_arch = "wasm32")]
3243            "fft_beat_ratio" | "อัตราจังหวะ" | "节拍比" | "ビート比" | "비트비율" => { return Ok(Value::Number(1.0)); }
3244            #[cfg(target_arch = "wasm32")]
3245            "fft_rms" | "ระดับRMS" | "均方根" | "二乗平均" | "RMS레벨" => { return Ok(Value::Number(0.0)); }
3246            #[cfg(target_arch = "wasm32")]
3247            "fft_dominant_freq" | "ความถี่หลัก" | "主频" | "主要周波数" | "주파수" => { return Ok(Value::Number(0.0)); }
3248
3249            // ══════════════════════════════════════════════════════════════════
3250            // PROCEDURAL TEXTURE BLIT BUILTINS  (screen-space)
3251            // All: name(dst_x, dst_y, width, height, ...params, palette)
3252            // palette: "rainbow" | "fire" | "ocean" | "psychedelic" | "neon" | "forest"
3253            // ══════════════════════════════════════════════════════════════════
3254
3255            // tex_checkerboard(x, y, w, h, tiles, r1,g1,b1, r2,g2,b2)
3256            "tex_checkerboard" | "ลายตารางหมากรุก" => {
3257                let (tx,ty,tw,th) = self.tex_rect(&args)?;
3258                let tiles = self.arg_num(&args, 4, 8.0)? as u32;
3259                let (r1,g1,b1) = (self.arg_num(&args,5,255.)? as u32, self.arg_num(&args,6,255.)? as u32, self.arg_num(&args,7,255.)? as u32);
3260                let (r2,g2,b2) = (self.arg_num(&args,8,0.)? as u32,   self.arg_num(&args,9,0.)? as u32,   self.arg_num(&args,10,0.)? as u32);
3261                let c1 = (r1<<16)|(g1<<8)|b1; let c2 = (r2<<16)|(g2<<8)|b2;
3262                let mut gfx = self.gfx.borrow_mut();
3263                let (bw, bh) = (gfx.width, gfx.height);
3264                for row in 0..th { for col in 0..tw {
3265                    let cx = col as u32 * tiles / tw as u32;
3266                    let cy = row as u32 * tiles / th as u32;
3267                    let (dx, dy) = (tx+col, ty+row);
3268                    if dx < bw && dy < bh { gfx.buffer[dy*bw+dx] = if (cx+cy)%2==0 { c1 } else { c2 }; }
3269                }}
3270                return Ok(Value::Unit);
3271            }
3272
3273            // tex_gradient(x, y, w, h, angle_deg, r1,g1,b1, r2,g2,b2)
3274            "tex_gradient" | "ลายไล่สี" => {
3275                let (tx,ty,tw,th) = self.tex_rect(&args)?;
3276                let angle = self.arg_num(&args, 4, 0.0)? as f32;
3277                let (r1,g1,b1) = (self.arg_num(&args,5,0.)? as f32/255., self.arg_num(&args,6,0.)? as f32/255., self.arg_num(&args,7,0.)? as f32/255.);
3278                let (r2,g2,b2) = (self.arg_num(&args,8,255.)? as f32/255., self.arg_num(&args,9,255.)? as f32/255., self.arg_num(&args,10,255.)? as f32/255.);
3279                let (ca, sa) = (angle.to_radians().cos(), angle.to_radians().sin());
3280                let mut gfx = self.gfx.borrow_mut();
3281                let (bw, bh) = (gfx.width, gfx.height);
3282                for row in 0..th { for col in 0..tw {
3283                    let nx = col as f32/tw as f32 - 0.5; let ny = row as f32/th as f32 - 0.5;
3284                    let t = ((nx*ca + ny*sa + 0.707)/1.414).clamp(0.,1.);
3285                    let (dx, dy) = (tx+col, ty+row);
3286                    if dx < bw && dy < bh { gfx.buffer[dy*bw+dx] = tex_rgb(r1+(r2-r1)*t, g1+(g2-g1)*t, b1+(b2-b1)*t); }
3287                }}
3288                return Ok(Value::Unit);
3289            }
3290
3291            // tex_noise(x, y, w, h, scale, octaves, seed, palette)
3292            "tex_noise" | "ลายนอยส์" => {
3293                let (tx,ty,tw,th) = self.tex_rect(&args)?;
3294                let scale   = self.arg_num(&args, 4, 4.0)? as f32;
3295                let octaves = self.arg_num(&args, 5, 4.0)? as u32;
3296                let seed    = self.arg_num(&args, 6, 0.0)? as u32;
3297                let palette = self.arg_str(&args, 7, "rainbow");
3298                let mut gfx = self.gfx.borrow_mut();
3299                let (bw, bh) = (gfx.width, gfx.height);
3300                for row in 0..th { for col in 0..tw {
3301                    let v = tex_fbm(col as f32*scale/tw as f32, row as f32*scale/th as f32, octaves, seed);
3302                    let [r,g,b] = tex_palette(&palette, v);
3303                    let (dx, dy) = (tx+col, ty+row);
3304                    if dx < bw && dy < bh { gfx.buffer[dy*bw+dx] = tex_rgb(r, g, b); }
3305                }}
3306                return Ok(Value::Unit);
3307            }
3308
3309            // tex_freq_map(x, y, w, h, time, speed, palette)
3310            // Uses bands written by the last fft_bands() call.
3311            "tex_freq_map" | "ลายความถี่" => {
3312                let (tx,ty,tw,th) = self.tex_rect(&args)?;
3313                let time    = self.arg_num(&args, 4, 0.0)? as f32;
3314                let speed   = self.arg_num(&args, 5, 0.3)? as f32;
3315                let palette = self.arg_str(&args, 6, "rainbow");
3316                let bands: Vec<f32> = {
3317                    let c = self.fft_bands_cache.borrow();
3318                    if c.is_empty() { vec![0.0; 32] } else { c.clone() }
3319                };
3320                let n = bands.len().max(1);
3321                let mut gfx = self.gfx.borrow_mut();
3322                let (bw, bh) = (gfx.width, gfx.height);
3323                for row in 0..th { for col in 0..tw {
3324                    let band_idx = (col * n / tw.max(1)).min(n-1);
3325                    let mag = bands[band_idx].clamp(0.,1.);
3326                    let fill_y = (mag * th as f32) as usize;
3327                    if row >= th.saturating_sub(fill_y) {
3328                        let t = (col as f32/tw as f32 + time*speed) % 1.0;
3329                        let [r,g,b] = tex_palette(&palette, t);
3330                        let bright = mag * (1.0 - row as f32/th as f32 * 0.5);
3331                        let (dx, dy) = (tx+col, ty+row);
3332                        if dx < bw && dy < bh { gfx.buffer[dy*bw+dx] = tex_rgb(r*bright, g*bright, b*bright); }
3333                    }
3334                }}
3335                return Ok(Value::Unit);
3336            }
3337
3338            // tex_spiral(x, y, w, h, freq, bands, time, palette)
3339            "tex_spiral" | "ลายเกลียวหมุน" => {
3340                let (tx,ty,tw,th) = self.tex_rect(&args)?;
3341                let freq    = self.arg_num(&args, 4, 5.0)? as f32;
3342                let n_bands = self.arg_num(&args, 5, 8.0)? as f32;
3343                let time    = self.arg_num(&args, 6, 0.0)? as f32;
3344                let palette = self.arg_str(&args, 7, "rainbow");
3345                let mut gfx = self.gfx.borrow_mut();
3346                let (bw, bh) = (gfx.width, gfx.height);
3347                for row in 0..th { for col in 0..tw {
3348                    let nx = col as f32/tw as f32 - 0.5; let ny = row as f32/th as f32 - 0.5;
3349                    let r  = (nx*nx + ny*ny).sqrt();
3350                    let theta = ny.atan2(nx);
3351                    let t = ((r*freq - theta/std::f32::consts::TAU + time*0.5) * n_bands % 1.0).abs();
3352                    let [cr,cg,cb] = tex_palette(&palette, t);
3353                    let (dx, dy) = (tx+col, ty+row);
3354                    if dx < bw && dy < bh { gfx.buffer[dy*bw+dx] = tex_rgb(cr, cg, cb); }
3355                }}
3356                return Ok(Value::Unit);
3357            }
3358
3359            // tex_ripple(x, y, w, h, freq, cx, cy, time, palette)
3360            "tex_ripple" | "ลายระลอก" => {
3361                let (tx,ty,tw,th) = self.tex_rect(&args)?;
3362                let freq    = self.arg_num(&args, 4, 10.0)? as f32;
3363                let rcx     = self.arg_num(&args, 5, 0.5)? as f32;
3364                let rcy     = self.arg_num(&args, 6, 0.5)? as f32;
3365                let time    = self.arg_num(&args, 7, 0.0)? as f32;
3366                let palette = self.arg_str(&args, 8, "ocean");
3367                let mut gfx = self.gfx.borrow_mut();
3368                let (bw, bh) = (gfx.width, gfx.height);
3369                for row in 0..th { for col in 0..tw {
3370                    let nx = col as f32/tw as f32 - rcx; let ny = row as f32/th as f32 - rcy;
3371                    let r = (nx*nx + ny*ny).sqrt();
3372                    let t = ((r*freq - time) % 1.0).abs();
3373                    let [cr,cg,cb] = tex_palette(&palette, t);
3374                    let (dx, dy) = (tx+col, ty+row);
3375                    if dx < bw && dy < bh { gfx.buffer[dy*bw+dx] = tex_rgb(cr, cg, cb); }
3376                }}
3377                return Ok(Value::Unit);
3378            }
3379
3380            // tex_mandelbrot(x, y, w, h, zoom, cx, cy, max_iter, palette)
3381            "tex_mandelbrot" | "ลายแมนเดลบรอต" => {
3382                let (tx,ty,tw,th) = self.tex_rect(&args)?;
3383                let zoom     = self.arg_num(&args, 4, 1.0)?;
3384                let mcx      = self.arg_num(&args, 5, -0.5)?;
3385                let mcy      = self.arg_num(&args, 6, 0.0)?;
3386                let max_iter = self.arg_num(&args, 7, 64.0)? as u32;
3387                let palette  = self.arg_str(&args, 8, "psychedelic");
3388                let mut gfx = self.gfx.borrow_mut();
3389                let (bw, bh) = (gfx.width, gfx.height);
3390                for row in 0..th { for col in 0..tw {
3391                    let zx0 = (col as f64/tw as f64 - 0.5)/zoom + mcx;
3392                    let zy0 = (row as f64/th as f64 - 0.5)/zoom + mcy;
3393                    let mut x = 0.0f64; let mut y = 0.0f64; let mut i = 0u32;
3394                    while i < max_iter && x*x+y*y < 4.0 { let t=x*x-y*y+zx0; y=2.0*x*y+zy0; x=t; i+=1; }
3395                    let t = if i==max_iter { 0.0f32 } else {
3396                        (i as f32 - (x as f32*x as f32+y as f32*y as f32).ln().ln()/2.0f32.ln()) / max_iter as f32
3397                    };
3398                    let [cr,cg,cb] = tex_palette(&palette, t.clamp(0.,1.));
3399                    let (dx, dy) = (tx+col, ty+row);
3400                    if dx < bw && dy < bh { gfx.buffer[dy*bw+dx] = tex_rgb(cr, cg, cb); }
3401                }}
3402                return Ok(Value::Unit);
3403            }
3404
3405            // tex_julia(x, y, w, h, c_re, c_im, max_iter, palette)
3406            "tex_julia" | "ลายจูเลีย" => {
3407                let (tx,ty,tw,th) = self.tex_rect(&args)?;
3408                let c_re     = self.arg_num(&args, 4, -0.7)?;
3409                let c_im     = self.arg_num(&args, 5, 0.27)?;
3410                let max_iter = self.arg_num(&args, 6, 64.0)? as u32;
3411                let palette  = self.arg_str(&args, 7, "neon");
3412                let mut gfx = self.gfx.borrow_mut();
3413                let (bw, bh) = (gfx.width, gfx.height);
3414                for row in 0..th { for col in 0..tw {
3415                    let mut zx = (col as f64/tw as f64 - 0.5)*3.5;
3416                    let mut zy = (row as f64/th as f64 - 0.5)*3.5;
3417                    let mut i = 0u32;
3418                    while i < max_iter && zx*zx+zy*zy < 4.0 { let t=zx*zx-zy*zy+c_re; zy=2.0*zx*zy+c_im; zx=t; i+=1; }
3419                    let t = i as f32 / max_iter as f32;
3420                    let [cr,cg,cb] = tex_palette(&palette, t);
3421                    let (dx, dy) = (tx+col, ty+row);
3422                    if dx < bw && dy < bh { gfx.buffer[dy*bw+dx] = tex_rgb(cr, cg, cb); }
3423                }}
3424                return Ok(Value::Unit);
3425            }
3426
3427            // tex_voronoi(x, y, w, h, cells, seed, palette)
3428            "tex_voronoi" | "ลายโวโรนอย" => {
3429                let (tx,ty,tw,th) = self.tex_rect(&args)?;
3430                let cells   = self.arg_num(&args, 4, 16.0)? as u32;
3431                let seed    = self.arg_num(&args, 5, 42.0)? as u32;
3432                let palette = self.arg_str(&args, 6, "rainbow");
3433                let pts: Vec<[f32;2]> = (0..cells).map(|i| [tex_hash(i as i32,0,seed), tex_hash(i as i32,1,seed+999)]).collect();
3434                let mut gfx = self.gfx.borrow_mut();
3435                let (bw, bh) = (gfx.width, gfx.height);
3436                for row in 0..th { for col in 0..tw {
3437                    let (fx, fy) = (col as f32/tw as f32, row as f32/th as f32);
3438                    let (min_d, nearest) = pts.iter().enumerate().fold((f32::MAX,0usize), |(d,idx),(i,&[cx,cy])| {
3439                        let dd = (fx-cx).powi(2)+(fy-cy).powi(2);
3440                        if dd < d { (dd,i) } else { (d,idx) }
3441                    });
3442                    let t = (nearest as f32/cells as f32 + min_d*4.0) % 1.0;
3443                    let [cr,cg,cb] = tex_palette(&palette, t);
3444                    let (dx, dy) = (tx+col, ty+row);
3445                    if dx < bw && dy < bh { gfx.buffer[dy*bw+dx] = tex_rgb(cr, cg, cb); }
3446                }}
3447                return Ok(Value::Unit);
3448            }
3449
3450            // tex_halftone(x, y, w, h, dot_size, time, palette)
3451            "tex_halftone" | "ลายฮาล์ฟโทน" => {
3452                let (tx,ty,tw,th) = self.tex_rect(&args)?;
3453                let dot_size = self.arg_num(&args, 4, 0.05)? as f32;
3454                let time     = self.arg_num(&args, 5, 0.0)? as f32;
3455                let palette  = self.arg_str(&args, 6, "rainbow");
3456                let mut gfx = self.gfx.borrow_mut();
3457                let (bw, bh) = (gfx.width, gfx.height);
3458                for row in 0..th { for col in 0..tw {
3459                    let (fx, fy) = (col as f32/tw as f32, row as f32/th as f32);
3460                    let gx = (fx/dot_size).floor(); let gy = (fy/dot_size).floor();
3461                    let lx = (fx/dot_size - gx - 0.5)*2.0; let ly = (fy/dot_size - gy - 0.5)*2.0;
3462                    let r = (lx*lx + ly*ly).sqrt();
3463                    let t = (gx/(1.0/dot_size) + time*0.1) % 1.0;
3464                    let a = if r < 0.7 { ((0.7-r)/0.7).clamp(0.,1.) } else { 0.0 };
3465                    if a > 0.0 {
3466                        let [cr,cg,cb] = tex_palette(&palette, t);
3467                        let (dx, dy) = (tx+col, ty+row);
3468                        if dx < bw && dy < bh { gfx.buffer[dy*bw+dx] = tex_rgb(cr, cg, cb); }
3469                    }
3470                }}
3471                return Ok(Value::Unit);
3472            }
3473
3474            // ══════════════════════════════════════════════════════════════════
3475            // RENDER / LIGHTING MODES  (holographic cel shading)
3476            // ══════════════════════════════════════════════════════════════════
3477            // set_shade_mode(m) — 0 flat · 1 cel · 2 holo (default)
3478            "set_shade_mode" | "设置着色" | "シェード設定" | "셰이드모드" | "ตั้งการแรเงา" => {
3479                let m = self.arg_num(&args, 0, 2.0)? as u8;
3480                self.gfx.borrow_mut().shade_mode = m;
3481                return Ok(Value::Unit);
3482            }
3483            // set_cel_bands(n) — number of posterisation bands (>=2)
3484            "set_cel_bands" | "设置色阶" | "セル段数" | "셀밴드" | "ตั้งระดับสี" => {
3485                let n = (self.arg_num(&args, 0, 4.0)? as u32).max(2);
3486                self.gfx.borrow_mut().shade.bands = n;
3487                return Ok(Value::Unit);
3488            }
3489            // set_shadow_color(r,g,b) — coloured-shadow tint, 0-255
3490            "set_shadow_color" | "设置阴影色" | "影の色" | "그림자색" | "ตั้งสีเงา" => {
3491                let r=self.arg_num(&args,0,26.)? as f32/255.0;
3492                let g=self.arg_num(&args,1,33.)? as f32/255.0;
3493                let b=self.arg_num(&args,2,77.)? as f32/255.0;
3494                self.gfx.borrow_mut().shade.shadow = [r,g,b];
3495                return Ok(Value::Unit);
3496            }
3497            // set_rim(strength, r,g,b) — holographic fresnel edge glow
3498            // ══════════════════════════════════════════════════════════════════
3499            // CRYPTOGRAPHY (ling-crypto) — geo suite, hybrid PQ KEM, holographic
3500            // Bytes cross the language boundary as lowercase hex strings.
3501            // ══════════════════════════════════════════════════════════════════
3502            #[cfg(not(target_arch = "wasm32"))]
3503            "crypto_hash" | "แฮชเข้ารหัส" | "几何哈希" | "幾何ハッシュ" | "기하해시" => {
3504                let s = self.arg_str(&args, 0, "");
3505                return Ok(Value::Str(hex_encode(&ling_crypto::geo::holo_hash(s.as_bytes()))));
3506            }
3507            // 3-D torus-knot fingerprint of any text/key → flat [x,y,z, x,y,z, …]
3508            #[cfg(not(target_arch = "wasm32"))]
3509            "knot_points" | "จุดปม" | "结点坐标" | "結び目点" | "매듭점" => {
3510                let s = self.arg_str(&args, 0, "");
3511                let shape = ling_crypto::geo::KnotShape::from_bytes(s.as_bytes());
3512                let mut out = Vec::with_capacity(shape.points.len() * 3);
3513                for p in &shape.points {
3514                    out.push(Value::Number(p[0] as f64));
3515                    out.push(Value::Number(p[1] as f64));
3516                    out.push(Value::Number(p[2] as f64));
3517                }
3518                return Ok(Value::List(out));
3519            }
3520            #[cfg(not(target_arch = "wasm32"))]
3521            "knot_label" | "ป้ายปม" | "结点标签" | "結び目ラベル" | "매듭라벨" => {
3522                let s = self.arg_str(&args, 0, "");
3523                return Ok(Value::Str(ling_crypto::geo::KnotShape::from_bytes(s.as_bytes()).label()));
3524            }
3525            // KEM keypair (hybrid X25519+ML-KEM-768) → integer handle
3526            #[cfg(not(target_arch = "wasm32"))]
3527            "knot_keygen" | "hybrid_keygen" | "สร้างกุญแจปม" | "生成密钥" | "鍵生成" | "키생성" => {
3528                self.crypto_ids.push(ling_crypto::KnotIdentity::generate());
3529                return Ok(Value::Number((self.crypto_ids.len() - 1) as f64));
3530            }
3531            #[cfg(not(target_arch = "wasm32"))]
3532            "knot_public" | "hybrid_public" | "กุญแจสาธารณะปม" | "公钥" | "公開鍵" | "공개키" => {
3533                let h = self.arg_num(&args, 0, 0.0)? as usize;
3534                let pk = self.crypto_ids.get(h).map(|id| hex_encode(id.public_key())).unwrap_or_default();
3535                return Ok(Value::Str(pk));
3536            }
3537            // encapsulate(pubkey_hex) → [ciphertext_hex, shared_secret_hex]
3538            #[cfg(not(target_arch = "wasm32"))]
3539            "knot_encapsulate" | "hybrid_encapsulate" | "ห่อกุญแจปม" | "封装密钥" | "カプセル化" | "캡슐화" => {
3540                let pk = hex_decode(&self.arg_str(&args, 0, ""));
3541                match ling_crypto::geo::knot_encapsulate(&pk) {
3542                    Ok((ct, ss)) => return Ok(Value::List(vec![Value::Str(hex_encode(&ct)), Value::Str(hex_encode(&ss))])),
3543                    Err(e) => return Ok(Value::Err(Box::new(Value::Str(e.to_string())))),
3544                }
3545            }
3546            // decapsulate(handle, ciphertext_hex) → shared_secret_hex
3547            #[cfg(not(target_arch = "wasm32"))]
3548            "knot_decapsulate" | "hybrid_decapsulate" | "แกะกุญแจปม" | "解封装密钥" | "カプセル解除" | "캡슐해제" => {
3549                let h = self.arg_num(&args, 0, 0.0)? as usize;
3550                let ct = hex_decode(&self.arg_str(&args, 1, ""));
3551                let ss = self.crypto_ids.get(h)
3552                    .and_then(|id| id.decapsulate(&ct).ok())
3553                    .map(|s| hex_encode(&s)).unwrap_or_default();
3554                return Ok(Value::Str(ss));
3555            }
3556            // Authenticated encryption (XChaCha20-Poly1305) — seal(key_hex, text) → ct_hex
3557            #[cfg(not(target_arch = "wasm32"))]
3558            "crypto_seal" | "ผนึก" | "封印" | "封印する" | "봉인" => {
3559                let key = hex_to_32(&self.arg_str(&args, 0, ""));
3560                let pt = self.arg_str(&args, 1, "");
3561                match ling_crypto::geo::holo_seal(key, pt.as_bytes()) {
3562                    Ok(ct) => return Ok(Value::Str(hex_encode(&ct))),
3563                    Err(e) => return Ok(Value::Err(Box::new(Value::Str(e.to_string())))),
3564                }
3565            }
3566            #[cfg(not(target_arch = "wasm32"))]
3567            "crypto_open" | "เปิดผนึก" | "解封" | "封印解除" | "봉인해제" => {
3568                let key = hex_to_32(&self.arg_str(&args, 0, ""));
3569                let ct = hex_decode(&self.arg_str(&args, 1, ""));
3570                match ling_crypto::geo::holo_open(key, &ct) {
3571                    Ok(pt) => return Ok(Value::Str(String::from_utf8_lossy(&pt).into_owned())),
3572                    Err(e) => return Ok(Value::Err(Box::new(Value::Str(e.to_string())))),
3573                }
3574            }
3575            // Holographic all-or-nothing transform — 4-D fragment coords [a,b,c,d, …]
3576            #[cfg(not(target_arch = "wasm32"))]
3577            "holo_points" | "จุดโฮโลแกรม" | "全息点" | "ホログラム点" | "홀로그램점" => {
3578                let s = self.arg_str(&args, 0, "");
3579                let frags = ling_crypto::geo::scatter(s.as_bytes());
3580                let mut out = Vec::with_capacity(frags.len() * 4);
3581                for f in &frags { for c in f.coord { out.push(Value::Number(c as f64)); } }
3582                return Ok(Value::List(out));
3583            }
3584            #[cfg(not(target_arch = "wasm32"))]
3585            "holo_fragment_count" | "จำนวนชิ้นโฮโลแกรม" | "全息碎片数" | "ホログラム断片数" | "홀로그램조각수" => {
3586                let s = self.arg_str(&args, 0, "");
3587                return Ok(Value::Number(ling_crypto::geo::scatter(s.as_bytes()).len() as f64));
3588            }
3589
3590            // ══════════════════════════════════════════════════════════════════
3591            // ling-ui — animation easings + holographic vector widgets + text I/O
3592            // ══════════════════════════════════════════════════════════════════
3593            "ease" => {
3594                let name = self.arg_str(&args, 0, "ease");
3595                let t = self.arg_num(&args, 1, 0.0)? as f32;
3596                return Ok(Value::Number(ling_ui::Easing::from_name(&name).apply(t) as f64));
3597            }
3598
3599            // ══════════════════════════════════════════════════════════════════
3600            // Anima — unified animation drivers (ling-animation). Organic 灵 +
3601            // mechanical 机 scalar drivers, callable per frame from a script.
3602            // ══════════════════════════════════════════════════════════════════
3603            "tween" | "补间" | "補間" | "트윈" | "แทรกค่า" => {
3604                let a = self.arg_num(&args, 0, 0.0)?;
3605                let b = self.arg_num(&args, 1, 0.0)?;
3606                let t = self.arg_num(&args, 2, 0.0)?.clamp(0.0, 1.0);
3607                return Ok(Value::Number(a + (b - a) * t));
3608            }
3609            "tween_ease" | "缓动补间" | "緩和補間" | "이징트윈" | "แทรกนุ่ม" => {
3610                let a = self.arg_num(&args, 0, 0.0)? as f32;
3611                let b = self.arg_num(&args, 1, 0.0)? as f32;
3612                let t = self.arg_num(&args, 2, 0.0)? as f32;
3613                let kind = self.arg_str(&args, 3, "linear");
3614                let e = ling_animation::EaseFunction::from_name(&kind);
3615                return Ok(Value::Number(ling_animation::ease::tween_ease(&a, &b, t, e) as f64));
3616            }
3617            // ── Organic 灵 ──
3618            "breathe" | "呼吸" | "호흡" | "หายใจ" => {
3619                let t = self.arg_num(&args, 0, 0.0)? as f32;
3620                let rate = self.arg_num(&args, 1, 1.0)? as f32;
3621                let depth = self.arg_num(&args, 2, 0.1)? as f32;
3622                return Ok(Value::Number(ling_animation::scalar::breathe(t, rate, depth) as f64));
3623            }
3624            "wobble" | "摆动" | "揺れ" | "흔들림" | "โยก" => {
3625                let t = self.arg_num(&args, 0, 0.0)? as f32;
3626                let freq = self.arg_num(&args, 1, 1.0)? as f32;
3627                let amp = self.arg_num(&args, 2, 1.0)? as f32;
3628                let phase = self.arg_num(&args, 3, 0.0)? as f32;
3629                return Ok(Value::Number(ling_animation::scalar::wobble(t, freq, amp, phase) as f64));
3630            }
3631            "gait_phase" | "步相" | "歩相" | "걸음위상" | "เฟสก้าว" => {
3632                let t = self.arg_num(&args, 0, 0.0)? as f32;
3633                let speed = self.arg_num(&args, 1, 1.0)? as f32;
3634                return Ok(Value::Number(ling_animation::scalar::gait_phase(t, speed) as f64));
3635            }
3636            "gait_swing" | "步摆" | "歩振り" | "걸음흔들" | "ก้าวแกว่ง" => {
3637                let t = self.arg_num(&args, 0, 0.0)? as f32;
3638                let speed = self.arg_num(&args, 1, 1.0)? as f32;
3639                let stride = self.arg_num(&args, 2, 1.0)? as f32;
3640                return Ok(Value::Number(ling_animation::scalar::gait_swing(t, speed, stride) as f64));
3641            }
3642            "gait_lift" | "抬脚" | "足上げ" | "발들기" | "ยกเท้า" => {
3643                let t = self.arg_num(&args, 0, 0.0)? as f32;
3644                let speed = self.arg_num(&args, 1, 1.0)? as f32;
3645                let height = self.arg_num(&args, 2, 1.0)? as f32;
3646                return Ok(Value::Number(ling_animation::scalar::gait_lift(t, speed, height) as f64));
3647            }
3648            "spring_to" | "弹向" | "バネ寄せ" | "스프링이동" | "สปริงไป" => {
3649                let pos = self.arg_num(&args, 0, 0.0)? as f32;
3650                let vel = self.arg_num(&args, 1, 0.0)? as f32;
3651                let target = self.arg_num(&args, 2, 0.0)? as f32;
3652                let stiffness = self.arg_num(&args, 3, 120.0)? as f32;
3653                let damping = self.arg_num(&args, 4, 14.0)? as f32;
3654                let dt = self.arg_num(&args, 5, 1.0 / 60.0)? as f32;
3655                let (np, nv) = ling_animation::scalar::spring_step(pos, vel, target, stiffness, damping, dt);
3656                return Ok(Value::List(vec![Value::Number(np as f64), Value::Number(nv as f64)]));
3657            }
3658            "ik2" | "反解" | "逆運動" | "역운동" | "ไอเค2" => {
3659                let l1 = self.arg_num(&args, 0, 1.0)? as f32;
3660                let l2 = self.arg_num(&args, 1, 1.0)? as f32;
3661                let tx = self.arg_num(&args, 2, 0.0)? as f32;
3662                let ty = self.arg_num(&args, 3, 0.0)? as f32;
3663                let (sh, el) = ling_animation::scalar::two_bone_ik(l1, l2, tx, ty);
3664                return Ok(Value::List(vec![Value::Number(sh as f64), Value::Number(el as f64)]));
3665            }
3666            // ── Mechanical 机 ──
3667            "gear_couple" | "齿轮联动" | "歯車連動" | "기어연동" | "เฟืองทด" => {
3668                let angle = self.arg_num(&args, 0, 0.0)? as f32;
3669                let ti = self.arg_num(&args, 1, 1.0)? as f32;
3670                let to = self.arg_num(&args, 2, 1.0)? as f32;
3671                return Ok(Value::Number(ling_animation::scalar::gear(angle, ti, to) as f64));
3672            }
3673            "gear_train" | "齿轮组" | "歯車列" | "기어열" | "ชุดเฟือง" => {
3674                let angle = self.arg_num(&args, 0, 0.0)? as f32;
3675                let teeth: Vec<f32> = match args.get(1) {
3676                    Some(Value::List(items)) => items.iter()
3677                        .filter_map(|v| if let Value::Number(n) = v { Some(*n as f32) } else { None }).collect(),
3678                    _ => Vec::new(),
3679                };
3680                let out = ling_animation::mechanism::gear_train(angle, &teeth);
3681                return Ok(Value::List(out.into_iter().map(|a| Value::Number(a as f64)).collect()));
3682            }
3683            "cam_lift" | "凸轮升程" | "カム揚程" | "캠리프트" | "ยกลูกเบี้ยว" => {
3684                let angle = self.arg_num(&args, 0, 0.0)? as f32;
3685                let lift = self.arg_num(&args, 1, 1.0)? as f32;
3686                return Ok(Value::Number(ling_animation::scalar::cam_lift(angle, lift) as f64));
3687            }
3688            "piston" | "活塞" | "ピストン" | "피스톤" | "ลูกสูบ" => {
3689                let angle = self.arg_num(&args, 0, 0.0)? as f32;
3690                let crank = self.arg_num(&args, 1, 1.0)? as f32;
3691                let rod = self.arg_num(&args, 2, 2.0)? as f32;
3692                return Ok(Value::Number(ling_animation::scalar::piston(angle, crank, rod) as f64));
3693            }
3694            "rack" | "齿条" | "ラック" | "랙" | "แร็ค" => {
3695                let angle = self.arg_num(&args, 0, 0.0)? as f32;
3696                let radius = self.arg_num(&args, 1, 1.0)? as f32;
3697                return Ok(Value::Number(ling_animation::scalar::rack(angle, radius) as f64));
3698            }
3699            #[cfg(not(target_arch = "wasm32"))]
3700            "mouse_x" => {
3701                let gfx = self.gfx.borrow();
3702                let v = gfx.window.as_ref().and_then(|w| w.get_mouse_pos(minifb::MouseMode::Clamp)).map(|p| p.0 as f64).unwrap_or(0.0);
3703                return Ok(Value::Number(v));
3704            }
3705            #[cfg(not(target_arch = "wasm32"))]
3706            "mouse_y" => {
3707                let gfx = self.gfx.borrow();
3708                let v = gfx.window.as_ref().and_then(|w| w.get_mouse_pos(minifb::MouseMode::Clamp)).map(|p| p.1 as f64).unwrap_or(0.0);
3709                return Ok(Value::Number(v));
3710            }
3711            #[cfg(not(target_arch = "wasm32"))]
3712            "mouse_down" => {
3713                let gfx = self.gfx.borrow();
3714                let d = gfx.window.as_ref().map(|w| w.get_mouse_down(minifb::MouseButton::Left)).unwrap_or(false);
3715                return Ok(Value::Bool(d));
3716            }
3717            "mouse_down_right" | "เมาส์ขวา" => {
3718                let gfx = self.gfx.borrow();
3719                let d = gfx.window.as_ref().map(|w| w.get_mouse_down(minifb::MouseButton::Right)).unwrap_or(false);
3720                return Ok(Value::Bool(d));
3721            }
3722            "mouse_down_middle" | "เมาส์กลาง" => {
3723                let gfx = self.gfx.borrow();
3724                let d = gfx.window.as_ref().map(|w| w.get_mouse_down(minifb::MouseButton::Middle)).unwrap_or(false);
3725                return Ok(Value::Bool(d));
3726            }
3727            #[cfg(not(target_arch = "wasm32"))]
3728            "ui_hot" | "热区" | "ホットエリア" | "핫존" | "พื้นที่สัมผัส" => {
3729                let x = self.arg_num(&args,0,0.0)? as f32;
3730                let y = self.arg_num(&args,1,0.0)? as f32;
3731                let w = self.arg_num(&args,2,0.0)? as f32;
3732                let h = self.arg_num(&args,3,0.0)? as f32;
3733                let gfx = self.gfx.borrow();
3734                let (mx,my) = gfx.window.as_ref().and_then(|win| win.get_mouse_pos(minifb::MouseMode::Clamp)).unwrap_or((0.0,0.0));
3735                return Ok(Value::Bool(ling_ui::holo::hit_rect(mx,my,x,y,w,h)));
3736            }
3737            // ui_text(x, y, scale, "string") — holographic vector text
3738            "ui_text" | "界面文字" | "UI文字" | "UI텍스트" | "ข้อความหน้าจอ" => {
3739                let x = self.arg_num(&args,0,0.0)? as f32;
3740                let y = self.arg_num(&args,1,0.0)? as f32;
3741                let scale = self.arg_num(&args,2,16.0)? as f32;
3742                let s = self.arg_str(&args,3,"");
3743                let segs = ling_ui::holo::text_lines(&s, x, y, scale*0.62, scale, scale*0.24);
3744                let mut gfx = self.gfx.borrow_mut();
3745                let (w,h,color) = (gfx.width, gfx.height, gfx.color);
3746                for sg in segs { draw_line(&mut gfx.buffer, w, h, color, sg[0], sg[1], sg[2], sg[3]); }
3747                return Ok(Value::Unit);
3748            }
3749            // font_load("path.ttf") — load a vector font (outlines cached lazily as
3750            // cache/fonts/<stem>/<codepoint>.ling). Returns a handle, or -1 on failure.
3751            #[cfg(not(target_arch = "wasm32"))]
3752            "font_load" | "โหลดฟอนต์" | "加载字体" | "フォント読込" | "글꼴로드" => {
3753                let path = self.arg_str(&args, 0, "");
3754                // Optional 2nd arg: variable-font weight (e.g. 600 for a solid, bold UI).
3755                let weight = match self.arg_num(&args, 1, 0.0)? {
3756                    w if w > 0.0 => Some(w as f32),
3757                    _ => None,
3758                };
3759                // Try the path as given, then relative to the script's directory.
3760                let mut loaded = ling_graphics::VectorFont::from_path_weight(&path, weight);
3761                if loaded.is_err() {
3762                    if let Some(dir) = &self.source_dir {
3763                        let joined = dir.join(&path);
3764                        loaded = ling_graphics::VectorFont::from_path_weight(&joined.to_string_lossy(), weight);
3765                    }
3766                }
3767                match loaded {
3768                    Ok(f) => {
3769                        let id = self.fonts.len();
3770                        self.fonts.push(f);
3771                        return Ok(Value::Number(id as f64));
3772                    }
3773                    Err(e) => {
3774                        eprintln!("font_load failed ({path}): {e}");
3775                        return Ok(Value::Number(-1.0));
3776                    }
3777                }
3778            }
3779            // font_text(handle, x, y, px, "string") — anti-aliased *stroked* vector outline
3780            // in the current set_color / set_blend. (x,y) is the text box top-left.
3781            #[cfg(not(target_arch = "wasm32"))]
3782            "font_text" | "ข้อความฟอนต์" | "字体文本" | "フォント文字" | "글꼴텍스트" => {
3783                let id = self.arg_num(&args, 0, 0.0)? as i64;
3784                let x  = self.arg_num(&args, 1, 0.0)? as f32;
3785                let y  = self.arg_num(&args, 2, 0.0)? as f32;
3786                let px = self.arg_num(&args, 3, 16.0)? as f32;
3787                let s  = self.arg_str(&args, 4, "");
3788                if id >= 0 && (id as usize) < self.fonts.len() && px > 0.0 {
3789                    let strokes = self.font_layout_2d(id as usize, x, y, px, &s);
3790                    let mut gfx = self.gfx.borrow_mut();
3791                    let (w, h, color, add) = (gfx.width, gfx.height, gfx.color, gfx.blend == 1);
3792                    for pl in &strokes {
3793                        for seg in pl.windows(2) {
3794                            crate::gfx::raster::draw_line_aa(&mut gfx.buffer, w, h, color, add,
3795                                seg[0][0], seg[0][1], seg[1][0], seg[1][1]);
3796                        }
3797                    }
3798                }
3799                return Ok(Value::Unit);
3800            }
3801            // font_text_fill(handle, x, y, px, "string") — anti-aliased *filled* vector glyphs.
3802            #[cfg(not(target_arch = "wasm32"))]
3803            "font_text_fill" | "เติมฟอนต์" | "填充字体" | "フォント塗り" | "글꼴채움" => {
3804                let id = self.arg_num(&args, 0, 0.0)? as i64;
3805                let x  = self.arg_num(&args, 1, 0.0)? as f32;
3806                let y  = self.arg_num(&args, 2, 0.0)? as f32;
3807                let px = self.arg_num(&args, 3, 16.0)? as f32;
3808                let s  = self.arg_str(&args, 4, "");
3809                if id >= 0 && (id as usize) < self.fonts.len() && px > 0.0 {
3810                    // fill each glyph independently so interior holes (winding) stay correct
3811                    let glyphs = self.font_layout_2d_glyphs(id as usize, x, y, px, &s);
3812                    let mut gfx = self.gfx.borrow_mut();
3813                    let (w, h, color, add) = (gfx.width, gfx.height, gfx.color, gfx.blend == 1);
3814                    for contours in &glyphs {
3815                        crate::gfx::raster::fill_contours_aa(&mut gfx.buffer, w, h, color, add, contours);
3816                    }
3817                }
3818                return Ok(Value::Unit);
3819            }
3820            // font_text_3d(handle, cx,cy,cz, ux,uy,uz, vx,vy,vz, size, "string")
3821            // — stroked vector text on a 3D plane: u = advance dir, v = up dir, size = world/em.
3822            //   Flows through the depth-sorted line pipeline, so it rotates with the camera (and 4D).
3823            #[cfg(not(target_arch = "wasm32"))]
3824            "font_text_3d" | "ข้อความฟอนต์3มิติ" | "字体3D" | "フォント3D" | "글꼴3D" => {
3825                let id = self.arg_num(&args, 0, 0.0)? as i64;
3826                let cx=self.arg_num(&args,1,0.0)? as f32; let cy=self.arg_num(&args,2,0.0)? as f32; let cz=self.arg_num(&args,3,0.0)? as f32;
3827                let ux=self.arg_num(&args,4,1.0)? as f32; let uy=self.arg_num(&args,5,0.0)? as f32; let uz=self.arg_num(&args,6,0.0)? as f32;
3828                let vx=self.arg_num(&args,7,0.0)? as f32; let vy=self.arg_num(&args,8,1.0)? as f32; let vz=self.arg_num(&args,9,0.0)? as f32;
3829                let size=self.arg_num(&args,10,1.0)? as f32;
3830                let s = self.arg_str(&args,11,"");
3831                if id >= 0 && (id as usize) < self.fonts.len() && size > 0.0 {
3832                    // Build world-space polylines: world = C + (pen+ex)*size*U + ey*size*V
3833                    let font = &mut self.fonts[id as usize];
3834                    let asc = font.ascent();
3835                    let mut pen = 0.0f32;
3836                    let mut lines: Vec<[f32; 6]> = Vec::new();
3837                    for ch in s.chars() {
3838                        let go = font.glyph_outline(ch, 0.01);
3839                        for pl in &go.polylines {
3840                            for seg in pl.windows(2) {
3841                                let map = |p: [f32; 2]| {
3842                                    let a = pen + p[0];
3843                                    let b = p[1] - asc; // shift so the top of the cap sits near C
3844                                    [cx + a*size*ux + b*size*vx,
3845                                     cy + a*size*uy + b*size*vy,
3846                                     cz + a*size*uz + b*size*vz]
3847                                };
3848                                let p0 = map(seg[0]); let p1 = map(seg[1]);
3849                                lines.push([p0[0],p0[1],p0[2], p1[0],p1[1],p1[2]]);
3850                            }
3851                        }
3852                        pen += go.advance;
3853                    }
3854                    let mut gfx = self.gfx.borrow_mut();
3855                    let color = gfx.color;
3856                    let near = -gfx.camera.zdist + 0.05;
3857                    for l in &lines {
3858                        let (mut ax, mut ay, mut az) = (l[0], l[1], l[2]);
3859                        let (mut bx, mut by, mut bz) = (l[3], l[4], l[5]);
3860                        let da = gfx.camera.depth(ax, ay, az);
3861                        let db = gfx.camera.depth(bx, by, bz);
3862                        if da <= near && db <= near { continue; }
3863                        if da <= near {
3864                            let t = (near - da) / (db - da);
3865                            ax += t*(bx-ax); ay += t*(by-ay); az += t*(bz-az);
3866                        } else if db <= near {
3867                            let t = (near - da) / (db - da);
3868                            bx = ax + t*(bx-ax); by = ay + t*(by-ay); bz = az + t*(bz-az);
3869                        }
3870                        let (sax, say, da2) = gfx.camera.project(ax, ay, az);
3871                        let (sbx, sby, db2) = gfx.camera.project(bx, by, bz);
3872                        let depth = (da2 + db2) / 2.0;
3873                        gfx.depth_queue.push_line(depth, color, sax, say, sbx, sby);
3874                    }
3875                }
3876                return Ok(Value::Unit);
3877            }
3878            // font_width(handle, px, "string") — pixel width of a string in a loaded font.
3879            #[cfg(not(target_arch = "wasm32"))]
3880            "font_width" | "ความกว้างฟอนต์" | "字体宽度" | "フォント幅" | "글꼴너비" => {
3881                let id = self.arg_num(&args, 0, 0.0)? as i64;
3882                let px = self.arg_num(&args, 1, 16.0)? as f32;
3883                let s  = self.arg_str(&args, 2, "");
3884                if id >= 0 && (id as usize) < self.fonts.len() {
3885                    return Ok(Value::Number(self.fonts[id as usize].measure(&s, px) as f64));
3886                }
3887                return Ok(Value::Number(0.0));
3888            }
3889            // ui_frame(x,y,w,h, bracketLen) — sci-fi corner brackets
3890            "ui_frame" | "边框" | "フレーム枠" | "프레임틀" | "กรอบ" => {
3891                let x=self.arg_num(&args,0,0.0)? as f32; let y=self.arg_num(&args,1,0.0)? as f32;
3892                let w0=self.arg_num(&args,2,0.0)? as f32; let h0=self.arg_num(&args,3,0.0)? as f32;
3893                let l=self.arg_num(&args,4,14.0)? as f32;
3894                let segs = ling_ui::holo::corner_brackets(x,y,w0,h0,l);
3895                let mut gfx = self.gfx.borrow_mut();
3896                let (w,h,color)=(gfx.width,gfx.height,gfx.color);
3897                for sg in segs { draw_line(&mut gfx.buffer, w,h,color, sg[0],sg[1],sg[2],sg[3]); }
3898                return Ok(Value::Unit);
3899            }
3900            // ui_bevel(x,y,w,h, bevel) — beveled holographic panel outline
3901            "ui_bevel" | "斜角框" | "ベベル枠" | "베벨틀" | "กรอบเฉียง" => {
3902                let x=self.arg_num(&args,0,0.0)? as f32; let y=self.arg_num(&args,1,0.0)? as f32;
3903                let w0=self.arg_num(&args,2,0.0)? as f32; let h0=self.arg_num(&args,3,0.0)? as f32;
3904                let bv=self.arg_num(&args,4,10.0)? as f32;
3905                let segs = ling_ui::holo::beveled_rect(x,y,w0,h0,bv);
3906                let mut gfx = self.gfx.borrow_mut();
3907                let (w,h,color)=(gfx.width,gfx.height,gfx.color);
3908                for sg in segs { draw_line(&mut gfx.buffer, w,h,color, sg[0],sg[1],sg[2],sg[3]); }
3909                return Ok(Value::Unit);
3910            }
3911
3912            // ══════════════════════════════════════════════════════════════════
3913            // VECTOR UI TOOLKIT  (crates/ling-ui/src/widgets.rs)
3914            // All widgets are vector + theme-coloured with an optional trailing
3915            // r,g,b override; interactive ones read the mouse and return state.
3916            // ══════════════════════════════════════════════════════════════════
3917            #[cfg(not(target_arch = "wasm32"))]
3918            "ui_theme" | "界面主题" | "UIテーマ" | "인터페이스테마" | "ธีมส่วนติดต่อ" => {
3919                let cur = self.ui_theme;
3920                let primary = self.color_at(&args, 0,  cur.primary);
3921                let accent  = self.color_at(&args, 3,  cur.accent);
3922                let track   = self.color_at(&args, 6,  cur.track);
3923                let warn    = self.color_at(&args, 9,  cur.warn);
3924                let text    = self.color_at(&args, 12, cur.text);
3925                let bg      = self.color_at(&args, 15, cur.bg);
3926                self.ui_theme = UiTheme { primary, accent, track, warn, text, bg };
3927                return Ok(Value::Unit);
3928            }
3929
3930            // ── HUD ──────────────────────────────────────────────────────────
3931            #[cfg(not(target_arch = "wasm32"))]
3932            "ui_radar" | "雷达" | "レーダー" | "레이더" | "เรดาร์" => {
3933                let cx=self.arg_num(&args,0,0.)? as f32; let cy=self.arg_num(&args,1,0.)? as f32;
3934                let r=self.arg_num(&args,2,60.)? as f32; let sweep=self.arg_num(&args,3,0.)? as f32;
3935                let th=self.ui_theme;
3936                let prim=self.color_at(&args,4,th.primary);
3937                self.draw_ui(&ling_ui::widgets::radar(cx,cy,r,sweep, prim, th.accent, th.track));
3938                return Ok(Value::Unit);
3939            }
3940            #[cfg(not(target_arch = "wasm32"))]
3941            "ui_compass" | "罗盘" | "コンパス" | "나침반" | "เข็มทิศ" => {
3942                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
3943                let w0=self.arg_num(&args,2,300.)? as f32; let h0=self.arg_num(&args,3,24.)? as f32;
3944                let head=self.arg_num(&args,4,0.)? as f32;
3945                let th=self.ui_theme; let prim=self.color_at(&args,5,th.primary);
3946                self.draw_ui(&ling_ui::widgets::compass(x,y,w0,h0,head, prim, th.track));
3947                return Ok(Value::Unit);
3948            }
3949            #[cfg(not(target_arch = "wasm32"))]
3950            "ui_reticle" | "准星" | "照準" | "조준선" | "เป้าเล็ง" => {
3951                let cx=self.arg_num(&args,0,0.)? as f32; let cy=self.arg_num(&args,1,0.)? as f32;
3952                let r=self.arg_num(&args,2,30.)? as f32; let spread=self.arg_num(&args,3,0.)? as f32;
3953                let th=self.ui_theme; let prim=self.color_at(&args,4,th.primary);
3954                self.draw_ui(&ling_ui::widgets::reticle(cx,cy,r,spread, prim));
3955                return Ok(Value::Unit);
3956            }
3957            #[cfg(not(target_arch = "wasm32"))]
3958            "ui_target" | "锁定框" | "ターゲット" | "표적" | "กรอบเป้า" => {
3959                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
3960                let w0=self.arg_num(&args,2,80.)? as f32; let h0=self.arg_num(&args,3,80.)? as f32;
3961                let lock=self.arg_num(&args,4,0.)? as f32;
3962                let th=self.ui_theme; let prim=self.color_at(&args,5,th.primary);
3963                self.draw_ui(&ling_ui::widgets::target(x,y,w0,h0,lock, prim, th.accent));
3964                return Ok(Value::Unit);
3965            }
3966            #[cfg(not(target_arch = "wasm32"))]
3967            "ui_panel" | "面板" | "パネル" | "패널" | "แผง" => {
3968                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
3969                let w0=self.arg_num(&args,2,200.)? as f32; let h0=self.arg_num(&args,3,120.)? as f32;
3970                let bv=self.arg_num(&args,4,12.)? as f32;
3971                let th=self.ui_theme; let prim=self.color_at(&args,5,th.primary);
3972                self.draw_ui(&ling_ui::widgets::panel(x,y,w0,h0,bv, prim, th.bg));
3973                return Ok(Value::Unit);
3974            }
3975            #[cfg(not(target_arch = "wasm32"))]
3976            "ui_scanlines" | "扫描线" | "走査線" | "스캔라인" | "เส้นสแกน" => {
3977                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
3978                let w0=self.arg_num(&args,2,200.)? as f32; let h0=self.arg_num(&args,3,120.)? as f32;
3979                let dens=self.arg_num(&args,4,24.)? as usize;
3980                let th=self.ui_theme; let line=self.color_at(&args,5,th.track);
3981                self.draw_ui(&ling_ui::widgets::scanlines(x,y,w0,h0,dens, line));
3982                return Ok(Value::Unit);
3983            }
3984
3985            // ── Meters ───────────────────────────────────────────────────────
3986            #[cfg(not(target_arch = "wasm32"))]
3987            "ui_bar" | "进度条" | "バー" | "막대" | "แถบ" => {
3988                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
3989                let w0=self.arg_num(&args,2,160.)? as f32; let h0=self.arg_num(&args,3,16.)? as f32;
3990                let val=self.arg_num(&args,4,0.)? as f32; let max=self.arg_num(&args,5,1.)? as f32;
3991                let th=self.ui_theme; let fill=self.color_at(&args,6,th.primary);
3992                self.draw_ui(&ling_ui::widgets::bar(x,y,w0,h0, val/max.max(1e-6), fill, th.track));
3993                return Ok(Value::Unit);
3994            }
3995            #[cfg(not(target_arch = "wasm32"))]
3996            "ui_segbar" | "分段条" | "分割バー" | "분할막대" | "แถบแบ่ง" => {
3997                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
3998                let w0=self.arg_num(&args,2,160.)? as f32; let h0=self.arg_num(&args,3,16.)? as f32;
3999                let val=self.arg_num(&args,4,0.)? as f32; let max=self.arg_num(&args,5,1.)? as f32;
4000                let segs=self.arg_num(&args,6,10.)? as usize;
4001                let th=self.ui_theme; let fill=self.color_at(&args,7,th.primary);
4002                self.draw_ui(&ling_ui::widgets::segbar(x,y,w0,h0, val/max.max(1e-6), segs, fill, th.track));
4003                return Ok(Value::Unit);
4004            }
4005            #[cfg(not(target_arch = "wasm32"))]
4006            "ui_gauge" | "仪表" | "ゲージ" | "게이지" | "มาตรวัด" => {
4007                let cx=self.arg_num(&args,0,0.)? as f32; let cy=self.arg_num(&args,1,0.)? as f32;
4008                let r=self.arg_num(&args,2,50.)? as f32;
4009                let val=self.arg_num(&args,3,0.)? as f32; let max=self.arg_num(&args,4,1.)? as f32;
4010                let th=self.ui_theme; let needle=self.color_at(&args,5,th.warn);
4011                self.draw_ui(&ling_ui::widgets::gauge(cx,cy,r, val/max.max(1e-6), needle, th.accent, th.track));
4012                return Ok(Value::Unit);
4013            }
4014            #[cfg(not(target_arch = "wasm32"))]
4015            "ui_ring" | "环表" | "リングメーター" | "링미터" | "วงแหวนวัด" => {
4016                let cx=self.arg_num(&args,0,0.)? as f32; let cy=self.arg_num(&args,1,0.)? as f32;
4017                let r=self.arg_num(&args,2,40.)? as f32;
4018                let val=self.arg_num(&args,3,0.)? as f32; let max=self.arg_num(&args,4,1.)? as f32;
4019                let th=self.ui_theme; let fill=self.color_at(&args,5,th.primary);
4020                self.draw_ui(&ling_ui::widgets::ring(cx,cy,r, val/max.max(1e-6), fill, th.track));
4021                return Ok(Value::Unit);
4022            }
4023            #[cfg(not(target_arch = "wasm32"))]
4024            "ui_vu" | "音量条" | "VUメーター" | "음량막대" | "มาตรเสียง" => {
4025                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
4026                let w0=self.arg_num(&args,2,160.)? as f32; let h0=self.arg_num(&args,3,60.)? as f32;
4027                let levels=self.arg_list_f32(&args,4);
4028                let th=self.ui_theme; let fill=self.color_at(&args,5,th.primary);
4029                self.draw_ui(&ling_ui::widgets::vu(x,y,w0,h0, &levels, fill, th.warn));
4030                return Ok(Value::Unit);
4031            }
4032            #[cfg(not(target_arch = "wasm32"))]
4033            "ui_spark" | "迷你图" | "スパークライン" | "스파크라인" | "กราฟจิ๋ว" => {
4034                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
4035                let w0=self.arg_num(&args,2,160.)? as f32; let h0=self.arg_num(&args,3,40.)? as f32;
4036                let vals=self.arg_list_f32(&args,4);
4037                let th=self.ui_theme; let line=self.color_at(&args,5,th.accent);
4038                self.draw_ui(&ling_ui::widgets::spark(x,y,w0,h0, &vals, line));
4039                return Ok(Value::Unit);
4040            }
4041            #[cfg(not(target_arch = "wasm32"))]
4042            "ui_battery" | "电池" | "バッテリー" | "배터리" | "แบตเตอรี่" => {
4043                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
4044                let w0=self.arg_num(&args,2,50.)? as f32; let h0=self.arg_num(&args,3,22.)? as f32;
4045                let val=self.arg_num(&args,4,1.)? as f32; let max=self.arg_num(&args,5,1.)? as f32;
4046                let th=self.ui_theme; let fill=self.color_at(&args,6,th.accent);
4047                self.draw_ui(&ling_ui::widgets::battery(x,y,w0,h0, val/max.max(1e-6), fill, th.track, th.warn));
4048                return Ok(Value::Unit);
4049            }
4050
4051            // ── Interface controls (interactive → return state) ──────────────
4052            #[cfg(not(target_arch = "wasm32"))]
4053            "ui_button" | "按钮" | "ボタン" | "버튼" | "ปุ่ม" => {
4054                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
4055                let w0=self.arg_num(&args,2,120.)? as f32; let h0=self.arg_num(&args,3,40.)? as f32;
4056                let (mx,my,down)=self.mouse_now();
4057                let hover=ling_ui::holo::hit_rect(mx,my,x,y,w0,h0);
4058                let clicked = hover && down && !self.mouse_was_down;
4059                let th=self.ui_theme; let prim=self.color_at(&args,4,th.primary);
4060                self.draw_ui(&ling_ui::widgets::button(x,y,w0,h0, hover, down&&hover, prim, th.bg));
4061                return Ok(Value::Number(if clicked {1.0} else {0.0}));
4062            }
4063            #[cfg(not(target_arch = "wasm32"))]
4064            "ui_toggle" | "开关" | "トグル" | "토글" | "สวิตช์" => {
4065                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
4066                let w0=self.arg_num(&args,2,52.)? as f32; let h0=self.arg_num(&args,3,24.)? as f32;
4067                let mut state=self.arg_num(&args,4,0.)? > 0.5;
4068                let (mx,my,down)=self.mouse_now();
4069                let hover=ling_ui::holo::hit_rect(mx,my,x,y,w0,h0);
4070                if hover && down && !self.mouse_was_down { state = !state; }
4071                let th=self.ui_theme; let on=self.color_at(&args,5,th.accent);
4072                self.draw_ui(&ling_ui::widgets::toggle(x,y,w0,h0, state, on, th.track));
4073                return Ok(Value::Number(if state {1.0} else {0.0}));
4074            }
4075            #[cfg(not(target_arch = "wasm32"))]
4076            "ui_slider" | "滑块" | "スライダー" | "슬라이더" | "แถบเลื่อน" => {
4077                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
4078                let w0=self.arg_num(&args,2,160.)? as f32;
4079                let mut val=self.arg_num(&args,3,0.)? as f32;
4080                let mn=self.arg_num(&args,4,0.)? as f32; let mx_=self.arg_num(&args,5,1.)? as f32;
4081                let (mx,my,down)=self.mouse_now();
4082                let hover=ling_ui::holo::hit_rect(mx,my,x-8.0,y-10.0,w0+16.0,20.0);
4083                if hover && down {
4084                    let frac=((mx-x)/w0).max(0.0).min(1.0);
4085                    val = mn + (mx_-mn)*frac;
4086                }
4087                let frac=((val-mn)/(mx_-mn).abs().max(1e-6)).max(0.0).min(1.0);
4088                let th=self.ui_theme; let fill=self.color_at(&args,6,th.primary);
4089                self.draw_ui(&ling_ui::widgets::slider(x,y,w0, frac, hover, fill, th.track));
4090                return Ok(Value::Number(val as f64));
4091            }
4092            #[cfg(not(target_arch = "wasm32"))]
4093            "ui_checkbox" | "复选框" | "チェックボックス" | "체크박스" | "ช่องเลือก" => {
4094                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
4095                let s=self.arg_num(&args,2,20.)? as f32;
4096                let mut checked=self.arg_num(&args,3,0.)? > 0.5;
4097                let (mx,my,down)=self.mouse_now();
4098                let hover=ling_ui::holo::hit_rect(mx,my,x,y,s,s);
4099                if hover && down && !self.mouse_was_down { checked = !checked; }
4100                let th=self.ui_theme; let prim=self.color_at(&args,4,th.primary);
4101                self.draw_ui(&ling_ui::widgets::checkbox(x,y,s, checked, hover, prim, th.track));
4102                return Ok(Value::Number(if checked {1.0} else {0.0}));
4103            }
4104            #[cfg(not(target_arch = "wasm32"))]
4105            "ui_tabs" | "标签页" | "タブ" | "탭" | "แท็บ" => {
4106                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
4107                let w0=self.arg_num(&args,2,240.)? as f32; let h0=self.arg_num(&args,3,28.)? as f32;
4108                let count=self.arg_num(&args,4,3.)? as usize;
4109                let mut active=self.arg_num(&args,5,0.)? as i32;
4110                let (mx,my,down)=self.mouse_now();
4111                let mut hover=-1;
4112                if my>=y && my<=y+h0 && mx>=x && mx<=x+w0 && count>0 {
4113                    hover = (((mx-x)/(w0/count as f32)) as i32).max(0).min(count as i32-1);
4114                    if down && !self.mouse_was_down { active = hover; }
4115                }
4116                let th=self.ui_theme; let prim=self.color_at(&args,6,th.primary);
4117                self.draw_ui(&ling_ui::widgets::tabs(x,y,w0,h0, count, active as usize, hover, prim, th.track));
4118                return Ok(Value::Number(active as f64));
4119            }
4120            #[cfg(not(target_arch = "wasm32"))]
4121            "ui_progress" | "进度" | "プログレス" | "진행바" | "ความคืบหน้า" => {
4122                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
4123                let w0=self.arg_num(&args,2,200.)? as f32; let h0=self.arg_num(&args,3,12.)? as f32;
4124                let frac=self.arg_num(&args,4,0.)? as f32;
4125                let th=self.ui_theme; let fill=self.color_at(&args,5,th.accent);
4126                self.draw_ui(&ling_ui::widgets::progress(x,y,w0,h0, frac, fill, th.track));
4127                return Ok(Value::Unit);
4128            }
4129            #[cfg(not(target_arch = "wasm32"))]
4130            "ui_tooltip" | "提示框" | "ツールチップ" | "툴팁" | "คำแนะนำ" => {
4131                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
4132                let w0=self.arg_num(&args,2,120.)? as f32; let h0=self.arg_num(&args,3,28.)? as f32;
4133                let th=self.ui_theme; let prim=self.color_at(&args,4,th.primary);
4134                self.draw_ui(&ling_ui::widgets::tooltip(x,y,w0,h0, prim, th.bg));
4135                return Ok(Value::Unit);
4136            }
4137            #[cfg(not(target_arch = "wasm32"))]
4138            "ui_stepper" | "步进器" | "ステッパー" | "스테퍼" | "ตัวปรับค่า" => {
4139                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
4140                let w0=self.arg_num(&args,2,120.)? as f32; let h0=self.arg_num(&args,3,28.)? as f32;
4141                let mut val=self.arg_num(&args,4,0.)? as f32; let step=self.arg_num(&args,5,1.)? as f32;
4142                let (mx,my,down)=self.mouse_now();
4143                let hm=ling_ui::holo::hit_rect(mx,my,x,y,h0,h0);
4144                let hp=ling_ui::holo::hit_rect(mx,my,x+w0-h0,y,h0,h0);
4145                if down && !self.mouse_was_down { if hm { val -= step; } if hp { val += step; } }
4146                let th=self.ui_theme; let prim=self.color_at(&args,6,th.primary);
4147                self.draw_ui(&ling_ui::widgets::stepper(x,y,w0,h0, hm, hp, prim, th.track));
4148                return Ok(Value::Number(val as f64));
4149            }
4150
4151            // ── Game UI ──────────────────────────────────────────────────────
4152            #[cfg(not(target_arch = "wasm32"))]
4153            "ui_healthbar" | "血条" | "体力バー" | "체력바" | "แถบพลังชีวิต" => {
4154                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
4155                let w0=self.arg_num(&args,2,180.)? as f32; let h0=self.arg_num(&args,3,16.)? as f32;
4156                let val=self.arg_num(&args,4,1.)? as f32; let max=self.arg_num(&args,5,1.)? as f32;
4157                let pulse=self.arg_num(&args,6,0.)? as f32;
4158                let th=self.ui_theme; let full=self.color_at(&args,7,th.accent);
4159                self.draw_ui(&ling_ui::widgets::healthbar(x,y,w0,h0, val/max.max(1e-6), pulse, full, th.warn, th.track));
4160                return Ok(Value::Unit);
4161            }
4162            #[cfg(not(target_arch = "wasm32"))]
4163            "ui_cooldown" | "冷却" | "クールダウン" | "쿨다운" | "คูลดาวน์" => {
4164                let cx=self.arg_num(&args,0,0.)? as f32; let cy=self.arg_num(&args,1,0.)? as f32;
4165                let r=self.arg_num(&args,2,28.)? as f32; let frac=self.arg_num(&args,3,0.)? as f32;
4166                let th=self.ui_theme; let fill=self.color_at(&args,4,th.primary);
4167                self.draw_ui(&ling_ui::widgets::cooldown(cx,cy,r, frac, fill, th.track));
4168                return Ok(Value::Unit);
4169            }
4170            #[cfg(not(target_arch = "wasm32"))]
4171            "ui_counter" | "计数器" | "カウンター" | "카운터" | "ตัวนับ" => {
4172                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
4173                let dw=self.arg_num(&args,2,14.)? as f32; let dh=self.arg_num(&args,3,24.)? as f32;
4174                let val=self.arg_num(&args,4,0.)? as i64; let digits=self.arg_num(&args,5,4.)? as usize;
4175                let th=self.ui_theme; let on=self.color_at(&args,6,th.primary);
4176                let off=ling_ui::widgets::shade(th.track,0.5);
4177                self.draw_ui(&ling_ui::widgets::counter(x,y,dw,dh, val, digits, on, off));
4178                return Ok(Value::Unit);
4179            }
4180            #[cfg(not(target_arch = "wasm32"))]
4181            "ui_minimap" | "小地图" | "ミニマップ" | "미니맵" | "แผนที่ย่อ" => {
4182                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
4183                let w0=self.arg_num(&args,2,140.)? as f32; let h0=self.arg_num(&args,3,140.)? as f32;
4184                let th=self.ui_theme; let prim=self.color_at(&args,4,th.primary);
4185                self.draw_ui(&ling_ui::widgets::minimap(x,y,w0,h0, prim, th.bg));
4186                return Ok(Value::Unit);
4187            }
4188            #[cfg(not(target_arch = "wasm32"))]
4189            "ui_dpad" | "方向键" | "方向パッド" | "방향패드" | "ปุ่มทิศทาง" => {
4190                let cx=self.arg_num(&args,0,0.)? as f32; let cy=self.arg_num(&args,1,0.)? as f32;
4191                let r=self.arg_num(&args,2,50.)? as f32;
4192                let (mx,my,down)=self.mouse_now();
4193                let mut dir=0;
4194                if down {
4195                    let (dx,dy)=(mx-cx, my-cy);
4196                    if dx*dx+dy*dy <= r*r {
4197                        if dx.abs() > dy.abs() { dir = if dx>0.0 {2} else {4}; }
4198                        else { dir = if dy>0.0 {3} else {1}; }
4199                    }
4200                }
4201                let th=self.ui_theme; let prim=self.color_at(&args,3,th.primary);
4202                self.draw_ui(&ling_ui::widgets::dpad(cx,cy,r, dir, prim, th.track));
4203                return Ok(Value::Number(dir as f64));
4204            }
4205            #[cfg(not(target_arch = "wasm32"))]
4206            "ui_slotgrid" | "物品格" | "スロットグリッド" | "슬롯격자" | "ช่องไอเทม" => {
4207                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
4208                let cols=self.arg_num(&args,2,4.)? as usize; let rows=self.arg_num(&args,3,1.)? as usize;
4209                let cell=self.arg_num(&args,4,36.)? as f32; let sel=self.arg_num(&args,5,-1.)? as i32;
4210                let th=self.ui_theme; let prim=self.color_at(&args,6,th.primary);
4211                self.draw_ui(&ling_ui::widgets::slotgrid(x,y,cols,rows,cell, sel, prim, th.track));
4212                return Ok(Value::Unit);
4213            }
4214            #[cfg(not(target_arch = "wasm32"))]
4215            "ui_vignette" | "暗角" | "ビネット" | "비네트" | "ขอบมืด" => {
4216                let intensity=self.arg_num(&args,0,0.5)? as f32;
4217                let (w,h)={ let g=self.gfx.borrow(); (g.width as f32, g.height as f32) };
4218                let th=self.ui_theme; let col=self.color_at(&args,1,th.warn);
4219                self.draw_ui(&ling_ui::widgets::vignette(w,h, intensity, col));
4220                return Ok(Value::Unit);
4221            }
4222
4223            // ── Faux-3D in 2D space ──────────────────────────────────────────
4224            #[cfg(not(target_arch = "wasm32"))]
4225            "ui_gauge3d" | "立体仪表" | "立体ゲージ" | "입체게이지" | "มาตรวัด3มิติ" => {
4226                let cx=self.arg_num(&args,0,0.)? as f32; let cy=self.arg_num(&args,1,0.)? as f32;
4227                let r=self.arg_num(&args,2,50.)? as f32;
4228                let val=self.arg_num(&args,3,0.)? as f32; let max=self.arg_num(&args,4,1.)? as f32;
4229                let spin=self.arg_num(&args,5,0.)? as f32;
4230                let th=self.ui_theme; let fill=self.color_at(&args,6,th.primary);
4231                self.draw_ui(&ling_ui::widgets::gauge3d(cx,cy,r, val/max.max(1e-6), spin, fill, th.track));
4232                return Ok(Value::Unit);
4233            }
4234            #[cfg(not(target_arch = "wasm32"))]
4235            "ui_panel3d" | "立体面板" | "立体パネル" | "입체패널" | "แผง3มิติ" => {
4236                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
4237                let w0=self.arg_num(&args,2,200.)? as f32; let h0=self.arg_num(&args,3,120.)? as f32;
4238                let depth=self.arg_num(&args,4,14.)? as f32;
4239                let th=self.ui_theme; let prim=self.color_at(&args,5,th.primary);
4240                self.draw_ui(&ling_ui::widgets::panel3d(x,y,w0,h0,depth, prim, th.bg));
4241                return Ok(Value::Unit);
4242            }
4243            #[cfg(not(target_arch = "wasm32"))]
4244            "ui_radar3d" | "立体雷达" | "立体レーダー" | "입체레이더" | "เรดาร์3มิติ" => {
4245                let cx=self.arg_num(&args,0,0.)? as f32; let cy=self.arg_num(&args,1,0.)? as f32;
4246                let r=self.arg_num(&args,2,60.)? as f32; let tilt=self.arg_num(&args,3,0.9)? as f32;
4247                let sweep=self.arg_num(&args,4,0.)? as f32;
4248                let th=self.ui_theme; let prim=self.color_at(&args,5,th.primary);
4249                self.draw_ui(&ling_ui::widgets::radar3d(cx,cy,r,tilt,sweep, prim, th.track));
4250                return Ok(Value::Unit);
4251            }
4252
4253            // ── Interface sounds ─────────────────────────────────────────────
4254            #[cfg(not(target_arch = "wasm32"))]
4255            "audio_blip" | "提示音" | "ビープ音" | "효과음" | "เสียงบี๊บ" => {
4256                let freq=self.arg_num(&args,0,660.)? as f32;
4257                let dur=self.arg_num(&args,1,0.08)? as f32;
4258                let wave=Wave::from_name(&self.arg_str(&args,2,"sine"));
4259                let amp=self.arg_num(&args,3,0.25)? as f32;
4260                if let Some(audio)=&self.audio { audio.blip(freq, amp, dur, wave); }
4261                return Ok(Value::Unit);
4262            }
4263            #[cfg(not(target_arch = "wasm32"))]
4264            "ui_sound" | "界面音" | "UI音" | "인터페이스음" | "เสียงปุ่ม" => {
4265                let name=self.arg_str(&args,0,"click");
4266                if let Some(audio)=&self.audio {
4267                    match name.as_str() {
4268                        "hover"   => audio.blip(880.0, 0.10, 0.04, Wave::Sine),
4269                        "confirm" => { audio.blip(660.0, 0.22, 0.07, Wave::Square); audio.blip(990.0, 0.18, 0.10, Wave::Square); }
4270                        "error"   => { audio.blip(180.0, 0.30, 0.16, Wave::Saw); audio.blip(140.0, 0.30, 0.18, Wave::Saw); }
4271                        "toggle"  => audio.blip(520.0, 0.22, 0.05, Wave::Triangle),
4272                        "tick"    => audio.blip(1500.0, 0.12, 0.02, Wave::Square),
4273                        _         => audio.blip(720.0, 0.26, 0.05, Wave::Square), // "click"
4274                    }
4275                }
4276                return Ok(Value::Unit);
4277            }
4278
4279            // ══════════════════════════════════════════════════════════════════
4280            // MUSIC TOOLKIT  (crates/ling-music) — decode · analysis · GM synth ·
4281            // rhythm · karaoke. Analysis/decoding need no audio device; playback
4282            // and synthesis lazily start a dedicated music engine.
4283            // ══════════════════════════════════════════════════════════════════
4284
4285            // music_load(path) -> track handle (decodes WAV/FLAC/OGG/MP3/AAC)
4286            #[cfg(not(target_arch = "wasm32"))]
4287            "music_load" | "载入音乐" | "音楽読込" | "음악로드" | "โหลดเพลง" => {
4288                let path = self.arg_str(&args, 0, "");
4289                let resolved = if std::path::Path::new(&path).exists() { path.clone() }
4290                    else if let Some(d) = &self.source_dir { d.join(&path).to_string_lossy().into_owned() }
4291                    else { path.clone() };
4292                match ling_music::load(&resolved) {
4293                    Ok(t) => { let id = self.tracks.len(); self.tracks.push(t); return Ok(Value::Number(id as f64)); }
4294                    Err(e) => { eprintln!("music_load failed ({path}): {e}"); return Ok(Value::Number(-1.0)); }
4295                }
4296            }
4297            #[cfg(not(target_arch = "wasm32"))]
4298            "music_duration" | "音乐时长" | "音楽長さ" | "음악길이" | "ความยาวเพลง" => {
4299                let id = self.arg_num(&args,0,0.0)? as i64;
4300                let d = self.tracks.get(id as usize).map(|t| t.duration).unwrap_or(0.0);
4301                return Ok(Value::Number(d as f64));
4302            }
4303            #[cfg(not(target_arch = "wasm32"))]
4304            "music_bpm" | "节拍速度" | "テンポ" | "템포" | "จังหวะต่อนาที" => {
4305                let id = self.arg_num(&args,0,0.0)? as i64;
4306                let b = self.tracks.get(id as usize).map(|t| ling_music::analysis::bpm(&t.mono, t.rate)).unwrap_or(0.0);
4307                return Ok(Value::Number(b as f64));
4308            }
4309            #[cfg(not(target_arch = "wasm32"))]
4310            "music_key" | "调性" | "調性" | "조성" | "คีย์เพลง" => {
4311                let id = self.arg_num(&args,0,0.0)? as i64;
4312                let k = self.tracks.get(id as usize).map(|t| ling_music::analysis::key_name(&t.mono, t.rate)).unwrap_or_default();
4313                return Ok(Value::Str(k));
4314            }
4315            #[cfg(not(target_arch = "wasm32"))]
4316            "music_onsets" | "音符起点" | "オンセット" | "온셋" | "จุดเริ่มเสียง" => {
4317                let id = self.arg_num(&args,0,0.0)? as i64;
4318                let v = self.tracks.get(id as usize).map(|t| ling_music::analysis::onsets(&t.mono, t.rate)).unwrap_or_default();
4319                return Ok(Value::List(v.into_iter().map(|x| Value::Number(x as f64)).collect()));
4320            }
4321            #[cfg(not(target_arch = "wasm32"))]
4322            "music_beat_grid" | "节拍网格" | "ビートグリッド" | "비트그리드" | "กริดจังหวะ" => {
4323                let id = self.arg_num(&args,0,0.0)? as i64;
4324                let beats = self.tracks.get(id as usize).map(|t| {
4325                    let b = ling_music::analysis::bpm(&t.mono, t.rate);
4326                    ling_music::analysis::beat_grid(&t.mono, t.rate, b)
4327                }).unwrap_or_default();
4328                return Ok(Value::List(beats.into_iter().map(|x| Value::Number(x as f64)).collect()));
4329            }
4330
4331            // ── playback ──
4332            #[cfg(not(target_arch = "wasm32"))]
4333            "music_play" | "播放音乐" | "音楽再生" | "음악재생" | "เล่นเพลง" => {
4334                let id = self.arg_num(&args,0,0.0)? as i64;
4335                if self.ensure_music() {
4336                    let track = self.tracks.get(id as usize).map(|t| (t.stereo.clone(), t.rate));
4337                    if let (Some((st, rate)), Some(m)) = (track, &self.music) { m.set_track(st, rate); m.play(); }
4338                    else if let Some(m) = &self.music { m.play(); }
4339                }
4340                return Ok(Value::Unit);
4341            }
4342            #[cfg(not(target_arch = "wasm32"))]
4343            "music_pause" | "暂停音乐" | "音楽一時停止" | "음악일시정지" | "หยุดเพลงชั่วคราว" => {
4344                if let Some(m) = &self.music { m.pause(); } return Ok(Value::Unit);
4345            }
4346            #[cfg(not(target_arch = "wasm32"))]
4347            "music_stop" | "停止音乐" | "音楽停止" | "음악정지" | "หยุดเพลง" => {
4348                if let Some(m) = &self.music { m.stop(); } return Ok(Value::Unit);
4349            }
4350            #[cfg(not(target_arch = "wasm32"))]
4351            "music_seek" | "定位音乐" | "音楽シーク" | "음악탐색" | "ค้นหาเพลง" => {
4352                let sec = self.arg_num(&args,0,0.0)? as f32;
4353                if let Some(m) = &self.music { m.seek(sec); } return Ok(Value::Unit);
4354            }
4355            #[cfg(not(target_arch = "wasm32"))]
4356            "music_pos" | "音乐位置" | "音楽位置" | "음악위치" | "ตำแหน่งเพลง" => {
4357                let p = self.music.as_ref().map(|m| m.position()).unwrap_or(0.0);
4358                return Ok(Value::Number(p as f64));
4359            }
4360            #[cfg(not(target_arch = "wasm32"))]
4361            "music_volume" | "音乐音量" | "音楽音量" | "음악음량" | "ระดับเพลง" => {
4362                let v = self.arg_num(&args,0,0.8)? as f32;
4363                if self.ensure_music() { if let Some(m) = &self.music { m.set_volume(v); } }
4364                return Ok(Value::Unit);
4365            }
4366
4367            // ── synthesis (GM-capable, patches from .ling files) ──
4368            #[cfg(not(target_arch = "wasm32"))]
4369            "music_patch" | "乐器音色" | "音色読込" | "악기패치" | "แพตช์เครื่องดนตรี" => {
4370                let path = self.arg_str(&args, 0, "");
4371                let resolved = if std::path::Path::new(&path).exists() { path.clone() }
4372                    else if let Some(d) = &self.source_dir { d.join(&path).to_string_lossy().into_owned() }
4373                    else { path.clone() };
4374                if !self.ensure_music() { return Ok(Value::Number(-1.0)); }
4375                match ling_music::patch::from_path(&resolved) {
4376                    Ok(p) => { let id = self.music.as_ref().unwrap().add_patch(p); return Ok(Value::Number(id as f64)); }
4377                    Err(e) => { eprintln!("music_patch failed ({path}): {e}"); return Ok(Value::Number(-1.0)); }
4378                }
4379            }
4380            #[cfg(not(target_arch = "wasm32"))]
4381            "music_note" | "弹音符" | "音符演奏" | "음표연주" | "เล่นโน้ต" => {
4382                let inst = self.arg_num(&args,0,0.0)? as usize;
4383                let midi = self.pitch_arg(&args, 1, 60);
4384                let dur  = self.arg_num(&args,2,0.5)? as f32;
4385                let vel  = self.arg_num(&args,3,0.9)? as f32;
4386                if self.ensure_music() { if let Some(m) = &self.music { m.note(inst, midi, vel, dur); } }
4387                return Ok(Value::Unit);
4388            }
4389            #[cfg(not(target_arch = "wasm32"))]
4390            "music_note_on" | "音符开始" | "音符オン" | "음표켜기" | "โน้ตเริ่ม" => {
4391                let inst = self.arg_num(&args,0,0.0)? as usize;
4392                let midi = self.pitch_arg(&args, 1, 60);
4393                let vel  = self.arg_num(&args,2,0.9)? as f32;
4394                if self.ensure_music() { if let Some(m) = &self.music { m.note_on(inst, midi, vel); } }
4395                return Ok(Value::Unit);
4396            }
4397            #[cfg(not(target_arch = "wasm32"))]
4398            "music_note_off" | "音符结束" | "音符オフ" | "음표끄기" | "โน้ตจบ" => {
4399                let inst = self.arg_num(&args,0,0.0)? as usize;
4400                let midi = self.pitch_arg(&args, 1, 60);
4401                if let Some(m) = &self.music { m.note_off(inst, midi); }
4402                return Ok(Value::Unit);
4403            }
4404
4405            // ── rhythm-game judging ──
4406            #[cfg(not(target_arch = "wasm32"))]
4407            "music_judge" | "判定" | "判定する" | "판정" | "ตัดสินจังหวะ" => {
4408                let delta_ms = self.arg_num(&args,0,9999.0)? as f32;
4409                return Ok(Value::Number(ling_music::Grade::judge(delta_ms).index() as f64));
4410            }
4411            #[cfg(not(target_arch = "wasm32"))]
4412            "music_grade_name" | "判定名" | "判定名称" | "판정이름" | "ชื่อการตัดสิน" => {
4413                let idx = self.arg_num(&args,0,4.0)? as i32;
4414                return Ok(Value::Str(ling_music::Grade::from_index(idx).name().to_string()));
4415            }
4416
4417            // ── karaoke ──
4418            #[cfg(not(target_arch = "wasm32"))]
4419            "music_lrc" | "载入歌词" | "歌詞読込" | "가사로드" | "โหลดเนื้อเพลง" => {
4420                let path = self.arg_str(&args, 0, "");
4421                let resolved = if std::path::Path::new(&path).exists() { path.clone() }
4422                    else if let Some(d) = &self.source_dir { d.join(&path).to_string_lossy().into_owned() }
4423                    else { path.clone() };
4424                match std::fs::read_to_string(&resolved) {
4425                    Ok(text) => { let id = self.lyrics.len(); self.lyrics.push(ling_music::Lyrics::parse(&text)); return Ok(Value::Number(id as f64)); }
4426                    Err(e) => { eprintln!("music_lrc failed ({path}): {e}"); return Ok(Value::Number(-1.0)); }
4427                }
4428            }
4429            #[cfg(not(target_arch = "wasm32"))]
4430            "music_lyric" | "当前歌词" | "現在歌詞" | "현재가사" | "เนื้อเพลงปัจจุบัน" => {
4431                let id = self.arg_num(&args,0,0.0)? as i64;
4432                let t  = self.arg_num(&args,1,0.0)? as f32;
4433                let line = self.lyrics.get(id as usize).map(|l| l.line_at(t).to_string()).unwrap_or_default();
4434                return Ok(Value::Str(line));
4435            }
4436            #[cfg(not(target_arch = "wasm32"))]
4437            "music_mic_pitch" | "麦克风音高" | "マイク音程" | "마이크음정" | "ระดับเสียงไมค์" => {
4438                let hz = if let Some(mic) = self.mic.as_ref() {
4439                    let s = mic.latest_samples();
4440                    let rate = mic.sample_rate();
4441                    ling_music::pitch::detect(&s, rate).unwrap_or(0.0)
4442                } else { 0.0 };
4443                return Ok(Value::Number(hz as f64));
4444            }
4445            #[cfg(not(target_arch = "wasm32"))]
4446            "music_note_name" | "音名" | "音名称" | "음이름" | "ชื่อโน้ต" => {
4447                let hz = self.arg_num(&args,0,0.0)? as f32;
4448                return Ok(Value::Str(ling_music::note::hz_to_name(hz)));
4449            }
4450            #[cfg(not(target_arch = "wasm32"))]
4451            "music_hz" | "音符频率" | "音符周波数" | "음표주파수" | "ความถี่โน้ต" => {
4452                let midi = self.pitch_arg(&args, 0, 69);
4453                return Ok(Value::Number(ling_music::note::midi_to_hz(midi as f32) as f64));
4454            }
4455            #[cfg(not(target_arch = "wasm32"))]
4456            "music_pitch_score" | "音准评分" | "音程スコア" | "음정점수" | "คะแนนเสียง" => {
4457                let hz = self.arg_num(&args,0,0.0)? as f32;
4458                let target = self.arg_num(&args,1,0.0)? as f32;
4459                return Ok(Value::Number(ling_music::karaoke::pitch_score(hz, target) as f64));
4460            }
4461
4462            // ── MIDI (inaudible note source: drive coins, cues, etc.) ──
4463            #[cfg(not(target_arch = "wasm32"))]
4464            "music_midi_load" | "载入MIDI" | "MIDI読込" | "미디로드" | "โหลดมิดี" => {
4465                let path = self.arg_str(&args, 0, "");
4466                let resolved = if std::path::Path::new(&path).exists() { path.clone() }
4467                    else if let Some(d) = &self.source_dir { d.join(&path).to_string_lossy().into_owned() }
4468                    else { path.clone() };
4469                match ling_music::midi::load(&resolved) {
4470                    Ok(m) => { let id = self.midis.len(); self.midis.push(m); return Ok(Value::Number(id as f64)); }
4471                    Err(e) => { eprintln!("music_midi_load failed ({path}): {e}"); return Ok(Value::Number(-1.0)); }
4472                }
4473            }
4474            #[cfg(not(target_arch = "wasm32"))]
4475            "music_midi_count" | "MIDI数量" | "MIDI数" | "미디수" | "จำนวนมิดี" => {
4476                let id = self.arg_num(&args,0,0.0)? as i64;
4477                let n = self.midis.get(id as usize).map(|m| m.notes.len()).unwrap_or(0);
4478                return Ok(Value::Number(n as f64));
4479            }
4480            // music_midi_notes(id) -> flat [time, midi, time, midi, …]
4481            #[cfg(not(target_arch = "wasm32"))]
4482            "music_midi_notes" | "MIDI音符" | "MIDIノート" | "미디음표" | "โน้ตมิดี" => {
4483                let id = self.arg_num(&args,0,0.0)? as i64;
4484                let mut out = Vec::new();
4485                if let Some(m) = self.midis.get(id as usize) {
4486                    for n in &m.notes { out.push(Value::Number(n.time as f64)); out.push(Value::Number(n.midi as f64)); }
4487                }
4488                return Ok(Value::List(out));
4489            }
4490            // music_midi_bars(id) -> flat [time, midi, dur, …] (for karaoke note bars)
4491            #[cfg(not(target_arch = "wasm32"))]
4492            "music_midi_bars" | "MIDI音条" | "MIDIバー" | "미디바" | "แท่งมิดี" => {
4493                let id = self.arg_num(&args,0,0.0)? as i64;
4494                let mut out = Vec::new();
4495                if let Some(m) = self.midis.get(id as usize) {
4496                    for n in &m.notes {
4497                        out.push(Value::Number(n.time as f64));
4498                        out.push(Value::Number(n.midi as f64));
4499                        out.push(Value::Number(n.dur as f64));
4500                    }
4501                }
4502                return Ok(Value::List(out));
4503            }
4504
4505            // music_fft(track_id, nbands) -> spectrum at the current playback position
4506            #[cfg(not(target_arch = "wasm32"))]
4507            "music_fft" | "音乐频谱" | "音楽スペクトル" | "음악스펙트럼" | "สเปกตรัมเพลง" => {
4508                let id = self.arg_num(&args,0,0.0)? as i64;
4509                let nbands = self.arg_num(&args,1,16.0)? as usize;
4510                let pos = self.music.as_ref().map(|m| m.position()).unwrap_or(0.0);
4511                if let Some(t) = self.tracks.get(id as usize) {
4512                    let idx = (pos * t.rate as f32) as usize;
4513                    let end = (idx + 2048).min(t.mono.len());
4514                    if end > idx + 64 {
4515                        self.fft.borrow_mut().push_samples(&t.mono[idx..end]);
4516                    }
4517                }
4518                let bands = self.fft.borrow().freq_bands(nbands);
4519                return Ok(Value::List(bands.into_iter().map(|x| Value::Number(x as f64)).collect()));
4520            }
4521
4522            // ── spatial (2D/3D/4D) one-shot SFX ──
4523            #[cfg(not(target_arch = "wasm32"))]
4524            "audio_sfx" | "音效" | "空間効果音" | "공간효과음" | "เสียงเอฟเฟกต์" => {
4525                let x=self.arg_num(&args,0,0.0)? as f32; let y=self.arg_num(&args,1,0.0)? as f32; let z=self.arg_num(&args,2,0.0)? as f32;
4526                let w=self.arg_num(&args,3,1.0)? as f32; let freq=self.arg_num(&args,4,440.0)? as f32;
4527                let amp=self.arg_num(&args,5,0.3)? as f32; let dur=self.arg_num(&args,6,0.15)? as f32;
4528                let wave=Wave::from_name(&self.arg_str(&args,7,"sine"));
4529                if let Some(a)=&self.audio { a.sfx(x,y,z,w,freq,amp,dur,wave); }
4530                return Ok(Value::Unit);
4531            }
4532            // ── sample load / positional play / loop / stop ──
4533            #[cfg(not(target_arch = "wasm32"))]
4534            "audio_sample_load" | "载入采样" | "サンプル読込" | "샘플로드" | "โหลดตัวอย่างเสียง" => {
4535                let path = self.arg_str(&args, 0, "");
4536                let resolved = if std::path::Path::new(&path).exists() { path.clone() }
4537                    else if let Some(d) = &self.source_dir { d.join(&path).to_string_lossy().into_owned() }
4538                    else { path.clone() };
4539                match ling_music::load(&resolved) {
4540                    Ok(t) => {
4541                        if let Some(a)=&self.audio { return Ok(Value::Number(a.add_sample(t.mono, t.rate) as f64)); }
4542                        return Ok(Value::Number(-1.0));
4543                    }
4544                    Err(e) => { eprintln!("audio_sample_load failed ({path}): {e}"); return Ok(Value::Number(-1.0)); }
4545                }
4546            }
4547            #[cfg(not(target_arch = "wasm32"))]
4548            "audio_sample_play" | "播放采样" | "サンプル再生" | "샘플재생" | "เล่นตัวอย่างเสียง" => {
4549                let id=self.arg_num(&args,0,0.0)? as usize;
4550                let x=self.arg_num(&args,1,0.0)? as f32; let y=self.arg_num(&args,2,0.0)? as f32; let z=self.arg_num(&args,3,0.0)? as f32;
4551                let w=self.arg_num(&args,4,1.0)? as f32; let vol=self.arg_num(&args,5,1.0)? as f32;
4552                let looping=self.arg_num(&args,6,0.0)? > 0.5;
4553                let v = self.audio.as_ref().map(|a| a.play_sample(id,x,y,z,w,vol,looping)).unwrap_or(0);
4554                return Ok(Value::Number(v as f64));
4555            }
4556            #[cfg(not(target_arch = "wasm32"))]
4557            "audio_sample_stop" | "停止采样" | "サンプル停止" | "샘플정지" | "หยุดตัวอย่างเสียง" => {
4558                let v=self.arg_num(&args,0,0.0)? as u32;
4559                if let Some(a)=&self.audio { a.stop_sample(v); }
4560                return Ok(Value::Unit);
4561            }
4562            // ── master FX: delay / reverb / low-pass (underwater) ──
4563            #[cfg(not(target_arch = "wasm32"))]
4564            "audio_fx_delay" | "回声" | "ディレイ効果" | "딜레이" | "เสียงสะท้อน" => {
4565                let time=self.arg_num(&args,0,0.3)? as f32; let fb=self.arg_num(&args,1,0.3)? as f32; let mix=self.arg_num(&args,2,0.3)? as f32;
4566                if let Some(a)=&self.audio { a.fx_delay(time,fb,mix); }
4567                return Ok(Value::Unit);
4568            }
4569            #[cfg(not(target_arch = "wasm32"))]
4570            "audio_fx_reverb" | "混响" | "リバーブ" | "리버브" | "เสียงก้อง" => {
4571                let mix=self.arg_num(&args,0,0.3)? as f32;
4572                if let Some(a)=&self.audio { a.fx_reverb(mix); }
4573                return Ok(Value::Unit);
4574            }
4575            #[cfg(not(target_arch = "wasm32"))]
4576            "audio_fx_lowpass" | "低通滤波" | "ローパス" | "저역통과" | "กรองความถี่ต่ำ" => {
4577                let cutoff=self.arg_num(&args,0,1.0)? as f32;
4578                if let Some(a)=&self.audio { a.fx_lowpass(cutoff); }
4579                return Ok(Value::Unit);
4580            }
4581
4582            // ══════════════════════════════════════════════════════════════════
4583            // PHYSICS BUILTINS  (crates/ling-physics) — soft bodies, rigid+angular,
4584            // and a fast 2-D water/oil liquid sim mappable onto 3-D surfaces.
4585            // ══════════════════════════════════════════════════════════════════
4586
4587            // ── soft bodies (deformable bouncy balls) ──
4588            #[cfg(not(target_arch = "wasm32"))]
4589            "soft_ball" | "软球" | "ソフトボール" | "소프트볼" | "ลูกบอลนุ่ม" => {
4590                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32; let z=self.arg_num(&args,2,0.)? as f32;
4591                let r=self.arg_num(&args,3,1.0)? as f32;
4592                let b = ling_physics::soft::SoftBody::sphere(ling_physics::Vec3::new(x,y,z), r, 8, 12, 1.0);
4593                let id = self.soft_bodies.len(); self.soft_bodies.push(b);
4594                return Ok(Value::Number(id as f64));
4595            }
4596            #[cfg(not(target_arch = "wasm32"))]
4597            "soft_step" | "软体步进" | "ソフト更新" | "소프트스텝" | "ก้าวนุ่ม" => {
4598                let id=self.arg_num(&args,0,0.)? as usize; let dt=self.arg_num(&args,1,0.016)? as f32;
4599                let gy=self.arg_num(&args,2,15.0)? as f32;
4600                if let Some(b)=self.soft_bodies.get_mut(id) { b.integrate(dt, ling_physics::Vec3::new(0.0,gy,0.0), 4); }
4601                return Ok(Value::Unit);
4602            }
4603            #[cfg(not(target_arch = "wasm32"))]
4604            "soft_bounce" | "软体落地" | "ソフト着地" | "소프트바운스" | "เด้งนุ่ม" => {
4605                let id=self.arg_num(&args,0,0.)? as usize; let fy=self.arg_num(&args,1,0.)? as f32; let rest=self.arg_num(&args,2,0.5)? as f32;
4606                if let Some(b)=self.soft_bodies.get_mut(id) { b.floor_collision(fy, rest); }
4607                return Ok(Value::Unit);
4608            }
4609            #[cfg(not(target_arch = "wasm32"))]
4610            "soft_contain" | "软体边界" | "ソフト箱" | "소프트경계" | "กล่องนุ่ม" => {
4611                let id=self.arg_num(&args,0,0.)? as usize;
4612                let nx=self.arg_num(&args,1,-5.)? as f32; let ny=self.arg_num(&args,2,-5.)? as f32; let nz=self.arg_num(&args,3,-5.)? as f32;
4613                let mx=self.arg_num(&args,4,5.)? as f32; let my=self.arg_num(&args,5,5.)? as f32; let mz=self.arg_num(&args,6,5.)? as f32;
4614                let rest=self.arg_num(&args,7,0.6)? as f32;
4615                if let Some(b)=self.soft_bodies.get_mut(id) { b.contain(ling_physics::Vec3::new(nx,ny,nz), ling_physics::Vec3::new(mx,my,mz), rest); }
4616                return Ok(Value::Unit);
4617            }
4618            #[cfg(not(target_arch = "wasm32"))]
4619            "soft_kick" | "软体踢" | "ソフト衝撃" | "소프트킥" | "เตะนุ่ม" => {
4620                let id=self.arg_num(&args,0,0.)? as usize;
4621                let dx=self.arg_num(&args,1,0.)? as f32; let dy=self.arg_num(&args,2,0.)? as f32; let dz=self.arg_num(&args,3,0.)? as f32;
4622                let s=self.arg_num(&args,4,0.1)? as f32;
4623                if let Some(b)=self.soft_bodies.get_mut(id) { b.kick(ling_physics::Vec3::new(dx,dy,dz), s); }
4624                return Ok(Value::Unit);
4625            }
4626            // soft_spin(id, ax, ay, az, rate) — add angular velocity about the axis
4627            // through the centroid (rate = rad/step; ≈ surface_speed / radius to roll)
4628            #[cfg(not(target_arch = "wasm32"))]
4629            "soft_spin" | "软体自旋" | "ソフト回転" | "소프트회전" | "หมุนนุ่ม" => {
4630                let id=self.arg_num(&args,0,0.)? as usize;
4631                let ax=self.arg_num(&args,1,0.)? as f32; let ay=self.arg_num(&args,2,0.)? as f32; let az=self.arg_num(&args,3,0.)? as f32;
4632                let rate=self.arg_num(&args,4,0.1)? as f32;
4633                if let Some(b)=self.soft_bodies.get_mut(id) { b.spin(ling_physics::Vec3::new(ax,ay,az), rate); }
4634                return Ok(Value::Unit);
4635            }
4636            #[cfg(not(target_arch = "wasm32"))]
4637            "soft_deform" | "形变量" | "変形量" | "변형량" | "ความบิดเบี้ยว" => {
4638                let id=self.arg_num(&args,0,0.)? as usize;
4639                let d=self.soft_bodies.get(id).map(|b| b.deformation()).unwrap_or(0.0);
4640                return Ok(Value::Number(d as f64));
4641            }
4642            // soft_angular_speed(id) -> magnitude of the body's angular velocity
4643            // (how fast it is tumbling/rolling), derived from its node velocities.
4644            #[cfg(not(target_arch = "wasm32"))]
4645            "soft_angular_speed" | "软体角速" | "ソフト角速度" | "소프트각속도" | "ความเร็วเชิงมุมนุ่ม" => {
4646                let id=self.arg_num(&args,0,0.)? as usize;
4647                let w=self.soft_bodies.get(id).map(|b| b.angular_speed()).unwrap_or(0.0);
4648                return Ok(Value::Number(w as f64));
4649            }
4650            #[cfg(not(target_arch = "wasm32"))]
4651            "soft_centroid" | "软体质心" | "ソフト重心" | "소프트중심" | "จุดศูนย์กลางนุ่ม" => {
4652                let id=self.arg_num(&args,0,0.)? as usize;
4653                let c=self.soft_bodies.get(id).map(|b| b.centroid()).unwrap_or(ling_physics::Vec3::ZERO);
4654                return Ok(Value::List(vec![Value::Number(c.x as f64),Value::Number(c.y as f64),Value::Number(c.z as f64)]));
4655            }
4656            // soft_nodes(id) -> flat [x,y,z, x,y,z, …] for rendering the deformed mesh
4657            #[cfg(not(target_arch = "wasm32"))]
4658            "soft_nodes" | "软体节点" | "ソフト節点" | "소프트노드" | "จุดนุ่ม" => {
4659                let id=self.arg_num(&args,0,0.)? as usize;
4660                let mut out=Vec::new();
4661                if let Some(b)=self.soft_bodies.get(id) {
4662                    for n in &b.nodes { out.push(Value::Number(n.pos.x as f64)); out.push(Value::Number(n.pos.y as f64)); out.push(Value::Number(n.pos.z as f64)); }
4663                }
4664                return Ok(Value::List(out));
4665            }
4666
4667            // ── rigid bodies with angular dynamics ──
4668            #[cfg(not(target_arch = "wasm32"))]
4669            "rb_add" | "刚体添加" | "剛体追加" | "강체추가" | "เพิ่มวัตถุแข็ง" => {
4670                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32; let z=self.arg_num(&args,2,0.)? as f32;
4671                let mass=self.arg_num(&args,3,1.0)? as f32;
4672                let mut b = ling_physics::rigid::RigidBody::new(ling_physics::Vec3::new(x,y,z), mass);
4673                b.restitution = 0.6;
4674                return Ok(Value::Number(self.rigid_world.add(b) as f64));
4675            }
4676            #[cfg(not(target_arch = "wasm32"))]
4677            "rb_torque" | "扭矩" | "トルク" | "토크" | "แรงบิด" => {
4678                let i=self.arg_num(&args,0,0.)? as usize;
4679                let tx=self.arg_num(&args,1,0.)? as f32; let ty=self.arg_num(&args,2,0.)? as f32; let tz=self.arg_num(&args,3,0.)? as f32;
4680                if let Some(b)=self.rigid_world.bodies.get_mut(i) { b.apply_torque(ling_physics::Vec3::new(tx,ty,tz)); }
4681                return Ok(Value::Unit);
4682            }
4683            #[cfg(not(target_arch = "wasm32"))]
4684            "rb_spin" | "自旋" | "スピン" | "스핀" | "หมุน" => {
4685                let i=self.arg_num(&args,0,0.)? as usize;
4686                let wx=self.arg_num(&args,1,0.)? as f32; let wy=self.arg_num(&args,2,0.)? as f32; let wz=self.arg_num(&args,3,0.)? as f32;
4687                if let Some(b)=self.rigid_world.bodies.get_mut(i) { b.apply_spin(ling_physics::Vec3::new(wx,wy,wz)); }
4688                return Ok(Value::Unit);
4689            }
4690            #[cfg(not(target_arch = "wasm32"))]
4691            "rb_impulse" | "刚体冲量" | "剛体インパルス" | "강체충격" | "แรงดลแข็ง" => {
4692                let i=self.arg_num(&args,0,0.)? as usize;
4693                let ix=self.arg_num(&args,1,0.)? as f32; let iy=self.arg_num(&args,2,0.)? as f32; let iz=self.arg_num(&args,3,0.)? as f32;
4694                if let Some(b)=self.rigid_world.bodies.get_mut(i) { b.apply_impulse(ling_physics::Vec3::new(ix,iy,iz)); }
4695                return Ok(Value::Unit);
4696            }
4697            #[cfg(not(target_arch = "wasm32"))]
4698            "rb_floor" | "刚体落地" | "剛体着地" | "강체바닥" | "พื้นแข็ง" => {
4699                let i=self.arg_num(&args,0,0.)? as usize; let fy=self.arg_num(&args,1,0.)? as f32;
4700                let rest=self.arg_num(&args,2,0.6)? as f32; let fric=self.arg_num(&args,3,0.6)? as f32;
4701                if let Some(b)=self.rigid_world.bodies.get_mut(i) { b.bounce_floor(fy, rest, fric); }
4702                return Ok(Value::Unit);
4703            }
4704            #[cfg(not(target_arch = "wasm32"))]
4705            "rb_gravity" | "刚体重力" | "剛体重力" | "강체중력" | "แรงโน้มถ่วงแข็ง" => {
4706                let gx=self.arg_num(&args,0,0.)? as f32; let gy=self.arg_num(&args,1,9.81)? as f32; let gz=self.arg_num(&args,2,0.)? as f32;
4707                self.rigid_world.gravity = ling_physics::Vec3::new(gx,gy,gz);
4708                return Ok(Value::Unit);
4709            }
4710            #[cfg(not(target_arch = "wasm32"))]
4711            "rb_step" | "刚体步进" | "剛体更新" | "강체스텝" | "ก้าวแข็ง" => {
4712                let dt=self.arg_num(&args,0,0.016)? as f32;
4713                self.rigid_world.step(dt);
4714                return Ok(Value::Unit);
4715            }
4716            #[cfg(not(target_arch = "wasm32"))]
4717            "rb_pos" | "刚体位置" | "剛体位置" | "강체위치" | "ตำแหน่งแข็ง" => {
4718                let i=self.arg_num(&args,0,0.)? as usize;
4719                let p=self.rigid_world.bodies.get(i).map(|b| b.pos).unwrap_or(ling_physics::Vec3::ZERO);
4720                return Ok(Value::List(vec![Value::Number(p.x as f64),Value::Number(p.y as f64),Value::Number(p.z as f64)]));
4721            }
4722            #[cfg(not(target_arch = "wasm32"))]
4723            "rb_rot" | "刚体旋转" | "剛体回転" | "강체회전" | "การหมุนแข็ง" => {
4724                let i=self.arg_num(&args,0,0.)? as usize;
4725                let q=self.rigid_world.bodies.get(i).map(|b| b.orientation).unwrap_or(ling_physics::Quat::IDENTITY);
4726                return Ok(Value::List(vec![Value::Number(q.x as f64),Value::Number(q.y as f64),Value::Number(q.z as f64),Value::Number(q.w as f64)]));
4727            }
4728
4729            // ── liquid sim (water + oil, immiscible) ──
4730            #[cfg(not(target_arch = "wasm32"))]
4731            "liquid_new" | "新建液体" | "液体新規" | "액체생성" | "สร้างของเหลว" => {
4732                let w=self.arg_num(&args,0,64.)? as usize; let h=self.arg_num(&args,1,64.)? as usize;
4733                let id=self.liquids.len(); self.liquids.push(ling_physics::liquid::LiquidGrid::new(w,h));
4734                return Ok(Value::Number(id as f64));
4735            }
4736            #[cfg(not(target_arch = "wasm32"))]
4737            "liquid_splat" | "液体注入" | "液体追加" | "액체분사" | "หยดของเหลว" => {
4738                let id=self.arg_num(&args,0,0.)? as usize;
4739                let x=self.arg_num(&args,1,0.)? as f32; let y=self.arg_num(&args,2,0.)? as f32;
4740                let kind=self.arg_num(&args,3,0.)? as i32; let amt=self.arg_num(&args,4,1.0)? as f32; let rad=self.arg_num(&args,5,4.0)? as f32;
4741                if let Some(g)=self.liquids.get_mut(id) { g.splat(x,y,kind,amt,rad); }
4742                return Ok(Value::Unit);
4743            }
4744            #[cfg(not(target_arch = "wasm32"))]
4745            "liquid_gravity" | "液体重力" | "液体重力ベクトル" | "액체중력" | "แรงโน้มถ่วงเหลว" => {
4746                let id=self.arg_num(&args,0,0.)? as usize;
4747                let gx=self.arg_num(&args,1,0.)? as f32; let gy=self.arg_num(&args,2,60.)? as f32;
4748                if let Some(g)=self.liquids.get_mut(id) { g.set_gravity(gx,gy); }
4749                return Ok(Value::Unit);
4750            }
4751            #[cfg(not(target_arch = "wasm32"))]
4752            "liquid_step" | "液体步进" | "液体更新" | "액체스텝" | "ก้าวของเหลว" => {
4753                let id=self.arg_num(&args,0,0.)? as usize; let dt=self.arg_num(&args,1,0.016)? as f32;
4754                if let Some(g)=self.liquids.get_mut(id) { g.step(dt); }
4755                return Ok(Value::Unit);
4756            }
4757            // liquid_rainbow(id, on) — colour the fluid as a flowing ROYGBIV marble
4758            #[cfg(not(target_arch = "wasm32"))]
4759            "liquid_rainbow" | "液体彩虹" | "液体虹" | "액체무지개" | "ของเหลวสายรุ้ง" => {
4760                let id=self.arg_num(&args,0,0.)? as usize;
4761                let on=self.arg_num(&args,1,1.0)? > 0.5;
4762                if let Some(g)=self.liquids.get_mut(id) { g.rainbow = on; }
4763                return Ok(Value::Unit);
4764            }
4765            // liquid_mix(id) -> 0 (oil/water separated) .. 1 (fully intermixed)
4766            #[cfg(not(target_arch = "wasm32"))]
4767            "liquid_mix" | "液体混合" | "液体混合度" | "액체혼합" | "การผสมของเหลว" => {
4768                let id=self.arg_num(&args,0,0.)? as usize;
4769                let m=self.liquids.get(id).map(|g| g.mix_amount()).unwrap_or(0.0);
4770                return Ok(Value::Number(m as f64));
4771            }
4772            // liquid_draw(id, sx, sy, scale) — fast flat 2-D blit of the colour field
4773            #[cfg(not(target_arch = "wasm32"))]
4774            "liquid_draw" | "绘制液体" | "液体描画" | "액체그리기" | "วาดของเหลว" => {
4775                let id=self.arg_num(&args,0,0.)? as usize;
4776                let sx=self.arg_num(&args,1,0.)? as i32; let sy=self.arg_num(&args,2,0.)? as i32;
4777                let scale=(self.arg_num(&args,3,4.)? as i32).max(1);
4778                if id < self.liquids.len() {
4779                    let (gw,gh)={ let g=&self.liquids[id]; (g.w,g.h) };
4780                    let mut gfx=self.gfx.borrow_mut(); let (w,h)=(gfx.width as i32, gfx.height as i32);
4781                    let g=&self.liquids[id];
4782                    for cy in 0..gh { for cx in 0..gw {
4783                        let col=g.sample_rgb(cx,cy);
4784                        let bx=sx + cx as i32*scale; let by=sy + cy as i32*scale;
4785                        for dy in 0..scale { for dx in 0..scale {
4786                            let px=bx+dx; let py=by+dy;
4787                            if px>=0 && py>=0 && px<w && py<h { gfx.buffer[(py*w+px) as usize]=col; }
4788                        }}
4789                    }}
4790                }
4791                return Ok(Value::Unit);
4792            }
4793            // liquid_draw_surface(id, kind, cx,cy,cz, radius, height)
4794            //   kind: 0 plane · 1 sphere · 2 cylinder · 3 cone · 4 dome
4795            #[cfg(not(target_arch = "wasm32"))]
4796            "liquid_draw_surface" | "液体贴面" | "液体曲面" | "액체곡면" | "ของเหลวบนพื้นผิว" => {
4797                let id=self.arg_num(&args,0,0.)? as usize;
4798                let kind=self.arg_num(&args,1,1.)? as i32;
4799                let cx=self.arg_num(&args,2,0.)? as f32; let cy=self.arg_num(&args,3,0.)? as f32; let cz=self.arg_num(&args,4,0.)? as f32;
4800                let radius=self.arg_num(&args,5,2.0)? as f32; let height=self.arg_num(&args,6,3.0)? as f32;
4801                if id < self.liquids.len() {
4802                    let (gw,gh)={ let g=&self.liquids[id]; (g.w,g.h) };
4803                    let mut gfx=self.gfx.borrow_mut();
4804                    let (w,h,add)=(gfx.width, gfx.height, gfx.blend==1);
4805                    let cam=gfx.camera.clone();
4806                    let near = -cam.zdist + 0.05;
4807                    let g=&self.liquids[id];
4808                    let tau=std::f32::consts::TAU; let pi=std::f32::consts::PI;
4809                    // surface point for a (u,v) in [0,1] on the chosen primitive
4810                    let sp = |u:f32, v:f32| -> [f32;3] {
4811                        if kind==0 { [cx+(u-0.5)*2.0*radius, cy, cz+(v-0.5)*2.0*radius] }
4812                        else if kind==2 { let th=u*tau; [cx+th.cos()*radius, cy+(v-0.5)*height, cz+th.sin()*radius] }
4813                        else if kind==3 { let th=u*tau; let rr=radius*(1.0-v); [cx+th.cos()*rr, cy+(v-0.5)*height, cz+th.sin()*rr] }
4814                        else if kind==4 { let th=u*tau; let ph=v*pi*0.5; [cx+ph.sin()*th.cos()*radius, cy-ph.cos()*radius, cz+ph.sin()*th.sin()*radius] }
4815                        else { let th=u*tau; let ph=v*pi; [cx+ph.sin()*th.cos()*radius, cy+ph.cos()*radius, cz+ph.sin()*th.sin()*radius] }
4816                    };
4817                    let nrm = |u:f32, v:f32| -> [f32;3] {
4818                        if kind==0 { [0.0,-1.0,0.0] }
4819                        else if kind==2 { let th=u*tau; [th.cos(),0.0,th.sin()] }
4820                        else if kind==3 { let th=u*tau; let s=(radius/height.max(0.01)).atan(); [th.cos()*s.cos(), s.sin(), th.sin()*s.cos()] }
4821                        else if kind==4 { let th=u*tau; let ph=v*pi*0.5; [ph.sin()*th.cos(),-ph.cos(),ph.sin()*th.sin()] }
4822                        else { let th=u*tau; let ph=v*pi; [ph.sin()*th.cos(),ph.cos(),ph.sin()*th.sin()] }
4823                    };
4824                    let gwf=gw as f32; let ghf=gh as f32;
4825                    let mut cyc=0usize;
4826                    while cyc<gh {
4827                        let mut cxc=0usize;
4828                        while cxc<gw {
4829                            // cull by the cell centre's outward normal
4830                            let uc=(cxc as f32+0.5)/gwf; let vc=(cyc as f32+0.5)/ghf;
4831                            let c=sp(uc,vc); let n=nrm(uc,vc);
4832                            let dc=cam.depth(c[0],c[1],c[2]);
4833                            if dc>near {
4834                                let cull = kind!=0 && cam.depth(c[0]+n[0]*0.06,c[1]+n[1]*0.06,c[2]+n[2]*0.06) > dc;
4835                                if !cull {
4836                                    // project the 4 cell corners → a filled AA vector quad
4837                                    let u0=cxc as f32/gwf; let u1=(cxc+1) as f32/gwf;
4838                                    let v0=cyc as f32/ghf; let v1=(cyc+1) as f32/ghf;
4839                                    let q=[sp(u0,v0),sp(u1,v0),sp(u1,v1),sp(u0,v1)];
4840                                    let mut poly: Vec<[f32;2]> = Vec::with_capacity(5);
4841                                    let mut ok=true;
4842                                    for p in &q { if cam.depth(p[0],p[1],p[2])<=near { ok=false; break; } let (sx,sy,_)=cam.project(p[0],p[1],p[2]); poly.push([sx,sy]); }
4843                                    if ok { let p0=poly[0]; poly.push(p0);
4844                                        let col=g.sample_rgb(cxc,cyc);
4845                                        crate::gfx::raster::fill_contours_aa(&mut gfx.buffer, w, h, col, add, std::slice::from_ref(&poly));
4846                                    }
4847                                }
4848                            }
4849                            cxc+=1;
4850                        }
4851                        cyc+=1;
4852                    }
4853                }
4854                return Ok(Value::Unit);
4855            }
4856            // sparkle(x, y, w, h, count [, t]) — scatter twinkling vector star-sparkles
4857            // in a rect (snowglobe effect) in the current colour + blend mode.
4858            #[cfg(not(target_arch = "wasm32"))]
4859            "sparkle" | "闪光" | "きらめき" | "반짝임" | "ประกาย" => {
4860                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
4861                let ww=self.arg_num(&args,2,200.)? as f32; let hh=self.arg_num(&args,3,200.)? as f32;
4862                let count=self.arg_num(&args,4,40.)? as i32;
4863                let t=self.arg_num(&args,5,0.)? as f32;
4864                let mut gfx=self.gfx.borrow_mut();
4865                let (w,h,add,color)=(gfx.width, gfx.height, gfx.blend==1, gfx.color);
4866                let (cr,cg,cb)=((color>>16&0xFF) as f32,(color>>8&0xFF) as f32,(color&0xFF) as f32);
4867                let mut n=0i32;
4868                while n<count {
4869                    let hsh=(n as u32).wrapping_mul(2654435761).wrapping_add(0x9E3779B9);
4870                    let u=((hsh>>8)&1023) as f32/1023.0;
4871                    let v=((hsh>>18)&1023) as f32/1023.0;
4872                    let phase=(hsh&255) as f32/255.0;
4873                    let tw=(t*3.0 + phase*6.2831 + n as f32).sin()*0.5+0.5;
4874                    let sz=1.5+tw*5.0;
4875                    let px=x+u*ww; let py=y+v*hh;
4876                    let b=tw*tw; // sharp twinkle
4877                    let col=(((cr*b)as u32)<<16)|(((cg*b)as u32)<<8)|((cb*b)as u32);
4878                    crate::gfx::raster::draw_line_aa(&mut gfx.buffer,w,h,col,add, px-sz,py, px+sz,py);
4879                    crate::gfx::raster::draw_line_aa(&mut gfx.buffer,w,h,col,add, px,py-sz, px,py+sz);
4880                    let d=sz*0.55;
4881                    crate::gfx::raster::draw_line_aa(&mut gfx.buffer,w,h,col,add, px-d,py-d, px+d,py+d);
4882                    crate::gfx::raster::draw_line_aa(&mut gfx.buffer,w,h,col,add, px-d,py+d, px+d,py-d);
4883                    n+=1;
4884                }
4885                return Ok(Value::Unit);
4886            }
4887
4888            // ══════════════════════════════════════════════════════════════════
4889            // DIALOG BUILTINS  (crates/ling-game/src/dialog.rs) — cinematic,
4890            // typed-out, colour-coded text boxes. Markup: {n}name{/} {p}place{/}
4891            // {i}item{/}, \n newline, || page break.
4892            // ══════════════════════════════════════════════════════════════════
4893            #[cfg(not(target_arch = "wasm32"))]
4894            "dialog_show" | "对话显示" | "会話表示" | "대화표시" | "แสดงบทสนทนา" => {
4895                let text = self.arg_str(&args, 0, "");
4896                let cps = self.arg_num(&args, 1, 32.0)? as f32;
4897                self.dialog = Some(ling_game::dialog::Dialog::new(&text, cps));
4898                return Ok(Value::Unit);
4899            }
4900            #[cfg(not(target_arch = "wasm32"))]
4901            "dialog_step" | "对话步进" | "会話更新" | "대화스텝" | "ก้าวบทสนทนา" => {
4902                let dt = self.arg_num(&args, 0, 0.016)? as f32;
4903                if let Some(d) = self.dialog.as_mut() { d.update(dt); }
4904                return Ok(Value::Unit);
4905            }
4906            #[cfg(not(target_arch = "wasm32"))]
4907            "dialog_advance" | "对话推进" | "会話送り" | "대화진행" | "เลื่อนบทสนทนา" => {
4908                if let Some(d) = self.dialog.as_mut() { d.advance(); }
4909                return Ok(Value::Unit);
4910            }
4911            #[cfg(not(target_arch = "wasm32"))]
4912            "dialog_active" | "对话激活" | "会話中" | "대화중" | "บทสนทนาทำงาน" => {
4913                let a = self.dialog.as_ref().map(|d| !d.is_closed()).unwrap_or(false);
4914                return Ok(Value::Bool(a));
4915            }
4916            #[cfg(not(target_arch = "wasm32"))]
4917            "dialog_typing" | "对话打字" | "会話タイプ中" | "대화타이핑" | "กำลังพิมพ์บทสนทนา" => {
4918                use ling_game::dialog::Dialog;
4919                
4920                let a = self.dialog.as_ref().map(|d: &Dialog | !d.is_closed() && d.is_typing()).unwrap_or(false);
4921                return Ok(Value::Bool(a))
4922            }
4923            #[cfg(not(target_arch = "wasm32"))]
4924            "dialog_close" | "对话关闭" | "会話閉じる" | "대화닫기" | "ปิดบทสนทนา" => {
4925                self.dialog = None;
4926                return Ok(Value::Unit);
4927            }
4928            // dialog_color(role, r, g, b) — role: 0 text · 1 name · 2 place · 3 item
4929            #[cfg(not(target_arch = "wasm32"))]
4930            "dialog_color" | "对话颜色" | "会話色" | "대화색" | "สีบทสนทนา" => {
4931                let role = (self.arg_num(&args,0,0.0)? as usize).min(3);
4932                let r = self.arg_num(&args,1,255.0)? as u32 & 0xFF;
4933                let g = self.arg_num(&args,2,255.0)? as u32 & 0xFF;
4934                let b = self.arg_num(&args,3,255.0)? as u32 & 0xFF;
4935                self.dialog_colors[role] = (r<<16)|(g<<8)|b;
4936                return Ok(Value::Unit);
4937            }
4938            // dialog_draw(x, y, w, h [, font_handle]) — draw the box + typed text
4939            #[cfg(not(target_arch = "wasm32"))]
4940            "dialog_draw" | "对话绘制" | "会話描画" | "대화그리기" | "วาดบทสนทนา" => {
4941                let x=self.arg_num(&args,0,40.0)? as f32; let y=self.arg_num(&args,1,0.0)? as f32;
4942                let ww=self.arg_num(&args,2,720.0)? as f32; let hh=self.arg_num(&args,3,150.0)? as f32;
4943                let font = self.arg_num(&args,4,-1.0)? as i64;
4944                let t = self.start_time.elapsed().as_secs_f32();
4945                self.render_dialog(x, y, ww, hh, font, t);
4946                return Ok(Value::Unit);
4947            }
4948
4949            // text_poll() — fold newly-typed keys into the input buffer, return it
4950            #[cfg(not(target_arch = "wasm32"))]
4951            "text_poll" => {
4952                let keys = { let gfx = self.gfx.borrow(); gfx.window.as_ref().map(|w| w.get_keys_pressed(minifb::KeyRepeat::No)).unwrap_or_default() };
4953                for k in keys {
4954                    if k == minifb::Key::Backspace { self.text_buffer.pop(); }
4955                    else if let Some(c) = key_char(k) { self.text_buffer.push(c); }
4956                }
4957                return Ok(Value::Str(self.text_buffer.clone()));
4958            }
4959            "text_get"   => return Ok(Value::Str(self.text_buffer.clone())),
4960            "text_set"   => { self.text_buffer = self.arg_str(&args,0,""); return Ok(Value::Unit); }
4961            "text_clear" => { self.text_buffer.clear(); return Ok(Value::Unit); }
4962            // record_frame() — append the current framebuffer as a PPM, return frame #
4963            #[cfg(not(target_arch = "wasm32"))]
4964            "record_frame" => {
4965                let n = self.record_n;
4966                let (buf, w, h) = { let gfx = self.gfx.borrow(); (gfx.buffer.clone(), gfx.width, gfx.height) };
4967                let _ = std::fs::create_dir_all("recordings");
4968                let mut out = Vec::with_capacity(w*h*3 + 32);
4969                out.extend_from_slice(format!("P6\n{w} {h}\n255\n").as_bytes());
4970                for px in &buf { let p = *px; out.push((p>>16) as u8); out.push((p>>8) as u8); out.push(p as u8); }
4971                let _ = std::fs::write(format!("recordings/frame_{n:05}.ppm"), out);
4972                self.record_n += 1;
4973                return Ok(Value::Number(n as f64));
4974            }
4975            "record_count" => return Ok(Value::Number(self.record_n as f64)),
4976            // ── microphone → crypto donut ──
4977            // mic_capture() — append the latest mic samples to the record buffer
4978            // (call each frame while recording). Returns the buffer length.
4979            #[cfg(not(target_arch = "wasm32"))]
4980            "mic_capture" => {
4981                if let Some(mic) = self.mic.as_ref() {
4982                    let s = mic.latest_samples();
4983                    self.mic_buffer.extend_from_slice(&s);
4984                    let cap = 96_000usize; // ~2 s @ 48 kHz
4985                    if self.mic_buffer.len() > cap {
4986                        let drop = self.mic_buffer.len() - cap;
4987                        self.mic_buffer.drain(0..drop);
4988                    }
4989                }
4990                return Ok(Value::Number(self.mic_buffer.len() as f64));
4991            }
4992            // mic_seed() — SHA3-256 hex of the recorded audio, usable as a donut seed
4993            #[cfg(not(target_arch = "wasm32"))]
4994            "mic_seed" => {
4995                let mut bytes = Vec::with_capacity(self.mic_buffer.len() * 4);
4996                for f in &self.mic_buffer { bytes.extend_from_slice(&f.to_le_bytes()); }
4997                return Ok(Value::Str(hex_encode(&ling_crypto::geo::holo_hash(&bytes))));
4998            }
4999            #[cfg(not(target_arch = "wasm32"))]
5000            "mic_clear" => { self.mic_buffer.clear(); return Ok(Value::Number(0.0)); }
5001            // flush the 3-D depth queue onto the framebuffer WITHOUT presenting,
5002            // so 2-D UI drawn afterwards overlays the 3-D scene.
5003            #[cfg(not(target_arch = "wasm32"))]
5004            "flush_3d" | "render_3d" => {
5005                let mut gfx = self.gfx.borrow_mut();
5006                if !gfx.depth_queue.is_empty() {
5007                    let w = gfx.width; let h = gfx.height;
5008                    let queue = std::mem::take(&mut gfx.depth_queue);
5009                    queue.flush(&mut gfx.buffer, w, h);
5010                }
5011                return Ok(Value::Unit);
5012            }
5013
5014            "set_rim" | "设置边缘光" | "リム設定" | "림라이트" | "ตั้งขอบเรือง" => {
5015                let s=self.arg_num(&args,0,0.6)? as f32;
5016                let r=self.arg_num(&args,1,115.)? as f32/255.0;
5017                let g=self.arg_num(&args,2,217.)? as f32/255.0;
5018                let b=self.arg_num(&args,3,255.)? as f32/255.0;
5019                let mut gfx=self.gfx.borrow_mut();
5020                gfx.shade.rim = s; gfx.shade.rim_color = [r,g,b];
5021                return Ok(Value::Unit);
5022            }
5023
5024            // ══════════════════════════════════════════════════════════════════
5025            // 3-D PRIMITIVES  (src/gfx/shapes.rs)  — "Inkscape for 3-D"
5026            //   shape(cx,cy,cz,  sx,sy,sz,  rx,ry,rz,  mode,  e0,e1,e2)
5027            //     centre (cx,cy,cz), per-axis scale, Euler rotation (radians),
5028            //     mode: 0 filled · 1 wireframe · 2 both,
5029            //     e0..e2: shape-specific (segments / sides / ratio …).
5030            //   Pen colour (set_color) drives fill lighting and wireframe colour.
5031            // ══════════════════════════════════════════════════════════════════
5032            n if crate::gfx::shapes::canon(n).is_some() => {
5033                let kind = crate::gfx::shapes::canon(n).unwrap();
5034                let cx=self.arg_num(&args,0,0.)? as f32; let cy=self.arg_num(&args,1,0.)? as f32; let cz=self.arg_num(&args,2,0.)? as f32;
5035                let sx=self.arg_num(&args,3,1.)? as f32; let sy=self.arg_num(&args,4,1.)? as f32; let sz=self.arg_num(&args,5,1.)? as f32;
5036                let rx=self.arg_num(&args,6,0.)? as f32; let ry=self.arg_num(&args,7,0.)? as f32; let rz=self.arg_num(&args,8,0.)? as f32;
5037                let mode=self.arg_num(&args,9,0.)? as i32;
5038                let e0=self.arg_num(&args,10,0.)? as f32; let e1=self.arg_num(&args,11,0.)? as f32; let e2=self.arg_num(&args,12,0.)? as f32;
5039                if let Some(mesh)=crate::gfx::shapes::build(kind,[cx,cy,cz,sx,sy,sz,rx,ry,rz],e0,e1,e2){
5040                    let mut gfx=self.gfx.borrow_mut();
5041                    gfx.emit_mesh(&mesh,mode);
5042                }
5043                return Ok(Value::Unit);
5044            }
5045
5046            _ => {}
5047        }
5048
5049        // User-defined function
5050        if let Some(def) = self.functions.get(name).cloned() {
5051            // Clone the pre-evaluated global seed (built once in run_program) and
5052            // add the params. Globals are immutable after load, so re-evaluating
5053            // them on every call was pure waste — this is the hot-path fix.
5054            let mut call_env = self.global_seed.clone();
5055            let _ = env; // call-site locals are intentionally NOT visible to fns
5056            for (param, arg) in def.params.iter().zip(args) {
5057                call_env.insert(param.clone(), arg);
5058            }
5059            return match self.framed(name, |me| me.exec_block(&def.body, &mut call_env)) {
5060                Ok(v) => Ok(v.unwrap_or(Value::Unit)),
5061                Err(EvalErr::Return(v)) => Ok(v),
5062                Err(e) => Err(e),
5063            };
5064        }
5065
5066        // `form` struct constructor: positional `Name(v0, v1, ...)`.
5067        if let Some(field_names) = self.structs.get(name).cloned() {
5068            if args.len() != field_names.len() {
5069                return Err(EvalErr::from(format!(
5070                    "{name} expects {} field(s), got {}", field_names.len(), args.len())));
5071            }
5072            let fields = field_names.into_iter().zip(args).collect();
5073            return Ok(Value::Struct { name: name.to_string(), fields });
5074        }
5075
5076        // `choose` enum variant constructor: `Variant(...)` or `Enum::Variant(...)`.
5077        if let Some((enum_name, arity)) = self.enum_variants.get(name).cloned() {
5078            if args.len() != arity {
5079                return Err(EvalErr::from(format!(
5080                    "{name} expects {arity} value(s), got {}", args.len())));
5081            }
5082            let variant = name.rsplit("::").next().unwrap_or(name).to_string();
5083            return Ok(Value::Variant { enum_name, variant, payload: args });
5084        }
5085
5086        Err(EvalErr::from(format!("unknown function '{name}'")))
5087    }
5088
5089    fn call_value(&mut self, v: Value, args: Vec<Value>) -> EvalResult {
5090        match v {
5091            Value::Fn(params, body, mut captured) => {
5092                for (p, a) in params.iter().zip(args) {
5093                    captured.insert(p.clone(), a);
5094                }
5095                match self.framed("<closure>", |me| me.exec_block(&body, &mut captured)) {
5096                    Ok(v) => Ok(v.unwrap_or(Value::Unit)),
5097                    Err(EvalErr::Return(v)) => Ok(v),
5098                    Err(e) => Err(e),
5099                }
5100            }
5101            other => Err(EvalErr::from(format!("cannot call {:?}", other))),
5102        }
5103    }
5104
5105    fn call_method(&self, recv: Value, method: &str, args: Vec<Value>) -> EvalResult {
5106        match (&recv, method) {
5107            (Value::Str(s), "is_empty" | "是空") => Ok(Value::Bool(s.is_empty())),
5108            (Value::Str(s), "len" | "长")        => Ok(Value::Number(s.len() as f64)),
5109            (Value::Str(s), "to_string" | "转文") => Ok(Value::Str(s.clone())),
5110            (Value::Str(s), "contains" | "包含") => {
5111                if let Some(Value::Str(sub)) = args.first() {
5112                    Ok(Value::Bool(s.contains(sub.as_str())))
5113                } else { Ok(Value::Bool(false)) }
5114            }
5115            (Value::Str(s), "push_str" | "推_文") => {
5116                let mut s2 = s.clone();
5117                if let Some(Value::Str(a)) = args.first() { s2.push_str(a); }
5118                Ok(Value::Str(s2))
5119            }
5120            (Value::List(v), "len" | "长") => Ok(Value::Number(v.len() as f64)),
5121            (Value::List(v), "push" | "推") => {
5122                let mut v2 = v.clone();
5123                if let Some(a) = args.first() { v2.push(a.clone()); }
5124                Ok(Value::List(v2))
5125            }
5126            // `form` field access: `point.x` (no-arg method == field read).
5127            (Value::Struct { fields, .. }, _) if args.is_empty() => {
5128                fields.iter().find(|(k, _)| k == method).map(|(_, v)| v.clone())
5129                    .ok_or_else(|| EvalErr::from(format!("no field '{method}' on {recv}")))
5130            }
5131            // Enum introspection: `.tag` → variant name, `.is(Name)` not needed for now.
5132            (Value::Variant { variant, .. }, "tag" | "标签" | "タグ" | "태그" | "ป้าย") if args.is_empty() =>
5133                Ok(Value::Str(variant.clone())),
5134            (Value::Ok(inner), _) | (Value::Err(inner), _) => Ok(*inner.clone()),
5135            _ => Err(EvalErr::from(format!("no method '{method}' on {recv}"))),
5136        }
5137    }
5138
5139    // ─── Pattern matching ─────────────────────────────────────────────────────
5140
5141    fn match_pattern(&self, pat: &Pattern, val: &Value) -> Option<Env> {
5142        match (pat, val) {
5143            (Pattern::Wildcard, _) => Some(Env::new()),
5144            (Pattern::Str(s), Value::Str(v)) if s == v => Some(Env::new()),
5145            (Pattern::Number(n), Value::Number(v)) if (n - v).abs() < 1e-12 => Some(Env::new()),
5146            (Pattern::Bool(b), Value::Bool(v)) if b == v => Some(Env::new()),
5147            (Pattern::Ident(name), _) => {
5148                let mut e = Env::new();
5149                e.insert(name.clone(), val.clone());
5150                Some(e)
5151            }
5152            (Pattern::Constructor(ctor, inner_pat), _) => {
5153                let (matches, inner_val) = match (ctor.as_str(), val) {
5154                    ("ok"  | "好", Value::Ok(v))  => (true, Some(v.as_ref().clone())),
5155                    ("bad" | "坏", Value::Err(v)) => (true, Some(v.as_ref().clone())),
5156                    ("ok"  | "好", v) if !matches!(v, Value::Err(_)) => (true, Some(v.clone())),
5157                    _ => (false, None),
5158                };
5159                if !matches { return None; }
5160                match (inner_pat, inner_val) {
5161                    (Some(p), Some(v)) => self.match_pattern(p, &v),
5162                    (None, _)          => Some(Env::new()),
5163                    (Some(p), None)    => self.match_pattern(p, &Value::Unit),
5164                }
5165            }
5166            // User enum variant pattern: `Circle(r)`, `Pair(a, b)`, nullary `Origin()`.
5167            (Pattern::Variant(vname, sub_pats), Value::Variant { variant, payload, .. }) => {
5168                if vname != variant || sub_pats.len() != payload.len() { return None; }
5169                let mut bindings = Env::new();
5170                for (p, v) in sub_pats.iter().zip(payload.iter()) {
5171                    bindings.extend(self.match_pattern(p, v)?);
5172                }
5173                Some(bindings)
5174            }
5175            // A zero-payload variant pattern also matches the bare result-style `ok`/`bad`
5176            // values so `Ok()`-style patterns keep working uniformly.
5177            (Pattern::Variant(vname, sub), Value::Ok(v)) if (vname == "ok" || vname == "好") => {
5178                match sub.as_slice() {
5179                    []  => Some(Env::new()),
5180                    [p] => self.match_pattern(p, v),
5181                    _   => None,
5182                }
5183            }
5184            (Pattern::Variant(vname, sub), Value::Err(v)) if (vname == "bad" || vname == "坏" || vname == "err") => {
5185                match sub.as_slice() {
5186                    []  => Some(Env::new()),
5187                    [p] => self.match_pattern(p, v),
5188                    _   => None,
5189                }
5190            }
5191            _ => None,
5192        }
5193    }
5194
5195    // ─── Utilities ───────────────────────────────────────────────────────────
5196
5197    fn value_to_iter(&self, val: Value) -> Result<Vec<Value>, EvalErr> {
5198        match val {
5199            Value::List(v)   => Ok(v),
5200            Value::Str(s)    => Ok(s.chars().map(|c| Value::Str(c.to_string())).collect()),
5201            Value::Number(n) => Ok((0..n as i64).map(|i| Value::Number(i as f64)).collect()),
5202            other => Err(EvalErr::from(format!("cannot iterate over {:?}", other))),
5203        }
5204    }
5205
5206    fn is_truthy(&self, val: &Value) -> bool {
5207        match val {
5208            Value::Bool(b)     => *b,
5209            Value::Unit        => false,
5210            Value::Number(n)   => *n != 0.0,
5211            Value::Str(s)      => !s.is_empty(),
5212            Value::List(v)     => !v.is_empty(),
5213            Value::Ok(_)       => true,
5214            Value::Err(_)      => false,
5215            Value::Fn(_, _, _) => true,
5216            Value::Struct { .. }  => true,
5217            Value::Variant { .. } => true,
5218        }
5219    }
5220
5221    fn to_number(&self, val: &Value) -> Result<f64, EvalErr> {
5222        match val {
5223            Value::Number(n) => Ok(*n),
5224            Value::Str(s)    => s.parse().map_err(|_| EvalErr::from(format!("cannot convert '{s}' to number"))),
5225            other => Err(EvalErr::from(format!("expected number, got {:?}", other))),
5226        }
5227    }
5228
5229    /// Get the n-th argument as f64, falling back to `default` if missing.
5230    fn arg_num(&self, args: &[Value], n: usize, default: f64) -> Result<f64, EvalErr> {
5231        match args.get(n) {
5232            Some(v) => self.to_number(v),
5233            None    => Ok(default),
5234        }
5235    }
5236
5237    fn arg_str(&self, args: &[Value], n: usize, default: &str) -> String {
5238        args.get(n).map(|v| v.to_string()).unwrap_or_else(|| default.to_string())
5239    }
5240
5241    /// Read a list-of-numbers argument as `Vec<f32>` (empty if absent/not a list).
5242    #[allow(dead_code)]
5243    fn arg_list_f32(&self, args: &[Value], n: usize) -> Vec<f32> {
5244        match args.get(n) {
5245            Some(Value::List(v)) => v.iter().filter_map(|x| match x {
5246                Value::Number(n) => Some(*n as f32),
5247                _ => None,
5248            }).collect(),
5249            _ => Vec::new(),
5250        }
5251    }
5252
5253    /// Optional `r,g,b` colour override starting at arg `i` → packed 0x00RRGGBB,
5254    /// or `default` if those three numeric args aren't present.
5255    #[cfg(not(target_arch = "wasm32"))]
5256    fn color_at(&self, args: &[Value], i: usize, default: u32) -> u32 {
5257        match (args.get(i), args.get(i + 1), args.get(i + 2)) {
5258            (Some(a), Some(b), Some(c)) => match (self.to_number(a), self.to_number(b), self.to_number(c)) {
5259                (Ok(r), Ok(g), Ok(bl)) =>
5260                    ((r as u32 & 0xFF) << 16) | ((g as u32 & 0xFF) << 8) | (bl as u32 & 0xFF),
5261                _ => default,
5262            },
5263            _ => default,
5264        }
5265    }
5266
5267    /// A pitch argument: a note-name string (`"C4"`, `"A#3"`) or a numeric MIDI value.
5268    #[cfg(not(target_arch = "wasm32"))]
5269    fn pitch_arg(&self, args: &[Value], i: usize, default: i32) -> i32 {
5270        match args.get(i) {
5271            Some(Value::Str(s)) => ling_music::note::parse_pitch(s).unwrap_or(default),
5272            Some(Value::Number(n)) => *n as i32,
5273            _ => default,
5274        }
5275    }
5276
5277    /// Current mouse position + left-button-down (native window only).
5278    #[cfg(not(target_arch = "wasm32"))]
5279    fn mouse_now(&self) -> (f32, f32, bool) {
5280        let gfx = self.gfx.borrow();
5281        let (mx, my) = gfx.window.as_ref()
5282            .and_then(|w| w.get_mouse_pos(minifb::MouseMode::Clamp)).unwrap_or((0.0, 0.0));
5283        let down = gfx.window.as_ref()
5284            .map(|w| w.get_mouse_down(minifb::MouseButton::Left)).unwrap_or(false);
5285        (mx, my, down)
5286    }
5287
5288    /// Rasterize a UI [`ling_ui::widgets::Draw`] into the framebuffer: filled
5289    /// polygons via the AA scanline fill, polylines via AA lines, honouring the
5290    /// current blend mode.
5291    #[cfg(not(target_arch = "wasm32"))]
5292    fn draw_ui(&self, d: &ling_ui::widgets::Draw) {
5293        let mut gfx = self.gfx.borrow_mut();
5294        let (w, h, add) = (gfx.width, gfx.height, gfx.blend == 1);
5295        for (c, poly) in &d.fills {
5296            crate::gfx::raster::fill_contours_aa(&mut gfx.buffer, w, h, *c, add, std::slice::from_ref(poly));
5297        }
5298        for (c, pl) in &d.strokes {
5299            for s in pl.windows(2) {
5300                crate::gfx::raster::draw_line_aa(&mut gfx.buffer, w, h, *c, add, s[0][0], s[0][1], s[1][0], s[1][1]);
5301            }
5302        }
5303    }
5304
5305    /// Parse (dst_x, dst_y, width, height) from the first four args of a tex_* builtin.
5306    fn tex_rect(&self, args: &[Value]) -> Result<(usize, usize, usize, usize), EvalErr> {
5307        let tx = self.arg_num(args, 0, 0.0)? as usize;
5308        let ty = self.arg_num(args, 1, 0.0)? as usize;
5309        let tw = self.arg_num(args, 2, 256.0)? as usize;
5310        let th = self.arg_num(args, 3, 256.0)? as usize;
5311        Ok((tx, ty, tw.max(1), th.max(1)))
5312    }
5313
5314    fn apply_binop(&self, op: &BinOp, l: Value, r: Value) -> EvalResult {
5315        match op {
5316            BinOp::Add => match (l, r) {
5317                (Value::Number(a), Value::Number(b)) => Ok(Value::Number(a + b)),
5318                (Value::Str(a), Value::Str(b))       => Ok(Value::Str(a + &b)),
5319                (Value::Str(a), b)                   => Ok(Value::Str(a + &b.to_string())),
5320                (a, Value::Str(b))                   => Ok(Value::Str(a.to_string() + &b)),
5321                (a, b) => Err(EvalErr::from(format!("cannot add {:?} and {:?}", a, b))),
5322            },
5323            BinOp::Sub => Ok(Value::Number(self.to_number(&l)? - self.to_number(&r)?)),
5324            BinOp::Mul => Ok(Value::Number(self.to_number(&l)? * self.to_number(&r)?)),
5325            BinOp::Div => Ok(Value::Number(self.to_number(&l)? / self.to_number(&r)?)),
5326            BinOp::Rem => Ok(Value::Number(self.to_number(&l)? % self.to_number(&r)?)),
5327            BinOp::Eq  => Ok(Value::Bool(values_equal(&l, &r))),
5328            BinOp::Ne  => Ok(Value::Bool(!values_equal(&l, &r))),
5329            BinOp::Lt  => Ok(Value::Bool(self.to_number(&l)? < self.to_number(&r)?)),
5330            BinOp::Gt  => Ok(Value::Bool(self.to_number(&l)? > self.to_number(&r)?)),
5331            BinOp::Le  => Ok(Value::Bool(self.to_number(&l)? <= self.to_number(&r)?)),
5332            BinOp::Ge  => Ok(Value::Bool(self.to_number(&l)? >= self.to_number(&r)?)),
5333            BinOp::And => Ok(Value::Bool(self.is_truthy(&l) && self.is_truthy(&r))),
5334            BinOp::Or  => Ok(Value::Bool(self.is_truthy(&l) || self.is_truthy(&r))),
5335        }
5336    }
5337
5338    fn builtin_format(&self, args: &[Value]) -> Result<String, EvalErr> {
5339        if args.is_empty() { return Ok(String::new()); }
5340        let fmt = match &args[0] {
5341            Value::Str(s) => s.clone(),
5342            other => return Ok(other.to_string()),
5343        };
5344
5345        let mut result = String::new();
5346        let mut arg_idx = 1usize;
5347        let mut chars = fmt.chars().peekable();
5348        while let Some(c) = chars.next() {
5349            if c == '{' {
5350                if chars.peek() == Some(&'}') {
5351                    chars.next();
5352                    if arg_idx < args.len() {
5353                        result.push_str(&args[arg_idx].to_string());
5354                        arg_idx += 1;
5355                    }
5356                } else {
5357                    let mut spec = String::new();
5358                    for ch in chars.by_ref() {
5359                        if ch == '}' { break; }
5360                        spec.push(ch);
5361                    }
5362                    if arg_idx < args.len() {
5363                        if spec.starts_with(":.") {
5364                            if let Value::Number(n) = &args[arg_idx] {
5365                                let prec: usize = spec[2..].trim_end_matches('f')
5366                                    .parse().unwrap_or(2);
5367                                result.push_str(&format!("{:.prec$}", n));
5368                                arg_idx += 1;
5369                                continue;
5370                            }
5371                        }
5372                        result.push_str(&args[arg_idx].to_string());
5373                        arg_idx += 1;
5374                    }
5375                }
5376            } else {
5377                result.push(c);
5378            }
5379        }
5380        Ok(result)
5381    }
5382}
5383
5384#[cfg(not(target_arch = "wasm32"))]
5385fn str_to_minifb_key(name: &str) -> Option<minifb::Key> {
5386    use minifb::Key;
5387    Some(match name {
5388        "numpad0" | "kp0" => Key::NumPad0,
5389        "numpad1" | "kp1" => Key::NumPad1,
5390        "numpad2" | "kp2" => Key::NumPad2,
5391        "numpad3" | "kp3" => Key::NumPad3,
5392        "numpad4" | "kp4" => Key::NumPad4,
5393        "numpad5" | "kp5" => Key::NumPad5,
5394        "numpad6" | "kp6" => Key::NumPad6,
5395        "numpad7" | "kp7" => Key::NumPad7,
5396        "numpad8" | "kp8" => Key::NumPad8,
5397        "numpad9" | "kp9" => Key::NumPad9,
5398        "numpad+" | "kp+" => Key::NumPadPlus,
5399        "numpad-" | "kp-" => Key::NumPadMinus,
5400        "numpad*" | "kp*" => Key::NumPadAsterisk,
5401        "numpad/" | "kp/" => Key::NumPadSlash,
5402        "left"   => Key::Left,
5403        "right"  => Key::Right,
5404        "up"     => Key::Up,
5405        "down"   => Key::Down,
5406        "space"  => Key::Space,
5407        "enter"  => Key::Enter,
5408        "escape" => Key::Escape,
5409        "pageup" => Key::PageUp,
5410        "pagedown" => Key::PageDown,
5411        "lshift" | "leftshift"  => Key::LeftShift,
5412        "rshift" | "rightshift" => Key::RightShift,
5413        "lctrl"  | "leftctrl"   => Key::LeftCtrl,
5414        "rctrl"  | "rightctrl"  => Key::RightCtrl,
5415        "lalt"   | "leftalt"    => Key::LeftAlt,
5416        "ralt"   | "rightalt"   => Key::RightAlt,
5417        "tab"    => Key::Tab,
5418        "backspace" => Key::Backspace,
5419        "delete" => Key::Delete,
5420        "insert" => Key::Insert,
5421        "home"   => Key::Home,
5422        "end"    => Key::End,
5423        "a" => Key::A, "b" => Key::B, "c" => Key::C, "d" => Key::D,
5424        "e" => Key::E, "f" => Key::F, "g" => Key::G, "h" => Key::H,
5425        "i" => Key::I, "j" => Key::J, "k" => Key::K, "l" => Key::L,
5426        "m" => Key::M, "n" => Key::N, "o" => Key::O, "p" => Key::P,
5427        "q" => Key::Q, "r" => Key::R, "s" => Key::S, "t" => Key::T,
5428        "u" => Key::U, "v" => Key::V, "w" => Key::W, "x" => Key::X,
5429        "y" => Key::Y, "z" => Key::Z,
5430        "0" => Key::Key0, "1" => Key::Key1, "2" => Key::Key2,
5431        "3" => Key::Key3, "4" => Key::Key4, "5" => Key::Key5,
5432        "6" => Key::Key6, "7" => Key::Key7, "8" => Key::Key8,
5433        "9" => Key::Key9,
5434        _ => return None,
5435    })
5436}
5437
5438fn values_equal(a: &Value, b: &Value) -> bool {
5439    match (a, b) {
5440        (Value::Number(x), Value::Number(y)) => (x - y).abs() < 1e-12,
5441        (Value::Str(x), Value::Str(y))       => x == y,
5442        (Value::Bool(x), Value::Bool(y))     => x == y,
5443        (Value::Unit, Value::Unit)            => true,
5444        _ => false,
5445    }
5446}
5447
5448// Rasteriser functions live in crate::gfx::raster — imported at top of file.
5449
5450// ── Window platform helpers ────────────────────────────────────────────────────
5451
5452/// Hide the console window that the OS auto-attaches to console-subsystem
5453/// processes. No-op on non-Windows and when no console is present.
5454#[cfg(not(target_arch = "wasm32"))]
5455fn hide_console_window() {
5456    #[cfg(windows)]
5457    unsafe {
5458        extern "system" {
5459            fn GetConsoleWindow() -> isize;
5460            fn ShowWindow(hwnd: isize, nCmdShow: i32) -> i32;
5461        }
5462        let hwnd = GetConsoleWindow();
5463        if hwnd != 0 {
5464            ShowWindow(hwnd, 0); // SW_HIDE = 0
5465        }
5466    }
5467}
5468
5469/// Strip *all* window chrome from `hwnd` and make it cover the whole primary
5470/// monitor (0,0 → screen_w × screen_h), above the taskbar. This turns the
5471/// minifb window into a true borderless-fullscreen surface: no title bar, no
5472/// frame, no resize grips — there is no visible window "handle" left.
5473#[cfg(all(not(target_arch = "wasm32"), windows))]
5474fn make_borderless_fullscreen(hwnd: isize, screen_w: i32, screen_h: i32) {
5475    if hwnd == 0 {
5476        return;
5477    }
5478    unsafe {
5479        extern "system" {
5480            fn SetWindowLongPtrW(hwnd: isize, index: i32, new: isize) -> isize;
5481            fn SetWindowPos(hwnd: isize, insert_after: isize,
5482                            x: i32, y: i32, cx: i32, cy: i32,
5483                            flags: u32) -> i32;
5484            fn ShowWindow(hwnd: isize, cmd: i32) -> i32;
5485        }
5486        const GWL_STYLE:   i32 = -16;
5487        const GWL_EXSTYLE: i32 = -20;
5488        // WS_POPUP (0x80000000) | WS_VISIBLE (0x10000000) — a bare top-level
5489        // window with no caption, border, or system menu.
5490        SetWindowLongPtrW(hwnd, GWL_STYLE, 0x9000_0000isize);
5491        // Clear extended edges (WS_EX_WINDOWEDGE / CLIENTEDGE / DLGMODALFRAME).
5492        SetWindowLongPtrW(hwnd, GWL_EXSTYLE, 0);
5493        // HWND_TOPMOST = -1; SWP_FRAMECHANGED (0x0020) | SWP_SHOWWINDOW (0x0040).
5494        SetWindowPos(hwnd, -1isize, 0, 0, screen_w, screen_h, 0x0020 | 0x0040);
5495        ShowWindow(hwnd, 3); // SW_MAXIMIZE-equivalent paint; 3 = SW_SHOWMAXIMIZED
5496    }
5497}
5498
5499/// Primary-monitor resolution and refresh rate as `(width, height, hz)`.
5500/// `hz` falls back to 60 when the driver reports an unknown/`default` rate.
5501#[cfg(all(not(target_arch = "wasm32"), windows))]
5502fn monitor_info() -> (i32, i32, i32) {
5503    unsafe {
5504        extern "system" {
5505            fn GetSystemMetrics(index: i32) -> i32;
5506            fn GetDC(hwnd: isize) -> isize;
5507            fn ReleaseDC(hwnd: isize, hdc: isize) -> i32;
5508            fn GetDeviceCaps(hdc: isize, index: i32) -> i32;
5509        }
5510        let w = GetSystemMetrics(0).max(1); // SM_CXSCREEN
5511        let h = GetSystemMetrics(1).max(1); // SM_CYSCREEN
5512        let hdc = GetDC(0);
5513        let mut hz = if hdc != 0 { GetDeviceCaps(hdc, 116) } else { 0 }; // VREFRESH
5514        if hdc != 0 {
5515            ReleaseDC(0, hdc);
5516        }
5517        if hz <= 1 {
5518            hz = 60; // 0 or 1 means "device default" → assume 60 Hz
5519        }
5520        (w, h, hz)
5521    }
5522}
5523
5524/// Non-Windows native fallback: resolution from [`native_screen_size`], 60 Hz.
5525#[cfg(all(not(target_arch = "wasm32"), not(windows)))]
5526fn monitor_info() -> (i32, i32, i32) {
5527    let (w, h) = native_screen_size();
5528    (w as i32, h as i32, 60)
5529}
5530
5531/// WASM fallback: the canvas is the display surface; assume 60 Hz.
5532#[cfg(target_arch = "wasm32")]
5533fn monitor_info() -> (i32, i32, i32) {
5534    let (w, h) = crate::gfx::webgl::canvas_size();
5535    (w as i32, h as i32, 60)
5536}
5537
5538/// Query the primary display resolution on non-Windows platforms.
5539/// Falls back to 1920×1080 if the size cannot be determined.
5540#[cfg(all(not(target_arch = "wasm32"), not(windows)))]
5541fn native_screen_size() -> (f64, f64) {
5542    // On Linux/macOS we don't have an easy dependency-free call; return a
5543    // sensible default. Callers can always pass explicit dimensions.
5544    (1920.0, 1080.0)
5545}