ling-lang 2030.1.13

Ling - The Omniglot Systems Language
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
// src/runtime/mod.rs — tree-walking interpreter with graphics support
use std::cell::RefCell;
use std::collections::HashMap;
use crate::parser::ast::*;
use crate::gfx::{GfxState, Light};
#[cfg(not(target_arch = "wasm32"))]
use crate::gfx::raster::{fill_triangle, draw_line};
#[cfg(not(target_arch = "wasm32"))]
use ling_audio::{AudioEngine, ToneParams, Wave};

#[cfg(not(target_arch = "wasm32"))]
use ling_audio::FftAnalyzer;

#[cfg(not(target_arch = "wasm32"))]
use ling_mic;

// ─── Values ──────────────────────────────────────────────────────────────────

#[derive(Debug, Clone)]
pub enum Value {
    Str(String),
    Number(f64),
    Bool(bool),
    Unit,
    List(Vec<Value>),
    Ok(Box<Value>),
    Err(Box<Value>),
    Fn(Vec<String>, Vec<Stmt>, Env),
}

type Env = HashMap<String, Value>;

impl std::fmt::Display for Value {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Value::Str(s)    => write!(f, "{s}"),
            Value::Number(n) => {
                if n.fract() == 0.0 && n.abs() < 1e15 { write!(f, "{}", *n as i64) }
                else { write!(f, "{n}") }
            }
            Value::Bool(b)   => write!(f, "{b}"),
            Value::Unit      => write!(f, "()"),
            Value::List(v)   => {
                write!(f, "[")?;
                for (i, x) in v.iter().enumerate() {
                    if i > 0 { write!(f, ", ")?; }
                    write!(f, "{x}")?;
                }
                write!(f, "]")
            }
            Value::Ok(v)     => write!(f, "Ok({v})"),
            Value::Err(v)    => write!(f, "Err({v})"),
            Value::Fn(_, _, _) => write!(f, "<fn>"),
        }
    }
}

// ─── Control flow ────────────────────────────────────────────────────────────

#[derive(Debug)]
enum EvalErr {
    Runtime(String),
    Return(Value),
    #[allow(dead_code)] // reserved for future `break` statement support
    Break,
}

impl From<String> for EvalErr {
    fn from(s: String) -> Self { EvalErr::Runtime(s) }
}

type EvalResult = Result<Value, EvalErr>;

// GfxState is now defined in crate::gfx — see src/gfx/mod.rs.

// ─── SVG writer ───────────────────────────────────────────────────────────────

struct SvgWriter {
    path:     String,
    width:    f64,
    height:   f64,
    elements: Vec<String>,
}

impl SvgWriter {
    fn new(path: String, width: f64, height: f64) -> Self {
        let bg = format!(
            "<rect width=\"{width}\" height=\"{height}\" fill=\"#0a0a0a\"/>"
        );
        Self { path, width, height, elements: vec![bg] }
    }

    fn save(&self) -> std::io::Result<()> {
        let w = self.width;
        let h = self.height;
        let mut out = format!(
            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\
             <svg xmlns=\"http://www.w3.org/2000/svg\" \
             width=\"{w}\" height=\"{h}\" viewBox=\"0 0 {w} {h}\">\n"
        );
        for elem in &self.elements {
            out.push_str("  ");
            out.push_str(elem);
            out.push('\n');
        }
        out.push_str("</svg>\n");
        // Create parent directory if it doesn't exist.
        if let Some(parent) = std::path::Path::new(&self.path).parent() {
            if !parent.as_os_str().is_empty() {
                let _ = std::fs::create_dir_all(parent);
            }
        }
        std::fs::write(&self.path, out.as_bytes())
    }
}

fn hsl_to_hex(h: f64, s: f64, l: f64) -> String {
    let s = s / 100.0;
    let l = l / 100.0;
    let c = (1.0 - (2.0 * l - 1.0).abs()) * s;
    let x = c * (1.0 - ((h / 60.0) % 2.0 - 1.0).abs());
    let m = l - c / 2.0;
    let (r1, g1, b1) = if h < 60.0       { (c, x, 0.0) }
                       else if h < 120.0  { (x, c, 0.0) }
                       else if h < 180.0  { (0.0, c, x) }
                       else if h < 240.0  { (0.0, x, c) }
                       else if h < 300.0  { (x, 0.0, c) }
                       else               { (c, 0.0, x) };
    let r = ((r1 + m) * 255.0).round() as u8;
    let g = ((g1 + m) * 255.0).round() as u8;
    let b = ((b1 + m) * 255.0).round() as u8;
    format!("#{r:02x}{g:02x}{b:02x}")
}

// ─── Procedural texture helpers ───────────────────────────────────────────────

fn tex_hash(x: i32, y: i32, seed: u32) -> f32 {
    let mut h = (x as u32).wrapping_add((y as u32).wrapping_mul(2654435769)).wrapping_add(seed.wrapping_mul(1234567891));
    h ^= h >> 16; h = h.wrapping_mul(0x45d9f3b); h ^= h >> 16;
    h as f32 / u32::MAX as f32
}

fn tex_vnoise(x: f32, y: f32, seed: u32) -> f32 {
    let xi = x.floor() as i32; let yi = y.floor() as i32;
    let sm = |t: f32| t * t * (3.0 - 2.0 * t);
    let xf = sm(x - xi as f32); let yf = sm(y - yi as f32);
    let a = tex_hash(xi, yi, seed); let b = tex_hash(xi+1, yi, seed);
    let c = tex_hash(xi, yi+1, seed); let d = tex_hash(xi+1, yi+1, seed);
    a + (b-a)*xf + (c-a)*yf + (a-b-c+d)*xf*yf
}

fn tex_fbm(x: f32, y: f32, octaves: u32, seed: u32) -> f32 {
    let mut v = 0.0f32; let mut amp = 0.5f32; let mut f = 1.0f32;
    for i in 0..octaves {
        v += tex_vnoise(x * f, y * f, seed.wrapping_add(i * 7919)) * amp;
        amp *= 0.5; f *= 2.0;
    }
    v
}

fn tex_palette(name: &str, t: f32) -> [f32; 3] {
    let (a, b, c, d): ([f32;3],[f32;3],[f32;3],[f32;3]) = match name {
        "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]),
        "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]),
        "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]),
        "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]),
        "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]),
        _             => ([0.5,0.5,0.5],[0.5,0.5,0.5],[1.0,1.0,1.0],[0.0,0.333,0.667]),
    };
    [0,1,2].map(|i| (a[i] + b[i] * (std::f32::consts::TAU * (c[i] * t + d[i])).cos()).clamp(0.0, 1.0))
}

/// Map a physical key to a typed character for ling-ui text input (lowercase).
#[cfg(not(target_arch = "wasm32"))]
fn key_char(k: minifb::Key) -> Option<char> {
    use minifb::Key::*;
    Some(match k {
        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',
        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',
        Key0=>'0',Key1=>'1',Key2=>'2',Key3=>'3',Key4=>'4',Key5=>'5',Key6=>'6',Key7=>'7',Key8=>'8',Key9=>'9',
        Space=>' ', Minus=>'-', Period=>'.',
        _ => return None,
    })
}

/// Lowercase-hex encode bytes (the wire format for crypto values in Ling).
fn hex_encode(bytes: &[u8]) -> String {
    let mut s = String::with_capacity(bytes.len() * 2);
    for b in bytes { s.push_str(&format!("{b:02x}")); }
    s
}

/// Decode a lowercase/uppercase hex string to bytes (ignores malformed tail).
fn hex_decode(s: &str) -> Vec<u8> {
    let s = s.trim();
    (0..s.len() / 2)
        .filter_map(|i| u8::from_str_radix(s.get(i * 2..i * 2 + 2)?, 16).ok())
        .collect()
}

/// Decode a hex string into a fixed 32-byte key (zero-padded / truncated).
fn hex_to_32(s: &str) -> [u8; 32] {
    let v = hex_decode(s);
    let mut out = [0u8; 32];
    let n = v.len().min(32);
    out[..n].copy_from_slice(&v[..n]);
    out
}

fn tex_rgb(r: f32, g: f32, b: f32) -> u32 {
    ((r * 255.0) as u32) << 16 | ((g * 255.0) as u32) << 8 | (b * 255.0) as u32
}

// ─── 3D Perlin Noise (Improved Perlin 2002) ───────────────────────────────────

const PERM: [u8; 512] = [
    151,160,137,91,90,15,131,13,201,95,96,53,194,233,7,225,
    140,36,103,30,69,142,8,99,37,240,21,10,23,190,6,148,
    247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,
    57,177,33,88,237,149,56,87,174,35,63,189,114,56,42,123,
    165,38,72,93,69,139,138,78,149,159,56,89,152,78,61,140,
    63,26,142,76,124,132,72,11,90,44,82,59,96,41,148,126,
    157,13,49,27,176,33,47,14,97,78,71,40,87,183,4,122,
    92,7,72,3,246,17,225,87,91,106,203,190,57,74,76,88,
    207,208,239,170,251,67,77,51,133,69,249,2,127,80,60,159,
    168,81,163,64,143,146,157,56,245,188,182,218,33,16,255,243,
    210,205,12,19,236,95,151,68,23,196,167,126,61,100,93,25,
    115,96,129,79,220,34,42,144,136,70,238,184,20,222,94,11,
    219,224,50,58,10,73,6,36,92,194,211,172,98,145,149,228,
    121,231,200,55,109,141,213,78,169,108,86,244,234,101,122,174,
    8,186,120,37,46,28,166,180,198,232,221,116,31,75,189,139,
    138,112,62,181,102,72,3,246,14,97,53,87,185,134,193,29,
    158,225,248,152,17,105,217,142,148,155,30,135,233,206,85,40,
    223,140,161,137,13,191,230,66,104,153,199,167,147,99,179,92,
    // Duplicate for wrap-around indexing
    151,160,137,91,90,15,131,13,201,95,96,53,194,233,7,225,
    140,36,103,30,69,142,8,99,37,240,21,10,23,190,6,148,
    247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,
    57,177,33,88,237,149,56,87,174,35,63,189,114,56,42,123,
    165,38,72,93,69,139,138,78,149,159,56,89,152,78,61,140,
    63,26,142,76,124,132,72,11,90,44,82,59,96,41,148,126,
    157,13,49,27,176,33,47,14,97,78,71,40,87,183,4,122,
    92,7,72,3,246,17,225,87,91,106,203,190,57,74,76,88,
    207,208,239,170,251,67,77,51,133,69,249,2,127,80,60,159,
    168,81,163,64,143,146,157,56,245,188,182,218,33,16,255,243,
    210,205,12,19,236,95,151,68,23,196,167,126,61,100,93,25,
    115,96,129,79,220,34,42,144,136,70,238,184,20,222,94,11,
    219,224,50,58,10,73,6,36,92,194,211,172,98,145,149,228,
    121,231,200,55,109,141,213,78,169,108,86,244,234,101,122,174,
];

fn fade(t: f32) -> f32 {
    t * t * t * (t * (t * 6.0 - 15.0) + 10.0)
}

fn grad(hash: u8, x: f32, y: f32, z: f32) -> f32 {
    let h = hash & 15;
    let u = if h < 8 { x } else { y };
    let v = if h < 8 { y } else { z };
    (if (h & 1) == 0 { u } else { -u }) + (if (h & 2) == 0 { v } else { -v })
}

fn perlin3(x: f32, y: f32, z: f32) -> f32 {
    let xi = (x.floor() as i32) & 255;
    let yi = (y.floor() as i32) & 255;
    let zi = (z.floor() as i32) & 255;

    let xf = x - x.floor();
    let yf = y - y.floor();
    let zf = z - z.floor();

    let u = fade(xf);
    let v = fade(yf);
    let w = fade(zf);

    let p0 = PERM[xi as usize] as usize;
    let p1 = PERM[((xi + 1) & 255) as usize] as usize;
    let pa = PERM[(p0 + yi as usize) & 255] as usize;
    let pb = PERM[(p0 + ((yi + 1) & 255) as usize) & 255] as usize;
    let pc = PERM[(p1 + yi as usize) & 255] as usize;
    let pd = PERM[(p1 + ((yi + 1) & 255) as usize) & 255] as usize;

    let g000 = grad(PERM[(pa + zi as usize) & 255], xf, yf, zf);
    let g001 = grad(PERM[(pa + ((zi + 1) & 255) as usize) & 255], xf, yf, zf - 1.0);
    let g010 = grad(PERM[(pb + zi as usize) & 255], xf, yf - 1.0, zf);
    let g011 = grad(PERM[(pb + ((zi + 1) & 255) as usize) & 255], xf, yf - 1.0, zf - 1.0);
    let g100 = grad(PERM[(pc + zi as usize) & 255], xf - 1.0, yf, zf);
    let g101 = grad(PERM[(pc + ((zi + 1) & 255) as usize) & 255], xf - 1.0, yf, zf - 1.0);
    let g110 = grad(PERM[(pd + zi as usize) & 255], xf - 1.0, yf - 1.0, zf);
    let g111 = grad(PERM[(pd + ((zi + 1) & 255) as usize) & 255], xf - 1.0, yf - 1.0, zf - 1.0);

    let l00 = g000 + u * (g100 - g000);
    let l01 = g001 + u * (g101 - g001);
    let l10 = g010 + u * (g110 - g010);
    let l11 = g011 + u * (g111 - g011);

    let l0 = l00 + v * (l10 - l00);
    let l1 = l01 + v * (l11 - l01);

    l0 + w * (l1 - l0)
}

fn fast_rand_f64(state: &mut u64) -> f64 {
    *state = state.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
    ((*state >> 32) as u32) as f64 / 4294967296.0
}

// ─── Circle Drawing Primitives ────────────────────────────────────────────────

/// Write one pixel into the framebuffer (normal or additive blend).
#[inline]
fn put_px(buf: &mut [u32], idx: usize, color: u32, blend: u8) {
    if idx >= buf.len() { return; }
    if blend == 0 {
        buf[idx] = color;
    } else {
        let old = buf[idx];
        let r = (((old >> 16) & 255) + ((color >> 16) & 255)).min(255);
        let g = (((old >> 8) & 255) + ((color >> 8) & 255)).min(255);
        let b = ((old & 255) + (color & 255)).min(255);
        buf[idx] = (r << 16) | (g << 8) | b;
    }
}

fn draw_circle_outline(buf: &mut [u32], w: i32, h: i32, cx: i32, cy: i32, r: i32, color: u32, blend: u8) {
    let mut x = 0;
    let mut y = r;
    let mut d = 3 - 2 * r;
    while x <= y {
        plot_circle_points(buf, w, h, cx, cy, x, y, color, blend);
        if d < 0 {
            d += 4 * x + 6;
        } else {
            d += 4 * (x - y) + 10;
            y -= 1;
        }
        x += 1;
    }
}

fn plot_circle_points(buf: &mut [u32], w: i32, h: i32, cx: i32, cy: i32, x: i32, y: i32, color: u32, blend: u8) {
    let points = [(cx+x, cy+y), (cx-x, cy+y), (cx+x, cy-y), (cx-x, cy-y),
                  (cx+y, cy+x), (cx-y, cy+x), (cx+y, cy-x), (cx-y, cy-x)];
    for &(px, py) in &points {
        if px >= 0 && px < w && py >= 0 && py < h {
            put_px(buf, (py * w + px) as usize, color, blend);
        }
    }
}

fn draw_circle_filled(buf: &mut [u32], w: i32, h: i32, cx: i32, cy: i32, r: i32, color: u32, blend: u8) {
    if r <= 0 { return; }
    for dy in -r..=r {
        let dx_max = ((r*r - dy*dy) as f64).sqrt() as i32;
        let py = cy + dy;
        if py < 0 || py >= h { continue; }
        for dx in -dx_max..=dx_max {
            let px = cx + dx;
            if px >= 0 && px < w {
                put_px(buf, (py * w + px) as usize, color, blend);
            }
        }
    }
}

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

    #[test]
    fn filled_circle_actually_writes_pixels() {
        let mut buf = vec![0u32; 100 * 100];
        draw_circle_filled(&mut buf, 100, 100, 50, 50, 10, 0xFF00FF, 0);
        assert_eq!(buf[50 * 100 + 50], 0xFF00FF, "centre pixel must be filled");
        assert_eq!(buf[0], 0, "far corner must stay clear");
        let n = buf.iter().filter(|&&p| p != 0).count();
        assert!(n > 200 && n < 500, "r=10 disc area ≈ 314, got {n}");
    }

    #[test]
    fn circle_outline_writes_a_ring() {
        let mut buf = vec![0u32; 100 * 100];
        draw_circle_outline(&mut buf, 100, 100, 50, 50, 20, 0x00FF00, 0);
        assert_eq!(buf[50 * 100 + 50], 0, "outline must NOT fill the centre");
        assert!(buf.iter().any(|&p| p == 0x00FF00), "outline must draw a ring");
    }

    #[test]
    fn additive_blend_accumulates_channels() {
        let mut buf = vec![0x202020u32; 1];
        put_px(&mut buf, 0, 0x404040, 1);
        assert_eq!(buf[0], 0x606060);
    }
}

// ─── Interpreter ─────────────────────────────────────────────────────────────

/// Customizable colour palette for the vector UI toolkit (packed 0x00RRGGBB).
/// `ui_theme(...)` sets it; every widget falls back to these and accepts a
/// trailing `r,g,b` override.
#[derive(Clone, Copy)]
pub struct UiTheme {
    pub primary: u32,
    pub accent:  u32,
    pub track:   u32,
    pub warn:    u32,
    pub text:    u32,
    pub bg:      u32,
}

impl Default for UiTheme {
    fn default() -> Self {
        Self {
            primary: 0x00D2FF, // holographic cyan
            accent:  0x28FFB4, // mint
            track:   0x2C3E64, // dim slate
            warn:    0xFF5A5A, // alert red
            text:    0xBEEBFF, // pale cyan
            bg:      0x0A1018, // near-black panel
        }
    }
}

pub struct Interpreter {
    globals:   HashMap<String, Expr>,
    functions: HashMap<String, FnDef>,
    _modules:  HashMap<String, Vec<FnDef>>,
    gfx:       RefCell<GfxState>,
    svg:       RefCell<Option<SvgWriter>>,
    /// Directory of the primary source file, for relative `use` resolution.
    pub source_dir: Option<std::path::PathBuf>,
    /// Files already loaded — prevents circular imports.
    loaded_files: std::collections::HashSet<String>,
    /// Optional audio engine — `None` if no audio device is available.
    #[cfg(not(target_arch = "wasm32"))]
    audio:     Option<AudioEngine>,
    #[cfg(not(target_arch = "wasm32"))]
    fft:       RefCell<FftAnalyzer>,
    fft_bands_cache: RefCell<Vec<f32>>,
    /// Real-time clock — initialized at startup
    start_time: std::time::Instant,
    /// Frame counter — incremented at each present()
    frame_num: u64,
    /// Random state for rand() builtin (xorshift)
    rand_state: u64,
    /// Microphone input (Phase 1 audio reactivity)
    #[cfg(not(target_arch = "wasm32"))]
    mic: Option<ling_mic::MicInput>,
    /// Persistent KEM keypairs (knot / hybrid identities), referenced by handle.
    #[cfg(not(target_arch = "wasm32"))]
    crypto_ids: Vec<ling_crypto::KnotIdentity>,
    /// Editable text-input buffer (ling-ui text fields).
    text_buffer: String,
    /// Frame counter for record_frame().
    record_n: u32,
    /// Accumulated microphone samples (for turning sound into crypto donuts).
    #[cfg(not(target_arch = "wasm32"))]
    mic_buffer: Vec<f32>,
    /// Loaded vector UI fonts, referenced by handle (index) from `font_load`.
    #[cfg(not(target_arch = "wasm32"))]
    fonts: Vec<ling_graphics::VectorFont>,
    /// Customizable UI colour palette (set via `ui_theme`).
    ui_theme: UiTheme,
    /// Left-mouse state on the previous frame — for widget click-edge detection.
    mouse_was_down: bool,
    /// Live music engine (decode playback + GM synth) — lazily initialised.
    #[cfg(not(target_arch = "wasm32"))]
    music: Option<ling_music::MusicEngine>,
    #[cfg(not(target_arch = "wasm32"))]
    music_init: bool,
    /// Decoded tracks (for analysis + playback), by `music_load` handle.
    #[cfg(not(target_arch = "wasm32"))]
    tracks: Vec<ling_music::DecodedAudio>,
    /// Parsed `.lrc` lyrics, by `music_lrc` handle.
    #[cfg(not(target_arch = "wasm32"))]
    lyrics: Vec<ling_music::Lyrics>,
    /// Parsed MIDI songs, by `music_midi_load` handle.
    #[cfg(not(target_arch = "wasm32"))]
    midis: Vec<ling_music::MidiSong>,
    /// Soft bodies (deformable balls), by `soft_ball` handle.
    soft_bodies: Vec<ling_physics::soft::SoftBody>,
    /// Rigid-body world (angular dynamics), shared by `rb_*`.
    rigid_world: ling_physics::rigid::PhysicsWorld,
    /// Liquid grids (water/oil), by `liquid_new` handle.
    liquids: Vec<ling_physics::liquid::LiquidGrid>,
}

impl Interpreter {
    pub fn new() -> Self {
        #[cfg(not(target_arch = "wasm32"))]
        let audio = AudioEngine::new()
            .map_err(|e| eprintln!("audio init failed (no sound): {e}"))
            .ok();
        Self {
            globals:   HashMap::new(),
            functions: HashMap::new(),
            _modules:  HashMap::new(),
            gfx:       RefCell::new(GfxState::new()),
            svg:       RefCell::new(None),
            source_dir: None,
            loaded_files: std::collections::HashSet::new(),
            #[cfg(not(target_arch = "wasm32"))]
            audio,
            #[cfg(not(target_arch = "wasm32"))]
            fft: RefCell::new(FftAnalyzer::new(2048, 44100)),
            fft_bands_cache: RefCell::new(vec![]),
            start_time: std::time::Instant::now(),
            frame_num: 0,
            rand_state: 0x123456789ABCDEF,
            #[cfg(not(target_arch = "wasm32"))]
            mic: None,
            #[cfg(not(target_arch = "wasm32"))]
            crypto_ids: Vec::new(),
            text_buffer: String::new(),
            record_n: 0,
            #[cfg(not(target_arch = "wasm32"))]
            mic_buffer: Vec::new(),
            #[cfg(not(target_arch = "wasm32"))]
            fonts: Vec::new(),
            ui_theme: UiTheme::default(),
            mouse_was_down: false,
            #[cfg(not(target_arch = "wasm32"))]
            music: None,
            #[cfg(not(target_arch = "wasm32"))]
            music_init: false,
            #[cfg(not(target_arch = "wasm32"))]
            tracks: Vec::new(),
            #[cfg(not(target_arch = "wasm32"))]
            lyrics: Vec::new(),
            #[cfg(not(target_arch = "wasm32"))]
            midis: Vec::new(),
            soft_bodies: Vec::new(),
            rigid_world: ling_physics::rigid::PhysicsWorld::new(),
            liquids: Vec::new(),
        }
    }

    /// Lazily start the music engine on first use (playback/synth need a device;
    /// analysis/decoding do not). Returns `false` if no audio device is available.
    #[cfg(not(target_arch = "wasm32"))]
    fn ensure_music(&mut self) -> bool {
        if self.music.is_some() { return true; }
        if self.music_init { return false; }
        self.music_init = true;
        match ling_music::MusicEngine::new() {
            Ok(m) => { self.music = Some(m); true }
            Err(e) => { eprintln!("music engine init failed (no music playback): {e}"); false }
        }
    }

    /// Lay out `text` for font `id` at size `px`, returning every glyph contour as
    /// a screen-space polyline (x→right, y→down). `(x, y)` is the text box top-left;
    /// the baseline is placed `ascent*px` below it. Curves are flattened to 0.3 px.
    #[cfg(not(target_arch = "wasm32"))]
    fn font_layout_2d(&mut self, id: usize, x: f32, y: f32, px: f32, text: &str) -> Vec<Vec<[f32; 2]>> {
        let mut out = Vec::new();
        for g in self.font_layout_2d_glyphs(id, x, y, px, text) { out.extend(g); }
        out
    }

    /// Same as [`font_layout_2d`] but grouped per glyph (so a fill can apply the
    /// non-zero winding rule within each glyph, preserving interior holes).
    #[cfg(not(target_arch = "wasm32"))]
    fn font_layout_2d_glyphs(&mut self, id: usize, x: f32, y: f32, px: f32, text: &str) -> Vec<Vec<Vec<[f32; 2]>>> {
        let font = &mut self.fonts[id];
        let asc = font.ascent();
        let tol = 0.3 / px;
        let mut pen = 0.0f32;
        let mut glyphs = Vec::new();
        for ch in text.chars() {
            let go = font.glyph_outline(ch, tol);
            let mut contours = Vec::with_capacity(go.polylines.len());
            for pl in &go.polylines {
                let mapped: Vec<[f32; 2]> = pl.iter()
                    .map(|p| [x + (pen + p[0]) * px, y + (asc - p[1]) * px])
                    .collect();
                contours.push(mapped);
            }
            glyphs.push(contours);
            pen += go.advance;
        }
        glyphs
    }

    pub fn run_program(&mut self, program: &Program) -> Result<(), String> {
        for item in &program.items {
            self.register_item("", item)?;
        }
        let entry = self.find_entry()
            .ok_or("no entry point — need `bind start = do {...}` or `ผูก เริ่ม = ทำ {...}`")?;
        // Seed the entry env with non-Do globals so top-level `令` bindings
        // are visible in the main Do block (same two-pass logic as call_named).
        let mut env = Env::new();
        let non_do: Vec<_> = self.globals.iter()
            .filter(|(_, e)| !matches!(e, Expr::Do(_)))
            .map(|(k, e)| (k.clone(), e.clone()))
            .collect();
        let mut pending: Vec<(String, Expr)> = Vec::new();
        for (k, expr) in &non_do {
            let mut tmp = Env::new();
            if let Ok(v) = self.eval_expr(expr, &mut tmp) {
                env.insert(k.clone(), v);
            } else {
                pending.push((k.clone(), expr.clone()));
            }
        }
        for (k, expr) in &pending {
            let mut tmp = env.clone();
            if let Ok(v) = self.eval_expr(expr, &mut tmp) {
                env.insert(k.clone(), v);
            }
        }
        self.eval_expr(&entry, &mut env).map(|_| ()).map_err(|e| match e {
            EvalErr::Runtime(s) => s,
            EvalErr::Return(_)  => "unexpected top-level return".to_string(),
            EvalErr::Break      => "unexpected break at top level".to_string(),
        })
    }

    fn register_item(&mut self, ns: &str, item: &Item) -> Result<(), String> {
        match item {
            Item::Bind(name, expr) => {
                let key = if ns.is_empty() { name.clone() } else { format!("{ns}::{name}") };
                self.globals.insert(key, expr.clone());
            }
            Item::Fn(def) => {
                let key = if ns.is_empty() { def.name.clone() } else { format!("{ns}::{}", def.name) };
                self.functions.insert(key, def.clone());
            }
            Item::Mod(name, body) => {
                let child_ns = if ns.is_empty() { name.clone() } else { format!("{ns}::{name}") };
                for child in body {
                    self.register_item(&child_ns, child)?;
                }
            }
            Item::TypeAlias(_, _) => {}
            Item::Use { path, alias } => {
                self.load_module(path, alias.as_deref(), ns)?;
            }
        }
        Ok(())
    }

    /// Resolve `path` relative to `source_dir`, load and parse it, then
    /// register all its definitions.  If `alias` is given, every name is
    /// prefixed with `<parent_ns>::<alias>`.  Circular imports are silently
    /// skipped.
    fn load_module(&mut self, path: &str, alias: Option<&str>, parent_ns: &str) -> Result<(), String> {
        // Build candidate file paths (.ling extension variants)
        let base_dir = self.source_dir.clone().unwrap_or_else(|| std::path::PathBuf::from("."));
        let raw = std::path::Path::new(path);
        let candidates: Vec<std::path::PathBuf> = vec![
            base_dir.join(format!("{}.ling", path)),
            base_dir.join(format!("{}.灵", path)),
            base_dir.join(format!("{}.령", path)),
            base_dir.join(format!("{}.霊", path)),
            base_dir.join(format!("{}.ลิง", path)),
            // exact path if already has extension
            base_dir.join(raw),
            std::path::PathBuf::from(format!("{}.ling", path)),
            std::path::PathBuf::from(path),
        ];

        let resolved = candidates.into_iter().find(|p| p.exists())
            .ok_or_else(|| format!("use: cannot find module '{path}'"))?;

        let canonical = resolved.canonicalize()
            .unwrap_or_else(|_| resolved.clone())
            .to_string_lossy()
            .to_string();

        // Skip if already loaded (circular import guard)
        if self.loaded_files.contains(&canonical) {
            return Ok(());
        }
        self.loaded_files.insert(canonical.clone());

        let source = std::fs::read_to_string(&resolved)
            .map_err(|e| format!("use: failed to read '{path}': {e}"))?;

        // Save/restore source_dir for nested relative imports
        let prev_dir = self.source_dir.clone();
        self.source_dir = resolved.parent().map(|p| p.to_path_buf());

        let program = crate::parser::parse(&source)
            .map_err(|e| format!("use: parse error in '{path}': {e}"))?;

        // Compute target namespace: parent_ns :: alias (or just alias, or just parent_ns)
        let target_ns = match (parent_ns.is_empty(), alias) {
            (_, Some(a)) if !parent_ns.is_empty() => format!("{parent_ns}::{a}"),
            (_, Some(a)) => a.to_string(),
            (false, None) => parent_ns.to_string(),
            (true,  None) => String::new(),
        };

        for item in &program.items {
            self.register_item(&target_ns, item)?;
        }

        self.source_dir = prev_dir;
        Ok(())
    }

