-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDomainBlockCompilerMixin.ts
More file actions
4893 lines (4473 loc) · 195 KB
/
Copy pathDomainBlockCompilerMixin.ts
File metadata and controls
4893 lines (4473 loc) · 195 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';
/**
* 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 || [],
};
}
// =============================================================================
// Physics Compilation
// =============================================================================
/** Compiled collider sub-block (box, sphere, capsule, mesh, convex) */
export interface CompiledCollider {
type: 'collider' | 'trigger';
shape?: string;
properties: Record<string, unknown>;
}
/** Compiled rigidbody sub-block (mass, drag, angular_damping, use_gravity) */
export interface CompiledRigidbody {
properties: Record<string, unknown>;
}
/** Compiled force field sub-block (gravity_zone, wind_zone, buoyancy_zone) */
export interface CompiledForceField {
keyword: string;
name?: string;
properties: Record<string, unknown>;
}
/** Compiled joint sub-block within articulation */
export interface CompiledJoint {
keyword: string;
name?: string;
properties: Record<string, unknown>;
}
export interface CompiledPhysics {
keyword: string;
name?: string;
shape?: string;
properties: Record<string, unknown>;
/** Nested collider sub-blocks */
colliders?: CompiledCollider[];
/** Nested rigidbody sub-block (at most one) */
rigidbody?: CompiledRigidbody;
/** Nested force field sub-blocks */
forceFields?: CompiledForceField[];
/** Nested joint sub-blocks (for articulation) */
joints?: CompiledJoint[];
}
export function compilePhysicsBlock(block: HoloDomainBlock): CompiledPhysics {
const colliders: CompiledCollider[] = [];
const forceFields: CompiledForceField[] = [];
const joints: CompiledJoint[] = [];
let rigidbody: CompiledRigidbody | undefined;
for (const child of block.children || []) {
const c = child as unknown as HoloDomainBlock;
if (c.type !== 'DomainBlock') continue;
const kw = c.keyword as string;
if (kw === 'collider' || kw === 'trigger') {
colliders.push({
type: kw as 'collider' | 'trigger',
shape: c.name, // shape stored as name for collider blocks
properties: c.properties || {},
});
} else if (kw === 'rigidbody') {
rigidbody = { properties: c.properties || {} };
} else if (
[
'force_field',
'gravity_zone',
'wind_zone',
'buoyancy_zone',
'magnetic_field',
'drag_zone',
].includes(kw)
) {
forceFields.push({
keyword: kw,
name: c.name,
properties: c.properties || {},
});
} else {
// Joint sub-blocks (hinge, slider, ball_socket, etc.)
joints.push({
keyword: kw,
name: c.name,
properties: c.properties || {},
});
}
}
return {
keyword: block.keyword,
name: block.name,
properties: block.properties || {},
colliders: colliders.length > 0 ? colliders : undefined,
rigidbody,
forceFields: forceFields.length > 0 ? forceFields : undefined,
joints: joints.length > 0 ? joints : undefined,
};
}
// =============================================================================
// Particle / VFX Compilation
// =============================================================================
/** Compiled particle module sub-block (emission, velocity, color_over_life, etc.) */
export interface CompiledParticleModule {
/** Module type keyword (emission, velocity, color_over_life, size_over_life, noise, etc.) */
type: string;
properties: Record<string, unknown>;
}
export interface CompiledParticleSystem {
/** Keyword used (particles, emitter, vfx, particle_system) */
keyword: string;
name: string;
/** Trait decorators (@looping, @burst, @gpu, etc.) */
traits: string[];
/** Top-level scalar properties (rate, max_particles, start_lifetime, etc.) */
properties: Record<string, unknown>;
/** Structured sub-module blocks (emission, velocity, color_over_life, etc.) */
modules: CompiledParticleModule[];
}
export function compileParticleBlock(block: HoloDomainBlock): CompiledParticleSystem {
const modules: CompiledParticleModule[] = [];
for (const child of block.children || []) {
const c = child as unknown as HoloDomainBlock;
if (c.type === 'DomainBlock') {
modules.push({
type: c.keyword,
properties: c.properties || {},
});
}
}
return {
keyword: block.keyword,
name: block.name || 'unnamed',
traits: block.traits || [],
properties: block.properties || {},
modules,
};
}
// =============================================================================
// Post-Processing Compilation
// =============================================================================
/** A single post-processing effect (bloom, depth_of_field, color_grading, etc.) */
export interface CompiledPostEffect {
/** Effect type keyword (bloom, depth_of_field, vignette, etc.) */
type: string;
properties: Record<string, unknown>;
}
export interface CompiledPostProcessing {
/** Keyword used (post_processing, post_fx, render_pipeline) */
keyword: string;
name?: string;
/** Ordered list of effects in the pipeline */
effects: CompiledPostEffect[];
}
export function compilePostProcessingBlock(block: HoloDomainBlock): CompiledPostProcessing {
const effects: CompiledPostEffect[] = [];
for (const child of block.children || []) {
const c = child as unknown as HoloDomainBlock;
if (c.type === 'DomainBlock') {
effects.push({
type: c.keyword,
properties: c.properties || {},
});
}
}
return {
keyword: block.keyword,
name: block.name,
effects,
};
}
// =============================================================================
// Audio Source Compilation
// =============================================================================
export interface CompiledAudioSource {
/** Keyword used (audio_source, audio_listener, reverb_zone, audio_mixer, ambience, sound_emitter) */
keyword: string;
name: string;
/** Trait decorators (@spatial, @hrtf, @stereo, etc.) */
traits: string[];
/** Audio properties (clip, volume, pitch, spatial_blend, etc.) */
properties: Record<string, unknown>;
}
export function compileAudioSourceBlock(block: HoloDomainBlock): CompiledAudioSource {
return {
keyword: block.keyword,
name: block.name || 'unnamed',
traits: block.traits || [],
properties: block.properties || {},
};
}
// =============================================================================
// Weather / Atmosphere Compilation
// =============================================================================
/** A single weather layer (rain, snow, wind, lightning, clouds, etc.) */
export interface CompiledWeatherLayer {
/** Layer type keyword (rain, snow, wind, lightning, clouds, fog_layer, etc.) */
type: string;
properties: Record<string, unknown>;
intensity?: number;
color?: string;
}
export interface CompiledWeather {
/** Keyword used (weather, atmosphere, sky, climate) */
keyword: string;
name?: string;
/** Trait decorators (@dynamic, @cyclical, etc.) */
traits: string[];
/** Top-level scalar properties (intensity, transition_time, etc.) */
properties: Record<string, unknown>;
/** Structured weather layers (rain, snow, wind, lightning, clouds, etc.) */
layers: CompiledWeatherLayer[];
/** Wind configuration */
wind?: { direction?: [number, number, number]; speed?: number };
}
export function compileWeatherBlock(block: HoloDomainBlock): CompiledWeather {
const layers: CompiledWeatherLayer[] = [];
for (const child of block.children || []) {
const c = child as unknown as HoloDomainBlock;
if (c.type === 'DomainBlock') {
layers.push({
type: c.keyword,
properties: c.properties || {},
});
}
}
return {
keyword: block.keyword,
name: block.name,
traits: block.traits || [],
properties: block.properties || {},
layers,
};
}
// =============================================================================
// Target-Specific Code Generation Helpers
// =============================================================================
/** Quality tier context for scaling particle counts, materials, etc. */
export interface TierContext {
particleScale: number;
lodLevel: 'draft' | 'mesh' | 'final';
maxLights: number;
shadowMapSize: number;
shaderComplexity: 'basic' | 'standard' | 'physical';
}
/** Generate R3F/Three.js particle system JSX */
export function particlesToR3F(ps: CompiledParticleSystem, tier?: TierContext): string {
const scale = tier?.particleScale ?? 1.0;
const props: string[] = [];
if (ps.properties.rate)
props.push(`rate={${Math.round((ps.properties.rate as number) * scale)}}`);
if (ps.properties.max_particles)
props.push(`maxParticles={${Math.round((ps.properties.max_particles as number) * scale)}}`);
if (ps.properties.start_lifetime) {
const lt = ps.properties.start_lifetime;
props.push(Array.isArray(lt) ? `lifetime={[${lt.join(', ')}]}` : `lifetime={${lt}}`);
}
if (ps.properties.start_speed) {
const sp = ps.properties.start_speed;
props.push(Array.isArray(sp) ? `speed={[${sp.join(', ')}]}` : `speed={${sp}}`);
}
if (ps.properties.gravity_modifier !== undefined) {
props.push(`gravityModifier={${ps.properties.gravity_modifier}}`);
}
const isLooping = ps.traits.includes('looping');
if (isLooping) props.push('loop');
const modulesJSX = ps.modules
.map((m) => {
const mProps = Object.entries(m.properties)
.map(([k, v]) => {
const camel = k.replace(/_([a-z])/g, (_, c) => c.toUpperCase());
return typeof v === 'string' ? `${camel}="${v}"` : `${camel}={${JSON.stringify(v)}}`;
})
.join(' ');
return ` <${m.type} ${mProps} />`;
})
.join('\n');
return [`<ParticleSystem name="${ps.name}" ${props.join(' ')}>`, modulesJSX, '</ParticleSystem>']
.filter(Boolean)
.join('\n');
}
/** Generate R3F/Three.js post-processing JSX (react-postprocessing) */
export function postProcessingToR3F(pp: CompiledPostProcessing): string {
const effectsJSX = pp.effects
.map((e) => {
const componentName = e.type
.split('_')
.map((w) => w[0].toUpperCase() + w.slice(1))
.join('');
const props = Object.entries(e.properties)
.map(([k, v]) => {
const camel = k.replace(/_([a-z])/g, (_, c) => c.toUpperCase());
return typeof v === 'string' ? `${camel}="${v}"` : `${camel}={${JSON.stringify(v)}}`;
})
.join(' ');
return ` <${componentName} ${props} />`;
})
.join('\n');
return ['<EffectComposer>', effectsJSX, '</EffectComposer>'].join('\n');
}
/** Generate R3F/Three.js audio source JSX */
export function audioSourceToR3F(audio: CompiledAudioSource): string {
const spatialBlend =
typeof audio.properties.spatial_blend === 'number' ? audio.properties.spatial_blend : 0;
const isSpatial = audio.traits.includes('spatial') || spatialBlend > 0;
const tag = isSpatial ? 'PositionalAudio' : 'Audio';
const props: string[] = [];
if (audio.properties.clip) props.push(`url="${audio.properties.clip}"`);
if (audio.properties.volume !== undefined) props.push(`volume={${audio.properties.volume}}`);
if (audio.properties.loop !== undefined) props.push(`loop={${audio.properties.loop}}`);
if (isSpatial && audio.properties.max_distance) {
props.push(`distance={${audio.properties.max_distance}}`);
}
if (audio.properties.play_on_awake) props.push('autoplay');
return `<${tag} name="${audio.name}" ${props.join(' ')} />`;
}
/** Generate USD weather/atmosphere representation */
export function weatherToUSD(weather: CompiledWeather): string {
const lines: string[] = [`def Scope "${weather.name || 'Weather'}" {`];
for (const [key, value] of Object.entries(weather.properties)) {
lines.push(
` custom ${typeof value === 'number' ? 'float' : 'string'} ${key} = ${JSON.stringify(value)}`
);
}
for (const layer of weather.layers) {
lines.push(` def Scope "${layer.type}" {`);
for (const [key, value] of Object.entries(layer.properties)) {
const usdType =
typeof value === 'number'
? 'float'
: typeof value === 'boolean'
? 'bool'
: Array.isArray(value)
? 'float3'
: 'string';
const usdVal = Array.isArray(value) ? `(${value.join(', ')})` : JSON.stringify(value);
lines.push(` custom ${usdType} ${key} = ${usdVal}`);
}
lines.push(' }');
}
lines.push('}');
return lines.join('\n');
}
/** Generate R3F/Three.js material JSX */
export function materialToR3F(mat: CompiledMaterial, tier?: TierContext): string {
// Tier-based material downgrade: basic tier uses meshBasicMaterial for all
const shaderLevel = tier?.shaderComplexity ?? 'physical';
if (shaderLevel === 'basic' && mat.type !== 'unlit') {
const props = [
mat.baseColor ? `color="${mat.baseColor}"` : '',
mat.opacity !== undefined ? `opacity={${mat.opacity}} transparent` : '',
]
.filter(Boolean)
.join(' ');
return `<meshBasicMaterial ${props} />`;
}
if (mat.type === 'unlit') {
const props = [
mat.emissiveColor ? `emissive="${mat.emissiveColor}"` : '',
mat.emissiveIntensity ? `emissiveIntensity={${mat.emissiveIntensity}}` : '',
mat.opacity !== undefined ? `opacity={${mat.opacity}} transparent` : '',
]
.filter(Boolean)
.join(' ');
return `<meshBasicMaterial ${props} />`;
}
const props = [
mat.baseColor ? `color="${mat.baseColor}"` : '',
mat.roughness !== undefined ? `roughness={${mat.roughness}}` : '',
mat.metallic !== undefined ? `metalness={${mat.metallic}}` : '',
mat.opacity !== undefined ? `opacity={${mat.opacity}} transparent` : '',
mat.emissiveColor ? `emissive="${mat.emissiveColor}"` : '',
mat.emissiveIntensity ? `emissiveIntensity={${mat.emissiveIntensity}}` : '',
]
.filter(Boolean)
.join(' ');
const textures = Object.entries(mat.textureMaps)
.map(([type, path]) => {
const propName = type.replace(/_map$/, 'Map').replace(/^albedo/, '');
return `${propName}={useTexture("${path}")}`;
})
.join(' ');
// Promote to MeshPhysicalMaterial when the material declares a physical effect
// (clearcoat/transmission/sheen/iridescence/…). StandardMaterial cannot express
// these — emitting them on it would be silently dropped. `ior` rides along on
// physical only (StandardMaterial has no ior).
if (isPhysicalMaterial(mat)) {
const physical = [
mat.ior !== undefined ? `ior={${mat.ior}}` : '',
mat.clearcoat !== undefined ? `clearcoat={${mat.clearcoat}}` : '',
mat.clearcoatRoughness !== undefined ? `clearcoatRoughness={${mat.clearcoatRoughness}}` : '',
mat.transmission !== undefined ? `transmission={${mat.transmission}}` : '',
mat.thickness !== undefined ? `thickness={${mat.thickness}}` : '',
mat.sheen !== undefined ? `sheen={${mat.sheen}}` : '',
mat.sheenColor ? `sheenColor="${mat.sheenColor}"` : '',
mat.sheenRoughness !== undefined ? `sheenRoughness={${mat.sheenRoughness}}` : '',
mat.specularIntensity !== undefined ? `specularIntensity={${mat.specularIntensity}}` : '',
mat.iridescence !== undefined ? `iridescence={${mat.iridescence}}` : '',
mat.attenuationColor ? `attenuationColor="${mat.attenuationColor}"` : '',
mat.attenuationDistance !== undefined
? `attenuationDistance={${mat.attenuationDistance}}`
: '',
]
.filter(Boolean)
.join(' ');
return `<meshPhysicalMaterial ${props} ${physical} ${textures} />`;
}
return `<meshStandardMaterial ${props} ${textures} />`;
}
/** Generate USD material prim */
export function materialToUSD(mat: CompiledMaterial): string {
const lines: string[] = [
`def Material "${mat.name}" {`,
` token outputs:surface.connect = <${mat.name}/PBRShader.outputs:surface>`,
` def Shader "PBRShader" {`,
` uniform token info:id = "UsdPreviewSurface"`,
];
if (mat.baseColor)
lines.push(` color3f inputs:diffuseColor = (${hexToRGB(mat.baseColor)})`);
if (mat.roughness !== undefined) lines.push(` float inputs:roughness = ${mat.roughness}`);
if (mat.metallic !== undefined) lines.push(` float inputs:metallic = ${mat.metallic}`);
if (mat.opacity !== undefined) lines.push(` float inputs:opacity = ${mat.opacity}`);
if (mat.ior !== undefined) lines.push(` float inputs:ior = ${mat.ior}`);
// Emissive — scale color by intensity since USD has no separate intensity input
if (mat.emissiveColor) {
const rgb = hexToRGB(mat.emissiveColor).split(', ').map(Number);
const intensity = mat.emissiveIntensity ?? 1;
const scaled = rgb.map((c) => Math.min(1, c * intensity));
lines.push(` color3f inputs:emissiveColor = (${scaled.join(', ')})`);
}
lines.push(` token outputs:surface`);
lines.push(` }`);
// Texture reader nodes
const texEntries = Object.entries(mat.textureMaps);
if (texEntries.length > 0) {
const TEX_MAP: Record<string, { input: string; type: string }> = {
albedo_map: { input: 'diffuseColor', type: 'rgb' },
normal_map: { input: 'normal', type: 'rgb' },
roughness_map: { input: 'roughness', type: 'r' },
metallic_map: { input: 'metallic', type: 'r' },
ao_map: { input: 'occlusion', type: 'r' },
emission_map: { input: 'emissiveColor', type: 'rgb' },
displacement_map: { input: 'displacement', type: 'r' },
};
lines.push(` def Shader "stReader" {`);
lines.push(` uniform token info:id = "UsdPrimvarReader_float2"`);
lines.push(` token inputs:varname = "st"`);
lines.push(` float2 outputs:result`);
lines.push(` }`);
for (const [channel, path] of texEntries) {
const mapping = TEX_MAP[channel];
if (!mapping) continue;
const readerName = `${mapping.input}Texture`;
lines.push(` def Shader "${readerName}" {`);
lines.push(` uniform token info:id = "UsdUVTexture"`);
lines.push(` asset inputs:file = @textures/${path}@`);
lines.push(` float2 inputs:st.connect = <${mat.name}/stReader.outputs:result>`);
if (mapping.type === 'rgb') {
lines.push(` color3f outputs:rgb`);
} else {
lines.push(` float outputs:r`);
}
lines.push(` }`);
}
}
lines.push(`}`);
return lines.join('\n');
}
/** Generate glTF material object */
export function materialToGLTF(mat: CompiledMaterial): object {
const gltfMat: Record<string, unknown> = { name: mat.name };
if (mat.type === 'pbr' || mat.type === 'shader') {
gltfMat.pbrMetallicRoughness = {
baseColorFactor: mat.baseColor ? hexToRGBA(mat.baseColor, mat.opacity ?? 1) : [1, 1, 1, 1],
metallicFactor: mat.metallic ?? 0,
roughnessFactor: mat.roughness ?? 0.5,
};
}
if (mat.emissiveColor) {
gltfMat.emissiveFactor = hexToRGB(mat.emissiveColor).split(', ').map(Number);
}
return gltfMat;
}
/** Map joint keyword to URDF joint type */
function jointKeywordToURDF(keyword: string): string {
switch (keyword) {
case 'hinge':
return 'revolute';
case 'slider':
case 'prismatic':
return 'prismatic';
case 'ball_socket':
return 'ball';
case 'fixed_joint':
return 'fixed';
case 'd6_joint':
return 'floating';
case 'spring_joint':
return 'revolute'; // closest URDF equivalent
default:
return 'fixed';
}
}
/** Generate URDF collider as collision element */
function colliderToURDF(collider: CompiledCollider): string {
const shape = collider.shape || 'box';
const props = collider.properties;
const lines = [' <collision>'];
switch (shape) {
case 'sphere':
lines.push(` <geometry><sphere radius="${props.radius || 0.5}"/></geometry>`);
break;
case 'capsule':
lines.push(
` <geometry><cylinder radius="${props.radius || 0.5}" length="${props.height || 1.0}"/></geometry>`
);
break;
case 'box':
default: {
const size = Array.isArray(props.size) ? props.size.join(' ') : '1 1 1';
lines.push(` <geometry><box size="${size}"/></geometry>`);
break;
}
}
lines.push(' </collision>');
return lines.join('\n');
}
/** Generate URDF inertial element from rigidbody */
function rigidbodyToURDF(rb: CompiledRigidbody): string {
const mass = rb.properties.mass ?? 1.0;
const inertiaValues = Array.isArray(rb.properties.inertia) ? rb.properties.inertia : undefined;
return [
' <inertial>',
` <mass value="${mass}"/>`,
inertiaValues
? ` <inertia ixx="${inertiaValues[0] || 0}" iyy="${inertiaValues[1] || 0}" izz="${inertiaValues[2] || 0}" ixy="0" ixz="0" iyz="0"/>`
: ` <inertia ixx="0.01" iyy="0.01" izz="0.01" ixy="0" ixz="0" iyz="0"/>`,
' </inertial>',
].join('\n');
}
/** Generate URDF physics joint */
export function physicsToURDF(physics: CompiledPhysics): string {
const parts: string[] = [];
// Articulation with joint sub-blocks
if (physics.keyword === 'articulation') {
const joints = (physics.joints || []).map((j) => {
const props = j.properties;
const limitsValues = Array.isArray(props.limits) ? props.limits : undefined;
return [
` <joint name="${j.name}" type="${jointKeywordToURDF(j.keyword)}">`,
props.axis
? ` <axis xyz="${Array.isArray(props.axis) ? props.axis.join(' ') : '0 0 1'}"/>`
: '',
limitsValues ? ` <limit lower="${limitsValues[0]}" upper="${limitsValues[1]}"/>` : '',
props.damping ? ` <dynamics damping="${props.damping}"/>` : '',
` </joint>`,
]
.filter(Boolean)
.join('\n');
});
parts.push(...joints);
}
// Collider sub-blocks -> URDF collision elements
if (physics.colliders) {
for (const collider of physics.colliders) {
parts.push(colliderToURDF(collider));
}
}
// Rigidbody sub-block -> URDF inertial element
if (physics.rigidbody) {
parts.push(rigidbodyToURDF(physics.rigidbody));
}
// Force fields -> URDF comments (no direct URDF equivalent)
if (physics.forceFields) {
for (const ff of physics.forceFields) {
parts.push(
` <!-- ${ff.keyword} "${ff.name || ''}" strength="${ff.properties.strength || 0}" -->`
);
}
}
if (parts.length > 0) return parts.join('\n');
return `<!-- ${physics.keyword} ${physics.name || ''} -->`;
}
// =============================================================================
// Unity (C#) Target Helpers
// =============================================================================
/** Generate Unity C# material setup code */
export function materialToUnity(mat: CompiledMaterial, varPrefix: string): string {
const lines: string[] = [];
lines.push(`// Material: ${mat.name}`);
lines.push(
`var ${varPrefix}Mat = new Material(Shader.Find("${mat.type === 'unlit' ? 'Unlit/Color' : 'Standard'}"));`
);
if (mat.baseColor) lines.push(`${varPrefix}Mat.color = ${hexToUnityColor(mat.baseColor)};`);
if (mat.roughness !== undefined)
lines.push(`${varPrefix}Mat.SetFloat("_Smoothness", ${(1 - mat.roughness).toFixed(3)}f);`);
if (mat.metallic !== undefined)
lines.push(`${varPrefix}Mat.SetFloat("_Metallic", ${mat.metallic}f);`);
if (mat.opacity !== undefined && mat.opacity < 1) {
lines.push(`${varPrefix}Mat.SetFloat("_Mode", 3); // Transparent`);
lines.push(
`${varPrefix}Mat.color = new Color(${varPrefix}Mat.color.r, ${varPrefix}Mat.color.g, ${varPrefix}Mat.color.b, ${mat.opacity}f);`
);
}
if (mat.emissiveColor) {
lines.push(`${varPrefix}Mat.EnableKeyword("_EMISSION");`);
lines.push(
`${varPrefix}Mat.SetColor("_EmissionColor", ${hexToUnityColor(mat.emissiveColor)}${mat.emissiveIntensity ? ` * ${mat.emissiveIntensity}f` : ''});`
);
}
for (const [mapType, path] of Object.entries(mat.textureMaps)) {
const shaderProp =
mapType === 'albedo_map'
? '_MainTex'
: mapType === 'normal_map'
? '_BumpMap'
: mapType === 'metallic_map'
? '_MetallicGlossMap'
: mapType === 'roughness_map'
? '_SpecGlossMap'
: mapType === 'emission_map'
? '_EmissionMap'
: mapType === 'occlusion_map'
? '_OcclusionMap'
: `_${mapType.replace(/_map$/, '')}`;
lines.push(
`${varPrefix}Mat.SetTexture("${shaderProp}", Resources.Load<Texture2D>("${path}"));`
);
}
return lines.join('\n');
}
/** Generate Unity C# physics setup code */
export function physicsToUnity(physics: CompiledPhysics, varPrefix: string): string {
const lines: string[] = [];
lines.push(`// Physics: ${physics.keyword} "${physics.name || ''}"`);
if (physics.rigidbody) {
lines.push(`var ${varPrefix}RB = ${varPrefix}GO.AddComponent<Rigidbody>();`);
const rb = physics.rigidbody.properties;
if (rb.mass !== undefined) lines.push(`${varPrefix}RB.mass = ${rb.mass}f;`);
if (rb.drag !== undefined) lines.push(`${varPrefix}RB.drag = ${rb.drag}f;`);
if (rb.angular_damping !== undefined)
lines.push(`${varPrefix}RB.angularDrag = ${rb.angular_damping}f;`);
if (rb.use_gravity === false) lines.push(`${varPrefix}RB.useGravity = false;`);
}
if (physics.colliders) {
for (let i = 0; i < physics.colliders.length; i++) {
const c = physics.colliders[i];
const shape = c.shape || 'box';
const colVar = `${varPrefix}Col${i}`;
if (shape === 'sphere') {
lines.push(`var ${colVar} = ${varPrefix}GO.AddComponent<SphereCollider>();`);
if (c.properties.radius) lines.push(`${colVar}.radius = ${c.properties.radius}f;`);
} else if (shape === 'capsule') {
lines.push(`var ${colVar} = ${varPrefix}GO.AddComponent<CapsuleCollider>();`);
if (c.properties.radius) lines.push(`${colVar}.radius = ${c.properties.radius}f;`);
if (c.properties.height) lines.push(`${colVar}.height = ${c.properties.height}f;`);
} else {
lines.push(`var ${colVar} = ${varPrefix}GO.AddComponent<BoxCollider>();`);
if (c.properties.size && Array.isArray(c.properties.size)) {
lines.push(`${colVar}.size = new Vector3(${c.properties.size.join('f, ')}f);`);
}
}
if (c.type === 'trigger') lines.push(`${colVar}.isTrigger = true;`);
}
}
if (physics.forceFields) {
for (const ff of physics.forceFields) {
if (ff.keyword === 'wind_zone') {
lines.push(`var ${varPrefix}Wind = ${varPrefix}GO.AddComponent<WindZone>();`);
if (ff.properties.strength)
lines.push(`${varPrefix}Wind.windMain = ${ff.properties.strength}f;`);
} else {
lines.push(`// ${ff.keyword} "${ff.name || ''}": ${JSON.stringify(ff.properties)}`);
}
}
}
if (physics.joints) {
for (const j of physics.joints) {
lines.push(`// Joint: ${j.keyword} "${j.name || ''}" — use ConfigurableJoint or HingeJoint`);
}
}
return lines.join('\n');
}
/** Generate Unity C# particle system setup code */
export function particlesToUnity(ps: CompiledParticleSystem, varPrefix: string): string {
const lines: string[] = [];
lines.push(`// Particles: ${ps.name}`);
lines.push(`var ${varPrefix}PS = ${varPrefix}GO.AddComponent<ParticleSystem>();`);
lines.push(`var ${varPrefix}Main = ${varPrefix}PS.main;`);
if (ps.properties.max_particles)
lines.push(`${varPrefix}Main.maxParticles = ${ps.properties.max_particles};`);
if (ps.properties.start_lifetime) {
const lt = ps.properties.start_lifetime;
lines.push(`${varPrefix}Main.startLifetime = ${Array.isArray(lt) ? lt[0] : lt}f;`);
}
if (ps.properties.start_speed) {
const sp = ps.properties.start_speed;
lines.push(`${varPrefix}Main.startSpeed = ${Array.isArray(sp) ? sp[0] : sp}f;`);
}
if (ps.properties.gravity_modifier !== undefined) {
lines.push(`${varPrefix}Main.gravityModifier = ${ps.properties.gravity_modifier}f;`);
}
if (ps.traits.includes('looping')) lines.push(`${varPrefix}Main.loop = true;`);
for (const m of ps.modules) {
lines.push(`// Module: ${m.type} — ${JSON.stringify(m.properties)}`);
}
return lines.join('\n');
}
/** Generate Unity C# post-processing setup code */
export function postProcessingToUnity(pp: CompiledPostProcessing): string {
const lines: string[] = [];
lines.push('// Post-Processing (URP Volume Profile)');
for (const e of pp.effects) {
const className = e.type
.split('_')
.map((w) => w[0].toUpperCase() + w.slice(1))
.join('');
lines.push(`// Effect: ${className}`);
for (const [k, v] of Object.entries(e.properties)) {
lines.push(`// ${k} = ${JSON.stringify(v)}`);
}
}
return lines.join('\n');
}
/** Generate Unity C# audio source setup code */
export function audioSourceToUnity(audio: CompiledAudioSource, varPrefix: string): string {
const lines: string[] = [];
lines.push(`// Audio: ${audio.name} (${audio.keyword})`);
if (audio.keyword === 'reverb_zone') {
lines.push(`var ${varPrefix}Reverb = ${varPrefix}GO.AddComponent<AudioReverbZone>();`);
if (audio.properties.min_distance)
lines.push(`${varPrefix}Reverb.minDistance = ${audio.properties.min_distance}f;`);
if (audio.properties.max_distance)
lines.push(`${varPrefix}Reverb.maxDistance = ${audio.properties.max_distance}f;`);
} else {
lines.push(`var ${varPrefix}AS = ${varPrefix}GO.AddComponent<AudioSource>();`);
if (audio.properties.clip)
lines.push(
`${varPrefix}AS.clip = Resources.Load<AudioClip>("Audio/${audio.properties.clip}");`
);
if (audio.properties.volume !== undefined)
lines.push(`${varPrefix}AS.volume = ${audio.properties.volume}f;`);
if (audio.properties.loop !== undefined)
lines.push(`${varPrefix}AS.loop = ${audio.properties.loop};`);
if (audio.properties.spatial_blend !== undefined)
lines.push(`${varPrefix}AS.spatialBlend = ${audio.properties.spatial_blend}f;`);
if (audio.properties.max_distance)
lines.push(`${varPrefix}AS.maxDistance = ${audio.properties.max_distance}f;`);
if (audio.traits.includes('spatial') || audio.traits.includes('hrtf')) {
lines.push(`${varPrefix}AS.spatialBlend = 1.0f;`);
}
if (audio.properties.play_on_awake) lines.push(`${varPrefix}AS.playOnAwake = true;`);
}
return lines.join('\n');
}
/** Generate Unity C# weather setup code */
export function weatherToUnity(weather: CompiledWeather): string {
const lines: string[] = [];
lines.push(`// Weather: ${weather.keyword} "${weather.name || ''}"`);
for (const layer of weather.layers) {
lines.push(`// Layer: ${layer.type} — ${JSON.stringify(layer.properties)}`);
}
if (weather.properties.intensity !== undefined) {
lines.push(`// Intensity: ${weather.properties.intensity}`);
}
return lines.join('\n');
}
// =============================================================================
// Unreal Engine (C++) Target Helpers
// =============================================================================
/** Generate Unreal C++ material setup code */
export function materialToUnreal(mat: CompiledMaterial, varPrefix: string): string {
const lines: string[] = [];
lines.push(`// Material: ${mat.name}`);
lines.push(`UMaterialInstanceDynamic* ${varPrefix}Mat = UMaterialInstanceDynamic::Create(`);
lines.push(
` LoadObject<UMaterial>(nullptr, TEXT("/Game/Materials/M_${mat.type === 'unlit' ? 'Unlit' : 'PBR'}")), this);`
);
if (mat.baseColor) {
const [r, g, b] = hexToRGBTuple(mat.baseColor);
lines.push(
`${varPrefix}Mat->SetVectorParameterValue(TEXT("BaseColor"), FLinearColor(${r}f, ${g}f, ${b}f));`
);
}
if (mat.roughness !== undefined)
lines.push(`${varPrefix}Mat->SetScalarParameterValue(TEXT("Roughness"), ${mat.roughness}f);`);
if (mat.metallic !== undefined)
lines.push(`${varPrefix}Mat->SetScalarParameterValue(TEXT("Metallic"), ${mat.metallic}f);`);
if (mat.opacity !== undefined)
lines.push(`${varPrefix}Mat->SetScalarParameterValue(TEXT("Opacity"), ${mat.opacity}f);`);
if (mat.emissiveColor) {
const [r, g, b] = hexToRGBTuple(mat.emissiveColor);
const intensity = mat.emissiveIntensity ?? 1;
lines.push(
`${varPrefix}Mat->SetVectorParameterValue(TEXT("EmissiveColor"), FLinearColor(${r * intensity}f, ${g * intensity}f, ${b * intensity}f));`
);
}
for (const [mapType, path] of Object.entries(mat.textureMaps)) {
lines.push(
`${varPrefix}Mat->SetTextureParameterValue(TEXT("${mapType}"), LoadObject<UTexture2D>(nullptr, TEXT("/Game/Textures/${path}")));`
);
}