-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAndroidXRCodeTemplates.ts
More file actions
1806 lines (1748 loc) · 80 KB
/
Copy pathAndroidXRCodeTemplates.ts
File metadata and controls
1806 lines (1748 loc) · 80 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 { AndroidXRTraitMapping } from './AndroidXRComponentTypes';
/**
* Android XR Code Templates
*
* Larger trait maps containing extensive Kotlin code generation templates
* for visual, V43, and AI traits.
*/
export const VISUAL_TRAIT_MAP: Record<string, AndroidXRTraitMapping> = {
visible: {
trait: 'visible',
components: [],
level: 'full',
generate: (varName, config) => {
const visible = config.visible ?? true;
return [visible ? '' : `${varName}.setEnabled(false)`].filter(Boolean);
},
},
invisible: {
trait: 'invisible',
components: [],
level: 'full',
generate: (varName) => [`${varName}.setEnabled(false)`],
},
billboard: {
trait: 'billboard',
components: ['BillboardNode'],
level: 'full',
imports: ['androidx.xr.runtime.math.Quaternion'],
generate: (varName) => [
`// @billboard -- face entity toward camera each frame`,
`// Android XR: no built-in BillboardComponent; update rotation in frame callback`,
`xrSession.scene.addOnUpdateListener { _ ->`,
` val camPose = xrSession.scene.activitySpace.pose`,
` val lookAt = Quaternion.lookRotation(`,
` camPose.translation - ${varName}.pose.translation,`,
` Vector3(0f, 1f, 0f)`,
` )`,
` ${varName}.setPose(Pose(${varName}.pose.translation, lookAt))`,
`}`,
],
},
particle_emitter: {
trait: 'particle_emitter',
components: ['ParticleSystem'],
level: 'full',
imports: ['android.opengl.GLES31', 'com.google.android.filament.RenderableManager'],
generate: (varName, config) => {
const rate = config.rate ?? 100;
const lifetime = config.lifetime ?? 1.0;
const maxParticles = config.max_particles ?? 1000;
const shape = String(config.shape || 'sphere');
return [
`// @particle_emitter -- GPU particle system via compute shader`,
`// rate: ${rate}/s, lifetime: ${lifetime}s, max: ${maxParticles}, shape: ${shape}`,
`val ${varName}MaxParticles = ${maxParticles}`,
`val ${varName}ParticleData = FloatArray(${varName}MaxParticles * 8) // pos(3) + vel(3) + life(1) + size(1)`,
`val ${varName}ParticleSSBO = IntArray(1)`,
`GLES31.glGenBuffers(1, ${varName}ParticleSSBO, 0)`,
`GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, ${varName}ParticleSSBO[0])`,
`GLES31.glBufferData(GLES31.GL_SHADER_STORAGE_BUFFER,`,
` ${varName}ParticleData.size * 4L, null, GLES31.GL_DYNAMIC_DRAW)`,
`// Emit ${rate} particles per second from ${shape} shape`,
`// Update kernel: position += velocity * dt; life -= dt; recycle dead particles`,
`val ${varName}EmitProgram = compileComputeShader(particleEmitShaderSource)`,
`val ${varName}UpdateProgram = compileComputeShader(particleUpdateShaderSource)`,
`xrSession.scene.addOnUpdateListener { frame ->`,
` GLES31.glUseProgram(${varName}EmitProgram)`,
` GLES31.glDispatchCompute(ceil(${rate}f / 256f).toInt(), 1, 1)`,
` GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT)`,
` GLES31.glUseProgram(${varName}UpdateProgram)`,
` GLES31.glDispatchCompute(ceil(${varName}MaxParticles / 256f).toInt(), 1, 1)`,
`}`,
];
},
},
animated: {
trait: 'animated',
components: ['GltfModelEntity'],
level: 'full',
imports: ['androidx.xr.scenecore.GltfModelEntity', 'androidx.xr.scenecore.GltfModel'],
generate: (varName, config) => {
const clip = config.clip || '';
const loop = config.loop ?? true;
return [
`// @animated -- GltfModelEntity animation playback`,
clip
? `${varName}Entity.startAnimation(loop = ${loop}, animationName = "${clip}")`
: `${varName}Entity.startAnimation(loop = ${loop})`,
`// Animation state: ${varName}Entity.getAnimationState()`,
];
},
},
lod: {
trait: 'lod',
components: [],
level: 'full',
generate: (varName, config) => {
const distances = config.distances || [5, 15];
const d = distances as number[];
return [
`// @lod -- level-of-detail switching`,
`// Android XR: no built-in LOD; implement distance check in frame callback`,
`// Thresholds: [${d[0] ?? 5}, ${d[1] ?? 15}] meters`,
`xrSession.scene.addOnUpdateListener { _ ->`,
` val camPos = xrSession.scene.activitySpace.pose.translation`,
` val dist = Vector3.distance(camPos, ${varName}.pose.translation)`,
` when {`,
` dist < ${d[0] ?? 5}f -> { /* high detail */ }`,
` dist < ${d[1] ?? 15}f -> { /* medium detail */ }`,
` else -> { /* low detail */ }`,
` }`,
`}`,
];
},
},
shadow_caster: {
trait: 'shadow_caster',
components: ['LightManager'],
level: 'full',
imports: [
'com.google.android.filament.LightManager',
'com.google.android.filament.RenderableManager',
],
generate: (varName, config) => {
const shadowBias = config.shadow_bias ?? 0.001;
return [
`// @shadow_caster -- enable shadow casting via Filament`,
`val ${varName}RenderableManager = engine.renderableManager`,
`val ${varName}Instance = ${varName}RenderableManager.getInstance(${varName}RenderableEntity)`,
`${varName}RenderableManager.setCastShadows(${varName}Instance, true)`,
`// Shadow bias to prevent shadow acne: ${shadowBias}`,
`${varName}RenderableManager.setScreenSpaceContactShadows(${varName}Instance, true)`,
];
},
},
shadow_receiver: {
trait: 'shadow_receiver',
components: ['LightManager'],
level: 'full',
imports: [
'com.google.android.filament.LightManager',
'com.google.android.filament.RenderableManager',
],
generate: (varName) => [
`// @shadow_receiver -- enable shadow receiving via Filament`,
`val ${varName}RenderableManager = engine.renderableManager`,
`val ${varName}Instance = ${varName}RenderableManager.getInstance(${varName}RenderableEntity)`,
`${varName}RenderableManager.setReceiveShadows(${varName}Instance, true)`,
],
},
instancing: {
trait: 'instancing',
components: ['GltfModelEntity'],
level: 'full',
imports: [
'com.google.android.filament.RenderableManager',
'com.google.android.filament.VertexBuffer',
],
generate: (varName, config) => {
const instanceCount = config.count ?? 100;
return [
`// @instancing -- GPU instancing for ${instanceCount} instances`,
`val ${varName}InstanceCount = ${instanceCount}`,
`val ${varName}Transforms = FloatArray(${varName}InstanceCount * 16)`,
`// Populate per-instance transform matrices`,
`for (i in 0 until ${varName}InstanceCount) {`,
` val offset = i * 16`,
` Matrix.setIdentityM(${varName}Transforms, offset)`,
` // Randomize position per instance`,
` Matrix.translateM(${varName}Transforms, offset, i * 1.0f, 0f, 0f)`,
`}`,
`val ${varName}InstanceBuffer = VertexBuffer.Builder()`,
` .bufferCount(1)`,
` .vertexCount(${varName}InstanceCount)`,
` .attribute(VertexBuffer.VertexAttribute.CUSTOM0, 0, VertexBuffer.AttributeType.FLOAT4, 0, 64)`,
` .build(engine)`,
`// RenderableManager.Builder().instances(${varName}InstanceCount)`,
];
},
},
gpu_culling: {
trait: 'gpu_culling',
components: [],
level: 'full',
imports: ['com.google.android.filament.View'],
generate: (varName, config) => {
const frustumCulling = config.frustum ?? true;
const occlusionCulling = config.occlusion ?? false;
return [
`// @gpu_culling -- Filament frustum + occlusion culling`,
`// frustum: ${frustumCulling}, occlusion: ${occlusionCulling}`,
`val ${varName}View = engine.createView()`,
`${varName}View.isFrontFaceWindingInverted = false`,
`// Filament performs automatic frustum culling on all renderables`,
...(occlusionCulling
? [
`// Occlusion culling: enable depth pre-pass`,
`${varName}View.depthPrePass = View.DepthPrePass.ENABLED`,
]
: []),
`// Dynamic culling: disable rendering for entities beyond threshold`,
`xrSession.scene.addOnUpdateListener { _ ->`,
` val camPos = xrSession.scene.activitySpace.pose.translation`,
` val dist = Vector3.distance(camPos, ${varName}.pose.translation)`,
` ${varName}.setEnabled(dist < 50f) // cull beyond 50m`,
`}`,
];
},
},
screen_space_reflections: {
trait: 'screen_space_reflections',
components: [],
level: 'full',
imports: ['com.google.android.filament.View'],
generate: (varName, config) => {
const quality = String(config.quality || 'medium');
return [
`// @screen_space_reflections -- Filament SSR`,
`// quality: ${quality}`,
`val ${varName}View = engine.createView()`,
`${varName}View.screenSpaceReflectionsOptions = View.ScreenSpaceReflectionsOptions().apply {`,
` enabled = true`,
` thickness = 0.1f`,
` bias = 0.01f`,
` maxDistance = 3.0f`,
` stride = ${quality === 'high' ? '1' : quality === 'low' ? '4' : '2'}`,
` resolution = ${quality === 'high' ? '1.0f' : quality === 'low' ? '0.25f' : '0.5f'}`,
`}`,
];
},
},
volumetric_fog: {
trait: 'volumetric_fog',
components: [],
level: 'full',
imports: ['com.google.android.filament.View'],
generate: (varName, config) => {
const density = config.density ?? 0.02;
const albedo = config.albedo || [0.8, 0.8, 0.9];
const a = albedo as number[];
const heightFalloff = config.height_falloff ?? 0.1;
return [
`// @volumetric_fog -- Filament volumetric fog`,
`// density: ${density}, albedo: [${a[0]}, ${a[1]}, ${a[2]}]`,
`val ${varName}View = engine.createView()`,
`${varName}View.fogOptions = View.FogOptions().apply {`,
` enabled = true`,
` density = ${density}f`,
` color = Color(${a[0]}f, ${a[1]}f, ${a[2]}f, 1f)`,
` heightFalloff = ${heightFalloff}f`,
` inScatteringStart = 0.0f`,
` inScatteringSize = 50.0f`,
`}`,
];
},
},
decal_projector: {
trait: 'decal_projector',
components: ['GltfModelEntity'],
level: 'full',
imports: [
'com.google.android.filament.MaterialInstance',
'com.google.android.filament.Texture',
],
generate: (varName, config) => {
const textureUri = String(config.texture || 'decal.png');
const size = config.size || [1, 1];
const s = size as number[];
return [
`// @decal_projector -- projected decal texture`,
`// texture: ${textureUri}, size: ${s[0]}m x ${s[1]}m`,
`val ${varName}DecalTexture = loadTexture(engine, "${textureUri}")`,
`val ${varName}DecalMaterial = engine.createMaterial(decalMaterialData)`,
`val ${varName}DecalInstance = ${varName}DecalMaterial.createInstance()`,
`${varName}DecalInstance.setParameter("baseColorMap", ${varName}DecalTexture,`,
` TextureSampler(TextureSampler.MinFilter.LINEAR, TextureSampler.MagFilter.LINEAR))`,
`// Project decal onto intersecting geometry`,
`${varName}DecalInstance.setParameter("projectionSize", ${s[0]}f, ${s[1]}f)`,
`// Decal uses deferred rendering pass with projection matrix`,
];
},
},
wireframe: {
trait: 'wireframe',
components: ['GltfModelEntity'],
level: 'full',
imports: ['com.google.android.filament.RenderableManager'],
generate: (varName) => [
`// @wireframe -- wireframe rendering mode`,
`val ${varName}RenderableManager = engine.renderableManager`,
`val ${varName}Instance = ${varName}RenderableManager.getInstance(${varName}RenderableEntity)`,
`// Filament: set polygon mode to WIREFRAME via material`,
`val ${varName}WireMaterial = engine.createMaterial(wireframeMaterialData)`,
`val ${varName}WireInstance = ${varName}WireMaterial.createInstance()`,
`${varName}RenderableManager.setMaterialInstanceAt(${varName}Instance, 0, ${varName}WireInstance)`,
],
},
outline: {
trait: 'outline',
components: ['GltfModelEntity'],
level: 'full',
imports: ['com.google.android.filament.RenderableManager'],
generate: (varName, config) => {
const color = config.color || '#00ff00';
const width = config.width ?? 2.0;
return [
`// @outline -- object outline via scaled back-face extrusion`,
`// color: ${color}, width: ${width}px`,
`// Pass 1: Render back-faces scaled slightly larger with solid outline color`,
`val ${varName}OutlineMaterial = engine.createMaterial(outlineMaterialData)`,
`val ${varName}OutlineInstance = ${varName}OutlineMaterial.createInstance()`,
`${varName}OutlineInstance.setParameter("outlineColor",`,
` Colors.RgbaType.SRGB, ${color.toString().replace('#', '0x')}FF.toInt())`,
`${varName}OutlineInstance.setParameter("outlineWidth", ${width}f)`,
`// Pass 2: Render normal geometry on top (depth test passes)`,
];
},
},
bloom: {
trait: 'bloom',
components: [],
level: 'full',
imports: ['com.google.android.filament.View'],
generate: (varName, config) => {
const intensity = config.intensity ?? 0.5;
const threshold = config.threshold ?? 1.0;
return [
`// @bloom -- Filament bloom post-processing`,
`// intensity: ${intensity}, threshold: ${threshold}`,
`val ${varName}View = engine.createView()`,
`${varName}View.bloomOptions = View.BloomOptions().apply {`,
` enabled = true`,
` strength = ${intensity}f`,
` threshold = ${threshold}f`,
` levels = 6`,
` blendMode = View.BloomOptions.BlendMode.ADD`,
` anamorphism = 1.0f`,
`}`,
];
},
},
chromatic_aberration: {
trait: 'chromatic_aberration',
components: [],
level: 'full',
imports: ['com.google.android.filament.View'],
generate: (varName, config) => {
const intensity = config.intensity ?? 0.5;
return [
`// @chromatic_aberration -- chromatic fringing post-processing`,
`// intensity: ${intensity}`,
`val ${varName}View = engine.createView()`,
`// Filament doesn't expose chromatic aberration directly;`,
`// implement via custom post-processing material`,
`val ${varName}ChromaticMaterial = engine.createMaterial(chromaticAberrationData)`,
`val ${varName}ChromaticInstance = ${varName}ChromaticMaterial.createInstance()`,
`${varName}ChromaticInstance.setParameter("intensity", ${intensity}f)`,
`// R, G, B channels offset by intensity * distance_from_center`,
];
},
},
depth_of_field: {
trait: 'depth_of_field',
components: [],
level: 'full',
imports: ['com.google.android.filament.View'],
generate: (varName, config) => {
const focusDistance = config.focus_distance ?? 2.0;
const aperture = config.aperture ?? 2.8;
const cocScale = config.coc_scale ?? 1.0;
return [
`// @depth_of_field -- Filament depth-of-field`,
`// focus distance: ${focusDistance}m, aperture: f/${aperture}`,
`val ${varName}View = engine.createView()`,
`${varName}View.depthOfFieldOptions = View.DepthOfFieldOptions().apply {`,
` enabled = true`,
` focusDistance = ${focusDistance}f`,
` cocScale = ${cocScale}f`,
` cocAspectRatio = 1.0f`,
` maxApertureDiameter = ${aperture}f`,
`}`,
];
},
},
color_grading: {
trait: 'color_grading',
components: [],
level: 'full',
imports: ['com.google.android.filament.View', 'com.google.android.filament.ColorGrading'],
generate: (varName, config) => {
const exposure = config.exposure ?? 0.0;
const contrast = config.contrast ?? 1.0;
const saturation = config.saturation ?? 1.0;
const toneMapping = String(config.tone_mapping || 'ACES');
return [
`// @color_grading -- Filament color grading`,
`// exposure: ${exposure}, contrast: ${contrast}, saturation: ${saturation}`,
`val ${varName}ColorGrading = ColorGrading.Builder()`,
` .toneMapping(ColorGrading.ToneMapping.${toneMapping})`,
` .exposure(${exposure}f)`,
` .contrast(${contrast}f)`,
` .saturation(${saturation}f)`,
` .build(engine)`,
`val ${varName}View = engine.createView()`,
`${varName}View.colorGrading = ${varName}ColorGrading`,
];
},
},
};
// =============================================================================
// ACCESSIBILITY TRAITS
// =============================================================================
export const V43_TRAIT_MAP: Record<string, AndroidXRTraitMapping> = {
spatial_persona: {
trait: 'spatial_persona',
components: ['GltfModelEntity'],
level: 'full',
imports: ['androidx.xr.scenecore.GltfModelEntity', 'androidx.xr.scenecore.GltfModel'],
generate: (varName, config) => {
const style = String(config.style || 'realistic');
const avatarModel = String(config.model || 'avatar.glb');
return [
`// @spatial_persona -- 3D avatar/persona (style: ${style})`,
`val ${varName}AvatarModel = GltfModel.create(session, Uri.parse("${avatarModel}"))`,
`val ${varName}Avatar = GltfModelEntity.create(session, ${varName}AvatarModel)`,
`${varName}Avatar.parent = session.scene.activitySpace`,
`// Animate avatar from hand/head tracking data`,
`xrSession.scene.addOnUpdateListener { _ ->`,
` val headPose = xrSession.scene.activitySpace.pose`,
` ${varName}Avatar.setPose(Pose(headPose.translation + Vector3(0f, -0.5f, 0f), headPose.rotation))`,
`}`,
`// IK: map hand joints to avatar skeleton for gestures`,
];
},
},
shareplay: {
trait: 'shareplay',
components: [],
level: 'full',
imports: [
'com.google.android.gms.nearby.Nearby',
'com.google.android.gms.nearby.connection.Strategy',
'com.google.android.gms.nearby.connection.Payload',
],
generate: (varName, config) => {
const activity = String(config.activity_type || 'custom');
const maxParticipants = config.max_participants ?? 4;
return [
`// @shareplay -- shared activity via Nearby Connections (type: ${activity})`,
`// max participants: ${maxParticipants}`,
`val ${varName}Participants = mutableListOf<String>()`,
`val ${varName}ActivityState = mutableMapOf<String, Any>()`,
``,
`// Start shared activity`,
`Nearby.getConnectionsClient(context).startAdvertising(`,
` "HoloScript-${activity}",`,
` "com.holoscript.shareplay",`,
` connectionLifecycleCallback,`,
` AdvertisingOptions.Builder().setStrategy(Strategy.P2P_STAR).build()`,
`)`,
`// Broadcast activity state changes`,
`fun ${varName}BroadcastState(key: String, value: Any) {`,
` ${varName}ActivityState[key] = value`,
` val stateBytes = Json.encodeToString(${varName}ActivityState).toByteArray()`,
` for (participant in ${varName}Participants) {`,
` Nearby.getConnectionsClient(context).sendPayload(participant, Payload.fromBytes(stateBytes))`,
` }`,
`}`,
];
},
},
object_tracking: {
trait: 'object_tracking',
components: [],
level: 'full',
imports: ['com.google.ar.core.Config', 'com.google.ar.core.AugmentedImageDatabase'],
generate: (varName, config) => {
const referenceObject = String(config.reference_object || 'MyObject');
const trackingMode = String(config.mode || 'image');
return [
`// @object_tracking -- ARCore ${trackingMode} tracking (ref: ${referenceObject})`,
`val ${varName}ImageDb = AugmentedImageDatabase(arSession)`,
`val ${varName}RefBitmap = BitmapFactory.decodeStream(context.assets.open("${referenceObject}.png"))`,
`${varName}ImageDb.addImage("${referenceObject}", ${varName}RefBitmap)`,
`val ${varName}Config = arSession.config.apply {`,
` augmentedImageDatabase = ${varName}ImageDb`,
`}`,
`arSession.configure(${varName}Config)`,
`// Track in frame loop`,
`xrSession.scene.addOnUpdateListener { frame ->`,
` val images = frame.getUpdatedTrackables(AugmentedImage::class.java)`,
` for (image in images) {`,
` if (image.trackingState == TrackingState.TRACKING && image.name == "${referenceObject}") {`,
` ${varName}.setPose(Pose(image.centerPose.translation.toVector3(), image.centerPose.rotation.toQuaternion()))`,
` }`,
` }`,
`}`,
];
},
},
scene_reconstruction: {
trait: 'scene_reconstruction',
components: [],
level: 'full',
imports: [
'com.google.ar.core.Config',
'com.google.ar.core.Frame',
'com.google.ar.core.DepthPoint',
'com.google.ar.core.PointCloud',
],
generate: (varName, config) => {
const mode = String(config.mode || 'mesh');
const maxPoints = Number(config.max_points || 5000);
return [
`// @scene_reconstruction -- ARCore depth-based scene reconstruction (mode: ${mode})`,
`xrSession.scene.configure { config ->`,
` config.depthMode = Config.DepthMode.AUTOMATIC`,
`}`,
`// Process depth frames to reconstruct scene mesh for ${varName}`,
`val ${varName}PointCloud = mutableListOf<FloatArray>()`,
``,
`fun ${varName}ProcessDepthFrame(frame: Frame) {`,
` // Acquire depth image from ARCore`,
` val depthImage = try { frame.acquireDepthImage16Bits() } catch (e: Exception) { return }`,
` val width = depthImage.width; val height = depthImage.height`,
` val buf = depthImage.planes[0].buffer.asShortBuffer()`,
` val pts = mutableListOf<FloatArray>()`,
` val stepX = (width / ${Math.ceil(Math.sqrt(maxPoints))}).coerceAtLeast(1)`,
` val stepY = (height / ${Math.ceil(Math.sqrt(maxPoints))}).coerceAtLeast(1)`,
` for (y in 0 until height step stepY) {`,
` for (x in 0 until width step stepX) {`,
` val depthMm = buf.get(y * width + x).toInt() and 0xFFFF`,
` if (depthMm == 0) continue`,
` val depthM = depthMm / 1000f`,
` // Back-project: focal length approximated from image width`,
` val fx = width.toFloat(); val fy = fx`,
` val cx = width / 2f; val cy = height / 2f`,
` pts += floatArrayOf(`,
` (x - cx) / fx * depthM,`,
` -(y - cy) / fy * depthM,`,
` -depthM`,
` )`,
` }`,
` }`,
` depthImage.close()`,
` ${varName}PointCloud.clear()`,
` ${varName}PointCloud.addAll(pts)`,
`}`,
];
},
},
volumetric_window: {
trait: 'volumetric_window',
components: ['SpatialEnvironment'],
level: 'full',
imports: [
'androidx.xr.compose.spatial.Subspace',
'androidx.xr.compose.subspace.layout.SubspaceModifier',
],
generate: (varName, config) => {
const width = Number(config.width || 0.5);
const height = Number(config.height || 0.5);
const depth = Number(config.depth || 0.5);
return [
`// @volumetric_window -- 3D content volume (${width}m x ${height}m x ${depth}m)`,
`Subspace {`,
` // ${varName} volumetric content`,
` val ${varName}Model = GltfModel.create(session, Paths.get("${varName}.glb"))`,
` val ${varName}Entity = GltfModelEntity.create(session, ${varName}Model)`,
` ${varName}Entity.setPose(Pose(Vector3(0f, 0f, 0f), Quaternion.identity()))`,
`}`,
];
},
},
spatial_navigation: {
trait: 'spatial_navigation',
components: ['InteractableComponent'],
level: 'full',
imports: ['androidx.xr.scenecore.InteractableComponent', 'androidx.xr.scenecore.InputEvent'],
generate: (varName, config) => {
const mode = String(config.mode || 'gaze');
return [
`// @spatial_navigation -- spatial navigation (mode: ${mode})`,
`val ${varName}NavTargets = mutableListOf<Entity>()`,
`var ${varName}CurrentTarget = 0`,
`val ${varName}NavInteractable = InteractableComponent.create(session, executor) { event ->`,
` when (event.action) {`,
` InputEvent.Action.ACTION_HOVER_ENTER -> {`,
` // Gaze entered: highlight as navigation target`,
` }`,
` InputEvent.Action.ACTION_UP -> {`,
` // Select current navigation target`,
` ${varName}CurrentTarget = (${varName}CurrentTarget + 1) % ${varName}NavTargets.size`,
` }`,
` }`,
`}`,
`${varName}.addComponent(${varName}NavInteractable)`,
];
},
},
eye_tracked: {
trait: 'eye_tracked',
components: ['InteractableComponent'],
level: 'full',
imports: ['androidx.xr.scenecore.InteractableComponent', 'androidx.xr.scenecore.InputEvent'],
generate: (varName) => [
`// @eye_tracked -- gaze-driven interaction via hover events`,
`val ${varName}Interactable = InteractableComponent.create(session, executor) { event ->`,
` when (event.action) {`,
` InputEvent.Action.ACTION_HOVER_ENTER -> { /* gaze entered */ }`,
` InputEvent.Action.ACTION_HOVER_EXIT -> { /* gaze exited */ }`,
` }`,
`}`,
`${varName}.addComponent(${varName}Interactable)`,
],
},
realitykit_mesh: {
trait: 'realitykit_mesh',
components: ['GltfModelEntity'],
level: 'full',
imports: ['androidx.xr.scenecore.GltfModelEntity', 'androidx.xr.scenecore.GltfModel'],
generate: (varName, config) => {
const shape = String(config.shape || 'box');
return [
`// @realitykit_mesh -- GltfModelEntity from primitive (shape: ${shape})`,
`// Android XR: use glTF models for geometry instead of programmatic shapes`,
`val ${varName}Model = GltfModel.create(session, Paths.get("primitives/${shape}.glb"))`,
`val ${varName}Entity = GltfModelEntity.create(session, ${varName}Model)`,
];
},
},
eye_hand_fusion: {
trait: 'eye_hand_fusion',
components: ['InteractableComponent', 'HandTrackingProvider'],
level: 'full',
imports: [
'androidx.xr.scenecore.InteractableComponent',
'androidx.xr.arcore.Hand',
'androidx.xr.arcore.HandJointType',
],
generate: (varName) => [
`// @eye_hand_fusion -- combined eye gaze + hand tracking`,
`// Fuse gaze raycast with hand joint positions for ${varName}`,
`var ${varName}GazeHit: FloatArray? = null // [x, y, z] from gaze raycast`,
``,
`val ${varName}Interactable = InteractableComponent.create(session, executor) { event ->`,
` if (event.source == InputEvent.Source.HANDS) {`,
` // Get index-tip pose from hand tracking`,
` val hand = if (event.pointerType == InputEvent.PointerType.LEFT_HAND)`,
` Hand.getOrCreate(session, HandType.LEFT)`,
` else Hand.getOrCreate(session, HandType.RIGHT)`,
` val tipPose = hand.handJoints[HandJointType.INDEX_TIP]`,
` val gazeHit = ${varName}GazeHit`,
` if (tipPose != null && gazeHit != null) {`,
` // Compute distance between finger tip and gaze hit point`,
` val dx = tipPose.translation.x - gazeHit[0]`,
` val dy = tipPose.translation.y - gazeHit[1]`,
` val dz = tipPose.translation.z - gazeHit[2]`,
` val distSq = dx * dx + dy * dy + dz * dz`,
` if (distSq < 0.04f) { // within 20cm — confirmed interaction`,
` when (event.action) {`,
` InputEvent.Action.ACTION_DOWN -> { /* pinch confirmed */ }`,
` InputEvent.Action.ACTION_UP -> { /* pinch released */ }`,
` else -> {}`,
` }`,
` }`,
` }`,
` }`,
`}`,
`${varName}.addComponent(${varName}Interactable)`,
],
},
// AI Generation traits -- comment-level stubs
controlnet: {
trait: 'controlnet',
components: [],
level: 'full',
imports: ['org.tensorflow.lite.Interpreter', 'org.tensorflow.lite.support.image.TensorImage'],
generate: (varName, config) => {
const model = String(config.model || 'controlnet_canny');
const endpoint = String(config.endpoint || '');
return [
`// @controlnet -- ControlNet inference (model: ${model})`,
...(endpoint
? [
`// Remote inference via HTTP`,
`fun ${varName}ControlNetInfer(inputBitmap: android.graphics.Bitmap): ByteArray? {`,
` val baos = java.io.ByteArrayOutputStream()`,
` inputBitmap.compress(android.graphics.Bitmap.CompressFormat.PNG, 90, baos)`,
` val b64 = android.util.Base64.encodeToString(baos.toByteArray(), android.util.Base64.NO_WRAP)`,
` val body = """{"model":"${model}","image":"$b64"}""".toByteArray()`,
` val conn = java.net.URL("${endpoint}/inference").openConnection() as java.net.HttpURLConnection`,
` conn.requestMethod = "POST"; conn.doOutput = true`,
` conn.setRequestProperty("Content-Type", "application/json")`,
` conn.outputStream.write(body)`,
` return if (conn.responseCode == 200) conn.inputStream.readBytes() else null`,
`}`,
]
: [
`// TFLite on-device inference`,
`fun ${varName}ControlNetInfer(inputBitmap: android.graphics.Bitmap): TensorImage? {`,
` val tfliteFile = context.assets.openFd("${model}.tflite")`,
` val chan = java.io.FileInputStream(tfliteFile.fileDescriptor).channel`,
` val mapped = chan.map(java.nio.channels.FileChannel.MapMode.READ_ONLY, tfliteFile.startOffset, tfliteFile.declaredLength)`,
` val opts = Interpreter.Options().apply { setNumThreads(4) }`,
` val interpreter = Interpreter(mapped, opts)`,
` val input = TensorImage.fromBitmap(inputBitmap)`,
` val outShape = interpreter.getOutputTensor(0).shape()`,
` val output = TensorImage(org.tensorflow.lite.DataType.FLOAT32)`,
` interpreter.run(input.buffer, output.buffer)`,
` interpreter.close()`,
` return output`,
`}`,
]),
];
},
},
ai_texture_gen: {
trait: 'ai_texture_gen',
components: ['GltfModelEntity'],
level: 'full',
imports: [
'org.tensorflow.lite.Interpreter',
'android.graphics.Bitmap',
'android.graphics.Canvas',
'android.graphics.Paint',
],
generate: (varName, config) => {
const style = String(config.style || 'photorealistic');
const resolution = Number(config.resolution || 512);
const endpoint = String(config.endpoint || '');
return [
`// @ai_texture_gen -- AI texture generation (style: ${style}, resolution: ${resolution})`,
...(endpoint
? [
`fun ${varName}GenerateTexture(prompt: String): Bitmap? {`,
` val body = """{"prompt":"$prompt","style":"${style}","width":${resolution},"height":${resolution}}""".toByteArray()`,
` val conn = java.net.URL("${endpoint}/generate").openConnection() as java.net.HttpURLConnection`,
` conn.requestMethod = "POST"; conn.doOutput = true`,
` conn.setRequestProperty("Content-Type", "application/json")`,
` conn.outputStream.write(body)`,
` if (conn.responseCode != 200) return null`,
` val responseBytes = conn.inputStream.readBytes()`,
` return android.graphics.BitmapFactory.decodeByteArray(responseBytes, 0, responseBytes.size)`,
`}`,
]
: [
`fun ${varName}GenerateTexture(prompt: String): Bitmap {`,
` // TFLite texture generator (requires texture_gen_${style}.tflite asset)`,
` return try {`,
` val fd = context.assets.openFd("texture_gen_${style}.tflite")`,
` val model = java.io.FileInputStream(fd.fileDescriptor).channel`,
` .map(java.nio.channels.FileChannel.MapMode.READ_ONLY, fd.startOffset, fd.declaredLength)`,
` val opts = Interpreter.Options().apply { setNumThreads(4) }`,
` val tflite = Interpreter(model, opts)`,
` val outBuf = java.nio.FloatBuffer.allocate(${resolution} * ${resolution} * 3)`,
` tflite.run(prompt.encodeToByteArray(), outBuf)`,
` tflite.close()`,
` // Convert float output [0,1] to Bitmap`,
` val bmp = Bitmap.createBitmap(${resolution}, ${resolution}, Bitmap.Config.ARGB_8888)`,
` for (i in 0 until ${resolution} * ${resolution}) {`,
` val r = (outBuf.get(i * 3) * 255).toInt().coerceIn(0, 255)`,
` val g = (outBuf.get(i * 3 + 1) * 255).toInt().coerceIn(0, 255)`,
` val b = (outBuf.get(i * 3 + 2) * 255).toInt().coerceIn(0, 255)`,
` bmp.setPixel(i % ${resolution}, i / ${resolution}, android.graphics.Color.rgb(r, g, b))`,
` }`,
` bmp`,
` } catch (e: Exception) {`,
` // Fallback: solid gray`,
` Bitmap.createBitmap(${resolution}, ${resolution}, Bitmap.Config.ARGB_8888).also {`,
` Canvas(it).drawColor(android.graphics.Color.GRAY)`,
` }`,
` }`,
`}`,
]),
`// Assign generated texture to ${varName} Filament material`,
`val ${varName}Texture = ${varName}GenerateTexture("${style} texture")`,
`// Apply via Filament: MaterialInstance.setParameter("baseColorMap", texture)`,
];
},
},
diffusion_realtime: {
trait: 'diffusion_realtime',
components: [],
level: 'full',
imports: ['org.tensorflow.lite.Interpreter', 'android.opengl.GLES31'],
generate: (varName, config) => {
const backend = String(config.backend || 'tflite');
const steps = Number(config.steps || 4);
const resolution = Number(config.resolution || 512);
return [
`// @diffusion_realtime -- real-time diffusion (backend: ${backend}, steps: ${steps})`,
...(backend === 'vulkan'
? [
`// Vulkan compute pipeline for latent diffusion`,
`// Note: Android XR Vulkan compute requires VK_KHR_vulkan_memory_model`,
`// For production: load SPIR-V shader and dispatch denoising kernel`,
`// Stub: Vulkan initialization via NDK (add vulkan lib in build.gradle)`,
`fun ${varName}DiffusionStep(latent: FloatArray, step: Int): FloatArray {`,
` // PLACEHOLDER: call into JNI Vulkan compute dispatch`,
` // Each step: bind denoising UBO, dispatch(${resolution / 8}, ${resolution / 8}, 1)`,
` return latent // passthrough until NDK Vulkan bridge implemented`,
`}`,
``,
`fun ${varName}RunDiffusion(noiseLatent: FloatArray): FloatArray {`,
` var latent = noiseLatent`,
` for (step in 0 until ${steps}) { latent = ${varName}DiffusionStep(latent, step) }`,
` return latent`,
`}`,
]
: [
`// TFLite diffusion U-Net (requires diffusion_unet_${steps}step.tflite asset)`,
`fun ${varName}RunDiffusion(noiseLatent: FloatArray): FloatArray {`,
` val fd = context.assets.openFd("diffusion_unet_${steps}step.tflite")`,
` val model = java.io.FileInputStream(fd.fileDescriptor).channel`,
` .map(java.nio.channels.FileChannel.MapMode.READ_ONLY, fd.startOffset, fd.declaredLength)`,
` val opts = Interpreter.Options().apply { setNumThreads(4) }`,
` val tflite = Interpreter(model, opts)`,
` var latent = noiseLatent.copyOf()`,
` val outBuf = FloatArray(latent.size)`,
` for (step in 0 until ${steps}) {`,
` tflite.run(latent, outBuf)`,
` outBuf.copyInto(latent)`,
` }`,
` tflite.close()`,
` return latent`,
`}`,
]),
];
},
},
ai_upscaling: {
trait: 'ai_upscaling',
components: [],
level: 'full',
imports: [
'org.tensorflow.lite.Interpreter',
'android.content.Context',
'android.graphics.Bitmap',
'android.graphics.BitmapFactory',
],
generate: (varName, config) => {
const factor = Number(config.factor || 2);
const modelName = String(config.model || 'super_resolution.tflite');
return [
`// @ai_upscaling -- TFLite super-resolution (factor: ${factor}x)`,
`fun ${varName}Upscale(context: Context, bitmap: Bitmap): Bitmap {`,
` val modelBuffer = context.assets.openFd("${modelName}").use {`,
` it.createInputStream().channel.map(java.nio.channels.FileChannel.MapMode.READ_ONLY, it.startOffset, it.declaredLength)`,
` }`,
` val interpreter = Interpreter(modelBuffer)`,
` val inputShape = interpreter.getInputTensor(0).shape() // [1, H, W, 3]`,
` val h = inputShape[1]; val w = inputShape[2]`,
` val scaled = Bitmap.createScaledBitmap(bitmap, w, h, true)`,
` val inputBuffer = java.nio.ByteBuffer.allocateDirect(1 * h * w * 3 * 4).apply { order(java.nio.ByteOrder.nativeOrder()) }`,
` scaled.getPixels(IntArray(h * w), 0, w, 0, 0, w, h)`,
` val outShape = interpreter.getOutputTensor(0).shape() // [1, H*${factor}, W*${factor}, 3]`,
` val outH = outShape[1]; val outW = outShape[2]`,
` val outputBuffer = java.nio.ByteBuffer.allocateDirect(1 * outH * outW * 3 * 4).apply { order(java.nio.ByteOrder.nativeOrder()) }`,
` interpreter.run(inputBuffer, outputBuffer)`,
` return Bitmap.createBitmap(outW, outH, Bitmap.Config.ARGB_8888)`,
`}`,
];
},
},
ai_inpainting: {
trait: 'ai_inpainting',
components: [],
level: 'full',
imports: [
'org.tensorflow.lite.Interpreter',
'android.content.Context',
'android.graphics.Bitmap',
],
generate: (varName, config) => {
const modelName = String(config.model || 'inpainting.tflite');
return [
`// @ai_inpainting -- TFLite mask-based inpainting`,
`fun ${varName}Inpaint(context: Context, image: Bitmap, mask: Bitmap): Bitmap {`,
` val modelBuffer = context.assets.openFd("${modelName}").use {`,
` it.createInputStream().channel.map(java.nio.channels.FileChannel.MapMode.READ_ONLY, it.startOffset, it.declaredLength)`,
` }`,
` val interpreter = Interpreter(modelBuffer)`,
` // Resize both image and mask to model input size`,
` val inputShape = interpreter.getInputTensor(0).shape() // [1, H, W, 4] (RGBA + mask)`,
` val h = inputShape[1]; val w = inputShape[2]`,
` val scaledImage = Bitmap.createScaledBitmap(image, w, h, true)`,
` val scaledMask = Bitmap.createScaledBitmap(mask, w, h, true)`,
` val inputBuffer = java.nio.ByteBuffer.allocateDirect(1 * h * w * 4 * 4).apply { order(java.nio.ByteOrder.nativeOrder()) }`,
` // interleave image RGB + mask alpha into input buffer`,
` val outputBuffer = java.nio.ByteBuffer.allocateDirect(1 * h * w * 3 * 4).apply { order(java.nio.ByteOrder.nativeOrder()) }`,
` interpreter.run(inputBuffer, outputBuffer)`,
` return Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)`,
`}`,
];
},
},
neural_link: {
trait: 'neural_link',
components: ['BluetoothGatt', 'UsbManager'],
level: 'full',
imports: [
'android.bluetooth.BluetoothGatt',
'android.bluetooth.BluetoothGattCallback',
'android.bluetooth.BluetoothGattCharacteristic',
'android.hardware.usb.UsbManager',
],
generate: (varName, config) => {
const interfaceType = String(config.interface_type || 'bci');
const sampleRate = Number(config.sample_rate || 250);
const channels = Number(config.channels || 8);
return [
`// @neural_link -- BCI signal processing pipeline (interface: ${interfaceType})`,
`// Sample rate: ${sampleRate}Hz, Channels: ${channels}`,
`val ${varName}SignalBuffer = ArrayDeque<FloatArray>(${sampleRate})`,
`val ${varName}BciCallback = object : BluetoothGattCallback() {`,
` override fun onCharacteristicChanged(gatt: BluetoothGatt, char: BluetoothGattCharacteristic) {`,
` val raw = char.value ?: return`,
` // Decode ${channels}-channel EEG frame (${sampleRate}Hz, little-endian float32)`,
` val frame = FloatArray(${channels}) { i ->`,
` java.nio.ByteBuffer.wrap(raw, i * 4, 4).order(java.nio.ByteOrder.LITTLE_ENDIAN).float`,
` }`,
` ${varName}SignalBuffer.addLast(frame)`,
` if (${varName}SignalBuffer.size > ${sampleRate}) ${varName}SignalBuffer.removeFirst()`,
` val alphaPower = ${varName}BandPower(frame, 8f, 13f, ${sampleRate}f)`,
` val betaPower = ${varName}BandPower(frame, 13f, 30f, ${sampleRate}f)`,
` if (alphaPower > betaPower * 1.5f) { /* relaxed / focus state */ }`,
` else if (betaPower > alphaPower * 1.5f) { /* active / alert state */ }`,
` }`,
`}`,
``,
`fun ${varName}BandPower(frame: FloatArray, lowHz: Float, highHz: Float, fs: Float): Float {`,
` var power = 0f`,
` val binLow = (lowHz / fs * frame.size).toInt()`,
` val binHigh = (highHz / fs * frame.size).toInt().coerceAtMost(frame.size / 2)`,
` for (k in binLow..binHigh) {`,
` val omega = 2.0 * Math.PI * k / frame.size`,
` val coeff = (2.0 * Math.cos(omega)).toFloat()`,
` var d1 = 0f; var d2 = 0f`,
` for (x in frame) { val d0 = x + coeff * d1 - d2; d2 = d1; d1 = d0 }`,
` power += d1 * d1 + d2 * d2 - coeff * d1 * d2`,
` }`,
` return power`,
`}`,
];
},
},
neural_forge: {
trait: 'neural_forge',
components: ['TFLiteInterpreter', 'NnApiDelegate'],
level: 'full',
imports: [
'org.tensorflow.lite.Interpreter',
'org.tensorflow.lite.nnapi.NnApiDelegate',
'java.io.FileInputStream',
'java.nio.MappedByteBuffer',
'java.nio.channels.FileChannel',
],
generate: (varName, config) => {
const modelPath = String(config.model_path || 'model.tflite');
const epochs = Number(config.epochs || 5);
return [
`// @neural_forge -- on-device TFLite model training / NNAPI`,