    fn find_entry(&self) -> Option<Expr> {
        // Try all known entry-point names in multiple human languages
        for key in &[
            "start", "main",
            "",
            "เริ่ม",           // Thai
            "시작",
            "начать", "начало",
            "inicio", "comenzar",
            "début", "commencer",
            "anfang", "starten",
            "início",
            "शुरू",
            "ابدأ",
        ] {
            if let Some(e) = self.globals.get(*key) { return Some(e.clone()); }
        }
        self.globals.values().find(|e| matches!(e, Expr::Do(_))).cloned()
    }

    // ─── Expression evaluation ────────────────────────────────────────────────

    fn eval_expr(&mut self, expr: &Expr, env: &mut Env) -> EvalResult {
        match expr {
            Expr::Str(s)    => Ok(Value::Str(s.clone())),
            Expr::Number(n) => Ok(Value::Number(*n)),
            Expr::Bool(b)   => Ok(Value::Bool(*b)),
            Expr::Unit      => Ok(Value::Unit),
            Expr::Array(elems) => {
                let vs: Vec<_> = elems.iter()
                    .map(|e| self.eval_expr(e, env))
                    .collect::<Result<_,_>>()?;
                Ok(Value::List(vs))
            }

            Expr::Ident(name) => self.lookup(name, env),

            Expr::Path(segs) => {
                if segs.len() == 1 { return self.lookup(&segs[0], env); }
                Ok(Value::Str(segs.join("::")))
            }

            Expr::Ref(inner) => self.eval_expr(inner, env),
            Expr::Await(inner) => self.eval_expr(inner, env),

            Expr::Do(stmts) => {
                let mut local = env.clone();
                Ok(self.exec_block(stmts, &mut local)?.unwrap_or(Value::Unit))
            }

            Expr::BinOp(op, lhs, rhs) => {
                let l = self.eval_expr(lhs, env)?;
                let r = self.eval_expr(rhs, env)?;
                self.apply_binop(op, l, r)
            }

            Expr::If { cond, then, elseifs, else_body } => {
                let cond_val = self.eval_expr(cond, env)?;
                if self.is_truthy(&cond_val) {
                    return Ok(self.exec_block(then, env)?.unwrap_or(Value::Unit));
                }
                for (ei_cond, ei_body) in elseifs {
                    let ei_cond_val = self.eval_expr(ei_cond, env)?;
                    if self.is_truthy(&ei_cond_val) {
                        return Ok(self.exec_block(ei_body, env)?.unwrap_or(Value::Unit));
                    }
                }
                if let Some(eb) = else_body {
                    return Ok(self.exec_block(eb, env)?.unwrap_or(Value::Unit));
                }
                Ok(Value::Unit)
            }

            Expr::While { cond, body } => {
                // Run the body directly in the *outer* env so that
                // `bind counter = counter + 1` persists across iterations,
                // which is the expected behaviour in a scripting language.
                loop {
                    let cv = self.eval_expr(cond, env)?;
                    if !self.is_truthy(&cv) { break; }
                    match self.exec_block(body, env) {
                        Ok(_) => {}
                        Err(EvalErr::Break) => break,
                        Err(e) => return Err(e),
                    }
                }
                Ok(Value::Unit)
            }

            Expr::For { var, iter, body } => {
                let iter_val = self.eval_expr(iter, env)?;
                let items = self.value_to_iter(iter_val)?;
                for item in items {
                    let mut local = env.clone();
                    local.insert(var.clone(), item);
                    match self.exec_block(body, &mut local) {
                        Ok(_) => {}
                        Err(EvalErr::Break) => break,
                        Err(e) => return Err(e),
                    }
                }
                Ok(Value::Unit)
            }

            Expr::Match(subject, arms) => {
                let subj = self.eval_expr(subject, env)?;
                for arm in arms {
                    if let Some(bindings) = self.match_pattern(&arm.pattern, &subj) {
                        let mut local = env.clone();
                        local.extend(bindings);
                        return self.eval_expr(&arm.body, &mut local);
                    }
                }
                Ok(Value::Unit)
            }

            Expr::Range(lo, hi) => {
                let lo_v = self.eval_expr(lo, env)?;
                let hi_v = self.eval_expr(hi, env)?;
                let lo_n = self.to_number(&lo_v)? as i64;
                let hi_n = self.to_number(&hi_v)? as i64;
                Ok(Value::List((lo_n..hi_n).map(|i| Value::Number(i as f64)).collect()))
            }

            Expr::Index(base, idx) => {
                let b = self.eval_expr(base, env)?;
                let i = self.eval_expr(idx, env)?;
                let n = self.to_number(&i)? as usize;
                match b {
                    Value::List(v) => v.get(n).cloned()
                        .ok_or_else(|| EvalErr::from(format!("index {n} out of bounds"))),
                    Value::Str(s)  => s.chars().nth(n)
                        .map(|c| Value::Str(c.to_string()))
                        .ok_or_else(|| EvalErr::from(format!("index {n} out of bounds"))),
                    other => Err(EvalErr::from(format!("cannot index {:?}", other))),
                }
            }

            Expr::Call(callee, args) => {
                let arg_vals: Vec<Value> = args.iter()
                    .map(|a| self.eval_expr(a, env))
                    .collect::<Result<_,_>>()?;
                match callee.as_ref() {
                    Expr::Ident(name) => self.call_named(name, arg_vals, env),
                    Expr::Path(segs)  => self.call_named(&segs.join("::"), arg_vals, env),
                    _ => {
                        let v = self.eval_expr(callee, env)?;
                        self.call_value(v, arg_vals)
                    }
                }
            }

            Expr::MethodCall { receiver, method, args } => {
                let recv = self.eval_expr(receiver, env)?;
                let arg_vals: Vec<Value> = args.iter()
                    .map(|a| self.eval_expr(a, env))
                    .collect::<Result<_,_>>()?;
                self.call_method(recv, method, arg_vals)
            }

            Expr::Closure(params, body) => {
                Ok(Value::Fn(params.clone(), vec![Stmt::Expr(*body.clone())], env.clone()))
            }
        }
    }

    // ─── Block execution ─────────────────────────────────────────────────────

    fn exec_block(&mut self, stmts: &[Stmt], env: &mut Env) -> Result<Option<Value>, EvalErr> {
        let mut last: Option<Value> = None;
        for stmt in stmts {
            match stmt {
                Stmt::Bind(name, expr) => {
                    let v = self.eval_expr(expr, env)?;
                    env.insert(name.clone(), v);
                    last = None;
                }
                Stmt::Return(expr) => {
                    let v = self.eval_expr(expr, env)?;
                    return Err(EvalErr::Return(v));
                }
                Stmt::Expr(expr) => {
                    last = Some(self.eval_expr(expr, env)?);
                }
            }
        }
        Ok(last)
    }

    // ─── Dispatch helpers ─────────────────────────────────────────────────────

    fn lookup(&self, name: &str, env: &Env) -> EvalResult {
        if let Some(v) = env.get(name) { return Ok(v.clone()); }
        if self.functions.contains_key(name) {
            let def = &self.functions[name];
            return Ok(Value::Fn(def.params.clone(), def.body.clone(), Env::new()));
        }
        // Math constants usable as plain identifiers (e.g. `sin(pi)`)
        match name {
            "pi" | "π" | "พาย" | "圆周率" | "円周率" | "파이" => return Ok(Value::Number(std::f64::consts::PI)),
            "tau" | "τ" | "双周率" | "タウ" | "타우" | "ทาว"        => return Ok(Value::Number(std::f64::consts::TAU)),
            _ => {}
        }
        Err(EvalErr::from(format!("undefined: '{name}'")))
    }

