-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIOSPeripheralGenerators.ts
More file actions
3115 lines (2942 loc) · 121 KB
/
Copy pathIOSPeripheralGenerators.ts
File metadata and controls
3115 lines (2942 loc) · 121 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 { HoloComposition } from '../parser/HoloCompositionTypes';
import type { IOSCompiler } from './IOSCompiler';
import { escapeStringValue } from './CompilerBase';
import { CAMERA_HAND_TRACKING_TRAITS } from '../traits/constants/mobile/camera-hand-tracking';
import { FACE_TRACKING_TRAITS } from '../traits/constants/mobile/face-tracking';
import { IOS_OBJECT_CAPTURE_TRAITS } from '../traits/constants/mobile/ios-object-capture';
import { SHAREPLAY_TRAITS } from '../traits/constants/mobile/shareplay';
import { UWB_POSITIONING_TRAITS } from '../traits/constants/mobile/uwb-positioning';
import { AIRPODS_SPATIAL_AUDIO_TRAITS } from '../traits/constants/mobile/airpods-spatial-audio';
export function hasHandTrackingTraits(composition: HoloComposition): boolean {
const handTraitNames: ReadonlyArray<string> = CAMERA_HAND_TRACKING_TRAITS;
for (const obj of composition.objects || []) {
for (const trait of obj.traits || []) {
const name = typeof trait === 'string' ? trait : trait.name;
if (handTraitNames.includes(name)) return true;
}
}
return false;
}
export function generateHandTrackingFile(
compiler: IOSCompiler,
composition: HoloComposition
): string {
compiler.lines = [];
compiler.indentLevel = 0;
const cls = compiler.options.className;
const twoHands = compiler.compositionHasTrait(composition, 'camera_hand_two_hands');
const maxHands = twoHands ? 2 : 1;
const hasPinch = compiler.compositionHasTrait(composition, 'camera_hand_gesture_pinch');
const hasPoint = compiler.compositionHasTrait(composition, 'camera_hand_gesture_point');
const hasPalm = compiler.compositionHasTrait(composition, 'camera_hand_gesture_palm');
const hasFist = compiler.compositionHasTrait(composition, 'camera_hand_gesture_fist');
const hasConfidence = compiler.compositionHasTrait(composition, 'camera_hand_confidence');
const hasSkeleton = compiler.compositionHasTrait(composition, 'camera_hand_skeleton');
const hasToSpatial = compiler.compositionHasTrait(composition, 'camera_hand_to_spatial');
compiler.emit('// Auto-generated by HoloScript IOSCompiler — Hand Tracking integration');
compiler.emit(
`// Source: composition "${escapeStringValue(composition.name as string, 'Swift')}"`
);
compiler.emit('// Requires iOS 14.0+, Vision framework');
compiler.emit('// Do not edit manually — regenerate from .holo source');
compiler.emit('');
compiler.emit('import Foundation');
compiler.emit('import Vision');
compiler.emit('import AVFoundation');
compiler.emit('import UIKit');
compiler.emit('');
// HandGesture enum
compiler.emit('/// Recognized hand gestures from camera-based tracking.');
compiler.emit('enum HandGesture: String {');
compiler.indentLevel++;
if (hasPinch) compiler.emit('case pinch = "pinch"');
if (hasPoint) compiler.emit('case point = "point"');
if (hasPalm) compiler.emit('case palm = "palm"');
if (hasFist) compiler.emit('case fist = "fist"');
compiler.emit('case none = "none"');
compiler.indentLevel--;
compiler.emit('}');
compiler.emit('');
// HandTrackingManager class
compiler.emit(`class ${cls}HandTrackingManager: NSObject, ObservableObject {`);
compiler.indentLevel++;
compiler.emit('@Published var currentGesture: HandGesture = .none');
compiler.emit('@Published var handCount: Int = 0');
if (hasSkeleton) {
compiler.emit(
'@Published var jointPositions: [[VNHumanHandPoseObservation.JointName: VNRecognizedPoint]] = []'
);
}
compiler.emit('');
compiler.emit('private var captureSession: AVCaptureSession?');
compiler.emit('private let handPoseRequest = VNDetectHumanHandPoseRequest()');
compiler.emit('private let sequenceHandler = VNSequenceRequestHandler()');
if (hasConfidence) {
compiler.emit('private let minConfidence: Float = 0.7');
} else {
compiler.emit('private let minConfidence: Float = 0.5');
}
compiler.emit('');
// init
compiler.emit('override init() {');
compiler.indentLevel++;
compiler.emit('super.init()');
compiler.emit(`handPoseRequest.maximumHandCount = ${maxHands}`);
compiler.indentLevel--;
compiler.emit('}');
compiler.emit('');
// startTracking
compiler.emit('func startTracking() {');
compiler.indentLevel++;
compiler.emit('let session = AVCaptureSession()');
compiler.emit('session.sessionPreset = .high');
compiler.emit('');
compiler.emit(
'guard let device = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .front),'
);
compiler.emit(' let input = try? AVCaptureDeviceInput(device: device) else {');
compiler.indentLevel++;
compiler.emit('print("[HoloScript] Failed to access front camera")');
compiler.emit('return');
compiler.indentLevel--;
compiler.emit('}');
compiler.emit('');
compiler.emit('session.addInput(input)');
compiler.emit('');
compiler.emit('let output = AVCaptureVideoDataOutput()');
compiler.emit(
'output.setSampleBufferDelegate(self, queue: DispatchQueue(label: "handTracking"))'
);
compiler.emit('session.addOutput(output)');
compiler.emit('');
compiler.emit('captureSession = session');
compiler.emit('session.startRunning()');
compiler.emit('print("[HoloScript] Hand tracking started")');
compiler.indentLevel--;
compiler.emit('}');
compiler.emit('');
// stopTracking
compiler.emit('func stopTracking() {');
compiler.indentLevel++;
compiler.emit('captureSession?.stopRunning()');
compiler.emit('captureSession = nil');
compiler.emit('print("[HoloScript] Hand tracking stopped")');
compiler.indentLevel--;
compiler.emit('}');
compiler.emit('');
// processObservation
compiler.emit('private func processObservation(_ observation: VNHumanHandPoseObservation) {');
compiler.indentLevel++;
compiler.emit('guard let thumbTip = try? observation.recognizedPoint(.thumbTip),');
compiler.emit(' let indexTip = try? observation.recognizedPoint(.indexTip),');
compiler.emit(' let indexMCP = try? observation.recognizedPoint(.indexMCP),');
compiler.emit(' let middleTip = try? observation.recognizedPoint(.middleTip),');
compiler.emit(' let middleMCP = try? observation.recognizedPoint(.middleMCP),');
compiler.emit(' let middlePIP = try? observation.recognizedPoint(.middlePIP),');
compiler.emit(' let ringTip = try? observation.recognizedPoint(.ringTip),');
compiler.emit(' let ringMCP = try? observation.recognizedPoint(.ringMCP),');
compiler.emit(' let ringPIP = try? observation.recognizedPoint(.ringPIP),');
compiler.emit(' let littleTip = try? observation.recognizedPoint(.littleTip),');
compiler.emit(' let littleMCP = try? observation.recognizedPoint(.littleMCP),');
compiler.emit(' let littlePIP = try? observation.recognizedPoint(.littlePIP),');
compiler.emit(' let indexPIP = try? observation.recognizedPoint(.indexPIP)');
compiler.emit('else { return }');
compiler.emit('');
if (hasConfidence) {
compiler.emit('// Filter low-confidence joints');
compiler.emit(
'guard thumbTip.confidence > minConfidence && indexTip.confidence > minConfidence else { return }'
);
compiler.emit('');
}
if (hasSkeleton) {
compiler.emit('// Extract all 21 joints');
compiler.emit('var joints: [VNHumanHandPoseObservation.JointName: VNRecognizedPoint] = [:]');
compiler.emit('let allJoints: [VNHumanHandPoseObservation.JointName] = [');
compiler.indentLevel++;
compiler.emit('.wrist, .thumbCMC, .thumbMP, .thumbIP, .thumbTip,');
compiler.emit('.indexMCP, .indexPIP, .indexDIP, .indexTip,');
compiler.emit('.middleMCP, .middlePIP, .middleDIP, .middleTip,');
compiler.emit('.ringMCP, .ringPIP, .ringDIP, .ringTip,');
compiler.emit('.littleMCP, .littlePIP, .littleDIP, .littleTip');
compiler.indentLevel--;
compiler.emit(']');
compiler.emit('for jointName in allJoints {');
compiler.indentLevel++;
compiler.emit('if let point = try? observation.recognizedPoint(jointName) {');
compiler.indentLevel++;
compiler.emit('joints[jointName] = point');
compiler.indentLevel--;
compiler.emit('}');
compiler.indentLevel--;
compiler.emit('}');
compiler.emit('');
}
// Gesture recognition
if (hasPinch) {
compiler.emit('// Pinch gesture: thumb tip close to index tip');
compiler.emit(
'let pinchDist = hypot(thumbTip.location[0] - indexTip.location[0], thumbTip.location[1] - indexTip.location[1])'
);
compiler.emit('if pinchDist < 0.05 {');
compiler.indentLevel++;
compiler.emit('DispatchQueue.main.async { self.currentGesture = .pinch }');
if (hasToSpatial) {
compiler.emit('emitSpatialInput(gesture: .pinch, location: thumbTip.location)');
}
compiler.emit('return');
compiler.indentLevel--;
compiler.emit('}');
compiler.emit('');
}
if (hasPoint) {
compiler.emit('// Point gesture: index extended, others curled');
compiler.emit('let indexExtended = indexTip.location[1] > indexMCP.location[1]');
compiler.emit('let middleCurled = middleTip.location[1] < middlePIP.location[1]');
compiler.emit('let ringCurled = ringTip.location[1] < ringPIP.location[1]');
compiler.emit('let littleCurled = littleTip.location[1] < littlePIP.location[1]');
compiler.emit('if indexExtended && middleCurled && ringCurled && littleCurled {');
compiler.indentLevel++;
compiler.emit('DispatchQueue.main.async { self.currentGesture = .point }');
if (hasToSpatial) {
compiler.emit('emitSpatialInput(gesture: .point, location: indexTip.location)');
}
compiler.emit('return');
compiler.indentLevel--;
compiler.emit('}');
compiler.emit('');
}
if (hasPalm) {
compiler.emit('// Palm gesture: all fingertips above MCPs (open hand)');
compiler.emit('let allExtended = indexTip.location[1] > indexMCP.location[1] &&');
compiler.emit(' middleTip.location[1] > middleMCP.location[1] &&');
compiler.emit(' ringTip.location[1] > ringMCP.location[1] &&');
compiler.emit(' littleTip.location[1] > littleMCP.location[1]');
compiler.emit('if allExtended {');
compiler.indentLevel++;
compiler.emit('DispatchQueue.main.async { self.currentGesture = .palm }');
if (hasToSpatial) {
compiler.emit('emitSpatialInput(gesture: .palm, location: indexTip.location)');
}
compiler.emit('return');
compiler.indentLevel--;
compiler.emit('}');
compiler.emit('');
}
if (hasFist) {
compiler.emit('// Fist gesture: all fingertips below PIPs (closed hand)');
compiler.emit('let allCurled = indexTip.location[1] < indexPIP.location[1] &&');
compiler.emit(' middleTip.location[1] < middlePIP.location[1] &&');
compiler.emit(' ringTip.location[1] < ringPIP.location[1] &&');
compiler.emit(' littleTip.location[1] < littlePIP.location[1]');
compiler.emit('if allCurled {');
compiler.indentLevel++;
compiler.emit('DispatchQueue.main.async { self.currentGesture = .fist }');
if (hasToSpatial) {
compiler.emit('emitSpatialInput(gesture: .fist, location: indexTip.location)');
}
compiler.emit('return');
compiler.indentLevel--;
compiler.emit('}');
compiler.emit('');
}
compiler.emit('DispatchQueue.main.async { self.currentGesture = .none }');
compiler.indentLevel--;
compiler.emit('}');
// Spatial input bridge
if (hasToSpatial) {
compiler.emit('');
compiler.emit('private func emitSpatialInput(gesture: HandGesture, location: CGPoint) {');
compiler.indentLevel++;
compiler.emit('// Bridge to HoloScript spatial_input event system');
compiler.emit('let event: [String: Any] = [');
compiler.indentLevel++;
compiler.emit('"type": "hand_gesture",');
compiler.emit('"gesture": gesture.rawValue,');
compiler.emit('"x": location[0],');
compiler.emit('"y": location[1]');
compiler.indentLevel--;
compiler.emit(']');
compiler.emit('print("[HoloScript] SpatialInput: \\(event)")');
compiler.indentLevel--;
compiler.emit('}');
}
compiler.indentLevel--;
compiler.emit('}');
compiler.emit('');
// AVCaptureVideoDataOutputSampleBufferDelegate extension
compiler.emit(
`extension ${cls}HandTrackingManager: AVCaptureVideoDataOutputSampleBufferDelegate {`
);
compiler.indentLevel++;
compiler.emit(
'func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {'
);
compiler.indentLevel++;
compiler.emit(
'guard let pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else { return }'
);
compiler.emit('');
compiler.emit(
'let handler = VNImageRequestHandler(cvPixelBuffer: pixelBuffer, orientation: .up, options: [:])'
);
compiler.emit('do {');
compiler.indentLevel++;
compiler.emit('try handler.perform([handPoseRequest])');
compiler.emit('guard let results = handPoseRequest.results else { return }');
compiler.emit('');
compiler.emit('DispatchQueue.main.async {');
compiler.indentLevel++;
compiler.emit('self.handCount = results.count');
compiler.indentLevel--;
compiler.emit('}');
compiler.emit('');
compiler.emit('for observation in results {');
compiler.indentLevel++;
compiler.emit('processObservation(observation)');
if (hasSkeleton) {
compiler.emit('// Update joint positions on main thread');
compiler.emit('DispatchQueue.main.async {');
compiler.indentLevel++;
compiler.emit('// jointPositions updated via processObservation');
compiler.indentLevel--;
compiler.emit('}');
}
compiler.indentLevel--;
compiler.emit('}');
compiler.indentLevel--;
compiler.emit('} catch {');
compiler.indentLevel++;
compiler.emit('print("[HoloScript] Hand pose detection error: \\(error)")');
compiler.indentLevel--;
compiler.emit('}');
compiler.indentLevel--;
compiler.emit('}');
compiler.indentLevel--;
compiler.emit('}');
return compiler.lines.join('\n');
}
export function hasObjectCaptureTraits(composition: HoloComposition): boolean {
const captureNames: ReadonlyArray<string> = IOS_OBJECT_CAPTURE_TRAITS;
for (const obj of composition.objects || []) {
for (const trait of obj.traits || []) {
const name = typeof trait === 'string' ? trait : trait.name;
if (captureNames.includes(name)) return true;
}
}
return false;
}
export function collectObjectCaptureTraits(composition: HoloComposition): Set<string> {
const captureNames: ReadonlyArray<string> = IOS_OBJECT_CAPTURE_TRAITS;
const found = new Set<string>();
for (const obj of composition.objects || []) {
for (const t of obj.traits || []) {
const name = typeof t === 'string' ? t : t.name;
if (captureNames.includes(name)) found.add(name);
}
}
return found;
}
export function generateObjectCaptureFile(
compiler: IOSCompiler,
composition: HoloComposition
): string {
compiler.lines = [];
compiler.indentLevel = 0;
const cls = compiler.options.className;
const traits = collectObjectCaptureTraits(composition);
compiler.emit('// Auto-generated by HoloScript IOSCompiler — Object Capture integration');
compiler.emit(
`// Source: composition "${escapeStringValue(composition.name as string, 'Swift')}"`
);
compiler.emit('// Requires iOS 17.0+, RealityKit Object Capture API');
compiler.emit('// Do not edit manually — regenerate from .holo source');
compiler.emit('');
compiler.emit('import Foundation');
compiler.emit('import RealityKit');
compiler.emit('import SwiftUI');
compiler.emit('import Combine');
compiler.emit('import os');
compiler.emit('');
// ── HoloCapturedEntity model ──
compiler.emit('struct HoloCapturedEntity: Identifiable {');
compiler.indentLevel++;
compiler.emit('let id = UUID()');
compiler.emit('let name: String');
compiler.emit('let modelURL: URL');
compiler.emit('let boundingBox: BoundingBox');
compiler.emit('let detailLevel: DetailLevel');
compiler.emit('let pbrMaterials: PBRMaterialSet?');
compiler.emit('');
compiler.emit('struct BoundingBox {');
compiler.indentLevel++;
compiler.emit('let center: SIMD3<Float>');
compiler.emit('let extents: SIMD3<Float>');
compiler.indentLevel--;
compiler.emit('}');
compiler.emit('');
compiler.emit('enum DetailLevel: String, CaseIterable {');
compiler.indentLevel++;
compiler.emit('case preview');
compiler.emit('case reduced');
compiler.emit('case medium');
compiler.emit('case full');
compiler.emit('case raw');
compiler.indentLevel--;
compiler.emit('}');
compiler.emit('');
compiler.emit('struct PBRMaterialSet {');
compiler.indentLevel++;
compiler.emit('let diffuseMap: URL?');
compiler.emit('let normalMap: URL?');
compiler.emit('let roughnessMap: URL?');
compiler.emit('let metallicMap: URL?');
compiler.emit('let aoMap: URL?');
compiler.indentLevel--;
compiler.emit('}');
compiler.indentLevel--;
compiler.emit('}');
compiler.emit('');
// ── ObjectCaptureManager class ──
compiler.emit(`class ${cls}ObjectCaptureManager: ObservableObject {`);
compiler.indentLevel++;
compiler.emit('');
compiler.emit(
'private let logger = Logger(subsystem: "net.holoscript", category: "ObjectCapture")'
);
compiler.emit('');
compiler.emit('enum CaptureState: Equatable {');
compiler.indentLevel++;
compiler.emit('case ready');
compiler.emit('case capturing');
compiler.emit('case processing');
compiler.emit('case completed');
compiler.emit('case failed(String)');
compiler.emit('');
compiler.emit('static func == (lhs: CaptureState, rhs: CaptureState) -> Bool {');
compiler.indentLevel++;
compiler.emit('switch (lhs, rhs) {');
compiler.emit('case (.ready, .ready), (.capturing, .capturing),');
compiler.emit(' (.processing, .processing), (.completed, .completed): return true');
compiler.emit('case (.failed(let a), .failed(let b)): return a == b');
compiler.emit('default: return false');
compiler.emit('}');
compiler.indentLevel--;
compiler.emit('}');
compiler.indentLevel--;
compiler.emit('}');
compiler.emit('');
compiler.emit('@Published var state: CaptureState = .ready');
compiler.emit('@Published var progress: Float = 0.0');
compiler.emit('@Published var capturedEntity: HoloCapturedEntity?');
compiler.emit('@Published var feedbackMessages: [String] = []');
compiler.emit('');
compiler.emit('private var captureSession: ObjectCaptureSession?');
compiler.emit('private var outputDirectory: URL');
compiler.emit('private var cancellables = Set<AnyCancellable>()');
compiler.emit('');
// ── init ──
compiler.emit('init() {');
compiler.indentLevel++;
compiler.emit(
'let docs = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!'
);
compiler.emit(
'self.outputDirectory = docs.appendingPathComponent("HoloCaptures", isDirectory: true)'
);
compiler.emit(
'try? FileManager.default.createDirectory(at: outputDirectory, withIntermediateDirectories: true)'
);
compiler.indentLevel--;
compiler.emit('}');
compiler.emit('');
// ── isSupported ──
compiler.emit('var isSupported: Bool {');
compiler.indentLevel++;
compiler.emit('ObjectCaptureSession.isSupported');
compiler.indentLevel--;
compiler.emit('}');
compiler.emit('');
// ── startCapture ──
compiler.emit('func startCapture() {');
compiler.indentLevel++;
compiler.emit('guard isSupported else {');
compiler.indentLevel++;
compiler.emit('state = .failed("Object Capture not supported on this device")');
compiler.emit('return');
compiler.indentLevel--;
compiler.emit('}');
compiler.emit('');
compiler.emit('let session = ObjectCaptureSession()');
compiler.emit('self.captureSession = session');
compiler.emit('');
compiler.emit('var configuration = ObjectCaptureSession.Configuration()');
compiler.emit(
'configuration.checkpointDirectory = outputDirectory.appendingPathComponent("Checkpoints")'
);
compiler.emit('configuration.isOverCaptureEnabled = true');
compiler.emit('session.start(imagesDirectory: outputDirectory.appendingPathComponent("Images"),');
compiler.emit(' configuration: configuration)');
compiler.emit('');
compiler.emit('observeSession(session)');
compiler.emit('state = .capturing');
compiler.emit('logger.info("[HoloScript] Object Capture session started")');
compiler.indentLevel--;
compiler.emit('}');
compiler.emit('');
// ── stopCapture ──
compiler.emit('func stopCapture() {');
compiler.indentLevel++;
compiler.emit('captureSession?.finish()');
compiler.emit('logger.info("[HoloScript] Object Capture session finished")');
compiler.indentLevel--;
compiler.emit('}');
compiler.emit('');
// ── observeSession (feedback) ──
if (traits.has('object_capture_feedback') || traits.has('object_capture')) {
compiler.emit('private func observeSession(_ session: ObjectCaptureSession) {');
compiler.indentLevel++;
compiler.emit('session.stateUpdates.sink { [weak self] newState in');
compiler.indentLevel++;
compiler.emit('guard let self = self else { return }');
compiler.emit('switch newState {');
compiler.emit('case .ready:');
compiler.indentLevel++;
compiler.emit('self.feedbackMessages.append("Ready to capture")');
compiler.indentLevel--;
compiler.emit('case .detecting:');
compiler.indentLevel++;
compiler.emit('self.feedbackMessages.append("Detecting object...")');
compiler.indentLevel--;
compiler.emit('case .capturing:');
compiler.indentLevel++;
compiler.emit('self.feedbackMessages.append("Move slowly around the object")');
compiler.indentLevel--;
compiler.emit('case .finishing:');
compiler.indentLevel++;
compiler.emit('self.feedbackMessages.append("Finishing capture...")');
compiler.indentLevel--;
compiler.emit('case .completed:');
compiler.indentLevel++;
compiler.emit('self.state = .processing');
compiler.emit('self.feedbackMessages.append("Capture complete — processing...")');
compiler.emit('self.processCapture()');
compiler.indentLevel--;
compiler.emit('case .failed(let error):');
compiler.indentLevel++;
compiler.emit('self.state = .failed(error.localizedDescription)');
compiler.indentLevel--;
compiler.emit('default:');
compiler.indentLevel++;
compiler.emit('break');
compiler.indentLevel--;
compiler.emit('}');
compiler.indentLevel--;
compiler.emit('}.store(in: &cancellables)');
compiler.indentLevel--;
compiler.emit('}');
compiler.emit('');
}
// ── processCapture (PhotogrammetrySession) ──
if (traits.has('photogrammetry_scan') || traits.has('object_capture')) {
compiler.emit('private func processCapture() {');
compiler.indentLevel++;
compiler.emit('Task {');
compiler.indentLevel++;
compiler.emit('do {');
compiler.indentLevel++;
compiler.emit('let inputFolder = outputDirectory.appendingPathComponent("Images")');
compiler.emit('let request = makePhotogrammetryRequest()');
compiler.emit('let session = try PhotogrammetrySession(input: inputFolder)');
compiler.emit('');
compiler.emit('try session.process(requests: [request])');
compiler.emit('');
compiler.emit('for try await output in session.outputs {');
compiler.indentLevel++;
compiler.emit('switch output {');
compiler.emit('case .requestProgress(let request, let fraction):');
compiler.indentLevel++;
compiler.emit('await MainActor.run { self.progress = Float(fraction) }');
compiler.indentLevel--;
compiler.emit('case .requestComplete(let request, let result):');
compiler.indentLevel++;
compiler.emit('await MainActor.run {');
compiler.indentLevel++;
compiler.emit('self.handlePhotogrammetryResult(result)');
compiler.emit('self.state = .completed');
compiler.indentLevel--;
compiler.emit('}');
compiler.indentLevel--;
compiler.emit('case .requestError(let request, let error):');
compiler.indentLevel++;
compiler.emit('await MainActor.run { self.state = .failed(error.localizedDescription) }');
compiler.indentLevel--;
compiler.emit('default: break');
compiler.emit('}');
compiler.indentLevel--;
compiler.emit('}');
compiler.indentLevel--;
compiler.emit('} catch {');
compiler.indentLevel++;
compiler.emit('await MainActor.run { self.state = .failed(error.localizedDescription) }');
compiler.indentLevel--;
compiler.emit('}');
compiler.indentLevel--;
compiler.emit('}');
compiler.indentLevel--;
compiler.emit('}');
compiler.emit('');
}
// ── makePhotogrammetryRequest with detail level ──
if (traits.has('object_capture_lod') || traits.has('object_capture')) {
compiler.emit('private func makePhotogrammetryRequest() -> PhotogrammetrySession.Request {');
compiler.indentLevel++;
compiler.emit('let outputURL = outputDirectory.appendingPathComponent("model.usdz")');
compiler.emit(
'// .full detail level captures PBR maps (diffuse, normal, roughness, metallic, AO)'
);
compiler.emit('return .modelFile(url: outputURL, detail: .full)');
compiler.indentLevel--;
compiler.emit('}');
compiler.emit('');
compiler.emit('func generateAllLODs() async throws -> [HoloCapturedEntity.DetailLevel: URL] {');
compiler.indentLevel++;
compiler.emit('var results: [HoloCapturedEntity.DetailLevel: URL] = [:]');
compiler.emit('let inputFolder = outputDirectory.appendingPathComponent("Images")');
compiler.emit('let session = try PhotogrammetrySession(input: inputFolder)');
compiler.emit('');
compiler.emit('for level in HoloCapturedEntity.DetailLevel.allCases {');
compiler.indentLevel++;
compiler.emit(
'let url = outputDirectory.appendingPathComponent("model_\\(level.rawValue).usdz")'
);
compiler.emit('let detail: PhotogrammetrySession.Request.Detail');
compiler.emit('switch level {');
compiler.emit('case .preview: detail = .preview');
compiler.emit('case .reduced: detail = .reduced');
compiler.emit('case .medium: detail = .medium');
compiler.emit('case .full: detail = .full');
compiler.emit('case .raw: detail = .raw');
compiler.emit('}');
compiler.emit(
'let request = PhotogrammetrySession.Request.modelFile(url: url, detail: detail)'
);
compiler.emit('try session.process(requests: [request])');
compiler.emit('for try await output in session.outputs {');
compiler.indentLevel++;
compiler.emit('if case .requestComplete = output { results[level] = url; break }');
compiler.indentLevel--;
compiler.emit('}');
compiler.indentLevel--;
compiler.emit('}');
compiler.emit('return results');
compiler.indentLevel--;
compiler.emit('}');
compiler.emit('');
}
// ── PBR texture extraction ──
if (traits.has('pbr_texture_extract') || traits.has('object_capture')) {
compiler.emit(
'private func extractPBRMaterials(from modelURL: URL) -> HoloCapturedEntity.PBRMaterialSet? {'
);
compiler.indentLevel++;
compiler.emit('let baseDir = modelURL.deletingLastPathComponent()');
compiler.emit('let diffuse = baseDir.appendingPathComponent("diffuse.png")');
compiler.emit('let normal = baseDir.appendingPathComponent("normal.png")');
compiler.emit('let roughness = baseDir.appendingPathComponent("roughness.png")');
compiler.emit('let metallic = baseDir.appendingPathComponent("metallic.png")');
compiler.emit('let ao = baseDir.appendingPathComponent("ao.png")');
compiler.emit('');
compiler.emit('return HoloCapturedEntity.PBRMaterialSet(');
compiler.emit(
' diffuseMap: FileManager.default.fileExists(atPath: diffuse.path) ? diffuse : nil,'
);
compiler.emit(
' normalMap: FileManager.default.fileExists(atPath: normal.path) ? normal : nil,'
);
compiler.emit(
' roughnessMap: FileManager.default.fileExists(atPath: roughness.path) ? roughness : nil,'
);
compiler.emit(
' metallicMap: FileManager.default.fileExists(atPath: metallic.path) ? metallic : nil,'
);
compiler.emit(' aoMap: FileManager.default.fileExists(atPath: ao.path) ? ao : nil');
compiler.emit(')');
compiler.indentLevel--;
compiler.emit('}');
compiler.emit('');
}
// ── handlePhotogrammetryResult ──
compiler.emit(
'private func handlePhotogrammetryResult(_ result: PhotogrammetrySession.Result) {'
);
compiler.indentLevel++;
compiler.emit('switch result {');
compiler.emit('case .modelFile(let url):');
compiler.indentLevel++;
compiler.emit('logger.info("[HoloScript] Model generated at \\(url.path)")');
if (traits.has('pbr_texture_extract') || traits.has('object_capture')) {
compiler.emit('let pbr = extractPBRMaterials(from: url)');
}
compiler.emit('capturedEntity = HoloCapturedEntity(');
compiler.emit(' name: "captured_object",');
compiler.emit(' modelURL: url,');
compiler.emit(' boundingBox: HoloCapturedEntity.BoundingBox(center: .zero, extents: .one),');
compiler.emit(' detailLevel: .full,');
if (traits.has('pbr_texture_extract') || traits.has('object_capture')) {
compiler.emit(' pbrMaterials: pbr');
} else {
compiler.emit(' pbrMaterials: nil');
}
compiler.emit(')');
compiler.indentLevel--;
compiler.emit('default:');
compiler.indentLevel++;
compiler.emit('logger.warning("[HoloScript] Unexpected photogrammetry result type")');
compiler.indentLevel--;
compiler.emit('}');
compiler.indentLevel--;
compiler.emit('}');
compiler.emit('');
// ── USDZ export ──
if (traits.has('object_capture_export_usdz') || traits.has('object_capture')) {
compiler.emit('func exportUSDZ() -> URL? {');
compiler.indentLevel++;
compiler.emit('let usdzURL = outputDirectory.appendingPathComponent("export.usdz")');
compiler.emit('guard let modelURL = capturedEntity?.modelURL else { return nil }');
compiler.emit('do {');
compiler.indentLevel++;
compiler.emit('try FileManager.default.copyItem(at: modelURL, to: usdzURL)');
compiler.emit('logger.info("[HoloScript] USDZ exported to \\(usdzURL.path)")');
compiler.emit('return usdzURL');
compiler.indentLevel--;
compiler.emit('} catch {');
compiler.indentLevel++;
compiler.emit(
'logger.error("[HoloScript] USDZ export failed: \\(error.localizedDescription)")'
);
compiler.emit('return nil');
compiler.indentLevel--;
compiler.emit('}');
compiler.indentLevel--;
compiler.emit('}');
compiler.emit('');
}
// ── Convert to .holo ──
if (traits.has('object_capture_to_holo') || traits.has('object_capture')) {
compiler.emit('func convertToHolo() -> String? {');
compiler.indentLevel++;
compiler.emit('guard let entity = capturedEntity else { return nil }');
compiler.emit('');
compiler.emit('var holo = "scene CapturedObject {\\n"');
compiler.emit('holo += " object \\(entity.name) {\\n"');
compiler.emit('holo += " model: \\"\\(entity.modelURL.lastPathComponent)\\"\\n"');
compiler.emit(
'holo += " position: [\\(entity.boundingBox.center[0]), \\(entity.boundingBox.center[1]), \\(entity.boundingBox.center[2])]\\n"'
);
compiler.emit(
'holo += " scale: [\\(entity.boundingBox.extents[0]), \\(entity.boundingBox.extents[1]), \\(entity.boundingBox.extents[2])]\\n"'
);
compiler.emit('holo += " traits: [object_capture, photogrammetry_scan]\\n"');
if (traits.has('pbr_texture_extract')) {
compiler.emit('if let pbr = entity.pbrMaterials {');
compiler.indentLevel++;
compiler.emit('if pbr.diffuseMap != nil { holo += " diffuse_map: \\"diffuse.png\\"\\n" }');
compiler.emit('if pbr.normalMap != nil { holo += " normal_map: \\"normal.png\\"\\n" }');
compiler.emit(
'if pbr.roughnessMap != nil { holo += " roughness_map: \\"roughness.png\\"\\n" }'
);
compiler.emit(
'if pbr.metallicMap != nil { holo += " metallic_map: \\"metallic.png\\"\\n" }'
);
compiler.emit('if pbr.aoMap != nil { holo += " ao_map: \\"ao.png\\"\\n" }');
compiler.indentLevel--;
compiler.emit('}');
}
compiler.emit('holo += " }\\n"');
compiler.emit('holo += "}\\n"');
compiler.emit('return holo');
compiler.indentLevel--;
compiler.emit('}');
compiler.emit('');
}
compiler.indentLevel--;
compiler.emit('}');
compiler.emit('');
// ── SwiftUI View ──
if (traits.has('object_capture_guide') || traits.has('object_capture')) {
compiler.emit(`struct ${cls}ObjectCaptureView: View {`);
compiler.indentLevel++;
compiler.emit(`@StateObject private var manager = ${cls}ObjectCaptureManager()`);
compiler.emit('');
compiler.emit('var body: some View {');
compiler.indentLevel++;
compiler.emit('ZStack {');
compiler.indentLevel++;
compiler.emit('if let session = manager.captureSession {');
compiler.indentLevel++;
compiler.emit('ObjectCapturePointCloudView(session: session)');
compiler.emit(' .edgesIgnoringSafeArea(.all)');
compiler.indentLevel--;
compiler.emit('}');
compiler.emit('');
compiler.emit('VStack {');
compiler.indentLevel++;
compiler.emit('Spacer()');
compiler.emit('');
// ── Feedback messages ──
compiler.emit('// Coverage indicator and feedback');
compiler.emit('if !manager.feedbackMessages.isEmpty {');
compiler.indentLevel++;
compiler.emit('Text(manager.feedbackMessages.last ?? "")');
compiler.emit(' .font(.caption)');
compiler.emit(' .foregroundColor(.white)');
compiler.emit(' .padding(8)');
compiler.emit(' .background(Color.black.opacity(0.6))');
compiler.emit(' .cornerRadius(8)');
compiler.indentLevel--;
compiler.emit('}');
compiler.emit('');
// ── Progress indicator ──
compiler.emit('if manager.state == .processing {');
compiler.indentLevel++;
compiler.emit('ProgressView(value: Double(manager.progress))');
compiler.emit(' .progressViewStyle(.linear)');
compiler.emit(' .padding()');
compiler.emit('Text("Processing: \\(Int(manager.progress * 100))%")');
compiler.emit(' .foregroundColor(.white)');
compiler.indentLevel--;
compiler.emit('}');
compiler.emit('');
// ── Capture controls ──
compiler.emit('HStack(spacing: 20) {');
compiler.indentLevel++;
compiler.emit('switch manager.state {');
compiler.emit('case .ready:');
compiler.indentLevel++;
compiler.emit('Button("Start Capture") { manager.startCapture() }');
compiler.emit(' .buttonStyle(.borderedProminent)');
compiler.indentLevel--;
compiler.emit('case .capturing:');
compiler.indentLevel++;
compiler.emit('Button("Finish Capture") { manager.stopCapture() }');
compiler.emit(' .buttonStyle(.borderedProminent)');
compiler.emit(' .tint(.red)');
compiler.indentLevel--;
compiler.emit('case .completed:');
compiler.indentLevel++;
compiler.emit('if let entity = manager.capturedEntity {');
compiler.indentLevel++;
compiler.emit('NavigationLink("Preview Model") {');
compiler.indentLevel++;
compiler.emit(`${cls}ModelPreviewView(url: entity.modelURL)`);
compiler.indentLevel--;
compiler.emit('}');
compiler.emit('.buttonStyle(.borderedProminent)');
compiler.indentLevel--;
compiler.emit('}');
compiler.indentLevel--;
compiler.emit('case .failed(let message):');
compiler.indentLevel++;
compiler.emit('Text("Error: \\(message)")');
compiler.emit(' .foregroundColor(.red)');
compiler.indentLevel--;
compiler.emit('default: EmptyView()');
compiler.emit('}');
compiler.indentLevel--;
compiler.emit('}');
compiler.emit('.padding()');
compiler.indentLevel--;
compiler.emit('}');
compiler.indentLevel--;
compiler.emit('}');
compiler.indentLevel--;
compiler.emit('}');
compiler.indentLevel--;
compiler.emit('}');
compiler.emit('');
// ── Model preview ──
compiler.emit(`struct ${cls}ModelPreviewView: View {`);
compiler.indentLevel++;
compiler.emit('let url: URL');
compiler.emit('');
compiler.emit('var body: some View {');
compiler.indentLevel++;
compiler.emit('Model3D(url: url) { model in');
compiler.indentLevel++;
compiler.emit('model.resizable()');
compiler.emit(' .aspectRatio(contentMode: .fit)');
compiler.indentLevel--;
compiler.emit('} placeholder: {');
compiler.indentLevel++;
compiler.emit('ProgressView()');
compiler.indentLevel--;
compiler.emit('}');
compiler.emit('.navigationTitle("Captured Object")');
compiler.indentLevel--;
compiler.emit('}');
compiler.indentLevel--;
compiler.emit('}');
}
return compiler.lines.join('\n');
}
export function hasSharePlayTraits(composition: HoloComposition): boolean {
const sharePlayNames: ReadonlyArray<string> = SHAREPLAY_TRAITS;
for (const obj of composition.objects || []) {
for (const trait of obj.traits || []) {
const name = typeof trait === 'string' ? trait : trait.name;
if (sharePlayNames.includes(name)) return true;
}
}
return false;
}
export function generateSharePlayFile(compiler: IOSCompiler, composition: HoloComposition): string {
compiler.lines = [];
compiler.indentLevel = 0;
const cls = compiler.options.className;
compiler.emit('// Auto-generated by HoloScript IOSCompiler — SharePlay Multi-User AR');
compiler.emit(
`// Source: composition "${escapeStringValue(composition.name as string, 'Swift')}"`
);
compiler.emit('// Requires iOS 15.4+, GroupActivities framework');
compiler.emit('// Do not edit manually — regenerate from .holo source');
compiler.emit('');
compiler.emit('import Foundation');
compiler.emit('import GroupActivities');
compiler.emit('import ARKit');
compiler.emit('import SceneKit');
compiler.emit('import RealityKit');
compiler.emit('import SwiftUI');
compiler.emit('import Combine');
compiler.emit('');
// ─── GroupActivity conforming type ──────────────────────────────
compiler.emit('// MARK: - GroupActivity Definition');
compiler.emit('');
compiler.emit('struct HoloGroupActivity: GroupActivity {');
compiler.indentLevel++;
compiler.emit(`let sceneName: String`);
compiler.emit('');
compiler.emit('var metadata: GroupActivityMetadata {');
compiler.indentLevel++;
compiler.emit('var meta = GroupActivityMetadata()');
compiler.emit(`meta.title = NSLocalizedString("HoloScript AR Session", comment: "")`);
compiler.emit('meta.type = .generic');
compiler.emit('return meta');
compiler.indentLevel--;
compiler.emit('}');
compiler.indentLevel--;
compiler.emit('}');
compiler.emit('');
// ─── Codable messages for scene sync ────────────────────────────
compiler.emit('// MARK: - Sync Messages (Codable, Loro CRDT-inspired diffs)');
compiler.emit('');
compiler.emit('struct SceneStateDiff: Codable {');
compiler.indentLevel++;
compiler.emit('let senderId: String');
compiler.emit('let timestamp: TimeInterval');
compiler.emit('let entityUpdates: [EntityUpdate]');
compiler.indentLevel--;
compiler.emit('}');
compiler.emit('');
compiler.emit('struct EntityUpdate: Codable {');
compiler.indentLevel++;
compiler.emit('let entityId: String');
compiler.emit('let ownerId: String?');
compiler.emit('let position: [Float]?');
compiler.emit('let rotation: [Float]?');