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                {
1906                    let mut gfx = self.gfx.borrow_mut();
1907                    gfx.camera.tx = x; gfx.camera.ty = y; gfx.camera.tz = z;
1908                }
1909                if let Some(audio) = &self.audio { audio.set_listener_pos(x, y, z); }
1910                return Ok(Value::Unit);
1911            }
1912
1913            // ── move_camera(dx, dy, dz) — translate camera by delta ──
1914            "move_camera" => {
1915                let dx = self.arg_num(&args, 0, 0.0)? as f32;
1916                let dy = self.arg_num(&args, 1, 0.0)? as f32;
1917                let dz = self.arg_num(&args, 2, 0.0)? as f32;
1918                let mut gfx = self.gfx.borrow_mut();
1919                gfx.camera.tx += dx; gfx.camera.ty += dy; gfx.camera.tz += dz;
1920                return Ok(Value::Unit);
1921            }
1922
1923            // ── set_zdist(d) — set perspective z-offset (field-of-view taper) ──
1924            "set_zdist" | "ตั้งระยะห่าง" | "镜距" | "Z距離設定" | "Z거리설정" => {
1925                let d = self.arg_num(&args, 0, 5.0)? as f32;
1926                self.gfx.borrow_mut().camera.zdist = d;
1927                return Ok(Value::Unit);
1928            }
1929
1930            // ── capture_mouse() — hide cursor and warp to centre each frame ──
1931            "capture_mouse" | "จับเมาส์" | "捕鼠" | "マウス捕捉" | "마우스잡기" => {
1932                #[cfg(not(target_arch = "wasm32"))]
1933                {
1934                    let mut gfx = self.gfx.borrow_mut();
1935                    gfx.mouse_captured = true;
1936                    gfx.last_mx = f32::NAN;
1937                    if let Some(win) = gfx.window.as_mut() {
1938                        win.set_cursor_visibility(false);
1939                    }
1940                }
1941                return Ok(Value::Unit);
1942            }
1943
1944            // ── release_mouse() — restore cursor and remove clip region ──
1945            "release_mouse" => {
1946                #[cfg(not(target_arch = "wasm32"))]
1947                {
1948                    let mut gfx = self.gfx.borrow_mut();
1949                    gfx.mouse_captured = false;
1950                    gfx.last_mx = f32::NAN;
1951                    if let Some(win) = gfx.window.as_mut() {
1952                        win.set_cursor_visibility(true);
1953                    }
1954                    #[cfg(windows)]
1955                    unsafe {
1956                        // Null releases the clip; reuse the RECT-typed declaration above.
1957                        extern "system" { fn ClipCursor(lpRect: *const std::ffi::c_void) -> i32; }
1958                        ClipCursor(std::ptr::null());
1959                    }
1960                }
1961                return Ok(Value::Unit);
1962            }
1963
1964            // ══════════════════════════════════════════════════════════════════
1965            // 3-D / 4-D DRAWING — camera, lights, depth-sorted geometry
1966            // ══════════════════════════════════════════════════════════════════
1967
1968            // ── set_camera(cry, sry, crx, srx) — store precomputed camera trig ──
1969            // Call once per frame after computing cos/sin of your rotation angles.
1970            "set_camera" | "ตั้งกล้อง" | "设镜" | "设置摄像机" | "カメラ設定" | "카메라설정" => {
1971                let cry = self.arg_num(&args, 0, 1.0)? as f32;
1972                let sry = self.arg_num(&args, 1, 0.0)? as f32;
1973                let crx = self.arg_num(&args, 2, 1.0)? as f32;
1974                let srx = self.arg_num(&args, 3, 0.0)? as f32;
1975                let mut gfx = self.gfx.borrow_mut();
1976                gfx.camera.cry = cry; gfx.camera.sry = sry;
1977                gfx.camera.crx = crx; gfx.camera.srx = srx;
1978                return Ok(Value::Unit);
1979            }
1980
1981            // ── set_projection(cx, cy, focal, zdist) — override projection params ──
1982            // Automatically set when the window opens; override only if needed.
1983            "set_projection" | "ตั้งโปรเจกชัน" | "投影" | "投影設定" | "투영설정" => {
1984                let cx    = self.arg_num(&args, 0, 960.0)? as f32;
1985                let cy    = self.arg_num(&args, 1, 540.0)? as f32;
1986                let focal = self.arg_num(&args, 2, 1080.0)? as f32;
1987                let zdist = self.arg_num(&args, 3, 5.0)? as f32;
1988                let mut gfx = self.gfx.borrow_mut();
1989                gfx.camera.cx    = cx;
1990                gfx.camera.cy    = cy;
1991                gfx.camera.focal = focal;
1992                gfx.camera.zdist = zdist;
1993                return Ok(Value::Unit);
1994            }
1995
1996            // ── draw_mesh(pos, idx, ox, oy, oz, scale, mode) ──
1997            //   Native batched triangle mesh. pos = flat [x,y,z,…], idx = flat tri indices.
1998            //   mode 0 = lit with current pen colour; 1 = per-face hue cycle.
1999            //   Vertices are batch-projected via ling-gpu (CPU fallback, or CUDA when the
2000            //   `cuda` feature is on); the per-triangle loop runs natively (not in the
2001            //   interpreter) so dense meshes (imported glTF, grids) stay fast.
2002            "draw_mesh" | "วาดเมช" => {
2003                let pos = match args.first() { Some(Value::List(v)) => v, _ => return Ok(Value::Unit) };
2004                let idx = match args.get(1)   { Some(Value::List(v)) => v, _ => return Ok(Value::Unit) };
2005                let ox = self.arg_num(&args,2,0.0)? as f32;
2006                let oy = self.arg_num(&args,3,0.0)? as f32;
2007                let oz = self.arg_num(&args,4,0.0)? as f32;
2008                let scale = self.arg_num(&args,5,1.0)? as f32;
2009                let mode = self.arg_num(&args,6,0.0)? as i64;
2010                let nv = pos.len() / 3;
2011                if nv == 0 { return Ok(Value::Unit); }
2012                let mut world = vec![0.0f32; nv*3];
2013                for i in 0..nv {
2014                    world[i*3]   = ox + self.to_number(&pos[i*3]).unwrap_or(0.0)   as f32 * scale;
2015                    world[i*3+1] = oy + self.to_number(&pos[i*3+1]).unwrap_or(0.0) as f32 * scale;
2016                    world[i*3+2] = oz + self.to_number(&pos[i*3+2]).unwrap_or(0.0) as f32 * scale;
2017                }
2018                let mut gfx = self.gfx.borrow_mut();
2019                let cp = {
2020                    let c = &gfx.camera;
2021                    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 }
2022                };
2023                let near = -gfx.camera.zdist + 0.02;
2024                let base = gfx.color;
2025                let ambient = gfx.ambient;
2026                let mut proj = vec![0.0f32; nv*3];   // (sx, sy, depth) per vertex
2027                ling_gpu::backend().project_points(&world, &cp, &mut proj);
2028                let nt = idx.len() / 3;
2029                for t in 0..nt {
2030                    let ia = self.to_number(&idx[t*3]).unwrap_or(0.0)   as usize;
2031                    let ib = self.to_number(&idx[t*3+1]).unwrap_or(0.0) as usize;
2032                    let ic = self.to_number(&idx[t*3+2]).unwrap_or(0.0) as usize;
2033                    if ia>=nv || ib>=nv || ic>=nv { continue; }
2034                    let (da, db, dc) = (proj[ia*3+2], proj[ib*3+2], proj[ic*3+2]);
2035                    if (da+db+dc)/3.0 <= near { continue; }   // near-plane cull (centroid)
2036                    let col = if mode == 1 {
2037                        let h = t as f32 * 0.6;
2038                        let r = ((h.sin()*0.5+0.5)*150.0+55.0) as u32;
2039                        let g = (((h+2.094).sin()*0.5+0.5)*150.0+55.0) as u32;
2040                        let b = (((h+4.189).sin()*0.5+0.5)*150.0+55.0) as u32;
2041                        (r<<16)|(g<<8)|b
2042                    } else {
2043                        let (ax,ay,az)=(world[ia*3],world[ia*3+1],world[ia*3+2]);
2044                        let (bx,by,bz)=(world[ib*3],world[ib*3+1],world[ib*3+2]);
2045                        let (px,py,pz)=(world[ic*3],world[ic*3+1],world[ic*3+2]);
2046                        let (ux,uy,uz)=(bx-ax,by-ay,bz-az);
2047                        let (vx,vy,vz)=(px-ax,py-ay,pz-az);
2048                        let normal=[uy*vz-uz*vy, uz*vx-ux*vz, ux*vy-uy*vx];
2049                        let centroid=[(ax+bx+px)/3.0,(ay+by+py)/3.0,(az+bz+pz)/3.0];
2050                        crate::gfx::light::compute_lit_color(base, normal, centroid, &gfx.lights, ambient)
2051                    };
2052                    let depth = (da+db+dc)/3.0;
2053                    let col = gfx.fog_apply(col, depth);
2054                    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]);
2055                }
2056                return Ok(Value::Unit);
2057            }
2058
2059            // ── add_light(x, y, z, r, g, b, intensity, radius) ──
2060            // Adds a point light in world space.  r/g/b in [0..1].
2061            // radius == 0 → no distance falloff.
2062            "add_light" | "เพิ่มแสง" | "加灯" | "ライト追加" | "조명추가" => {
2063                let x   = self.arg_num(&args, 0, 0.0)? as f32;
2064                let y   = self.arg_num(&args, 1, -3.0)? as f32;
2065                let z   = self.arg_num(&args, 2, 3.0)? as f32;
2066                let mut r   = self.arg_num(&args, 3, 1.0)? as f32;
2067                let mut g   = self.arg_num(&args, 4, 1.0)? as f32;
2068                let mut b   = self.arg_num(&args, 5, 1.0)? as f32;
2069                // Forgive 0-255 colour values: if any channel is clearly > 1,
2070                // treat the triple as 0-255 and normalise. Keeps 0-1 callers exact.
2071                if r > 1.5 || g > 1.5 || b > 1.5 { r/=255.0; g/=255.0; b/=255.0; }
2072                let intensity = self.arg_num(&args, 6, 1.0)? as f32;
2073                let radius    = self.arg_num(&args, 7, 0.0)? as f32;
2074                self.gfx.borrow_mut().lights.push(Light { x, y, z, r, g, b, intensity, radius });
2075                return Ok(Value::Unit);
2076            }
2077
2078            // ── clear_lights() — remove all lights ──
2079            "clear_lights" | "ล้างแสง" | "清灯" | "ライト消去" | "조명초기화" => {
2080                self.gfx.borrow_mut().lights.clear();
2081                return Ok(Value::Unit);
2082            }
2083
2084            // ── set_ambient(v) — ambient light level [0..1] ──
2085            "set_ambient" | "ตั้งแสงรอบข้าง" | "环境光" | "環境光設定" | "환경광설정" => {
2086                let v = self.arg_num(&args, 0, 0.15)? as f32;
2087                self.gfx.borrow_mut().ambient = v;
2088                return Ok(Value::Unit);
2089            }
2090
2091            // ── set_fog(r,g,b, start, end) — distance fog toward (r,g,b).
2092            //    triangles/lines fade from `start`..`end` camera depth. end<=0 = off.
2093            "set_fog" | "ตั้งหมอก" | "雾" | "霧設定" | "안개설정" => {
2094                let r = self.arg_num(&args, 0, 0.0)?.clamp(0.0, 255.0) as u32;
2095                let g = self.arg_num(&args, 1, 0.0)?.clamp(0.0, 255.0) as u32;
2096                let b = self.arg_num(&args, 2, 0.0)?.clamp(0.0, 255.0) as u32;
2097                let start = self.arg_num(&args, 3, 0.0)? as f32;
2098                let end   = self.arg_num(&args, 4, 0.0)? as f32;
2099                let mut gfx = self.gfx.borrow_mut();
2100                gfx.fog_color = (r << 16) | (g << 8) | b;
2101                gfx.fog_start = start;
2102                gfx.fog_end   = end;
2103                return Ok(Value::Unit);
2104            }
2105
2106            // ── วาดสามเหลี่ยม3มิติ(ax,ay,az, bx,by,bz, cx,cy,cz) ──
2107            // Computes lighting from world-space normal + active lights (cel shading),
2108            // projects via the stored camera, and pushes to the depth queue.
2109            "วาดสามเหลี่ยม3มิติ" | "draw_triangle_3d" | "triangle3d" => {
2110                let ax = self.arg_num(&args, 0, 0.0)? as f32;
2111                let ay = self.arg_num(&args, 1, 0.0)? as f32;
2112                let az = self.arg_num(&args, 2, 0.0)? as f32;
2113                let bx = self.arg_num(&args, 3, 0.0)? as f32;
2114                let by = self.arg_num(&args, 4, 0.0)? as f32;
2115                let bz = self.arg_num(&args, 5, 0.0)? as f32;
2116                let cx = self.arg_num(&args, 6, 0.0)? as f32;
2117                let cy = self.arg_num(&args, 7, 0.0)? as f32;
2118                let cz = self.arg_num(&args, 8, 0.0)? as f32;
2119
2120                let mut gfx = self.gfx.borrow_mut();
2121
2122                // World-space face normal  N = (B−A) × (C−A)
2123                let ux = bx-ax; let uy = by-ay; let uz = bz-az;
2124                let vx = cx-ax; let vy = cy-ay; let vz = cz-az;
2125                let normal = [
2126                    uy*vz - uz*vy,
2127                    uz*vx - ux*vz,
2128                    ux*vy - uy*vx,
2129                ];
2130                // World-space centroid
2131                let centroid = [
2132                    (ax+bx+cx)/3.0,
2133                    (ay+by+cy)/3.0,
2134                    (az+bz+cz)/3.0,
2135                ];
2136
2137                // Cel-shaded colour
2138                let lit_color = crate::gfx::light::compute_lit_color(
2139                    gfx.color, normal, centroid, &gfx.lights, gfx.ambient,
2140                );
2141
2142                // ── Near-plane CLIP (Sutherland–Hodgman) ──
2143                // A vertex just in front of the eye divides by ~0 in the perspective
2144                // projection and smears the triangle into a screen-filling fan. The old
2145                // "cull if any vertex past near" still let a vertex sitting just inside
2146                // near blow up. Clipping the triangle to the near plane keeps only the
2147                // in-front portion (finite projection — no fan, no over-cull).
2148                let near = -gfx.camera.zdist + 0.05;
2149                let vw = [
2150                    (ax, ay, az, gfx.camera.depth(ax, ay, az)),
2151                    (bx, by, bz, gfx.camera.depth(bx, by, bz)),
2152                    (cx, cy, cz, gfx.camera.depth(cx, cy, cz)),
2153                ];
2154                let mut poly: Vec<(f32, f32, f32)> = Vec::with_capacity(4);
2155                let mut ei = 0;
2156                while ei < 3 {
2157                    let a = vw[ei];
2158                    let b = vw[(ei + 1) % 3];
2159                    let ain = a.3 > near;
2160                    let bin = b.3 > near;
2161                    if ain { poly.push((a.0, a.1, a.2)); }
2162                    if ain != bin {
2163                        let tt = (near - a.3) / (b.3 - a.3);
2164                        poly.push((a.0 + (b.0 - a.0) * tt, a.1 + (b.1 - a.1) * tt, a.2 + (b.2 - a.2) * tt));
2165                    }
2166                    ei += 1;
2167                }
2168                if poly.len() < 3 { return Ok(Value::Unit); }
2169                // Project the clipped polygon, painter-depth = mean, fan-triangulate.
2170                let proj: Vec<(f32, f32, f32)> =
2171                    poly.iter().map(|p| gfx.camera.project(p.0, p.1, p.2)).collect();
2172                let mut dsum = 0.0f32;
2173                for p in &proj { dsum += p.2; }
2174                let depth = dsum / proj.len() as f32;
2175                let lit_color = gfx.fog_apply(lit_color, depth);
2176                let mut fk = 1;
2177                while fk + 1 < proj.len() {
2178                    gfx.depth_queue.push_triangle(
2179                        depth, lit_color,
2180                        proj[0].0, proj[0].1, proj[fk].0, proj[fk].1, proj[fk + 1].0, proj[fk + 1].1,
2181                    );
2182                    fk += 1;
2183                }
2184                return Ok(Value::Unit);
2185            }
2186
2187            // ── วาดเส้น3มิติ(ax,ay,az, bx,by,bz) ──
2188            // Projects two world-space points via the stored camera and pushes
2189            // a line to the depth queue.
2190            "วาดเส้น3มิติ" | "draw_line_3d" | "line3d" | "画3D线" | "3D線描く" | "3D선그리기" => {
2191                let ax = self.arg_num(&args, 0, 0.0)? as f32;
2192                let ay = self.arg_num(&args, 1, 0.0)? as f32;
2193                let az = self.arg_num(&args, 2, 0.0)? as f32;
2194                let bx = self.arg_num(&args, 3, 0.0)? as f32;
2195                let by = self.arg_num(&args, 4, 0.0)? as f32;
2196                let bz = self.arg_num(&args, 5, 0.0)? as f32;
2197
2198                let mut gfx = self.gfx.borrow_mut();
2199                let color = gfx.color;
2200                // Near-plane clip in 3-D before perspective divide
2201                let near = -gfx.camera.zdist + 0.05;
2202                let mut lax = ax; let mut lay = ay; let mut laz = az;
2203                let mut lbx = bx; let mut lby = by; let mut lbz = bz;
2204                let da_raw = gfx.camera.depth(lax, lay, laz);
2205                let db_raw = gfx.camera.depth(lbx, lby, lbz);
2206                if da_raw <= near && db_raw <= near {
2207                    return Ok(Value::Unit);
2208                }
2209                if da_raw <= near {
2210                    let t = (near - da_raw) / (db_raw - da_raw);
2211                    lax += t * (lbx - lax);
2212                    lay += t * (lby - lay);
2213                    laz += t * (lbz - laz);
2214                } else if db_raw <= near {
2215                    let t = (near - da_raw) / (db_raw - da_raw);
2216                    lbx = lax + t * (lbx - lax);
2217                    lby = lay + t * (lby - lay);
2218                    lbz = laz + t * (lbz - laz);
2219                }
2220                let (sax, say, da) = gfx.camera.project(lax, lay, laz);
2221                let (sbx, sby, db) = gfx.camera.project(lbx, lby, lbz);
2222                let depth = (da + db) / 2.0;
2223                let color = gfx.fog_apply(color, depth);
2224                gfx.depth_queue.push_line(depth, color, sax, say, sbx, sby);
2225                return Ok(Value::Unit);
2226            }
2227
2228            // orb_shell(cx,cy,cz, radius, rot_y, rot_x, density, r,g,b)
2229            //   A single trippy, grayscale, depth-faded vector pattern wound around
2230            //   a sphere — two families of interleaved spherical spirals (a guilloché
2231            //   weave), NOT a lat/long cage. Each segment's brightness follows its
2232            //   facing (front bright, back dim), so it reads as a translucent
2233            //   grayscale "texture" with alpha rather than a hard wireframe; the
2234            //   inner marble shows through. `rot_y`/`rot_x` roll the texture around
2235            //   the orb; `density` = spirals per winding direction. r,g,b tint it
2236            //   (pass a gray like 230,230,230 for pure grayscale).
2237            #[cfg(not(target_arch = "wasm32"))]
2238            "orb_shell" | "球壳" | "オーブ殻" | "오브껍질" | "เปลือกทรงกลม" => {
2239                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;
2240                let radius=self.arg_num(&args,3,1.0)? as f32;
2241                let ry=self.arg_num(&args,4,0.)? as f32; let rx=self.arg_num(&args,5,0.)? as f32;
2242                let density=(self.arg_num(&args,6,10.)? as i32).clamp(1, 48);
2243                let tr=(self.arg_num(&args,7,230.)? as f32).clamp(0.,255.);
2244                let tg=(self.arg_num(&args,8,230.)? as f32).clamp(0.,255.);
2245                let tb=(self.arg_num(&args,9,235.)? as f32).clamp(0.,255.);
2246                let (cyr, syr) = (ry.cos(), ry.sin());
2247                let (cxr, sxr) = (rx.cos(), rx.sin());
2248                let tau = std::f32::consts::TAU;
2249                let pi = std::f32::consts::PI;
2250                let turns = 6.0_f32;            // how many times each spiral wraps pole→pole
2251                let nseg  = 96;                 // segments per spiral (smoothness)
2252                let inv_r = if radius.abs() > 1e-5 { 1.0 / radius } else { 0.0 };
2253                // a point along a spiral (param u 0..1, start angle theta0, winding dir),
2254                // spun by ry/rx — returns (world point, facing 0..1 where 1 = toward camera)
2255                let pt = |u: f32, theta0: f32, dir: f32| -> ([f32;3], f32) {
2256                    let phi = pi * u;                       // 0..pi  (north → south)
2257                    let th  = dir * turns * tau * u + theta0;
2258                    let (mut x, y, mut z) = (phi.sin()*th.cos()*radius, phi.cos()*radius, phi.sin()*th.sin()*radius);
2259                    let x1 =  x*cyr + z*syr;                // yaw about Y
2260                    let z1 = -x*syr + z*cyr;
2261                    x = x1; z = z1;
2262                    let y2 = y*cxr - z*sxr;                 // pitch about X
2263                    let z2 = y*sxr + z*cxr;
2264                    // facing: camera sits at -zdist looking +z, so smaller z2 = nearer = brighter
2265                    let facing = (0.5 - 0.5 * z2 * inv_r).clamp(0.0, 1.0);
2266                    ([cx + x, cy + y2, cz + z2], facing)
2267                };
2268                let mut gfx = self.gfx.borrow_mut();
2269                let near = -gfx.camera.zdist + 0.05;
2270                // draw one segment (near-clipped) in a grayscale tint scaled by `lum`
2271                let seg = |gfx: &mut crate::gfx::GfxState, a: [f32;3], b: [f32;3], lum: f32| {
2272                    let (mut lax,mut lay,mut laz)=(a[0],a[1],a[2]);
2273                    let (mut lbx,mut lby,mut lbz)=(b[0],b[1],b[2]);
2274                    let da=gfx.camera.depth(lax,lay,laz); let db=gfx.camera.depth(lbx,lby,lbz);
2275                    if da<=near && db<=near { return; }
2276                    if da<=near { let t=(near-da)/(db-da); lax+=t*(lbx-lax); lay+=t*(lby-lay); laz+=t*(lbz-laz); }
2277                    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); }
2278                    let (sax,say,da2)=gfx.camera.project(lax,lay,laz);
2279                    let (sbx,sby,db2)=gfx.camera.project(lbx,lby,lbz);
2280                    // grayscale-alpha: front-facing bright, back faded toward black
2281                    let l = (0.12 + 0.88 * lum).clamp(0.0, 1.0);
2282                    let cr=(tr*l) as u32; let cg=(tg*l) as u32; let cb=(tb*l) as u32;
2283                    let color=(cr<<16)|(cg<<8)|cb;
2284                    gfx.depth_queue.push_line((da2+db2)*0.5, color, sax,say, sbx,sby);
2285                };
2286                // two opposite winding directions → a soft guilloché weave (not a cage)
2287                for &dir in &[1.0_f32, -1.0_f32] {
2288                    for s in 0..density {
2289                        let theta0 = s as f32 * tau / density as f32;
2290                        let mut prev = pt(0.0, theta0, dir);
2291                        for k in 1..=nseg {
2292                            let cur = pt(k as f32 / nseg as f32, theta0, dir);
2293                            seg(&mut gfx, prev.0, cur.0, (prev.1 + cur.1) * 0.5);
2294                            prev = cur;
2295                        }
2296                    }
2297                }
2298                return Ok(Value::Unit);
2299            }
2300
2301            // orb_particles(cx,cy,cz, radius, count, t, r,g,b)
2302            //   Fills the VOLUME of a sphere with `count` swirling vector points —
2303            //   like motes suspended inside a snow-globe orb. Points are distributed
2304            //   uniformly through the ball, slowly tumble as a cloud + wobble
2305            //   individually over time `t`, and are depth-shaded (near = bright,
2306            //   far = dim) so the cloud has real volume. Additive, so it layers under
2307            //   a shell / over a liquid marble.
2308            #[cfg(not(target_arch = "wasm32"))]
2309            "orb_particles" | "球内粒子" | "オーブ粒子" | "오브입자" | "อนุภาคทรงกลม" => {
2310                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;
2311                let radius=self.arg_num(&args,3,1.0)? as f32;
2312                let count=(self.arg_num(&args,4,160.)? as i32).clamp(1, 4000);
2313                let t=self.arg_num(&args,5,0.)? as f32;
2314                let tr=(self.arg_num(&args,6,255.)? as f32).clamp(0.,255.);
2315                let tg=(self.arg_num(&args,7,255.)? as f32).clamp(0.,255.);
2316                let tb=(self.arg_num(&args,8,255.)? as f32).clamp(0.,255.);
2317                let inv_r = if radius.abs() > 1e-5 { 1.0/radius } else { 0.0 };
2318                // cheap deterministic hash → [0,1)
2319                let h = |mut x: u32| -> f32 {
2320                    x = x.wrapping_mul(747796405).wrapping_add(2891336453);
2321                    x = ((x >> ((x >> 28).wrapping_add(4))) ^ x).wrapping_mul(277803737);
2322                    (((x >> 22) ^ x) & 0xFFFFFF) as f32 / 16_777_216.0
2323                };
2324                let tau = std::f32::consts::TAU;
2325                // slow tumble of the whole cloud
2326                let (cyr, syr) = ((t*0.5).cos(), (t*0.5).sin());
2327                let (cxr, sxr) = ((t*0.23).cos(), (t*0.23).sin());
2328                let mut gfx = self.gfx.borrow_mut();
2329                let near = -gfx.camera.zdist + 0.05;
2330                let (sw, sh) = (gfx.width as i32, gfx.height as i32);
2331                for i in 0..count {
2332                    let i = i as u32;
2333                    // uniform-in-volume: r = cbrt(u) * radius; direction from two hashes
2334                    let u  = h(i.wrapping_mul(3) + 1);
2335                    let rr = u.cbrt() * radius * (0.85 + 0.15 * (t*1.3 + i as f32).sin()); // gentle pulse
2336                    let th = h(i.wrapping_mul(3) + 2) * tau + t * (0.3 + 0.5 * h(i*7+5)); // per-mote orbit
2337                    let ph = (h(i.wrapping_mul(3) + 3) * 2.0 - 1.0).acos();               // uniform cos(phi)
2338                    let (mut x, y, mut z) = (rr*ph.sin()*th.cos(), rr*ph.cos(), rr*ph.sin()*th.sin());
2339                    // tumble the cloud (yaw then pitch)
2340                    let x1 = x*cyr + z*syr; let z1 = -x*syr + z*cyr; x = x1; z = z1;
2341                    let y2 = y*cxr - z*sxr; let z2 = y*sxr + z*cxr;
2342                    let (wx, wy, wz) = (cx + x, cy + y2, cz + z2);
2343                    if gfx.camera.depth(wx, wy, wz) <= near { continue; }
2344                    let (sx, sy, dep) = gfx.camera.project(wx, wy, wz);
2345                    let sxi = sx as i32; let syi = sy as i32;
2346                    if sxi < 0 || syi < 0 || sxi >= sw || syi >= sh { continue; }
2347                    // depth-shade: nearer (smaller z2) = brighter
2348                    let facing = (0.5 - 0.5 * z2 * inv_r).clamp(0.15, 1.0);
2349                    let l = facing;
2350                    let cr=(tr*l) as u32; let cg=(tg*l) as u32; let cb=(tb*l) as u32;
2351                    let color=(cr<<16)|(cg<<8)|cb;
2352                    // a 1–2px dot (bigger when near) as a short segment in the depth queue
2353                    let len = if facing > 0.7 { 1.0 } else { 0.0 };
2354                    gfx.depth_queue.push_line(dep, color, sx, sy, sx + len, sy);
2355                }
2356                return Ok(Value::Unit);
2357            }
2358
2359            // project_3d(x,y,z) -> [screen_x, screen_y, depth]; behind the camera
2360            // returns a sentinel ([-99999,-99999, depth]) so scripts can skip it.
2361            // Lets scripts place 2-D overlays (e.g. filled teardrop flames) onto 3-D points.
2362            "project_3d" | "投影3D" | "3D投影" | "3D투영" | "ฉาย3มิติ" => {
2363                let x = self.arg_num(&args,0,0.0)? as f32;
2364                let y = self.arg_num(&args,1,0.0)? as f32;
2365                let z = self.arg_num(&args,2,0.0)? as f32;
2366                let gfx = self.gfx.borrow();
2367                let near = -gfx.camera.zdist + 0.05;
2368                let d = gfx.camera.depth(x, y, z);
2369                if d <= near {
2370                    return Ok(Value::List(vec![Value::Number(-99999.0), Value::Number(-99999.0), Value::Number(d as f64)]));
2371                }
2372                let (sx, sy, depth) = gfx.camera.project(x, y, z);
2373                return Ok(Value::List(vec![Value::Number(sx as f64), Value::Number(sy as f64), Value::Number(depth as f64)]));
2374            }
2375            // draw_poly([x0,y0,x1,y1,…]) — filled 2-D polygon in the current colour,
2376            // honouring the blend mode (additive → translucent glow). Auto-closes.
2377            #[cfg(not(target_arch = "wasm32"))]
2378            "draw_poly" | "填充多边形" | "ポリゴン塗り" | "다각형채우기" | "เติมรูปหลายเหลี่ยม" => {
2379                let mut pts: Vec<[f32; 2]> = Vec::new();
2380                if let Some(Value::List(v)) = args.first() {
2381                    let mut i = 0;
2382                    while i + 1 < v.len() {
2383                        let x = self.to_number(&v[i]).unwrap_or(0.0) as f32;
2384                        let y = self.to_number(&v[i + 1]).unwrap_or(0.0) as f32;
2385                        pts.push([x, y]);
2386                        i += 2;
2387                    }
2388                }
2389                if pts.len() >= 3 {
2390                    if pts[0] != pts[pts.len() - 1] { let p0 = pts[0]; pts.push(p0); } // close
2391                    let mut gfx = self.gfx.borrow_mut();
2392                    let (w, h, color, add) = (gfx.width, gfx.height, gfx.color, gfx.blend == 1);
2393                    crate::gfx::raster::fill_contours_aa(&mut gfx.buffer, w, h, color, add, std::slice::from_ref(&pts));
2394                }
2395                return Ok(Value::Unit);
2396            }
2397
2398            // ══════════════════════════════════════════════════════════════════
2399            // VECTOR TEXTURE BUILTINS  (src/gfx/vtex.rs)
2400            // All patterns are depth-biased so they appear on top of surfaces.
2401            // Plane defined by: centre (cx,cy,cz) + U tangent + V tangent.
2402            // Last two args always: fr (frame f32), hue (phase offset f32).
2403            // ══════════════════════════════════════════════════════════════════
2404
2405            // vtex_grid(cx,cy,cz, ux,uy,uz, vx,vy,vz, cols,rows, cw,ch, fr,hue)
2406            "vtex_grid" | "ลายตาราง" | "纹格" | "格子模様" | "격자무늬" => {
2407                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;
2408                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;
2409                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;
2410                let cols=self.arg_num(&args,9,10.)?as usize; let rows=self.arg_num(&args,10,10.)?as usize;
2411                let cw=self.arg_num(&args,11,1.)?as f32;  let ch=self.arg_num(&args,12,1.)?as f32;
2412                let fr=self.arg_num(&args,13,0.)?as f32;  let hue=self.arg_num(&args,14,0.)?as f32;
2413                let mut gfx = self.gfx.borrow_mut();
2414                let cam = gfx.camera.clone();
2415                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);
2416                return Ok(Value::Unit);
2417            }
2418
2419            // vtex_rings(cx,cy,cz, ux,uy,uz, vx,vy,vz, n_rings,n_sides, max_r,twist, fr,hue)
2420            "vtex_rings" | "ลายวงซ้อน" | "纹环" | "同心円" | "동심원" => {
2421                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;
2422                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;
2423                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;
2424                let nr=self.arg_num(&args,9,6.)?as usize; let ns=self.arg_num(&args,10,6.)?as usize;
2425                let mr=self.arg_num(&args,11,3.)?as f32;  let tw=self.arg_num(&args,12,0.)?as f32;
2426                let fr=self.arg_num(&args,13,0.)?as f32;  let hue=self.arg_num(&args,14,0.)?as f32;
2427                let mut gfx = self.gfx.borrow_mut();
2428                let cam = gfx.camera.clone();
2429                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);
2430                return Ok(Value::Unit);
2431            }
2432
2433            // vtex_star(cx,cy,cz, ux,uy,uz, vx,vy,vz, n_pts,r_out,r_in, rot_speed, fr,hue)
2434            "vtex_star" | "ลายดาว" | "纹星" | "星模様" | "별무늬" => {
2435                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;
2436                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;
2437                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;
2438                let np=self.arg_num(&args,9,6.)?as usize;
2439                let ro=self.arg_num(&args,10,2.)?as f32; let ri=self.arg_num(&args,11,1.)?as f32;
2440                let rs=self.arg_num(&args,12,0.01)?as f32;
2441                let fr=self.arg_num(&args,13,0.)?as f32; let hue=self.arg_num(&args,14,0.)?as f32;
2442                let mut gfx = self.gfx.borrow_mut();
2443                let cam = gfx.camera.clone();
2444                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);
2445                return Ok(Value::Unit);
2446            }
2447
2448            // vtex_spiral(cx,cy,cz, ux,uy,uz, vx,vy,vz, n_turns,max_r,steps, fr,hue)
2449            "vtex_spiral" | "ลายเกลียว" | "纹螺" | "螺旋" | "나선" => {
2450                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;
2451                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;
2452                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;
2453                let nt=self.arg_num(&args,9,3.)?as f32; let mr=self.arg_num(&args,10,3.)?as f32;
2454                let st=self.arg_num(&args,11,120.)?as usize;
2455                let fr=self.arg_num(&args,12,0.)?as f32; let hue=self.arg_num(&args,13,0.)?as f32;
2456                let mut gfx = self.gfx.borrow_mut();
2457                let cam = gfx.camera.clone();
2458                crate::gfx::vtex::draw_spiral(&mut gfx.depth_queue,&cam, cx,cy,cz, ux,uy,uz, vx,vy,vz, nt,mr,st, fr,hue);
2459                return Ok(Value::Unit);
2460            }
2461
2462            // vtex_flower(cx,cy,cz, ux,uy,uz, vx,vy,vz, radius,n_sides, fr,hue)
2463            "vtex_flower" | "ลายดอก" | "纹花" | "花模様" | "꽃무늬" => {
2464                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;
2465                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;
2466                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;
2467                let r=self.arg_num(&args,9,1.)?as f32; let ns=self.arg_num(&args,10,24.)?as usize;
2468                let fr=self.arg_num(&args,11,0.)?as f32; let hue=self.arg_num(&args,12,0.)?as f32;
2469                let mut gfx = self.gfx.borrow_mut();
2470                let cam = gfx.camera.clone();
2471                crate::gfx::vtex::draw_flower(&mut gfx.depth_queue,&cam, cx,cy,cz, ux,uy,uz, vx,vy,vz, r,ns, fr,hue);
2472                return Ok(Value::Unit);
2473            }
2474
2475            // vtex_letter_rain(cx,cy,cz, ux,uy,uz, vx,vy,vz, n_cols,n_vis, col_w,row_h, speed, fr,hue)
2476            "vtex_letter_rain" | "ลายอักษรไหล" | "纹字雨" | "文字雨" | "글자비" => {
2477                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;
2478                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;
2479                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;
2480                let nc=self.arg_num(&args,9,16.)?as usize; let nv=self.arg_num(&args,10,14.)?as usize;
2481                let cw=self.arg_num(&args,11,0.65)?as f32; let rh=self.arg_num(&args,12,0.60)?as f32;
2482                let sp=self.arg_num(&args,13,0.025)?as f32;
2483                let fr=self.arg_num(&args,14,0.)?as f32; let hue=self.arg_num(&args,15,0.)?as f32;
2484                let mut gfx = self.gfx.borrow_mut();
2485                let cam = gfx.camera.clone();
2486                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);
2487                return Ok(Value::Unit);
2488            }
2489
2490            // vtex_hyperbolic_uv(cx,cy,cz, ux,uy,uz, vx,vy,vz, max_r,n_circles,n_rays, fr,hue)
2491            "vtex_hyperbolic_uv" | "ลายไฮเพอร์โบลิก" | "纹曲面" | "双曲線" | "쌍곡선" => {
2492                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;
2493                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;
2494                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;
2495                let mr=self.arg_num(&args,9,5.)?as f32;
2496                let nc=self.arg_num(&args,10,12.)?as usize; let nr=self.arg_num(&args,11,18.)?as usize;
2497                let fr=self.arg_num(&args,12,0.)?as f32; let hue=self.arg_num(&args,13,0.)?as f32;
2498                let mut gfx = self.gfx.borrow_mut();
2499                let cam = gfx.camera.clone();
2500                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);
2501                return Ok(Value::Unit);
2502            }
2503
2504            // vtex_halftone(cx,cy,cz, ux,uy,uz, vx,vy,vz, cols,rows, cell_w,cell_h, density, fr,hue)
2505            "vtex_halftone" | "ลายจุด" | "纹半调" | "網点模様" | "망점" => {
2506                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;
2507                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;
2508                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;
2509                let cols=self.arg_num(&args,9,16.)?as usize; let rows=self.arg_num(&args,10,12.)?as usize;
2510                let cw=self.arg_num(&args,11,0.5)?as f32; let ch=self.arg_num(&args,12,0.5)?as f32;
2511                let dens=self.arg_num(&args,13,0.4)?as f32;
2512                let fr=self.arg_num(&args,14,0.)?as f32; let hue=self.arg_num(&args,15,0.)?as f32;
2513                let mut gfx = self.gfx.borrow_mut();
2514                let cam = gfx.camera.clone();
2515                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);
2516                return Ok(Value::Unit);
2517            }
2518
2519            // vtex_tessellated(cx,cy,cz, ux,uy,uz, vx,vy,vz, cols,rows, cell, amplitude,freq, fr,hue)
2520            "vtex_tessellated" | "ลายตาข่าย" | "纹镶嵌" | "網目模様" | "격자망" => {
2521                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;
2522                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;
2523                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;
2524                let cols=self.arg_num(&args,9,14.)?as usize; let rows=self.arg_num(&args,10,10.)?as usize;
2525                let cell=self.arg_num(&args,11,0.6)?as f32;
2526                let amp=self.arg_num(&args,12,0.25)?as f32; let freq=self.arg_num(&args,13,4.)?as f32;
2527                let fr=self.arg_num(&args,14,0.)?as f32; let hue=self.arg_num(&args,15,0.)?as f32;
2528                let mut gfx = self.gfx.borrow_mut();
2529                let cam = gfx.camera.clone();
2530                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);
2531                return Ok(Value::Unit);
2532            }
2533
2534            // vtex_lotus(cx,cy,cz, ux,uy,uz, vx,vy,vz, r_inner,r_outer,n_petals, fr,hue)
2535            "vtex_lotus" | "ลายดอกบัว" | "纹莲" | "蓮模様" | "연꽃무늬" => {
2536                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;
2537                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;
2538                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;
2539                let ri=self.arg_num(&args,9,1.)?as f32; let ro=self.arg_num(&args,10,2.)?as f32;
2540                let np=self.arg_num(&args,11,12.)?as usize;
2541                let fr=self.arg_num(&args,12,0.)?as f32; let hue=self.arg_num(&args,13,0.)?as f32;
2542                let mut gfx = self.gfx.borrow_mut();
2543                let cam = gfx.camera.clone();
2544                crate::gfx::vtex::draw_lotus(&mut gfx.depth_queue,&cam, cx,cy,cz, ux,uy,uz, vx,vy,vz, ri,ro,np, fr,hue);
2545                return Ok(Value::Unit);
2546            }
2547
2548            // vtex_chakra(cx,cy,cz, ux,uy,uz, vx,vy,vz, r,n_spokes, fr,hue)
2549            "vtex_chakra" | "ลายจักร" | "纹轮" | "輪模様" | "바퀴무늬" => {
2550                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;
2551                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;
2552                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;
2553                let r=self.arg_num(&args,9,2.)?as f32; let ns=self.arg_num(&args,10,8.)?as usize;
2554                let fr=self.arg_num(&args,11,0.)?as f32; let hue=self.arg_num(&args,12,0.)?as f32;
2555                let mut gfx = self.gfx.borrow_mut();
2556                let cam = gfx.camera.clone();
2557                crate::gfx::vtex::draw_chakra(&mut gfx.depth_queue,&cam, cx,cy,cz, ux,uy,uz, vx,vy,vz, r,ns, fr,hue);
2558                return Ok(Value::Unit);
2559            }
2560
2561            // vtex_yantra(cx,cy,cz, ux,uy,uz, vx,vy,vz, n_layers,max_r, fr,hue)
2562            "vtex_yantra" | "ลายยันต์" | "纹咒" | "護符模様" | "부적무늬" => {
2563                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;
2564                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;
2565                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;
2566                let nl=self.arg_num(&args,9,4.)?as usize; let mr=self.arg_num(&args,10,3.)?as f32;
2567                let fr=self.arg_num(&args,11,0.)?as f32; let hue=self.arg_num(&args,12,0.)?as f32;
2568                let mut gfx = self.gfx.borrow_mut();
2569                let cam = gfx.camera.clone();
2570                crate::gfx::vtex::draw_yantra(&mut gfx.depth_queue,&cam, cx,cy,cz, ux,uy,uz, vx,vy,vz, nl,mr, fr,hue);
2571                return Ok(Value::Unit);
2572            }
2573
2574            // vtex_spiked_cog(cx,cy,cz, ux,uy,uz, vx,vy,vz, n_teeth,r_body,r_spike,r_hub,n_spokes, fr,hue)
2575            "vtex_spiked_cog" | "ฟันเฟืองหนาม" | "纹棘轮" | "歯車模様" | "톱니바퀴" => {
2576                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;
2577                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;
2578                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;
2579                let nt=self.arg_num(&args,9,12.)?as usize; let rb=self.arg_num(&args,10,1.)?as f32;
2580                let rs=self.arg_num(&args,11,1.3)?as f32; let rh=self.arg_num(&args,12,0.2)?as f32;
2581                let ns=self.arg_num(&args,13,6.)?as usize;
2582                let fr=self.arg_num(&args,14,0.)?as f32; let hue=self.arg_num(&args,15,0.)?as f32;
2583                let mut gfx = self.gfx.borrow_mut();
2584                let cam = gfx.camera.clone();
2585                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);
2586                return Ok(Value::Unit);
2587            }
2588
2589            // vtex_torii(cx,cy,cz, ux,uy,uz, vx,vy,vz, width,height, fr,hue)
2590            "vtex_torii" | "ประตูโทริอิ" | "纹鸟居" | "鳥居" | "도리이" => {
2591                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;
2592                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;
2593                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;
2594                let w=self.arg_num(&args,9,4.)?as f32; let h=self.arg_num(&args,10,5.)?as f32;
2595                let fr=self.arg_num(&args,11,0.)?as f32; let hue=self.arg_num(&args,12,0.)?as f32;
2596                let mut gfx = self.gfx.borrow_mut();
2597                let cam = gfx.camera.clone();
2598                crate::gfx::vtex::draw_torii(&mut gfx.depth_queue,&cam, cx,cy,cz, ux,uy,uz, vx,vy,vz, w,h, fr,hue);
2599                return Ok(Value::Unit);
2600            }
2601
2602            // vtex_pagoda(cx,cy,cz, ux,uy,uz, vx,vy,vz, n_tiers,base_w,tier_h,taper,eave_out, fr,hue)
2603            "vtex_pagoda" | "เจดีย์" | "纹塔" | "塔" | "탑" => {
2604                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;
2605                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;
2606                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;
2607                let nt=self.arg_num(&args,9,5.)?as usize; let bw=self.arg_num(&args,10,2.)?as f32;
2608                let th=self.arg_num(&args,11,1.)?as f32; let tp=self.arg_num(&args,12,0.72)?as f32;
2609                let eo=self.arg_num(&args,13,0.28)?as f32;
2610                let fr=self.arg_num(&args,14,0.)?as f32; let hue=self.arg_num(&args,15,0.)?as f32;
2611                let mut gfx = self.gfx.borrow_mut();
2612                let cam = gfx.camera.clone();
2613                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);
2614                return Ok(Value::Unit);
2615            }
2616
2617            // ══════════════════════════════════════════════════════════════════
2618            // AUDIO BUILTINS
2619            // ══════════════════════════════════════════════════════════════════
2620
2621            // audio_tone(idx, x, y, z, w, freq, amp, lfo_rate, lfo_depth)
2622            #[cfg(not(target_arch = "wasm32"))]
2623            "audio_tone" | "เสียงโทน" | "音调" | "音調" | "음조" | "空间音" | "空間音" | "공간음" => {
2624                let idx  = self.arg_num(&args, 0, 0.0)? as usize;
2625                let x    = self.arg_num(&args, 1, 0.0)? as f32;
2626                let y    = self.arg_num(&args, 2, 0.0)? as f32;
2627                let z    = self.arg_num(&args, 3, 0.0)? as f32;
2628                let w    = self.arg_num(&args, 4, 1.0)? as f32;
2629                let freq = self.arg_num(&args, 5, 220.0)? as f32;
2630                let amp  = self.arg_num(&args, 6, 0.15)? as f32;
2631                let lfo_rate  = self.arg_num(&args, 7, 0.5)? as f32;
2632                let lfo_depth = self.arg_num(&args, 8, 0.02)? as f32;
2633                if let Some(audio) = &self.audio {
2634                    audio.set_tone(idx, ToneParams { x, y, z, w, freq, amp, lfo_rate, lfo_depth });
2635                }
2636                return Ok(Value::Unit);
2637            }
2638
2639            #[cfg(not(target_arch = "wasm32"))]
2640            "audio_listener" | "ผู้ฟัง" | "音频监听" | "音声リスナー" | "오디오리스너" => {
2641                let cry = self.arg_num(&args, 0, 1.0)? as f32;
2642                let sry = self.arg_num(&args, 1, 0.0)? as f32;
2643                let crx = self.arg_num(&args, 2, 1.0)? as f32;
2644                let srx = self.arg_num(&args, 3, 0.0)? as f32;
2645                if let Some(audio) = &self.audio {
2646                    audio.set_listener(cry, sry, crx, srx);
2647                }
2648                return Ok(Value::Unit);
2649            }
2650
2651            #[cfg(not(target_arch = "wasm32"))]
2652            "audio_bgm" | "เพลงพื้นหลัง" | "เพลงประกอบ" | "背景乐" | "BGM" | "배경음악" => {
2653                let path = match args.first() {
2654                    Some(Value::Str(s)) => s.clone(),
2655                    _ => return Ok(Value::Unit),
2656                };
2657                let vol = self.arg_num(&args, 1, 0.5)? as f32;
2658                if let Some(audio) = &self.audio {
2659                    audio.load_bgm(&path, vol);
2660                }
2661                return Ok(Value::Unit);
2662            }
2663
2664            #[cfg(not(target_arch = "wasm32"))]
2665            "audio_bgm_volume" | "ระดับเสียงพื้นหลัง" | "ระดับเพลงประกอบ" | "背景乐音量" | "BGM音量" | "배경음악음량" => {
2666                let vol = self.arg_num(&args, 0, 0.5)? as f32;
2667                if let Some(audio) = &self.audio {
2668                    audio.set_bgm_volume(vol);
2669                }
2670                return Ok(Value::Unit);
2671            }
2672
2673            #[cfg(not(target_arch = "wasm32"))]
2674            "audio_volume" | "ระดับเสียง" | "音量" | "음량" => {
2675                let vol = self.arg_num(&args, 0, 0.7)? as f32;
2676                if let Some(audio) = &self.audio {
2677                    audio.set_master_volume(vol);
2678                }
2679                return Ok(Value::Unit);
2680            }
2681
2682            // WASM audio builtins — delegate to Web Audio API
2683            #[cfg(target_arch = "wasm32")]
2684            "audio_tone" | "เสียงโทน" | "音调" | "音調" | "음조" | "空间音" | "空間音" | "공간음" => {
2685                let idx  = self.arg_num(&args, 0, 0.0)? as usize;
2686                let x    = self.arg_num(&args, 1, 0.0)? as f32;
2687                let y    = self.arg_num(&args, 2, 0.0)? as f32;
2688                let z    = self.arg_num(&args, 3, 0.0)? as f32;
2689                let w    = self.arg_num(&args, 4, 1.0)? as f32;
2690                let freq = self.arg_num(&args, 5, 220.0)? as f32;
2691                let amp  = self.arg_num(&args, 6, 0.15)? as f32;
2692                let lfo_rate  = self.arg_num(&args, 7, 0.5)? as f32;
2693                let lfo_depth = self.arg_num(&args, 8, 0.02)? as f32;
2694                crate::gfx::audio_web::set_tone(idx, x, y, z, w, freq, amp, lfo_rate, lfo_depth);
2695                return Ok(Value::Unit);
2696            }
2697
2698            #[cfg(target_arch = "wasm32")]
2699            "audio_listener" | "ผู้ฟัง" | "音频监听" | "音声リスナー" | "오디오리스너" => {
2700                let cry = self.arg_num(&args, 0, 1.0)? as f32;
2701                let sry = self.arg_num(&args, 1, 0.0)? as f32;
2702                let crx = self.arg_num(&args, 2, 1.0)? as f32;
2703                let srx = self.arg_num(&args, 3, 0.0)? as f32;
2704                crate::gfx::audio_web::set_listener(cry, sry, crx, srx);
2705                return Ok(Value::Unit);
2706            }
2707
2708            #[cfg(target_arch = "wasm32")]
2709            "audio_bgm" | "เพลงพื้นหลัง" | "เพลงประกอบ" | "背景乐" | "BGM" | "배경음악" => {
2710                let path = self.arg_str(&args, 0, "");
2711                let vol  = self.arg_num(&args, 1, 0.5)? as f32;
2712                crate::gfx::audio_web::load_bgm(&path, vol);
2713                return Ok(Value::Unit);
2714            }
2715
2716            #[cfg(target_arch = "wasm32")]
2717            "audio_bgm_volume" | "ระดับเสียงพื้นหลัง" | "ระดับเพลงประกอบ" | "背景乐音量" | "BGM音量" | "배경음악음량" => {
2718                let vol = self.arg_num(&args, 0, 0.5)? as f32;
2719                crate::gfx::audio_web::set_bgm_volume(vol);
2720                return Ok(Value::Unit);
2721            }
2722
2723            #[cfg(target_arch = "wasm32")]
2724            "audio_volume" | "ระดับเสียง" | "音量" | "음량" => {
2725                let vol = self.arg_num(&args, 0, 0.7)? as f32;
2726                crate::gfx::audio_web::set_master_volume(vol);
2727                return Ok(Value::Unit);
2728            }
2729
2730            // ── รอหน้าต่าง() — block until window closed / Escape ──
2731            "รอหน้าต่าง" | "wait_window" | "gfx_wait" => {
2732                #[cfg(not(target_arch = "wasm32"))]
2733                loop {
2734                    let still_open = {
2735                        let gfx = self.gfx.borrow();
2736                        gfx.window.as_ref()
2737                            .map(|w| w.is_open() && !w.is_key_down(minifb::Key::Escape))
2738                            .unwrap_or(false)
2739                    };
2740                    if !still_open { break; }
2741                    let (buf, w, h) = {
2742                        let gfx = self.gfx.borrow();
2743                        (gfx.buffer.clone(), gfx.width, gfx.height)
2744                    };
2745                    let mut gfx = self.gfx.borrow_mut();
2746                    if let Some(win) = gfx.window.as_mut() {
2747                        if win.update_with_buffer(&buf, w, h).is_err() { break; }
2748                    }
2749                }
2750                return Ok(Value::Unit);
2751            }
2752
2753            // ── File I/O ──────────────────────────────────────────────────────
2754            "read_file" | "อ่านไฟล์" => {
2755                let path = self.arg_str(&args, 0, "");
2756                return std::fs::read_to_string(&path)
2757                    .map(Value::Str)
2758                    .map_err(|e| EvalErr::from(format!("read_file '{path}': {e}")));
2759            }
2760            // ── networking (TCP, 2-peer co-op) ───────────────────────────────
2761            #[cfg(not(target_arch = "wasm32"))]
2762            "net_host" | "เน็ตโฮสต์" => {
2763                let port = self.arg_num(&args, 0, 7777.0)? as u16;
2764                net::host(port);
2765                return Ok(Value::Unit);
2766            }
2767            #[cfg(not(target_arch = "wasm32"))]
2768            "net_join" | "เน็ตจอย" => {
2769                let ip   = self.arg_str(&args, 0, "127.0.0.1");
2770                let port = self.arg_num(&args, 1, 7777.0)? as u16;
2771                net::join(&ip, port);
2772                return Ok(Value::Unit);
2773            }
2774            #[cfg(not(target_arch = "wasm32"))]
2775            "net_send" | "เน็ตส่ง" => {
2776                let s = self.arg_str(&args, 0, "");
2777                net::send(&s);
2778                return Ok(Value::Unit);
2779            }
2780            #[cfg(not(target_arch = "wasm32"))]
2781            "net_recv" | "เน็ตรับ" => {
2782                return Ok(Value::Str(net::recv()));
2783            }
2784            #[cfg(not(target_arch = "wasm32"))]
2785            "net_status" | "เน็ตสถานะ" => {
2786                return Ok(Value::Number(net::status() as f64));
2787            }
2788            // ── LAN lobby discovery (UDP broadcast) ──
2789            #[cfg(not(target_arch = "wasm32"))]
2790            "net_announce" | "เน็ตประกาศ" => {
2791                let port = self.arg_num(&args, 0, 7778.0)? as u16;
2792                let info = self.arg_str(&args, 1, "");
2793                net::announce(port, &info);
2794                return Ok(Value::Unit);
2795            }
2796            #[cfg(not(target_arch = "wasm32"))]
2797            "net_announce_stop" | "เน็ตหยุดประกาศ" => {
2798                net::announce_stop();
2799                return Ok(Value::Unit);
2800            }
2801            #[cfg(not(target_arch = "wasm32"))]
2802            "net_discover" | "เน็ตค้นหา" => {
2803                let port = self.arg_num(&args, 0, 7778.0)? as u16;
2804                return Ok(Value::Str(net::discover(port)));
2805            }
2806
2807            // ── game AI: neural networks ─────────────────────────────────────
2808            // nn_new(inputs[, seed]) → handle
2809            #[cfg(not(target_arch = "wasm32"))]
2810            "nn_new" | "建神经网" | "ニューラル作成" | "신경망생성" | "สร้างโครงข่าย" => {
2811                let n_in = self.arg_num(&args, 0, 1.0)?.max(0.0) as usize;
2812                let seed = self.arg_num(&args, 1, 1.0)? as u64;
2813                return Ok(Value::Number(ai::nn_new(n_in, seed) as f64));
2814            }
2815            // nn_dense(handle, units[, activation]) — append a layer
2816            #[cfg(not(target_arch = "wasm32"))]
2817            "nn_dense" | "密集层" | "密層追加" | "밀집층" | "ชั้นหนาแน่น" => {
2818                let id    = self.arg_num(&args, 0, -1.0)? as i64;
2819                let units = self.arg_num(&args, 1, 1.0)?.max(1.0) as usize;
2820                let act   = self.arg_str(&args, 2, "relu");
2821                ai::nn_dense(id, units, &act);
2822                return Ok(Value::Unit);
2823            }
2824            // nn_forward(handle, [inputs]) → [outputs]
2825            #[cfg(not(target_arch = "wasm32"))]
2826            "nn_forward" | "神经前向" | "順伝播" | "순전파" | "ส่งต่อโครงข่าย" => {
2827                let id = self.arg_num(&args, 0, -1.0)? as i64;
2828                let input = self.arg_list_f32(&args, 1);
2829                let out = ai::nn_forward(id, &input);
2830                return Ok(Value::List(out.into_iter().map(|v| Value::Number(v as f64)).collect()));
2831            }
2832            // nn_train(handle, [inputs], [targets][, lr]) → loss
2833            #[cfg(not(target_arch = "wasm32"))]
2834            "nn_train" | "训练网" | "ニューラル学習" | "신경망학습" | "ฝึกโครงข่าย" => {
2835                let id     = self.arg_num(&args, 0, -1.0)? as i64;
2836                let input  = self.arg_list_f32(&args, 1);
2837                let target = self.arg_list_f32(&args, 2);
2838                let lr     = self.arg_num(&args, 3, 0.01)? as f32;
2839                return Ok(Value::Number(ai::nn_train(id, &input, &target, lr) as f64));
2840            }
2841            // nn_save(handle, path) → bool
2842            #[cfg(not(target_arch = "wasm32"))]
2843            "nn_save" | "保存网" | "網保存" | "신경망저장" | "บันทึกโครงข่าย" => {
2844                let id   = self.arg_num(&args, 0, -1.0)? as i64;
2845                let path = self.arg_str(&args, 1, "model.lnn");
2846                return Ok(Value::Bool(ai::nn_save(id, &path)));
2847            }
2848            // nn_load(path) → handle (-1 on failure)
2849            #[cfg(not(target_arch = "wasm32"))]
2850            "nn_load" | "载入网" | "網読込" | "신경망불러오기" | "โหลดโครงข่าย" => {
2851                let path = self.arg_str(&args, 0, "model.lnn");
2852                return Ok(Value::Number(ai::nn_load(&path) as f64));
2853            }
2854
2855            // ── game AI: behavior trees ──────────────────────────────────────
2856            // bt_build(dsl_string) → handle
2857            #[cfg(not(target_arch = "wasm32"))]
2858            "bt_build" | "建行为树" | "行動木構築" | "행동트리구성" | "สร้างต้นไม้พฤติกรรม" => {
2859                let spec = self.arg_str(&args, 0, "");
2860                return Ok(Value::Number(ai::bt_build(&spec) as f64));
2861            }
2862            // bt_set(handle, key, value) — set a blackboard fact
2863            #[cfg(not(target_arch = "wasm32"))]
2864            "bt_set" | "设事实" | "事実設定" | "사실설정" | "ตั้งข้อเท็จจริง" => {
2865                let id  = self.arg_num(&args, 0, -1.0)? as i64;
2866                let key = self.arg_str(&args, 1, "");
2867                let val = self.arg_num(&args, 2, 0.0)? as f32;
2868                ai::bt_set(id, &key, val);
2869                return Ok(Value::Unit);
2870            }
2871            // bt_tick(handle) → chosen action name ("" if none)
2872            #[cfg(not(target_arch = "wasm32"))]
2873            "bt_tick" | "行为树滴答" | "行動木更新" | "행동트리틱" | "เดินต้นไม้พฤติกรรม" => {
2874                let id = self.arg_num(&args, 0, -1.0)? as i64;
2875                return Ok(Value::Str(ai::bt_tick(id)));
2876            }
2877            // bt_status(handle) → 0 fail / 1 success / 2 running
2878            #[cfg(not(target_arch = "wasm32"))]
2879            "bt_status" | "行为树状态" | "行動木状態" | "행동트리상태" | "สถานะต้นไม้พฤติกรรม" => {
2880                let id = self.arg_num(&args, 0, -1.0)? as i64;
2881                return Ok(Value::Number(ai::bt_status(id) as f64));
2882            }
2883
2884            // ── game AI: miniature dialog LLM ────────────────────────────────
2885            // dialog_new([ctx, embed, hidden, seed]) → handle
2886            #[cfg(not(target_arch = "wasm32"))]
2887            "dialog_new" | "建对话模型" | "対話モデル作成" | "대화모델생성" | "สร้างโมเดลสนทนา" => {
2888                let ctx    = self.arg_num(&args, 0, 3.0)?.max(1.0) as usize;
2889                let embed  = self.arg_num(&args, 1, 32.0)?.max(1.0) as usize;
2890                let hidden = self.arg_num(&args, 2, 64.0)?.max(1.0) as usize;
2891                let seed   = self.arg_num(&args, 3, 1.0)? as u64;
2892                return Ok(Value::Number(ai::dialog_new(ctx, embed, hidden, seed) as f64));
2893            }
2894            // dialog_learn(handle, text) — add one utterance to the corpus
2895            #[cfg(not(target_arch = "wasm32"))]
2896            "dialog_learn" | "对话学习" | "対話学習" | "대화학습" | "เรียนรู้สนทนา" => {
2897                let id   = self.arg_num(&args, 0, -1.0)? as i64;
2898                let text = self.arg_str(&args, 1, "");
2899                ai::dialog_learn(id, &text);
2900                return Ok(Value::Unit);
2901            }
2902            // dialog_load(handle, path) → lines added (-1 on error)
2903            #[cfg(not(target_arch = "wasm32"))]
2904            "dialog_load" | "对话载入" | "対話読込" | "대화불러오기" | "โหลดชุดสนทนา" => {
2905                let id   = self.arg_num(&args, 0, -1.0)? as i64;
2906                let path = self.arg_str(&args, 1, "");
2907                return Ok(Value::Number(ai::dialog_load(id, &path) as f64));
2908            }
2909            // dialog_train(handle[, epochs, lr]) → loss
2910            #[cfg(not(target_arch = "wasm32"))]
2911            "dialog_train" | "对话训练" | "対話訓練" | "대화훈련" | "ฝึกสนทนา" => {
2912                let id     = self.arg_num(&args, 0, -1.0)? as i64;
2913                let epochs = self.arg_num(&args, 1, 20.0)?.max(1.0) as usize;
2914                let lr     = self.arg_num(&args, 2, 0.1)? as f32;
2915                return Ok(Value::Number(ai::dialog_train(id, epochs, lr) as f64));
2916            }
2917            // dialog_say(handle, prompt[, max_tokens, temperature]) → reply text
2918            #[cfg(not(target_arch = "wasm32"))]
2919            "dialog_say" | "对话生成" | "対話生成" | "대화생성" | "พูดสนทนา" => {
2920                let id     = self.arg_num(&args, 0, -1.0)? as i64;
2921                let prompt = self.arg_str(&args, 1, "");
2922                let max    = self.arg_num(&args, 2, 24.0)?.max(1.0) as usize;
2923                let temp   = self.arg_num(&args, 3, 0.8)? as f32;
2924                return Ok(Value::Str(ai::dialog_say(id, &prompt, max, temp)));
2925            }
2926            // dialog_save(handle, path) → bool
2927            #[cfg(not(target_arch = "wasm32"))]
2928            "dialog_save" | "对话存模" | "対話モデル保存" | "대화모델저장" | "บันทึกโมเดลสนทนา" => {
2929                let id   = self.arg_num(&args, 0, -1.0)? as i64;
2930                let path = self.arg_str(&args, 1, "model.llm");
2931                return Ok(Value::Bool(ai::dialog_save(id, &path)));
2932            }
2933            // dialog_load_model(path) → handle (-1 on failure)
2934            #[cfg(not(target_arch = "wasm32"))]
2935            "dialog_load_model" | "对话载模" | "対話モデル読込" | "대화모델불러오기" | "โหลดโมเดลสนทนา" => {
2936                let path = self.arg_str(&args, 0, "model.llm");
2937                return Ok(Value::Number(ai::dialog_load_model(&path) as f64));
2938            }
2939
2940            "write_file" | "เขียนไฟล์" => {
2941                let path    = self.arg_str(&args, 0, "");
2942                let content = self.arg_str(&args, 1, "");
2943                std::fs::write(&path, content.as_bytes())
2944                    .map_err(|e| EvalErr::from(format!("write_file '{path}': {e}")))?;
2945                return Ok(Value::Unit);
2946            }
2947            "print_file" | "พิมพ์ไฟล์" => {
2948                let content = self.arg_str(&args, 0, "");
2949                print!("{content}");
2950                return Ok(Value::Unit);
2951            }
2952
2953            // ── CLI arguments ─────────────────────────────────────────────────
2954            "get_args" | "รับอาร์กิวเมนต์" => {
2955                let v: Vec<Value> = std::env::args().map(Value::Str).collect();
2956                return Ok(Value::List(v));
2957            }
2958
2959            // ── String utilities ──────────────────────────────────────────────
2960            "split" | "str_split" | "แยก" => {
2961                let s   = self.arg_str(&args, 0, "");
2962                let sep = self.arg_str(&args, 1, "\n");
2963                let sep = if sep.is_empty() { "\n".into() } else { sep };
2964                let parts: Vec<Value> = s.split(sep.as_str())
2965                    .map(|p| Value::Str(p.to_string())).collect();
2966                return Ok(Value::List(parts));
2967            }
2968            "trim" | "str_trim" | "ตัดช่องว่าง" => {
2969                let s = self.arg_str(&args, 0, "");
2970                return Ok(Value::Str(s.trim().to_string()));
2971            }
2972            "starts_with" | "str_starts_with" | "เริ่มด้วย" => {
2973                let s      = self.arg_str(&args, 0, "");
2974                let prefix = self.arg_str(&args, 1, "");
2975                return Ok(Value::Bool(s.starts_with(prefix.as_str())));
2976            }
2977            "ends_with" | "str_ends_with" | "ลงท้ายด้วย" => {
2978                let s      = self.arg_str(&args, 0, "");
2979                let suffix = self.arg_str(&args, 1, "");
2980                return Ok(Value::Bool(s.ends_with(suffix.as_str())));
2981            }
2982            "str_replace" | "แทนสตริง" => {
2983                let s    = self.arg_str(&args, 0, "");
2984                let from = self.arg_str(&args, 1, "");
2985                let to   = self.arg_str(&args, 2, "");
2986                return Ok(Value::Str(s.replace(from.as_str(), to.as_str())));
2987            }
2988            "str_find" | "หาในสตริง" => {
2989                let s      = self.arg_str(&args, 0, "");
2990                let needle = self.arg_str(&args, 1, "");
2991                // Return char index (not byte index) for consistency with substr
2992                let pos = s.find(needle.as_str())
2993                    .map(|byte_i| s[..byte_i].chars().count() as f64)
2994                    .unwrap_or(-1.0);
2995                return Ok(Value::Number(pos));
2996            }
2997            "substr" | "str_slice" | "ส่วนสตริง" => {
2998                let s     = self.arg_str(&args, 0, "");
2999                let start = self.arg_num(&args, 1, 0.0)? as usize;
3000                let len   = args.get(2)
3001                    .map(|v| self.to_number(v).unwrap_or(999999.0) as usize)
3002                    .unwrap_or_else(|| s.chars().count().saturating_sub(start));
3003                let chars: Vec<char> = s.chars().collect();
3004                let end   = (start + len).min(chars.len());
3005                let slice: String = chars.get(start..end).unwrap_or(&[]).iter().collect();
3006                return Ok(Value::Str(slice));
3007            }
3008            "to_str" | "str" | "num_str" | "แปลงสตริง" => {
3009                let v = args.into_iter().next().unwrap_or(Value::Unit);
3010                return Ok(Value::Str(v.to_string()));
3011            }
3012            "str_repeat" | "ทำซ้ำสตริง" => {
3013                let s = self.arg_str(&args, 0, "");
3014                let n = self.arg_num(&args, 1, 1.0)? as usize;
3015                return Ok(Value::Str(s.repeat(n)));
3016            }
3017            "str_upper" => {
3018                let s = self.arg_str(&args, 0, "");
3019                return Ok(Value::Str(s.to_uppercase()));
3020            }
3021            "str_lower" => {
3022                let s = self.arg_str(&args, 0, "");
3023                return Ok(Value::Str(s.to_lowercase()));
3024            }
3025            "str_len" | "len" | "ความยาว" | "长度" | "長さ" | "길이" => {
3026                match args.first() {
3027                    Some(Value::Str(s))  => return Ok(Value::Number(s.chars().count() as f64)),
3028                    Some(Value::List(v)) => return Ok(Value::Number(v.len() as f64)),
3029                    _ => return Ok(Value::Number(0.0)),
3030                }
3031            }
3032
3033            // ── FNV-1a hash (deterministic, normalized 0.0–1.0) ──────────────
3034            "hash_str" | "แฮช" => {
3035                let s = self.arg_str(&args, 0, "");
3036                let mut h: u64 = 14695981039346656037_u64;
3037                for b in s.bytes() { h ^= b as u64; h = h.wrapping_mul(1099511628211); }
3038                return Ok(Value::Number((h & 0xFFFFFF) as f64 / 16777215.0));
3039            }
3040            "hash_int" | "แฮชจำนวน" => {
3041                let s = self.arg_str(&args, 0, "");
3042                let n = self.arg_num(&args, 1, 100.0)? as u64;
3043                let mut h: u64 = 14695981039346656037_u64;
3044                for b in s.bytes() { h ^= b as u64; h = h.wrapping_mul(1099511628211); }
3045                return Ok(Value::Number((h % n.max(1)) as f64));
3046            }
3047
3048            // ── List utilities ────────────────────────────────────────────────
3049            "list_new" | "รายการใหม่" | "新建列表" | "新規リスト" | "새목록" => {
3050                return Ok(Value::List(Vec::new()));
3051            }
3052            "list_push" | "เพิ่มรายการ" | "列表添加" | "リスト追加" | "목록추가" => {
3053                let lst = args.first().cloned().unwrap_or(Value::List(vec![]));
3054                let val = args.get(1).cloned().unwrap_or(Value::Unit);
3055                if let Value::List(mut v) = lst { v.push(val); return Ok(Value::List(v)); }
3056                return Ok(Value::List(vec![val]));
3057            }
3058            "list_get" | "รับรายการ" | "取元素" | "要素取得" | "요소가져오기" => {
3059                let lst = args.first().cloned().unwrap_or(Value::List(vec![]));
3060                let i   = self.arg_num(&args, 1, 0.0)? as usize;
3061                if let Value::List(v) = lst {
3062                    return Ok(v.get(i).cloned().unwrap_or(Value::Str(String::new())));
3063                }
3064                return Ok(Value::Str(String::new()));
3065            }
3066            "list_join" | "join" | "รวมรายการ" | "连接" | "連結" | "연결" => {
3067                let lst = args.first().cloned().unwrap_or(Value::List(vec![]));
3068                let sep = args.get(1).map(|v| v.to_string()).unwrap_or_default();
3069                if let Value::List(v) = lst {
3070                    return Ok(Value::Str(v.iter().map(|x| x.to_string())
3071                        .collect::<Vec<_>>().join(&sep)));
3072                }
3073                return Ok(Value::Str(String::new()));
3074            }
3075            // blob_f32("<deflate+base64>") / blob_i32(...) — decode an embedded,
3076            // losslessly-compressed numeric blob into a list. Produced by
3077            // `ling convert`; lets converted assets carry geometry/PCM/etc. compactly.
3078            #[cfg(not(target_arch = "wasm32"))]
3079            "blob_f32" | "blob_i32" => {
3080                let s = self.arg_str(&args, 0, "");
3081                let is_i32 = name == "blob_i32";
3082                match decode_blob(&s) {
3083                    Ok(bytes) => {
3084                        let mut out = Vec::with_capacity(bytes.len() / 4);
3085                        for ch in bytes.chunks_exact(4) {
3086                            let arr = [ch[0], ch[1], ch[2], ch[3]];
3087                            let n = if is_i32 {
3088                                i32::from_le_bytes(arr) as f64
3089                            } else {
3090                                f32::from_le_bytes(arr) as f64
3091                            };
3092                            out.push(Value::Number(n));
3093                        }
3094                        return Ok(Value::List(out));
3095                    }
3096                    Err(e) => {
3097                        eprintln!("blob decode failed: {e}");
3098                        return Ok(Value::List(vec![]));
3099                    }
3100                }
3101            }
3102
3103            // ══════════════════════════════════════════════════════════════════
3104            // SVG EXPORT  (svg_begin / svg_rect / svg_circle / svg_line /
3105            //              svg_polyline / svg_text / svg_end / hsl_color)
3106            // Chinese aliases: 开始SVG 结束SVG SVG矩形 SVG圆形 SVG线段 SVG折线 SVG文本 HSL颜色
3107            // Thai aliases:    เริ่มSVG จบSVG SVGสี่เหลี่ยม SVGวงกลม SVGเส้น SVGเส้นหัก SVGข้อความ สีHSL
3108            // ══════════════════════════════════════════════════════════════════
3109
3110            "svg_begin" | "开始SVG" | "เริ่มSVG" => {
3111                let path   = self.arg_str(&args, 0, "output.svg");
3112                let width  = self.arg_num(&args, 1, 800.0)?;
3113                let height = self.arg_num(&args, 2, 600.0)?;
3114                *self.svg.borrow_mut() = Some(SvgWriter::new(path, width, height));
3115                return Ok(Value::Unit);
3116            }
3117
3118            "svg_rect" | "SVG矩形" | "SVGสี่เหลี่ยม" => {
3119                let x    = self.arg_num(&args, 0, 0.0)?;
3120                let y    = self.arg_num(&args, 1, 0.0)?;
3121                let w    = self.arg_num(&args, 2, 10.0)?;
3122                let h    = self.arg_num(&args, 3, 10.0)?;
3123                let fill = self.arg_str(&args, 4, "#ffffff");
3124                if let Some(svg) = self.svg.borrow_mut().as_mut() {
3125                    svg.elements.push(format!(
3126                        "<rect x=\"{x:.1}\" y=\"{y:.1}\" width=\"{w:.1}\" \
3127                         height=\"{h:.1}\" fill=\"{fill}\"/>"));
3128                }
3129                return Ok(Value::Unit);
3130            }
3131
3132            "svg_circle" | "SVG圆形" | "SVGวงกลม" => {
3133                let cx   = self.arg_num(&args, 0, 0.0)?;
3134                let cy   = self.arg_num(&args, 1, 0.0)?;
3135                let r    = self.arg_num(&args, 2, 5.0)?;
3136                let fill = self.arg_str(&args, 3, "#ffffff");
3137                if let Some(svg) = self.svg.borrow_mut().as_mut() {
3138                    svg.elements.push(format!(
3139                        "<circle cx=\"{cx:.1}\" cy=\"{cy:.1}\" r=\"{r:.1}\" fill=\"{fill}\"/>"));
3140                }
3141                return Ok(Value::Unit);
3142            }
3143
3144            "svg_line" | "SVG线段" | "SVGเส้น" => {
3145                let x1     = self.arg_num(&args, 0, 0.0)?;
3146                let y1     = self.arg_num(&args, 1, 0.0)?;
3147                let x2     = self.arg_num(&args, 2, 0.0)?;
3148                let y2     = self.arg_num(&args, 3, 0.0)?;
3149                let stroke = self.arg_str(&args, 4, "#ffffff");
3150                let sw     = self.arg_num(&args, 5, 1.0)?;
3151                if let Some(svg) = self.svg.borrow_mut().as_mut() {
3152                    svg.elements.push(format!(
3153                        "<line x1=\"{x1:.1}\" y1=\"{y1:.1}\" x2=\"{x2:.1}\" y2=\"{y2:.1}\" \
3154                         stroke=\"{stroke}\" stroke-width=\"{sw:.1}\"/>"));
3155                }
3156                return Ok(Value::Unit);
3157            }
3158
3159            "svg_polyline" | "SVG折线" | "SVGเส้นหัก" => {
3160                let pts    = self.arg_str(&args, 0, "");
3161                let stroke = self.arg_str(&args, 1, "#ffffff");
3162                let sw     = self.arg_num(&args, 2, 1.0)?;
3163                if let Some(svg) = self.svg.borrow_mut().as_mut() {
3164                    svg.elements.push(format!(
3165                        "<polyline points=\"{pts}\" fill=\"none\" \
3166                         stroke=\"{stroke}\" stroke-width=\"{sw:.1}\"/>"));
3167                }
3168                return Ok(Value::Unit);
3169            }
3170
3171            "svg_text" | "SVG文本" | "SVGข้อความ" => {
3172                let x    = self.arg_num(&args, 0, 0.0)?;
3173                let y    = self.arg_num(&args, 1, 0.0)?;
3174                let text = self.arg_str(&args, 2, "");
3175                let fill = self.arg_str(&args, 3, "#ffffff");
3176                let size = self.arg_num(&args, 4, 12.0)?;
3177                if let Some(svg) = self.svg.borrow_mut().as_mut() {
3178                    let safe = text.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;");
3179                    svg.elements.push(format!(
3180                        "<text x=\"{x:.1}\" y=\"{y:.1}\" fill=\"{fill}\" \
3181                         font-family=\"monospace\" font-size=\"{size:.0}\">{safe}</text>"));
3182                }
3183                return Ok(Value::Unit);
3184            }
3185
3186            "svg_end" | "结束SVG" | "จบSVG" => {
3187                {
3188                    let borrow = self.svg.borrow();
3189                    if let Some(svg) = borrow.as_ref() {
3190                        svg.save().map_err(|e| EvalErr::from(format!("svg_end: {e}")))?;
3191                    }
3192                }
3193                *self.svg.borrow_mut() = None;
3194                return Ok(Value::Unit);
3195            }
3196
3197            "hsl_color" | "HSL颜色" | "สีHSL" => {
3198                let h = self.arg_num(&args, 0, 0.0)?;
3199                let s = self.arg_num(&args, 1, 70.0)?;
3200                let l = self.arg_num(&args, 2, 50.0)?;
3201                return Ok(Value::Str(hsl_to_hex(h, s, l)));
3202            }
3203
3204            // ══════════════════════════════════════════════════════════════════
3205            // FFT / AUDIO ANALYSIS BUILTINS  (native only)
3206            // ══════════════════════════════════════════════════════════════════
3207
3208            // fft_push(samples_list) — feed raw audio samples and run FFT
3209            #[cfg(not(target_arch = "wasm32"))]
3210            "fft_push" | "วิเคราะห์เสียง" | "频谱输入" | "FFT入力" | "FFT입력" => {
3211                if let Some(Value::List(v)) = args.first() {
3212                    let samples: Vec<f32> = v.iter()
3213                        .filter_map(|x| if let Value::Number(n) = x { Some(*n as f32) } else { None })
3214                        .collect();
3215                    self.fft.borrow_mut().push_samples(&samples);
3216                }
3217                return Ok(Value::Unit);
3218            }
3219
3220            // fft_bands(n) → list of n log-spaced magnitude bands (0..1)
3221            #[cfg(not(target_arch = "wasm32"))]
3222            "fft_bands" | "แถบความถี่" | "频段" | "周波数帯" | "주파수대" => {
3223                let n = self.arg_num(&args, 0, 32.0)? as usize;
3224                let bands = self.fft.borrow().freq_bands(n);
3225                *self.fft_bands_cache.borrow_mut() = bands.clone();
3226                return Ok(Value::List(bands.into_iter().map(|v| Value::Number(v as f64)).collect()));
3227            }
3228
3229            // fft_beat() → bool
3230            #[cfg(not(target_arch = "wasm32"))]
3231            "fft_beat" | "จังหวะเสียง" | "节拍检测" | "ビート検出" | "비트" => {
3232                return Ok(Value::Bool(self.fft.borrow().is_beat()));
3233            }
3234
3235            // fft_beat_ratio() → f64  (1.0 = at threshold, >1 = strong beat)
3236            #[cfg(not(target_arch = "wasm32"))]
3237            "fft_beat_ratio" | "อัตราจังหวะ" | "节拍比" | "ビート比" | "비트비율" => {
3238                return Ok(Value::Number(self.fft.borrow().beat_ratio() as f64));
3239            }
3240
3241            // fft_rms() → f64
3242            #[cfg(not(target_arch = "wasm32"))]
3243            "fft_rms" | "ระดับRMS" | "均方根" | "二乗平均" | "RMS레벨" => {
3244                return Ok(Value::Number(self.fft.borrow().rms() as f64));
3245            }
3246
3247            // fft_dominant_freq() → f64  in Hz
3248            #[cfg(not(target_arch = "wasm32"))]
3249            "fft_dominant_freq" | "ความถี่หลัก" | "主频" | "主要周波数" | "주파수" => {
3250                return Ok(Value::Number(self.fft.borrow().dominant_freq() as f64));
3251            }
3252
3253            // ── wasm32 stubs: fft builtins are no-ops on web ───────────────
3254            #[cfg(target_arch = "wasm32")]
3255            "fft_push" | "วิเคราะห์เสียง" | "频谱输入" | "FFT入力" | "FFT입력" => { return Ok(Value::Unit); }
3256            #[cfg(target_arch = "wasm32")]
3257            "fft_bands" | "แถบความถี่" | "频段" | "周波数帯" | "주파수대" => {
3258                let n = self.arg_num(&args, 0, 32.0)? as usize;
3259                return Ok(Value::List(vec![Value::Number(0.0); n]));
3260            }
3261            #[cfg(target_arch = "wasm32")]
3262            "fft_beat" | "จังหวะเสียง" | "节拍检测" | "ビート検出" | "비트" => { return Ok(Value::Bool(false)); }
3263            #[cfg(target_arch = "wasm32")]
3264            "fft_beat_ratio" | "อัตราจังหวะ" | "节拍比" | "ビート比" | "비트비율" => { return Ok(Value::Number(1.0)); }
3265            #[cfg(target_arch = "wasm32")]
3266            "fft_rms" | "ระดับRMS" | "均方根" | "二乗平均" | "RMS레벨" => { return Ok(Value::Number(0.0)); }
3267            #[cfg(target_arch = "wasm32")]
3268            "fft_dominant_freq" | "ความถี่หลัก" | "主频" | "主要周波数" | "주파수" => { return Ok(Value::Number(0.0)); }
3269
3270            // ══════════════════════════════════════════════════════════════════
3271            // PROCEDURAL TEXTURE BLIT BUILTINS  (screen-space)
3272            // All: name(dst_x, dst_y, width, height, ...params, palette)
3273            // palette: "rainbow" | "fire" | "ocean" | "psychedelic" | "neon" | "forest"
3274            // ══════════════════════════════════════════════════════════════════
3275
3276            // tex_checkerboard(x, y, w, h, tiles, r1,g1,b1, r2,g2,b2)
3277            "tex_checkerboard" | "ลายตารางหมากรุก" => {
3278                let (tx,ty,tw,th) = self.tex_rect(&args)?;
3279                let tiles = self.arg_num(&args, 4, 8.0)? as u32;
3280                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);
3281                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);
3282                let c1 = (r1<<16)|(g1<<8)|b1; let c2 = (r2<<16)|(g2<<8)|b2;
3283                let mut gfx = self.gfx.borrow_mut();
3284                let (bw, bh) = (gfx.width, gfx.height);
3285                for row in 0..th { for col in 0..tw {
3286                    let cx = col as u32 * tiles / tw as u32;
3287                    let cy = row as u32 * tiles / th as u32;
3288                    let (dx, dy) = (tx+col, ty+row);
3289                    if dx < bw && dy < bh { gfx.buffer[dy*bw+dx] = if (cx+cy)%2==0 { c1 } else { c2 }; }
3290                }}
3291                return Ok(Value::Unit);
3292            }
3293
3294            // tex_gradient(x, y, w, h, angle_deg, r1,g1,b1, r2,g2,b2)
3295            "tex_gradient" | "ลายไล่สี" => {
3296                let (tx,ty,tw,th) = self.tex_rect(&args)?;
3297                let angle = self.arg_num(&args, 4, 0.0)? as f32;
3298                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.);
3299                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.);
3300                let (ca, sa) = (angle.to_radians().cos(), angle.to_radians().sin());
3301                let mut gfx = self.gfx.borrow_mut();
3302                let (bw, bh) = (gfx.width, gfx.height);
3303                for row in 0..th { for col in 0..tw {
3304                    let nx = col as f32/tw as f32 - 0.5; let ny = row as f32/th as f32 - 0.5;
3305                    let t = ((nx*ca + ny*sa + 0.707)/1.414).clamp(0.,1.);
3306                    let (dx, dy) = (tx+col, ty+row);
3307                    if dx < bw && dy < bh { gfx.buffer[dy*bw+dx] = tex_rgb(r1+(r2-r1)*t, g1+(g2-g1)*t, b1+(b2-b1)*t); }
3308                }}
3309                return Ok(Value::Unit);
3310            }
3311
3312            // tex_noise(x, y, w, h, scale, octaves, seed, palette)
3313            "tex_noise" | "ลายนอยส์" => {
3314                let (tx,ty,tw,th) = self.tex_rect(&args)?;
3315                let scale   = self.arg_num(&args, 4, 4.0)? as f32;
3316                let octaves = self.arg_num(&args, 5, 4.0)? as u32;
3317                let seed    = self.arg_num(&args, 6, 0.0)? as u32;
3318                let palette = self.arg_str(&args, 7, "rainbow");
3319                let mut gfx = self.gfx.borrow_mut();
3320                let (bw, bh) = (gfx.width, gfx.height);
3321                for row in 0..th { for col in 0..tw {
3322                    let v = tex_fbm(col as f32*scale/tw as f32, row as f32*scale/th as f32, octaves, seed);
3323                    let [r,g,b] = tex_palette(&palette, v);
3324                    let (dx, dy) = (tx+col, ty+row);
3325                    if dx < bw && dy < bh { gfx.buffer[dy*bw+dx] = tex_rgb(r, g, b); }
3326                }}
3327                return Ok(Value::Unit);
3328            }
3329
3330            // tex_freq_map(x, y, w, h, time, speed, palette)
3331            // Uses bands written by the last fft_bands() call.
3332            "tex_freq_map" | "ลายความถี่" => {
3333                let (tx,ty,tw,th) = self.tex_rect(&args)?;
3334                let time    = self.arg_num(&args, 4, 0.0)? as f32;
3335                let speed   = self.arg_num(&args, 5, 0.3)? as f32;
3336                let palette = self.arg_str(&args, 6, "rainbow");
3337                let bands: Vec<f32> = {
3338                    let c = self.fft_bands_cache.borrow();
3339                    if c.is_empty() { vec![0.0; 32] } else { c.clone() }
3340                };
3341                let n = bands.len().max(1);
3342                let mut gfx = self.gfx.borrow_mut();
3343                let (bw, bh) = (gfx.width, gfx.height);
3344                for row in 0..th { for col in 0..tw {
3345                    let band_idx = (col * n / tw.max(1)).min(n-1);
3346                    let mag = bands[band_idx].clamp(0.,1.);
3347                    let fill_y = (mag * th as f32) as usize;
3348                    if row >= th.saturating_sub(fill_y) {
3349                        let t = (col as f32/tw as f32 + time*speed) % 1.0;
3350                        let [r,g,b] = tex_palette(&palette, t);
3351                        let bright = mag * (1.0 - row as f32/th as f32 * 0.5);
3352                        let (dx, dy) = (tx+col, ty+row);
3353                        if dx < bw && dy < bh { gfx.buffer[dy*bw+dx] = tex_rgb(r*bright, g*bright, b*bright); }
3354                    }
3355                }}
3356                return Ok(Value::Unit);
3357            }
3358
3359            // tex_spiral(x, y, w, h, freq, bands, time, palette)
3360            "tex_spiral" | "ลายเกลียวหมุน" => {
3361                let (tx,ty,tw,th) = self.tex_rect(&args)?;
3362                let freq    = self.arg_num(&args, 4, 5.0)? as f32;
3363                let n_bands = self.arg_num(&args, 5, 8.0)? as f32;
3364                let time    = self.arg_num(&args, 6, 0.0)? as f32;
3365                let palette = self.arg_str(&args, 7, "rainbow");
3366                let mut gfx = self.gfx.borrow_mut();
3367                let (bw, bh) = (gfx.width, gfx.height);
3368                for row in 0..th { for col in 0..tw {
3369                    let nx = col as f32/tw as f32 - 0.5; let ny = row as f32/th as f32 - 0.5;
3370                    let r  = (nx*nx + ny*ny).sqrt();
3371                    let theta = ny.atan2(nx);
3372                    let t = ((r*freq - theta/std::f32::consts::TAU + time*0.5) * n_bands % 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_ripple(x, y, w, h, freq, cx, cy, time, palette)
3381            "tex_ripple" | "ลายระลอก" => {
3382                let (tx,ty,tw,th) = self.tex_rect(&args)?;
3383                let freq    = self.arg_num(&args, 4, 10.0)? as f32;
3384                let rcx     = self.arg_num(&args, 5, 0.5)? as f32;
3385                let rcy     = self.arg_num(&args, 6, 0.5)? as f32;
3386                let time    = self.arg_num(&args, 7, 0.0)? as f32;
3387                let palette = self.arg_str(&args, 8, "ocean");
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 nx = col as f32/tw as f32 - rcx; let ny = row as f32/th as f32 - rcy;
3392                    let r = (nx*nx + ny*ny).sqrt();
3393                    let t = ((r*freq - time) % 1.0).abs();
3394                    let [cr,cg,cb] = tex_palette(&palette, t);
3395                    let (dx, dy) = (tx+col, ty+row);
3396                    if dx < bw && dy < bh { gfx.buffer[dy*bw+dx] = tex_rgb(cr, cg, cb); }
3397                }}
3398                return Ok(Value::Unit);
3399            }
3400
3401            // tex_mandelbrot(x, y, w, h, zoom, cx, cy, max_iter, palette)
3402            "tex_mandelbrot" | "ลายแมนเดลบรอต" => {
3403                let (tx,ty,tw,th) = self.tex_rect(&args)?;
3404                let zoom     = self.arg_num(&args, 4, 1.0)?;
3405                let mcx      = self.arg_num(&args, 5, -0.5)?;
3406                let mcy      = self.arg_num(&args, 6, 0.0)?;
3407                let max_iter = self.arg_num(&args, 7, 64.0)? as u32;
3408                let palette  = self.arg_str(&args, 8, "psychedelic");
3409                let mut gfx = self.gfx.borrow_mut();
3410                let (bw, bh) = (gfx.width, gfx.height);
3411                for row in 0..th { for col in 0..tw {
3412                    let zx0 = (col as f64/tw as f64 - 0.5)/zoom + mcx;
3413                    let zy0 = (row as f64/th as f64 - 0.5)/zoom + mcy;
3414                    let mut x = 0.0f64; let mut y = 0.0f64; let mut i = 0u32;
3415                    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; }
3416                    let t = if i==max_iter { 0.0f32 } else {
3417                        (i as f32 - (x as f32*x as f32+y as f32*y as f32).ln().ln()/2.0f32.ln()) / max_iter as f32
3418                    };
3419                    let [cr,cg,cb] = tex_palette(&palette, t.clamp(0.,1.));
3420                    let (dx, dy) = (tx+col, ty+row);
3421                    if dx < bw && dy < bh { gfx.buffer[dy*bw+dx] = tex_rgb(cr, cg, cb); }
3422                }}
3423                return Ok(Value::Unit);
3424            }
3425
3426            // tex_julia(x, y, w, h, c_re, c_im, max_iter, palette)
3427            "tex_julia" | "ลายจูเลีย" => {
3428                let (tx,ty,tw,th) = self.tex_rect(&args)?;
3429                let c_re     = self.arg_num(&args, 4, -0.7)?;
3430                let c_im     = self.arg_num(&args, 5, 0.27)?;
3431                let max_iter = self.arg_num(&args, 6, 64.0)? as u32;
3432                let palette  = self.arg_str(&args, 7, "neon");
3433                let mut gfx = self.gfx.borrow_mut();
3434                let (bw, bh) = (gfx.width, gfx.height);
3435                for row in 0..th { for col in 0..tw {
3436                    let mut zx = (col as f64/tw as f64 - 0.5)*3.5;
3437                    let mut zy = (row as f64/th as f64 - 0.5)*3.5;
3438                    let mut i = 0u32;
3439                    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; }
3440                    let t = i as f32 / max_iter as f32;
3441                    let [cr,cg,cb] = tex_palette(&palette, t);
3442                    let (dx, dy) = (tx+col, ty+row);
3443                    if dx < bw && dy < bh { gfx.buffer[dy*bw+dx] = tex_rgb(cr, cg, cb); }
3444                }}
3445                return Ok(Value::Unit);
3446            }
3447
3448            // tex_voronoi(x, y, w, h, cells, seed, palette)
3449            "tex_voronoi" | "ลายโวโรนอย" => {
3450                let (tx,ty,tw,th) = self.tex_rect(&args)?;
3451                let cells   = self.arg_num(&args, 4, 16.0)? as u32;
3452                let seed    = self.arg_num(&args, 5, 42.0)? as u32;
3453                let palette = self.arg_str(&args, 6, "rainbow");
3454                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();
3455                let mut gfx = self.gfx.borrow_mut();
3456                let (bw, bh) = (gfx.width, gfx.height);
3457                for row in 0..th { for col in 0..tw {
3458                    let (fx, fy) = (col as f32/tw as f32, row as f32/th as f32);
3459                    let (min_d, nearest) = pts.iter().enumerate().fold((f32::MAX,0usize), |(d,idx),(i,&[cx,cy])| {
3460                        let dd = (fx-cx).powi(2)+(fy-cy).powi(2);
3461                        if dd < d { (dd,i) } else { (d,idx) }
3462                    });
3463                    let t = (nearest as f32/cells as f32 + min_d*4.0) % 1.0;
3464                    let [cr,cg,cb] = tex_palette(&palette, t);
3465                    let (dx, dy) = (tx+col, ty+row);
3466                    if dx < bw && dy < bh { gfx.buffer[dy*bw+dx] = tex_rgb(cr, cg, cb); }
3467                }}
3468                return Ok(Value::Unit);
3469            }
3470
3471            // tex_halftone(x, y, w, h, dot_size, time, palette)
3472            "tex_halftone" | "ลายฮาล์ฟโทน" => {
3473                let (tx,ty,tw,th) = self.tex_rect(&args)?;
3474                let dot_size = self.arg_num(&args, 4, 0.05)? as f32;
3475                let time     = self.arg_num(&args, 5, 0.0)? as f32;
3476                let palette  = self.arg_str(&args, 6, "rainbow");
3477                let mut gfx = self.gfx.borrow_mut();
3478                let (bw, bh) = (gfx.width, gfx.height);
3479                for row in 0..th { for col in 0..tw {
3480                    let (fx, fy) = (col as f32/tw as f32, row as f32/th as f32);
3481                    let gx = (fx/dot_size).floor(); let gy = (fy/dot_size).floor();
3482                    let lx = (fx/dot_size - gx - 0.5)*2.0; let ly = (fy/dot_size - gy - 0.5)*2.0;
3483                    let r = (lx*lx + ly*ly).sqrt();
3484                    let t = (gx/(1.0/dot_size) + time*0.1) % 1.0;
3485                    let a = if r < 0.7 { ((0.7-r)/0.7).clamp(0.,1.) } else { 0.0 };
3486                    if a > 0.0 {
3487                        let [cr,cg,cb] = tex_palette(&palette, t);
3488                        let (dx, dy) = (tx+col, ty+row);
3489                        if dx < bw && dy < bh { gfx.buffer[dy*bw+dx] = tex_rgb(cr, cg, cb); }
3490                    }
3491                }}
3492                return Ok(Value::Unit);
3493            }
3494
3495            // ══════════════════════════════════════════════════════════════════
3496            // RENDER / LIGHTING MODES  (holographic cel shading)
3497            // ══════════════════════════════════════════════════════════════════
3498            // set_shade_mode(m) — 0 flat · 1 cel · 2 holo (default)
3499            "set_shade_mode" | "设置着色" | "シェード設定" | "셰이드모드" | "ตั้งการแรเงา" => {
3500                let m = self.arg_num(&args, 0, 2.0)? as u8;
3501                self.gfx.borrow_mut().shade_mode = m;
3502                return Ok(Value::Unit);
3503            }
3504            // set_cel_bands(n) — number of posterisation bands (>=2)
3505            "set_cel_bands" | "设置色阶" | "セル段数" | "셀밴드" | "ตั้งระดับสี" => {
3506                let n = (self.arg_num(&args, 0, 4.0)? as u32).max(2);
3507                self.gfx.borrow_mut().shade.bands = n;
3508                return Ok(Value::Unit);
3509            }
3510            // set_shadow_color(r,g,b) — coloured-shadow tint, 0-255
3511            "set_shadow_color" | "设置阴影色" | "影の色" | "그림자색" | "ตั้งสีเงา" => {
3512                let r=self.arg_num(&args,0,26.)? as f32/255.0;
3513                let g=self.arg_num(&args,1,33.)? as f32/255.0;
3514                let b=self.arg_num(&args,2,77.)? as f32/255.0;
3515                self.gfx.borrow_mut().shade.shadow = [r,g,b];
3516                return Ok(Value::Unit);
3517            }
3518            // set_rim(strength, r,g,b) — holographic fresnel edge glow
3519            // ══════════════════════════════════════════════════════════════════
3520            // CRYPTOGRAPHY (ling-crypto) — geo suite, hybrid PQ KEM, holographic
3521            // Bytes cross the language boundary as lowercase hex strings.
3522            // ══════════════════════════════════════════════════════════════════
3523            #[cfg(not(target_arch = "wasm32"))]
3524            "crypto_hash" | "แฮชเข้ารหัส" | "几何哈希" | "幾何ハッシュ" | "기하해시" => {
3525                let s = self.arg_str(&args, 0, "");
3526                return Ok(Value::Str(hex_encode(&ling_crypto::geo::holo_hash(s.as_bytes()))));
3527            }
3528            // 3-D torus-knot fingerprint of any text/key → flat [x,y,z, x,y,z, …]
3529            #[cfg(not(target_arch = "wasm32"))]
3530            "knot_points" | "จุดปม" | "结点坐标" | "結び目点" | "매듭점" => {
3531                let s = self.arg_str(&args, 0, "");
3532                let shape = ling_crypto::geo::KnotShape::from_bytes(s.as_bytes());
3533                let mut out = Vec::with_capacity(shape.points.len() * 3);
3534                for p in &shape.points {
3535                    out.push(Value::Number(p[0] as f64));
3536                    out.push(Value::Number(p[1] as f64));
3537                    out.push(Value::Number(p[2] as f64));
3538                }
3539                return Ok(Value::List(out));
3540            }
3541            #[cfg(not(target_arch = "wasm32"))]
3542            "knot_label" | "ป้ายปม" | "结点标签" | "結び目ラベル" | "매듭라벨" => {
3543                let s = self.arg_str(&args, 0, "");
3544                return Ok(Value::Str(ling_crypto::geo::KnotShape::from_bytes(s.as_bytes()).label()));
3545            }
3546            // KEM keypair (hybrid X25519+ML-KEM-768) → integer handle
3547            #[cfg(not(target_arch = "wasm32"))]
3548            "knot_keygen" | "hybrid_keygen" | "สร้างกุญแจปม" | "生成密钥" | "鍵生成" | "키생성" => {
3549                self.crypto_ids.push(ling_crypto::KnotIdentity::generate());
3550                return Ok(Value::Number((self.crypto_ids.len() - 1) as f64));
3551            }
3552            #[cfg(not(target_arch = "wasm32"))]
3553            "knot_public" | "hybrid_public" | "กุญแจสาธารณะปม" | "公钥" | "公開鍵" | "공개키" => {
3554                let h = self.arg_num(&args, 0, 0.0)? as usize;
3555                let pk = self.crypto_ids.get(h).map(|id| hex_encode(id.public_key())).unwrap_or_default();
3556                return Ok(Value::Str(pk));
3557            }
3558            // encapsulate(pubkey_hex) → [ciphertext_hex, shared_secret_hex]
3559            #[cfg(not(target_arch = "wasm32"))]
3560            "knot_encapsulate" | "hybrid_encapsulate" | "ห่อกุญแจปม" | "封装密钥" | "カプセル化" | "캡슐화" => {
3561                let pk = hex_decode(&self.arg_str(&args, 0, ""));
3562                match ling_crypto::geo::knot_encapsulate(&pk) {
3563                    Ok((ct, ss)) => return Ok(Value::List(vec![Value::Str(hex_encode(&ct)), Value::Str(hex_encode(&ss))])),
3564                    Err(e) => return Ok(Value::Err(Box::new(Value::Str(e.to_string())))),
3565                }
3566            }
3567            // decapsulate(handle, ciphertext_hex) → shared_secret_hex
3568            #[cfg(not(target_arch = "wasm32"))]
3569            "knot_decapsulate" | "hybrid_decapsulate" | "แกะกุญแจปม" | "解封装密钥" | "カプセル解除" | "캡슐해제" => {
3570                let h = self.arg_num(&args, 0, 0.0)? as usize;
3571                let ct = hex_decode(&self.arg_str(&args, 1, ""));
3572                let ss = self.crypto_ids.get(h)
3573                    .and_then(|id| id.decapsulate(&ct).ok())
3574                    .map(|s| hex_encode(&s)).unwrap_or_default();
3575                return Ok(Value::Str(ss));
3576            }
3577            // Authenticated encryption (XChaCha20-Poly1305) — seal(key_hex, text) → ct_hex
3578            #[cfg(not(target_arch = "wasm32"))]
3579            "crypto_seal" | "ผนึก" | "封印" | "封印する" | "봉인" => {
3580                let key = hex_to_32(&self.arg_str(&args, 0, ""));
3581                let pt = self.arg_str(&args, 1, "");
3582                match ling_crypto::geo::holo_seal(key, pt.as_bytes()) {
3583                    Ok(ct) => return Ok(Value::Str(hex_encode(&ct))),
3584                    Err(e) => return Ok(Value::Err(Box::new(Value::Str(e.to_string())))),
3585                }
3586            }
3587            #[cfg(not(target_arch = "wasm32"))]
3588            "crypto_open" | "เปิดผนึก" | "解封" | "封印解除" | "봉인해제" => {
3589                let key = hex_to_32(&self.arg_str(&args, 0, ""));
3590                let ct = hex_decode(&self.arg_str(&args, 1, ""));
3591                match ling_crypto::geo::holo_open(key, &ct) {
3592                    Ok(pt) => return Ok(Value::Str(String::from_utf8_lossy(&pt).into_owned())),
3593                    Err(e) => return Ok(Value::Err(Box::new(Value::Str(e.to_string())))),
3594                }
3595            }
3596            // Holographic all-or-nothing transform — 4-D fragment coords [a,b,c,d, …]
3597            #[cfg(not(target_arch = "wasm32"))]
3598            "holo_points" | "จุดโฮโลแกรม" | "全息点" | "ホログラム点" | "홀로그램점" => {
3599                let s = self.arg_str(&args, 0, "");
3600                let frags = ling_crypto::geo::scatter(s.as_bytes());
3601                let mut out = Vec::with_capacity(frags.len() * 4);
3602                for f in &frags { for c in f.coord { out.push(Value::Number(c as f64)); } }
3603                return Ok(Value::List(out));
3604            }
3605            #[cfg(not(target_arch = "wasm32"))]
3606            "holo_fragment_count" | "จำนวนชิ้นโฮโลแกรม" | "全息碎片数" | "ホログラム断片数" | "홀로그램조각수" => {
3607                let s = self.arg_str(&args, 0, "");
3608                return Ok(Value::Number(ling_crypto::geo::scatter(s.as_bytes()).len() as f64));
3609            }
3610
3611            // ══════════════════════════════════════════════════════════════════
3612            // ling-ui — animation easings + holographic vector widgets + text I/O
3613            // ══════════════════════════════════════════════════════════════════
3614            "ease" => {
3615                let name = self.arg_str(&args, 0, "ease");
3616                let t = self.arg_num(&args, 1, 0.0)? as f32;
3617                return Ok(Value::Number(ling_ui::Easing::from_name(&name).apply(t) as f64));
3618            }
3619
3620            // ══════════════════════════════════════════════════════════════════
3621            // Anima — unified animation drivers (ling-animation). Organic 灵 +
3622            // mechanical 机 scalar drivers, callable per frame from a script.
3623            // ══════════════════════════════════════════════════════════════════
3624            "tween" | "补间" | "補間" | "트윈" | "แทรกค่า" => {
3625                let a = self.arg_num(&args, 0, 0.0)?;
3626                let b = self.arg_num(&args, 1, 0.0)?;
3627                let t = self.arg_num(&args, 2, 0.0)?.clamp(0.0, 1.0);
3628                return Ok(Value::Number(a + (b - a) * t));
3629            }
3630            "tween_ease" | "缓动补间" | "緩和補間" | "이징트윈" | "แทรกนุ่ม" => {
3631                let a = self.arg_num(&args, 0, 0.0)? as f32;
3632                let b = self.arg_num(&args, 1, 0.0)? as f32;
3633                let t = self.arg_num(&args, 2, 0.0)? as f32;
3634                let kind = self.arg_str(&args, 3, "linear");
3635                let e = ling_animation::EaseFunction::from_name(&kind);
3636                return Ok(Value::Number(ling_animation::ease::tween_ease(&a, &b, t, e) as f64));
3637            }
3638            // ── Organic 灵 ──
3639            "breathe" | "呼吸" | "호흡" | "หายใจ" => {
3640                let t = self.arg_num(&args, 0, 0.0)? as f32;
3641                let rate = self.arg_num(&args, 1, 1.0)? as f32;
3642                let depth = self.arg_num(&args, 2, 0.1)? as f32;
3643                return Ok(Value::Number(ling_animation::scalar::breathe(t, rate, depth) as f64));
3644            }
3645            "wobble" | "摆动" | "揺れ" | "흔들림" | "โยก" => {
3646                let t = self.arg_num(&args, 0, 0.0)? as f32;
3647                let freq = self.arg_num(&args, 1, 1.0)? as f32;
3648                let amp = self.arg_num(&args, 2, 1.0)? as f32;
3649                let phase = self.arg_num(&args, 3, 0.0)? as f32;
3650                return Ok(Value::Number(ling_animation::scalar::wobble(t, freq, amp, phase) as f64));
3651            }
3652            "gait_phase" | "步相" | "歩相" | "걸음위상" | "เฟสก้าว" => {
3653                let t = self.arg_num(&args, 0, 0.0)? as f32;
3654                let speed = self.arg_num(&args, 1, 1.0)? as f32;
3655                return Ok(Value::Number(ling_animation::scalar::gait_phase(t, speed) as f64));
3656            }
3657            "gait_swing" | "步摆" | "歩振り" | "걸음흔들" | "ก้าวแกว่ง" => {
3658                let t = self.arg_num(&args, 0, 0.0)? as f32;
3659                let speed = self.arg_num(&args, 1, 1.0)? as f32;
3660                let stride = self.arg_num(&args, 2, 1.0)? as f32;
3661                return Ok(Value::Number(ling_animation::scalar::gait_swing(t, speed, stride) as f64));
3662            }
3663            "gait_lift" | "抬脚" | "足上げ" | "발들기" | "ยกเท้า" => {
3664                let t = self.arg_num(&args, 0, 0.0)? as f32;
3665                let speed = self.arg_num(&args, 1, 1.0)? as f32;
3666                let height = self.arg_num(&args, 2, 1.0)? as f32;
3667                return Ok(Value::Number(ling_animation::scalar::gait_lift(t, speed, height) as f64));
3668            }
3669            "spring_to" | "弹向" | "バネ寄せ" | "스프링이동" | "สปริงไป" => {
3670                let pos = self.arg_num(&args, 0, 0.0)? as f32;
3671                let vel = self.arg_num(&args, 1, 0.0)? as f32;
3672                let target = self.arg_num(&args, 2, 0.0)? as f32;
3673                let stiffness = self.arg_num(&args, 3, 120.0)? as f32;
3674                let damping = self.arg_num(&args, 4, 14.0)? as f32;
3675                let dt = self.arg_num(&args, 5, 1.0 / 60.0)? as f32;
3676                let (np, nv) = ling_animation::scalar::spring_step(pos, vel, target, stiffness, damping, dt);
3677                return Ok(Value::List(vec![Value::Number(np as f64), Value::Number(nv as f64)]));
3678            }
3679            "ik2" | "反解" | "逆運動" | "역운동" | "ไอเค2" => {
3680                let l1 = self.arg_num(&args, 0, 1.0)? as f32;
3681                let l2 = self.arg_num(&args, 1, 1.0)? as f32;
3682                let tx = self.arg_num(&args, 2, 0.0)? as f32;
3683                let ty = self.arg_num(&args, 3, 0.0)? as f32;
3684                let (sh, el) = ling_animation::scalar::two_bone_ik(l1, l2, tx, ty);
3685                return Ok(Value::List(vec![Value::Number(sh as f64), Value::Number(el as f64)]));
3686            }
3687            // ── Mechanical 机 ──
3688            "gear_couple" | "齿轮联动" | "歯車連動" | "기어연동" | "เฟืองทด" => {
3689                let angle = self.arg_num(&args, 0, 0.0)? as f32;
3690                let ti = self.arg_num(&args, 1, 1.0)? as f32;
3691                let to = self.arg_num(&args, 2, 1.0)? as f32;
3692                return Ok(Value::Number(ling_animation::scalar::gear(angle, ti, to) as f64));
3693            }
3694            "gear_train" | "齿轮组" | "歯車列" | "기어열" | "ชุดเฟือง" => {
3695                let angle = self.arg_num(&args, 0, 0.0)? as f32;
3696                let teeth: Vec<f32> = match args.get(1) {
3697                    Some(Value::List(items)) => items.iter()
3698                        .filter_map(|v| if let Value::Number(n) = v { Some(*n as f32) } else { None }).collect(),
3699                    _ => Vec::new(),
3700                };
3701                let out = ling_animation::mechanism::gear_train(angle, &teeth);
3702                return Ok(Value::List(out.into_iter().map(|a| Value::Number(a as f64)).collect()));
3703            }
3704            "cam_lift" | "凸轮升程" | "カム揚程" | "캠리프트" | "ยกลูกเบี้ยว" => {
3705                let angle = self.arg_num(&args, 0, 0.0)? as f32;
3706                let lift = self.arg_num(&args, 1, 1.0)? as f32;
3707                return Ok(Value::Number(ling_animation::scalar::cam_lift(angle, lift) as f64));
3708            }
3709            "piston" | "活塞" | "ピストン" | "피스톤" | "ลูกสูบ" => {
3710                let angle = self.arg_num(&args, 0, 0.0)? as f32;
3711                let crank = self.arg_num(&args, 1, 1.0)? as f32;
3712                let rod = self.arg_num(&args, 2, 2.0)? as f32;
3713                return Ok(Value::Number(ling_animation::scalar::piston(angle, crank, rod) as f64));
3714            }
3715            "rack" | "齿条" | "ラック" | "랙" | "แร็ค" => {
3716                let angle = self.arg_num(&args, 0, 0.0)? as f32;
3717                let radius = self.arg_num(&args, 1, 1.0)? as f32;
3718                return Ok(Value::Number(ling_animation::scalar::rack(angle, radius) as f64));
3719            }
3720            #[cfg(not(target_arch = "wasm32"))]
3721            "mouse_x" => {
3722                let gfx = self.gfx.borrow();
3723                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);
3724                return Ok(Value::Number(v));
3725            }
3726            #[cfg(not(target_arch = "wasm32"))]
3727            "mouse_y" => {
3728                let gfx = self.gfx.borrow();
3729                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);
3730                return Ok(Value::Number(v));
3731            }
3732            #[cfg(not(target_arch = "wasm32"))]
3733            "mouse_down" => {
3734                let gfx = self.gfx.borrow();
3735                let d = gfx.window.as_ref().map(|w| w.get_mouse_down(minifb::MouseButton::Left)).unwrap_or(false);
3736                return Ok(Value::Bool(d));
3737            }
3738            "mouse_down_right" | "เมาส์ขวา" => {
3739                let gfx = self.gfx.borrow();
3740                let d = gfx.window.as_ref().map(|w| w.get_mouse_down(minifb::MouseButton::Right)).unwrap_or(false);
3741                return Ok(Value::Bool(d));
3742            }
3743            "mouse_down_middle" | "เมาส์กลาง" => {
3744                let gfx = self.gfx.borrow();
3745                let d = gfx.window.as_ref().map(|w| w.get_mouse_down(minifb::MouseButton::Middle)).unwrap_or(false);
3746                return Ok(Value::Bool(d));
3747            }
3748            #[cfg(not(target_arch = "wasm32"))]
3749            "ui_hot" | "热区" | "ホットエリア" | "핫존" | "พื้นที่สัมผัส" => {
3750                let x = self.arg_num(&args,0,0.0)? as f32;
3751                let y = self.arg_num(&args,1,0.0)? as f32;
3752                let w = self.arg_num(&args,2,0.0)? as f32;
3753                let h = self.arg_num(&args,3,0.0)? as f32;
3754                let gfx = self.gfx.borrow();
3755                let (mx,my) = gfx.window.as_ref().and_then(|win| win.get_mouse_pos(minifb::MouseMode::Clamp)).unwrap_or((0.0,0.0));
3756                return Ok(Value::Bool(ling_ui::holo::hit_rect(mx,my,x,y,w,h)));
3757            }
3758            // ui_text(x, y, scale, "string") — holographic vector text
3759            "ui_text" | "界面文字" | "UI文字" | "UI텍스트" | "ข้อความหน้าจอ" => {
3760                let x = self.arg_num(&args,0,0.0)? as f32;
3761                let y = self.arg_num(&args,1,0.0)? as f32;
3762                let scale = self.arg_num(&args,2,16.0)? as f32;
3763                let s = self.arg_str(&args,3,"");
3764                let segs = ling_ui::holo::text_lines(&s, x, y, scale*0.62, scale, scale*0.24);
3765                let mut gfx = self.gfx.borrow_mut();
3766                let (w,h,color) = (gfx.width, gfx.height, gfx.color);
3767                for sg in segs { draw_line(&mut gfx.buffer, w, h, color, sg[0], sg[1], sg[2], sg[3]); }
3768                return Ok(Value::Unit);
3769            }
3770            // font_load("path.ttf") — load a vector font (outlines cached lazily as
3771            // cache/fonts/<stem>/<codepoint>.ling). Returns a handle, or -1 on failure.
3772            #[cfg(not(target_arch = "wasm32"))]
3773            "font_load" | "โหลดฟอนต์" | "加载字体" | "フォント読込" | "글꼴로드" => {
3774                let path = self.arg_str(&args, 0, "");
3775                // Optional 2nd arg: variable-font weight (e.g. 600 for a solid, bold UI).
3776                let weight = match self.arg_num(&args, 1, 0.0)? {
3777                    w if w > 0.0 => Some(w as f32),
3778                    _ => None,
3779                };
3780                // Try the path as given, then relative to the script's directory.
3781                let mut loaded = ling_graphics::VectorFont::from_path_weight(&path, weight);
3782                if loaded.is_err() {
3783                    if let Some(dir) = &self.source_dir {
3784                        let joined = dir.join(&path);
3785                        loaded = ling_graphics::VectorFont::from_path_weight(&joined.to_string_lossy(), weight);
3786                    }
3787                }
3788                match loaded {
3789                    Ok(f) => {
3790                        let id = self.fonts.len();
3791                        self.fonts.push(f);
3792                        return Ok(Value::Number(id as f64));
3793                    }
3794                    Err(e) => {
3795                        eprintln!("font_load failed ({path}): {e}");
3796                        return Ok(Value::Number(-1.0));
3797                    }
3798                }
3799            }
3800            // font_text(handle, x, y, px, "string") — anti-aliased *stroked* vector outline
3801            // in the current set_color / set_blend. (x,y) is the text box top-left.
3802            #[cfg(not(target_arch = "wasm32"))]
3803            "font_text" | "ข้อความฟอนต์" | "字体文本" | "フォント文字" | "글꼴텍스트" => {
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                    let strokes = self.font_layout_2d(id as usize, x, y, px, &s);
3811                    let mut gfx = self.gfx.borrow_mut();
3812                    let (w, h, color, add) = (gfx.width, gfx.height, gfx.color, gfx.blend == 1);
3813                    for pl in &strokes {
3814                        for seg in pl.windows(2) {
3815                            crate::gfx::raster::draw_line_aa(&mut gfx.buffer, w, h, color, add,
3816                                seg[0][0], seg[0][1], seg[1][0], seg[1][1]);
3817                        }
3818                    }
3819                }
3820                return Ok(Value::Unit);
3821            }
3822            // font_text_fill(handle, x, y, px, "string") — anti-aliased *filled* vector glyphs.
3823            #[cfg(not(target_arch = "wasm32"))]
3824            "font_text_fill" | "เติมฟอนต์" | "填充字体" | "フォント塗り" | "글꼴채움" => {
3825                let id = self.arg_num(&args, 0, 0.0)? as i64;
3826                let x  = self.arg_num(&args, 1, 0.0)? as f32;
3827                let y  = self.arg_num(&args, 2, 0.0)? as f32;
3828                let px = self.arg_num(&args, 3, 16.0)? as f32;
3829                let s  = self.arg_str(&args, 4, "");
3830                if id >= 0 && (id as usize) < self.fonts.len() && px > 0.0 {
3831                    // fill each glyph independently so interior holes (winding) stay correct
3832                    let glyphs = self.font_layout_2d_glyphs(id as usize, x, y, px, &s);
3833                    let mut gfx = self.gfx.borrow_mut();
3834                    let (w, h, color, add) = (gfx.width, gfx.height, gfx.color, gfx.blend == 1);
3835                    for contours in &glyphs {
3836                        crate::gfx::raster::fill_contours_aa(&mut gfx.buffer, w, h, color, add, contours);
3837                    }
3838                }
3839                return Ok(Value::Unit);
3840            }
3841            // font_text_3d(handle, cx,cy,cz, ux,uy,uz, vx,vy,vz, size, "string")
3842            // — stroked vector text on a 3D plane: u = advance dir, v = up dir, size = world/em.
3843            //   Flows through the depth-sorted line pipeline, so it rotates with the camera (and 4D).
3844            #[cfg(not(target_arch = "wasm32"))]
3845            "font_text_3d" | "ข้อความฟอนต์3มิติ" | "字体3D" | "フォント3D" | "글꼴3D" => {
3846                let id = self.arg_num(&args, 0, 0.0)? as i64;
3847                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;
3848                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;
3849                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;
3850                let size=self.arg_num(&args,10,1.0)? as f32;
3851                let s = self.arg_str(&args,11,"");
3852                if id >= 0 && (id as usize) < self.fonts.len() && size > 0.0 {
3853                    // Build world-space polylines: world = C + (pen+ex)*size*U + ey*size*V
3854                    let font = &mut self.fonts[id as usize];
3855                    let asc = font.ascent();
3856                    let mut pen = 0.0f32;
3857                    let mut lines: Vec<[f32; 6]> = Vec::new();
3858                    for ch in s.chars() {
3859                        let go = font.glyph_outline(ch, 0.01);
3860                        for pl in &go.polylines {
3861                            for seg in pl.windows(2) {
3862                                let map = |p: [f32; 2]| {
3863                                    let a = pen + p[0];
3864                                    let b = p[1] - asc; // shift so the top of the cap sits near C
3865                                    [cx + a*size*ux + b*size*vx,
3866                                     cy + a*size*uy + b*size*vy,
3867                                     cz + a*size*uz + b*size*vz]
3868                                };
3869                                let p0 = map(seg[0]); let p1 = map(seg[1]);
3870                                lines.push([p0[0],p0[1],p0[2], p1[0],p1[1],p1[2]]);
3871                            }
3872                        }
3873                        pen += go.advance;
3874                    }
3875                    let mut gfx = self.gfx.borrow_mut();
3876                    let color = gfx.color;
3877                    let near = -gfx.camera.zdist + 0.05;
3878                    for l in &lines {
3879                        let (mut ax, mut ay, mut az) = (l[0], l[1], l[2]);
3880                        let (mut bx, mut by, mut bz) = (l[3], l[4], l[5]);
3881                        let da = gfx.camera.depth(ax, ay, az);
3882                        let db = gfx.camera.depth(bx, by, bz);
3883                        if da <= near && db <= near { continue; }
3884                        if da <= near {
3885                            let t = (near - da) / (db - da);
3886                            ax += t*(bx-ax); ay += t*(by-ay); az += t*(bz-az);
3887                        } else if db <= near {
3888                            let t = (near - da) / (db - da);
3889                            bx = ax + t*(bx-ax); by = ay + t*(by-ay); bz = az + t*(bz-az);
3890                        }
3891                        let (sax, say, da2) = gfx.camera.project(ax, ay, az);
3892                        let (sbx, sby, db2) = gfx.camera.project(bx, by, bz);
3893                        let depth = (da2 + db2) / 2.0;
3894                        gfx.depth_queue.push_line(depth, color, sax, say, sbx, sby);
3895                    }
3896                }
3897                return Ok(Value::Unit);
3898            }
3899            // font_width(handle, px, "string") — pixel width of a string in a loaded font.
3900            #[cfg(not(target_arch = "wasm32"))]
3901            "font_width" | "ความกว้างฟอนต์" | "字体宽度" | "フォント幅" | "글꼴너비" => {
3902                let id = self.arg_num(&args, 0, 0.0)? as i64;
3903                let px = self.arg_num(&args, 1, 16.0)? as f32;
3904                let s  = self.arg_str(&args, 2, "");
3905                if id >= 0 && (id as usize) < self.fonts.len() {
3906                    return Ok(Value::Number(self.fonts[id as usize].measure(&s, px) as f64));
3907                }
3908                return Ok(Value::Number(0.0));
3909            }
3910            // ui_frame(x,y,w,h, bracketLen) — sci-fi corner brackets
3911            "ui_frame" | "边框" | "フレーム枠" | "프레임틀" | "กรอบ" => {
3912                let x=self.arg_num(&args,0,0.0)? as f32; let y=self.arg_num(&args,1,0.0)? as f32;
3913                let w0=self.arg_num(&args,2,0.0)? as f32; let h0=self.arg_num(&args,3,0.0)? as f32;
3914                let l=self.arg_num(&args,4,14.0)? as f32;
3915                let segs = ling_ui::holo::corner_brackets(x,y,w0,h0,l);
3916                let mut gfx = self.gfx.borrow_mut();
3917                let (w,h,color)=(gfx.width,gfx.height,gfx.color);
3918                for sg in segs { draw_line(&mut gfx.buffer, w,h,color, sg[0],sg[1],sg[2],sg[3]); }
3919                return Ok(Value::Unit);
3920            }
3921            // ui_bevel(x,y,w,h, bevel) — beveled holographic panel outline
3922            "ui_bevel" | "斜角框" | "ベベル枠" | "베벨틀" | "กรอบเฉียง" => {
3923                let x=self.arg_num(&args,0,0.0)? as f32; let y=self.arg_num(&args,1,0.0)? as f32;
3924                let w0=self.arg_num(&args,2,0.0)? as f32; let h0=self.arg_num(&args,3,0.0)? as f32;
3925                let bv=self.arg_num(&args,4,10.0)? as f32;
3926                let segs = ling_ui::holo::beveled_rect(x,y,w0,h0,bv);
3927                let mut gfx = self.gfx.borrow_mut();
3928                let (w,h,color)=(gfx.width,gfx.height,gfx.color);
3929                for sg in segs { draw_line(&mut gfx.buffer, w,h,color, sg[0],sg[1],sg[2],sg[3]); }
3930                return Ok(Value::Unit);
3931            }
3932
3933            // ══════════════════════════════════════════════════════════════════
3934            // VECTOR UI TOOLKIT  (crates/ling-ui/src/widgets.rs)
3935            // All widgets are vector + theme-coloured with an optional trailing
3936            // r,g,b override; interactive ones read the mouse and return state.
3937            // ══════════════════════════════════════════════════════════════════
3938            #[cfg(not(target_arch = "wasm32"))]
3939            "ui_theme" | "界面主题" | "UIテーマ" | "인터페이스테마" | "ธีมส่วนติดต่อ" => {
3940                let cur = self.ui_theme;
3941                let primary = self.color_at(&args, 0,  cur.primary);
3942                let accent  = self.color_at(&args, 3,  cur.accent);
3943                let track   = self.color_at(&args, 6,  cur.track);
3944                let warn    = self.color_at(&args, 9,  cur.warn);
3945                let text    = self.color_at(&args, 12, cur.text);
3946                let bg      = self.color_at(&args, 15, cur.bg);
3947                self.ui_theme = UiTheme { primary, accent, track, warn, text, bg };
3948                return Ok(Value::Unit);
3949            }
3950
3951            // ── HUD ──────────────────────────────────────────────────────────
3952            #[cfg(not(target_arch = "wasm32"))]
3953            "ui_radar" | "雷达" | "レーダー" | "레이더" | "เรดาร์" => {
3954                let cx=self.arg_num(&args,0,0.)? as f32; let cy=self.arg_num(&args,1,0.)? as f32;
3955                let r=self.arg_num(&args,2,60.)? as f32; let sweep=self.arg_num(&args,3,0.)? as f32;
3956                let th=self.ui_theme;
3957                let prim=self.color_at(&args,4,th.primary);
3958                self.draw_ui(&ling_ui::widgets::radar(cx,cy,r,sweep, prim, th.accent, th.track));
3959                return Ok(Value::Unit);
3960            }
3961            #[cfg(not(target_arch = "wasm32"))]
3962            "ui_compass" | "罗盘" | "コンパス" | "나침반" | "เข็มทิศ" => {
3963                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
3964                let w0=self.arg_num(&args,2,300.)? as f32; let h0=self.arg_num(&args,3,24.)? as f32;
3965                let head=self.arg_num(&args,4,0.)? as f32;
3966                let th=self.ui_theme; let prim=self.color_at(&args,5,th.primary);
3967                self.draw_ui(&ling_ui::widgets::compass(x,y,w0,h0,head, prim, th.track));
3968                return Ok(Value::Unit);
3969            }
3970            #[cfg(not(target_arch = "wasm32"))]
3971            "ui_reticle" | "准星" | "照準" | "조준선" | "เป้าเล็ง" => {
3972                let cx=self.arg_num(&args,0,0.)? as f32; let cy=self.arg_num(&args,1,0.)? as f32;
3973                let r=self.arg_num(&args,2,30.)? as f32; let spread=self.arg_num(&args,3,0.)? as f32;
3974                let th=self.ui_theme; let prim=self.color_at(&args,4,th.primary);
3975                self.draw_ui(&ling_ui::widgets::reticle(cx,cy,r,spread, prim));
3976                return Ok(Value::Unit);
3977            }
3978            #[cfg(not(target_arch = "wasm32"))]
3979            "ui_target" | "锁定框" | "ターゲット" | "표적" | "กรอบเป้า" => {
3980                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
3981                let w0=self.arg_num(&args,2,80.)? as f32; let h0=self.arg_num(&args,3,80.)? as f32;
3982                let lock=self.arg_num(&args,4,0.)? as f32;
3983                let th=self.ui_theme; let prim=self.color_at(&args,5,th.primary);
3984                self.draw_ui(&ling_ui::widgets::target(x,y,w0,h0,lock, prim, th.accent));
3985                return Ok(Value::Unit);
3986            }
3987            #[cfg(not(target_arch = "wasm32"))]
3988            "ui_panel" | "面板" | "パネル" | "패널" | "แผง" => {
3989                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
3990                let w0=self.arg_num(&args,2,200.)? as f32; let h0=self.arg_num(&args,3,120.)? as f32;
3991                let bv=self.arg_num(&args,4,12.)? as f32;
3992                let th=self.ui_theme; let prim=self.color_at(&args,5,th.primary);
3993                self.draw_ui(&ling_ui::widgets::panel(x,y,w0,h0,bv, prim, th.bg));
3994                return Ok(Value::Unit);
3995            }
3996            #[cfg(not(target_arch = "wasm32"))]
3997            "ui_scanlines" | "扫描线" | "走査線" | "스캔라인" | "เส้นสแกน" => {
3998                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
3999                let w0=self.arg_num(&args,2,200.)? as f32; let h0=self.arg_num(&args,3,120.)? as f32;
4000                let dens=self.arg_num(&args,4,24.)? as usize;
4001                let th=self.ui_theme; let line=self.color_at(&args,5,th.track);
4002                self.draw_ui(&ling_ui::widgets::scanlines(x,y,w0,h0,dens, line));
4003                return Ok(Value::Unit);
4004            }
4005
4006            // ── Meters ───────────────────────────────────────────────────────
4007            #[cfg(not(target_arch = "wasm32"))]
4008            "ui_bar" | "进度条" | "バー" | "막대" | "แถบ" => {
4009                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
4010                let w0=self.arg_num(&args,2,160.)? as f32; let h0=self.arg_num(&args,3,16.)? as f32;
4011                let val=self.arg_num(&args,4,0.)? as f32; let max=self.arg_num(&args,5,1.)? as f32;
4012                let th=self.ui_theme; let fill=self.color_at(&args,6,th.primary);
4013                self.draw_ui(&ling_ui::widgets::bar(x,y,w0,h0, val/max.max(1e-6), fill, th.track));
4014                return Ok(Value::Unit);
4015            }
4016            #[cfg(not(target_arch = "wasm32"))]
4017            "ui_segbar" | "分段条" | "分割バー" | "분할막대" | "แถบแบ่ง" => {
4018                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
4019                let w0=self.arg_num(&args,2,160.)? as f32; let h0=self.arg_num(&args,3,16.)? as f32;
4020                let val=self.arg_num(&args,4,0.)? as f32; let max=self.arg_num(&args,5,1.)? as f32;
4021                let segs=self.arg_num(&args,6,10.)? as usize;
4022                let th=self.ui_theme; let fill=self.color_at(&args,7,th.primary);
4023                self.draw_ui(&ling_ui::widgets::segbar(x,y,w0,h0, val/max.max(1e-6), segs, fill, th.track));
4024                return Ok(Value::Unit);
4025            }
4026            #[cfg(not(target_arch = "wasm32"))]
4027            "ui_gauge" | "仪表" | "ゲージ" | "게이지" | "มาตรวัด" => {
4028                let cx=self.arg_num(&args,0,0.)? as f32; let cy=self.arg_num(&args,1,0.)? as f32;
4029                let r=self.arg_num(&args,2,50.)? as f32;
4030                let val=self.arg_num(&args,3,0.)? as f32; let max=self.arg_num(&args,4,1.)? as f32;
4031                let th=self.ui_theme; let needle=self.color_at(&args,5,th.warn);
4032                self.draw_ui(&ling_ui::widgets::gauge(cx,cy,r, val/max.max(1e-6), needle, th.accent, th.track));
4033                return Ok(Value::Unit);
4034            }
4035            #[cfg(not(target_arch = "wasm32"))]
4036            "ui_ring" | "环表" | "リングメーター" | "링미터" | "วงแหวนวัด" => {
4037                let cx=self.arg_num(&args,0,0.)? as f32; let cy=self.arg_num(&args,1,0.)? as f32;
4038                let r=self.arg_num(&args,2,40.)? as f32;
4039                let val=self.arg_num(&args,3,0.)? as f32; let max=self.arg_num(&args,4,1.)? as f32;
4040                let th=self.ui_theme; let fill=self.color_at(&args,5,th.primary);
4041                self.draw_ui(&ling_ui::widgets::ring(cx,cy,r, val/max.max(1e-6), fill, th.track));
4042                return Ok(Value::Unit);
4043            }
4044            #[cfg(not(target_arch = "wasm32"))]
4045            "ui_vu" | "音量条" | "VUメーター" | "음량막대" | "มาตรเสียง" => {
4046                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
4047                let w0=self.arg_num(&args,2,160.)? as f32; let h0=self.arg_num(&args,3,60.)? as f32;
4048                let levels=self.arg_list_f32(&args,4);
4049                let th=self.ui_theme; let fill=self.color_at(&args,5,th.primary);
4050                self.draw_ui(&ling_ui::widgets::vu(x,y,w0,h0, &levels, fill, th.warn));
4051                return Ok(Value::Unit);
4052            }
4053            #[cfg(not(target_arch = "wasm32"))]
4054            "ui_spark" | "迷你图" | "スパークライン" | "스파크라인" | "กราฟจิ๋ว" => {
4055                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
4056                let w0=self.arg_num(&args,2,160.)? as f32; let h0=self.arg_num(&args,3,40.)? as f32;
4057                let vals=self.arg_list_f32(&args,4);
4058                let th=self.ui_theme; let line=self.color_at(&args,5,th.accent);
4059                self.draw_ui(&ling_ui::widgets::spark(x,y,w0,h0, &vals, line));
4060                return Ok(Value::Unit);
4061            }
4062            #[cfg(not(target_arch = "wasm32"))]
4063            "ui_battery" | "电池" | "バッテリー" | "배터리" | "แบตเตอรี่" => {
4064                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
4065                let w0=self.arg_num(&args,2,50.)? as f32; let h0=self.arg_num(&args,3,22.)? as f32;
4066                let val=self.arg_num(&args,4,1.)? as f32; let max=self.arg_num(&args,5,1.)? as f32;
4067                let th=self.ui_theme; let fill=self.color_at(&args,6,th.accent);
4068                self.draw_ui(&ling_ui::widgets::battery(x,y,w0,h0, val/max.max(1e-6), fill, th.track, th.warn));
4069                return Ok(Value::Unit);
4070            }
4071
4072            // ── Interface controls (interactive → return state) ──────────────
4073            #[cfg(not(target_arch = "wasm32"))]
4074            "ui_button" | "按钮" | "ボタン" | "버튼" | "ปุ่ม" => {
4075                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
4076                let w0=self.arg_num(&args,2,120.)? as f32; let h0=self.arg_num(&args,3,40.)? as f32;
4077                let (mx,my,down)=self.mouse_now();
4078                let hover=ling_ui::holo::hit_rect(mx,my,x,y,w0,h0);
4079                let clicked = hover && down && !self.mouse_was_down;
4080                let th=self.ui_theme; let prim=self.color_at(&args,4,th.primary);
4081                self.draw_ui(&ling_ui::widgets::button(x,y,w0,h0, hover, down&&hover, prim, th.bg));
4082                return Ok(Value::Number(if clicked {1.0} else {0.0}));
4083            }
4084            #[cfg(not(target_arch = "wasm32"))]
4085            "ui_toggle" | "开关" | "トグル" | "토글" | "สวิตช์" => {
4086                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
4087                let w0=self.arg_num(&args,2,52.)? as f32; let h0=self.arg_num(&args,3,24.)? as f32;
4088                let mut state=self.arg_num(&args,4,0.)? > 0.5;
4089                let (mx,my,down)=self.mouse_now();
4090                let hover=ling_ui::holo::hit_rect(mx,my,x,y,w0,h0);
4091                if hover && down && !self.mouse_was_down { state = !state; }
4092                let th=self.ui_theme; let on=self.color_at(&args,5,th.accent);
4093                self.draw_ui(&ling_ui::widgets::toggle(x,y,w0,h0, state, on, th.track));
4094                return Ok(Value::Number(if state {1.0} else {0.0}));
4095            }
4096            #[cfg(not(target_arch = "wasm32"))]
4097            "ui_slider" | "滑块" | "スライダー" | "슬라이더" | "แถบเลื่อน" => {
4098                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
4099                let w0=self.arg_num(&args,2,160.)? as f32;
4100                let mut val=self.arg_num(&args,3,0.)? as f32;
4101                let mn=self.arg_num(&args,4,0.)? as f32; let mx_=self.arg_num(&args,5,1.)? as f32;
4102                let (mx,my,down)=self.mouse_now();
4103                let hover=ling_ui::holo::hit_rect(mx,my,x-8.0,y-10.0,w0+16.0,20.0);
4104                if hover && down {
4105                    let frac=((mx-x)/w0).max(0.0).min(1.0);
4106                    val = mn + (mx_-mn)*frac;
4107                }
4108                let frac=((val-mn)/(mx_-mn).abs().max(1e-6)).max(0.0).min(1.0);
4109                let th=self.ui_theme; let fill=self.color_at(&args,6,th.primary);
4110                self.draw_ui(&ling_ui::widgets::slider(x,y,w0, frac, hover, fill, th.track));
4111                return Ok(Value::Number(val as f64));
4112            }
4113            #[cfg(not(target_arch = "wasm32"))]
4114            "ui_checkbox" | "复选框" | "チェックボックス" | "체크박스" | "ช่องเลือก" => {
4115                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
4116                let s=self.arg_num(&args,2,20.)? as f32;
4117                let mut checked=self.arg_num(&args,3,0.)? > 0.5;
4118                let (mx,my,down)=self.mouse_now();
4119                let hover=ling_ui::holo::hit_rect(mx,my,x,y,s,s);
4120                if hover && down && !self.mouse_was_down { checked = !checked; }
4121                let th=self.ui_theme; let prim=self.color_at(&args,4,th.primary);
4122                self.draw_ui(&ling_ui::widgets::checkbox(x,y,s, checked, hover, prim, th.track));
4123                return Ok(Value::Number(if checked {1.0} else {0.0}));
4124            }
4125            #[cfg(not(target_arch = "wasm32"))]
4126            "ui_tabs" | "标签页" | "タブ" | "탭" | "แท็บ" => {
4127                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
4128                let w0=self.arg_num(&args,2,240.)? as f32; let h0=self.arg_num(&args,3,28.)? as f32;
4129                let count=self.arg_num(&args,4,3.)? as usize;
4130                let mut active=self.arg_num(&args,5,0.)? as i32;
4131                let (mx,my,down)=self.mouse_now();
4132                let mut hover=-1;
4133                if my>=y && my<=y+h0 && mx>=x && mx<=x+w0 && count>0 {
4134                    hover = (((mx-x)/(w0/count as f32)) as i32).max(0).min(count as i32-1);
4135                    if down && !self.mouse_was_down { active = hover; }
4136                }
4137                let th=self.ui_theme; let prim=self.color_at(&args,6,th.primary);
4138                self.draw_ui(&ling_ui::widgets::tabs(x,y,w0,h0, count, active as usize, hover, prim, th.track));
4139                return Ok(Value::Number(active as f64));
4140            }
4141            #[cfg(not(target_arch = "wasm32"))]
4142            "ui_progress" | "进度" | "プログレス" | "진행바" | "ความคืบหน้า" => {
4143                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
4144                let w0=self.arg_num(&args,2,200.)? as f32; let h0=self.arg_num(&args,3,12.)? as f32;
4145                let frac=self.arg_num(&args,4,0.)? as f32;
4146                let th=self.ui_theme; let fill=self.color_at(&args,5,th.accent);
4147                self.draw_ui(&ling_ui::widgets::progress(x,y,w0,h0, frac, fill, th.track));
4148                return Ok(Value::Unit);
4149            }
4150            #[cfg(not(target_arch = "wasm32"))]
4151            "ui_tooltip" | "提示框" | "ツールチップ" | "툴팁" | "คำแนะนำ" => {
4152                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
4153                let w0=self.arg_num(&args,2,120.)? as f32; let h0=self.arg_num(&args,3,28.)? as f32;
4154                let th=self.ui_theme; let prim=self.color_at(&args,4,th.primary);
4155                self.draw_ui(&ling_ui::widgets::tooltip(x,y,w0,h0, prim, th.bg));
4156                return Ok(Value::Unit);
4157            }
4158            #[cfg(not(target_arch = "wasm32"))]
4159            "ui_stepper" | "步进器" | "ステッパー" | "스테퍼" | "ตัวปรับค่า" => {
4160                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
4161                let w0=self.arg_num(&args,2,120.)? as f32; let h0=self.arg_num(&args,3,28.)? as f32;
4162                let mut val=self.arg_num(&args,4,0.)? as f32; let step=self.arg_num(&args,5,1.)? as f32;
4163                let (mx,my,down)=self.mouse_now();
4164                let hm=ling_ui::holo::hit_rect(mx,my,x,y,h0,h0);
4165                let hp=ling_ui::holo::hit_rect(mx,my,x+w0-h0,y,h0,h0);
4166                if down && !self.mouse_was_down { if hm { val -= step; } if hp { val += step; } }
4167                let th=self.ui_theme; let prim=self.color_at(&args,6,th.primary);
4168                self.draw_ui(&ling_ui::widgets::stepper(x,y,w0,h0, hm, hp, prim, th.track));
4169                return Ok(Value::Number(val as f64));
4170            }
4171
4172            // ── Game UI ──────────────────────────────────────────────────────
4173            #[cfg(not(target_arch = "wasm32"))]
4174            "ui_healthbar" | "血条" | "体力バー" | "체력바" | "แถบพลังชีวิต" => {
4175                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
4176                let w0=self.arg_num(&args,2,180.)? as f32; let h0=self.arg_num(&args,3,16.)? as f32;
4177                let val=self.arg_num(&args,4,1.)? as f32; let max=self.arg_num(&args,5,1.)? as f32;
4178                let pulse=self.arg_num(&args,6,0.)? as f32;
4179                let th=self.ui_theme; let full=self.color_at(&args,7,th.accent);
4180                self.draw_ui(&ling_ui::widgets::healthbar(x,y,w0,h0, val/max.max(1e-6), pulse, full, th.warn, th.track));
4181                return Ok(Value::Unit);
4182            }
4183            #[cfg(not(target_arch = "wasm32"))]
4184            "ui_cooldown" | "冷却" | "クールダウン" | "쿨다운" | "คูลดาวน์" => {
4185                let cx=self.arg_num(&args,0,0.)? as f32; let cy=self.arg_num(&args,1,0.)? as f32;
4186                let r=self.arg_num(&args,2,28.)? as f32; let frac=self.arg_num(&args,3,0.)? as f32;
4187                let th=self.ui_theme; let fill=self.color_at(&args,4,th.primary);
4188                self.draw_ui(&ling_ui::widgets::cooldown(cx,cy,r, frac, fill, th.track));
4189                return Ok(Value::Unit);
4190            }
4191            #[cfg(not(target_arch = "wasm32"))]
4192            "ui_counter" | "计数器" | "カウンター" | "카운터" | "ตัวนับ" => {
4193                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
4194                let dw=self.arg_num(&args,2,14.)? as f32; let dh=self.arg_num(&args,3,24.)? as f32;
4195                let val=self.arg_num(&args,4,0.)? as i64; let digits=self.arg_num(&args,5,4.)? as usize;
4196                let th=self.ui_theme; let on=self.color_at(&args,6,th.primary);
4197                let off=ling_ui::widgets::shade(th.track,0.5);
4198                self.draw_ui(&ling_ui::widgets::counter(x,y,dw,dh, val, digits, on, off));
4199                return Ok(Value::Unit);
4200            }
4201            #[cfg(not(target_arch = "wasm32"))]
4202            "ui_minimap" | "小地图" | "ミニマップ" | "미니맵" | "แผนที่ย่อ" => {
4203                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
4204                let w0=self.arg_num(&args,2,140.)? as f32; let h0=self.arg_num(&args,3,140.)? as f32;
4205                let th=self.ui_theme; let prim=self.color_at(&args,4,th.primary);
4206                self.draw_ui(&ling_ui::widgets::minimap(x,y,w0,h0, prim, th.bg));
4207                return Ok(Value::Unit);
4208            }
4209            #[cfg(not(target_arch = "wasm32"))]
4210            "ui_dpad" | "方向键" | "方向パッド" | "방향패드" | "ปุ่มทิศทาง" => {
4211                let cx=self.arg_num(&args,0,0.)? as f32; let cy=self.arg_num(&args,1,0.)? as f32;
4212                let r=self.arg_num(&args,2,50.)? as f32;
4213                let (mx,my,down)=self.mouse_now();
4214                let mut dir=0;
4215                if down {
4216                    let (dx,dy)=(mx-cx, my-cy);
4217                    if dx*dx+dy*dy <= r*r {
4218                        if dx.abs() > dy.abs() { dir = if dx>0.0 {2} else {4}; }
4219                        else { dir = if dy>0.0 {3} else {1}; }
4220                    }
4221                }
4222                let th=self.ui_theme; let prim=self.color_at(&args,3,th.primary);
4223                self.draw_ui(&ling_ui::widgets::dpad(cx,cy,r, dir, prim, th.track));
4224                return Ok(Value::Number(dir as f64));
4225            }
4226            #[cfg(not(target_arch = "wasm32"))]
4227            "ui_slotgrid" | "物品格" | "スロットグリッド" | "슬롯격자" | "ช่องไอเทม" => {
4228                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
4229                let cols=self.arg_num(&args,2,4.)? as usize; let rows=self.arg_num(&args,3,1.)? as usize;
4230                let cell=self.arg_num(&args,4,36.)? as f32; let sel=self.arg_num(&args,5,-1.)? as i32;
4231                let th=self.ui_theme; let prim=self.color_at(&args,6,th.primary);
4232                self.draw_ui(&ling_ui::widgets::slotgrid(x,y,cols,rows,cell, sel, prim, th.track));
4233                return Ok(Value::Unit);
4234            }
4235            #[cfg(not(target_arch = "wasm32"))]
4236            "ui_vignette" | "暗角" | "ビネット" | "비네트" | "ขอบมืด" => {
4237                let intensity=self.arg_num(&args,0,0.5)? as f32;
4238                let (w,h)={ let g=self.gfx.borrow(); (g.width as f32, g.height as f32) };
4239                let th=self.ui_theme; let col=self.color_at(&args,1,th.warn);
4240                self.draw_ui(&ling_ui::widgets::vignette(w,h, intensity, col));
4241                return Ok(Value::Unit);
4242            }
4243
4244            // ── Faux-3D in 2D space ──────────────────────────────────────────
4245            #[cfg(not(target_arch = "wasm32"))]
4246            "ui_gauge3d" | "立体仪表" | "立体ゲージ" | "입체게이지" | "มาตรวัด3มิติ" => {
4247                let cx=self.arg_num(&args,0,0.)? as f32; let cy=self.arg_num(&args,1,0.)? as f32;
4248                let r=self.arg_num(&args,2,50.)? as f32;
4249                let val=self.arg_num(&args,3,0.)? as f32; let max=self.arg_num(&args,4,1.)? as f32;
4250                let spin=self.arg_num(&args,5,0.)? as f32;
4251                let th=self.ui_theme; let fill=self.color_at(&args,6,th.primary);
4252                self.draw_ui(&ling_ui::widgets::gauge3d(cx,cy,r, val/max.max(1e-6), spin, fill, th.track));
4253                return Ok(Value::Unit);
4254            }
4255            #[cfg(not(target_arch = "wasm32"))]
4256            "ui_panel3d" | "立体面板" | "立体パネル" | "입체패널" | "แผง3มิติ" => {
4257                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
4258                let w0=self.arg_num(&args,2,200.)? as f32; let h0=self.arg_num(&args,3,120.)? as f32;
4259                let depth=self.arg_num(&args,4,14.)? as f32;
4260                let th=self.ui_theme; let prim=self.color_at(&args,5,th.primary);
4261                self.draw_ui(&ling_ui::widgets::panel3d(x,y,w0,h0,depth, prim, th.bg));
4262                return Ok(Value::Unit);
4263            }
4264            #[cfg(not(target_arch = "wasm32"))]
4265            "ui_radar3d" | "立体雷达" | "立体レーダー" | "입체레이더" | "เรดาร์3มิติ" => {
4266                let cx=self.arg_num(&args,0,0.)? as f32; let cy=self.arg_num(&args,1,0.)? as f32;
4267                let r=self.arg_num(&args,2,60.)? as f32; let tilt=self.arg_num(&args,3,0.9)? as f32;
4268                let sweep=self.arg_num(&args,4,0.)? as f32;
4269                let th=self.ui_theme; let prim=self.color_at(&args,5,th.primary);
4270                self.draw_ui(&ling_ui::widgets::radar3d(cx,cy,r,tilt,sweep, prim, th.track));
4271                return Ok(Value::Unit);
4272            }
4273
4274            // ── Interface sounds ─────────────────────────────────────────────
4275            #[cfg(not(target_arch = "wasm32"))]
4276            "audio_blip" | "提示音" | "ビープ音" | "효과음" | "เสียงบี๊บ" => {
4277                let freq=self.arg_num(&args,0,660.)? as f32;
4278                let dur=self.arg_num(&args,1,0.08)? as f32;
4279                let wave=Wave::from_name(&self.arg_str(&args,2,"sine"));
4280                let amp=self.arg_num(&args,3,0.25)? as f32;
4281                if let Some(audio)=&self.audio { audio.blip(freq, amp, dur, wave); }
4282                return Ok(Value::Unit);
4283            }
4284            #[cfg(not(target_arch = "wasm32"))]
4285            "ui_sound" | "界面音" | "UI音" | "인터페이스음" | "เสียงปุ่ม" => {
4286                let name=self.arg_str(&args,0,"click");
4287                if let Some(audio)=&self.audio {
4288                    match name.as_str() {
4289                        "hover"   => audio.blip(880.0, 0.10, 0.04, Wave::Sine),
4290                        "confirm" => { audio.blip(660.0, 0.22, 0.07, Wave::Square); audio.blip(990.0, 0.18, 0.10, Wave::Square); }
4291                        "error"   => { audio.blip(180.0, 0.30, 0.16, Wave::Saw); audio.blip(140.0, 0.30, 0.18, Wave::Saw); }
4292                        "toggle"  => audio.blip(520.0, 0.22, 0.05, Wave::Triangle),
4293                        "tick"    => audio.blip(1500.0, 0.12, 0.02, Wave::Square),
4294                        _         => audio.blip(720.0, 0.26, 0.05, Wave::Square), // "click"
4295                    }
4296                }
4297                return Ok(Value::Unit);
4298            }
4299
4300            // ══════════════════════════════════════════════════════════════════
4301            // MUSIC TOOLKIT  (crates/ling-music) — decode · analysis · GM synth ·
4302            // rhythm · karaoke. Analysis/decoding need no audio device; playback
4303            // and synthesis lazily start a dedicated music engine.
4304            // ══════════════════════════════════════════════════════════════════
4305
4306            // music_load(path) -> track handle (decodes WAV/FLAC/OGG/MP3/AAC)
4307            #[cfg(not(target_arch = "wasm32"))]
4308            "music_load" | "载入音乐" | "音楽読込" | "음악로드" | "โหลดเพลง" => {
4309                let path = self.arg_str(&args, 0, "");
4310                let resolved = if std::path::Path::new(&path).exists() { path.clone() }
4311                    else if let Some(d) = &self.source_dir { d.join(&path).to_string_lossy().into_owned() }
4312                    else { path.clone() };
4313                match ling_music::load(&resolved) {
4314                    Ok(t) => { let id = self.tracks.len(); self.tracks.push(t); return Ok(Value::Number(id as f64)); }
4315                    Err(e) => { eprintln!("music_load failed ({path}): {e}"); return Ok(Value::Number(-1.0)); }
4316                }
4317            }
4318            #[cfg(not(target_arch = "wasm32"))]
4319            "music_duration" | "音乐时长" | "音楽長さ" | "음악길이" | "ความยาวเพลง" => {
4320                let id = self.arg_num(&args,0,0.0)? as i64;
4321                let d = self.tracks.get(id as usize).map(|t| t.duration).unwrap_or(0.0);
4322                return Ok(Value::Number(d as f64));
4323            }
4324            #[cfg(not(target_arch = "wasm32"))]
4325            "music_bpm" | "节拍速度" | "テンポ" | "템포" | "จังหวะต่อนาที" => {
4326                let id = self.arg_num(&args,0,0.0)? as i64;
4327                let b = self.tracks.get(id as usize).map(|t| ling_music::analysis::bpm(&t.mono, t.rate)).unwrap_or(0.0);
4328                return Ok(Value::Number(b as f64));
4329            }
4330            #[cfg(not(target_arch = "wasm32"))]
4331            "music_key" | "调性" | "調性" | "조성" | "คีย์เพลง" => {
4332                let id = self.arg_num(&args,0,0.0)? as i64;
4333                let k = self.tracks.get(id as usize).map(|t| ling_music::analysis::key_name(&t.mono, t.rate)).unwrap_or_default();
4334                return Ok(Value::Str(k));
4335            }
4336            #[cfg(not(target_arch = "wasm32"))]
4337            "music_onsets" | "音符起点" | "オンセット" | "온셋" | "จุดเริ่มเสียง" => {
4338                let id = self.arg_num(&args,0,0.0)? as i64;
4339                let v = self.tracks.get(id as usize).map(|t| ling_music::analysis::onsets(&t.mono, t.rate)).unwrap_or_default();
4340                return Ok(Value::List(v.into_iter().map(|x| Value::Number(x as f64)).collect()));
4341            }
4342            #[cfg(not(target_arch = "wasm32"))]
4343            "music_beat_grid" | "节拍网格" | "ビートグリッド" | "비트그리드" | "กริดจังหวะ" => {
4344                let id = self.arg_num(&args,0,0.0)? as i64;
4345                let beats = self.tracks.get(id as usize).map(|t| {
4346                    let b = ling_music::analysis::bpm(&t.mono, t.rate);
4347                    ling_music::analysis::beat_grid(&t.mono, t.rate, b)
4348                }).unwrap_or_default();
4349                return Ok(Value::List(beats.into_iter().map(|x| Value::Number(x as f64)).collect()));
4350            }
4351
4352            // ── playback ──
4353            #[cfg(not(target_arch = "wasm32"))]
4354            "music_play" | "播放音乐" | "音楽再生" | "음악재생" | "เล่นเพลง" => {
4355                let id = self.arg_num(&args,0,0.0)? as i64;
4356                if self.ensure_music() {
4357                    let track = self.tracks.get(id as usize).map(|t| (t.stereo.clone(), t.rate));
4358                    if let (Some((st, rate)), Some(m)) = (track, &self.music) { m.set_track(st, rate); m.play(); }
4359                    else if let Some(m) = &self.music { m.play(); }
4360                }
4361                return Ok(Value::Unit);
4362            }
4363            #[cfg(not(target_arch = "wasm32"))]
4364            "music_pause" | "暂停音乐" | "音楽一時停止" | "음악일시정지" | "หยุดเพลงชั่วคราว" => {
4365                if let Some(m) = &self.music { m.pause(); } return Ok(Value::Unit);
4366            }
4367            #[cfg(not(target_arch = "wasm32"))]
4368            "music_stop" | "停止音乐" | "音楽停止" | "음악정지" | "หยุดเพลง" => {
4369                if let Some(m) = &self.music { m.stop(); } return Ok(Value::Unit);
4370            }
4371            #[cfg(not(target_arch = "wasm32"))]
4372            "music_seek" | "定位音乐" | "音楽シーク" | "음악탐색" | "ค้นหาเพลง" => {
4373                let sec = self.arg_num(&args,0,0.0)? as f32;
4374                if let Some(m) = &self.music { m.seek(sec); } return Ok(Value::Unit);
4375            }
4376            #[cfg(not(target_arch = "wasm32"))]
4377            "music_pos" | "音乐位置" | "音楽位置" | "음악위치" | "ตำแหน่งเพลง" => {
4378                let p = self.music.as_ref().map(|m| m.position()).unwrap_or(0.0);
4379                return Ok(Value::Number(p as f64));
4380            }
4381            #[cfg(not(target_arch = "wasm32"))]
4382            "music_volume" | "音乐音量" | "音楽音量" | "음악음량" | "ระดับเพลง" => {
4383                let v = self.arg_num(&args,0,0.8)? as f32;
4384                if self.ensure_music() { if let Some(m) = &self.music { m.set_volume(v); } }
4385                return Ok(Value::Unit);
4386            }
4387
4388            // ── synthesis (GM-capable, patches from .ling files) ──
4389            #[cfg(not(target_arch = "wasm32"))]
4390            "music_patch" | "乐器音色" | "音色読込" | "악기패치" | "แพตช์เครื่องดนตรี" => {
4391                let path = self.arg_str(&args, 0, "");
4392                let resolved = if std::path::Path::new(&path).exists() { path.clone() }
4393                    else if let Some(d) = &self.source_dir { d.join(&path).to_string_lossy().into_owned() }
4394                    else { path.clone() };
4395                if !self.ensure_music() { return Ok(Value::Number(-1.0)); }
4396                match ling_music::patch::from_path(&resolved) {
4397                    Ok(p) => { let id = self.music.as_ref().unwrap().add_patch(p); return Ok(Value::Number(id as f64)); }
4398                    Err(e) => { eprintln!("music_patch failed ({path}): {e}"); return Ok(Value::Number(-1.0)); }
4399                }
4400            }
4401            #[cfg(not(target_arch = "wasm32"))]
4402            "music_note" | "弹音符" | "音符演奏" | "음표연주" | "เล่นโน้ต" => {
4403                let inst = self.arg_num(&args,0,0.0)? as usize;
4404                let midi = self.pitch_arg(&args, 1, 60);
4405                let dur  = self.arg_num(&args,2,0.5)? as f32;
4406                let vel  = self.arg_num(&args,3,0.9)? as f32;
4407                if self.ensure_music() { if let Some(m) = &self.music { m.note(inst, midi, vel, dur); } }
4408                return Ok(Value::Unit);
4409            }
4410            #[cfg(not(target_arch = "wasm32"))]
4411            "music_note_on" | "音符开始" | "音符オン" | "음표켜기" | "โน้ตเริ่ม" => {
4412                let inst = self.arg_num(&args,0,0.0)? as usize;
4413                let midi = self.pitch_arg(&args, 1, 60);
4414                let vel  = self.arg_num(&args,2,0.9)? as f32;
4415                if self.ensure_music() { if let Some(m) = &self.music { m.note_on(inst, midi, vel); } }
4416                return Ok(Value::Unit);
4417            }
4418            #[cfg(not(target_arch = "wasm32"))]
4419            "music_note_off" | "音符结束" | "音符オフ" | "음표끄기" | "โน้ตจบ" => {
4420                let inst = self.arg_num(&args,0,0.0)? as usize;
4421                let midi = self.pitch_arg(&args, 1, 60);
4422                if let Some(m) = &self.music { m.note_off(inst, midi); }
4423                return Ok(Value::Unit);
4424            }
4425
4426            // ── rhythm-game judging ──
4427            #[cfg(not(target_arch = "wasm32"))]
4428            "music_judge" | "判定" | "判定する" | "판정" | "ตัดสินจังหวะ" => {
4429                let delta_ms = self.arg_num(&args,0,9999.0)? as f32;
4430                return Ok(Value::Number(ling_music::Grade::judge(delta_ms).index() as f64));
4431            }
4432            #[cfg(not(target_arch = "wasm32"))]
4433            "music_grade_name" | "判定名" | "判定名称" | "판정이름" | "ชื่อการตัดสิน" => {
4434                let idx = self.arg_num(&args,0,4.0)? as i32;
4435                return Ok(Value::Str(ling_music::Grade::from_index(idx).name().to_string()));
4436            }
4437
4438            // ── karaoke ──
4439            #[cfg(not(target_arch = "wasm32"))]
4440            "music_lrc" | "载入歌词" | "歌詞読込" | "가사로드" | "โหลดเนื้อเพลง" => {
4441                let path = self.arg_str(&args, 0, "");
4442                let resolved = if std::path::Path::new(&path).exists() { path.clone() }
4443                    else if let Some(d) = &self.source_dir { d.join(&path).to_string_lossy().into_owned() }
4444                    else { path.clone() };
4445                match std::fs::read_to_string(&resolved) {
4446                    Ok(text) => { let id = self.lyrics.len(); self.lyrics.push(ling_music::Lyrics::parse(&text)); return Ok(Value::Number(id as f64)); }
4447                    Err(e) => { eprintln!("music_lrc failed ({path}): {e}"); return Ok(Value::Number(-1.0)); }
4448                }
4449            }
4450            #[cfg(not(target_arch = "wasm32"))]
4451            "music_lyric" | "当前歌词" | "現在歌詞" | "현재가사" | "เนื้อเพลงปัจจุบัน" => {
4452                let id = self.arg_num(&args,0,0.0)? as i64;
4453                let t  = self.arg_num(&args,1,0.0)? as f32;
4454                let line = self.lyrics.get(id as usize).map(|l| l.line_at(t).to_string()).unwrap_or_default();
4455                return Ok(Value::Str(line));
4456            }
4457            #[cfg(not(target_arch = "wasm32"))]
4458            "music_mic_pitch" | "麦克风音高" | "マイク音程" | "마이크음정" | "ระดับเสียงไมค์" => {
4459                let hz = if let Some(mic) = self.mic.as_ref() {
4460                    let s = mic.latest_samples();
4461                    let rate = mic.sample_rate();
4462                    ling_music::pitch::detect(&s, rate).unwrap_or(0.0)
4463                } else { 0.0 };
4464                return Ok(Value::Number(hz as f64));
4465            }
4466            #[cfg(not(target_arch = "wasm32"))]
4467            "music_note_name" | "音名" | "音名称" | "음이름" | "ชื่อโน้ต" => {
4468                let hz = self.arg_num(&args,0,0.0)? as f32;
4469                return Ok(Value::Str(ling_music::note::hz_to_name(hz)));
4470            }
4471            #[cfg(not(target_arch = "wasm32"))]
4472            "music_hz" | "音符频率" | "音符周波数" | "음표주파수" | "ความถี่โน้ต" => {
4473                let midi = self.pitch_arg(&args, 0, 69);
4474                return Ok(Value::Number(ling_music::note::midi_to_hz(midi as f32) as f64));
4475            }
4476            #[cfg(not(target_arch = "wasm32"))]
4477            "music_pitch_score" | "音准评分" | "音程スコア" | "음정점수" | "คะแนนเสียง" => {
4478                let hz = self.arg_num(&args,0,0.0)? as f32;
4479                let target = self.arg_num(&args,1,0.0)? as f32;
4480                return Ok(Value::Number(ling_music::karaoke::pitch_score(hz, target) as f64));
4481            }
4482
4483            // ── MIDI (inaudible note source: drive coins, cues, etc.) ──
4484            #[cfg(not(target_arch = "wasm32"))]
4485            "music_midi_load" | "载入MIDI" | "MIDI読込" | "미디로드" | "โหลดมิดี" => {
4486                let path = self.arg_str(&args, 0, "");
4487                let resolved = if std::path::Path::new(&path).exists() { path.clone() }
4488                    else if let Some(d) = &self.source_dir { d.join(&path).to_string_lossy().into_owned() }
4489                    else { path.clone() };
4490                match ling_music::midi::load(&resolved) {
4491                    Ok(m) => { let id = self.midis.len(); self.midis.push(m); return Ok(Value::Number(id as f64)); }
4492                    Err(e) => { eprintln!("music_midi_load failed ({path}): {e}"); return Ok(Value::Number(-1.0)); }
4493                }
4494            }
4495            #[cfg(not(target_arch = "wasm32"))]
4496            "music_midi_count" | "MIDI数量" | "MIDI数" | "미디수" | "จำนวนมิดี" => {
4497                let id = self.arg_num(&args,0,0.0)? as i64;
4498                let n = self.midis.get(id as usize).map(|m| m.notes.len()).unwrap_or(0);
4499                return Ok(Value::Number(n as f64));
4500            }
4501            // music_midi_notes(id) -> flat [time, midi, time, midi, …]
4502            #[cfg(not(target_arch = "wasm32"))]
4503            "music_midi_notes" | "MIDI音符" | "MIDIノート" | "미디음표" | "โน้ตมิดี" => {
4504                let id = self.arg_num(&args,0,0.0)? as i64;
4505                let mut out = Vec::new();
4506                if let Some(m) = self.midis.get(id as usize) {
4507                    for n in &m.notes { out.push(Value::Number(n.time as f64)); out.push(Value::Number(n.midi as f64)); }
4508                }
4509                return Ok(Value::List(out));
4510            }
4511            // music_midi_bars(id) -> flat [time, midi, dur, …] (for karaoke note bars)
4512            #[cfg(not(target_arch = "wasm32"))]
4513            "music_midi_bars" | "MIDI音条" | "MIDIバー" | "미디바" | "แท่งมิดี" => {
4514                let id = self.arg_num(&args,0,0.0)? as i64;
4515                let mut out = Vec::new();
4516                if let Some(m) = self.midis.get(id as usize) {
4517                    for n in &m.notes {
4518                        out.push(Value::Number(n.time as f64));
4519                        out.push(Value::Number(n.midi as f64));
4520                        out.push(Value::Number(n.dur as f64));
4521                    }
4522                }
4523                return Ok(Value::List(out));
4524            }
4525
4526            // music_fft(track_id, nbands) -> spectrum at the current playback position
4527            #[cfg(not(target_arch = "wasm32"))]
4528            "music_fft" | "音乐频谱" | "音楽スペクトル" | "음악스펙트럼" | "สเปกตรัมเพลง" => {
4529                let id = self.arg_num(&args,0,0.0)? as i64;
4530                let nbands = self.arg_num(&args,1,16.0)? as usize;
4531                let pos = self.music.as_ref().map(|m| m.position()).unwrap_or(0.0);
4532                if let Some(t) = self.tracks.get(id as usize) {
4533                    let idx = (pos * t.rate as f32) as usize;
4534                    let end = (idx + 2048).min(t.mono.len());
4535                    if end > idx + 64 {
4536                        self.fft.borrow_mut().push_samples(&t.mono[idx..end]);
4537                    }
4538                }
4539                let bands = self.fft.borrow().freq_bands(nbands);
4540                return Ok(Value::List(bands.into_iter().map(|x| Value::Number(x as f64)).collect()));
4541            }
4542
4543            // ── spatial (2D/3D/4D) one-shot SFX ──
4544            #[cfg(not(target_arch = "wasm32"))]
4545            "audio_sfx" | "音效" | "空間効果音" | "공간효과음" | "เสียงเอฟเฟกต์" => {
4546                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;
4547                let w=self.arg_num(&args,3,1.0)? as f32; let freq=self.arg_num(&args,4,440.0)? as f32;
4548                let amp=self.arg_num(&args,5,0.3)? as f32; let dur=self.arg_num(&args,6,0.15)? as f32;
4549                let wave=Wave::from_name(&self.arg_str(&args,7,"sine"));
4550                if let Some(a)=&self.audio { a.sfx(x,y,z,w,freq,amp,dur,wave); }
4551                return Ok(Value::Unit);
4552            }
4553            // ── sample load / positional play / loop / stop ──
4554            #[cfg(not(target_arch = "wasm32"))]
4555            "audio_sample_load" | "载入采样" | "サンプル読込" | "샘플로드" | "โหลดตัวอย่างเสียง" => {
4556                let path = self.arg_str(&args, 0, "");
4557                let resolved = if std::path::Path::new(&path).exists() { path.clone() }
4558                    else if let Some(d) = &self.source_dir { d.join(&path).to_string_lossy().into_owned() }
4559                    else { path.clone() };
4560                match ling_music::load(&resolved) {
4561                    Ok(t) => {
4562                        if let Some(a)=&self.audio { return Ok(Value::Number(a.add_sample(t.mono, t.rate) as f64)); }
4563                        return Ok(Value::Number(-1.0));
4564                    }
4565                    Err(e) => { eprintln!("audio_sample_load failed ({path}): {e}"); return Ok(Value::Number(-1.0)); }
4566                }
4567            }
4568            #[cfg(not(target_arch = "wasm32"))]
4569            "audio_sample_play" | "播放采样" | "サンプル再生" | "샘플재생" | "เล่นตัวอย่างเสียง" => {
4570                let id=self.arg_num(&args,0,0.0)? as usize;
4571                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;
4572                let w=self.arg_num(&args,4,1.0)? as f32; let vol=self.arg_num(&args,5,1.0)? as f32;
4573                let looping=self.arg_num(&args,6,0.0)? > 0.5;
4574                let v = self.audio.as_ref().map(|a| a.play_sample(id,x,y,z,w,vol,looping)).unwrap_or(0);
4575                return Ok(Value::Number(v as f64));
4576            }
4577            #[cfg(not(target_arch = "wasm32"))]
4578            "audio_sample_stop" | "停止采样" | "サンプル停止" | "샘플정지" | "หยุดตัวอย่างเสียง" => {
4579                let v=self.arg_num(&args,0,0.0)? as u32;
4580                if let Some(a)=&self.audio { a.stop_sample(v); }
4581                return Ok(Value::Unit);
4582            }
4583            // ── master FX: delay / reverb / low-pass (underwater) ──
4584            #[cfg(not(target_arch = "wasm32"))]
4585            "audio_fx_delay" | "回声" | "ディレイ効果" | "딜레이" | "เสียงสะท้อน" => {
4586                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;
4587                if let Some(a)=&self.audio { a.fx_delay(time,fb,mix); }
4588                return Ok(Value::Unit);
4589            }
4590            #[cfg(not(target_arch = "wasm32"))]
4591            "audio_fx_reverb" | "混响" | "リバーブ" | "리버브" | "เสียงก้อง" => {
4592                let mix=self.arg_num(&args,0,0.3)? as f32;
4593                if let Some(a)=&self.audio { a.fx_reverb(mix); }
4594                return Ok(Value::Unit);
4595            }
4596            #[cfg(not(target_arch = "wasm32"))]
4597            "audio_fx_lowpass" | "低通滤波" | "ローパス" | "저역통과" | "กรองความถี่ต่ำ" => {
4598                let cutoff=self.arg_num(&args,0,1.0)? as f32;
4599                if let Some(a)=&self.audio { a.fx_lowpass(cutoff); }
4600                return Ok(Value::Unit);
4601            }
4602
4603            // ══════════════════════════════════════════════════════════════════
4604            // PHYSICS BUILTINS  (crates/ling-physics) — soft bodies, rigid+angular,
4605            // and a fast 2-D water/oil liquid sim mappable onto 3-D surfaces.
4606            // ══════════════════════════════════════════════════════════════════
4607
4608            // ── soft bodies (deformable bouncy balls) ──
4609            #[cfg(not(target_arch = "wasm32"))]
4610            "soft_ball" | "软球" | "ソフトボール" | "소프트볼" | "ลูกบอลนุ่ม" => {
4611                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;
4612                let r=self.arg_num(&args,3,1.0)? as f32;
4613                let b = ling_physics::soft::SoftBody::sphere(ling_physics::Vec3::new(x,y,z), r, 8, 12, 1.0);
4614                let id = self.soft_bodies.len(); self.soft_bodies.push(b);
4615                return Ok(Value::Number(id as f64));
4616            }
4617            #[cfg(not(target_arch = "wasm32"))]
4618            "soft_step" | "软体步进" | "ソフト更新" | "소프트스텝" | "ก้าวนุ่ม" => {
4619                let id=self.arg_num(&args,0,0.)? as usize; let dt=self.arg_num(&args,1,0.016)? as f32;
4620                let gy=self.arg_num(&args,2,15.0)? as f32;
4621                if let Some(b)=self.soft_bodies.get_mut(id) { b.integrate(dt, ling_physics::Vec3::new(0.0,gy,0.0), 4); }
4622                return Ok(Value::Unit);
4623            }
4624            #[cfg(not(target_arch = "wasm32"))]
4625            "soft_bounce" | "软体落地" | "ソフト着地" | "소프트바운스" | "เด้งนุ่ม" => {
4626                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;
4627                if let Some(b)=self.soft_bodies.get_mut(id) { b.floor_collision(fy, rest); }
4628                return Ok(Value::Unit);
4629            }
4630            #[cfg(not(target_arch = "wasm32"))]
4631            "soft_contain" | "软体边界" | "ソフト箱" | "소프트경계" | "กล่องนุ่ม" => {
4632                let id=self.arg_num(&args,0,0.)? as usize;
4633                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;
4634                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;
4635                let rest=self.arg_num(&args,7,0.6)? as f32;
4636                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); }
4637                return Ok(Value::Unit);
4638            }
4639            #[cfg(not(target_arch = "wasm32"))]
4640            "soft_kick" | "软体踢" | "ソフト衝撃" | "소프트킥" | "เตะนุ่ม" => {
4641                let id=self.arg_num(&args,0,0.)? as usize;
4642                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;
4643                let s=self.arg_num(&args,4,0.1)? as f32;
4644                if let Some(b)=self.soft_bodies.get_mut(id) { b.kick(ling_physics::Vec3::new(dx,dy,dz), s); }
4645                return Ok(Value::Unit);
4646            }
4647            // soft_spin(id, ax, ay, az, rate) — add angular velocity about the axis
4648            // through the centroid (rate = rad/step; ≈ surface_speed / radius to roll)
4649            #[cfg(not(target_arch = "wasm32"))]
4650            "soft_spin" | "软体自旋" | "ソフト回転" | "소프트회전" | "หมุนนุ่ม" => {
4651                let id=self.arg_num(&args,0,0.)? as usize;
4652                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;
4653                let rate=self.arg_num(&args,4,0.1)? as f32;
4654                if let Some(b)=self.soft_bodies.get_mut(id) { b.spin(ling_physics::Vec3::new(ax,ay,az), rate); }
4655                return Ok(Value::Unit);
4656            }
4657            #[cfg(not(target_arch = "wasm32"))]
4658            "soft_deform" | "形变量" | "変形量" | "변형량" | "ความบิดเบี้ยว" => {
4659                let id=self.arg_num(&args,0,0.)? as usize;
4660                let d=self.soft_bodies.get(id).map(|b| b.deformation()).unwrap_or(0.0);
4661                return Ok(Value::Number(d as f64));
4662            }
4663            // soft_angular_speed(id) -> magnitude of the body's angular velocity
4664            // (how fast it is tumbling/rolling), derived from its node velocities.
4665            #[cfg(not(target_arch = "wasm32"))]
4666            "soft_angular_speed" | "软体角速" | "ソフト角速度" | "소프트각속도" | "ความเร็วเชิงมุมนุ่ม" => {
4667                let id=self.arg_num(&args,0,0.)? as usize;
4668                let w=self.soft_bodies.get(id).map(|b| b.angular_speed()).unwrap_or(0.0);
4669                return Ok(Value::Number(w as f64));
4670            }
4671            #[cfg(not(target_arch = "wasm32"))]
4672            "soft_centroid" | "软体质心" | "ソフト重心" | "소프트중심" | "จุดศูนย์กลางนุ่ม" => {
4673                let id=self.arg_num(&args,0,0.)? as usize;
4674                let c=self.soft_bodies.get(id).map(|b| b.centroid()).unwrap_or(ling_physics::Vec3::ZERO);
4675                return Ok(Value::List(vec![Value::Number(c.x as f64),Value::Number(c.y as f64),Value::Number(c.z as f64)]));
4676            }
4677            // soft_nodes(id) -> flat [x,y,z, x,y,z, …] for rendering the deformed mesh
4678            #[cfg(not(target_arch = "wasm32"))]
4679            "soft_nodes" | "软体节点" | "ソフト節点" | "소프트노드" | "จุดนุ่ม" => {
4680                let id=self.arg_num(&args,0,0.)? as usize;
4681                let mut out=Vec::new();
4682                if let Some(b)=self.soft_bodies.get(id) {
4683                    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)); }
4684                }
4685                return Ok(Value::List(out));
4686            }
4687
4688            // ── rigid bodies with angular dynamics ──
4689            #[cfg(not(target_arch = "wasm32"))]
4690            "rb_add" | "刚体添加" | "剛体追加" | "강체추가" | "เพิ่มวัตถุแข็ง" => {
4691                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;
4692                let mass=self.arg_num(&args,3,1.0)? as f32;
4693                let mut b = ling_physics::rigid::RigidBody::new(ling_physics::Vec3::new(x,y,z), mass);
4694                b.restitution = 0.6;
4695                return Ok(Value::Number(self.rigid_world.add(b) as f64));
4696            }
4697            #[cfg(not(target_arch = "wasm32"))]
4698            "rb_torque" | "扭矩" | "トルク" | "토크" | "แรงบิด" => {
4699                let i=self.arg_num(&args,0,0.)? as usize;
4700                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;
4701                if let Some(b)=self.rigid_world.bodies.get_mut(i) { b.apply_torque(ling_physics::Vec3::new(tx,ty,tz)); }
4702                return Ok(Value::Unit);
4703            }
4704            #[cfg(not(target_arch = "wasm32"))]
4705            "rb_spin" | "自旋" | "スピン" | "스핀" | "หมุน" => {
4706                let i=self.arg_num(&args,0,0.)? as usize;
4707                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;
4708                if let Some(b)=self.rigid_world.bodies.get_mut(i) { b.apply_spin(ling_physics::Vec3::new(wx,wy,wz)); }
4709                return Ok(Value::Unit);
4710            }
4711            #[cfg(not(target_arch = "wasm32"))]
4712            "rb_impulse" | "刚体冲量" | "剛体インパルス" | "강체충격" | "แรงดลแข็ง" => {
4713                let i=self.arg_num(&args,0,0.)? as usize;
4714                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;
4715                if let Some(b)=self.rigid_world.bodies.get_mut(i) { b.apply_impulse(ling_physics::Vec3::new(ix,iy,iz)); }
4716                return Ok(Value::Unit);
4717            }
4718            #[cfg(not(target_arch = "wasm32"))]
4719            "rb_floor" | "刚体落地" | "剛体着地" | "강체바닥" | "พื้นแข็ง" => {
4720                let i=self.arg_num(&args,0,0.)? as usize; let fy=self.arg_num(&args,1,0.)? as f32;
4721                let rest=self.arg_num(&args,2,0.6)? as f32; let fric=self.arg_num(&args,3,0.6)? as f32;
4722                if let Some(b)=self.rigid_world.bodies.get_mut(i) { b.bounce_floor(fy, rest, fric); }
4723                return Ok(Value::Unit);
4724            }
4725            #[cfg(not(target_arch = "wasm32"))]
4726            "rb_gravity" | "刚体重力" | "剛体重力" | "강체중력" | "แรงโน้มถ่วงแข็ง" => {
4727                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;
4728                self.rigid_world.gravity = ling_physics::Vec3::new(gx,gy,gz);
4729                return Ok(Value::Unit);
4730            }
4731            #[cfg(not(target_arch = "wasm32"))]
4732            "rb_step" | "刚体步进" | "剛体更新" | "강체스텝" | "ก้าวแข็ง" => {
4733                let dt=self.arg_num(&args,0,0.016)? as f32;
4734                self.rigid_world.step(dt);
4735                return Ok(Value::Unit);
4736            }
4737            #[cfg(not(target_arch = "wasm32"))]
4738            "rb_pos" | "刚体位置" | "剛体位置" | "강체위치" | "ตำแหน่งแข็ง" => {
4739                let i=self.arg_num(&args,0,0.)? as usize;
4740                let p=self.rigid_world.bodies.get(i).map(|b| b.pos).unwrap_or(ling_physics::Vec3::ZERO);
4741                return Ok(Value::List(vec![Value::Number(p.x as f64),Value::Number(p.y as f64),Value::Number(p.z as f64)]));
4742            }
4743            #[cfg(not(target_arch = "wasm32"))]
4744            "rb_rot" | "刚体旋转" | "剛体回転" | "강체회전" | "การหมุนแข็ง" => {
4745                let i=self.arg_num(&args,0,0.)? as usize;
4746                let q=self.rigid_world.bodies.get(i).map(|b| b.orientation).unwrap_or(ling_physics::Quat::IDENTITY);
4747                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)]));
4748            }
4749
4750            // ── liquid sim (water + oil, immiscible) ──
4751            #[cfg(not(target_arch = "wasm32"))]
4752            "liquid_new" | "新建液体" | "液体新規" | "액체생성" | "สร้างของเหลว" => {
4753                let w=self.arg_num(&args,0,64.)? as usize; let h=self.arg_num(&args,1,64.)? as usize;
4754                let id=self.liquids.len(); self.liquids.push(ling_physics::liquid::LiquidGrid::new(w,h));
4755                return Ok(Value::Number(id as f64));
4756            }
4757            #[cfg(not(target_arch = "wasm32"))]
4758            "liquid_splat" | "液体注入" | "液体追加" | "액체분사" | "หยดของเหลว" => {
4759                let id=self.arg_num(&args,0,0.)? as usize;
4760                let x=self.arg_num(&args,1,0.)? as f32; let y=self.arg_num(&args,2,0.)? as f32;
4761                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;
4762                if let Some(g)=self.liquids.get_mut(id) { g.splat(x,y,kind,amt,rad); }
4763                return Ok(Value::Unit);
4764            }
4765            #[cfg(not(target_arch = "wasm32"))]
4766            "liquid_gravity" | "液体重力" | "液体重力ベクトル" | "액체중력" | "แรงโน้มถ่วงเหลว" => {
4767                let id=self.arg_num(&args,0,0.)? as usize;
4768                let gx=self.arg_num(&args,1,0.)? as f32; let gy=self.arg_num(&args,2,60.)? as f32;
4769                if let Some(g)=self.liquids.get_mut(id) { g.set_gravity(gx,gy); }
4770                return Ok(Value::Unit);
4771            }
4772            #[cfg(not(target_arch = "wasm32"))]
4773            "liquid_step" | "液体步进" | "液体更新" | "액체스텝" | "ก้าวของเหลว" => {
4774                let id=self.arg_num(&args,0,0.)? as usize; let dt=self.arg_num(&args,1,0.016)? as f32;
4775                if let Some(g)=self.liquids.get_mut(id) { g.step(dt); }
4776                return Ok(Value::Unit);
4777            }
4778            // liquid_rainbow(id, on) — colour the fluid as a flowing ROYGBIV marble
4779            #[cfg(not(target_arch = "wasm32"))]
4780            "liquid_rainbow" | "液体彩虹" | "液体虹" | "액체무지개" | "ของเหลวสายรุ้ง" => {
4781                let id=self.arg_num(&args,0,0.)? as usize;
4782                let on=self.arg_num(&args,1,1.0)? > 0.5;
4783                if let Some(g)=self.liquids.get_mut(id) { g.rainbow = on; }
4784                return Ok(Value::Unit);
4785            }
4786            // liquid_mix(id) -> 0 (oil/water separated) .. 1 (fully intermixed)
4787            #[cfg(not(target_arch = "wasm32"))]
4788            "liquid_mix" | "液体混合" | "液体混合度" | "액체혼합" | "การผสมของเหลว" => {
4789                let id=self.arg_num(&args,0,0.)? as usize;
4790                let m=self.liquids.get(id).map(|g| g.mix_amount()).unwrap_or(0.0);
4791                return Ok(Value::Number(m as f64));
4792            }
4793            // liquid_draw(id, sx, sy, scale) — fast flat 2-D blit of the colour field
4794            #[cfg(not(target_arch = "wasm32"))]
4795            "liquid_draw" | "绘制液体" | "液体描画" | "액체그리기" | "วาดของเหลว" => {
4796                let id=self.arg_num(&args,0,0.)? as usize;
4797                let sx=self.arg_num(&args,1,0.)? as i32; let sy=self.arg_num(&args,2,0.)? as i32;
4798                let scale=(self.arg_num(&args,3,4.)? as i32).max(1);
4799                if id < self.liquids.len() {
4800                    let (gw,gh)={ let g=&self.liquids[id]; (g.w,g.h) };
4801                    let mut gfx=self.gfx.borrow_mut(); let (w,h)=(gfx.width as i32, gfx.height as i32);
4802                    let g=&self.liquids[id];
4803                    for cy in 0..gh { for cx in 0..gw {
4804                        let col=g.sample_rgb(cx,cy);
4805                        let bx=sx + cx as i32*scale; let by=sy + cy as i32*scale;
4806                        for dy in 0..scale { for dx in 0..scale {
4807                            let px=bx+dx; let py=by+dy;
4808                            if px>=0 && py>=0 && px<w && py<h { gfx.buffer[(py*w+px) as usize]=col; }
4809                        }}
4810                    }}
4811                }
4812                return Ok(Value::Unit);
4813            }
4814            // liquid_draw_surface(id, kind, cx,cy,cz, radius, height)
4815            //   kind: 0 plane · 1 sphere · 2 cylinder · 3 cone · 4 dome
4816            #[cfg(not(target_arch = "wasm32"))]
4817            "liquid_draw_surface" | "液体贴面" | "液体曲面" | "액체곡면" | "ของเหลวบนพื้นผิว" => {
4818                let id=self.arg_num(&args,0,0.)? as usize;
4819                let kind=self.arg_num(&args,1,1.)? as i32;
4820                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;
4821                let radius=self.arg_num(&args,5,2.0)? as f32; let height=self.arg_num(&args,6,3.0)? as f32;
4822                if id < self.liquids.len() {
4823                    let (gw,gh)={ let g=&self.liquids[id]; (g.w,g.h) };
4824                    let mut gfx=self.gfx.borrow_mut();
4825                    let (w,h,add)=(gfx.width, gfx.height, gfx.blend==1);
4826                    let cam=gfx.camera.clone();
4827                    let near = -cam.zdist + 0.05;
4828                    let g=&self.liquids[id];
4829                    let tau=std::f32::consts::TAU; let pi=std::f32::consts::PI;
4830                    // surface point for a (u,v) in [0,1] on the chosen primitive
4831                    let sp = |u:f32, v:f32| -> [f32;3] {
4832                        if kind==0 { [cx+(u-0.5)*2.0*radius, cy, cz+(v-0.5)*2.0*radius] }
4833                        else if kind==2 { let th=u*tau; [cx+th.cos()*radius, cy+(v-0.5)*height, cz+th.sin()*radius] }
4834                        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] }
4835                        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] }
4836                        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] }
4837                    };
4838                    let nrm = |u:f32, v:f32| -> [f32;3] {
4839                        if kind==0 { [0.0,-1.0,0.0] }
4840                        else if kind==2 { let th=u*tau; [th.cos(),0.0,th.sin()] }
4841                        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()] }
4842                        else if kind==4 { let th=u*tau; let ph=v*pi*0.5; [ph.sin()*th.cos(),-ph.cos(),ph.sin()*th.sin()] }
4843                        else { let th=u*tau; let ph=v*pi; [ph.sin()*th.cos(),ph.cos(),ph.sin()*th.sin()] }
4844                    };
4845                    let gwf=gw as f32; let ghf=gh as f32;
4846                    let mut cyc=0usize;
4847                    while cyc<gh {
4848                        let mut cxc=0usize;
4849                        while cxc<gw {
4850                            // cull by the cell centre's outward normal
4851                            let uc=(cxc as f32+0.5)/gwf; let vc=(cyc as f32+0.5)/ghf;
4852                            let c=sp(uc,vc); let n=nrm(uc,vc);
4853                            let dc=cam.depth(c[0],c[1],c[2]);
4854                            if dc>near {
4855                                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;
4856                                if !cull {
4857                                    // project the 4 cell corners → a filled AA vector quad
4858                                    let u0=cxc as f32/gwf; let u1=(cxc+1) as f32/gwf;
4859                                    let v0=cyc as f32/ghf; let v1=(cyc+1) as f32/ghf;
4860                                    let q=[sp(u0,v0),sp(u1,v0),sp(u1,v1),sp(u0,v1)];
4861                                    let mut poly: Vec<[f32;2]> = Vec::with_capacity(5);
4862                                    let mut ok=true;
4863                                    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]); }
4864                                    if ok { let p0=poly[0]; poly.push(p0);
4865                                        let col=g.sample_rgb(cxc,cyc);
4866                                        crate::gfx::raster::fill_contours_aa(&mut gfx.buffer, w, h, col, add, std::slice::from_ref(&poly));
4867                                    }
4868                                }
4869                            }
4870                            cxc+=1;
4871                        }
4872                        cyc+=1;
4873                    }
4874                }
4875                return Ok(Value::Unit);
4876            }
4877            // sparkle(x, y, w, h, count [, t]) — scatter twinkling vector star-sparkles
4878            // in a rect (snowglobe effect) in the current colour + blend mode.
4879            #[cfg(not(target_arch = "wasm32"))]
4880            "sparkle" | "闪光" | "きらめき" | "반짝임" | "ประกาย" => {
4881                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
4882                let ww=self.arg_num(&args,2,200.)? as f32; let hh=self.arg_num(&args,3,200.)? as f32;
4883                let count=self.arg_num(&args,4,40.)? as i32;
4884                let t=self.arg_num(&args,5,0.)? as f32;
4885                let mut gfx=self.gfx.borrow_mut();
4886                let (w,h,add,color)=(gfx.width, gfx.height, gfx.blend==1, gfx.color);
4887                let (cr,cg,cb)=((color>>16&0xFF) as f32,(color>>8&0xFF) as f32,(color&0xFF) as f32);
4888                let mut n=0i32;
4889                while n<count {
4890                    let hsh=(n as u32).wrapping_mul(2654435761).wrapping_add(0x9E3779B9);
4891                    let u=((hsh>>8)&1023) as f32/1023.0;
4892                    let v=((hsh>>18)&1023) as f32/1023.0;
4893                    let phase=(hsh&255) as f32/255.0;
4894                    let tw=(t*3.0 + phase*6.2831 + n as f32).sin()*0.5+0.5;
4895                    let sz=1.5+tw*5.0;
4896                    let px=x+u*ww; let py=y+v*hh;
4897                    let b=tw*tw; // sharp twinkle
4898                    let col=(((cr*b)as u32)<<16)|(((cg*b)as u32)<<8)|((cb*b)as u32);
4899                    crate::gfx::raster::draw_line_aa(&mut gfx.buffer,w,h,col,add, px-sz,py, px+sz,py);
4900                    crate::gfx::raster::draw_line_aa(&mut gfx.buffer,w,h,col,add, px,py-sz, px,py+sz);
4901                    let d=sz*0.55;
4902                    crate::gfx::raster::draw_line_aa(&mut gfx.buffer,w,h,col,add, px-d,py-d, px+d,py+d);
4903                    crate::gfx::raster::draw_line_aa(&mut gfx.buffer,w,h,col,add, px-d,py+d, px+d,py-d);
4904                    n+=1;
4905                }
4906                return Ok(Value::Unit);
4907            }
4908
4909            // ══════════════════════════════════════════════════════════════════
4910            // DIALOG BUILTINS  (crates/ling-game/src/dialog.rs) — cinematic,
4911            // typed-out, colour-coded text boxes. Markup: {n}name{/} {p}place{/}
4912            // {i}item{/}, \n newline, || page break.
4913            // ══════════════════════════════════════════════════════════════════
4914            #[cfg(not(target_arch = "wasm32"))]
4915            "dialog_show" | "对话显示" | "会話表示" | "대화표시" | "แสดงบทสนทนา" => {
4916                let text = self.arg_str(&args, 0, "");
4917                let cps = self.arg_num(&args, 1, 32.0)? as f32;
4918                self.dialog = Some(ling_game::dialog::Dialog::new(&text, cps));
4919                return Ok(Value::Unit);
4920            }
4921            #[cfg(not(target_arch = "wasm32"))]
4922            "dialog_step" | "对话步进" | "会話更新" | "대화스텝" | "ก้าวบทสนทนา" => {
4923                let dt = self.arg_num(&args, 0, 0.016)? as f32;
4924                if let Some(d) = self.dialog.as_mut() { d.update(dt); }
4925                return Ok(Value::Unit);
4926            }
4927            #[cfg(not(target_arch = "wasm32"))]
4928            "dialog_advance" | "对话推进" | "会話送り" | "대화진행" | "เลื่อนบทสนทนา" => {
4929                if let Some(d) = self.dialog.as_mut() { d.advance(); }
4930                return Ok(Value::Unit);
4931            }
4932            #[cfg(not(target_arch = "wasm32"))]
4933            "dialog_active" | "对话激活" | "会話中" | "대화중" | "บทสนทนาทำงาน" => {
4934                let a = self.dialog.as_ref().map(|d| !d.is_closed()).unwrap_or(false);
4935                return Ok(Value::Bool(a));
4936            }
4937            #[cfg(not(target_arch = "wasm32"))]
4938            "dialog_typing" | "对话打字" | "会話タイプ中" | "대화타이핑" | "กำลังพิมพ์บทสนทนา" => {
4939                use ling_game::dialog::Dialog;
4940                
4941                let a = self.dialog.as_ref().map(|d: &Dialog | !d.is_closed() && d.is_typing()).unwrap_or(false);
4942                return Ok(Value::Bool(a))
4943            }
4944            #[cfg(not(target_arch = "wasm32"))]
4945            "dialog_close" | "对话关闭" | "会話閉じる" | "대화닫기" | "ปิดบทสนทนา" => {
4946                self.dialog = None;
4947                return Ok(Value::Unit);
4948            }
4949            // dialog_color(role, r, g, b) — role: 0 text · 1 name · 2 place · 3 item
4950            #[cfg(not(target_arch = "wasm32"))]
4951            "dialog_color" | "对话颜色" | "会話色" | "대화색" | "สีบทสนทนา" => {
4952                let role = (self.arg_num(&args,0,0.0)? as usize).min(3);
4953                let r = self.arg_num(&args,1,255.0)? as u32 & 0xFF;
4954                let g = self.arg_num(&args,2,255.0)? as u32 & 0xFF;
4955                let b = self.arg_num(&args,3,255.0)? as u32 & 0xFF;
4956                self.dialog_colors[role] = (r<<16)|(g<<8)|b;
4957                return Ok(Value::Unit);
4958            }
4959            // dialog_draw(x, y, w, h [, font_handle]) — draw the box + typed text
4960            #[cfg(not(target_arch = "wasm32"))]
4961            "dialog_draw" | "对话绘制" | "会話描画" | "대화그리기" | "วาดบทสนทนา" => {
4962                let x=self.arg_num(&args,0,40.0)? as f32; let y=self.arg_num(&args,1,0.0)? as f32;
4963                let ww=self.arg_num(&args,2,720.0)? as f32; let hh=self.arg_num(&args,3,150.0)? as f32;
4964                let font = self.arg_num(&args,4,-1.0)? as i64;
4965                let t = self.start_time.elapsed().as_secs_f32();
4966                self.render_dialog(x, y, ww, hh, font, t);
4967                return Ok(Value::Unit);
4968            }
4969
4970            // text_poll() — fold newly-typed keys into the input buffer, return it
4971            #[cfg(not(target_arch = "wasm32"))]
4972            "text_poll" => {
4973                let keys = { let gfx = self.gfx.borrow(); gfx.window.as_ref().map(|w| w.get_keys_pressed(minifb::KeyRepeat::No)).unwrap_or_default() };
4974                for k in keys {
4975                    if k == minifb::Key::Backspace { self.text_buffer.pop(); }
4976                    else if let Some(c) = key_char(k) { self.text_buffer.push(c); }
4977                }
4978                return Ok(Value::Str(self.text_buffer.clone()));
4979            }
4980            "text_get"   => return Ok(Value::Str(self.text_buffer.clone())),
4981            "text_set"   => { self.text_buffer = self.arg_str(&args,0,""); return Ok(Value::Unit); }
4982            "text_clear" => { self.text_buffer.clear(); return Ok(Value::Unit); }
4983            // record_frame() — append the current framebuffer as a PPM, return frame #
4984            #[cfg(not(target_arch = "wasm32"))]
4985            "record_frame" => {
4986                let n = self.record_n;
4987                let (buf, w, h) = { let gfx = self.gfx.borrow(); (gfx.buffer.clone(), gfx.width, gfx.height) };
4988                let _ = std::fs::create_dir_all("recordings");
4989                let mut out = Vec::with_capacity(w*h*3 + 32);
4990                out.extend_from_slice(format!("P6\n{w} {h}\n255\n").as_bytes());
4991                for px in &buf { let p = *px; out.push((p>>16) as u8); out.push((p>>8) as u8); out.push(p as u8); }
4992                let _ = std::fs::write(format!("recordings/frame_{n:05}.ppm"), out);
4993                self.record_n += 1;
4994                return Ok(Value::Number(n as f64));
4995            }
4996            "record_count" => return Ok(Value::Number(self.record_n as f64)),
4997            // ── microphone → crypto donut ──
4998            // mic_capture() — append the latest mic samples to the record buffer
4999            // (call each frame while recording). Returns the buffer length.
5000            #[cfg(not(target_arch = "wasm32"))]
5001            "mic_capture" => {
5002                if let Some(mic) = self.mic.as_ref() {
5003                    let s = mic.latest_samples();
5004                    self.mic_buffer.extend_from_slice(&s);
5005                    let cap = 96_000usize; // ~2 s @ 48 kHz
5006                    if self.mic_buffer.len() > cap {
5007                        let drop = self.mic_buffer.len() - cap;
5008                        self.mic_buffer.drain(0..drop);
5009                    }
5010                }
5011                return Ok(Value::Number(self.mic_buffer.len() as f64));
5012            }
5013            // mic_seed() — SHA3-256 hex of the recorded audio, usable as a donut seed
5014            #[cfg(not(target_arch = "wasm32"))]
5015            "mic_seed" => {
5016                let mut bytes = Vec::with_capacity(self.mic_buffer.len() * 4);
5017                for f in &self.mic_buffer { bytes.extend_from_slice(&f.to_le_bytes()); }
5018                return Ok(Value::Str(hex_encode(&ling_crypto::geo::holo_hash(&bytes))));
5019            }
5020            #[cfg(not(target_arch = "wasm32"))]
5021            "mic_clear" => { self.mic_buffer.clear(); return Ok(Value::Number(0.0)); }
5022            // flush the 3-D depth queue onto the framebuffer WITHOUT presenting,
5023            // so 2-D UI drawn afterwards overlays the 3-D scene.
5024            #[cfg(not(target_arch = "wasm32"))]
5025            "flush_3d" | "render_3d" => {
5026                let mut gfx = self.gfx.borrow_mut();
5027                if !gfx.depth_queue.is_empty() {
5028                    let w = gfx.width; let h = gfx.height;
5029                    let queue = std::mem::take(&mut gfx.depth_queue);
5030                    queue.flush(&mut gfx.buffer, w, h);
5031                }
5032                return Ok(Value::Unit);
5033            }
5034
5035            "set_rim" | "设置边缘光" | "リム設定" | "림라이트" | "ตั้งขอบเรือง" => {
5036                let s=self.arg_num(&args,0,0.6)? as f32;
5037                let r=self.arg_num(&args,1,115.)? as f32/255.0;
5038                let g=self.arg_num(&args,2,217.)? as f32/255.0;
5039                let b=self.arg_num(&args,3,255.)? as f32/255.0;
5040                let mut gfx=self.gfx.borrow_mut();
5041                gfx.shade.rim = s; gfx.shade.rim_color = [r,g,b];
5042                return Ok(Value::Unit);
5043            }
5044
5045            // ══════════════════════════════════════════════════════════════════
5046            // 3-D PRIMITIVES  (src/gfx/shapes.rs)  — "Inkscape for 3-D"
5047            //   shape(cx,cy,cz,  sx,sy,sz,  rx,ry,rz,  mode,  e0,e1,e2)
5048            //     centre (cx,cy,cz), per-axis scale, Euler rotation (radians),
5049            //     mode: 0 filled · 1 wireframe · 2 both,
5050            //     e0..e2: shape-specific (segments / sides / ratio …).
5051            //   Pen colour (set_color) drives fill lighting and wireframe colour.
5052            // ══════════════════════════════════════════════════════════════════
5053            n if crate::gfx::shapes::canon(n).is_some() => {
5054                let kind = crate::gfx::shapes::canon(n).unwrap();
5055                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;
5056                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;
5057                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;
5058                let mode=self.arg_num(&args,9,0.)? as i32;
5059                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;
5060                if let Some(mesh)=crate::gfx::shapes::build(kind,[cx,cy,cz,sx,sy,sz,rx,ry,rz],e0,e1,e2){
5061                    let mut gfx=self.gfx.borrow_mut();
5062                    gfx.emit_mesh(&mesh,mode);
5063                }
5064                return Ok(Value::Unit);
5065            }
5066
5067            _ => {}
5068        }
5069
5070        // User-defined function
5071        if let Some(def) = self.functions.get(name).cloned() {
5072            // Clone the pre-evaluated global seed (built once in run_program) and
5073            // add the params. Globals are immutable after load, so re-evaluating
5074            // them on every call was pure waste — this is the hot-path fix.
5075            let mut call_env = self.global_seed.clone();
5076            let _ = env; // call-site locals are intentionally NOT visible to fns
5077            for (param, arg) in def.params.iter().zip(args) {
5078                call_env.insert(param.clone(), arg);
5079            }
5080            return match self.framed(name, |me| me.exec_block(&def.body, &mut call_env)) {
5081                Ok(v) => Ok(v.unwrap_or(Value::Unit)),
5082                Err(EvalErr::Return(v)) => Ok(v),
5083                Err(e) => Err(e),
5084            };
5085        }
5086
5087        // `form` struct constructor: positional `Name(v0, v1, ...)`.
5088        if let Some(field_names) = self.structs.get(name).cloned() {
5089            if args.len() != field_names.len() {
5090                return Err(EvalErr::from(format!(
5091                    "{name} expects {} field(s), got {}", field_names.len(), args.len())));
5092            }
5093            let fields = field_names.into_iter().zip(args).collect();
5094            return Ok(Value::Struct { name: name.to_string(), fields });
5095        }
5096
5097        // `choose` enum variant constructor: `Variant(...)` or `Enum::Variant(...)`.
5098        if let Some((enum_name, arity)) = self.enum_variants.get(name).cloned() {
5099            if args.len() != arity {
5100                return Err(EvalErr::from(format!(
5101                    "{name} expects {arity} value(s), got {}", args.len())));
5102            }
5103            let variant = name.rsplit("::").next().unwrap_or(name).to_string();
5104            return Ok(Value::Variant { enum_name, variant, payload: args });
5105        }
5106
5107        Err(EvalErr::from(format!("unknown function '{name}'")))
5108    }
5109
5110    fn call_value(&mut self, v: Value, args: Vec<Value>) -> EvalResult {
5111        match v {
5112            Value::Fn(params, body, mut captured) => {
5113                for (p, a) in params.iter().zip(args) {
5114                    captured.insert(p.clone(), a);
5115                }
5116                match self.framed("<closure>", |me| me.exec_block(&body, &mut captured)) {
5117                    Ok(v) => Ok(v.unwrap_or(Value::Unit)),
5118                    Err(EvalErr::Return(v)) => Ok(v),
5119                    Err(e) => Err(e),
5120                }
5121            }
5122            other => Err(EvalErr::from(format!("cannot call {:?}", other))),
5123        }
5124    }
5125
5126    fn call_method(&self, recv: Value, method: &str, args: Vec<Value>) -> EvalResult {
5127        match (&recv, method) {
5128            (Value::Str(s), "is_empty" | "是空") => Ok(Value::Bool(s.is_empty())),
5129            (Value::Str(s), "len" | "长")        => Ok(Value::Number(s.len() as f64)),
5130            (Value::Str(s), "to_string" | "转文") => Ok(Value::Str(s.clone())),
5131            (Value::Str(s), "contains" | "包含") => {
5132                if let Some(Value::Str(sub)) = args.first() {
5133                    Ok(Value::Bool(s.contains(sub.as_str())))
5134                } else { Ok(Value::Bool(false)) }
5135            }
5136            (Value::Str(s), "push_str" | "推_文") => {
5137                let mut s2 = s.clone();
5138                if let Some(Value::Str(a)) = args.first() { s2.push_str(a); }
5139                Ok(Value::Str(s2))
5140            }
5141            (Value::List(v), "len" | "长") => Ok(Value::Number(v.len() as f64)),
5142            (Value::List(v), "push" | "推") => {
5143                let mut v2 = v.clone();
5144                if let Some(a) = args.first() { v2.push(a.clone()); }
5145                Ok(Value::List(v2))
5146            }
5147            // `form` field access: `point.x` (no-arg method == field read).
5148            (Value::Struct { fields, .. }, _) if args.is_empty() => {
5149                fields.iter().find(|(k, _)| k == method).map(|(_, v)| v.clone())
5150                    .ok_or_else(|| EvalErr::from(format!("no field '{method}' on {recv}")))
5151            }
5152            // Enum introspection: `.tag` → variant name, `.is(Name)` not needed for now.
5153            (Value::Variant { variant, .. }, "tag" | "标签" | "タグ" | "태그" | "ป้าย") if args.is_empty() =>
5154                Ok(Value::Str(variant.clone())),
5155            (Value::Ok(inner), _) | (Value::Err(inner), _) => Ok(*inner.clone()),
5156            _ => Err(EvalErr::from(format!("no method '{method}' on {recv}"))),
5157        }
5158    }
5159
5160    // ─── Pattern matching ─────────────────────────────────────────────────────
5161
5162    fn match_pattern(&self, pat: &Pattern, val: &Value) -> Option<Env> {
5163        match (pat, val) {
5164            (Pattern::Wildcard, _) => Some(Env::new()),
5165            (Pattern::Str(s), Value::Str(v)) if s == v => Some(Env::new()),
5166            (Pattern::Number(n), Value::Number(v)) if (n - v).abs() < 1e-12 => Some(Env::new()),
5167            (Pattern::Bool(b), Value::Bool(v)) if b == v => Some(Env::new()),
5168            (Pattern::Ident(name), _) => {
5169                let mut e = Env::new();
5170                e.insert(name.clone(), val.clone());
5171                Some(e)
5172            }
5173            (Pattern::Constructor(ctor, inner_pat), _) => {
5174                let (matches, inner_val) = match (ctor.as_str(), val) {
5175                    ("ok"  | "好", Value::Ok(v))  => (true, Some(v.as_ref().clone())),
5176                    ("bad" | "坏", Value::Err(v)) => (true, Some(v.as_ref().clone())),
5177                    ("ok"  | "好", v) if !matches!(v, Value::Err(_)) => (true, Some(v.clone())),
5178                    _ => (false, None),
5179                };
5180                if !matches { return None; }
5181                match (inner_pat, inner_val) {
5182                    (Some(p), Some(v)) => self.match_pattern(p, &v),
5183                    (None, _)          => Some(Env::new()),
5184                    (Some(p), None)    => self.match_pattern(p, &Value::Unit),
5185                }
5186            }
5187            // User enum variant pattern: `Circle(r)`, `Pair(a, b)`, nullary `Origin()`.
5188            (Pattern::Variant(vname, sub_pats), Value::Variant { variant, payload, .. }) => {
5189                if vname != variant || sub_pats.len() != payload.len() { return None; }
5190                let mut bindings = Env::new();
5191                for (p, v) in sub_pats.iter().zip(payload.iter()) {
5192                    bindings.extend(self.match_pattern(p, v)?);
5193                }
5194                Some(bindings)
5195            }
5196            // A zero-payload variant pattern also matches the bare result-style `ok`/`bad`
5197            // values so `Ok()`-style patterns keep working uniformly.
5198            (Pattern::Variant(vname, sub), Value::Ok(v)) if (vname == "ok" || vname == "好") => {
5199                match sub.as_slice() {
5200                    []  => Some(Env::new()),
5201                    [p] => self.match_pattern(p, v),
5202                    _   => None,
5203                }
5204            }
5205            (Pattern::Variant(vname, sub), Value::Err(v)) if (vname == "bad" || vname == "坏" || vname == "err") => {
5206                match sub.as_slice() {
5207                    []  => Some(Env::new()),
5208                    [p] => self.match_pattern(p, v),
5209                    _   => None,
5210                }
5211            }
5212            _ => None,
5213        }
5214    }
5215
5216    // ─── Utilities ───────────────────────────────────────────────────────────
5217
5218    fn value_to_iter(&self, val: Value) -> Result<Vec<Value>, EvalErr> {
5219        match val {
5220            Value::List(v)   => Ok(v),
5221            Value::Str(s)    => Ok(s.chars().map(|c| Value::Str(c.to_string())).collect()),
5222            Value::Number(n) => Ok((0..n as i64).map(|i| Value::Number(i as f64)).collect()),
5223            other => Err(EvalErr::from(format!("cannot iterate over {:?}", other))),
5224        }
5225    }
5226
5227    fn is_truthy(&self, val: &Value) -> bool {
5228        match val {
5229            Value::Bool(b)     => *b,
5230            Value::Unit        => false,
5231            Value::Number(n)   => *n != 0.0,
5232            Value::Str(s)      => !s.is_empty(),
5233            Value::List(v)     => !v.is_empty(),
5234            Value::Ok(_)       => true,
5235            Value::Err(_)      => false,
5236            Value::Fn(_, _, _) => true,
5237            Value::Struct { .. }  => true,
5238            Value::Variant { .. } => true,
5239        }
5240    }
5241
5242    fn to_number(&self, val: &Value) -> Result<f64, EvalErr> {
5243        match val {
5244            Value::Number(n) => Ok(*n),
5245            Value::Str(s)    => s.parse().map_err(|_| EvalErr::from(format!("cannot convert '{s}' to number"))),
5246            other => Err(EvalErr::from(format!("expected number, got {:?}", other))),
5247        }
5248    }
5249
5250    /// Get the n-th argument as f64, falling back to `default` if missing.
5251    fn arg_num(&self, args: &[Value], n: usize, default: f64) -> Result<f64, EvalErr> {
5252        match args.get(n) {
5253            Some(v) => self.to_number(v),
5254            None    => Ok(default),
5255        }
5256    }
5257
5258    fn arg_str(&self, args: &[Value], n: usize, default: &str) -> String {
5259        args.get(n).map(|v| v.to_string()).unwrap_or_else(|| default.to_string())
5260    }
5261
5262    /// Read a list-of-numbers argument as `Vec<f32>` (empty if absent/not a list).
5263    #[allow(dead_code)]
5264    fn arg_list_f32(&self, args: &[Value], n: usize) -> Vec<f32> {
5265        match args.get(n) {
5266            Some(Value::List(v)) => v.iter().filter_map(|x| match x {
5267                Value::Number(n) => Some(*n as f32),
5268                _ => None,
5269            }).collect(),
5270            _ => Vec::new(),
5271        }
5272    }
5273
5274    /// Optional `r,g,b` colour override starting at arg `i` → packed 0x00RRGGBB,
5275    /// or `default` if those three numeric args aren't present.
5276    #[cfg(not(target_arch = "wasm32"))]
5277    fn color_at(&self, args: &[Value], i: usize, default: u32) -> u32 {
5278        match (args.get(i), args.get(i + 1), args.get(i + 2)) {
5279            (Some(a), Some(b), Some(c)) => match (self.to_number(a), self.to_number(b), self.to_number(c)) {
5280                (Ok(r), Ok(g), Ok(bl)) =>
5281                    ((r as u32 & 0xFF) << 16) | ((g as u32 & 0xFF) << 8) | (bl as u32 & 0xFF),
5282                _ => default,
5283            },
5284            _ => default,
5285        }
5286    }
5287
5288    /// A pitch argument: a note-name string (`"C4"`, `"A#3"`) or a numeric MIDI value.
5289    #[cfg(not(target_arch = "wasm32"))]
5290    fn pitch_arg(&self, args: &[Value], i: usize, default: i32) -> i32 {
5291        match args.get(i) {
5292            Some(Value::Str(s)) => ling_music::note::parse_pitch(s).unwrap_or(default),
5293            Some(Value::Number(n)) => *n as i32,
5294            _ => default,
5295        }
5296    }
5297
5298    /// Current mouse position + left-button-down (native window only).
5299    #[cfg(not(target_arch = "wasm32"))]
5300    fn mouse_now(&self) -> (f32, f32, bool) {
5301        let gfx = self.gfx.borrow();
5302        let (mx, my) = gfx.window.as_ref()
5303            .and_then(|w| w.get_mouse_pos(minifb::MouseMode::Clamp)).unwrap_or((0.0, 0.0));
5304        let down = gfx.window.as_ref()
5305            .map(|w| w.get_mouse_down(minifb::MouseButton::Left)).unwrap_or(false);
5306        (mx, my, down)
5307    }
5308
5309    /// Rasterize a UI [`ling_ui::widgets::Draw`] into the framebuffer: filled
5310    /// polygons via the AA scanline fill, polylines via AA lines, honouring the
5311    /// current blend mode.
5312    #[cfg(not(target_arch = "wasm32"))]
5313    fn draw_ui(&self, d: &ling_ui::widgets::Draw) {
5314        let mut gfx = self.gfx.borrow_mut();
5315        let (w, h, add) = (gfx.width, gfx.height, gfx.blend == 1);
5316        for (c, poly) in &d.fills {
5317            crate::gfx::raster::fill_contours_aa(&mut gfx.buffer, w, h, *c, add, std::slice::from_ref(poly));
5318        }
5319        for (c, pl) in &d.strokes {
5320            for s in pl.windows(2) {
5321                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]);
5322            }
5323        }
5324    }
5325
5326    /// Parse (dst_x, dst_y, width, height) from the first four args of a tex_* builtin.
5327    fn tex_rect(&self, args: &[Value]) -> Result<(usize, usize, usize, usize), EvalErr> {
5328        let tx = self.arg_num(args, 0, 0.0)? as usize;
5329        let ty = self.arg_num(args, 1, 0.0)? as usize;
5330        let tw = self.arg_num(args, 2, 256.0)? as usize;
5331        let th = self.arg_num(args, 3, 256.0)? as usize;
5332        Ok((tx, ty, tw.max(1), th.max(1)))
5333    }
5334
5335    fn apply_binop(&self, op: &BinOp, l: Value, r: Value) -> EvalResult {
5336        match op {
5337            BinOp::Add => match (l, r) {
5338                (Value::Number(a), Value::Number(b)) => Ok(Value::Number(a + b)),
5339                (Value::Str(a), Value::Str(b))       => Ok(Value::Str(a + &b)),
5340                (Value::Str(a), b)                   => Ok(Value::Str(a + &b.to_string())),
5341                (a, Value::Str(b))                   => Ok(Value::Str(a.to_string() + &b)),
5342                (a, b) => Err(EvalErr::from(format!("cannot add {:?} and {:?}", a, b))),
5343            },
5344            BinOp::Sub => Ok(Value::Number(self.to_number(&l)? - self.to_number(&r)?)),
5345            BinOp::Mul => Ok(Value::Number(self.to_number(&l)? * self.to_number(&r)?)),
5346            BinOp::Div => Ok(Value::Number(self.to_number(&l)? / self.to_number(&r)?)),
5347            BinOp::Rem => Ok(Value::Number(self.to_number(&l)? % self.to_number(&r)?)),
5348            BinOp::Eq  => Ok(Value::Bool(values_equal(&l, &r))),
5349            BinOp::Ne  => Ok(Value::Bool(!values_equal(&l, &r))),
5350            BinOp::Lt  => Ok(Value::Bool(self.to_number(&l)? < self.to_number(&r)?)),
5351            BinOp::Gt  => Ok(Value::Bool(self.to_number(&l)? > self.to_number(&r)?)),
5352            BinOp::Le  => Ok(Value::Bool(self.to_number(&l)? <= self.to_number(&r)?)),
5353            BinOp::Ge  => Ok(Value::Bool(self.to_number(&l)? >= self.to_number(&r)?)),
5354            BinOp::And => Ok(Value::Bool(self.is_truthy(&l) && self.is_truthy(&r))),
5355            BinOp::Or  => Ok(Value::Bool(self.is_truthy(&l) || self.is_truthy(&r))),
5356        }
5357    }
5358
5359    fn builtin_format(&self, args: &[Value]) -> Result<String, EvalErr> {
5360        if args.is_empty() { return Ok(String::new()); }
5361        let fmt = match &args[0] {
5362            Value::Str(s) => s.clone(),
5363            other => return Ok(other.to_string()),
5364        };
5365
5366        let mut result = String::new();
5367        let mut arg_idx = 1usize;
5368        let mut chars = fmt.chars().peekable();
5369        while let Some(c) = chars.next() {
5370            if c == '{' {
5371                if chars.peek() == Some(&'}') {
5372                    chars.next();
5373                    if arg_idx < args.len() {
5374                        result.push_str(&args[arg_idx].to_string());
5375                        arg_idx += 1;
5376                    }
5377                } else {
5378                    let mut spec = String::new();
5379                    for ch in chars.by_ref() {
5380                        if ch == '}' { break; }
5381                        spec.push(ch);
5382                    }
5383                    if arg_idx < args.len() {
5384                        if spec.starts_with(":.") {
5385                            if let Value::Number(n) = &args[arg_idx] {
5386                                let prec: usize = spec[2..].trim_end_matches('f')
5387                                    .parse().unwrap_or(2);
5388                                result.push_str(&format!("{:.prec$}", n));
5389                                arg_idx += 1;
5390                                continue;
5391                            }
5392                        }
5393                        result.push_str(&args[arg_idx].to_string());
5394                        arg_idx += 1;
5395                    }
5396                }
5397            } else {
5398                result.push(c);
5399            }
5400        }
5401        Ok(result)
5402    }
5403}
5404
5405#[cfg(not(target_arch = "wasm32"))]
5406fn str_to_minifb_key(name: &str) -> Option<minifb::Key> {
5407    use minifb::Key;
5408    Some(match name {
5409        "numpad0" | "kp0" => Key::NumPad0,
5410        "numpad1" | "kp1" => Key::NumPad1,
5411        "numpad2" | "kp2" => Key::NumPad2,
5412        "numpad3" | "kp3" => Key::NumPad3,
5413        "numpad4" | "kp4" => Key::NumPad4,
5414        "numpad5" | "kp5" => Key::NumPad5,
5415        "numpad6" | "kp6" => Key::NumPad6,
5416        "numpad7" | "kp7" => Key::NumPad7,
5417        "numpad8" | "kp8" => Key::NumPad8,
5418        "numpad9" | "kp9" => Key::NumPad9,
5419        "numpad+" | "kp+" => Key::NumPadPlus,
5420        "numpad-" | "kp-" => Key::NumPadMinus,
5421        "numpad*" | "kp*" => Key::NumPadAsterisk,
5422        "numpad/" | "kp/" => Key::NumPadSlash,
5423        "left"   => Key::Left,
5424        "right"  => Key::Right,
5425        "up"     => Key::Up,
5426        "down"   => Key::Down,
5427        "space"  => Key::Space,
5428        "enter"  => Key::Enter,
5429        "escape" => Key::Escape,
5430        "pageup" => Key::PageUp,
5431        "pagedown" => Key::PageDown,
5432        "lshift" | "leftshift"  => Key::LeftShift,
5433        "rshift" | "rightshift" => Key::RightShift,
5434        "lctrl"  | "leftctrl"   => Key::LeftCtrl,
5435        "rctrl"  | "rightctrl"  => Key::RightCtrl,
5436        "lalt"   | "leftalt"    => Key::LeftAlt,
5437        "ralt"   | "rightalt"   => Key::RightAlt,
5438        "tab"    => Key::Tab,
5439        "backspace" => Key::Backspace,
5440        "delete" => Key::Delete,
5441        "insert" => Key::Insert,
5442        "home"   => Key::Home,
5443        "end"    => Key::End,
5444        "a" => Key::A, "b" => Key::B, "c" => Key::C, "d" => Key::D,
5445        "e" => Key::E, "f" => Key::F, "g" => Key::G, "h" => Key::H,
5446        "i" => Key::I, "j" => Key::J, "k" => Key::K, "l" => Key::L,
5447        "m" => Key::M, "n" => Key::N, "o" => Key::O, "p" => Key::P,
5448        "q" => Key::Q, "r" => Key::R, "s" => Key::S, "t" => Key::T,
5449        "u" => Key::U, "v" => Key::V, "w" => Key::W, "x" => Key::X,
5450        "y" => Key::Y, "z" => Key::Z,
5451        "0" => Key::Key0, "1" => Key::Key1, "2" => Key::Key2,
5452        "3" => Key::Key3, "4" => Key::Key4, "5" => Key::Key5,
5453        "6" => Key::Key6, "7" => Key::Key7, "8" => Key::Key8,
5454        "9" => Key::Key9,
5455        _ => return None,
5456    })
5457}
5458
5459fn values_equal(a: &Value, b: &Value) -> bool {
5460    match (a, b) {
5461        (Value::Number(x), Value::Number(y)) => (x - y).abs() < 1e-12,
5462        (Value::Str(x), Value::Str(y))       => x == y,
5463        (Value::Bool(x), Value::Bool(y))     => x == y,
5464        (Value::Unit, Value::Unit)            => true,
5465        _ => false,
5466    }
5467}
5468
5469// Rasteriser functions live in crate::gfx::raster — imported at top of file.
5470
5471// ── Window platform helpers ────────────────────────────────────────────────────
5472
5473/// Hide the console window that the OS auto-attaches to console-subsystem
5474/// processes. No-op on non-Windows and when no console is present.
5475#[cfg(not(target_arch = "wasm32"))]
5476fn hide_console_window() {
5477    #[cfg(windows)]
5478    unsafe {
5479        extern "system" {
5480            fn GetConsoleWindow() -> isize;
5481            fn ShowWindow(hwnd: isize, nCmdShow: i32) -> i32;
5482        }
5483        let hwnd = GetConsoleWindow();
5484        if hwnd != 0 {
5485            ShowWindow(hwnd, 0); // SW_HIDE = 0
5486        }
5487    }
5488}
5489
5490/// Strip *all* window chrome from `hwnd` and make it cover the whole primary
5491/// monitor (0,0 → screen_w × screen_h), above the taskbar. This turns the
5492/// minifb window into a true borderless-fullscreen surface: no title bar, no
5493/// frame, no resize grips — there is no visible window "handle" left.
5494#[cfg(all(not(target_arch = "wasm32"), windows))]
5495fn make_borderless_fullscreen(hwnd: isize, screen_w: i32, screen_h: i32) {
5496    if hwnd == 0 {
5497        return;
5498    }
5499    unsafe {
5500        extern "system" {
5501            fn SetWindowLongPtrW(hwnd: isize, index: i32, new: isize) -> isize;
5502            fn SetWindowPos(hwnd: isize, insert_after: isize,
5503                            x: i32, y: i32, cx: i32, cy: i32,
5504                            flags: u32) -> i32;
5505            fn ShowWindow(hwnd: isize, cmd: i32) -> i32;
5506        }
5507        const GWL_STYLE:   i32 = -16;
5508        const GWL_EXSTYLE: i32 = -20;
5509        // WS_POPUP (0x80000000) | WS_VISIBLE (0x10000000) — a bare top-level
5510        // window with no caption, border, or system menu.
5511        SetWindowLongPtrW(hwnd, GWL_STYLE, 0x9000_0000isize);
5512        // Clear extended edges (WS_EX_WINDOWEDGE / CLIENTEDGE / DLGMODALFRAME).
5513        SetWindowLongPtrW(hwnd, GWL_EXSTYLE, 0);
5514        // HWND_TOPMOST = -1; SWP_FRAMECHANGED (0x0020) | SWP_SHOWWINDOW (0x0040).
5515        SetWindowPos(hwnd, -1isize, 0, 0, screen_w, screen_h, 0x0020 | 0x0040);
5516        ShowWindow(hwnd, 3); // SW_MAXIMIZE-equivalent paint; 3 = SW_SHOWMAXIMIZED
5517    }
5518}
5519
5520/// Primary-monitor resolution and refresh rate as `(width, height, hz)`.
5521/// `hz` falls back to 60 when the driver reports an unknown/`default` rate.
5522#[cfg(all(not(target_arch = "wasm32"), windows))]
5523fn monitor_info() -> (i32, i32, i32) {
5524    unsafe {
5525        extern "system" {
5526            fn GetSystemMetrics(index: i32) -> i32;
5527            fn GetDC(hwnd: isize) -> isize;
5528            fn ReleaseDC(hwnd: isize, hdc: isize) -> i32;
5529            fn GetDeviceCaps(hdc: isize, index: i32) -> i32;
5530        }
5531        let w = GetSystemMetrics(0).max(1); // SM_CXSCREEN
5532        let h = GetSystemMetrics(1).max(1); // SM_CYSCREEN
5533        let hdc = GetDC(0);
5534        let mut hz = if hdc != 0 { GetDeviceCaps(hdc, 116) } else { 0 }; // VREFRESH
5535        if hdc != 0 {
5536            ReleaseDC(0, hdc);
5537        }
5538        if hz <= 1 {
5539            hz = 60; // 0 or 1 means "device default" → assume 60 Hz
5540        }
5541        (w, h, hz)
5542    }
5543}
5544
5545/// Non-Windows native fallback: resolution from [`native_screen_size`], 60 Hz.
5546#[cfg(all(not(target_arch = "wasm32"), not(windows)))]
5547fn monitor_info() -> (i32, i32, i32) {
5548    let (w, h) = native_screen_size();
5549    (w as i32, h as i32, 60)
5550}
5551
5552/// WASM fallback: the canvas is the display surface; assume 60 Hz.
5553#[cfg(target_arch = "wasm32")]
5554fn monitor_info() -> (i32, i32, i32) {
5555    let (w, h) = crate::gfx::webgl::canvas_size();
5556    (w as i32, h as i32, 60)
5557}
5558
5559/// Query the primary display resolution on non-Windows platforms.
5560/// Falls back to 1920×1080 if the size cannot be determined.
5561#[cfg(all(not(target_arch = "wasm32"), not(windows)))]
5562fn native_screen_size() -> (f64, f64) {
5563    // On Linux/macOS we don't have an easy dependency-free call; return a
5564    // sensible default. Callers can always pass explicit dimensions.
5565    (1920.0, 1080.0)
5566}