    fn call_named(&mut self, name: &str, args: Vec<Value>, env: &Env) -> EvalResult {
        match name {
            // ── Print ──
            "print" | "println" | "" | "打印" | "印刷" | "พิมพ์" | "출력" | "вывести" | "imprimir" | "afficher" => {
                let s = args.iter().map(|v| v.to_string()).collect::<Vec<_>>().join("");
                println!("{s}");
                return Ok(Value::Unit);
            }
            // ── Format ──
            "format" | "格式" | "フォーマット" | "서식" | "รูปแบบ" | "форматировать" | "formatear" | "formater" => {
                return Ok(Value::Str(self.builtin_format(&args)?));
            }
            // ── String join / concatenation ──
            "格式::拼接" | "format::join" => {
                match args.first() {
                    Some(Value::List(items)) => {
                        return Ok(Value::Str(items.iter().map(|v| v.to_string()).collect()));
                    }
                    _ => return Ok(Value::Str(self.builtin_format(&args)?)),
                }
            }
            // ── Result constructors ──
            "ok" | "" | "良し" | "좋아" | "โอเค" => {
                let val = args.into_iter().next().unwrap_or(Value::Unit);
                return Ok(Value::Ok(Box::new(val)));
            }
            "bad" | "" | "err" | "悪い" | "나쁨" | "ผิด" => {
                let val = args.into_iter().next().unwrap_or(Value::Unit);
                return Ok(Value::Err(Box::new(val)));
            }
            // ── Vec constructors ──
            "向量::从" | "Vec::from" => {
                if let Some(Value::List(v)) = args.first() {
                    return Ok(Value::List(v.clone()));
                }
                return Ok(Value::List(args));
            }
            "向量::有容量" | "Vec::with_capacity" => return Ok(Value::List(Vec::new())),
            // ── Timer stubs ──
            "计时::获取当前小时" | "Timer::hour" => return Ok(Value::Number(14.0)),
            "计时::现在" | "Timer::now"          => return Ok(Value::Number(1000.0)),
            // ── Sleep ──
            "sleep" | "หยุด" | "นอน" | "sleep_ms" | "睡眠" | "眠る" | "スリープ" | "잠자기" | "" | "流水::睡眠" | "Flow::sleep" => {
                if let Some(ms_val) = args.first() {
                    if let Ok(ms) = self.to_number(ms_val) {
                        std::thread::sleep(std::time::Duration::from_millis(ms as u64));
                    }
                }
                return Ok(Value::Unit);
            }
            // ── Flow::parallel stub ──
            "流水::并行" | "Flow::parallel" => {
                if let Some(Value::Fn(params, body, mut cap)) = args.first().cloned() {
                    let _ = params;
                    match self.exec_block(&body, &mut cap) {
                        Ok(Some(v)) => return Ok(v),
                        Ok(None) => return Ok(Value::Unit),
                        Err(EvalErr::Return(v)) => return Ok(v),
                        Err(e) => return Err(e),
                    }
                }
                return Ok(Value::Unit);
            }

            // ══════════════════════════════════════════════════════════════════
            // MATH BUILTINS  (all args and results are f64)
            // Thai aliases: ไซน์ โคไซน์ แทนเจนต์ รากที่สอง ค่าสัมบูรณ์
            //               ปัดลง ปัดขึ้น ปัดเศษ ตัดทศนิยม ต่ำสุด สูงสุด
            //               จำกัด ยกกำลัง ลอการิทึม พาย
            // ══════════════════════════════════════════════════════════════════

            // ── Trigonometry (input in radians) ──
            "sin" | "ไซน์" | "正弦" | "サイン" | "사인" => {
                return Ok(Value::Number(self.arg_num(&args, 0, 0.0)?.sin()));
            }
            "cos" | "โคไซน์" | "余弦" | "コサイン" | "코사인" => {
                return Ok(Value::Number(self.arg_num(&args, 0, 0.0)?.cos()));
            }

            // ── Hyperbolic functions ──
            // Hyperbolic tangent
            "tanh" | "tanhf" | "双曲正切" | "双曲線正接" | "쌍곡탄젠트" => {
                return Ok(Value::Number(self.arg_num(&args, 0, 0.0)?.tanh()));
            }


            "tan" | "แทนเจนต์" | "正切" | "タンジェント" | "탄젠트" => {
                return Ok(Value::Number(self.arg_num(&args, 0, 0.0)?.tan()));
            }
            "asin" | "arcsin" | "反正弦" | "アークサイン" | "아크사인" | "อาร์กไซน์" => {
                return Ok(Value::Number(self.arg_num(&args, 0, 0.0)?.asin()));
            }
            "acos" | "arccos" | "反余弦" | "アークコサイン" | "아크코사인" | "อาร์กโคไซน์" => {
                return Ok(Value::Number(self.arg_num(&args, 0, 0.0)?.acos()));
            }
            "atan" | "arctan" | "反正切" | "アークタンジェント" | "아크탄젠트" | "อาร์กแทนเจนต์" => {
                return Ok(Value::Number(self.arg_num(&args, 0, 0.0)?.atan()));
            }
            "atan2" | "arctan2" | "反正切2" | "アークタンジェント2" | "아크탄젠트2" => {
                let y = self.arg_num(&args, 0, 0.0)?;
                let x = self.arg_num(&args, 1, 1.0)?;
                return Ok(Value::Number(y.atan2(x)));
            }

            // ── Roots / powers ──
            "sqrt" | "รากที่สอง" | "平方根" | "" | "제곱근" => {
                return Ok(Value::Number(self.arg_num(&args, 0, 0.0)?.sqrt()));
            }
            "cbrt" | "立方根" | "세제곱근" | "รากที่สาม" => {
                return Ok(Value::Number(self.arg_num(&args, 0, 0.0)?.cbrt()));
            }
            "pow" | "ยกกำลัง" | "" | "べき乗" | "거듭제곱" => {
                let base = self.arg_num(&args, 0, 0.0)?;
                let exp  = self.arg_num(&args, 1, 1.0)?;
                return Ok(Value::Number(base.powf(exp)));
            }
            "exp" | "指数" | "指数関数" | "지수" => {
                return Ok(Value::Number(self.arg_num(&args, 0, 0.0)?.exp()));
            }
            "hypot" | "斜边" | "斜辺" | "빗변" => {
                let x = self.arg_num(&args, 0, 0.0)?;
                let y = self.arg_num(&args, 1, 0.0)?;
                return Ok(Value::Number(x.hypot(y)));
            }

            // ── Logarithms ──
            "ln" | "log" | "ลอการิทึม" | "对数" | "対数" | "로그" => {
                return Ok(Value::Number(self.arg_num(&args, 0, 1.0)?.ln()));
            }
            "log2" | "对数2" | "対数2" | "로그2" => {
                return Ok(Value::Number(self.arg_num(&args, 0, 1.0)?.log2()));
            }
            "log10" | "对数10" | "対数10" | "로그10" => {
                return Ok(Value::Number(self.arg_num(&args, 0, 1.0)?.log10()));
            }

            // ── Rounding / truncation ──
            "abs" | "ค่าสัมบูรณ์" | "绝对值" | "绝对" | "絶対値" | "절댓값" | "절대값" => {
                return Ok(Value::Number(self.arg_num(&args, 0, 0.0)?.abs()));
            }
            "floor" | "ปัดลง" | "向下取整" | "下整" | "床関数" | "내림" => {
                return Ok(Value::Number(self.arg_num(&args, 0, 0.0)?.floor()));
            }
            "ceil" | "ปัดขึ้น" | "向上取整" | "上整" | "天井関数" | "올림" => {
                return Ok(Value::Number(self.arg_num(&args, 0, 0.0)?.ceil()));
            }
            "round" | "ปัดเศษ" | "四舍五入" | "四舍" | "四捨五入" | "반올림" => {
                return Ok(Value::Number(self.arg_num(&args, 0, 0.0)?.round()));
            }
            "trunc" | "int" | "ตัดทศนิยม" | "取整" | "整数化" | "整数" | "截整"
                    | "정수화" | "정수" | "切り捨て" | "버림" => {
                return Ok(Value::Number(self.arg_num(&args, 0, 0.0)?.trunc()));
            }
            "fract" | "小数部分" | "小数部" | "소수부" => {
                return Ok(Value::Number(self.arg_num(&args, 0, 0.0)?.fract()));
            }

            // ── min / max / clamp ──
            "min" | "ต่ำสุด" | "最小" | "최솟값" => {
                let a = self.arg_num(&args, 0, 0.0)?;
                let b = self.arg_num(&args, 1, 0.0)?;
                return Ok(Value::Number(a.min(b)));
            }
            "max" | "สูงสุด" | "最大" | "최댓값" => {
                let a = self.arg_num(&args, 0, 0.0)?;
                let b = self.arg_num(&args, 1, 0.0)?;
                return Ok(Value::Number(a.max(b)));
            }
            "clamp" | "จำกัด" | "截取" | "範囲制限" | "범위제한" => {
                let x  = self.arg_num(&args, 0, 0.0)?;
                let lo = self.arg_num(&args, 1, 0.0)?;
                let hi = self.arg_num(&args, 2, 1.0)?;
                return Ok(Value::Number(x.clamp(lo, hi)));
            }

            // ── Constants (also accessible as plain identifiers via lookup) ──
            "pi" | "π" | "พาย" | "圆周率" | "円周率" | "파이" => return Ok(Value::Number(std::f64::consts::PI)),
            "tau" | "τ" | "双周率" | "タウ" | "타우" | "ทาว"        => return Ok(Value::Number(std::f64::consts::TAU)),

            // ══════════════════════════════════════════════════════════════════
            // PHASE 1: DMT TRIP CODER FEATURES
            // ══════════════════════════════════════════════════════════════════

            // ── Step 1: Noise Functions ──
            "vnoise" | "noise2" | "นอยส์2ดี" | "柏林噪声2D" | "バリューノイズ2D" | "값노이즈2D" => {
                let x = self.arg_num(&args, 0, 0.0)? as f32;
                let y = self.arg_num(&args, 1, 0.0)? as f32;
                let seed = self.arg_num(&args, 2, 0.0)? as u32;
                return Ok(Value::Number(tex_vnoise(x, y, seed) as f64));
            }

            "fbm" | "นอยส์ออร์แกนิก" | "分形噪声" | "フラクタルノイズ" | "프랙탈노이즈" => {
                let x = self.arg_num(&args, 0, 0.0)? as f32;
                let y = self.arg_num(&args, 1, 0.0)? as f32;
                let octaves = self.arg_num(&args, 2, 4.0)? as u32;
                let seed = self.arg_num(&args, 3, 0.0)? as u32;
                return Ok(Value::Number(tex_fbm(x, y, octaves, seed) as f64));
            }

            "perlin" | "perlin3" | "เพอร์ลิน3ดี" | "柏林噪声3D" | "パーリンノイズ3D" | "펄린노이즈3D" => {
                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;
                return Ok(Value::Number(perlin3(x, y, z) as f64));
            }

            // ── Step 2: Math Ergonomics ──
            "lerp" | "ค่าระหว่าง" | "线性插值" | "線形補間" | "선형보간" => {
                let a = self.arg_num(&args, 0, 0.0)?;
                let b = self.arg_num(&args, 1, 1.0)?;
                let t = self.arg_num(&args, 2, 0.0)?;
                return Ok(Value::Number(a + (b - a) * t));
            }

            "smoothstep" | "เปลี่ยนแบบนุ่ม" | "平滑步进" | "スムーズステップ" | "스무스스텝" => {
                let lo = self.arg_num(&args, 0, 0.0)?;
                let hi = self.arg_num(&args, 1, 1.0)?;
                let x = self.arg_num(&args, 2, 0.5)?;
                let t = ((x - lo) / (hi - lo)).clamp(0.0, 1.0);
                return Ok(Value::Number(t * t * (3.0 - 2.0 * t)));
            }

            "rand" | "สุ่ม" | "随机" | "乱数" | "난수" => {
                let val = fast_rand_f64(&mut self.rand_state);
                return Ok(Value::Number(val));
            }

            "sign" | "เครื่องหมาย" | "符号" | "符号関数" | "부호" => {
                let x = self.arg_num(&args, 0, 0.0)?;
                return Ok(Value::Number(x.signum()));
            }

            "hsv_to_rgb" | "เอชเอสวีเป็นRGB" | "HSV转RGB" | "HSV変換RGB" | "HSV변환RGB" => {
                let h = self.arg_num(&args, 0, 0.0)?; // 0-360
                let s = self.arg_num(&args, 1, 1.0)?; // 0-1
                let v = self.arg_num(&args, 2, 1.0)?; // 0-1
                let c = v * s;
                let x = c * (1.0 - (((h / 60.0) % 2.0) - 1.0).abs());
                let m = v - c;
                let (r1, g1, b1) = if h < 60.0       { (c, x, 0.0) }
                                    else if h < 120.0  { (x, c, 0.0) }
                                    else if h < 180.0  { (0.0, c, x) }
                                    else if h < 240.0  { (0.0, x, c) }
                                    else if h < 300.0  { (x, 0.0, c) }
                                    else               { (c, 0.0, x) };
                let r = ((r1 + m) * 255.0).round();
                let g = ((g1 + m) * 255.0).round();
                let b = ((b1 + m) * 255.0).round();
                return Ok(Value::List(vec![Value::Number(r), Value::Number(g), Value::Number(b)]));
            }

            "lerp_color" | "ไล่สี" | "颜色插值" | "色補間" | "색보간" => {
                let r1 = self.arg_num(&args, 0, 0.0)?;
                let g1 = self.arg_num(&args, 1, 0.0)?;
                let b1 = self.arg_num(&args, 2, 0.0)?;
                let r2 = self.arg_num(&args, 3, 255.0)?;
                let g2 = self.arg_num(&args, 4, 255.0)?;
                let b2 = self.arg_num(&args, 5, 255.0)?;
                let t = self.arg_num(&args, 6, 0.0)?;
                let r = r1 + (r2 - r1) * t;
                let g = g1 + (g2 - g1) * t;
                let b = b1 + (b2 - b1) * t;
                let c = ((r as u32) << 16) | ((g as u32) << 8) | (b as u32);
                self.gfx.borrow_mut().color = c;
                return Ok(Value::Unit);
            }

            // ── Step 3: Real-Time Clock ──
            "time_now" | "เวลาปัจจุบัน" | "当前时间" | "経過時間" | "현재시간" => {
                return Ok(Value::Number(self.start_time.elapsed().as_secs_f64()));
            }

            "frame_count" | "เฟรม" | "帧数" | "フレーム数" | "프레임수" => {
                return Ok(Value::Number(self.frame_num as f64));
            }

            // ── Step 4: Microphone Input ──
            "mic_open" | "เปิดไมค์" | "开麦克风" | "マイク開く" | "마이크열기" => {
                #[cfg(not(target_arch = "wasm32"))]
                {
                    match ling_mic::MicInput::open(Default::default()) {
                        Ok(mic) => {
                            let _ = mic.start(|_samples: &[f32]| {});  // No-op callback
                            self.mic = Some(mic);
                            return Ok(Value::Unit);
                        }
                        Err(e) => return Err(EvalErr::from(format!("mic_open failed: {e}"))),
                    }
                }
                #[cfg(target_arch = "wasm32")]
                return Ok(Value::Unit);
            }

            "mic_rms" | "เสียงRMS" | "麦克风音量" | "マイクRMS" | "마이크RMS" => {
                #[cfg(not(target_arch = "wasm32"))]
                {
                    let rms = self.mic.as_ref().map(|m: &ling_mic::MicInput| m.rms()).unwrap_or(0.0);
                    return Ok(Value::Number(rms as f64));
                }
                #[cfg(target_arch = "wasm32")]
                return Ok(Value::Number(0.0));
            }

            "mic_peak" | "เสียงพีค" | "麦克风峰值" | "マイクピーク" | "마이크피크" => {
                #[cfg(not(target_arch = "wasm32"))]
                {
                    let peak = self.mic.as_ref().map(|m: &ling_mic::MicInput| m.peak()).unwrap_or(0.0);
                    return Ok(Value::Number(peak as f64));
                }
                #[cfg(target_arch = "wasm32")]
                return Ok(Value::Number(0.0));
            }

            "mic_fft" | "วิเคราะห์เสียงสด" | "实时频谱" | "リアルタイムFFT" | "실시간FFT" => {
                #[cfg(not(target_arch = "wasm32"))]
                {
                    let n = self.arg_num(&args, 0, 8.0)? as usize;
                    if let Some(mic) = self.mic.as_ref() {
                        let samples = mic.latest_samples();
                        self.fft.borrow_mut().push_samples(&samples);
                    }
                    let bands = self.fft.borrow().freq_bands(n);
                    let result = bands.iter().map(|&v| Value::Number(v as f64)).collect();
                    return Ok(Value::List(result));
                }
                #[cfg(target_arch = "wasm32")]
                return Ok(Value::List(vec![]));
            }

            // ── Step 5: Additive Blend Mode ──
            "set_blend" | "โหมดผสม" | "混合模式" | "ブレンドモード" | "블렌드모드" => {
                let mode = self.arg_num(&args, 0, 0.0)? as u8;
                self.gfx.borrow_mut().blend = mode;
                return Ok(Value::Unit);
            }

            // ── Step 6: Circle Primitives ──
            "draw_circle" | "วาดวงกลม" | "画圆" | "円描画" | "원그리기" => {
                let cx = self.arg_num(&args, 0, 0.0)? as i32;
                let cy = self.arg_num(&args, 1, 0.0)? as i32;
                let r = self.arg_num(&args, 2, 10.0)? as i32;
                let mut gfx = self.gfx.borrow_mut();
                let (w, h, color, blend) = (gfx.width as i32, gfx.height as i32, gfx.color, gfx.blend);
                draw_circle_outline(&mut gfx.buffer, w, h, cx, cy, r, color, blend);
                return Ok(Value::Unit);
            }

            "draw_filled_circle" | "draw_disc" | "วาดวงกลมทึบ" | "画实心圆" | "塗りつぶし円" | "원채우기" => {
                let cx = self.arg_num(&args, 0, 0.0)? as i32;
                let cy = self.arg_num(&args, 1, 0.0)? as i32;
                let r = self.arg_num(&args, 2, 10.0)? as i32;
                let mut gfx = self.gfx.borrow_mut();
                let (w, h, color, blend) = (gfx.width as i32, gfx.height as i32, gfx.color, gfx.blend);
                draw_circle_filled(&mut gfx.buffer, w, h, cx, cy, r, color, blend);
                return Ok(Value::Unit);
            }

            // ══════════════════════════════════════════════════════════════════
            // GRAPHICS BUILTINS
            // Thai names first, then English aliases.
            // ══════════════════════════════════════════════════════════════════

            // ── เปิดหน้าต่าง(width, height, title) — open_window ──
            "เปิดหน้าต่าง" | "open_window" | "gfx_window" | "开窗" | "ウィンドウ開く" | "창열기" => {
                let w = self.arg_num(&args, 0, 800.0)? as usize;
                let h = self.arg_num(&args, 1, 600.0)? as usize;
                #[cfg(not(target_arch = "wasm32"))]
                {
                    let title = args.get(2).map(|v| v.to_string()).unwrap_or_else(|| "Ling".into());
                    let mut gfx = self.gfx.borrow_mut();
                    let mut win = minifb::Window::new(
                        &title, w, h,
                        minifb::WindowOptions {
                            resize: false,
                            scale: minifb::Scale::X1,
                            ..Default::default()
                        },
                    ).map_err(|e| EvalErr::from(format!("cannot open window: {e}")))?;
                    #[allow(deprecated)]
                    win.limit_update_rate(Some(std::time::Duration::from_millis(8)));
                    gfx.buffer = vec![0u32; w * h];
                    gfx.width  = w;
                    gfx.height = h;
                    gfx.window = Some(win);
                    gfx.sync_projection();
                    hide_console_window();
                }
                #[cfg(target_arch = "wasm32")]
                {
                    let mut gfx = self.gfx.borrow_mut();
                    gfx.width  = w;
                    gfx.height = h;
                    gfx.sync_projection();
                    crate::gfx::webgl::resize(w as u32, h as u32);
                }
                return Ok(Value::Unit);
            }

            // ── เติม(r, g, b) — fill / clear screen with colour ──
            "เติม" | "fill" | "gfx_fill" | "clear" | "" | "塗り潰し" | "채우기" | "" | "消去" | "지우기" => {
                let r = self.arg_num(&args, 0, 0.0)? as u32;
                let g = self.arg_num(&args, 1, 0.0)? as u32;
                let b = self.arg_num(&args, 2, 0.0)? as u32;
                #[cfg(not(target_arch = "wasm32"))]
                {
                    let c = (r << 16) | (g << 8) | b;
                    self.gfx.borrow_mut().buffer.fill(c);
                }
                #[cfg(target_arch = "wasm32")]
                {
                    let mut gfx = self.gfx.borrow_mut();
                    gfx.fill_r = r as f32 / 255.0;
                    gfx.fill_g = g as f32 / 255.0;
                    gfx.fill_b = b as f32 / 255.0;
                }
                return Ok(Value::Unit);
            }

            // ── set_color_hsl(h, s, l) — set drawing colour from HSL ──
            // h: 0–360 degrees, s: 0–100 saturation, l: 0–100 lightness
            "set_color_hsl" | "颜色HSL" | "色相" | "HSL色" | "HSL색설정" | "สีHSLวาด" => {
                let h = self.arg_num(&args, 0, 0.0)?;
                let s = self.arg_num(&args, 1, 70.0)?;
                let l = self.arg_num(&args, 2, 50.0)?;
                let hex = hsl_to_hex(h, s, l);
                let r = u32::from_str_radix(&hex[1..3], 16).unwrap_or(255);
                let g = u32::from_str_radix(&hex[3..5], 16).unwrap_or(255);
                let b = u32::from_str_radix(&hex[5..7], 16).unwrap_or(255);
                self.gfx.borrow_mut().color = (r << 16) | (g << 8) | b;
                return Ok(Value::Unit);
            }

            // ── สีดินสอ(r, g, b) — set drawing colour ──
            "สีดินสอ" | "set_color" | "gfx_color" | "color" | "设色" | "色設定" | "색설정" => {
                let r = self.arg_num(&args, 0, 255.0)? as u32;
                let g = self.arg_num(&args, 1, 255.0)? as u32;
                let b = self.arg_num(&args, 2, 255.0)? as u32;
                self.gfx.borrow_mut().color = (r << 16) | (g << 8) | b;
                return Ok(Value::Unit);
            }

            // ── วาดสามเหลี่ยม(x1,y1, x2,y2, x3,y3) — draw filled triangle ──
            "วาดสามเหลี่ยม" | "draw_triangle" | "gfx_triangle" | "triangle" | "画三角" | "三角形描画" | "삼각형그리기" => {
                let x0 = self.arg_num(&args, 0, 0.0)? as f32;
                let y0 = self.arg_num(&args, 1, 0.0)? as f32;
                let x1 = self.arg_num(&args, 2, 0.0)? as f32;
                let y1 = self.arg_num(&args, 3, 0.0)? as f32;
                let x2 = self.arg_num(&args, 4, 0.0)? as f32;
                let y2 = self.arg_num(&args, 5, 0.0)? as f32;
                let mut gfx = self.gfx.borrow_mut();
                let color = gfx.color;
                #[cfg(not(target_arch = "wasm32"))]
                {
                    let w = gfx.width;
                    let h = gfx.height;
                    fill_triangle(&mut gfx.buffer, w, h, color, x0, y0, x1, y1, x2, y2);
                }
                #[cfg(target_arch = "wasm32")]
                gfx.depth_queue.push_triangle(0.0, color, x0, y0, x1, y1, x2, y2);
                return Ok(Value::Unit);
            }

            // ── วาดเส้น(x1,y1, x2,y2) — draw line ──
            "วาดเส้น" | "draw_line" | "gfx_line" | "line" | "画线" | "線描く" | "선그리기" => {
                let x0 = self.arg_num(&args, 0, 0.0)? as f32;
                let y0 = self.arg_num(&args, 1, 0.0)? as f32;
                let x1 = self.arg_num(&args, 2, 0.0)? as f32;
                let y1 = self.arg_num(&args, 3, 0.0)? as f32;
                let mut gfx = self.gfx.borrow_mut();
                let color = gfx.color;
                #[cfg(not(target_arch = "wasm32"))]
                {
                    let w = gfx.width;
                    let h = gfx.height;
                    draw_line(&mut gfx.buffer, w, h, color, x0, y0, x1, y1);
                }
                #[cfg(target_arch = "wasm32")]
                gfx.depth_queue.push_line(0.0, color, x0, y0, x1, y1);
                return Ok(Value::Unit);
            }

            // ── วาดจุด(x, y) — plot a single pixel ──
            "วาดจุด" | "draw_pixel" | "gfx_pixel" | "pixel" | "画点" | "点描く" | "점그리기" => {
                let px = self.arg_num(&args, 0, 0.0)? as i32;
                let py = self.arg_num(&args, 1, 0.0)? as i32;
                #[cfg(not(target_arch = "wasm32"))]
                {
                    let mut gfx = self.gfx.borrow_mut();
                    let color = gfx.color;
                    let w = gfx.width;
                    let h = gfx.height;
                    if px >= 0 && py >= 0 && (px as usize) < w && (py as usize) < h {
                        gfx.buffer[py as usize * w + px as usize] = color;
                    }
                }
                #[cfg(target_arch = "wasm32")]
                {
                    // Render pixel as a 1×1 square via two triangles.
                    let mut gfx = self.gfx.borrow_mut();
                    let color = gfx.color;
                    let x = px as f32; let y = py as f32;
                    gfx.depth_queue.push_triangle(0.0, color, x, y, x+1.0, y, x+1.0, y+1.0);
                    gfx.depth_queue.push_triangle(0.0, color, x, y, x+1.0, y+1.0, x, y+1.0);
                }
                return Ok(Value::Unit);
            }

            // ── แสดงผล() — flush depth queue, then present frame to screen ──
            "แสดงผล" | "present" | "gfx_present" | "show" | "" | "呈现" | "表示" | "표시" => {
                #[cfg(not(target_arch = "wasm32"))]
                {
                    // Flush depth queue and present — release borrow before reading mouse.
                    {
                        let mut gfx = self.gfx.borrow_mut();
                        if !gfx.depth_queue.is_empty() {
                            let w = gfx.width;
                            let h = gfx.height;
                            let queue = std::mem::take(&mut gfx.depth_queue);
                            queue.flush(&mut gfx.buffer, w, h);
                        }
                        let buf = gfx.buffer.clone();
                        let w   = gfx.width;
                        let h   = gfx.height;
                        if let Some(win) = gfx.window.as_mut() {
                            win.update_with_buffer(&buf, w, h)
                                .map_err(|e| EvalErr::from(format!("present error: {e}")))?;
                        }
                    }
                    // Read mouse AFTER update_with_buffer so events are processed.
                    let mouse_pos = {
                        let gfx = self.gfx.borrow();
                        gfx.window.as_ref()
                            .and_then(|w| w.get_mouse_pos(minifb::MouseMode::Clamp))
                    };
                    let mut gfx = self.gfx.borrow_mut();
                    if gfx.mouse_captured {
                        if let Some((mx, my)) = mouse_pos {
                            if gfx.last_mx.is_nan() {
                                gfx.mouse_dx = 0.0; gfx.mouse_dy = 0.0;
                            } else {
                                gfx.mouse_dx = mx - gfx.last_mx;
                                gfx.mouse_dy = my - gfx.last_my;
                            }
                            gfx.last_mx = mx; gfx.last_my = my;
                        } else {
                            gfx.mouse_dx = 0.0; gfx.mouse_dy = 0.0;
                        }
                        // Clip cursor to window bounds so it can't escape.
                        #[cfg(windows)]
                        unsafe {
                            #[repr(C)]
                            struct RECT { left: i32, top: i32, right: i32, bottom: i32 }
                            extern "system" {
                                fn ClipCursor(lpRect: *const std::ffi::c_void) -> i32;
                                fn GetForegroundWindow() -> isize;
                                fn GetWindowRect(hwnd: isize, lpRect: *mut RECT) -> i32;
                            }
                            let hwnd = GetForegroundWindow();
                            let mut rect = RECT { left: 0, top: 0, right: 0, bottom: 0 };
                            if GetWindowRect(hwnd, &mut rect) != 0 {
                                ClipCursor(&rect as *const RECT as *const std::ffi::c_void);
                            }
                        }
                    } else if let Some((mx, my)) = mouse_pos {
                        if gfx.last_mx.is_nan() {
                            gfx.mouse_dx = 0.0; gfx.mouse_dy = 0.0;
                        } else {
                            gfx.mouse_dx = mx - gfx.last_mx;
                            gfx.mouse_dy = my - gfx.last_my;
                        }
                        gfx.last_mx = mx; gfx.last_my = my;
                    } else {
                        gfx.mouse_dx = 0.0; gfx.mouse_dy = 0.0;
                    }
                }
                #[cfg(target_arch = "wasm32")]
                {
                    let mut gfx = self.gfx.borrow_mut();
                    let w  = gfx.width;
                    let h  = gfx.height;
                    let fr = gfx.fill_r;
                    let fg = gfx.fill_g;
                    let fb = gfx.fill_b;
                    let queue = std::mem::take(&mut gfx.depth_queue);
                    queue.flush_to_webgl(fr, fg, fb, w, h);
                }
                // Update the click-edge latch for interactive UI widgets.
                #[cfg(not(target_arch = "wasm32"))]
                {
                    let (_, _, down) = self.mouse_now();
                    self.mouse_was_down = down;
                }
                // Increment frame counter
                self.frame_num += 1;
                return Ok(Value::Unit);
            }

            // ── เปิดหน้าต่างเต็มจอ(title) — true native-res fullscreen window ──
            "เปิดหน้าต่างเต็มจอ" | "open_fullscreen" | "fullscreen" | "全屏" | "全画面" | "전체화면" => {
                // In WASM the canvas defines the viewport; use its current size
                // as the default so the projection matches what's actually visible.
                #[cfg(target_arch = "wasm32")]
                let (default_w, default_h) = {
                    let (cw, ch) = crate::gfx::webgl::canvas_size();
                    (cw as f64, ch as f64)
                };
                // On native: query the actual primary monitor resolution.
                #[cfg(all(not(target_arch = "wasm32"), windows))]
                let (default_w, default_h) = unsafe {
                    extern "system" { fn GetSystemMetrics(nIndex: i32) -> i32; }
                    (GetSystemMetrics(0) as f64, GetSystemMetrics(1) as f64)
                };
                #[cfg(all(not(target_arch = "wasm32"), not(windows)))]
                let (default_w, default_h) = native_screen_size();

                let w = args.get(1).map(|v| self.to_number(v).unwrap_or(default_w) as usize).unwrap_or(default_w as usize);
                let h = args.get(2).map(|v| self.to_number(v).unwrap_or(default_h) as usize).unwrap_or(default_h as usize);
                #[cfg(not(target_arch = "wasm32"))]
                {
                    let title = args.get(0).map(|v| v.to_string()).unwrap_or_else(|| "Ling".into());
                    let mut gfx = self.gfx.borrow_mut();
                    let mut win = minifb::Window::new(
                        &title, w, h,
                        minifb::WindowOptions {
                            borderless: true,
                            title:      false,
                            resize:     false,
                            scale:      minifb::Scale::X1,
                            ..Default::default()
                        },
                    ).map_err(|e| EvalErr::from(format!("cannot open fullscreen: {e}")))?;
                    #[allow(deprecated)]
                    win.limit_update_rate(Some(std::time::Duration::from_millis(8)));
                    gfx.buffer = vec![0u32; w * h];
                    gfx.width  = w;
                    gfx.height = h;
                    gfx.window = Some(win);
                    gfx.sync_projection();
                    // Snap to top-left, cover full screen, bring above taskbar.
                    #[cfg(windows)]
                    reposition_fullscreen(w as i32, h as i32);
                    hide_console_window();
                }
                #[cfg(target_arch = "wasm32")]
                {
                    let mut gfx = self.gfx.borrow_mut();
                    gfx.width  = w;
                    gfx.height = h;
                    gfx.sync_projection();
                    crate::gfx::webgl::resize(w as u32, h as u32);
                }
                return Ok(Value::Unit);
            }

            // ── ความกว้าง() / ความสูง() — current framebuffer size ──
            "get_width" | "ความกว้าง" | "" | "幅取得" | "너비" => {
                return Ok(Value::Number(self.gfx.borrow().width as f64));
            }
            "get_height" | "ความสูง" | "" | "高取得" | "높이" => {
                return Ok(Value::Number(self.gfx.borrow().height as f64));
            }

            // ── หน้าต่างเปิดอยู่() → bool — is the window still open? ──
            "หน้าต่างเปิดอยู่" | "window_is_open" | "gfx_is_open" | "is_open" | "窗开" | "開いている" | "창열림" => {
                #[cfg(not(target_arch = "wasm32"))]
                {
                    let gfx = self.gfx.borrow();
                    let open = gfx.window.as_ref()
                        .map(|w| w.is_open() && !w.is_key_down(minifb::Key::Escape))
                        .unwrap_or(false);
                    return Ok(Value::Bool(open));
                }
                #[cfg(target_arch = "wasm32")]
                return Ok(Value::Bool(true));
            }

            // ── key_down(name) → bool — is a key held? ──
            "key_down" | "กดค้าง" | "按键" | "キー押す" | "키누름" => {
                #[cfg(not(target_arch = "wasm32"))]
                {
                    let name = self.arg_str(&args, 0, "");
                    let gfx  = self.gfx.borrow();
                    let down = gfx.window.as_ref()
                        .and_then(|w| str_to_minifb_key(&name).map(|k| w.is_key_down(k)))
                        .unwrap_or(false);
                    return Ok(Value::Bool(down));
                }
                #[cfg(target_arch = "wasm32")]
                return Ok(Value::Bool(false));
            }

            // ── key_pressed(name) → bool — was a key pressed this frame? ──
            "key_pressed" | "กดปุ่ม" | "键按" | "キー押した" | "키눌림" => {
                #[cfg(not(target_arch = "wasm32"))]
                {
                    let name = self.arg_str(&args, 0, "");
                    let gfx  = self.gfx.borrow();
                    let pressed = gfx.window.as_ref()
                        .and_then(|w| str_to_minifb_key(&name)
                            .map(|k| w.is_key_pressed(k, minifb::KeyRepeat::No)))
                        .unwrap_or(false);
                    return Ok(Value::Bool(pressed));
                }
                #[cfg(target_arch = "wasm32")]
                return Ok(Value::Bool(false));
            }

            // ── mouse_dx() / mouse_dy() → f64 — delta since last frame ──
            "mouse_dx" | "เมาส์X" | "鼠ΔX" | "マウスΔX" | "마우스ΔX" => {
                #[cfg(not(target_arch = "wasm32"))]
                return Ok(Value::Number(self.gfx.borrow().mouse_dx as f64));
                #[cfg(target_arch = "wasm32")]
                return Ok(Value::Number(0.0));
            }
            "mouse_dy" | "เมาส์Y" | "鼠ΔY" | "マウスΔY" | "마우스ΔY" => {
                #[cfg(not(target_arch = "wasm32"))]
                return Ok(Value::Number(self.gfx.borrow().mouse_dy as f64));
                #[cfg(target_arch = "wasm32")]
                return Ok(Value::Number(0.0));
            }

            // ── set_camera_pos(x, y, z) — move camera to world position ──
            "set_camera_pos" | "ตั้งตำแหน่งกล้อง" | "镜坐标" | "カメラ座標" | "카메라좌표" => {
                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;
                let mut gfx = self.gfx.borrow_mut();
                gfx.camera.tx = x; gfx.camera.ty = y; gfx.camera.tz = z;
                return Ok(Value::Unit);
            }

            // ── move_camera(dx, dy, dz) — translate camera by delta ──
            "move_camera" => {
                let dx = self.arg_num(&args, 0, 0.0)? as f32;
                let dy = self.arg_num(&args, 1, 0.0)? as f32;
                let dz = self.arg_num(&args, 2, 0.0)? as f32;
                let mut gfx = self.gfx.borrow_mut();
                gfx.camera.tx += dx; gfx.camera.ty += dy; gfx.camera.tz += dz;
                return Ok(Value::Unit);
            }

            // ── set_zdist(d) — set perspective z-offset (field-of-view taper) ──
            "set_zdist" | "ตั้งระยะห่าง" | "镜距" | "Z距離設定" | "Z거리설정" => {
                let d = self.arg_num(&args, 0, 5.0)? as f32;
                self.gfx.borrow_mut().camera.zdist = d;
                return Ok(Value::Unit);
            }

            // ── capture_mouse() — hide cursor and warp to centre each frame ──
            "capture_mouse" | "จับเมาส์" | "捕鼠" | "マウス捕捉" | "마우스잡기" => {
                #[cfg(not(target_arch = "wasm32"))]
                {
                    let mut gfx = self.gfx.borrow_mut();
                    gfx.mouse_captured = true;
                    gfx.last_mx = f32::NAN;
                    if let Some(win) = gfx.window.as_mut() {
                        win.set_cursor_visibility(false);
                    }
                }
                return Ok(Value::Unit);
            }

            // ── release_mouse() — restore cursor and remove clip region ──
            "release_mouse" => {
                #[cfg(not(target_arch = "wasm32"))]
                {
                    let mut gfx = self.gfx.borrow_mut();
                    gfx.mouse_captured = false;
                    gfx.last_mx = f32::NAN;
                    if let Some(win) = gfx.window.as_mut() {
                        win.set_cursor_visibility(true);
                    }
                    #[cfg(windows)]
                    unsafe {
                        // Null releases the clip; reuse the RECT-typed declaration above.
                        extern "system" { fn ClipCursor(lpRect: *const std::ffi::c_void) -> i32; }
                        ClipCursor(std::ptr::null());
                    }
                }
                return Ok(Value::Unit);
            }

            // ══════════════════════════════════════════════════════════════════
            // 3-D / 4-D DRAWING — camera, lights, depth-sorted geometry
            // ══════════════════════════════════════════════════════════════════

            // ── set_camera(cry, sry, crx, srx) — store precomputed camera trig ──
            // Call once per frame after computing cos/sin of your rotation angles.
            "set_camera" | "ตั้งกล้อง" | "设镜" | "设置摄像机" | "カメラ設定" | "카메라설정" => {
                let cry = self.arg_num(&args, 0, 1.0)? as f32;
                let sry = self.arg_num(&args, 1, 0.0)? as f32;
                let crx = self.arg_num(&args, 2, 1.0)? as f32;
                let srx = self.arg_num(&args, 3, 0.0)? as f32;
                let mut gfx = self.gfx.borrow_mut();
                gfx.camera.cry = cry; gfx.camera.sry = sry;
                gfx.camera.crx = crx; gfx.camera.srx = srx;
                return Ok(Value::Unit);
            }

            // ── set_projection(cx, cy, focal, zdist) — override projection params ──
            // Automatically set when the window opens; override only if needed.
            "set_projection" | "ตั้งโปรเจกชัน" | "投影" | "投影設定" | "투영설정" => {
                let cx    = self.arg_num(&args, 0, 960.0)? as f32;
                let cy    = self.arg_num(&args, 1, 540.0)? as f32;
                let focal = self.arg_num(&args, 2, 1080.0)? as f32;
                let zdist = self.arg_num(&args, 3, 5.0)? as f32;
                let mut gfx = self.gfx.borrow_mut();
                gfx.camera.cx    = cx;
                gfx.camera.cy    = cy;
                gfx.camera.focal = focal;
                gfx.camera.zdist = zdist;
                return Ok(Value::Unit);
            }

            // ── add_light(x, y, z, r, g, b, intensity, radius) ──
            // Adds a point light in world space.  r/g/b in [0..1].
            // radius == 0 → no distance falloff.
            "add_light" | "เพิ่มแสง" | "加灯" | "ライト追加" | "조명추가" => {
                let x   = self.arg_num(&args, 0, 0.0)? as f32;
                let y   = self.arg_num(&args, 1, -3.0)? as f32;
                let z   = self.arg_num(&args, 2, 3.0)? as f32;
                let mut r   = self.arg_num(&args, 3, 1.0)? as f32;
                let mut g   = self.arg_num(&args, 4, 1.0)? as f32;
                let mut b   = self.arg_num(&args, 5, 1.0)? as f32;
                // Forgive 0-255 colour values: if any channel is clearly > 1,
                // treat the triple as 0-255 and normalise. Keeps 0-1 callers exact.
                if r > 1.5 || g > 1.5 || b > 1.5 { r/=255.0; g/=255.0; b/=255.0; }
                let intensity = self.arg_num(&args, 6, 1.0)? as f32;
                let radius    = self.arg_num(&args, 7, 0.0)? as f32;
                self.gfx.borrow_mut().lights.push(Light { x, y, z, r, g, b, intensity, radius });
                return Ok(Value::Unit);
            }

            // ── clear_lights() — remove all lights ──
            "clear_lights" | "ล้างแสง" | "清灯" | "ライト消去" | "조명초기화" => {
                self.gfx.borrow_mut().lights.clear();
                return Ok(Value::Unit);
            }

            // ── set_ambient(v) — ambient light level [0..1] ──
            "set_ambient" | "ตั้งแสงรอบข้าง" | "环境光" | "環境光設定" | "환경광설정" => {
                let v = self.arg_num(&args, 0, 0.15)? as f32;
                self.gfx.borrow_mut().ambient = v;
                return Ok(Value::Unit);
            }

            // ── วาดสามเหลี่ยม3มิติ(ax,ay,az, bx,by,bz, cx,cy,cz) ──
            // Computes lighting from world-space normal + active lights (cel shading),
            // projects via the stored camera, and pushes to the depth queue.
            "วาดสามเหลี่ยม3มิติ" | "draw_triangle_3d" | "triangle3d" => {
                let ax = self.arg_num(&args, 0, 0.0)? as f32;
                let ay = self.arg_num(&args, 1, 0.0)? as f32;
                let az = self.arg_num(&args, 2, 0.0)? as f32;
                let bx = self.arg_num(&args, 3, 0.0)? as f32;
                let by = self.arg_num(&args, 4, 0.0)? as f32;
                let bz = self.arg_num(&args, 5, 0.0)? as f32;
                let cx = self.arg_num(&args, 6, 0.0)? as f32;
                let cy = self.arg_num(&args, 7, 0.0)? as f32;
                let cz = self.arg_num(&args, 8, 0.0)? as f32;

                let mut gfx = self.gfx.borrow_mut();

                // World-space face normal  N = (B−A) × (C−A)
                let ux = bx-ax; let uy = by-ay; let uz = bz-az;
                let vx = cx-ax; let vy = cy-ay; let vz = cz-az;
                let normal = [
                    uy*vz - uz*vy,
                    uz*vx - ux*vz,
                    ux*vy - uy*vx,
                ];
                // World-space centroid
                let centroid = [
                    (ax+bx+cx)/3.0,
                    (ay+by+cy)/3.0,
                    (az+bz+cz)/3.0,
                ];

                // Cel-shaded colour
                let lit_color = crate::gfx::light::compute_lit_color(
                    gfx.color, normal, centroid, &gfx.lights, gfx.ambient,
                );

                // Near-plane cull — skip any triangle that has a vertex
                // behind or at the camera near plane (avoids projected-to-infinity blowup).
                let near = -gfx.camera.zdist + 0.05;
                let da_raw = gfx.camera.depth(ax, ay, az);
                let db_raw = gfx.camera.depth(bx, by, bz);
                let dc_raw = gfx.camera.depth(cx, cy, cz);
                if da_raw <= near || db_raw <= near || dc_raw <= near {
                    return Ok(Value::Unit);
                }

                // Project to screen
                let (sax, say, da) = gfx.camera.project(ax, ay, az);
                let (sbx, sby, db) = gfx.camera.project(bx, by, bz);
                let (scx, scy, dc) = gfx.camera.project(cx, cy, cz);

                // Average camera depth (used for painter's sort)
                let depth = (da + db + dc) / 3.0;

                gfx.depth_queue.push_triangle(
                    depth, lit_color,
                    sax, say, sbx, sby, scx, scy,
                );
                return Ok(Value::Unit);
            }

            // ── วาดเส้น3มิติ(ax,ay,az, bx,by,bz) ──
            // Projects two world-space points via the stored camera and pushes
            // a line to the depth queue.
            "วาดเส้น3มิติ" | "draw_line_3d" | "line3d" | "画3D线" | "3D線描く" | "3D선그리기" => {
                let ax = self.arg_num(&args, 0, 0.0)? as f32;
                let ay = self.arg_num(&args, 1, 0.0)? as f32;
                let az = self.arg_num(&args, 2, 0.0)? as f32;
                let bx = self.arg_num(&args, 3, 0.0)? as f32;
                let by = self.arg_num(&args, 4, 0.0)? as f32;
                let bz = self.arg_num(&args, 5, 0.0)? as f32;

                let mut gfx = self.gfx.borrow_mut();
                let color = gfx.color;
                // Near-plane clip in 3-D before perspective divide
                let near = -gfx.camera.zdist + 0.05;
                let mut lax = ax; let mut lay = ay; let mut laz = az;
                let mut lbx = bx; let mut lby = by; let mut lbz = bz;
                let da_raw = gfx.camera.depth(lax, lay, laz);
                let db_raw = gfx.camera.depth(lbx, lby, lbz);
                if da_raw <= near && db_raw <= near {
                    return Ok(Value::Unit);
                }
                if da_raw <= near {
                    let t = (near - da_raw) / (db_raw - da_raw);
                    lax += t * (lbx - lax);
                    lay += t * (lby - lay);
                    laz += t * (lbz - laz);
                } else if db_raw <= near {
                    let t = (near - da_raw) / (db_raw - da_raw);
                    lbx = lax + t * (lbx - lax);
                    lby = lay + t * (lby - lay);
                    lbz = laz + t * (lbz - laz);
                }
                let (sax, say, da) = gfx.camera.project(lax, lay, laz);
                let (sbx, sby, db) = gfx.camera.project(lbx, lby, lbz);
                let depth = (da + db) / 2.0;
                gfx.depth_queue.push_line(depth, color, sax, say, sbx, sby);
                return Ok(Value::Unit);
            }

            // project_3d(x,y,z) -> [screen_x, screen_y, depth]; behind the camera
            // returns a sentinel ([-99999,-99999, depth]) so scripts can skip it.
            // Lets scripts place 2-D overlays (e.g. filled teardrop flames) onto 3-D points.
            "project_3d" | "投影3D" | "3D投影" | "3D투영" | "ฉาย3มิติ" => {
                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;
                let gfx = self.gfx.borrow();
                let near = -gfx.camera.zdist + 0.05;
                let d = gfx.camera.depth(x, y, z);
                if d <= near {
                    return Ok(Value::List(vec![Value::Number(-99999.0), Value::Number(-99999.0), Value::Number(d as f64)]));
                }
                let (sx, sy, depth) = gfx.camera.project(x, y, z);
                return Ok(Value::List(vec![Value::Number(sx as f64), Value::Number(sy as f64), Value::Number(depth as f64)]));
            }
            // draw_poly([x0,y0,x1,y1,…]) — filled 2-D polygon in the current colour,
            // honouring the blend mode (additive → translucent glow). Auto-closes.
            #[cfg(not(target_arch = "wasm32"))]
            "draw_poly" | "填充多边形" | "ポリゴン塗り" | "다각형채우기" | "เติมรูปหลายเหลี่ยม" => {
                let mut pts: Vec<[f32; 2]> = Vec::new();
                if let Some(Value::List(v)) = args.first() {
                    let mut i = 0;
                    while i + 1 < v.len() {
                        let x = self.to_number(&v[i]).unwrap_or(0.0) as f32;
                        let y = self.to_number(&v[i + 1]).unwrap_or(0.0) as f32;
                        pts.push([x, y]);
                        i += 2;
                    }
                }
                if pts.len() >= 3 {
                    if pts[0] != pts[pts.len() - 1] { let p0 = pts[0]; pts.push(p0); } // close
                    let mut gfx = self.gfx.borrow_mut();
                    let (w, h, color, add) = (gfx.width, gfx.height, gfx.color, gfx.blend == 1);
                    crate::gfx::raster::fill_contours_aa(&mut gfx.buffer, w, h, color, add, std::slice::from_ref(&pts));
                }
                return Ok(Value::Unit);
            }

            // ══════════════════════════════════════════════════════════════════
            // VECTOR TEXTURE BUILTINS  (src/gfx/vtex.rs)
            // All patterns are depth-biased so they appear on top of surfaces.
            // Plane defined by: centre (cx,cy,cz) + U tangent + V tangent.
            // Last two args always: fr (frame f32), hue (phase offset f32).
            // ══════════════════════════════════════════════════════════════════

            // vtex_grid(cx,cy,cz, ux,uy,uz, vx,vy,vz, cols,rows, cw,ch, fr,hue)
            "vtex_grid" | "ลายตาราง" | "纹格" | "格子模様" | "격자무늬" => {
                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;
                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;
                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;
                let cols=self.arg_num(&args,9,10.)?as usize; let rows=self.arg_num(&args,10,10.)?as usize;
                let cw=self.arg_num(&args,11,1.)?as f32;  let ch=self.arg_num(&args,12,1.)?as f32;
                let fr=self.arg_num(&args,13,0.)?as f32;  let hue=self.arg_num(&args,14,0.)?as f32;
                let mut gfx = self.gfx.borrow_mut();
                let cam = gfx.camera.clone();
                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);
                return Ok(Value::Unit);
            }

            // vtex_rings(cx,cy,cz, ux,uy,uz, vx,vy,vz, n_rings,n_sides, max_r,twist, fr,hue)
            "vtex_rings" | "ลายวงซ้อน" | "纹环" | "同心円" | "동심원" => {
                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;
                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;
                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;
                let nr=self.arg_num(&args,9,6.)?as usize; let ns=self.arg_num(&args,10,6.)?as usize;
                let mr=self.arg_num(&args,11,3.)?as f32;  let tw=self.arg_num(&args,12,0.)?as f32;
                let fr=self.arg_num(&args,13,0.)?as f32;  let hue=self.arg_num(&args,14,0.)?as f32;
                let mut gfx = self.gfx.borrow_mut();
                let cam = gfx.camera.clone();
                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);
                return Ok(Value::Unit);
            }

