Repository navigation
Expand file tree
/
Copy pathDomainBlockCompilerMixin.ts
More file actions
6174 lines (5671 loc) · 244 KB
/
Copy pathDomainBlockCompilerMixin.ts
File metadata and controls
6174 lines (5671 loc) · 244 KB
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
import type { Vector3 } from '../types';
/**
* DomainBlockCompilerMixin.ts
*
* Shared utilities for compiling domain blocks and simulation constructs
* to target platform code. Any compiler can import these helpers.
*
* Handles: materials, physics, particles, post-fx, audio, weather,
* procedural, LOD, navigation, input, annotations.
*
* @version 4.2.0
*/
import type { HoloDomainBlock, HoloDomainType, HoloValue } from '../parser/HoloCompositionTypes';
import { escapeStringValue, type EscapeTarget } from './CompilerBase';
import { ANSCapabilityPath, type ANSCapabilityPathValue } from './identity/ANSNamespace';
import {
applyPerceptualColorPass,
type PerceptualColorPassInput,
type PerceptualColorPassResult,
type PerceptualGradientStop,
} from './PerceptualColorPass';
/**
* Escape a string for safe interpolation into a specific target language.
* Convenience alias for DomainBlockCompilerMixin standalone functions.
*
* SECURITY: All user-controlled strings interpolated into generated code
* MUST go through this function to prevent CWE-94 injection attacks.
*/
function esc(value: string, target: EscapeTarget): string {
return escapeStringValue(value, target);
}
// =============================================================================
// Material Compilation
// =============================================================================
export interface CompiledMaterial {
name: string;
type: 'pbr' | 'unlit' | 'shader';
baseColor?: string;
roughness?: number;
metallic?: number;
opacity?: number;
ior?: number;
emissiveColor?: string;
emissiveIntensity?: number;
// Physical-material (three MeshPhysicalMaterial) props — emitted when any is set.
clearcoat?: number;
clearcoatRoughness?: number;
transmission?: number;
thickness?: number;
sheen?: number;
sheenColor?: string;
sheenRoughness?: number;
specularIntensity?: number;
iridescence?: number;
attenuationColor?: string;
attenuationDistance?: number;
textureMaps: Record<string, string>;
traits: string[];
}
/** Physical-material prop keys that, when present, promote a PBR material to
* three's MeshPhysicalMaterial. `ior` alone does NOT promote (StandardMaterial
* ignores it harmlessly; promotion requires a genuinely-physical effect). */
const PHYSICAL_MATERIAL_KEYS = [
'clearcoat',
'clearcoatRoughness',
'transmission',
'thickness',
'sheen',
'sheenColor',
'sheenRoughness',
'specularIntensity',
'iridescence',
'attenuationColor',
'attenuationDistance',
] as const;
/** True when the material declares any genuinely-physical effect. */
export function isPhysicalMaterial(mat: CompiledMaterial): boolean {
return PHYSICAL_MATERIAL_KEYS.some((k) => mat[k] !== undefined);
}
export function compileMaterialBlock(block: HoloDomainBlock): CompiledMaterial {
const type =
block.keyword === 'unlit_material' ? 'unlit' : block.keyword === 'shader' ? 'shader' : 'pbr';
const textureMaps: Record<string, string> = {};
const otherProps: Record<string, unknown> = {};
for (const [key, value] of Object.entries(block.properties || {})) {
if (key.endsWith('_map')) {
textureMaps[key] = String(value);
} else {
otherProps[key] = value;
}
}
return {
name: block.name || 'unnamed',
type,
baseColor: otherProps.baseColor as string,
roughness: otherProps.roughness as number,
metallic: otherProps.metallic as number,
opacity: otherProps.opacity as number,
ior: otherProps.ior as number,
emissiveColor: otherProps.emissive_color as string,
emissiveIntensity: otherProps.emissive_intensity as number,
clearcoat: (otherProps.clearcoat ?? otherProps.clear_coat) as number,
clearcoatRoughness: (otherProps.clearcoat_roughness ?? otherProps.clearcoatRoughness) as number,
transmission: otherProps.transmission as number,
thickness: otherProps.thickness as number,
sheen: otherProps.sheen as number,
sheenColor: (otherProps.sheen_color ?? otherProps.sheenColor) as string,
sheenRoughness: (otherProps.sheen_roughness ?? otherProps.sheenRoughness) as number,
specularIntensity: (otherProps.specular_intensity ?? otherProps.specularIntensity) as number,
iridescence: otherProps.iridescence as number,
attenuationColor: (otherProps.attenuation_color ?? otherProps.attenuationColor) as string,
attenuationDistance: (otherProps.attenuation_distance ??
otherProps.attenuationDistance) as number,
textureMaps,
traits: block.traits || [],
};
}
// =============================================================================
// Material Graph Compilation (material_graph domain — node-DAG materials)
// =============================================================================
//
// A material_graph is the typed node-graph generalization of a flat material:
// a DAG of value/math/sample nodes whose edges feed a terminal `output` node's
// surface ports (base_color / roughness / metallic / emissive). It lowers to a
// real WGSL function that evaluates the graph in topological order — the
// sovereign, exact answer to Unreal's Material Editor / Substrate (CG-323).
//
// Authoring shape (verified against HoloCompositionParser):
// material_graph "name" {
// base { type: "constant", value: "#8B4513" }
// rust { type: "noise", scale: 8.0 }
// albedo { type: "lerp" }
// out { type: "output" }
// base -> albedo.a
// rust -> albedo.t
// albedo -> out.base_color
// }
// → HoloDomainBlock.properties = { <nodeId>: {type, ...params}, connections: [{from,to}] }
/** A single node in a compiled material graph. */
export interface CompiledMaterialGraphNode {
id: string;
/** Node kind: constant | noise | fresnel | multiply | add | lerp | output */
nodeType: string;
/** Scalar/string params authored on the node (value, scale, power, ...). */
params: Record<string, unknown>;
}
/** A directed edge: fromNodeId → toNodeId.port */
export interface CompiledMaterialGraphEdge {
from: string;
toNode: string;
toPort: string;
}
export interface CompiledMaterialGraph {
name: string;
nodes: CompiledMaterialGraphNode[];
edges: CompiledMaterialGraphEdge[];
traits: string[];
}
/**
* Normalize a `material_graph` domain block into a typed node/edge graph.
* Mirrors compileMaterialBlock: reads the shared HoloDomainBlock.properties bag
* (each non-`connections` key is a node; `connections` are the edges).
*/
export function compileMaterialGraphBlock(block: HoloDomainBlock): CompiledMaterialGraph {
const props = (block.properties || {}) as Record<string, unknown>;
const nodes: CompiledMaterialGraphNode[] = [];
for (const [key, raw] of Object.entries(props)) {
if (key === 'connections') continue;
const nodeObj = (raw && typeof raw === 'object' ? raw : {}) as Record<string, unknown>;
const { type: nodeType, ...params } = nodeObj;
nodes.push({
id: key,
nodeType: typeof nodeType === 'string' ? nodeType : 'constant',
params,
});
}
const rawConns = Array.isArray(props.connections)
? (props.connections as Array<{ from?: unknown; to?: unknown }>)
: [];
const edges: CompiledMaterialGraphEdge[] = [];
for (const c of rawConns) {
const from = typeof c.from === 'string' ? c.from : '';
const to = typeof c.to === 'string' ? c.to : '';
if (!from || !to) continue;
const dot = to.indexOf('.');
const toNode = dot >= 0 ? to.slice(0, dot) : to;
const toPort = dot >= 0 ? to.slice(dot + 1) : 'in';
edges.push({ from, toNode, toPort });
}
return {
name: block.name || 'unnamed',
nodes,
edges,
traits: block.traits || [],
};
}
/** WGSL-safe identifier from a node id (letters/digits/underscore). */
function sanitizeMgIdent(id: string): string {
const s = id.replace(/[^A-Za-z0-9_]/g, '_');
return /^[A-Za-z_]/.test(s) ? s : `n_${s}`;
}
/** Parse a hex color to a WGSL vec3<f32> literal (falls back to mid-grey). */
function mgHexToVec3(value: unknown): string {
const hex = typeof value === 'string' ? value : '';
const m = /^#?([0-9a-fA-F]{6})$/.exec(hex.trim());
if (!m) return 'vec3<f32>(0.5, 0.5, 0.5)';
const n = parseInt(m[1], 16);
const r = ((n >> 16) & 0xff) / 255;
const g = ((n >> 8) & 0xff) / 255;
const b = (n & 0xff) / 255;
return `vec3<f32>(${r.toFixed(4)}, ${g.toFixed(4)}, ${b.toFixed(4)})`;
}
/** A resolved WGSL expression plus its type, for graph wiring. */
interface MgValue {
ref: string;
type: 'vec3' | 'f32';
}
const mgToVec3 = (v: MgValue | undefined): string =>
!v ? 'vec3<f32>(0.0)' : v.type === 'vec3' ? v.ref : `vec3<f32>(${v.ref})`;
const mgToF32 = (v: MgValue | undefined, fallback = '0.0'): string =>
!v ? fallback : v.type === 'f32' ? v.ref : `(${v.ref}).x`;
/**
* Lower a CompiledMaterialGraph to an evaluatable WGSL fragment function.
*
* Topologically orders the DAG (Kahn) so every `let mg_<id>` references only
* already-emitted values; the terminal `output` node's ports become the
* returned surface struct. This is real executable WGSL, not a scaffold.
*/
export function materialGraphToWGSL(graph: CompiledMaterialGraph): {
fnName: string;
wgsl: string;
} {
const safeName = sanitizeMgIdent(graph.name);
const fnName = `evalMaterialGraph_${safeName}`;
const warnings: string[] = [];
const nodeById = new Map(graph.nodes.map((n) => [n.id, n]));
// incoming edges per node: port -> fromNodeId
const inputs = new Map<string, Map<string, string>>();
for (const n of graph.nodes) inputs.set(n.id, new Map());
for (const e of graph.edges) {
if (!nodeById.has(e.from)) {
warnings.push(`edge from unknown node "${e.from}"`);
continue;
}
if (!inputs.has(e.toNode)) {
warnings.push(`edge to unknown node "${e.toNode}"`);
continue;
}
inputs.get(e.toNode)!.set(e.toPort, e.from);
}
// Kahn topological sort over dependency edges (from -> toNode).
const indeg = new Map<string, number>();
const adj = new Map<string, string[]>();
for (const n of graph.nodes) {
indeg.set(n.id, 0);
adj.set(n.id, []);
}
for (const e of graph.edges) {
if (!nodeById.has(e.from) || !nodeById.has(e.toNode)) continue;
adj.get(e.from)!.push(e.toNode);
indeg.set(e.toNode, (indeg.get(e.toNode) || 0) + 1);
}
const queue = graph.nodes.filter((n) => (indeg.get(n.id) || 0) === 0).map((n) => n.id);
const order: string[] = [];
while (queue.length) {
const id = queue.shift()!;
order.push(id);
for (const next of adj.get(id) || []) {
indeg.set(next, (indeg.get(next) || 0) - 1);
if ((indeg.get(next) || 0) === 0) queue.push(next);
}
}
if (order.length < graph.nodes.length) {
warnings.push('material graph has a cycle; emitting nodes in declaration order');
for (const n of graph.nodes) if (!order.includes(n.id)) order.push(n.id);
}
const values = new Map<string, MgValue>();
const inPort = (nodeId: string, port: string): MgValue | undefined => {
const from = inputs.get(nodeId)?.get(port);
return from ? values.get(from) : undefined;
};
const body: string[] = [];
let output: { id: string } | null = null;
for (const id of order) {
const node = nodeById.get(id)!;
const v = sanitizeMgIdent(id);
switch (node.nodeType) {
case 'constant': {
if (typeof node.params.value === 'number') {
body.push(` let mg_${v} = ${(node.params.value as number).toFixed(4)}; // constant`);
values.set(id, { ref: `mg_${v}`, type: 'f32' });
} else {
body.push(` let mg_${v} = ${mgHexToVec3(node.params.value)}; // constant`);
values.set(id, { ref: `mg_${v}`, type: 'vec3' });
}
break;
}
case 'noise': {
const scale = typeof node.params.scale === 'number' ? node.params.scale : 1;
body.push(` let mg_${v} = mgNoise(uv * ${scale.toFixed(4)}); // noise`);
values.set(id, { ref: `mg_${v}`, type: 'f32' });
break;
}
case 'fresnel': {
const power = typeof node.params.power === 'number' ? node.params.power : 5;
body.push(
` let mg_${v} = pow(1.0 - max(dot(N, V), 0.0), ${power.toFixed(4)}); // fresnel`
);
values.set(id, { ref: `mg_${v}`, type: 'f32' });
break;
}
case 'multiply':
case 'add': {
const a = inPort(id, 'a');
const b = inPort(id, 'b');
const op = node.nodeType === 'multiply' ? '*' : '+';
const asVec = a?.type === 'vec3' || b?.type === 'vec3';
if (asVec) {
body.push(` let mg_${v} = ${mgToVec3(a)} ${op} ${mgToVec3(b)}; // ${node.nodeType}`);
values.set(id, { ref: `mg_${v}`, type: 'vec3' });
} else {
body.push(` let mg_${v} = ${mgToF32(a)} ${op} ${mgToF32(b)}; // ${node.nodeType}`);
values.set(id, { ref: `mg_${v}`, type: 'f32' });
}
break;
}
case 'lerp': {
const a = inPort(id, 'a');
const b = inPort(id, 'b');
const t = inPort(id, 't');
body.push(
` let mg_${v} = mix(${mgToVec3(a)}, ${mgToVec3(b)}, vec3<f32>(${mgToF32(t)})); // lerp`
);
values.set(id, { ref: `mg_${v}`, type: 'vec3' });
break;
}
case 'output': {
output = { id };
break;
}
default: {
warnings.push(`unknown node type "${node.nodeType}" (node "${id}") — treated as black`);
body.push(` let mg_${v} = vec3<f32>(0.0); // unknown:${esc(node.nodeType, 'TypeScript')}`);
values.set(id, { ref: `mg_${v}`, type: 'vec3' });
}
}
}
// Unconnected surface ports fall back to neutral material defaults (grey
// dielectric), whether the output node is absent or its port is just unwired.
const baseColorIn = output ? inPort(output.id, 'base_color') : undefined;
const roughnessIn = output ? inPort(output.id, 'roughness') : undefined;
const metallicIn = output ? inPort(output.id, 'metallic') : undefined;
const emissiveIn = output ? inPort(output.id, 'emissive') : undefined;
const baseColor = baseColorIn ? mgToVec3(baseColorIn) : 'vec3<f32>(0.8)';
const roughness = roughnessIn ? mgToF32(roughnessIn, '0.5') : '0.5';
const metallic = metallicIn ? mgToF32(metallicIn, '0.0') : '0.0';
const emissive = emissiveIn ? mgToVec3(emissiveIn) : 'vec3<f32>(0.0)';
const header = [
`// Material Graph "${esc(graph.name, 'TypeScript')}" — generated by HoloScript TSLCompiler`,
`// Nodes: ${graph.nodes.length} | Edges: ${graph.edges.length} | topo-ordered: [${order
.map((o) => esc(o, 'TypeScript'))
.join(' -> ')}]`,
...warnings.map((w) => `// WARNING: ${esc(w, 'TypeScript')}`),
];
const wgsl = [
...header,
'',
'struct MaterialGraphSurface {',
' baseColor: vec3<f32>,',
' roughness: f32,',
' metallic: f32,',
' emissive: vec3<f32>,',
'};',
'',
'// Cheap value-noise helper (hash-based); replace with a texture sample for AAA fidelity.',
'fn mgNoise(p: vec2<f32>) -> f32 {',
' return fract(sin(dot(p, vec2<f32>(12.9898, 78.233))) * 43758.5453);',
'}',
'',
`fn ${fnName}(uv: vec2<f32>, N: vec3<f32>, V: vec3<f32>, time: f32) -> MaterialGraphSurface {`,
...body,
' var surface: MaterialGraphSurface;',
` surface.baseColor = ${baseColor};`,
` surface.roughness = ${roughness};`,
` surface.metallic = ${metallic};`,
` surface.emissive = ${emissive};`,
' return surface;',
'}',
].join('\n');
return { fnName, wgsl };
}
// =============================================================================
// Particle Field Compilation (particle_field domain — typed force-stack GPU particles)
// =============================================================================
//
// A particle_field is the composable-force generalization of a fixed particle
// system: top-level `count`/`lifetime` plus a stack of typed force nodes
// (gravity / drag / vortex / attractor / curl_noise / turbulence) that each
// lower to real WGSL accumulated into per-particle acceleration. The sovereign,
// $0-on-fleet answer to Unreal's Niagara module stack (CG-312) — where the
// current `vfx` block only integrates fixed gravity, this composes N forces.
//
// Authoring shape (verified against HoloCompositionParser):
// particle_field "embers" {
// count: 20000
// lifetime: 3.0
// grav { type: "gravity", strength: -2.0 }
// swirl { type: "vortex", strength: 4.0 }
// air { type: "drag", coefficient: 0.1 }
// }
// → properties = { count, lifetime, <forceId>: {type, ...params} }
export interface CompiledParticleForce {
id: string;
/** gravity | drag | vortex | attractor | curl_noise | turbulence */
forceType: string;
params: Record<string, unknown>;
}
export interface CompiledParticleField {
name: string;
count: number;
lifetime: number;
forces: CompiledParticleForce[];
traits: string[];
}
/** Normalize a `particle_field` domain block: scalars stay config, typed
* sub-blocks (objects carrying a `type`) become the force stack. */
export function compileParticleFieldBlock(block: HoloDomainBlock): CompiledParticleField {
const props = (block.properties || {}) as Record<string, unknown>;
const forces: CompiledParticleForce[] = [];
let count = 1000;
let lifetime = 2.0;
for (const [key, raw] of Object.entries(props)) {
if (key === 'count' && typeof raw === 'number') {
count = raw;
continue;
}
if (key === 'lifetime' && typeof raw === 'number') {
lifetime = raw;
continue;
}
if (raw && typeof raw === 'object' && !Array.isArray(raw)) {
const { type, ...params } = raw as Record<string, unknown>;
if (typeof type === 'string') forces.push({ id: key, forceType: type, params });
}
}
return { name: block.name || 'unnamed', count, lifetime, forces, traits: block.traits || [] };
}
/**
* Lower a CompiledParticleField to a WGSL compute shader that integrates the
* composed force stack per particle (semi-implicit Euler) with lifetime respawn.
* Real executable compute WGSL — each force is accumulated, not a comment.
*/
export function particleFieldToWGSL(field: CompiledParticleField): {
fnName: string;
wgsl: string;
} {
const safe = sanitizeMgIdent(field.name);
const fnName = `cs_particle_field_${safe}`;
const warnings: string[] = [];
const num = (p: Record<string, unknown>, k: string, d: number): number =>
typeof p[k] === 'number' ? (p[k] as number) : d;
const forceLines: string[] = [];
for (const f of field.forces) {
const p = f.params;
switch (f.forceType) {
case 'gravity':
forceLines.push(
` accel += vec3<f32>(0.0, ${num(p, 'strength', -9.81).toFixed(4)}, 0.0); // gravity:${esc(f.id, 'TypeScript')}`
);
break;
case 'drag':
forceLines.push(
` accel -= p.vel * ${num(p, 'coefficient', 0.1).toFixed(4)}; // drag:${esc(f.id, 'TypeScript')}`
);
break;
case 'vortex':
forceLines.push(
` accel += normalize(vec3<f32>(-p.pos.z, 0.0, p.pos.x) + vec3<f32>(1e-4)) * ${num(p, 'strength', 1.0).toFixed(4)}; // vortex:${esc(f.id, 'TypeScript')}`
);
break;
case 'attractor':
forceLines.push(
` accel += -normalize(p.pos + vec3<f32>(1e-4)) * ${num(p, 'strength', 1.0).toFixed(4)}; // attractor:${esc(f.id, 'TypeScript')}`
);
break;
case 'curl_noise':
case 'turbulence':
forceLines.push(
` accel += pfCurl(p.pos * ${num(p, 'scale', 1.0).toFixed(4)}) * ${num(p, 'strength', 1.0).toFixed(4)}; // ${f.forceType}:${esc(f.id, 'TypeScript')}`
);
break;
default:
warnings.push(`unknown force "${f.forceType}" (node "${f.id}") — skipped`);
forceLines.push(
` // unknown force ${esc(f.forceType, 'TypeScript')}:${esc(f.id, 'TypeScript')}`
);
}
}
if (forceLines.length === 0)
forceLines.push(' // no forces declared — particles drift inertially');
const wgsl = [
`// Particle Field "${esc(field.name, 'TypeScript')}" — generated by HoloScript TSLCompiler`,
`// count: ${field.count} | lifetime: ${field.lifetime} | forces: [${field.forces
.map((f) => `${esc(f.forceType, 'TypeScript')}:${esc(f.id, 'TypeScript')}`)
.join(', ')}]`,
...warnings.map((w) => `// WARNING: ${esc(w, 'TypeScript')}`),
'',
`struct ParticleField_${safe} {`,
' pos: vec3<f32>,',
' life: f32,',
' vel: vec3<f32>,',
' _pad: f32,',
'};',
'',
'// hash-based value noise → cheap curl approximation for turbulent forces',
'fn pfHash3(p: vec3<f32>) -> f32 {',
' return fract(sin(dot(p, vec3<f32>(12.9898, 78.233, 37.719))) * 43758.5453);',
'}',
'fn pfCurl(p: vec3<f32>) -> vec3<f32> {',
' let e = 0.1;',
' let dx = pfHash3(p + vec3<f32>(e, 0.0, 0.0)) - pfHash3(p - vec3<f32>(e, 0.0, 0.0));',
' let dy = pfHash3(p + vec3<f32>(0.0, e, 0.0)) - pfHash3(p - vec3<f32>(0.0, e, 0.0));',
' let dz = pfHash3(p + vec3<f32>(0.0, 0.0, e)) - pfHash3(p - vec3<f32>(0.0, 0.0, e));',
' return vec3<f32>(dy - dz, dz - dx, dx - dy);',
'}',
'',
`@group(0) @binding(0) var<storage, read> pfIn_${safe}: array<ParticleField_${safe}>;`,
`@group(0) @binding(1) var<storage, read_write> pfOut_${safe}: array<ParticleField_${safe}>;`,
`@group(0) @binding(2) var<uniform> pfDt_${safe}: f32;`,
'',
'@compute @workgroup_size(64)',
`fn ${fnName}(@builtin(global_invocation_id) gid: vec3<u32>) {`,
` let i = gid.x;`,
` if (i >= arrayLength(&pfIn_${safe})) { return; }`,
` var p = pfIn_${safe}[i];`,
` let dt = pfDt_${safe};`,
' var accel = vec3<f32>(0.0);',
...forceLines,
' p.vel += accel * dt;',
' p.pos += p.vel * dt;',
' p.life -= dt;',
' if (p.life <= 0.0) {',
' p.pos = vec3<f32>(0.0);',
' p.vel = vec3<f32>(0.0, 1.0, 0.0);',
` p.life = ${field.lifetime.toFixed(4)};`,
' }',
` pfOut_${safe}[i] = p;`,
'}',
].join('\n');
return { fnName, wgsl };
}
// =============================================================================
// Light Field Compilation (light_field domain — typed multi-light + GI model)
// =============================================================================
//
// A light_field is a typed lighting rig: block-level ambient/bounces/intensity
// (a cheap indirect-GI lift) plus a stack of typed lights (directional / point /
// spot / ambient) that lower to a real WGSL lighting function accumulating
// radiance per fragment. The sovereign answer to Unreal's Lumen (CG-309): the
// world model EMITS the lighting pass from typed structure — dynamic, provable,
// and target-portable — instead of a proprietary GI black box.
//
// Authoring shape (verified against HoloCompositionParser):
// light_field "interior" {
// ambient: "#202028"
// bounces: 2
// sun { type: "directional", dir_y: -1.0, color: "#FFF4E0", intensity: 3.0 }
// fill { type: "point", pos_y: 3.0, color: "#88AAFF", intensity: 1.5, range: 10.0 }
// }
// → properties = { ambient, bounces, intensity?, <lightId>: {type, ...params} }
export interface CompiledLight {
id: string;
/** directional | point | spot | ambient */
lightType: string;
params: Record<string, unknown>;
}
export interface CompiledLightField {
name: string;
ambient: string;
bounces: number;
intensity: number;
lights: CompiledLight[];
traits: string[];
}
/** Normalize a `light_field` domain block: scalars stay GI config, typed
* sub-blocks (objects carrying a `type`) become the light stack. */
export function compileLightFieldBlock(block: HoloDomainBlock): CompiledLightField {
const props = (block.properties || {}) as Record<string, unknown>;
const lights: CompiledLight[] = [];
let ambient = '#000000';
let bounces = 1;
let intensity = 1.0;
for (const [key, raw] of Object.entries(props)) {
if (key === 'ambient' && typeof raw === 'string') {
ambient = raw;
continue;
}
if (key === 'bounces' && typeof raw === 'number') {
bounces = raw;
continue;
}
if (key === 'intensity' && typeof raw === 'number') {
intensity = raw;
continue;
}
if (raw && typeof raw === 'object' && !Array.isArray(raw)) {
const { type, ...params } = raw as Record<string, unknown>;
if (typeof type === 'string') lights.push({ id: key, lightType: type, params });
}
}
return {
name: block.name || 'unnamed',
ambient,
bounces,
intensity,
lights,
traits: block.traits || [],
};
}
/**
* Lower a CompiledLightField to a WGSL fragment lighting function that
* accumulates a GI ambient base plus each typed light's direct contribution.
* Real executable WGSL — each light integrates, GI bounces lift the ambient.
*/
export function lightFieldToWGSL(field: CompiledLightField): { fnName: string; wgsl: string } {
const safe = sanitizeMgIdent(field.name);
const fnName = `evalLightField_${safe}`;
const warnings: string[] = [];
const num = (p: Record<string, unknown>, k: string, d: number): number =>
typeof p[k] === 'number' ? (p[k] as number) : d;
const lightBlocks: string[] = [];
for (const l of field.lights) {
const p = l.params;
const color = mgHexToVec3(p.color);
const intensity = num(p, 'intensity', 1.0).toFixed(4);
switch (l.lightType) {
case 'directional':
case 'sun':
lightBlocks.push(
[
` { // directional:${esc(l.id, 'TypeScript')}`,
` let L = normalize(-vec3<f32>(${num(p, 'dir_x', 0).toFixed(4)}, ${num(p, 'dir_y', -1).toFixed(4)}, ${num(p, 'dir_z', 0).toFixed(4)}));`,
` let NdotL = max(dot(N, L), 0.0);`,
` radiance += albedo * ${color} * ${intensity} * NdotL;`,
` }`,
].join('\n')
);
break;
case 'point':
lightBlocks.push(
[
` { // point:${esc(l.id, 'TypeScript')}`,
` let d = vec3<f32>(${num(p, 'pos_x', 0).toFixed(4)}, ${num(p, 'pos_y', 0).toFixed(4)}, ${num(p, 'pos_z', 0).toFixed(4)}) - worldPos;`,
` let dist = length(d);`,
` let L = d / max(dist, 1e-4);`,
` let NdotL = max(dot(N, L), 0.0);`,
` let atten = 1.0 / (1.0 + (dist * dist) / (${num(p, 'range', 10).toFixed(4)} * ${num(p, 'range', 10).toFixed(4)}));`,
` radiance += albedo * ${color} * ${intensity} * NdotL * atten;`,
` }`,
].join('\n')
);
break;
case 'spot':
lightBlocks.push(
[
` { // spot:${esc(l.id, 'TypeScript')}`,
` let d = vec3<f32>(${num(p, 'pos_x', 0).toFixed(4)}, ${num(p, 'pos_y', 5).toFixed(4)}, ${num(p, 'pos_z', 0).toFixed(4)}) - worldPos;`,
` let dist = length(d);`,
` let L = d / max(dist, 1e-4);`,
` let spotDir = normalize(vec3<f32>(${num(p, 'dir_x', 0).toFixed(4)}, ${num(p, 'dir_y', -1).toFixed(4)}, ${num(p, 'dir_z', 0).toFixed(4)}));`,
` let cone = smoothstep(${Math.cos((num(p, 'cone', 30) * Math.PI) / 180).toFixed(4)}, 1.0, dot(-L, spotDir));`,
` let NdotL = max(dot(N, L), 0.0);`,
` let atten = 1.0 / (1.0 + (dist * dist) / (${num(p, 'range', 10).toFixed(4)} * ${num(p, 'range', 10).toFixed(4)}));`,
` radiance += albedo * ${color} * ${intensity} * NdotL * atten * cone;`,
` }`,
].join('\n')
);
break;
case 'ambient':
case 'ambient_probe':
case 'sky':
lightBlocks.push(
[
` { // ambient:${esc(l.id, 'TypeScript')}`,
` radiance += albedo * ${color} * ${intensity};`,
` }`,
].join('\n')
);
break;
default:
warnings.push(`unknown light "${l.lightType}" (node "${l.id}") — skipped`);
lightBlocks.push(
` // unknown light ${esc(l.lightType, 'TypeScript')}:${esc(l.id, 'TypeScript')}`
);
}
}
const giScale = `(${field.intensity.toFixed(4)} * (1.0 + f32(${Math.round(field.bounces)}) * 0.5))`;
const wgsl = [
`// Light Field "${esc(field.name, 'TypeScript')}" — generated by HoloScript TSLCompiler`,
`// ambient: ${esc(field.ambient, 'TypeScript')} | bounces: ${field.bounces} | lights: [${field.lights
.map((l) => `${esc(l.lightType, 'TypeScript')}:${esc(l.id, 'TypeScript')}`)
.join(', ')}]`,
...warnings.map((w) => `// WARNING: ${esc(w, 'TypeScript')}`),
'',
`fn ${fnName}(worldPos: vec3<f32>, N: vec3<f32>, V: vec3<f32>, albedo: vec3<f32>, roughness: f32, metallic: f32) -> vec3<f32> {`,
' var radiance = vec3<f32>(0.0);',
' // ambient / GI base — bounces approximated as an indirect ambient lift',
` radiance += albedo * ${mgHexToVec3(field.ambient)} * ${giScale};`,
...lightBlocks,
' return radiance;',
'}',
].join('\n');
return { fnName, wgsl };
}
// =============================================================================
// Nav Field Compilation (nav_field domain — typed crowd-steering behaviors)
// =============================================================================
//
// A nav_field is a typed steering rig for a crowd: top-level agents/max_speed
// plus a stack of typed field-based behaviors (seek / flee / flow / arrive) that
// lower to a WGSL compute shader accumulating a per-agent steering force, then
// integrating clamped velocity. The sovereign answer to Unreal's AI/nav +
// crowd framework (CG-325): the behavior stack is typed data the compiler
// lowers to a real solve, not a per-engine behavior-tree binary.
//
// Authoring shape (verified against HoloCompositionParser):
// nav_field "crowd" {
// agents: 500
// max_speed: 3.0
// goal { type: "seek", target_x: 10.0, weight: 1.0 }
// lane { type: "flow", dir_x: 1.0, weight: 0.5 }
// }
// → properties = { agents, max_speed, <behaviorId>: {type, ...params} }
export interface CompiledNavBehavior {
id: string;
/** seek | flee | flow | arrive */
behaviorType: string;
params: Record<string, unknown>;
}
export interface CompiledNavField {
name: string;
agents: number;
maxSpeed: number;
behaviors: CompiledNavBehavior[];
traits: string[];
}
/** Normalize a `nav_field` domain block: scalars stay config, typed sub-blocks
* (objects carrying a `type`) become the steering-behavior stack. */
export function compileNavFieldBlock(block: HoloDomainBlock): CompiledNavField {
const props = (block.properties || {}) as Record<string, unknown>;
const behaviors: CompiledNavBehavior[] = [];
let agents = 256;
let maxSpeed = 2.0;
for (const [key, raw] of Object.entries(props)) {
if (key === 'agents' && typeof raw === 'number') {
agents = raw;
continue;
}
if ((key === 'max_speed' || key === 'maxSpeed') && typeof raw === 'number') {
maxSpeed = raw;
continue;
}
if (raw && typeof raw === 'object' && !Array.isArray(raw)) {
const { type, ...params } = raw as Record<string, unknown>;
if (typeof type === 'string') behaviors.push({ id: key, behaviorType: type, params });
}
}
return { name: block.name || 'unnamed', agents, maxSpeed, behaviors, traits: block.traits || [] };
}
/**
* Lower a CompiledNavField to a WGSL compute shader that accumulates each typed
* steering behavior into a per-agent force, then integrates velocity clamped to
* max_speed. Real executable compute WGSL — each behavior steers, not a comment.
*/
export function navFieldToWGSL(field: CompiledNavField): { fnName: string; wgsl: string } {
const safe = sanitizeMgIdent(field.name);
const fnName = `cs_nav_field_${safe}`;
const ms = field.maxSpeed.toFixed(4);
const warnings: string[] = [];
const num = (p: Record<string, unknown>, k: string, d: number): number =>
typeof p[k] === 'number' ? (p[k] as number) : d;
const steerLines: string[] = [];
for (const b of field.behaviors) {
const p = b.params;
const w = num(p, 'weight', 1.0).toFixed(4);
const target = `vec3<f32>(${num(p, 'target_x', 0).toFixed(4)}, ${num(p, 'target_y', 0).toFixed(4)}, ${num(p, 'target_z', 0).toFixed(4)})`;
switch (b.behaviorType) {
case 'seek':
steerLines.push(
` { let desired = normalize(${target} - a.pos + vec3<f32>(1e-4)) * ${ms}; steer += (desired - a.vel) * ${w}; } // seek:${esc(b.id, 'TypeScript')}`
);
break;
case 'flee':
steerLines.push(
` { let desired = normalize(a.pos - ${target} + vec3<f32>(1e-4)) * ${ms}; steer += (desired - a.vel) * ${w}; } // flee:${esc(b.id, 'TypeScript')}`
);
break;
case 'flow':
steerLines.push(
` { let desired = normalize(vec3<f32>(${num(p, 'dir_x', 1).toFixed(4)}, ${num(p, 'dir_y', 0).toFixed(4)}, ${num(p, 'dir_z', 0).toFixed(4)}) + vec3<f32>(1e-4)) * ${ms}; steer += (desired - a.vel) * ${w}; } // flow:${esc(b.id, 'TypeScript')}`
);
break;
case 'arrive':
steerLines.push(
[
` { // arrive:${esc(b.id, 'TypeScript')}`,
` let to = ${target} - a.pos;`,
` let dist = length(to);`,
` let speed = ${ms} * clamp(dist / ${num(p, 'slow_radius', 3).toFixed(4)}, 0.0, 1.0);`,
` let desired = normalize(to + vec3<f32>(1e-4)) * speed;`,
` steer += (desired - a.vel) * ${w};`,
` }`,
].join('\n')
);
break;
default:
warnings.push(`unknown behavior "${b.behaviorType}" (node "${b.id}") — skipped`);
steerLines.push(
` // unknown behavior ${esc(b.behaviorType, 'TypeScript')}:${esc(b.id, 'TypeScript')}`
);
}
}
if (steerLines.length === 0) steerLines.push(' // no behaviors declared — agents coast');
const wgsl = [
`// Nav Field "${esc(field.name, 'TypeScript')}" — generated by HoloScript TSLCompiler`,
`// agents: ${field.agents} | max_speed: ${field.maxSpeed} | behaviors: [${field.behaviors
.map((b) => `${esc(b.behaviorType, 'TypeScript')}:${esc(b.id, 'TypeScript')}`)
.join(', ')}]`,
...warnings.map((w) => `// WARNING: ${esc(w, 'TypeScript')}`),
'',
`struct NavAgent_${safe} {`,
' pos: vec3<f32>,',
' _pad0: f32,',
' vel: vec3<f32>,',
' _pad1: f32,',
'};',
'',
`@group(0) @binding(0) var<storage, read> navIn_${safe}: array<NavAgent_${safe}>;`,
`@group(0) @binding(1) var<storage, read_write> navOut_${safe}: array<NavAgent_${safe}>;`,
`@group(0) @binding(2) var<uniform> navDt_${safe}: f32;`,
'',
'@compute @workgroup_size(64)',
`fn ${fnName}(@builtin(global_invocation_id) gid: vec3<u32>) {`,
` let i = gid.x;`,
` if (i >= arrayLength(&navIn_${safe})) { return; }`,
` var a = navIn_${safe}[i];`,
` let dt = navDt_${safe};`,
' var steer = vec3<f32>(0.0);',
...steerLines,
' a.vel += steer * dt;',
` let sp = length(a.vel);`,
` if (sp > ${ms}) { a.vel = a.vel / sp * ${ms}; }`,
' a.pos += a.vel * dt;',
` navOut_${safe}[i] = a;`,
'}',
].join('\n');
return { fnName, wgsl };
}
// =============================================================================
// Physics Contract Compilation (physics_contract domain — typed rigid-body + constraint stack)
// =============================================================================
//
// A physics_contract is a typed rigid-body rig: top-level gravity/substeps plus
// two kinds of unique-id sub-blocks — bodies (kind:"body") and constraints
// (kind:"constraint", discriminated further by type). It lowers to a WGSL compute
// shader that runs a semi-implicit-Euler integration step and a PBD-style
// positional constraint projection, substepped for convergence. The sovereign
// answer to Unreal's Chaos / PhysX (CG-313): the rig is typed data the compiler
// lowers to a real deterministic solve, not a per-engine physics binary.
//
// Authoring shape (verified against HoloCompositionParser — MUST use the unique-id
// sub-block form; the `body "name" { }` keyword-named form collides in properties):
// physics_contract "stack" {
// gravity_y: -9.81
// substeps: 2
// ground { kind: "body", mass: 0.0, shape: "box", pos_y: 0.0 } // mass 0 = static
// crate { kind: "body", mass: 2.0, shape: "box", pos_y: 4.0 }
// tether { kind: "constraint", type: "distance", body_a: "crate", body_b: "ground", rest: 2.0 }
// }
// → properties = { gravity_y, substeps, <bodyId|constraintId>: {kind, ...} }
export interface CompiledPhysBody {
id: string;
mass: number;
/** box | sphere | capsule | ... — kept for downstream; increment-1 treats bodies as point masses */
shape: string;
pos: [number, number, number];
}
export interface CompiledPhysConstraint {
id: string;
/** distance | hinge | fixed */
constraintType: string;
bodyA: string;
bodyB: string;
params: Record<string, unknown>;
}
export interface CompiledPhysicsContract {
name: string;
gravity: [number, number, number];
substeps: number;
bodies: CompiledPhysBody[];
constraints: CompiledPhysConstraint[];
traits: string[];
}
/** Normalize a `physics_contract` domain block: scalars stay config, unique-id
* sub-blocks split into bodies (kind:"body") and constraints (kind:"constraint"). */
export function compilePhysicsContractBlock(block: HoloDomainBlock): CompiledPhysicsContract {
const props = (block.properties || {}) as Record<string, unknown>;
const bodies: CompiledPhysBody[] = [];
const constraints: CompiledPhysConstraint[] = [];
const gravity: [number, number, number] = [0, -9.81, 0];
let substeps = 1;
const numOf = (v: unknown, d: number): number => (typeof v === 'number' ? v : d);
for (const [key, raw] of Object.entries(props)) {
if (key === 'gravity' && Array.isArray(raw)) {
gravity[0] = numOf(raw[0], gravity[0]);
gravity[1] = numOf(raw[1], gravity[1]);
gravity[2] = numOf(raw[2], gravity[2]);
continue;
}
if (key === 'gravity_x' && typeof raw === 'number') {
gravity[0] = raw;
continue;
}
if (key === 'gravity_y' && typeof raw === 'number') {
gravity[1] = raw;
continue;
}
if (key === 'gravity_z' && typeof raw === 'number') {
gravity[2] = raw;
continue;