            // vtex_star(cx,cy,cz, ux,uy,uz, vx,vy,vz, n_pts,r_out,r_in, rot_speed, fr,hue)
            "vtex_star" | "ลายดาว" | "纹星" | "星模様" | "별무늬" => {
                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;
                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;
                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;
                let np=self.arg_num(&args,9,6.)?as usize;
                let ro=self.arg_num(&args,10,2.)?as f32; let ri=self.arg_num(&args,11,1.)?as f32;
                let rs=self.arg_num(&args,12,0.01)?as f32;
                let fr=self.arg_num(&args,13,0.)?as f32; let hue=self.arg_num(&args,14,0.)?as f32;
                let mut gfx = self.gfx.borrow_mut();
                let cam = gfx.camera.clone();
                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);
                return Ok(Value::Unit);
            }

            // vtex_spiral(cx,cy,cz, ux,uy,uz, vx,vy,vz, n_turns,max_r,steps, fr,hue)
            "vtex_spiral" | "ลายเกลียว" | "纹螺" | "螺旋" | "나선" => {
                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;
                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;
                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;
                let nt=self.arg_num(&args,9,3.)?as f32; let mr=self.arg_num(&args,10,3.)?as f32;
                let st=self.arg_num(&args,11,120.)?as usize;
                let fr=self.arg_num(&args,12,0.)?as f32; let hue=self.arg_num(&args,13,0.)?as f32;
                let mut gfx = self.gfx.borrow_mut();
                let cam = gfx.camera.clone();
                crate::gfx::vtex::draw_spiral(&mut gfx.depth_queue,&cam, cx,cy,cz, ux,uy,uz, vx,vy,vz, nt,mr,st, fr,hue);
                return Ok(Value::Unit);
            }

            // vtex_flower(cx,cy,cz, ux,uy,uz, vx,vy,vz, radius,n_sides, fr,hue)
            "vtex_flower" | "ลายดอก" | "纹花" | "花模様" | "꽃무늬" => {
                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;
                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;
                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;
                let r=self.arg_num(&args,9,1.)?as f32; let ns=self.arg_num(&args,10,24.)?as usize;
                let fr=self.arg_num(&args,11,0.)?as f32; let hue=self.arg_num(&args,12,0.)?as f32;
                let mut gfx = self.gfx.borrow_mut();
                let cam = gfx.camera.clone();
                crate::gfx::vtex::draw_flower(&mut gfx.depth_queue,&cam, cx,cy,cz, ux,uy,uz, vx,vy,vz, r,ns, fr,hue);
                return Ok(Value::Unit);
            }

            // vtex_letter_rain(cx,cy,cz, ux,uy,uz, vx,vy,vz, n_cols,n_vis, col_w,row_h, speed, fr,hue)
            "vtex_letter_rain" | "ลายอักษรไหล" | "纹字雨" | "文字雨" | "글자비" => {
                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;
                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;
                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;
                let nc=self.arg_num(&args,9,16.)?as usize; let nv=self.arg_num(&args,10,14.)?as usize;
                let cw=self.arg_num(&args,11,0.65)?as f32; let rh=self.arg_num(&args,12,0.60)?as f32;
                let sp=self.arg_num(&args,13,0.025)?as f32;
                let fr=self.arg_num(&args,14,0.)?as f32; let hue=self.arg_num(&args,15,0.)?as f32;
                let mut gfx = self.gfx.borrow_mut();
                let cam = gfx.camera.clone();
                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);
                return Ok(Value::Unit);
            }

            // vtex_hyperbolic_uv(cx,cy,cz, ux,uy,uz, vx,vy,vz, max_r,n_circles,n_rays, fr,hue)
            "vtex_hyperbolic_uv" | "ลายไฮเพอร์โบลิก" | "纹曲面" | "双曲線" | "쌍곡선" => {
                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;
                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;
                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;
                let mr=self.arg_num(&args,9,5.)?as f32;
                let nc=self.arg_num(&args,10,12.)?as usize; let nr=self.arg_num(&args,11,18.)?as usize;
                let fr=self.arg_num(&args,12,0.)?as f32; let hue=self.arg_num(&args,13,0.)?as f32;
                let mut gfx = self.gfx.borrow_mut();
                let cam = gfx.camera.clone();
                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);
                return Ok(Value::Unit);
            }

            // vtex_halftone(cx,cy,cz, ux,uy,uz, vx,vy,vz, cols,rows, cell_w,cell_h, density, fr,hue)
            "vtex_halftone" | "ลายจุด" | "纹半调" | "網点模様" | "망점" => {
                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;
                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;
                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;
                let cols=self.arg_num(&args,9,16.)?as usize; let rows=self.arg_num(&args,10,12.)?as usize;
                let cw=self.arg_num(&args,11,0.5)?as f32; let ch=self.arg_num(&args,12,0.5)?as f32;
                let dens=self.arg_num(&args,13,0.4)?as f32;
                let fr=self.arg_num(&args,14,0.)?as f32; let hue=self.arg_num(&args,15,0.)?as f32;
                let mut gfx = self.gfx.borrow_mut();
                let cam = gfx.camera.clone();
                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);
                return Ok(Value::Unit);
            }

            // vtex_tessellated(cx,cy,cz, ux,uy,uz, vx,vy,vz, cols,rows, cell, amplitude,freq, fr,hue)
            "vtex_tessellated" | "ลายตาข่าย" | "纹镶嵌" | "網目模様" | "격자망" => {
                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;
                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;
                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;
                let cols=self.arg_num(&args,9,14.)?as usize; let rows=self.arg_num(&args,10,10.)?as usize;
                let cell=self.arg_num(&args,11,0.6)?as f32;
                let amp=self.arg_num(&args,12,0.25)?as f32; let freq=self.arg_num(&args,13,4.)?as f32;
                let fr=self.arg_num(&args,14,0.)?as f32; let hue=self.arg_num(&args,15,0.)?as f32;
                let mut gfx = self.gfx.borrow_mut();
                let cam = gfx.camera.clone();
                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);
                return Ok(Value::Unit);
            }

            // vtex_lotus(cx,cy,cz, ux,uy,uz, vx,vy,vz, r_inner,r_outer,n_petals, fr,hue)
            "vtex_lotus" | "ลายดอกบัว" | "纹莲" | "蓮模様" | "연꽃무늬" => {
                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;
                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;
                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;
                let ri=self.arg_num(&args,9,1.)?as f32; let ro=self.arg_num(&args,10,2.)?as f32;
                let np=self.arg_num(&args,11,12.)?as usize;
                let fr=self.arg_num(&args,12,0.)?as f32; let hue=self.arg_num(&args,13,0.)?as f32;
                let mut gfx = self.gfx.borrow_mut();
                let cam = gfx.camera.clone();
                crate::gfx::vtex::draw_lotus(&mut gfx.depth_queue,&cam, cx,cy,cz, ux,uy,uz, vx,vy,vz, ri,ro,np, fr,hue);
                return Ok(Value::Unit);
            }

            // vtex_chakra(cx,cy,cz, ux,uy,uz, vx,vy,vz, r,n_spokes, fr,hue)
            "vtex_chakra" | "ลายจักร" | "纹轮" | "輪模様" | "바퀴무늬" => {
                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;
                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;
                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;
                let r=self.arg_num(&args,9,2.)?as f32; let ns=self.arg_num(&args,10,8.)?as usize;
                let fr=self.arg_num(&args,11,0.)?as f32; let hue=self.arg_num(&args,12,0.)?as f32;
                let mut gfx = self.gfx.borrow_mut();
                let cam = gfx.camera.clone();
                crate::gfx::vtex::draw_chakra(&mut gfx.depth_queue,&cam, cx,cy,cz, ux,uy,uz, vx,vy,vz, r,ns, fr,hue);
                return Ok(Value::Unit);
            }

            // vtex_yantra(cx,cy,cz, ux,uy,uz, vx,vy,vz, n_layers,max_r, fr,hue)
            "vtex_yantra" | "ลายยันต์" | "纹咒" | "護符模様" | "부적무늬" => {
                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;
                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;
                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;
                let nl=self.arg_num(&args,9,4.)?as usize; let mr=self.arg_num(&args,10,3.)?as f32;
                let fr=self.arg_num(&args,11,0.)?as f32; let hue=self.arg_num(&args,12,0.)?as f32;
                let mut gfx = self.gfx.borrow_mut();
                let cam = gfx.camera.clone();
                crate::gfx::vtex::draw_yantra(&mut gfx.depth_queue,&cam, cx,cy,cz, ux,uy,uz, vx,vy,vz, nl,mr, fr,hue);
                return Ok(Value::Unit);
            }

            // vtex_spiked_cog(cx,cy,cz, ux,uy,uz, vx,vy,vz, n_teeth,r_body,r_spike,r_hub,n_spokes, fr,hue)
            "vtex_spiked_cog" | "ฟันเฟืองหนาม" | "纹棘轮" | "歯車模様" | "톱니바퀴" => {
                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;
                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;
                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;
                let nt=self.arg_num(&args,9,12.)?as usize; let rb=self.arg_num(&args,10,1.)?as f32;
                let rs=self.arg_num(&args,11,1.3)?as f32; let rh=self.arg_num(&args,12,0.2)?as f32;
                let ns=self.arg_num(&args,13,6.)?as usize;
                let fr=self.arg_num(&args,14,0.)?as f32; let hue=self.arg_num(&args,15,0.)?as f32;
                let mut gfx = self.gfx.borrow_mut();
                let cam = gfx.camera.clone();
                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);
                return Ok(Value::Unit);
            }

            // vtex_torii(cx,cy,cz, ux,uy,uz, vx,vy,vz, width,height, fr,hue)
            "vtex_torii" | "ประตูโทริอิ" | "纹鸟居" | "鳥居" | "도리이" => {
                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;
                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;
                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;
                let w=self.arg_num(&args,9,4.)?as f32; let h=self.arg_num(&args,10,5.)?as f32;
                let fr=self.arg_num(&args,11,0.)?as f32; let hue=self.arg_num(&args,12,0.)?as f32;
                let mut gfx = self.gfx.borrow_mut();
                let cam = gfx.camera.clone();
                crate::gfx::vtex::draw_torii(&mut gfx.depth_queue,&cam, cx,cy,cz, ux,uy,uz, vx,vy,vz, w,h, fr,hue);
                return Ok(Value::Unit);
            }

            // vtex_pagoda(cx,cy,cz, ux,uy,uz, vx,vy,vz, n_tiers,base_w,tier_h,taper,eave_out, fr,hue)
            "vtex_pagoda" | "เจดีย์" | "纹塔" | "" | "" => {
                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;
                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;
                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;
                let nt=self.arg_num(&args,9,5.)?as usize; let bw=self.arg_num(&args,10,2.)?as f32;
                let th=self.arg_num(&args,11,1.)?as f32; let tp=self.arg_num(&args,12,0.72)?as f32;
                let eo=self.arg_num(&args,13,0.28)?as f32;
                let fr=self.arg_num(&args,14,0.)?as f32; let hue=self.arg_num(&args,15,0.)?as f32;
                let mut gfx = self.gfx.borrow_mut();
                let cam = gfx.camera.clone();
                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);
                return Ok(Value::Unit);
            }

            // ══════════════════════════════════════════════════════════════════
            // AUDIO BUILTINS
            // ══════════════════════════════════════════════════════════════════

            // audio_tone(idx, x, y, z, w, freq, amp, lfo_rate, lfo_depth)
            #[cfg(not(target_arch = "wasm32"))]
            "audio_tone" | "เสียงโทน" | "音调" | "音調" | "음조" | "空间音" | "空間音" | "공간음" => {
                let idx  = self.arg_num(&args, 0, 0.0)? as usize;
                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;
                let w    = self.arg_num(&args, 4, 1.0)? as f32;
                let freq = self.arg_num(&args, 5, 220.0)? as f32;
                let amp  = self.arg_num(&args, 6, 0.15)? as f32;
                let lfo_rate  = self.arg_num(&args, 7, 0.5)? as f32;
                let lfo_depth = self.arg_num(&args, 8, 0.02)? as f32;
                if let Some(audio) = &self.audio {
                    audio.set_tone(idx, ToneParams { x, y, z, w, freq, amp, lfo_rate, lfo_depth });
                }
                return Ok(Value::Unit);
            }

            #[cfg(not(target_arch = "wasm32"))]
            "audio_listener" | "ผู้ฟัง" | "音频监听" | "音声リスナー" | "오디오리스너" => {
                let cry = self.arg_num(&args, 0, 1.0)? as f32;
                let sry = self.arg_num(&args, 1, 0.0)? as f32;
                let crx = self.arg_num(&args, 2, 1.0)? as f32;
                let srx = self.arg_num(&args, 3, 0.0)? as f32;
                if let Some(audio) = &self.audio {
                    audio.set_listener(cry, sry, crx, srx);
                }
                return Ok(Value::Unit);
            }

            #[cfg(not(target_arch = "wasm32"))]
            "audio_bgm" | "เพลงพื้นหลัง" | "เพลงประกอบ" | "背景乐" | "BGM" | "배경음악" => {
                let path = match args.first() {
                    Some(Value::Str(s)) => s.clone(),
                    _ => return Ok(Value::Unit),
                };
                let vol = self.arg_num(&args, 1, 0.5)? as f32;
                if let Some(audio) = &self.audio {
                    audio.load_bgm(&path, vol);
                }
                return Ok(Value::Unit);
            }

            #[cfg(not(target_arch = "wasm32"))]
            "audio_bgm_volume" | "ระดับเสียงพื้นหลัง" | "ระดับเพลงประกอบ" | "背景乐音量" | "BGM音量" | "배경음악음량" => {
                let vol = self.arg_num(&args, 0, 0.5)? as f32;
                if let Some(audio) = &self.audio {
                    audio.set_bgm_volume(vol);
                }
                return Ok(Value::Unit);
            }

            #[cfg(not(target_arch = "wasm32"))]
            "audio_volume" | "ระดับเสียง" | "音量" | "음량" => {
                let vol = self.arg_num(&args, 0, 0.7)? as f32;
                if let Some(audio) = &self.audio {
                    audio.set_master_volume(vol);
                }
                return Ok(Value::Unit);
            }

            // WASM audio builtins — delegate to Web Audio API
            #[cfg(target_arch = "wasm32")]
            "audio_tone" | "เสียงโทน" | "音调" | "音調" | "음조" | "空间音" | "空間音" | "공간음" => {
                let idx  = self.arg_num(&args, 0, 0.0)? as usize;
                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;
                let w    = self.arg_num(&args, 4, 1.0)? as f32;
                let freq = self.arg_num(&args, 5, 220.0)? as f32;
                let amp  = self.arg_num(&args, 6, 0.15)? as f32;
                let lfo_rate  = self.arg_num(&args, 7, 0.5)? as f32;
                let lfo_depth = self.arg_num(&args, 8, 0.02)? as f32;
                crate::gfx::audio_web::set_tone(idx, x, y, z, w, freq, amp, lfo_rate, lfo_depth);
                return Ok(Value::Unit);
            }

            #[cfg(target_arch = "wasm32")]
            "audio_listener" | "ผู้ฟัง" | "音频监听" | "音声リスナー" | "오디오리스너" => {
                let cry = self.arg_num(&args, 0, 1.0)? as f32;
                let sry = self.arg_num(&args, 1, 0.0)? as f32;
                let crx = self.arg_num(&args, 2, 1.0)? as f32;
                let srx = self.arg_num(&args, 3, 0.0)? as f32;
                crate::gfx::audio_web::set_listener(cry, sry, crx, srx);
                return Ok(Value::Unit);
            }

            #[cfg(target_arch = "wasm32")]
            "audio_bgm" | "เพลงพื้นหลัง" | "เพลงประกอบ" | "背景乐" | "BGM" | "배경음악" => {
                let path = self.arg_str(&args, 0, "");
                let vol  = self.arg_num(&args, 1, 0.5)? as f32;
                crate::gfx::audio_web::load_bgm(&path, vol);
                return Ok(Value::Unit);
            }

            #[cfg(target_arch = "wasm32")]
            "audio_bgm_volume" | "ระดับเสียงพื้นหลัง" | "ระดับเพลงประกอบ" | "背景乐音量" | "BGM音量" | "배경음악음량" => {
                let vol = self.arg_num(&args, 0, 0.5)? as f32;
                crate::gfx::audio_web::set_bgm_volume(vol);
                return Ok(Value::Unit);
            }

            #[cfg(target_arch = "wasm32")]
            "audio_volume" | "ระดับเสียง" | "音量" | "음량" => {
                let vol = self.arg_num(&args, 0, 0.7)? as f32;
                crate::gfx::audio_web::set_master_volume(vol);
                return Ok(Value::Unit);
            }

            // ── รอหน้าต่าง() — block until window closed / Escape ──
            "รอหน้าต่าง" | "wait_window" | "gfx_wait" => {
                #[cfg(not(target_arch = "wasm32"))]
                loop {
                    let still_open = {
                        let gfx = self.gfx.borrow();
                        gfx.window.as_ref()
                            .map(|w| w.is_open() && !w.is_key_down(minifb::Key::Escape))
                            .unwrap_or(false)
                    };
                    if !still_open { break; }
                    let (buf, w, h) = {
                        let gfx = self.gfx.borrow();
                        (gfx.buffer.clone(), gfx.width, gfx.height)
                    };
                    let mut gfx = self.gfx.borrow_mut();
                    if let Some(win) = gfx.window.as_mut() {
                        if win.update_with_buffer(&buf, w, h).is_err() { break; }
                    }
                }
                return Ok(Value::Unit);
            }

            // ── File I/O ──────────────────────────────────────────────────────
            "read_file" | "อ่านไฟล์" => {
                let path = self.arg_str(&args, 0, "");
                return std::fs::read_to_string(&path)
                    .map(Value::Str)
                    .map_err(|e| EvalErr::from(format!("read_file '{path}': {e}")));
            }
            "write_file" | "เขียนไฟล์" => {
                let path    = self.arg_str(&args, 0, "");
                let content = self.arg_str(&args, 1, "");
                std::fs::write(&path, content.as_bytes())
                    .map_err(|e| EvalErr::from(format!("write_file '{path}': {e}")))?;
                return Ok(Value::Unit);
            }
            "print_file" | "พิมพ์ไฟล์" => {
                let content = self.arg_str(&args, 0, "");
                print!("{content}");
                return Ok(Value::Unit);
            }

            // ── CLI arguments ─────────────────────────────────────────────────
            "get_args" | "รับอาร์กิวเมนต์" => {
                let v: Vec<Value> = std::env::args().map(Value::Str).collect();
                return Ok(Value::List(v));
            }

            // ── String utilities ──────────────────────────────────────────────
            "split" | "str_split" | "แยก" => {
                let s   = self.arg_str(&args, 0, "");
                let sep = self.arg_str(&args, 1, "\n");
                let sep = if sep.is_empty() { "\n".into() } else { sep };
                let parts: Vec<Value> = s.split(sep.as_str())
                    .map(|p| Value::Str(p.to_string())).collect();
                return Ok(Value::List(parts));
            }
            "trim" | "str_trim" | "ตัดช่องว่าง" => {
                let s = self.arg_str(&args, 0, "");
                return Ok(Value::Str(s.trim().to_string()));
            }
            "starts_with" | "str_starts_with" | "เริ่มด้วย" => {
                let s      = self.arg_str(&args, 0, "");
                let prefix = self.arg_str(&args, 1, "");
                return Ok(Value::Bool(s.starts_with(prefix.as_str())));
            }
            "ends_with" | "str_ends_with" | "ลงท้ายด้วย" => {
                let s      = self.arg_str(&args, 0, "");
                let suffix = self.arg_str(&args, 1, "");
                return Ok(Value::Bool(s.ends_with(suffix.as_str())));
            }
            "str_replace" | "แทนสตริง" => {
                let s    = self.arg_str(&args, 0, "");
                let from = self.arg_str(&args, 1, "");
                let to   = self.arg_str(&args, 2, "");
                return Ok(Value::Str(s.replace(from.as_str(), to.as_str())));
            }
            "str_find" | "หาในสตริง" => {
                let s      = self.arg_str(&args, 0, "");
                let needle = self.arg_str(&args, 1, "");
                // Return char index (not byte index) for consistency with substr
                let pos = s.find(needle.as_str())
                    .map(|byte_i| s[..byte_i].chars().count() as f64)
                    .unwrap_or(-1.0);
                return Ok(Value::Number(pos));
            }
            "substr" | "str_slice" | "ส่วนสตริง" => {
                let s     = self.arg_str(&args, 0, "");
                let start = self.arg_num(&args, 1, 0.0)? as usize;
                let len   = args.get(2)
                    .map(|v| self.to_number(v).unwrap_or(999999.0) as usize)
                    .unwrap_or_else(|| s.chars().count().saturating_sub(start));
                let chars: Vec<char> = s.chars().collect();
                let end   = (start + len).min(chars.len());
                let slice: String = chars.get(start..end).unwrap_or(&[]).iter().collect();
                return Ok(Value::Str(slice));
            }
            "to_str" | "str" | "num_str" | "แปลงสตริง" => {
                let v = args.into_iter().next().unwrap_or(Value::Unit);
                return Ok(Value::Str(v.to_string()));
            }
            "str_repeat" | "ทำซ้ำสตริง" => {
                let s = self.arg_str(&args, 0, "");
                let n = self.arg_num(&args, 1, 1.0)? as usize;
                return Ok(Value::Str(s.repeat(n)));
            }
            "str_upper" => {
                let s = self.arg_str(&args, 0, "");
                return Ok(Value::Str(s.to_uppercase()));
            }
            "str_lower" => {
                let s = self.arg_str(&args, 0, "");
                return Ok(Value::Str(s.to_lowercase()));
            }
            "str_len" | "len" | "ความยาว" | "长度" | "長さ" | "길이" => {
                match args.first() {
                    Some(Value::Str(s))  => return Ok(Value::Number(s.chars().count() as f64)),
                    Some(Value::List(v)) => return Ok(Value::Number(v.len() as f64)),
                    _ => return Ok(Value::Number(0.0)),
                }
            }

            // ── FNV-1a hash (deterministic, normalized 0.0–1.0) ──────────────
            "hash_str" | "แฮช" => {
                let s = self.arg_str(&args, 0, "");
                let mut h: u64 = 14695981039346656037_u64;
                for b in s.bytes() { h ^= b as u64; h = h.wrapping_mul(1099511628211); }
                return Ok(Value::Number((h & 0xFFFFFF) as f64 / 16777215.0));
            }
            "hash_int" | "แฮชจำนวน" => {
                let s = self.arg_str(&args, 0, "");
                let n = self.arg_num(&args, 1, 100.0)? as u64;
                let mut h: u64 = 14695981039346656037_u64;
                for b in s.bytes() { h ^= b as u64; h = h.wrapping_mul(1099511628211); }
                return Ok(Value::Number((h % n.max(1)) as f64));
            }

            // ── List utilities ────────────────────────────────────────────────
            "list_new" | "รายการใหม่" | "新建列表" | "新規リスト" | "새목록" => {
                return Ok(Value::List(Vec::new()));
            }
            "list_push" | "เพิ่มรายการ" | "列表添加" | "リスト追加" | "목록추가" => {
                let lst = args.first().cloned().unwrap_or(Value::List(vec![]));
                let val = args.get(1).cloned().unwrap_or(Value::Unit);
                if let Value::List(mut v) = lst { v.push(val); return Ok(Value::List(v)); }
                return Ok(Value::List(vec![val]));
            }
            "list_get" | "รับรายการ" | "取元素" | "要素取得" | "요소가져오기" => {
                let lst = args.first().cloned().unwrap_or(Value::List(vec![]));
                let i   = self.arg_num(&args, 1, 0.0)? as usize;
                if let Value::List(v) = lst {
                    return Ok(v.get(i).cloned().unwrap_or(Value::Str(String::new())));
                }
                return Ok(Value::Str(String::new()));
            }
            "list_join" | "join" | "รวมรายการ" | "连接" | "連結" | "연결" => {
                let lst = args.first().cloned().unwrap_or(Value::List(vec![]));
                let sep = args.get(1).map(|v| v.to_string()).unwrap_or_default();
                if let Value::List(v) = lst {
                    return Ok(Value::Str(v.iter().map(|x| x.to_string())
                        .collect::<Vec<_>>().join(&sep)));
                }
                return Ok(Value::Str(String::new()));
            }

            // ══════════════════════════════════════════════════════════════════
            // SVG EXPORT  (svg_begin / svg_rect / svg_circle / svg_line /
            //              svg_polyline / svg_text / svg_end / hsl_color)
            // Chinese aliases: 开始SVG 结束SVG SVG矩形 SVG圆形 SVG线段 SVG折线 SVG文本 HSL颜色
            // Thai aliases:    เริ่มSVG จบSVG SVGสี่เหลี่ยม SVGวงกลม SVGเส้น SVGเส้นหัก SVGข้อความ สีHSL
            // ══════════════════════════════════════════════════════════════════

            "svg_begin" | "开始SVG" | "เริ่มSVG" => {
                let path   = self.arg_str(&args, 0, "output.svg");
                let width  = self.arg_num(&args, 1, 800.0)?;
                let height = self.arg_num(&args, 2, 600.0)?;
                *self.svg.borrow_mut() = Some(SvgWriter::new(path, width, height));
                return Ok(Value::Unit);
            }

            "svg_rect" | "SVG矩形" | "SVGสี่เหลี่ยม" => {
                let x    = self.arg_num(&args, 0, 0.0)?;
                let y    = self.arg_num(&args, 1, 0.0)?;
                let w    = self.arg_num(&args, 2, 10.0)?;
                let h    = self.arg_num(&args, 3, 10.0)?;
                let fill = self.arg_str(&args, 4, "#ffffff");
                if let Some(svg) = self.svg.borrow_mut().as_mut() {
                    svg.elements.push(format!(
                        "<rect x=\"{x:.1}\" y=\"{y:.1}\" width=\"{w:.1}\" \
                         height=\"{h:.1}\" fill=\"{fill}\"/>"));
                }
                return Ok(Value::Unit);
            }

            "svg_circle" | "SVG圆形" | "SVGวงกลม" => {
                let cx   = self.arg_num(&args, 0, 0.0)?;
                let cy   = self.arg_num(&args, 1, 0.0)?;
                let r    = self.arg_num(&args, 2, 5.0)?;
                let fill = self.arg_str(&args, 3, "#ffffff");
                if let Some(svg) = self.svg.borrow_mut().as_mut() {
                    svg.elements.push(format!(
                        "<circle cx=\"{cx:.1}\" cy=\"{cy:.1}\" r=\"{r:.1}\" fill=\"{fill}\"/>"));
                }
                return Ok(Value::Unit);
            }

            "svg_line" | "SVG线段" | "SVGเส้น" => {
                let x1     = self.arg_num(&args, 0, 0.0)?;
                let y1     = self.arg_num(&args, 1, 0.0)?;
                let x2     = self.arg_num(&args, 2, 0.0)?;
                let y2     = self.arg_num(&args, 3, 0.0)?;
                let stroke = self.arg_str(&args, 4, "#ffffff");
                let sw     = self.arg_num(&args, 5, 1.0)?;
                if let Some(svg) = self.svg.borrow_mut().as_mut() {
                    svg.elements.push(format!(
                        "<line x1=\"{x1:.1}\" y1=\"{y1:.1}\" x2=\"{x2:.1}\" y2=\"{y2:.1}\" \
                         stroke=\"{stroke}\" stroke-width=\"{sw:.1}\"/>"));
                }
                return Ok(Value::Unit);
            }

            "svg_polyline" | "SVG折线" | "SVGเส้นหัก" => {
                let pts    = self.arg_str(&args, 0, "");
                let stroke = self.arg_str(&args, 1, "#ffffff");
                let sw     = self.arg_num(&args, 2, 1.0)?;
                if let Some(svg) = self.svg.borrow_mut().as_mut() {
                    svg.elements.push(format!(
                        "<polyline points=\"{pts}\" fill=\"none\" \
                         stroke=\"{stroke}\" stroke-width=\"{sw:.1}\"/>"));
                }
                return Ok(Value::Unit);
            }

            "svg_text" | "SVG文本" | "SVGข้อความ" => {
                let x    = self.arg_num(&args, 0, 0.0)?;
                let y    = self.arg_num(&args, 1, 0.0)?;
                let text = self.arg_str(&args, 2, "");
                let fill = self.arg_str(&args, 3, "#ffffff");
                let size = self.arg_num(&args, 4, 12.0)?;
                if let Some(svg) = self.svg.borrow_mut().as_mut() {
                    let safe = text.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;");
                    svg.elements.push(format!(
                        "<text x=\"{x:.1}\" y=\"{y:.1}\" fill=\"{fill}\" \
                         font-family=\"monospace\" font-size=\"{size:.0}\">{safe}</text>"));
                }
                return Ok(Value::Unit);
            }

            "svg_end" | "结束SVG" | "จบSVG" => {
                {
                    let borrow = self.svg.borrow();
                    if let Some(svg) = borrow.as_ref() {
                        svg.save().map_err(|e| EvalErr::from(format!("svg_end: {e}")))?;
                    }
                }
                *self.svg.borrow_mut() = None;
                return Ok(Value::Unit);
            }

            "hsl_color" | "HSL颜色" | "สีHSL" => {
                let h = self.arg_num(&args, 0, 0.0)?;
                let s = self.arg_num(&args, 1, 70.0)?;
                let l = self.arg_num(&args, 2, 50.0)?;
                return Ok(Value::Str(hsl_to_hex(h, s, l)));
            }

            // ══════════════════════════════════════════════════════════════════
            // FFT / AUDIO ANALYSIS BUILTINS  (native only)
            // ══════════════════════════════════════════════════════════════════

            // fft_push(samples_list) — feed raw audio samples and run FFT
            #[cfg(not(target_arch = "wasm32"))]
            "fft_push" | "วิเคราะห์เสียง" | "频谱输入" | "FFT入力" | "FFT입력" => {
                if let Some(Value::List(v)) = args.first() {
                    let samples: Vec<f32> = v.iter()
                        .filter_map(|x| if let Value::Number(n) = x { Some(*n as f32) } else { None })
                        .collect();
                    self.fft.borrow_mut().push_samples(&samples);
                }
                return Ok(Value::Unit);
            }

            // fft_bands(n) → list of n log-spaced magnitude bands (0..1)
            #[cfg(not(target_arch = "wasm32"))]
            "fft_bands" | "แถบความถี่" | "频段" | "周波数帯" | "주파수대" => {
                let n = self.arg_num(&args, 0, 32.0)? as usize;
                let bands = self.fft.borrow().freq_bands(n);
                *self.fft_bands_cache.borrow_mut() = bands.clone();
                return Ok(Value::List(bands.into_iter().map(|v| Value::Number(v as f64)).collect()));
            }

            // fft_beat() → bool
            #[cfg(not(target_arch = "wasm32"))]
            "fft_beat" | "จังหวะเสียง" | "节拍检测" | "ビート検出" | "비트" => {
                return Ok(Value::Bool(self.fft.borrow().is_beat()));
            }

            // fft_beat_ratio() → f64  (1.0 = at threshold, >1 = strong beat)
            #[cfg(not(target_arch = "wasm32"))]
            "fft_beat_ratio" | "อัตราจังหวะ" | "节拍比" | "ビート比" | "비트비율" => {
                return Ok(Value::Number(self.fft.borrow().beat_ratio() as f64));
            }

            // fft_rms() → f64
            #[cfg(not(target_arch = "wasm32"))]
            "fft_rms" | "ระดับRMS" | "均方根" | "二乗平均" | "RMS레벨" => {
                return Ok(Value::Number(self.fft.borrow().rms() as f64));
            }

            // fft_dominant_freq() → f64  in Hz
            #[cfg(not(target_arch = "wasm32"))]
            "fft_dominant_freq" | "ความถี่หลัก" | "主频" | "主要周波数" | "주파수" => {
                return Ok(Value::Number(self.fft.borrow().dominant_freq() as f64));
            }

            // ── wasm32 stubs: fft builtins are no-ops on web ───────────────
            #[cfg(target_arch = "wasm32")]
            "fft_push" | "วิเคราะห์เสียง" | "频谱输入" | "FFT入力" | "FFT입력" => { return Ok(Value::Unit); }
            #[cfg(target_arch = "wasm32")]
            "fft_bands" | "แถบความถี่" | "频段" | "周波数帯" | "주파수대" => {
                let n = self.arg_num(&args, 0, 32.0)? as usize;
                return Ok(Value::List(vec![Value::Number(0.0); n]));
            }
            #[cfg(target_arch = "wasm32")]
            "fft_beat" | "จังหวะเสียง" | "节拍检测" | "ビート検出" | "비트" => { return Ok(Value::Bool(false)); }
            #[cfg(target_arch = "wasm32")]
            "fft_beat_ratio" | "อัตราจังหวะ" | "节拍比" | "ビート比" | "비트비율" => { return Ok(Value::Number(1.0)); }
            #[cfg(target_arch = "wasm32")]
            "fft_rms" | "ระดับRMS" | "均方根" | "二乗平均" | "RMS레벨" => { return Ok(Value::Number(0.0)); }
            #[cfg(target_arch = "wasm32")]
            "fft_dominant_freq" | "ความถี่หลัก" | "主频" | "主要周波数" | "주파수" => { return Ok(Value::Number(0.0)); }

            // ══════════════════════════════════════════════════════════════════
            // PROCEDURAL TEXTURE BLIT BUILTINS  (screen-space)
            // All: name(dst_x, dst_y, width, height, ...params, palette)
            // palette: "rainbow" | "fire" | "ocean" | "psychedelic" | "neon" | "forest"
            // ══════════════════════════════════════════════════════════════════

            // tex_checkerboard(x, y, w, h, tiles, r1,g1,b1, r2,g2,b2)
            "tex_checkerboard" | "ลายตารางหมากรุก" => {
                let (tx,ty,tw,th) = self.tex_rect(&args)?;
                let tiles = self.arg_num(&args, 4, 8.0)? as u32;
                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);
                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);
                let c1 = (r1<<16)|(g1<<8)|b1; let c2 = (r2<<16)|(g2<<8)|b2;
                let mut gfx = self.gfx.borrow_mut();
                let (bw, bh) = (gfx.width, gfx.height);
                for row in 0..th { for col in 0..tw {
                    let cx = col as u32 * tiles / tw as u32;
                    let cy = row as u32 * tiles / th as u32;
                    let (dx, dy) = (tx+col, ty+row);
                    if dx < bw && dy < bh { gfx.buffer[dy*bw+dx] = if (cx+cy)%2==0 { c1 } else { c2 }; }
                }}
                return Ok(Value::Unit);
            }

            // tex_gradient(x, y, w, h, angle_deg, r1,g1,b1, r2,g2,b2)
            "tex_gradient" | "ลายไล่สี" => {
                let (tx,ty,tw,th) = self.tex_rect(&args)?;
                let angle = self.arg_num(&args, 4, 0.0)? as f32;
                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.);
                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.);
                let (ca, sa) = (angle.to_radians().cos(), angle.to_radians().sin());
                let mut gfx = self.gfx.borrow_mut();
                let (bw, bh) = (gfx.width, gfx.height);
                for row in 0..th { for col in 0..tw {
                    let nx = col as f32/tw as f32 - 0.5; let ny = row as f32/th as f32 - 0.5;
                    let t = ((nx*ca + ny*sa + 0.707)/1.414).clamp(0.,1.);
                    let (dx, dy) = (tx+col, ty+row);
                    if dx < bw && dy < bh { gfx.buffer[dy*bw+dx] = tex_rgb(r1+(r2-r1)*t, g1+(g2-g1)*t, b1+(b2-b1)*t); }
                }}
                return Ok(Value::Unit);
            }

            // tex_noise(x, y, w, h, scale, octaves, seed, palette)
            "tex_noise" | "ลายนอยส์" => {
                let (tx,ty,tw,th) = self.tex_rect(&args)?;
                let scale   = self.arg_num(&args, 4, 4.0)? as f32;
                let octaves = self.arg_num(&args, 5, 4.0)? as u32;
                let seed    = self.arg_num(&args, 6, 0.0)? as u32;
                let palette = self.arg_str(&args, 7, "rainbow");
                let mut gfx = self.gfx.borrow_mut();
                let (bw, bh) = (gfx.width, gfx.height);
                for row in 0..th { for col in 0..tw {
                    let v = tex_fbm(col as f32*scale/tw as f32, row as f32*scale/th as f32, octaves, seed);
                    let [r,g,b] = tex_palette(&palette, v);
                    let (dx, dy) = (tx+col, ty+row);
                    if dx < bw && dy < bh { gfx.buffer[dy*bw+dx] = tex_rgb(r, g, b); }
                }}
                return Ok(Value::Unit);
            }

            // tex_freq_map(x, y, w, h, time, speed, palette)
            // Uses bands written by the last fft_bands() call.
            "tex_freq_map" | "ลายความถี่" => {
                let (tx,ty,tw,th) = self.tex_rect(&args)?;
                let time    = self.arg_num(&args, 4, 0.0)? as f32;
                let speed   = self.arg_num(&args, 5, 0.3)? as f32;
                let palette = self.arg_str(&args, 6, "rainbow");
                let bands: Vec<f32> = {
                    let c = self.fft_bands_cache.borrow();
                    if c.is_empty() { vec![0.0; 32] } else { c.clone() }
                };
                let n = bands.len().max(1);
                let mut gfx = self.gfx.borrow_mut();
                let (bw, bh) = (gfx.width, gfx.height);
                for row in 0..th { for col in 0..tw {
                    let band_idx = (col * n / tw.max(1)).min(n-1);
                    let mag = bands[band_idx].clamp(0.,1.);
                    let fill_y = (mag * th as f32) as usize;
                    if row >= th.saturating_sub(fill_y) {
                        let t = (col as f32/tw as f32 + time*speed) % 1.0;
                        let [r,g,b] = tex_palette(&palette, t);
                        let bright = mag * (1.0 - row as f32/th as f32 * 0.5);
                        let (dx, dy) = (tx+col, ty+row);
                        if dx < bw && dy < bh { gfx.buffer[dy*bw+dx] = tex_rgb(r*bright, g*bright, b*bright); }
                    }
                }}
                return Ok(Value::Unit);
            }

            // tex_spiral(x, y, w, h, freq, bands, time, palette)
            "tex_spiral" | "ลายเกลียวหมุน" => {
                let (tx,ty,tw,th) = self.tex_rect(&args)?;
                let freq    = self.arg_num(&args, 4, 5.0)? as f32;
                let n_bands = self.arg_num(&args, 5, 8.0)? as f32;
                let time    = self.arg_num(&args, 6, 0.0)? as f32;
                let palette = self.arg_str(&args, 7, "rainbow");
                let mut gfx = self.gfx.borrow_mut();
                let (bw, bh) = (gfx.width, gfx.height);
                for row in 0..th { for col in 0..tw {
                    let nx = col as f32/tw as f32 - 0.5; let ny = row as f32/th as f32 - 0.5;
                    let r  = (nx*nx + ny*ny).sqrt();
                    let theta = ny.atan2(nx);
                    let t = ((r*freq - theta/std::f32::consts::TAU + time*0.5) * n_bands % 1.0).abs();
                    let [cr,cg,cb] = tex_palette(&palette, t);
                    let (dx, dy) = (tx+col, ty+row);
                    if dx < bw && dy < bh { gfx.buffer[dy*bw+dx] = tex_rgb(cr, cg, cb); }
                }}
                return Ok(Value::Unit);
            }

            // tex_ripple(x, y, w, h, freq, cx, cy, time, palette)
            "tex_ripple" | "ลายระลอก" => {
                let (tx,ty,tw,th) = self.tex_rect(&args)?;
                let freq    = self.arg_num(&args, 4, 10.0)? as f32;
                let rcx     = self.arg_num(&args, 5, 0.5)? as f32;
                let rcy     = self.arg_num(&args, 6, 0.5)? as f32;
                let time    = self.arg_num(&args, 7, 0.0)? as f32;
                let palette = self.arg_str(&args, 8, "ocean");
                let mut gfx = self.gfx.borrow_mut();
                let (bw, bh) = (gfx.width, gfx.height);
                for row in 0..th { for col in 0..tw {
                    let nx = col as f32/tw as f32 - rcx; let ny = row as f32/th as f32 - rcy;
                    let r = (nx*nx + ny*ny).sqrt();
                    let t = ((r*freq - time) % 1.0).abs();
                    let [cr,cg,cb] = tex_palette(&palette, t);
                    let (dx, dy) = (tx+col, ty+row);
                    if dx < bw && dy < bh { gfx.buffer[dy*bw+dx] = tex_rgb(cr, cg, cb); }
                }}
                return Ok(Value::Unit);
            }

            // tex_mandelbrot(x, y, w, h, zoom, cx, cy, max_iter, palette)
            "tex_mandelbrot" | "ลายแมนเดลบรอต" => {
                let (tx,ty,tw,th) = self.tex_rect(&args)?;
                let zoom     = self.arg_num(&args, 4, 1.0)?;
                let mcx      = self.arg_num(&args, 5, -0.5)?;
                let mcy      = self.arg_num(&args, 6, 0.0)?;
                let max_iter = self.arg_num(&args, 7, 64.0)? as u32;
                let palette  = self.arg_str(&args, 8, "psychedelic");
                let mut gfx = self.gfx.borrow_mut();
                let (bw, bh) = (gfx.width, gfx.height);
                for row in 0..th { for col in 0..tw {
                    let zx0 = (col as f64/tw as f64 - 0.5)/zoom + mcx;
                    let zy0 = (row as f64/th as f64 - 0.5)/zoom + mcy;
                    let mut x = 0.0f64; let mut y = 0.0f64; let mut i = 0u32;
                    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; }
                    let t = if i==max_iter { 0.0f32 } else {
                        (i as f32 - (x as f32*x as f32+y as f32*y as f32).ln().ln()/2.0f32.ln()) / max_iter as f32
                    };
                    let [cr,cg,cb] = tex_palette(&palette, t.clamp(0.,1.));
                    let (dx, dy) = (tx+col, ty+row);
                    if dx < bw && dy < bh { gfx.buffer[dy*bw+dx] = tex_rgb(cr, cg, cb); }
                }}
                return Ok(Value::Unit);
            }

            // tex_julia(x, y, w, h, c_re, c_im, max_iter, palette)
            "tex_julia" | "ลายจูเลีย" => {
                let (tx,ty,tw,th) = self.tex_rect(&args)?;
                let c_re     = self.arg_num(&args, 4, -0.7)?;
                let c_im     = self.arg_num(&args, 5, 0.27)?;
                let max_iter = self.arg_num(&args, 6, 64.0)? as u32;
                let palette  = self.arg_str(&args, 7, "neon");
                let mut gfx = self.gfx.borrow_mut();
                let (bw, bh) = (gfx.width, gfx.height);
                for row in 0..th { for col in 0..tw {
                    let mut zx = (col as f64/tw as f64 - 0.5)*3.5;
                    let mut zy = (row as f64/th as f64 - 0.5)*3.5;
                    let mut i = 0u32;
                    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; }
                    let t = i as f32 / max_iter as f32;
                    let [cr,cg,cb] = tex_palette(&palette, t);
                    let (dx, dy) = (tx+col, ty+row);
                    if dx < bw && dy < bh { gfx.buffer[dy*bw+dx] = tex_rgb(cr, cg, cb); }
                }}
                return Ok(Value::Unit);
            }

            // tex_voronoi(x, y, w, h, cells, seed, palette)
            "tex_voronoi" | "ลายโวโรนอย" => {
                let (tx,ty,tw,th) = self.tex_rect(&args)?;
                let cells   = self.arg_num(&args, 4, 16.0)? as u32;
                let seed    = self.arg_num(&args, 5, 42.0)? as u32;
                let palette = self.arg_str(&args, 6, "rainbow");
                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();
                let mut gfx = self.gfx.borrow_mut();
                let (bw, bh) = (gfx.width, gfx.height);
                for row in 0..th { for col in 0..tw {
                    let (fx, fy) = (col as f32/tw as f32, row as f32/th as f32);
                    let (min_d, nearest) = pts.iter().enumerate().fold((f32::MAX,0usize), |(d,idx),(i,&[cx,cy])| {
                        let dd = (fx-cx).powi(2)+(fy-cy).powi(2);
                        if dd < d { (dd,i) } else { (d,idx) }
                    });
                    let t = (nearest as f32/cells as f32 + min_d*4.0) % 1.0;
                    let [cr,cg,cb] = tex_palette(&palette, t);
                    let (dx, dy) = (tx+col, ty+row);
                    if dx < bw && dy < bh { gfx.buffer[dy*bw+dx] = tex_rgb(cr, cg, cb); }
                }}
                return Ok(Value::Unit);
            }

            // tex_halftone(x, y, w, h, dot_size, time, palette)
            "tex_halftone" | "ลายฮาล์ฟโทน" => {
                let (tx,ty,tw,th) = self.tex_rect(&args)?;
                let dot_size = self.arg_num(&args, 4, 0.05)? as f32;
                let time     = self.arg_num(&args, 5, 0.0)? as f32;
                let palette  = self.arg_str(&args, 6, "rainbow");
                let mut gfx = self.gfx.borrow_mut();
                let (bw, bh) = (gfx.width, gfx.height);
                for row in 0..th { for col in 0..tw {
                    let (fx, fy) = (col as f32/tw as f32, row as f32/th as f32);
                    let gx = (fx/dot_size).floor(); let gy = (fy/dot_size).floor();
                    let lx = (fx/dot_size - gx - 0.5)*2.0; let ly = (fy/dot_size - gy - 0.5)*2.0;
                    let r = (lx*lx + ly*ly).sqrt();
                    let t = (gx/(1.0/dot_size) + time*0.1) % 1.0;
                    let a = if r < 0.7 { ((0.7-r)/0.7).clamp(0.,1.) } else { 0.0 };
                    if a > 0.0 {
                        let [cr,cg,cb] = tex_palette(&palette, t);
                        let (dx, dy) = (tx+col, ty+row);
                        if dx < bw && dy < bh { gfx.buffer[dy*bw+dx] = tex_rgb(cr, cg, cb); }
                    }
                }}
                return Ok(Value::Unit);
            }

            // ══════════════════════════════════════════════════════════════════
            // RENDER / LIGHTING MODES  (holographic cel shading)
            // ══════════════════════════════════════════════════════════════════
            // set_shade_mode(m) — 0 flat · 1 cel · 2 holo (default)
            "set_shade_mode" | "设置着色" | "シェード設定" | "셰이드모드" | "ตั้งการแรเงา" => {
                let m = self.arg_num(&args, 0, 2.0)? as u8;
                self.gfx.borrow_mut().shade_mode = m;
                return Ok(Value::Unit);
            }
            // set_cel_bands(n) — number of posterisation bands (>=2)
            "set_cel_bands" | "设置色阶" | "セル段数" | "셀밴드" | "ตั้งระดับสี" => {
                let n = (self.arg_num(&args, 0, 4.0)? as u32).max(2);
                self.gfx.borrow_mut().shade.bands = n;
                return Ok(Value::Unit);
            }
            // set_shadow_color(r,g,b) — coloured-shadow tint, 0-255
            "set_shadow_color" | "设置阴影色" | "影の色" | "그림자색" | "ตั้งสีเงา" => {
                let r=self.arg_num(&args,0,26.)? as f32/255.0;
                let g=self.arg_num(&args,1,33.)? as f32/255.0;
                let b=self.arg_num(&args,2,77.)? as f32/255.0;
                self.gfx.borrow_mut().shade.shadow = [r,g,b];
                return Ok(Value::Unit);
            }
            // set_rim(strength, r,g,b) — holographic fresnel edge glow
            // ══════════════════════════════════════════════════════════════════
            // CRYPTOGRAPHY (ling-crypto) — geo suite, hybrid PQ KEM, holographic
            // Bytes cross the language boundary as lowercase hex strings.
            // ══════════════════════════════════════════════════════════════════
            #[cfg(not(target_arch = "wasm32"))]
            "crypto_hash" | "แฮชเข้ารหัส" | "几何哈希" | "幾何ハッシュ" | "기하해시" => {
                let s = self.arg_str(&args, 0, "");
                return Ok(Value::Str(hex_encode(&ling_crypto::geo::holo_hash(s.as_bytes()))));
            }
            // 3-D torus-knot fingerprint of any text/key → flat [x,y,z, x,y,z, …]
            #[cfg(not(target_arch = "wasm32"))]
            "knot_points" | "จุดปม" | "结点坐标" | "結び目点" | "매듭점" => {
                let s = self.arg_str(&args, 0, "");
                let shape = ling_crypto::geo::KnotShape::from_bytes(s.as_bytes());
                let mut out = Vec::with_capacity(shape.points.len() * 3);
                for p in &shape.points {
                    out.push(Value::Number(p[0] as f64));
                    out.push(Value::Number(p[1] as f64));
                    out.push(Value::Number(p[2] as f64));
                }
                return Ok(Value::List(out));
            }
            #[cfg(not(target_arch = "wasm32"))]
            "knot_label" | "ป้ายปม" | "结点标签" | "結び目ラベル" | "매듭라벨" => {
                let s = self.arg_str(&args, 0, "");
                return Ok(Value::Str(ling_crypto::geo::KnotShape::from_bytes(s.as_bytes()).label()));
            }
            // KEM keypair (hybrid X25519+ML-KEM-768) → integer handle
            #[cfg(not(target_arch = "wasm32"))]
            "knot_keygen" | "hybrid_keygen" | "สร้างกุญแจปม" | "生成密钥" | "鍵生成" | "키생성" => {
                self.crypto_ids.push(ling_crypto::KnotIdentity::generate());
                return Ok(Value::Number((self.crypto_ids.len() - 1) as f64));
            }
            #[cfg(not(target_arch = "wasm32"))]
            "knot_public" | "hybrid_public" | "กุญแจสาธารณะปม" | "公钥" | "公開鍵" | "공개키" => {
                let h = self.arg_num(&args, 0, 0.0)? as usize;
                let pk = self.crypto_ids.get(h).map(|id| hex_encode(id.public_key())).unwrap_or_default();
                return Ok(Value::Str(pk));
            }
            // encapsulate(pubkey_hex) → [ciphertext_hex, shared_secret_hex]
            #[cfg(not(target_arch = "wasm32"))]
            "knot_encapsulate" | "hybrid_encapsulate" | "ห่อกุญแจปม" | "封装密钥" | "カプセル化" | "캡슐화" => {
                let pk = hex_decode(&self.arg_str(&args, 0, ""));
                match ling_crypto::geo::knot_encapsulate(&pk) {
                    Ok((ct, ss)) => return Ok(Value::List(vec![Value::Str(hex_encode(&ct)), Value::Str(hex_encode(&ss))])),
                    Err(e) => return Ok(Value::Err(Box::new(Value::Str(e.to_string())))),
                }
            }
            // decapsulate(handle, ciphertext_hex) → shared_secret_hex
            #[cfg(not(target_arch = "wasm32"))]
            "knot_decapsulate" | "hybrid_decapsulate" | "แกะกุญแจปม" | "解封装密钥" | "カプセル解除" | "캡슐해제" => {
                let h = self.arg_num(&args, 0, 0.0)? as usize;
                let ct = hex_decode(&self.arg_str(&args, 1, ""));
                let ss = self.crypto_ids.get(h)
                    .and_then(|id| id.decapsulate(&ct).ok())
                    .map(|s| hex_encode(&s)).unwrap_or_default();
                return Ok(Value::Str(ss));
            }
            // Authenticated encryption (XChaCha20-Poly1305) — seal(key_hex, text) → ct_hex
            #[cfg(not(target_arch = "wasm32"))]
            "crypto_seal" | "ผนึก" | "封印" | "封印する" | "봉인" => {
                let key = hex_to_32(&self.arg_str(&args, 0, ""));
                let pt = self.arg_str(&args, 1, "");
                match ling_crypto::geo::holo_seal(key, pt.as_bytes()) {
                    Ok(ct) => return Ok(Value::Str(hex_encode(&ct))),
                    Err(e) => return Ok(Value::Err(Box::new(Value::Str(e.to_string())))),
                }
            }
            #[cfg(not(target_arch = "wasm32"))]
            "crypto_open" | "เปิดผนึก" | "解封" | "封印解除" | "봉인해제" => {
                let key = hex_to_32(&self.arg_str(&args, 0, ""));
                let ct = hex_decode(&self.arg_str(&args, 1, ""));
                match ling_crypto::geo::holo_open(key, &ct) {
                    Ok(pt) => return Ok(Value::Str(String::from_utf8_lossy(&pt).into_owned())),
                    Err(e) => return Ok(Value::Err(Box::new(Value::Str(e.to_string())))),
                }
            }
            // Holographic all-or-nothing transform — 4-D fragment coords [a,b,c,d, …]
            #[cfg(not(target_arch = "wasm32"))]
            "holo_points" | "จุดโฮโลแกรม" | "全息点" | "ホログラム点" | "홀로그램점" => {
                let s = self.arg_str(&args, 0, "");
                let frags = ling_crypto::geo::scatter(s.as_bytes());
                let mut out = Vec::with_capacity(frags.len() * 4);
                for f in &frags { for c in f.coord { out.push(Value::Number(c as f64)); } }
                return Ok(Value::List(out));
            }
            #[cfg(not(target_arch = "wasm32"))]
            "holo_fragment_count" | "จำนวนชิ้นโฮโลแกรม" | "全息碎片数" | "ホログラム断片数" | "홀로그램조각수" => {
                let s = self.arg_str(&args, 0, "");
                return Ok(Value::Number(ling_crypto::geo::scatter(s.as_bytes()).len() as f64));
            }

            // ══════════════════════════════════════════════════════════════════
            // ling-ui — animation easings + holographic vector widgets + text I/O
            // ══════════════════════════════════════════════════════════════════
            "ease" => {
                let name = self.arg_str(&args, 0, "ease");
                let t = self.arg_num(&args, 1, 0.0)? as f32;
                return Ok(Value::Number(ling_ui::Easing::from_name(&name).apply(t) as f64));
            }
            #[cfg(not(target_arch = "wasm32"))]
            "mouse_x" => {
                let gfx = self.gfx.borrow();
                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);
                return Ok(Value::Number(v));
            }
            #[cfg(not(target_arch = "wasm32"))]
            "mouse_y" => {
                let gfx = self.gfx.borrow();
                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);
                return Ok(Value::Number(v));
            }
            #[cfg(not(target_arch = "wasm32"))]
            "mouse_down" => {
                let gfx = self.gfx.borrow();
                let d = gfx.window.as_ref().map(|w| w.get_mouse_down(minifb::MouseButton::Left)).unwrap_or(false);
                return Ok(Value::Bool(d));
            }
            #[cfg(not(target_arch = "wasm32"))]
            "ui_hot" | "热区" | "ホットエリア" | "핫존" | "พื้นที่สัมผัส" => {
                let x = self.arg_num(&args,0,0.0)? as f32;
                let y = self.arg_num(&args,1,0.0)? as f32;
                let w = self.arg_num(&args,2,0.0)? as f32;
                let h = self.arg_num(&args,3,0.0)? as f32;
                let gfx = self.gfx.borrow();
                let (mx,my) = gfx.window.as_ref().and_then(|win| win.get_mouse_pos(minifb::MouseMode::Clamp)).unwrap_or((0.0,0.0));
                return Ok(Value::Bool(ling_ui::holo::hit_rect(mx,my,x,y,w,h)));
            }
            // ui_text(x, y, scale, "string") — holographic vector text
            "ui_text" | "界面文字" | "UI文字" | "UI텍스트" | "ข้อความหน้าจอ" => {
                let x = self.arg_num(&args,0,0.0)? as f32;
                let y = self.arg_num(&args,1,0.0)? as f32;
                let scale = self.arg_num(&args,2,16.0)? as f32;
                let s = self.arg_str(&args,3,"");
                let segs = ling_ui::holo::text_lines(&s, x, y, scale*0.62, scale, scale*0.24);
                let mut gfx = self.gfx.borrow_mut();
                let (w,h,color) = (gfx.width, gfx.height, gfx.color);
                for sg in segs { draw_line(&mut gfx.buffer, w, h, color, sg[0], sg[1], sg[2], sg[3]); }
                return Ok(Value::Unit);
            }
            // font_load("path.ttf") — load a vector font (outlines cached lazily as
            // cache/fonts/<stem>/<codepoint>.ling). Returns a handle, or -1 on failure.
            #[cfg(not(target_arch = "wasm32"))]
            "font_load" | "โหลดฟอนต์" | "加载字体" | "フォント読込" | "글꼴로드" => {
                let path = self.arg_str(&args, 0, "");
                // Optional 2nd arg: variable-font weight (e.g. 600 for a solid, bold UI).
                let weight = match self.arg_num(&args, 1, 0.0)? {
                    w if w > 0.0 => Some(w as f32),
                    _ => None,
                };
                // Try the path as given, then relative to the script's directory.
                let mut loaded = ling_graphics::VectorFont::from_path_weight(&path, weight);
                if loaded.is_err() {
                    if let Some(dir) = &self.source_dir {
                        let joined = dir.join(&path);
                        loaded = ling_graphics::VectorFont::from_path_weight(&joined.to_string_lossy(), weight);
                    }
                }
                match loaded {
                    Ok(f) => {
                        let id = self.fonts.len();
                        self.fonts.push(f);
                        return Ok(Value::Number(id as f64));
                    }
                    Err(e) => {
                        eprintln!("font_load failed ({path}): {e}");
                        return Ok(Value::Number(-1.0));
                    }
                }
            }
            // font_text(handle, x, y, px, "string") — anti-aliased *stroked* vector outline
            // in the current set_color / set_blend. (x,y) is the text box top-left.
            #[cfg(not(target_arch = "wasm32"))]
            "font_text" | "ข้อความฟอนต์" | "字体文本" | "フォント文字" | "글꼴텍스트" => {
                let id = self.arg_num(&args, 0, 0.0)? as i64;
                let x  = self.arg_num(&args, 1, 0.0)? as f32;
                let y  = self.arg_num(&args, 2, 0.0)? as f32;
                let px = self.arg_num(&args, 3, 16.0)? as f32;
                let s  = self.arg_str(&args, 4, "");
                if id >= 0 && (id as usize) < self.fonts.len() && px > 0.0 {
                    let strokes = self.font_layout_2d(id as usize, x, y, px, &s);
                    let mut gfx = self.gfx.borrow_mut();
                    let (w, h, color, add) = (gfx.width, gfx.height, gfx.color, gfx.blend == 1);
                    for pl in &strokes {
                        for seg in pl.windows(2) {
                            crate::gfx::raster::draw_line_aa(&mut gfx.buffer, w, h, color, add,
                                seg[0][0], seg[0][1], seg[1][0], seg[1][1]);
                        }
                    }
                }
                return Ok(Value::Unit);
            }
            // font_text_fill(handle, x, y, px, "string") — anti-aliased *filled* vector glyphs.
            #[cfg(not(target_arch = "wasm32"))]
            "font_text_fill" | "เติมฟอนต์" | "填充字体" | "フォント塗り" | "글꼴채움" => {
                let id = self.arg_num(&args, 0, 0.0)? as i64;
                let x  = self.arg_num(&args, 1, 0.0)? as f32;
                let y  = self.arg_num(&args, 2, 0.0)? as f32;
                let px = self.arg_num(&args, 3, 16.0)? as f32;
                let s  = self.arg_str(&args, 4, "");
                if id >= 0 && (id as usize) < self.fonts.len() && px > 0.0 {
                    // fill each glyph independently so interior holes (winding) stay correct
                    let glyphs = self.font_layout_2d_glyphs(id as usize, x, y, px, &s);
                    let mut gfx = self.gfx.borrow_mut();
                    let (w, h, color, add) = (gfx.width, gfx.height, gfx.color, gfx.blend == 1);
                    for contours in &glyphs {
                        crate::gfx::raster::fill_contours_aa(&mut gfx.buffer, w, h, color, add, contours);
                    }
                }
                return Ok(Value::Unit);
            }
            // font_text_3d(handle, cx,cy,cz, ux,uy,uz, vx,vy,vz, size, "string")
            // — stroked vector text on a 3D plane: u = advance dir, v = up dir, size = world/em.
            //   Flows through the depth-sorted line pipeline, so it rotates with the camera (and 4D).
            #[cfg(not(target_arch = "wasm32"))]
            "font_text_3d" | "ข้อความฟอนต์3มิติ" | "字体3D" | "フォント3D" | "글꼴3D" => {
                let id = self.arg_num(&args, 0, 0.0)? as i64;
                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;
                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;
                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;
                let size=self.arg_num(&args,10,1.0)? as f32;
                let s = self.arg_str(&args,11,"");
                if id >= 0 && (id as usize) < self.fonts.len() && size > 0.0 {
                    // Build world-space polylines: world = C + (pen+ex)*size*U + ey*size*V
                    let font = &mut self.fonts[id as usize];
                    let asc = font.ascent();
                    let mut pen = 0.0f32;
                    let mut lines: Vec<[f32; 6]> = Vec::new();
                    for ch in s.chars() {
                        let go = font.glyph_outline(ch, 0.01);
                        for pl in &go.polylines {
                            for seg in pl.windows(2) {
                                let map = |p: [f32; 2]| {
                                    let a = pen + p[0];
                                    let b = p[1] - asc; // shift so the top of the cap sits near C
                                    [cx + a*size*ux + b*size*vx,
                                     cy + a*size*uy + b*size*vy,
                                     cz + a*size*uz + b*size*vz]
                                };
                                let p0 = map(seg[0]); let p1 = map(seg[1]);
                                lines.push([p0[0],p0[1],p0[2], p1[0],p1[1],p1[2]]);
                            }
                        }
                        pen += go.advance;
                    }
                    let mut gfx = self.gfx.borrow_mut();
                    let color = gfx.color;
                    let near = -gfx.camera.zdist + 0.05;
                    for l in &lines {
                        let (mut ax, mut ay, mut az) = (l[0], l[1], l[2]);
                        let (mut bx, mut by, mut bz) = (l[3], l[4], l[5]);
                        let da = gfx.camera.depth(ax, ay, az);
                        let db = gfx.camera.depth(bx, by, bz);
                        if da <= near && db <= near { continue; }
                        if da <= near {
                            let t = (near - da) / (db - da);
                            ax += t*(bx-ax); ay += t*(by-ay); az += t*(bz-az);
                        } else if db <= near {
                            let t = (near - da) / (db - da);
                            bx = ax + t*(bx-ax); by = ay + t*(by-ay); bz = az + t*(bz-az);
                        }
                        let (sax, say, da2) = gfx.camera.project(ax, ay, az);
                        let (sbx, sby, db2) = gfx.camera.project(bx, by, bz);
                        let depth = (da2 + db2) / 2.0;
                        gfx.depth_queue.push_line(depth, color, sax, say, sbx, sby);
                    }
                }
                return Ok(Value::Unit);
            }
            // font_width(handle, px, "string") — pixel width of a string in a loaded font.
            #[cfg(not(target_arch = "wasm32"))]
            "font_width" | "ความกว้างฟอนต์" | "字体宽度" | "フォント幅" | "글꼴너비" => {
                let id = self.arg_num(&args, 0, 0.0)? as i64;
                let px = self.arg_num(&args, 1, 16.0)? as f32;
                let s  = self.arg_str(&args, 2, "");
                if id >= 0 && (id as usize) < self.fonts.len() {
                    return Ok(Value::Number(self.fonts[id as usize].measure(&s, px) as f64));
                }
                return Ok(Value::Number(0.0));
            }
            // ui_frame(x,y,w,h, bracketLen) — sci-fi corner brackets
            "ui_frame" | "边框" | "フレーム枠" | "프레임틀" | "กรอบ" => {
                let x=self.arg_num(&args,0,0.0)? as f32; let y=self.arg_num(&args,1,0.0)? as f32;
                let w0=self.arg_num(&args,2,0.0)? as f32; let h0=self.arg_num(&args,3,0.0)? as f32;
                let l=self.arg_num(&args,4,14.0)? as f32;
                let segs = ling_ui::holo::corner_brackets(x,y,w0,h0,l);
                let mut gfx = self.gfx.borrow_mut();
                let (w,h,color)=(gfx.width,gfx.height,gfx.color);
                for sg in segs { draw_line(&mut gfx.buffer, w,h,color, sg[0],sg[1],sg[2],sg[3]); }
                return Ok(Value::Unit);
            }
            // ui_bevel(x,y,w,h, bevel) — beveled holographic panel outline
            "ui_bevel" | "斜角框" | "ベベル枠" | "베벨틀" | "กรอบเฉียง" => {
                let x=self.arg_num(&args,0,0.0)? as f32; let y=self.arg_num(&args,1,0.0)? as f32;
                let w0=self.arg_num(&args,2,0.0)? as f32; let h0=self.arg_num(&args,3,0.0)? as f32;
                let bv=self.arg_num(&args,4,10.0)? as f32;
                let segs = ling_ui::holo::beveled_rect(x,y,w0,h0,bv);
                let mut gfx = self.gfx.borrow_mut();
                let (w,h,color)=(gfx.width,gfx.height,gfx.color);
                for sg in segs { draw_line(&mut gfx.buffer, w,h,color, sg[0],sg[1],sg[2],sg[3]); }
                return Ok(Value::Unit);
            }

            // ══════════════════════════════════════════════════════════════════
            // VECTOR UI TOOLKIT  (crates/ling-ui/src/widgets.rs)
            // All widgets are vector + theme-coloured with an optional trailing
            // r,g,b override; interactive ones read the mouse and return state.
            // ══════════════════════════════════════════════════════════════════
            #[cfg(not(target_arch = "wasm32"))]
            "ui_theme" | "界面主题" | "UIテーマ" | "인터페이스테마" | "ธีมส่วนติดต่อ" => {
                let cur = self.ui_theme;
                let primary = self.color_at(&args, 0,  cur.primary);
                let accent  = self.color_at(&args, 3,  cur.accent);
                let track   = self.color_at(&args, 6,  cur.track);
                let warn    = self.color_at(&args, 9,  cur.warn);
                let text    = self.color_at(&args, 12, cur.text);
                let bg      = self.color_at(&args, 15, cur.bg);
                self.ui_theme = UiTheme { primary, accent, track, warn, text, bg };
                return Ok(Value::Unit);
            }

            // ── HUD ──────────────────────────────────────────────────────────
            #[cfg(not(target_arch = "wasm32"))]
            "ui_radar" | "雷达" | "レーダー" | "레이더" | "เรดาร์" => {
                let cx=self.arg_num(&args,0,0.)? as f32; let cy=self.arg_num(&args,1,0.)? as f32;
                let r=self.arg_num(&args,2,60.)? as f32; let sweep=self.arg_num(&args,3,0.)? as f32;
                let th=self.ui_theme;
                let prim=self.color_at(&args,4,th.primary);
                self.draw_ui(&ling_ui::widgets::radar(cx,cy,r,sweep, prim, th.accent, th.track));
                return Ok(Value::Unit);
            }
            #[cfg(not(target_arch = "wasm32"))]
            "ui_compass" | "罗盘" | "コンパス" | "나침반" | "เข็มทิศ" => {
                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
                let w0=self.arg_num(&args,2,300.)? as f32; let h0=self.arg_num(&args,3,24.)? as f32;
                let head=self.arg_num(&args,4,0.)? as f32;
                let th=self.ui_theme; let prim=self.color_at(&args,5,th.primary);
                self.draw_ui(&ling_ui::widgets::compass(x,y,w0,h0,head, prim, th.track));
                return Ok(Value::Unit);
            }
            #[cfg(not(target_arch = "wasm32"))]
            "ui_reticle" | "准星" | "照準" | "조준선" | "เป้าเล็ง" => {
                let cx=self.arg_num(&args,0,0.)? as f32; let cy=self.arg_num(&args,1,0.)? as f32;
                let r=self.arg_num(&args,2,30.)? as f32; let spread=self.arg_num(&args,3,0.)? as f32;
                let th=self.ui_theme; let prim=self.color_at(&args,4,th.primary);
                self.draw_ui(&ling_ui::widgets::reticle(cx,cy,r,spread, prim));
                return Ok(Value::Unit);
            }
            #[cfg(not(target_arch = "wasm32"))]
            "ui_target" | "锁定框" | "ターゲット" | "표적" | "กรอบเป้า" => {
                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
                let w0=self.arg_num(&args,2,80.)? as f32; let h0=self.arg_num(&args,3,80.)? as f32;
                let lock=self.arg_num(&args,4,0.)? as f32;
                let th=self.ui_theme; let prim=self.color_at(&args,5,th.primary);
                self.draw_ui(&ling_ui::widgets::target(x,y,w0,h0,lock, prim, th.accent));
                return Ok(Value::Unit);
            }
            #[cfg(not(target_arch = "wasm32"))]
            "ui_panel" | "面板" | "パネル" | "패널" | "แผง" => {
                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
                let w0=self.arg_num(&args,2,200.)? as f32; let h0=self.arg_num(&args,3,120.)? as f32;
                let bv=self.arg_num(&args,4,12.)? as f32;
                let th=self.ui_theme; let prim=self.color_at(&args,5,th.primary);
                self.draw_ui(&ling_ui::widgets::panel(x,y,w0,h0,bv, prim, th.bg));
                return Ok(Value::Unit);
            }
            #[cfg(not(target_arch = "wasm32"))]
            "ui_scanlines" | "扫描线" | "走査線" | "스캔라인" | "เส้นสแกน" => {
                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
                let w0=self.arg_num(&args,2,200.)? as f32; let h0=self.arg_num(&args,3,120.)? as f32;
                let dens=self.arg_num(&args,4,24.)? as usize;
                let th=self.ui_theme; let line=self.color_at(&args,5,th.track);
                self.draw_ui(&ling_ui::widgets::scanlines(x,y,w0,h0,dens, line));
                return Ok(Value::Unit);
            }

            // ── Meters ───────────────────────────────────────────────────────
            #[cfg(not(target_arch = "wasm32"))]
            "ui_bar" | "进度条" | "バー" | "막대" | "แถบ" => {
                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
                let w0=self.arg_num(&args,2,160.)? as f32; let h0=self.arg_num(&args,3,16.)? as f32;
                let val=self.arg_num(&args,4,0.)? as f32; let max=self.arg_num(&args,5,1.)? as f32;
                let th=self.ui_theme; let fill=self.color_at(&args,6,th.primary);
                self.draw_ui(&ling_ui::widgets::bar(x,y,w0,h0, val/max.max(1e-6), fill, th.track));
                return Ok(Value::Unit);
            }
            #[cfg(not(target_arch = "wasm32"))]
            "ui_segbar" | "分段条" | "分割バー" | "분할막대" | "แถบแบ่ง" => {
                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
                let w0=self.arg_num(&args,2,160.)? as f32; let h0=self.arg_num(&args,3,16.)? as f32;
                let val=self.arg_num(&args,4,0.)? as f32; let max=self.arg_num(&args,5,1.)? as f32;
                let segs=self.arg_num(&args,6,10.)? as usize;
                let th=self.ui_theme; let fill=self.color_at(&args,7,th.primary);
                self.draw_ui(&ling_ui::widgets::segbar(x,y,w0,h0, val/max.max(1e-6), segs, fill, th.track));
                return Ok(Value::Unit);
            }
            #[cfg(not(target_arch = "wasm32"))]
            "ui_gauge" | "仪表" | "ゲージ" | "게이지" | "มาตรวัด" => {
                let cx=self.arg_num(&args,0,0.)? as f32; let cy=self.arg_num(&args,1,0.)? as f32;
                let r=self.arg_num(&args,2,50.)? as f32;
                let val=self.arg_num(&args,3,0.)? as f32; let max=self.arg_num(&args,4,1.)? as f32;
                let th=self.ui_theme; let needle=self.color_at(&args,5,th.warn);
                self.draw_ui(&ling_ui::widgets::gauge(cx,cy,r, val/max.max(1e-6), needle, th.accent, th.track));
                return Ok(Value::Unit);
            }
            #[cfg(not(target_arch = "wasm32"))]
            "ui_ring" | "环表" | "リングメーター" | "링미터" | "วงแหวนวัด" => {
                let cx=self.arg_num(&args,0,0.)? as f32; let cy=self.arg_num(&args,1,0.)? as f32;
                let r=self.arg_num(&args,2,40.)? as f32;
                let val=self.arg_num(&args,3,0.)? as f32; let max=self.arg_num(&args,4,1.)? as f32;
                let th=self.ui_theme; let fill=self.color_at(&args,5,th.primary);
                self.draw_ui(&ling_ui::widgets::ring(cx,cy,r, val/max.max(1e-6), fill, th.track));
                return Ok(Value::Unit);
            }
            #[cfg(not(target_arch = "wasm32"))]
            "ui_vu" | "音量条" | "VUメーター" | "음량막대" | "มาตรเสียง" => {
                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
                let w0=self.arg_num(&args,2,160.)? as f32; let h0=self.arg_num(&args,3,60.)? as f32;
                let levels=self.arg_list_f32(&args,4);
                let th=self.ui_theme; let fill=self.color_at(&args,5,th.primary);
                self.draw_ui(&ling_ui::widgets::vu(x,y,w0,h0, &levels, fill, th.warn));
                return Ok(Value::Unit);
            }
            #[cfg(not(target_arch = "wasm32"))]
            "ui_spark" | "迷你图" | "スパークライン" | "스파크라인" | "กราฟจิ๋ว" => {
                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
                let w0=self.arg_num(&args,2,160.)? as f32; let h0=self.arg_num(&args,3,40.)? as f32;
                let vals=self.arg_list_f32(&args,4);
                let th=self.ui_theme; let line=self.color_at(&args,5,th.accent);
                self.draw_ui(&ling_ui::widgets::spark(x,y,w0,h0, &vals, line));
                return Ok(Value::Unit);
            }
            #[cfg(not(target_arch = "wasm32"))]
            "ui_battery" | "电池" | "バッテリー" | "배터리" | "แบตเตอรี่" => {
                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
                let w0=self.arg_num(&args,2,50.)? as f32; let h0=self.arg_num(&args,3,22.)? as f32;
                let val=self.arg_num(&args,4,1.)? as f32; let max=self.arg_num(&args,5,1.)? as f32;
                let th=self.ui_theme; let fill=self.color_at(&args,6,th.accent);
                self.draw_ui(&ling_ui::widgets::battery(x,y,w0,h0, val/max.max(1e-6), fill, th.track, th.warn));
                return Ok(Value::Unit);
            }

            // ── Interface controls (interactive → return state) ──────────────
            #[cfg(not(target_arch = "wasm32"))]
            "ui_button" | "按钮" | "ボタン" | "버튼" | "ปุ่ม" => {
                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
                let w0=self.arg_num(&args,2,120.)? as f32; let h0=self.arg_num(&args,3,40.)? as f32;
                let (mx,my,down)=self.mouse_now();
                let hover=ling_ui::holo::hit_rect(mx,my,x,y,w0,h0);
                let clicked = hover && down && !self.mouse_was_down;
                let th=self.ui_theme; let prim=self.color_at(&args,4,th.primary);
                self.draw_ui(&ling_ui::widgets::button(x,y,w0,h0, hover, down&&hover, prim, th.bg));
                return Ok(Value::Number(if clicked {1.0} else {0.0}));
            }
            #[cfg(not(target_arch = "wasm32"))]
            "ui_toggle" | "开关" | "トグル" | "토글" | "สวิตช์" => {
                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
                let w0=self.arg_num(&args,2,52.)? as f32; let h0=self.arg_num(&args,3,24.)? as f32;
                let mut state=self.arg_num(&args,4,0.)? > 0.5;
                let (mx,my,down)=self.mouse_now();
                let hover=ling_ui::holo::hit_rect(mx,my,x,y,w0,h0);
                if hover && down && !self.mouse_was_down { state = !state; }
                let th=self.ui_theme; let on=self.color_at(&args,5,th.accent);
                self.draw_ui(&ling_ui::widgets::toggle(x,y,w0,h0, state, on, th.track));
                return Ok(Value::Number(if state {1.0} else {0.0}));
            }
            #[cfg(not(target_arch = "wasm32"))]
            "ui_slider" | "滑块" | "スライダー" | "슬라이더" | "แถบเลื่อน" => {
                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
                let w0=self.arg_num(&args,2,160.)? as f32;
                let mut val=self.arg_num(&args,3,0.)? as f32;
                let mn=self.arg_num(&args,4,0.)? as f32; let mx_=self.arg_num(&args,5,1.)? as f32;
                let (mx,my,down)=self.mouse_now();
                let hover=ling_ui::holo::hit_rect(mx,my,x-8.0,y-10.0,w0+16.0,20.0);
                if hover && down {
                    let frac=((mx-x)/w0).max(0.0).min(1.0);
                    val = mn + (mx_-mn)*frac;
                }
                let frac=((val-mn)/(mx_-mn).abs().max(1e-6)).max(0.0).min(1.0);
                let th=self.ui_theme; let fill=self.color_at(&args,6,th.primary);
                self.draw_ui(&ling_ui::widgets::slider(x,y,w0, frac, hover, fill, th.track));
                return Ok(Value::Number(val as f64));
            }
            #[cfg(not(target_arch = "wasm32"))]
            "ui_checkbox" | "复选框" | "チェックボックス" | "체크박스" | "ช่องเลือก" => {
                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
                let s=self.arg_num(&args,2,20.)? as f32;
                let mut checked=self.arg_num(&args,3,0.)? > 0.5;
                let (mx,my,down)=self.mouse_now();
                let hover=ling_ui::holo::hit_rect(mx,my,x,y,s,s);
                if hover && down && !self.mouse_was_down { checked = !checked; }
                let th=self.ui_theme; let prim=self.color_at(&args,4,th.primary);
                self.draw_ui(&ling_ui::widgets::checkbox(x,y,s, checked, hover, prim, th.track));
                return Ok(Value::Number(if checked {1.0} else {0.0}));
            }
            #[cfg(not(target_arch = "wasm32"))]
            "ui_tabs" | "标签页" | "タブ" | "" | "แท็บ" => {
                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
                let w0=self.arg_num(&args,2,240.)? as f32; let h0=self.arg_num(&args,3,28.)? as f32;
                let count=self.arg_num(&args,4,3.)? as usize;
                let mut active=self.arg_num(&args,5,0.)? as i32;
                let (mx,my,down)=self.mouse_now();
                let mut hover=-1;
                if my>=y && my<=y+h0 && mx>=x && mx<=x+w0 && count>0 {
                    hover = (((mx-x)/(w0/count as f32)) as i32).max(0).min(count as i32-1);
                    if down && !self.mouse_was_down { active = hover; }
                }
                let th=self.ui_theme; let prim=self.color_at(&args,6,th.primary);
                self.draw_ui(&ling_ui::widgets::tabs(x,y,w0,h0, count, active as usize, hover, prim, th.track));
                return Ok(Value::Number(active as f64));
            }
            #[cfg(not(target_arch = "wasm32"))]
            "ui_progress" | "进度" | "プログレス" | "진행바" | "ความคืบหน้า" => {
                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
                let w0=self.arg_num(&args,2,200.)? as f32; let h0=self.arg_num(&args,3,12.)? as f32;
                let frac=self.arg_num(&args,4,0.)? as f32;
                let th=self.ui_theme; let fill=self.color_at(&args,5,th.accent);
                self.draw_ui(&ling_ui::widgets::progress(x,y,w0,h0, frac, fill, th.track));
                return Ok(Value::Unit);
            }
            #[cfg(not(target_arch = "wasm32"))]
            "ui_tooltip" | "提示框" | "ツールチップ" | "툴팁" | "คำแนะนำ" => {
                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
                let w0=self.arg_num(&args,2,120.)? as f32; let h0=self.arg_num(&args,3,28.)? as f32;
                let th=self.ui_theme; let prim=self.color_at(&args,4,th.primary);
                self.draw_ui(&ling_ui::widgets::tooltip(x,y,w0,h0, prim, th.bg));
                return Ok(Value::Unit);
            }
            #[cfg(not(target_arch = "wasm32"))]
            "ui_stepper" | "步进器" | "ステッパー" | "스테퍼" | "ตัวปรับค่า" => {
                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
                let w0=self.arg_num(&args,2,120.)? as f32; let h0=self.arg_num(&args,3,28.)? as f32;
                let mut val=self.arg_num(&args,4,0.)? as f32; let step=self.arg_num(&args,5,1.)? as f32;
                let (mx,my,down)=self.mouse_now();
                let hm=ling_ui::holo::hit_rect(mx,my,x,y,h0,h0);
                let hp=ling_ui::holo::hit_rect(mx,my,x+w0-h0,y,h0,h0);
                if down && !self.mouse_was_down { if hm { val -= step; } if hp { val += step; } }
                let th=self.ui_theme; let prim=self.color_at(&args,6,th.primary);
                self.draw_ui(&ling_ui::widgets::stepper(x,y,w0,h0, hm, hp, prim, th.track));
                return Ok(Value::Number(val as f64));
            }

            // ── Game UI ──────────────────────────────────────────────────────
            #[cfg(not(target_arch = "wasm32"))]
            "ui_healthbar" | "血条" | "体力バー" | "체력바" | "แถบพลังชีวิต" => {
                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
                let w0=self.arg_num(&args,2,180.)? as f32; let h0=self.arg_num(&args,3,16.)? as f32;
                let val=self.arg_num(&args,4,1.)? as f32; let max=self.arg_num(&args,5,1.)? as f32;
                let pulse=self.arg_num(&args,6,0.)? as f32;
                let th=self.ui_theme; let full=self.color_at(&args,7,th.accent);
                self.draw_ui(&ling_ui::widgets::healthbar(x,y,w0,h0, val/max.max(1e-6), pulse, full, th.warn, th.track));
                return Ok(Value::Unit);
            }
            #[cfg(not(target_arch = "wasm32"))]
            "ui_cooldown" | "冷却" | "クールダウン" | "쿨다운" | "คูลดาวน์" => {
                let cx=self.arg_num(&args,0,0.)? as f32; let cy=self.arg_num(&args,1,0.)? as f32;
                let r=self.arg_num(&args,2,28.)? as f32; let frac=self.arg_num(&args,3,0.)? as f32;
                let th=self.ui_theme; let fill=self.color_at(&args,4,th.primary);
                self.draw_ui(&ling_ui::widgets::cooldown(cx,cy,r, frac, fill, th.track));
                return Ok(Value::Unit);
            }
            #[cfg(not(target_arch = "wasm32"))]
            "ui_counter" | "计数器" | "カウンター" | "카운터" | "ตัวนับ" => {
                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
                let dw=self.arg_num(&args,2,14.)? as f32; let dh=self.arg_num(&args,3,24.)? as f32;
                let val=self.arg_num(&args,4,0.)? as i64; let digits=self.arg_num(&args,5,4.)? as usize;
                let th=self.ui_theme; let on=self.color_at(&args,6,th.primary);
                let off=ling_ui::widgets::shade(th.track,0.5);
                self.draw_ui(&ling_ui::widgets::counter(x,y,dw,dh, val, digits, on, off));
                return Ok(Value::Unit);
            }
            #[cfg(not(target_arch = "wasm32"))]
            "ui_minimap" | "小地图" | "ミニマップ" | "미니맵" | "แผนที่ย่อ" => {
                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
                let w0=self.arg_num(&args,2,140.)? as f32; let h0=self.arg_num(&args,3,140.)? as f32;
                let th=self.ui_theme; let prim=self.color_at(&args,4,th.primary);
                self.draw_ui(&ling_ui::widgets::minimap(x,y,w0,h0, prim, th.bg));
                return Ok(Value::Unit);
            }
            #[cfg(not(target_arch = "wasm32"))]
            "ui_dpad" | "方向键" | "方向パッド" | "방향패드" | "ปุ่มทิศทาง" => {
                let cx=self.arg_num(&args,0,0.)? as f32; let cy=self.arg_num(&args,1,0.)? as f32;
                let r=self.arg_num(&args,2,50.)? as f32;
                let (mx,my,down)=self.mouse_now();
                let mut dir=0;
                if down {
                    let (dx,dy)=(mx-cx, my-cy);
                    if dx*dx+dy*dy <= r*r {
                        if dx.abs() > dy.abs() { dir = if dx>0.0 {2} else {4}; }
                        else { dir = if dy>0.0 {3} else {1}; }
                    }
                }
                let th=self.ui_theme; let prim=self.color_at(&args,3,th.primary);
                self.draw_ui(&ling_ui::widgets::dpad(cx,cy,r, dir, prim, th.track));
                return Ok(Value::Number(dir as f64));
            }
            #[cfg(not(target_arch = "wasm32"))]
            "ui_slotgrid" | "物品格" | "スロットグリッド" | "슬롯격자" | "ช่องไอเทม" => {
                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
                let cols=self.arg_num(&args,2,4.)? as usize; let rows=self.arg_num(&args,3,1.)? as usize;
                let cell=self.arg_num(&args,4,36.)? as f32; let sel=self.arg_num(&args,5,-1.)? as i32;
                let th=self.ui_theme; let prim=self.color_at(&args,6,th.primary);
                self.draw_ui(&ling_ui::widgets::slotgrid(x,y,cols,rows,cell, sel, prim, th.track));
                return Ok(Value::Unit);
            }
            #[cfg(not(target_arch = "wasm32"))]
            "ui_vignette" | "暗角" | "ビネット" | "비네트" | "ขอบมืด" => {
                let intensity=self.arg_num(&args,0,0.5)? as f32;
                let (w,h)={ let g=self.gfx.borrow(); (g.width as f32, g.height as f32) };
                let th=self.ui_theme; let col=self.color_at(&args,1,th.warn);
                self.draw_ui(&ling_ui::widgets::vignette(w,h, intensity, col));
                return Ok(Value::Unit);
            }

            // ── Faux-3D in 2D space ──────────────────────────────────────────
            #[cfg(not(target_arch = "wasm32"))]
            "ui_gauge3d" | "立体仪表" | "立体ゲージ" | "입체게이지" | "มาตรวัด3มิติ" => {
                let cx=self.arg_num(&args,0,0.)? as f32; let cy=self.arg_num(&args,1,0.)? as f32;
                let r=self.arg_num(&args,2,50.)? as f32;
                let val=self.arg_num(&args,3,0.)? as f32; let max=self.arg_num(&args,4,1.)? as f32;
                let spin=self.arg_num(&args,5,0.)? as f32;
                let th=self.ui_theme; let fill=self.color_at(&args,6,th.primary);
                self.draw_ui(&ling_ui::widgets::gauge3d(cx,cy,r, val/max.max(1e-6), spin, fill, th.track));
                return Ok(Value::Unit);
            }
            #[cfg(not(target_arch = "wasm32"))]
            "ui_panel3d" | "立体面板" | "立体パネル" | "입체패널" | "แผง3มิติ" => {
                let x=self.arg_num(&args,0,0.)? as f32; let y=self.arg_num(&args,1,0.)? as f32;
                let w0=self.arg_num(&args,2,200.)? as f32; let h0=self.arg_num(&args,3,120.)? as f32;
                let depth=self.arg_num(&args,4,14.)? as f32;
                let th=self.ui_theme; let prim=self.color_at(&args,5,th.primary);
                self.draw_ui(&ling_ui::widgets::panel3d(x,y,w0,h0,depth, prim, th.bg));
                return Ok(Value::Unit);
            }
            #[cfg(not(target_arch = "wasm32"))]
            "ui_radar3d" | "立体雷达" | "立体レーダー" | "입체레이더" | "เรดาร์3มิติ" => {
                let cx=self.arg_num(&args,0,0.)? as f32; let cy=self.arg_num(&args,1,0.)? as f32;
                let r=self.arg_num(&args,2,60.)? as f32; let tilt=self.arg_num(&args,3,0.9)? as f32;
                let sweep=self.arg_num(&args,4,0.)? as f32;
                let th=self.ui_theme; let prim=self.color_at(&args,5,th.primary);
                self.draw_ui(&ling_ui::widgets::radar3d(cx,cy,r,tilt,sweep, prim, th.track));
                return Ok(Value::Unit);
            }

            // ── Interface sounds ─────────────────────────────────────────────
            #[cfg(not(target_arch = "wasm32"))]
            "audio_blip" | "提示音" | "ビープ音" | "효과음" | "เสียงบี๊บ" => {
                let freq=self.arg_num(&args,0,660.)? as f32;
                let dur=self.arg_num(&args,1,0.08)? as f32;
                let wave=Wave::from_name(&self.arg_str(&args,2,"sine"));
                let amp=self.arg_num(&args,3,0.25)? as f32;
                if let Some(audio)=&self.audio { audio.blip(freq, amp, dur, wave); }
                return Ok(Value::Unit);
            }
            #[cfg(not(target_arch = "wasm32"))]
            "ui_sound" | "界面音" | "UI音" | "인터페이스음" | "เสียงปุ่ม" => {
                let name=self.arg_str(&args,0,"click");
                if let Some(audio)=&self.audio {
                    match name.as_str() {
                        "hover"   => audio.blip(880.0, 0.10, 0.04, Wave::Sine),
                        "confirm" => { audio.blip(660.0, 0.22, 0.07, Wave::Square); audio.blip(990.0, 0.18, 0.10, Wave::Square); }
                        "error"   => { audio.blip(180.0, 0.30, 0.16, Wave::Saw); audio.blip(140.0, 0.30, 0.18, Wave::Saw); }
                        "toggle"  => audio.blip(520.0, 0.22, 0.05, Wave::Triangle),
                        "tick"    => audio.blip(1500.0, 0.12, 0.02, Wave::Square),
                        _         => audio.blip(720.0, 0.26, 0.05, Wave::Square), // "click"
                    }
                }
                return Ok(Value::Unit);
            }

            // ══════════════════════════════════════════════════════════════════
            // MUSIC TOOLKIT  (crates/ling-music) — decode · analysis · GM synth ·
            // rhythm · karaoke. Analysis/decoding need no audio device; playback
            // and synthesis lazily start a dedicated music engine.
            // ══════════════════════════════════════════════════════════════════

            // music_load(path) -> track handle (decodes WAV/FLAC/OGG/MP3/AAC)
            #[cfg(not(target_arch = "wasm32"))]
            "music_load" | "载入音乐" | "音楽読込" | "음악로드" | "โหลดเพลง" => {
                let path = self.arg_str(&args, 0, "");
                let resolved = if std::path::Path::new(&path).exists() { path.clone() }
                    else if let Some(d) = &self.source_dir { d.join(&path).to_string_lossy().into_owned() }
                    else { path.clone() };
                match ling_music::load(&resolved) {
                    Ok(t) => { let id = self.tracks.len(); self.tracks.push(t); return Ok(Value::Number(id as f64)); }
                    Err(e) => { eprintln!("music_load failed ({path}): {e}"); return Ok(Value::Number(-1.0)); }
                }
            }
            #[cfg(not(target_arch = "wasm32"))]
            "music_duration" | "音乐时长" | "音楽長さ" | "음악길이" | "ความยาวเพลง" => {
                let id = self.arg_num(&args,0,0.0)? as i64;
                let d = self.tracks.get(id as usize).map(|t| t.duration).unwrap_or(0.0);
                return Ok(Value::Number(d as f64));
            }
            #[cfg(not(target_arch = "wasm32"))]
            "music_bpm" | "节拍速度" | "テンポ" | "템포" | "จังหวะต่อนาที" => {
                let id = self.arg_num(&args,0,0.0)? as i64;
                let b = self.tracks.get(id as usize).map(|t| ling_music::analysis::bpm(&t.mono, t.rate)).unwrap_or(0.0);
                return Ok(Value::Number(b as f64));
            }
            #[cfg(not(target_arch = "wasm32"))]
            "music_key" | "调性" | "調性" | "조성" | "คีย์เพลง" => {
                let id = self.arg_num(&args,0,0.0)? as i64;
                let k = self.tracks.get(id as usize).map(|t| ling_music::analysis::key_name(&t.mono, t.rate)).unwrap_or_default();
                return Ok(Value::Str(k));
            }
            #[cfg(not(target_arch = "wasm32"))]
            "music_onsets" | "音符起点" | "オンセット" | "온셋" | "จุดเริ่มเสียง" => {
                let id = self.arg_num(&args,0,0.0)? as i64;
                let v = self.tracks.get(id as usize).map(|t| ling_music::analysis::onsets(&t.mono, t.rate)).unwrap_or_default();
                return Ok(Value::List(v.into_iter().map(|x| Value::Number(x as f64)).collect()));
            }
            #[cfg(not(target_arch = "wasm32"))]
            "music_beat_grid" | "节拍网格" | "ビートグリッド" | "비트그리드" | "กริดจังหวะ" => {
                let id = self.arg_num(&args,0,0.0)? as i64;
                let beats = self.tracks.get(id as usize).map(|t| {
                    let b = ling_music::analysis::bpm(&t.mono, t.rate);
                    ling_music::analysis::beat_grid(&t.mono, t.rate, b)
                }).unwrap_or_default();
                return Ok(Value::List(beats.into_iter().map(|x| Value::Number(x as f64)).collect()));
            }

            // ── playback ──
            #[cfg(not(target_arch = "wasm32"))]
            "music_play" | "播放音乐" | "音楽再生" | "음악재생" | "เล่นเพลง" => {
                let id = self.arg_num(&args,0,0.0)? as i64;
                if self.ensure_music() {
                    let track = self.tracks.get(id as usize).map(|t| (t.stereo.clone(), t.rate));
                    if let (Some((st, rate)), Some(m)) = (track, &self.music) { m.set_track(st, rate); m.play(); }
                    else if let Some(m) = &self.music { m.play(); }
                }
                return Ok(Value::Unit);
            }
            #[cfg(not(target_arch = "wasm32"))]
            "music_pause" | "暂停音乐" | "音楽一時停止" | "음악일시정지" | "หยุดเพลงชั่วคราว" => {
                if let Some(m) = &self.music { m.pause(); } return Ok(Value::Unit);
            }
            #[cfg(not(target_arch = "wasm32"))]
            "music_stop" | "停止音乐" | "音楽停止" | "음악정지" | "หยุดเพลง" => {
                if let Some(m) = &self.music { m.stop(); } return Ok(Value::Unit);
            }
            #[cfg(not(target_arch = "wasm32"))]
            "music_seek" | "定位音乐" | "音楽シーク" | "음악탐색" | "ค้นหาเพลง" => {
                let sec = self.arg_num(&args,0,0.0)? as f32;
                if let Some(m) = &self.music { m.seek(sec); } return Ok(Value::Unit);
            }
            #[cfg(not(target_arch = "wasm32"))]
            "music_pos" | "音乐位置" | "音楽位置" | "음악위치" | "ตำแหน่งเพลง" => {
                let p = self.music.as_ref().map(|m| m.position()).unwrap_or(0.0);
                return Ok(Value::Number(p as f64));
            }
            #[cfg(not(target_arch = "wasm32"))]
            "music_volume" | "音乐音量" | "音楽音量" | "음악음량" | "ระดับเพลง" => {
                let v = self.arg_num(&args,0,0.8)? as f32;
                if self.ensure_music() { if let Some(m) = &self.music { m.set_volume(v); } }
                return Ok(Value::Unit);
            }

            // ── synthesis (GM-capable, patches from .ling files) ──
            #[cfg(not(target_arch = "wasm32"))]
            "music_patch" | "乐器音色" | "音色読込" | "악기패치" | "แพตช์เครื่องดนตรี" => {
                let path = self.arg_str(&args, 0, "");
                let resolved = if std::path::Path::new(&path).exists() { path.clone() }
                    else if let Some(d) = &self.source_dir { d.join(&path).to_string_lossy().into_owned() }
                    else { path.clone() };
                if !self.ensure_music() { return Ok(Value::Number(-1.0)); }
                match ling_music::patch::from_path(&resolved) {
                    Ok(p) => { let id = self.music.as_ref().unwrap().add_patch(p); return Ok(Value::Number(id as f64)); }
                    Err(e) => { eprintln!("music_patch failed ({path}): {e}"); return Ok(Value::Number(-1.0)); }
                }
            }
            #[cfg(not(target_arch = "wasm32"))]
            "music_note" | "弹音符" | "音符演奏" | "음표연주" | "เล่นโน้ต" => {
                let inst = self.arg_num(&args,0,0.0)? as usize;
                let midi = self.pitch_arg(&args, 1, 60);
                let dur  = self.arg_num(&args,2,0.5)? as f32;
                let vel  = self.arg_num(&args,3,0.9)? as f32;
                if self.ensure_music() { if let Some(m) = &self.music { m.note(inst, midi, vel, dur); } }
                return Ok(Value::Unit);
            }
            #[cfg(not(target_arch = "wasm32"))]
            "music_note_on" | "音符开始" | "音符オン" | "음표켜기" | "โน้ตเริ่ม" => {
                let inst = self.arg_num(&args,0,0.0)? as usize;
                let midi = self.pitch_arg(&args, 1, 60);
                let vel  = self.arg_num(&args,2,0.9)? as f32;
                if self.ensure_music() { if let Some(m) = &self.music { m.note_on(inst, midi, vel); } }
                return Ok(Value::Unit);
            }
            #[cfg(not(target_arch = "wasm32"))]
            "music_note_off" | "音符结束" | "音符オフ" | "음표끄기" | "โน้ตจบ" => {
                let inst = self.arg_num(&args,0,0.0)? as usize;
                let midi = self.pitch_arg(&args, 1, 60);
                if let Some(m) = &self.music { m.note_off(inst, midi); }
                return Ok(Value::Unit);
            }

            // ── rhythm-game judging ──
            #[cfg(not(target_arch = "wasm32"))]
            "music_judge" | "判定" | "判定する" | "판정" | "ตัดสินจังหวะ" => {
                let delta_ms = self.arg_num(&args,0,9999.0)? as f32;
                return Ok(Value::Number(ling_music::Grade::judge(delta_ms).index() as f64));
            }
            #[cfg(not(target_arch = "wasm32"))]
            "music_grade_name" | "判定名" | "判定名称" | "판정이름" | "ชื่อการตัดสิน" => {
                let idx = self.arg_num(&args,0,4.0)? as i32;
                return Ok(Value::Str(ling_music::Grade::from_index(idx).name().to_string()));
            }

            // ── karaoke ──
            #[cfg(not(target_arch = "wasm32"))]
            "music_lrc" | "载入歌词" | "歌詞読込" | "가사로드" | "โหลดเนื้อเพลง" => {
                let path = self.arg_str(&args, 0, "");
                let resolved = if std::path::Path::new(&path).exists() { path.clone() }
                    else if let Some(d) = &self.source_dir { d.join(&path).to_string_lossy().into_owned() }
                    else { path.clone() };
                match std::fs::read_to_string(&resolved) {
                    Ok(text) => { let id = self.lyrics.len(); self.lyrics.push(ling_music::Lyrics::parse(&text)); return Ok(Value::Number(id as f64)); }
                    Err(e) => { eprintln!("music_lrc failed ({path}): {e}"); return Ok(Value::Number(-1.0)); }
                }
            }
            #[cfg(not(target_arch = "wasm32"))]
            "music_lyric" | "当前歌词" | "現在歌詞" | "현재가사" | "เนื้อเพลงปัจจุบัน" => {
                let id = self.arg_num(&args,0,0.0)? as i64;
                let t  = self.arg_num(&args,1,0.0)? as f32;
                let line = self.lyrics.get(id as usize).map(|l| l.line_at(t).to_string()).unwrap_or_default();
                return Ok(Value::Str(line));
            }
            #[cfg(not(target_arch = "wasm32"))]
            "music_mic_pitch" | "麦克风音高" | "マイク音程" | "마이크음정" | "ระดับเสียงไมค์" => {
                let hz = if let Some(mic) = self.mic.as_ref() {
                    let s = mic.latest_samples();
                    let rate = mic.sample_rate();
                    ling_music::pitch::detect(&s, rate).unwrap_or(0.0)
                } else { 0.0 };
                return Ok(Value::Number(hz as f64));
            }
            #[cfg(not(target_arch = "wasm32"))]
            "music_note_name" | "音名" | "音名称" | "음이름" | "ชื่อโน้ต" => {
                let hz = self.arg_num(&args,0,0.0)? as f32;
                return Ok(Value::Str(ling_music::note::hz_to_name(hz)));
            }
            #[cfg(not(target_arch = "wasm32"))]
            "music_hz" | "音符频率" | "音符周波数" | "음표주파수" | "ความถี่โน้ต" => {
                let midi = self.pitch_arg(&args, 0, 69);
                return Ok(Value::Number(ling_music::note::midi_to_hz(midi as f32) as f64));
            }
            #[cfg(not(target_arch = "wasm32"))]
            "music_pitch_score" | "音准评分" | "音程スコア" | "음정점수" | "คะแนนเสียง" => {
                let hz = self.arg_num(&args,0,0.0)? as f32;
                let target = self.arg_num(&args,1,0.0)? as f32;
                return Ok(Value::Number(ling_music::karaoke::pitch_score(hz, target) as f64));
            }

            // ── MIDI (inaudible note source: drive coins, cues, etc.) ──
            #[cfg(not(target_arch = "wasm32"))]
            "music_midi_load" | "载入MIDI" | "MIDI読込" | "미디로드" | "โหลดมิดี" => {
                let path = self.arg_str(&args, 0, "");
                let resolved = if std::path::Path::new(&path).exists() { path.clone() }
                    else if let Some(d) = &self.source_dir { d.join(&path).to_string_lossy().into_owned() }
                    else { path.clone() };
                match ling_music::midi::load(&resolved) {
                    Ok(m) => { let id = self.midis.len(); self.midis.push(m); return Ok(Value::Number(id as f64)); }
                    Err(e) => { eprintln!("music_midi_load failed ({path}): {e}"); return Ok(Value::Number(-1.0)); }
                }
            }
            #[cfg(not(target_arch = "wasm32"))]
            "music_midi_count" | "MIDI数量" | "MIDI数" | "미디수" | "จำนวนมิดี" => {
                let id = self.arg_num(&args,0,0.0)? as i64;
                let n = self.midis.get(id as usize).map(|m| m.notes.len()).unwrap_or(0);
                return Ok(Value::Number(n as f64));
            }
            // music_midi_notes(id) -> flat [time, midi, time, midi, …]
            #[cfg(not(target_arch = "wasm32"))]
            "music_midi_notes" | "MIDI音符" | "MIDIノート" | "미디음표" | "โน้ตมิดี" => {
                let id = self.arg_num(&args,0,0.0)? as i64;
                let mut out = Vec::new();
                if let Some(m) = self.midis.get(id as usize) {
                    for n in &m.notes { out.push(Value::Number(n.time as f64)); out.push(Value::Number(n.midi as f64)); }
                }
                return Ok(Value::List(out));
            }
            // music_midi_bars(id) -> flat [time, midi, dur, …] (for karaoke note bars)
            #[cfg(not(target_arch = "wasm32"))]
            "music_midi_bars" | "MIDI音条" | "MIDIバー" | "미디바" | "แท่งมิดี" => {
                let id = self.arg_num(&args,0,0.0)? as i64;
                let mut out = Vec::new();
                if let Some(m) = self.midis.get(id as usize) {
                    for n in &m.notes {
                        out.push(Value::Number(n.time as f64));
                        out.push(Value::Number(n.midi as f64));
                        out.push(Value::Number(n.dur as f64));
                    }
                }
                return Ok(Value::List(out));
            }

            // music_fft(track_id, nbands) -> spectrum at the current playback position
            #[cfg(not(target_arch = "wasm32"))]
            "music_fft" | "音乐频谱" | "音楽スペクトル" | "음악스펙트럼" | "สเปกตรัมเพลง" => {
                let id = self.arg_num(&args,0,0.0)? as i64;
                let nbands = self.arg_num(&args,1,16.0)? as usize;
                let pos = self.music.as_ref().map(|m| m.position()).unwrap_or(0.0);
                if let Some(t) = self.tracks.get(id as usize) {
                    let idx = (pos * t.rate as f32) as usize;
                    let end = (idx + 2048).min(t.mono.len());
                    if end > idx + 64 {
                        self.fft.borrow_mut().push_samples(&t.mono[idx..end]);
                    }
                }
                let bands = self.fft.borrow().freq_bands(nbands);
                return Ok(Value::List(bands.into_iter().map(|x| Value::Number(x as f64)).collect()));
            }

            // ── spatial (2D/3D/4D) one-shot SFX ──
            #[cfg(not(target_arch = "wasm32"))]
            "audio_sfx" | "音效" | "空間効果音" | "공간효과음" | "เสียงเอฟเฟกต์" => {
                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;
                let w=self.arg_num(&args,3,1.0)? as f32; let freq=self.arg_num(&args,4,440.0)? as f32;
                let amp=self.arg_num(&args,5,0.3)? as f32; let dur=self.arg_num(&args,6,0.15)? as f32;
                let wave=Wave::from_name(&self.arg_str(&args,7,"sine"));
                if let Some(a)=&self.audio { a.sfx(x,y,z,w,freq,amp,dur,wave); }
                return Ok(Value::Unit);
            }
            // ── sample load / positional play / loop / stop ──
            #[cfg(not(target_arch = "wasm32"))]
            "audio_sample_load" | "载入采样" | "サンプル読込" | "샘플로드" | "โหลดตัวอย่างเสียง" => {
                let path = self.arg_str(&args, 0, "");
                let resolved = if std::path::Path::new(&path).exists() { path.clone() }
                    else if let Some(d) = &self.source_dir { d.join(&path).to_string_lossy().into_owned() }
                    else { path.clone() };
                match ling_music::load(&resolved) {
                    Ok(t) => {
                        if let Some(a)=&self.audio { return Ok(Value::Number(a.add_sample(t.mono, t.rate) as f64)); }
                        return Ok(Value::Number(-1.0));
                    }
                    Err(e) => { eprintln!("audio_sample_load failed ({path}): {e}"); return Ok(Value::Number(-1.0)); }
                }
            }
            #[cfg(not(target_arch = "wasm32"))]
            "audio_sample_play" | "播放采样" | "サンプル再生" | "샘플재생" | "เล่นตัวอย่างเสียง" => {
                let id=self.arg_num(&args,0,0.0)? as usize;
                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;
                let w=self.arg_num(&args,4,1.0)? as f32; let vol=self.arg_num(&args,5,1.0)? as f32;
                let looping=self.arg_num(&args,6,0.0)? > 0.5;
                let v = self.audio.as_ref().map(|a| a.play_sample(id,x,y,z,w,vol,looping)).unwrap_or(0);
                return Ok(Value::Number(v as f64));
            }
            #[cfg(not(target_arch = "wasm32"))]
            "audio_sample_stop" | "停止采样" | "サンプル停止" | "샘플정지" | "หยุดตัวอย่างเสียง" => {
                let v=self.arg_num(&args,0,0.0)? as u32;
                if let Some(a)=&self.audio { a.stop_sample(v); }
                return Ok(Value::Unit);
            }
            // ── master FX: delay / reverb / low-pass (underwater) ──
            #[cfg(not(target_arch = "wasm32"))]
            "audio_fx_delay" | "回声" | "ディレイ効果" | "딜레이" | "เสียงสะท้อน" => {
                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;
                if let Some(a)=&self.audio { a.fx_delay(time,fb,mix); }
                return Ok(Value::Unit);
            }
            #[cfg(not(target_arch = "wasm32"))]
            "audio_fx_reverb" | "混响" | "リバーブ" | "리버브" | "เสียงก้อง" => {
                let mix=self.arg_num(&args,0,0.3)? as f32;
                if let Some(a)=&self.audio { a.fx_reverb(mix); }
                return Ok(Value::Unit);
            }
            #[cfg(not(target_arch = "wasm32"))]
            "audio_fx_lowpass" | "低通滤波" | "ローパス" | "저역통과" | "กรองความถี่ต่ำ" => {
                let cutoff=self.arg_num(&args,0,1.0)? as f32;
                if let Some(a)=&self.audio { a.fx_lowpass(cutoff); }
                return Ok(Value::Unit);
            }

            // ══════════════════════════════════════════════════════════════════
            // PHYSICS BUILTINS  (crates/ling-physics) — soft bodies, rigid+angular,
            // and a fast 2-D water/oil liquid sim mappable onto 3-D surfaces.
            // ══════════════════════════════════════════════════════════════════

            // ── soft bodies (deformable bouncy balls) ──
            #[cfg(not(target_arch = "wasm32"))]
            "soft_ball" | "软球" | "ソフトボール" | "소프트볼" | "ลูกบอลนุ่ม" => {
                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;
                let r=self.arg_num(&args,3,1.0)? as f32;
                let b = ling_physics::soft::SoftBody::sphere(ling_physics::Vec3::new(x,y,z), r, 8, 12, 1.0);
                let id = self.soft_bodies.len(); self.soft_bodies.push(b);
                return Ok(Value::Number(id as f64));
            }
            #[cfg(not(target_arch = "wasm32"))]
            "soft_step" | "软体步进" | "ソフト更新" | "소프트스텝" | "ก้าวนุ่ม" => {
                let id=self.arg_num(&args,0,0.)? as usize; let dt=self.arg_num(&args,1,0.016)? as f32;
                let gy=self.arg_num(&args,2,15.0)? as f32;
                if let Some(b)=self.soft_bodies.get_mut(id) { b.integrate(dt, ling_physics::Vec3::new(0.0,gy,0.0), 4); }
                return Ok(Value::Unit);
            }
            #[cfg(not(target_arch = "wasm32"))]
            "soft_bounce" | "软体落地" | "ソフト着地" | "소프트바운스" | "เด้งนุ่ม" => {
                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;
                if let Some(b)=self.soft_bodies.get_mut(id) { b.floor_collision(fy, rest); }
                return Ok(Value::Unit);
            }
            #[cfg(not(target_arch = "wasm32"))]
            "soft_contain" | "软体边界" | "ソフト箱" | "소프트경계" | "กล่องนุ่ม" => {
                let id=self.arg_num(&args,0,0.)? as usize;
                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;
                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;
                let rest=self.arg_num(&args,7,0.6)? as f32;
                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); }
                return Ok(Value::Unit);
            }
            #[cfg(not(target_arch = "wasm32"))]
            "soft_kick" | "软体踢" | "ソフト衝撃" | "소프트킥" | "เตะนุ่ม" => {
                let id=self.arg_num(&args,0,0.)? as usize;
                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;
                let s=self.arg_num(&args,4,0.1)? as f32;
                if let Some(b)=self.soft_bodies.get_mut(id) { b.kick(ling_physics::Vec3::new(dx,dy,dz), s); }
                return Ok(Value::Unit);
            }
            #[cfg(not(target_arch = "wasm32"))]
            "soft_deform" | "形变量" | "変形量" | "변형량" | "ความบิดเบี้ยว" => {
                let id=self.arg_num(&args,0,0.)? as usize;
                let d=self.soft_bodies.get(id).map(|b| b.deformation()).unwrap_or(0.0);
                return Ok(Value::Number(d as f64));
            }
            #[cfg(not(target_arch = "wasm32"))]
            "soft_centroid" | "软体质心" | "ソフト重心" | "소프트중심" | "จุดศูนย์กลางนุ่ม" => {
                let id=self.arg_num(&args,0,0.)? as usize;
                let c=self.soft_bodies.get(id).map(|b| b.centroid()).unwrap_or(ling_physics::Vec3::ZERO);
                return Ok(Value::List(vec![Value::Number(c.x as f64),Value::Number(c.y as f64),Value::Number(c.z as f64)]));
            }
            // soft_nodes(id) -> flat [x,y,z, x,y,z, …] for rendering the deformed mesh
            #[cfg(not(target_arch = "wasm32"))]
            "soft_nodes" | "软体节点" | "ソフト節点" | "소프트노드" | "จุดนุ่ม" => {
                let id=self.arg_num(&args,0,0.)? as usize;
                let mut out=Vec::new();
                if let Some(b)=self.soft_bodies.get(id) {
                    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)); }
                }
                return Ok(Value::List(out));
            }

            // ── rigid bodies with angular dynamics ──
            #[cfg(not(target_arch = "wasm32"))]
            "rb_add" | "刚体添加" | "剛体追加" | "강체추가" | "เพิ่มวัตถุแข็ง" => {
                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;
                let mass=self.arg_num(&args,3,1.0)? as f32;
                let mut b = ling_physics::rigid::RigidBody::new(ling_physics::Vec3::new(x,y,z), mass);
                b.restitution = 0.6;
                return Ok(Value::Number(self.rigid_world.add(b) as f64));
            }
            #[cfg(not(target_arch = "wasm32"))]
            "rb_torque" | "扭矩" | "トルク" | "토크" | "แรงบิด" => {
                let i=self.arg_num(&args,0,0.)? as usize;
                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;
                if let Some(b)=self.rigid_world.bodies.get_mut(i) { b.apply_torque(ling_physics::Vec3::new(tx,ty,tz)); }
                return Ok(Value::Unit);
            }
            #[cfg(not(target_arch = "wasm32"))]
            "rb_spin" | "自旋" | "スピン" | "스핀" | "หมุน" => {
                let i=self.arg_num(&args,0,0.)? as usize;
                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;
                if let Some(b)=self.rigid_world.bodies.get_mut(i) { b.apply_spin(ling_physics::Vec3::new(wx,wy,wz)); }
                return Ok(Value::Unit);
            }
            #[cfg(not(target_arch = "wasm32"))]
            "rb_impulse" | "刚体冲量" | "剛体インパルス" | "강체충격" | "แรงดลแข็ง" => {
                let i=self.arg_num(&args,0,0.)? as usize;
                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;
                if let Some(b)=self.rigid_world.bodies.get_mut(i) { b.apply_impulse(ling_physics::Vec3::new(ix,iy,iz)); }
                return Ok(Value::Unit);
            }
            #[cfg(not(target_arch = "wasm32"))]
            "rb_floor" | "刚体落地" | "剛体着地" | "강체바닥" | "พื้นแข็ง" => {
                let i=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.6)? as f32; let fric=self.arg_num(&args,3,0.6)? as f32;
                if let Some(b)=self.rigid_world.bodies.get_mut(i) { b.bounce_floor(fy, rest, fric); }
                return Ok(Value::Unit);
            }
            #[cfg(not(target_arch = "wasm32"))]
            "rb_gravity" | "刚体重力" | "剛体重力" | "강체중력" | "แรงโน้มถ่วงแข็ง" => {
                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;
                self.rigid_world.gravity = ling_physics::Vec3::new(gx,gy,gz);
                return Ok(Value::Unit);
            }
            #[cfg(not(target_arch = "wasm32"))]
            "rb_step" | "刚体步进" | "剛体更新" | "강체스텝" | "ก้าวแข็ง" => {
                let dt=self.arg_num(&args,0,0.016)? as f32;
                self.rigid_world.step(dt);
                return Ok(Value::Unit);
            }
            #[cfg(not(target_arch = "wasm32"))]
            "rb_pos" | "刚体位置" | "剛体位置" | "강체위치" | "ตำแหน่งแข็ง" => {
                let i=self.arg_num(&args,0,0.)? as usize;
                let p=self.rigid_world.bodies.get(i).map(|b| b.pos).unwrap_or(ling_physics::Vec3::ZERO);
                return Ok(Value::List(vec![Value::Number(p.x as f64),Value::Number(p.y as f64),Value::Number(p.z as f64)]));
            }
            #[cfg(not(target_arch = "wasm32"))]
            "rb_rot" | "刚体旋转" | "剛体回転" | "강체회전" | "การหมุนแข็ง" => {
                let i=self.arg_num(&args,0,0.)? as usize;
                let q=self.rigid_world.bodies.get(i).map(|b| b.orientation).unwrap_or(ling_physics::Quat::IDENTITY);
                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)]));
            }

            // ── liquid sim (water + oil, immiscible) ──
            #[cfg(not(target_arch = "wasm32"))]
            "liquid_new" | "新建液体" | "液体新規" | "액체생성" | "สร้างของเหลว" => {
                let w=self.arg_num(&args,0,64.)? as usize; let h=self.arg_num(&args,1,64.)? as usize;
                let id=self.liquids.len(); self.liquids.push(ling_physics::liquid::LiquidGrid::new(w,h));
                return Ok(Value::Number(id as f64));
            }
            #[cfg(not(target_arch = "wasm32"))]
            "liquid_splat" | "液体注入" | "液体追加" | "액체분사" | "หยดของเหลว" => {
                let id=self.arg_num(&args,0,0.)? as usize;
                let x=self.arg_num(&args,1,0.)? as f32; let y=self.arg_num(&args,2,0.)? as f32;
                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;
                if let Some(g)=self.liquids.get_mut(id) { g.splat(x,y,kind,amt,rad); }
                return Ok(Value::Unit);
            }
            #[cfg(not(target_arch = "wasm32"))]
            "liquid_gravity" | "液体重力" | "液体重力ベクトル" | "액체중력" | "แรงโน้มถ่วงเหลว" => {
                let id=self.arg_num(&args,0,0.)? as usize;
                let gx=self.arg_num(&args,1,0.)? as f32; let gy=self.arg_num(&args,2,60.)? as f32;
                if let Some(g)=self.liquids.get_mut(id) { g.set_gravity(gx,gy); }
                return Ok(Value::Unit);
            }
            #[cfg(not(target_arch = "wasm32"))]
            "liquid_step" | "液体步进" | "液体更新" | "액체스텝" | "ก้าวของเหลว" => {
                let id=self.arg_num(&args,0,0.)? as usize; let dt=self.arg_num(&args,1,0.016)? as f32;
                if let Some(g)=self.liquids.get_mut(id) { g.step(dt); }
                return Ok(Value::Unit);
            }
            // liquid_draw(id, sx, sy, scale) — fast flat 2-D blit of the colour field
            #[cfg(not(target_arch = "wasm32"))]
            "liquid_draw" | "绘制液体" | "液体描画" | "액체그리기" | "วาดของเหลว" => {
                let id=self.arg_num(&args,0,0.)? as usize;
                let sx=self.arg_num(&args,1,0.)? as i32; let sy=self.arg_num(&args,2,0.)? as i32;
                let scale=(self.arg_num(&args,3,4.)? as i32).max(1);
                if id < self.liquids.len() {
                    let (gw,gh)={ let g=&self.liquids[id]; (g.w,g.h) };
                    let mut gfx=self.gfx.borrow_mut(); let (w,h)=(gfx.width as i32, gfx.height as i32);
                    let g=&self.liquids[id];
                    for cy in 0..gh { for cx in 0..gw {
                        let col=g.sample_rgb(cx,cy);
                        let bx=sx + cx as i32*scale; let by=sy + cy as i32*scale;
                        for dy in 0..scale { for dx in 0..scale {
                            let px=bx+dx; let py=by+dy;
                            if px>=0 && py>=0 && px<w && py<h { gfx.buffer[(py*w+px) as usize]=col; }
                        }}
                    }}
                }
                return Ok(Value::Unit);
            }
            // liquid_draw_surface(id, kind, cx,cy,cz, radius, height)
            //   kind: 0 plane · 1 sphere · 2 cylinder · 3 cone · 4 dome
            #[cfg(not(target_arch = "wasm32"))]
            "liquid_draw_surface" | "液体贴面" | "液体曲面" | "액체곡면" | "ของเหลวบนพื้นผิว" => {
                let id=self.arg_num(&args,0,0.)? as usize;
                let kind=self.arg_num(&args,1,1.)? as i32;
                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;
                let radius=self.arg_num(&args,5,2.0)? as f32; let height=self.arg_num(&args,6,3.0)? as f32;
                if id < self.liquids.len() {
                    let (gw,gh)={ let g=&self.liquids[id]; (g.w,g.h) };
                    let mut gfx=self.gfx.borrow_mut();
                    let (w,h)=(gfx.width as i32, gfx.height as i32);
                    let cam=gfx.camera.clone();
                    let near = -cam.zdist + 0.05;
                    let g=&self.liquids[id];
                    let tau=std::f32::consts::TAU; let pi=std::f32::consts::PI;
                    let mut cyc=0usize;
                    while cyc<gh {
                        let v=cyc as f32/(gh as f32-1.0);
                        let mut cxc=0usize;
                        while cxc<gw {
                            let u=cxc as f32/(gw as f32-1.0);
                            // surface point P and outward normal N
                            let (px_,py_,pz_,nx_,ny_,nz_);
                            if kind==0 { // plane
                                px_=cx+(u-0.5)*2.0*radius; py_=cy; pz_=cz+(v-0.5)*2.0*radius; nx_=0.0; ny_=-1.0; nz_=0.0;
                            } else if kind==2 { // cylinder
                                let th=u*tau; px_=cx+th.cos()*radius; py_=cy+(v-0.5)*height; pz_=cz+th.sin()*radius; nx_=th.cos(); ny_=0.0; nz_=th.sin();
                            } else if kind==3 { // cone
                                let th=u*tau; let rr=radius*(1.0-v); px_=cx+th.cos()*rr; py_=cy+(v-0.5)*height; pz_=cz+th.sin()*rr;
                                let s=(radius/height.max(0.01)).atan(); nx_=th.cos()*s.cos(); ny_=s.sin(); nz_=th.sin()*s.cos();
                            } else if kind==4 { // dome (upper hemisphere)
                                let th=u*tau; let ph=v*pi*0.5; px_=cx+ph.sin()*th.cos()*radius; py_=cy-ph.cos()*radius; pz_=cz+ph.sin()*th.sin()*radius; nx_=ph.sin()*th.cos(); ny_=-ph.cos(); nz_=ph.sin()*th.sin();
                            } else { // sphere
                                let th=u*tau; let ph=v*pi; px_=cx+ph.sin()*th.cos()*radius; py_=cy+ph.cos()*radius; pz_=cz+ph.sin()*th.sin()*radius; nx_=ph.sin()*th.cos(); ny_=ph.cos(); nz_=ph.sin()*th.sin();
                            }
                            let dP=cam.depth(px_,py_,pz_);
                            if dP>near {
                                // back-face cull (skip for the plane): outward normal pointing away → deeper
                                let cull = kind!=0 && cam.depth(px_+nx_*0.06, py_+ny_*0.06, pz_+nz_*0.06) > dP;
                                if !cull {
                                    let (spx,spy,depth)=cam.project(px_,py_,pz_);
                                    if depth>0.0 {
                                        let col=g.sample_rgb(cxc,cyc);
                                        let bs=((radius*cam.focal/(depth*gw as f32))*1.6).max(1.0).min(7.0) as i32;
                                        let ix=spx as i32; let iy=spy as i32;
                                        let mut dy=-bs; while dy<=bs { let mut dx=-bs; while dx<=bs {
                                            let qx=ix+dx; let qy=iy+dy;
                                            if qx>=0 && qy>=0 && qx<w && qy<h { gfx.buffer[(qy*w+qx) as usize]=col; }
                                            dx+=1; } dy+=1; }
                                    }
                                }
                            }
                            cxc+=1;
                        }
                        cyc+=1;
                    }
                }
                return Ok(Value::Unit);
            }

            // text_poll() — fold newly-typed keys into the input buffer, return it
            #[cfg(not(target_arch = "wasm32"))]
            "text_poll" => {
                let keys = { let gfx = self.gfx.borrow(); gfx.window.as_ref().map(|w| w.get_keys_pressed(minifb::KeyRepeat::No)).unwrap_or_default() };
                for k in keys {
                    if k == minifb::Key::Backspace { self.text_buffer.pop(); }
                    else if let Some(c) = key_char(k) { self.text_buffer.push(c); }
                }
                return Ok(Value::Str(self.text_buffer.clone()));
            }
            "text_get"   => return Ok(Value::Str(self.text_buffer.clone())),
            "text_set"   => { self.text_buffer = self.arg_str(&args,0,""); return Ok(Value::Unit); }
            "text_clear" => { self.text_buffer.clear(); return Ok(Value::Unit); }
            // record_frame() — append the current framebuffer as a PPM, return frame #
            #[cfg(not(target_arch = "wasm32"))]
            "record_frame" => {
                let n = self.record_n;
                let (buf, w, h) = { let gfx = self.gfx.borrow(); (gfx.buffer.clone(), gfx.width, gfx.height) };
                let _ = std::fs::create_dir_all("recordings");
                let mut out = Vec::with_capacity(w*h*3 + 32);
                out.extend_from_slice(format!("P6\n{w} {h}\n255\n").as_bytes());
                for px in &buf { let p = *px; out.push((p>>16) as u8); out.push((p>>8) as u8); out.push(p as u8); }
                let _ = std::fs::write(format!("recordings/frame_{n:05}.ppm"), out);
                self.record_n += 1;
                return Ok(Value::Number(n as f64));
            }
            "record_count" => return Ok(Value::Number(self.record_n as f64)),
            // ── microphone → crypto donut ──
            // mic_capture() — append the latest mic samples to the record buffer
            // (call each frame while recording). Returns the buffer length.
            #[cfg(not(target_arch = "wasm32"))]
            "mic_capture" => {
                if let Some(mic) = self.mic.as_ref() {
                    let s = mic.latest_samples();
                    self.mic_buffer.extend_from_slice(&s);
                    let cap = 96_000usize; // ~2 s @ 48 kHz
                    if self.mic_buffer.len() > cap {
                        let drop = self.mic_buffer.len() - cap;
                        self.mic_buffer.drain(0..drop);
                    }
                }
                return Ok(Value::Number(self.mic_buffer.len() as f64));
            }
            // mic_seed() — SHA3-256 hex of the recorded audio, usable as a donut seed
            #[cfg(not(target_arch = "wasm32"))]
            "mic_seed" => {
                let mut bytes = Vec::with_capacity(self.mic_buffer.len() * 4);
                for f in &self.mic_buffer { bytes.extend_from_slice(&f.to_le_bytes()); }
                return Ok(Value::Str(hex_encode(&ling_crypto::geo::holo_hash(&bytes))));
            }
            #[cfg(not(target_arch = "wasm32"))]
            "mic_clear" => { self.mic_buffer.clear(); return Ok(Value::Number(0.0)); }
            // flush the 3-D depth queue onto the framebuffer WITHOUT presenting,
            // so 2-D UI drawn afterwards overlays the 3-D scene.
            #[cfg(not(target_arch = "wasm32"))]
            "flush_3d" | "render_3d" => {
                let mut gfx = self.gfx.borrow_mut();
                if !gfx.depth_queue.is_empty() {
                    let w = gfx.width; let h = gfx.height;
                    let queue = std::mem::take(&mut gfx.depth_queue);
                    queue.flush(&mut gfx.buffer, w, h);
                }
                return Ok(Value::Unit);
            }

            "set_rim" | "设置边缘光" | "リム設定" | "림라이트" | "ตั้งขอบเรือง" => {
                let s=self.arg_num(&args,0,0.6)? as f32;
                let r=self.arg_num(&args,1,115.)? as f32/255.0;
                let g=self.arg_num(&args,2,217.)? as f32/255.0;
                let b=self.arg_num(&args,3,255.)? as f32/255.0;
                let mut gfx=self.gfx.borrow_mut();
                gfx.shade.rim = s; gfx.shade.rim_color = [r,g,b];
                return Ok(Value::Unit);
            }

            // ══════════════════════════════════════════════════════════════════
            // 3-D PRIMITIVES  (src/gfx/shapes.rs)  — "Inkscape for 3-D"
            //   shape(cx,cy,cz,  sx,sy,sz,  rx,ry,rz,  mode,  e0,e1,e2)
            //     centre (cx,cy,cz), per-axis scale, Euler rotation (radians),
            //     mode: 0 filled · 1 wireframe · 2 both,
            //     e0..e2: shape-specific (segments / sides / ratio …).
            //   Pen colour (set_color) drives fill lighting and wireframe colour.
            // ══════════════════════════════════════════════════════════════════
            n if crate::gfx::shapes::canon(n).is_some() => {
                let kind = crate::gfx::shapes::canon(n).unwrap();
                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;
                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;
                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;
                let mode=self.arg_num(&args,9,0.)? as i32;
                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;
                if let Some(mesh)=crate::gfx::shapes::build(kind,[cx,cy,cz,sx,sy,sz,rx,ry,rz],e0,e1,e2){
                    let mut gfx=self.gfx.borrow_mut();
                    gfx.emit_mesh(&mesh,mode);
                }
                return Ok(Value::Unit);
            }

            _ => {}
        }

        // User-defined function
        if let Some(def) = self.functions.get(name).cloned() {
            let mut call_env = Env::new();
            // Seed env with non-Do globals (skip entry-point blocks to avoid infinite recursion).
            // Pass 1: evaluate each global with the call-site env — simple literals succeed.
            // Pass 2: retry failed globals with the partially-built call_env so that compound
            //         globals (e.g. `FM = (NZ + FZ) / 2.0`) can resolve their dependencies.
            let non_do_globals: Vec<_> = self.globals.iter()
                .filter(|(_, expr)| !matches!(expr, Expr::Do(_)))
                .map(|(k, e)| (k.clone(), e.clone()))
                .collect();
            let mut pending: Vec<(String, Expr)> = Vec::new();
            for (k, expr) in &non_do_globals {
                let mut tmp = env.clone();
                if let Ok(v) = self.eval_expr(expr, &mut tmp) {
                    call_env.insert(k.clone(), v);
                } else {
                    pending.push((k.clone(), expr.clone()));
                }
            }
            // Second pass: retry compound globals now that literals are in call_env.
            for (k, expr) in &pending {
                let mut tmp = env.clone();
                tmp.extend(call_env.clone());
                if let Ok(v) = self.eval_expr(expr, &mut tmp) {
                    call_env.insert(k.clone(), v);
                }
            }
            for (param, arg) in def.params.iter().zip(args) {
                call_env.insert(param.clone(), arg);
            }
            return match self.exec_block(&def.body, &mut call_env) {
                Ok(v) => Ok(v.unwrap_or(Value::Unit)),
                Err(EvalErr::Return(v)) => Ok(v),
                Err(e) => Err(e),
            };
        }

        Err(EvalErr::from(format!("unknown function '{name}'")))
    }

    fn call_value(&mut self, v: Value, args: Vec<Value>) -> EvalResult {
        match v {
            Value::Fn(params, body, mut captured) => {
                for (p, a) in params.iter().zip(args) {
                    captured.insert(p.clone(), a);
                }
                match self.exec_block(&body, &mut captured) {
                    Ok(v) => Ok(v.unwrap_or(Value::Unit)),
                    Err(EvalErr::Return(v)) => Ok(v),
                    Err(e) => Err(e),
                }
            }
            other => Err(EvalErr::from(format!("cannot call {:?}", other))),
        }
    }

    fn call_method(&self, recv: Value, method: &str, args: Vec<Value>) -> EvalResult {
        match (&recv, method) {
            (Value::Str(s), "is_empty" | "是空") => Ok(Value::Bool(s.is_empty())),
            (Value::Str(s), "len" | "")        => Ok(Value::Number(s.len() as f64)),
            (Value::Str(s), "to_string" | "转文") => Ok(Value::Str(s.clone())),
            (Value::Str(s), "contains" | "包含") => {
                if let Some(Value::Str(sub)) = args.first() {
                    Ok(Value::Bool(s.contains(sub.as_str())))
                } else { Ok(Value::Bool(false)) }
            }
            (Value::Str(s), "push_str" | "推_文") => {
                let mut s2 = s.clone();
                if let Some(Value::Str(a)) = args.first() { s2.push_str(a); }
                Ok(Value::Str(s2))
            }
            (Value::List(v), "len" | "") => Ok(Value::Number(v.len() as f64)),
            (Value::List(v), "push" | "") => {
                let mut v2 = v.clone();
                if let Some(a) = args.first() { v2.push(a.clone()); }
                Ok(Value::List(v2))
            }
            (Value::Ok(inner), _) | (Value::Err(inner), _) => Ok(*inner.clone()),
            _ => Err(EvalErr::from(format!("no method '{method}' on {recv}"))),
        }
    }

    // ─── Pattern matching ─────────────────────────────────────────────────────

    fn match_pattern(&self, pat: &Pattern, val: &Value) -> Option<Env> {
        match (pat, val) {
            (Pattern::Wildcard, _) => Some(Env::new()),
            (Pattern::Str(s), Value::Str(v)) if s == v => Some(Env::new()),
            (Pattern::Number(n), Value::Number(v)) if (n - v).abs() < 1e-12 => Some(Env::new()),
            (Pattern::Bool(b), Value::Bool(v)) if b == v => Some(Env::new()),
            (Pattern::Ident(name), _) => {
                let mut e = Env::new();
                e.insert(name.clone(), val.clone());
                Some(e)
            }
            (Pattern::Constructor(ctor, inner_pat), _) => {
                let (matches, inner_val) = match (ctor.as_str(), val) {
                    ("ok"  | "", Value::Ok(v))  => (true, Some(v.as_ref().clone())),
                    ("bad" | "", Value::Err(v)) => (true, Some(v.as_ref().clone())),
                    ("ok"  | "", v) if !matches!(v, Value::Err(_)) => (true, Some(v.clone())),
                    _ => (false, None),
                };
                if !matches { return None; }
                match (inner_pat, inner_val) {
                    (Some(p), Some(v)) => self.match_pattern(p, &v),
                    (None, _)          => Some(Env::new()),
                    (Some(p), None)    => self.match_pattern(p, &Value::Unit),
                }
            }
            _ => None,
        }
    }

    // ─── Utilities ───────────────────────────────────────────────────────────

    fn value_to_iter(&self, val: Value) -> Result<Vec<Value>, EvalErr> {
        match val {
            Value::List(v)   => Ok(v),
            Value::Str(s)    => Ok(s.chars().map(|c| Value::Str(c.to_string())).collect()),
            Value::Number(n) => Ok((0..n as i64).map(|i| Value::Number(i as f64)).collect()),
            other => Err(EvalErr::from(format!("cannot iterate over {:?}", other))),
        }
    }

    fn is_truthy(&self, val: &Value) -> bool {
        match val {
            Value::Bool(b)     => *b,
            Value::Unit        => false,
            Value::Number(n)   => *n != 0.0,
            Value::Str(s)      => !s.is_empty(),
            Value::List(v)     => !v.is_empty(),
            Value::Ok(_)       => true,
            Value::Err(_)      => false,
            Value::Fn(_, _, _) => true,
        }
    }

    fn to_number(&self, val: &Value) -> Result<f64, EvalErr> {
        match val {
            Value::Number(n) => Ok(*n),
            Value::Str(s)    => s.parse().map_err(|_| EvalErr::from(format!("cannot convert '{s}' to number"))),
            other => Err(EvalErr::from(format!("expected number, got {:?}", other))),
        }
    }

    /// Get the n-th argument as f64, falling back to `default` if missing.
    fn arg_num(&self, args: &[Value], n: usize, default: f64) -> Result<f64, EvalErr> {
        match args.get(n) {
            Some(v) => self.to_number(v),
            None    => Ok(default),
        }
    }

    fn arg_str(&self, args: &[Value], n: usize, default: &str) -> String {
        args.get(n).map(|v| v.to_string()).unwrap_or_else(|| default.to_string())
    }

    /// Read a list-of-numbers argument as `Vec<f32>` (empty if absent/not a list).
    #[allow(dead_code)]
    fn arg_list_f32(&self, args: &[Value], n: usize) -> Vec<f32> {
        match args.get(n) {
            Some(Value::List(v)) => v.iter().filter_map(|x| match x {
                Value::Number(n) => Some(*n as f32),
                _ => None,
            }).collect(),
            _ => Vec::new(),
        }
    }

    /// Optional `r,g,b` colour override starting at arg `i` → packed 0x00RRGGBB,
    /// or `default` if those three numeric args aren't present.
    #[cfg(not(target_arch = "wasm32"))]
    fn color_at(&self, args: &[Value], i: usize, default: u32) -> u32 {
        match (args.get(i), args.get(i + 1), args.get(i + 2)) {
            (Some(a), Some(b), Some(c)) => match (self.to_number(a), self.to_number(b), self.to_number(c)) {
                (Ok(r), Ok(g), Ok(bl)) =>
                    ((r as u32 & 0xFF) << 16) | ((g as u32 & 0xFF) << 8) | (bl as u32 & 0xFF),
                _ => default,
            },
            _ => default,
        }
    }

    /// A pitch argument: a note-name string (`"C4"`, `"A#3"`) or a numeric MIDI value.
    #[cfg(not(target_arch = "wasm32"))]
    fn pitch_arg(&self, args: &[Value], i: usize, default: i32) -> i32 {
        match args.get(i) {
            Some(Value::Str(s)) => ling_music::note::parse_pitch(s).unwrap_or(default),
            Some(Value::Number(n)) => *n as i32,
            _ => default,
        }
    }

    /// Current mouse position + left-button-down (native window only).
    #[cfg(not(target_arch = "wasm32"))]
    fn mouse_now(&self) -> (f32, f32, bool) {
        let gfx = self.gfx.borrow();
        let (mx, my) = gfx.window.as_ref()
            .and_then(|w| w.get_mouse_pos(minifb::MouseMode::Clamp)).unwrap_or((0.0, 0.0));
        let down = gfx.window.as_ref()
            .map(|w| w.get_mouse_down(minifb::MouseButton::Left)).unwrap_or(false);
        (mx, my, down)
    }

    /// Rasterize a UI [`ling_ui::widgets::Draw`] into the framebuffer: filled
    /// polygons via the AA scanline fill, polylines via AA lines, honouring the
    /// current blend mode.
    #[cfg(not(target_arch = "wasm32"))]
    fn draw_ui(&self, d: &ling_ui::widgets::Draw) {
        let mut gfx = self.gfx.borrow_mut();
        let (w, h, add) = (gfx.width, gfx.height, gfx.blend == 1);
        for (c, poly) in &d.fills {
            crate::gfx::raster::fill_contours_aa(&mut gfx.buffer, w, h, *c, add, std::slice::from_ref(poly));
        }
        for (c, pl) in &d.strokes {
            for s in pl.windows(2) {
                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]);
            }
        }
    }

    /// Parse (dst_x, dst_y, width, height) from the first four args of a tex_* builtin.
    fn tex_rect(&self, args: &[Value]) -> Result<(usize, usize, usize, usize), EvalErr> {
        let tx = self.arg_num(args, 0, 0.0)? as usize;
        let ty = self.arg_num(args, 1, 0.0)? as usize;
        let tw = self.arg_num(args, 2, 256.0)? as usize;
        let th = self.arg_num(args, 3, 256.0)? as usize;
        Ok((tx, ty, tw.max(1), th.max(1)))
    }

    fn apply_binop(&self, op: &BinOp, l: Value, r: Value) -> EvalResult {
        match op {
            BinOp::Add => match (l, r) {
                (Value::Number(a), Value::Number(b)) => Ok(Value::Number(a + b)),
                (Value::Str(a), Value::Str(b))       => Ok(Value::Str(a + &b)),
                (Value::Str(a), b)                   => Ok(Value::Str(a + &b.to_string())),
                (a, Value::Str(b))                   => Ok(Value::Str(a.to_string() + &b)),
                (a, b) => Err(EvalErr::from(format!("cannot add {:?} and {:?}", a, b))),
            },
            BinOp::Sub => Ok(Value::Number(self.to_number(&l)? - self.to_number(&r)?)),
            BinOp::Mul => Ok(Value::Number(self.to_number(&l)? * self.to_number(&r)?)),
            BinOp::Div => Ok(Value::Number(self.to_number(&l)? / self.to_number(&r)?)),
            BinOp::Rem => Ok(Value::Number(self.to_number(&l)? % self.to_number(&r)?)),
            BinOp::Eq  => Ok(Value::Bool(values_equal(&l, &r))),
            BinOp::Ne  => Ok(Value::Bool(!values_equal(&l, &r))),
            BinOp::Lt  => Ok(Value::Bool(self.to_number(&l)? < self.to_number(&r)?)),
            BinOp::Gt  => Ok(Value::Bool(self.to_number(&l)? > self.to_number(&r)?)),
            BinOp::Le  => Ok(Value::Bool(self.to_number(&l)? <= self.to_number(&r)?)),
            BinOp::Ge  => Ok(Value::Bool(self.to_number(&l)? >= self.to_number(&r)?)),
            BinOp::And => Ok(Value::Bool(self.is_truthy(&l) && self.is_truthy(&r))),
            BinOp::Or  => Ok(Value::Bool(self.is_truthy(&l) || self.is_truthy(&r))),
        }
    }

    fn builtin_format(&self, args: &[Value]) -> Result<String, EvalErr> {
        if args.is_empty() { return Ok(String::new()); }
        let fmt = match &args[0] {
            Value::Str(s) => s.clone(),
            other => return Ok(other.to_string()),
        };

        let mut result = String::new();
        let mut arg_idx = 1usize;
        let mut chars = fmt.chars().peekable();
        while let Some(c) = chars.next() {
            if c == '{' {
                if chars.peek() == Some(&'}') {
                    chars.next();
                    if arg_idx < args.len() {
                        result.push_str(&args[arg_idx].to_string());
                        arg_idx += 1;
                    }
                } else {
                    let mut spec = String::new();
                    for ch in chars.by_ref() {
                        if ch == '}' { break; }
                        spec.push(ch);
                    }
                    if arg_idx < args.len() {
                        if spec.starts_with(":.") {
                            if let Value::Number(n) = &args[arg_idx] {
                                let prec: usize = spec[2..].trim_end_matches('f')
                                    .parse().unwrap_or(2);
                                result.push_str(&format!("{:.prec$}", n));
                                arg_idx += 1;
                                continue;
                            }
                        }
                        result.push_str(&args[arg_idx].to_string());
                        arg_idx += 1;
                    }
                }
            } else {
                result.push(c);
            }
        }
        Ok(result)
    }
}

#[cfg(not(target_arch = "wasm32"))]
fn str_to_minifb_key(name: &str) -> Option<minifb::Key> {
    use minifb::Key;
    Some(match name {
        "numpad0" | "kp0" => Key::NumPad0,
        "numpad1" | "kp1" => Key::NumPad1,
        "numpad2" | "kp2" => Key::NumPad2,
        "numpad3" | "kp3" => Key::NumPad3,
        "numpad4" | "kp4" => Key::NumPad4,
        "numpad5" | "kp5" => Key::NumPad5,
        "numpad6" | "kp6" => Key::NumPad6,
        "numpad7" | "kp7" => Key::NumPad7,
        "numpad8" | "kp8" => Key::NumPad8,
        "numpad9" | "kp9" => Key::NumPad9,
        "numpad+" | "kp+" => Key::NumPadPlus,
        "numpad-" | "kp-" => Key::NumPadMinus,
        "numpad*" | "kp*" => Key::NumPadAsterisk,
        "numpad/" | "kp/" => Key::NumPadSlash,
        "left"   => Key::Left,
        "right"  => Key::Right,
        "up"     => Key::Up,
        "down"   => Key::Down,
        "space"  => Key::Space,
        "enter"  => Key::Enter,
        "escape" => Key::Escape,
        "pageup" => Key::PageUp,
        "pagedown" => Key::PageDown,
        "lshift" | "leftshift"  => Key::LeftShift,
        "rshift" | "rightshift" => Key::RightShift,
        "lctrl"  | "leftctrl"   => Key::LeftCtrl,
        "rctrl"  | "rightctrl"  => Key::RightCtrl,
        "tab"    => Key::Tab,
        "backspace" => Key::Backspace,
        "delete" => Key::Delete,
        "insert" => Key::Insert,
        "home"   => Key::Home,
        "end"    => Key::End,
        "a" => Key::A, "b" => Key::B, "c" => Key::C, "d" => Key::D,
        "e" => Key::E, "f" => Key::F, "g" => Key::G, "h" => Key::H,
        "i" => Key::I, "j" => Key::J, "k" => Key::K, "l" => Key::L,
        "m" => Key::M, "n" => Key::N, "o" => Key::O, "p" => Key::P,
        "q" => Key::Q, "r" => Key::R, "s" => Key::S, "t" => Key::T,
        "u" => Key::U, "v" => Key::V, "w" => Key::W, "x" => Key::X,
        "y" => Key::Y, "z" => Key::Z,
        "0" => Key::Key0, "1" => Key::Key1, "2" => Key::Key2,
        "3" => Key::Key3, "4" => Key::Key4, "5" => Key::Key5,
        "6" => Key::Key6, "7" => Key::Key7, "8" => Key::Key8,
        "9" => Key::Key9,
        _ => return None,
    })
}

fn values_equal(a: &Value, b: &Value) -> bool {
    match (a, b) {
        (Value::Number(x), Value::Number(y)) => (x - y).abs() < 1e-12,
        (Value::Str(x), Value::Str(y))       => x == y,
        (Value::Bool(x), Value::Bool(y))     => x == y,
        (Value::Unit, Value::Unit)            => true,
        _ => false,
    }
}

// Rasteriser functions live in crate::gfx::raster — imported at top of file.

// ── Window platform helpers ────────────────────────────────────────────────────

/// Hide the console window that the OS auto-attaches to console-subsystem
/// processes. No-op on non-Windows and when no console is present.
#[cfg(not(target_arch = "wasm32"))]
fn hide_console_window() {
    #[cfg(windows)]
    unsafe {
        extern "system" {
            fn GetConsoleWindow() -> isize;
            fn ShowWindow(hwnd: isize, nCmdShow: i32) -> i32;
        }
        let hwnd = GetConsoleWindow();
        if hwnd != 0 {
            ShowWindow(hwnd, 0); // SW_HIDE = 0
        }
    }
}

/// Move and resize the foreground window so it fills the primary monitor
/// (0,0 → screen_w × screen_h) and sits above the taskbar (HWND_TOPMOST).
#[cfg(all(not(target_arch = "wasm32"), windows))]
fn reposition_fullscreen(screen_w: i32, screen_h: i32) {
    unsafe {
        extern "system" {
            fn GetForegroundWindow() -> isize;
            fn SetWindowPos(hwnd: isize, insert_after: isize,
                            x: i32, y: i32, cx: i32, cy: i32,
                            flags: u32) -> i32;
        }
        let hwnd = GetForegroundWindow();
        if hwnd != 0 {
            // HWND_TOPMOST = -1, SWP_SHOWWINDOW = 0x0040
            SetWindowPos(hwnd, -1isize, 0, 0, screen_w, screen_h, 0x0040);
        }
    }
}

/// Query the primary display resolution on non-Windows platforms.
/// Falls back to 1920×1080 if the size cannot be determined.
#[cfg(all(not(target_arch = "wasm32"), not(windows)))]
fn native_screen_size() -> (f64, f64) {
    // On Linux/macOS we don't have an easy dependency-free call; return a
    // sensible default. Callers can always pass explicit dimensions.
    (1920.0, 1080.0)
}