-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathARSessionNative.mm
1287 lines (1102 loc) · 46.9 KB
/
ARSessionNative.mm
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
// Unity Technologies Inc (c) 2017
// ARSessionNative.mm
// Main implementation of ARKit plugin native parts
#import <CoreVideo/CoreVideo.h>
#include "stdlib.h"
#include "UnityAppController.h"
#include "ARKitDefines.h"
// These don't all need to be static data, but no other better place for them at the moment.
static id <MTLTexture> s_CapturedImageTextureY = NULL;
static id <MTLTexture> s_CapturedImageTextureCbCr = NULL;
static UnityARMatrix4x4 s_CameraProjectionMatrix;
static float s_AmbientIntensity;
static int s_TrackingQuality;
static float s_ShaderScale;
static float unityCameraNearZ;
static float unityCameraFarZ;
static inline UnityARTrackingState GetUnityARTrackingStateFromARTrackingState(ARTrackingState trackingState)
{
switch (trackingState) {
case ARTrackingStateNormal:
return UnityARTrackingStateNormal;
case ARTrackingStateLimited:
return UnityARTrackingStateLimited;
case ARTrackingStateNotAvailable:
return UnityARTrackingStateNotAvailable;
default:
[NSException raise:@"UnrecognizedARTrackingState" format:@"Unrecognized ARTrackingState: %ld", (long)trackingState];
break;
}
}
static inline UnityARTrackingReason GetUnityARTrackingReasonFromARTrackingReason(ARTrackingStateReason trackingReason)
{
switch (trackingReason)
{
case ARTrackingStateReasonNone:
return UnityARTrackingStateReasonNone;
case ARTrackingStateReasonInitializing:
return UnityARTrackingStateReasonInitializing;
case ARTrackingStateReasonExcessiveMotion:
return UnityARTrackingStateReasonExcessiveMotion;
case ARTrackingStateReasonInsufficientFeatures:
return UnityARTrackingStateReasonInsufficientFeatures;
case ARTrackingStateReasonRelocalizing:
return UnityARTrackingStateReasonRelocalizing;
default:
[NSException raise:@"UnrecognizedARTrackingStateReason" format:@"Unrecognized ARTrackingStateReason: %ld", (long)trackingReason];
break;
}
}
API_AVAILABLE(ios(12.0))
static inline UnityARWorldMappingStatus GetUnityARWorldMappingStatusFromARWorldMappingStatus(ARWorldMappingStatus worldMappingStatus)
{
switch (worldMappingStatus) {
case ARWorldMappingStatusNotAvailable:
return UnityARWorldMappingStatusNotAvailable;
case ARWorldMappingStatusLimited:
return UnityARWorldMappingStatusLimited;
case ARWorldMappingStatusExtending:
return UnityARWorldMappingStatusExtending;
case ARWorldMappingStatusMapped:
return UnityARWorldMappingStatusMapped;
default:
[NSException raise:@"UnrecognizedARWorldMappingStatus" format:@"Unrecognized ARWorldMappingStatus: %ld", (long)worldMappingStatus];
break;
}
}
API_AVAILABLE(ios(12.0))
static inline AREnvironmentTexturing GetAREnvironmentTexturingFromUnityAREnvironmentTexturing(UnityAREnvironmentTexturing& unityEnvTexturing)
{
switch (unityEnvTexturing)
{
case UnityAREnvironmentTexturingNone:
return AREnvironmentTexturingNone;
case UnityAREnvironmentTexturingManual:
return AREnvironmentTexturingManual;
case UnityAREnvironmentTexturingAutomatic:
return AREnvironmentTexturingAutomatic;
}
}
inline void GetARSessionConfigurationFromARKitWorldTrackingSessionConfiguration(ARKitWorldTrackingSessionConfiguration& unityConfig, ARWorldTrackingConfiguration* appleConfig)
{
appleConfig.planeDetection = GetARPlaneDetectionFromUnityARPlaneDetection(unityConfig.planeDetection);
appleConfig.worldAlignment = GetARWorldAlignmentFromUnityARAlignment(unityConfig.alignment);
appleConfig.lightEstimationEnabled = (BOOL)unityConfig.enableLightEstimation;
if (@available(iOS 12.0, *))
{
appleConfig.maximumNumberOfTrackedImages = unityConfig.maximumNumberOfTrackedImages;
}
if (@available(iOS 11.3, *))
{
appleConfig.autoFocusEnabled = (BOOL) unityConfig.enableAutoFocus;
if (unityConfig.ptrVideoFormat != NULL)
{
appleConfig.videoFormat = (__bridge ARVideoFormat*) unityConfig.ptrVideoFormat;
}
}
if (UnityIsARKit_2_0_Supported())
{
if (@available(iOS 12.0, *)) {
appleConfig.initialWorldMap = (__bridge ARWorldMap*)unityConfig.ptrWorldMap;
appleConfig.environmentTexturing = GetAREnvironmentTexturingFromUnityAREnvironmentTexturing(unityConfig.environmentTexturing);
}
}
}
inline void GetARSessionConfigurationFromARKitSessionConfiguration(ARKitSessionConfiguration& unityConfig, ARConfiguration* appleConfig)
{
appleConfig.worldAlignment = GetARWorldAlignmentFromUnityARAlignment(unityConfig.alignment);
appleConfig.lightEstimationEnabled = (BOOL)unityConfig.enableLightEstimation;
}
#if ARKIT_USES_FACETRACKING
inline void GetARFaceConfigurationFromARKitFaceConfiguration(ARKitFaceTrackingConfiguration& unityConfig, ARConfiguration* appleConfig)
{
appleConfig.worldAlignment = GetARWorldAlignmentFromUnityARAlignment(unityConfig.alignment);
appleConfig.lightEstimationEnabled = (BOOL)unityConfig.enableLightEstimation;
if (@available(iOS 11.3, *))
{
if (unityConfig.ptrVideoFormat != NULL)
{
appleConfig.videoFormat = (__bridge ARVideoFormat*) unityConfig.ptrVideoFormat;
}
}
}
#endif
static inline void GetUnityARCameraDataFromCamera(UnityARCamera& unityARCamera, ARCamera* camera)
{
CGSize nativeSize = GetAppController().rootView.bounds.size;
matrix_float4x4 projectionMatrix = [camera projectionMatrixForOrientation:[[UIApplication sharedApplication] statusBarOrientation] viewportSize:nativeSize zNear:(CGFloat)unityCameraNearZ zFar:(CGFloat)unityCameraFarZ];
ARKitMatrixToUnityARMatrix4x4(projectionMatrix, &s_CameraProjectionMatrix);
ARKitMatrixToUnityARMatrix4x4(projectionMatrix, &unityARCamera.projectionMatrix);
unityARCamera.trackingState = GetUnityARTrackingStateFromARTrackingState(camera.trackingState);
unityARCamera.trackingReason = GetUnityARTrackingReasonFromARTrackingReason(camera.trackingStateReason);
}
API_AVAILABLE(ios(11.3))
inline void UnityARPlaneGeometryFromARPlaneGeometry(UnityARPlaneGeometry& planeGeometry, ARPlaneGeometry *arPlaneGeometry)
{
planeGeometry.vertexCount = arPlaneGeometry.vertexCount;
planeGeometry.triangleCount = arPlaneGeometry.triangleCount;
planeGeometry.textureCoordinateCount = arPlaneGeometry.textureCoordinateCount;
planeGeometry.boundaryVertexCount = arPlaneGeometry.boundaryVertexCount;
planeGeometry.vertices = (float *) arPlaneGeometry.vertices;
planeGeometry.triangleIndices = (int *) arPlaneGeometry.triangleIndices;
planeGeometry.textureCoordinates = (float *) arPlaneGeometry.textureCoordinates;
planeGeometry.boundaryVertices = (float *) arPlaneGeometry.boundaryVertices;
}
inline void UnityARAnchorDataFromARAnchorPtr(UnityARAnchorData& anchorData, ARPlaneAnchor* nativeAnchor)
{
anchorData.identifier = (void*)[nativeAnchor.identifier.UUIDString UTF8String];
ARKitMatrixToUnityARMatrix4x4(nativeAnchor.transform, &anchorData.transform);
anchorData.alignment = nativeAnchor.alignment;
anchorData.center.x = nativeAnchor.center.x;
anchorData.center.y = nativeAnchor.center.y;
anchorData.center.z = nativeAnchor.center.z;
anchorData.extent.x = nativeAnchor.extent.x;
anchorData.extent.y = nativeAnchor.extent.y;
anchorData.extent.z = nativeAnchor.extent.z;
if (@available(iOS 11.3, *))
{
UnityARPlaneGeometryFromARPlaneGeometry(anchorData.planeGeometry, nativeAnchor.geometry);
}
}
inline void UnityARMatrix4x4FromCGAffineTransform(UnityARMatrix4x4& outMatrix, CGAffineTransform displayTransform, BOOL isLandscape)
{
if (isLandscape)
{
outMatrix.column0.x = displayTransform.a;
outMatrix.column0.y = displayTransform.c;
outMatrix.column0.z = displayTransform.tx;
outMatrix.column1.x = displayTransform.b;
outMatrix.column1.y = -displayTransform.d;
outMatrix.column1.z = 1.0f - displayTransform.ty;
outMatrix.column2.z = 1.0f;
outMatrix.column3.w = 1.0f;
}
else
{
outMatrix.column0.x = displayTransform.a;
outMatrix.column0.y = -displayTransform.c;
outMatrix.column0.z = 1.0f - displayTransform.tx;
outMatrix.column1.x = displayTransform.b;
outMatrix.column1.y = displayTransform.d;
outMatrix.column1.z = displayTransform.ty;
outMatrix.column2.z = 1.0f;
outMatrix.column3.w = 1.0f;
}
}
inline void UnityARUserAnchorDataFromARAnchorPtr(UnityARUserAnchorData& anchorData, ARAnchor* nativeAnchor)
{
anchorData.identifier = (void*)[nativeAnchor.identifier.UUIDString UTF8String];
ARKitMatrixToUnityARMatrix4x4(nativeAnchor.transform, &anchorData.transform);
}
#if ARKIT_USES_FACETRACKING
inline void UnityARFaceGeometryFromARFaceGeometry(UnityARFaceGeometry& faceGeometry, ARFaceGeometry *arFaceGeometry)
{
faceGeometry.vertexCount = arFaceGeometry.vertexCount;
faceGeometry.triangleCount = arFaceGeometry.triangleCount;
faceGeometry.textureCoordinateCount = arFaceGeometry.textureCoordinateCount;
faceGeometry.vertices = (float *) arFaceGeometry.vertices;
faceGeometry.triangleIndices = (int *) arFaceGeometry.triangleIndices;
faceGeometry.textureCoordinates = (float *) arFaceGeometry.textureCoordinates;
}
inline void UnityARFaceAnchorDataFromARFaceAnchorPtr(UnityARFaceAnchorData& anchorData, ARFaceAnchor* nativeAnchor)
{
anchorData.identifier = (void*)[nativeAnchor.identifier.UUIDString UTF8String];
ARKitMatrixToUnityARMatrix4x4(nativeAnchor.transform, &anchorData.transform);
if (UnityIsARKit_2_0_Supported())
{
ARKitMatrixToUnityARMatrix4x4(nativeAnchor.leftEyeTransform, &anchorData.leftEyeTransform);
ARKitMatrixToUnityARMatrix4x4(nativeAnchor.rightEyeTransform, &anchorData.rightEyeTransform);
anchorData.lookAtPoint = UnityARVector3{nativeAnchor.lookAtPoint.x, nativeAnchor.lookAtPoint.y, nativeAnchor.lookAtPoint.z};
}
UnityARFaceGeometryFromARFaceGeometry(anchorData.faceGeometry, nativeAnchor.geometry);
anchorData.blendShapes = (__bridge void *) nativeAnchor.blendShapes;
anchorData.isTracked = (uint32_t) nativeAnchor.isTracked;
}
#endif
API_AVAILABLE(ios(11.3))
inline void UnityARImageAnchorDataFromARImageAnchorPtr(UnityARImageAnchorData& anchorData, ARImageAnchor* nativeAnchor)
{
anchorData.identifier = (void*)[nativeAnchor.identifier.UUIDString UTF8String];
ARKitMatrixToUnityARMatrix4x4(nativeAnchor.transform, &anchorData.transform);
anchorData.referenceImageName = (void*)[nativeAnchor.referenceImage.name UTF8String];
anchorData.referenceImageSize = nativeAnchor.referenceImage.physicalSize.width;
anchorData.isTracked = [nativeAnchor isTracked] ? 1 : 0;
}
inline void UnityLightDataFromARFrame(UnityLightData& lightData, ARFrame *arFrame)
{
if (arFrame.lightEstimate != NULL)
{
#if ARKIT_USES_FACETRACKING
if ([arFrame.lightEstimate class] == [ARDirectionalLightEstimate class])
{
lightData.arLightingType = DirectionalLightEstimate;
ARDirectionalLightEstimate *dirLightEst = (ARDirectionalLightEstimate *) arFrame.lightEstimate;
lightData.arDirectionalLightEstimate.sphericalHarmonicsCoefficients = (float *) dirLightEst.sphericalHarmonicsCoefficients.bytes;
//[dirLightEst.sphericalHarmonicsCoefficients getBytes:lightData.arDirectionalLightEstimate.sphericalHarmonicsCoefficients length:sizeof(float)*27 ];
UnityARVector4 dirAndIntensity;
dirAndIntensity.x = dirLightEst.primaryLightDirection.x;
dirAndIntensity.y = dirLightEst.primaryLightDirection.y;
dirAndIntensity.z = dirLightEst.primaryLightDirection.z;
dirAndIntensity.w = dirLightEst.primaryLightIntensity;
lightData.arDirectionalLightEstimate.primaryLightDirectionAndIntensity = dirAndIntensity;
}
else
#endif
{
lightData.arLightingType = LightEstimate;
lightData.arLightEstimate.ambientIntensity = arFrame.lightEstimate.ambientIntensity;
lightData.arLightEstimate.ambientColorTemperature = arFrame.lightEstimate.ambientColorTemperature;
}
}
}
@interface UnityARAnchorCallbackWrapper : NSObject <UnityARAnchorEventDispatcher>
{
@public
UNITY_AR_ANCHOR_CALLBACK _anchorAddedCallback;
UNITY_AR_ANCHOR_CALLBACK _anchorUpdatedCallback;
UNITY_AR_ANCHOR_CALLBACK _anchorRemovedCallback;
}
@end
@implementation UnityARAnchorCallbackWrapper
-(void)sendAnchorAddedEvent:(ARAnchor*)anchor
{
UnityARAnchorData data;
UnityARAnchorDataFromARAnchorPtr(data, (ARPlaneAnchor*)anchor);
_anchorAddedCallback(data);
}
-(void)sendAnchorRemovedEvent:(ARAnchor*)anchor
{
UnityARAnchorData data;
UnityARAnchorDataFromARAnchorPtr(data, (ARPlaneAnchor*)anchor);
_anchorRemovedCallback(data);
}
-(void)sendAnchorUpdatedEvent:(ARAnchor*)anchor
{
UnityARAnchorData data;
UnityARAnchorDataFromARAnchorPtr(data, (ARPlaneAnchor*)anchor);
_anchorUpdatedCallback(data);
}
@end
@interface UnityARUserAnchorCallbackWrapper : NSObject <UnityARAnchorEventDispatcher>
{
@public
UNITY_AR_USER_ANCHOR_CALLBACK _anchorAddedCallback;
UNITY_AR_USER_ANCHOR_CALLBACK _anchorUpdatedCallback;
UNITY_AR_USER_ANCHOR_CALLBACK _anchorRemovedCallback;
}
@end
@implementation UnityARUserAnchorCallbackWrapper
-(void)sendAnchorAddedEvent:(ARAnchor*)anchor
{
UnityARUserAnchorData data;
UnityARUserAnchorDataFromARAnchorPtr(data, anchor);
_anchorAddedCallback(data);
}
-(void)sendAnchorRemovedEvent:(ARAnchor*)anchor
{
UnityARUserAnchorData data;
UnityARUserAnchorDataFromARAnchorPtr(data, anchor);
_anchorRemovedCallback(data);
}
-(void)sendAnchorUpdatedEvent:(ARAnchor*)anchor
{
UnityARUserAnchorData data;
UnityARUserAnchorDataFromARAnchorPtr(data, anchor);
_anchorUpdatedCallback(data);
}
@end
@interface UnityARFaceAnchorCallbackWrapper : NSObject <UnityARAnchorEventDispatcher>
{
@public
UNITY_AR_FACE_ANCHOR_CALLBACK _anchorAddedCallback;
UNITY_AR_FACE_ANCHOR_CALLBACK _anchorUpdatedCallback;
UNITY_AR_FACE_ANCHOR_CALLBACK _anchorRemovedCallback;
}
@end
@implementation UnityARFaceAnchorCallbackWrapper
-(void)sendAnchorAddedEvent:(ARAnchor*)anchor
{
#if ARKIT_USES_FACETRACKING
UnityARFaceAnchorData data;
UnityARFaceAnchorDataFromARFaceAnchorPtr(data, (ARFaceAnchor*)anchor);
_anchorAddedCallback(data);
#endif
}
-(void)sendAnchorRemovedEvent:(ARAnchor*)anchor
{
#if ARKIT_USES_FACETRACKING
UnityARFaceAnchorData data;
UnityARFaceAnchorDataFromARFaceAnchorPtr(data, (ARFaceAnchor*)anchor);
_anchorRemovedCallback(data);
#endif
}
-(void)sendAnchorUpdatedEvent:(ARAnchor*)anchor
{
#if ARKIT_USES_FACETRACKING
UnityARFaceAnchorData data;
UnityARFaceAnchorDataFromARFaceAnchorPtr(data, (ARFaceAnchor*)anchor);
_anchorUpdatedCallback(data);
#endif
}
@end
@interface UnityARImageAnchorCallbackWrapper : NSObject <UnityARAnchorEventDispatcher>
{
@public
UNITY_AR_IMAGE_ANCHOR_CALLBACK _anchorAddedCallback;
UNITY_AR_IMAGE_ANCHOR_CALLBACK _anchorUpdatedCallback;
UNITY_AR_IMAGE_ANCHOR_CALLBACK _anchorRemovedCallback;
}
@end
@implementation UnityARImageAnchorCallbackWrapper
-(void)sendAnchorAddedEvent:(ARAnchor*)anchor
{
UnityARImageAnchorData data;
if (@available(iOS 11.3, *)) {
UnityARImageAnchorDataFromARImageAnchorPtr(data, (ARImageAnchor*)anchor);
}
_anchorAddedCallback(data);
}
-(void)sendAnchorRemovedEvent:(ARAnchor*)anchor
{
UnityARImageAnchorData data;
if (@available(iOS 11.3, *)) {
UnityARImageAnchorDataFromARImageAnchorPtr(data, (ARImageAnchor*)anchor);
}
_anchorRemovedCallback(data);
}
-(void)sendAnchorUpdatedEvent:(ARAnchor*)anchor
{
UnityARImageAnchorData data;
if (@available(iOS 11.3, *)) {
UnityARImageAnchorDataFromARImageAnchorPtr(data, (ARImageAnchor*)anchor);
}
_anchorUpdatedCallback(data);
}
@end
static UnityPixelBuffer s_UnityPixelBuffers;
@implementation UnityARSession
- (id)init
{
if (self = [super init])
{
_textureCache = NULL;
_classToCallbackMap = [[NSMutableDictionary alloc] init];
}
return self;
}
- (void)setupMetal
{
if (_textureCache != NULL)
{
return;
}
_device = MTLCreateSystemDefaultDevice();
CVMetalTextureCacheCreate(NULL, NULL, _device, NULL, &_textureCache);
}
- (void)teardownMetal
{
if (_textureCache != NULL) {
CFRelease(_textureCache);
_textureCache = NULL;
}
}
static CGAffineTransform s_CurAffineTransform;
- (void)session:(ARSession *)session didUpdateFrame:(ARFrame *)frame
{
s_AmbientIntensity = frame.lightEstimate.ambientIntensity;
s_TrackingQuality = (int)frame.camera.trackingState;
UIInterfaceOrientation orient = [[UIApplication sharedApplication] statusBarOrientation];
CGRect nativeBounds = [[UIScreen mainScreen] nativeBounds];
CGSize nativeSize = GetAppController().rootView.bounds.size;
UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
s_CurAffineTransform = CGAffineTransformInvert([frame displayTransformForOrientation:orientation viewportSize:nativeSize]);
UnityARCamera unityARCamera;
GetUnityARCameraDataFromCamera(unityARCamera, frame.camera);
if (_getPointCloudData && frame.rawFeaturePoints != nullptr)
{
unityARCamera.ptrPointCloud = (__bridge_retained void *) frame.rawFeaturePoints;
}
else
{
unityARCamera.ptrPointCloud = nullptr;
}
CVPixelBufferRef pixelBuffer = frame.capturedImage;
size_t imageWidth = CVPixelBufferGetWidth(pixelBuffer);
size_t imageHeight = CVPixelBufferGetHeight(pixelBuffer);
float imageAspect = (float)imageWidth / (float)imageHeight;
float screenAspect = nativeBounds.size.height / nativeBounds.size.width;
unityARCamera.videoParams.texCoordScale = screenAspect / imageAspect;
s_ShaderScale = screenAspect / imageAspect;
unityARCamera.getLightEstimation = _getLightEstimation;
if (_getLightEstimation)
{
UnityLightDataFromARFrame(unityARCamera.lightData, frame);
}
unityARCamera.videoParams.yWidth = (uint32_t)imageWidth;
unityARCamera.videoParams.yHeight = (uint32_t)imageHeight;
unityARCamera.videoParams.cvPixelBufferPtr = (void *) pixelBuffer;
UnityARMatrix4x4 displayTransform;
memset(&displayTransform, 0, sizeof(UnityARMatrix4x4));
UnityARMatrix4x4FromCGAffineTransform(displayTransform, s_CurAffineTransform, UIInterfaceOrientationIsLandscape(orientation));
unityARCamera.displayTransform = displayTransform;
if (UnityIsARKit_2_0_Supported())
{
if (@available(iOS 12.0, *))
{
unityARCamera.worldMappingStatus = GetUnityARWorldMappingStatusFromARWorldMappingStatus(frame.worldMappingStatus);
}
}
if (_frameCallback != NULL)
{
matrix_float4x4 rotatedMatrix = matrix_identity_float4x4;
unityARCamera.videoParams.screenOrientation = 3;
// rotation matrix
// [ cos -sin]
// [ sin cos]
switch (orient) {
case UIInterfaceOrientationPortrait:
rotatedMatrix.columns[0][0] = 0;
rotatedMatrix.columns[0][1] = 1;
rotatedMatrix.columns[1][0] = -1;
rotatedMatrix.columns[1][1] = 0;
unityARCamera.videoParams.screenOrientation = 1;
break;
case UIInterfaceOrientationLandscapeLeft:
rotatedMatrix.columns[0][0] = -1;
rotatedMatrix.columns[0][1] = 0;
rotatedMatrix.columns[1][0] = 0;
rotatedMatrix.columns[1][1] = -1;
unityARCamera.videoParams.screenOrientation = 4;
break;
case UIInterfaceOrientationPortraitUpsideDown:
rotatedMatrix.columns[0][0] = 0;
rotatedMatrix.columns[0][1] = -1;
rotatedMatrix.columns[1][0] = 1;
rotatedMatrix.columns[1][1] = 0;
unityARCamera.videoParams.screenOrientation = 2;
break;
default:
break;
}
matrix_float4x4 matrix = matrix_multiply(frame.camera.transform, rotatedMatrix);
ARKitMatrixToUnityARMatrix4x4(matrix, &unityARCamera.worldTransform);
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
_frameCallback(unityARCamera);
if (unityARCamera.ptrPointCloud != nullptr)
{
CFRelease(unityARCamera.ptrPointCloud);
}
});
}
if (CVPixelBufferGetPlaneCount(pixelBuffer) < 2 || CVPixelBufferGetPixelFormatType(pixelBuffer) != kCVPixelFormatType_420YpCbCr8BiPlanarFullRange) {
return;
}
if (s_UnityPixelBuffers.bEnable)
{
CVPixelBufferLockBaseAddress(pixelBuffer, kCVPixelBufferLock_ReadOnly);
if (s_UnityPixelBuffers.pYPixelBytes)
{
unsigned long numBytes = CVPixelBufferGetBytesPerRowOfPlane(pixelBuffer, 0) * CVPixelBufferGetHeightOfPlane(pixelBuffer,0);
void* baseAddress = CVPixelBufferGetBaseAddressOfPlane(pixelBuffer,0);
memcpy(s_UnityPixelBuffers.pYPixelBytes, baseAddress, numBytes);
}
if (s_UnityPixelBuffers.pUVPixelBytes)
{
unsigned long numBytes = CVPixelBufferGetBytesPerRowOfPlane(pixelBuffer, 1) * CVPixelBufferGetHeightOfPlane(pixelBuffer,1);
void* baseAddress = CVPixelBufferGetBaseAddressOfPlane(pixelBuffer,1);
memcpy(s_UnityPixelBuffers.pUVPixelBytes, baseAddress, numBytes);
}
CVPixelBufferUnlockBaseAddress(pixelBuffer, kCVPixelBufferLock_ReadOnly);
}
id<MTLTexture> textureY = nil;
id<MTLTexture> textureCbCr = nil;
// textureY
{
const size_t width = CVPixelBufferGetWidthOfPlane(pixelBuffer, 0);
const size_t height = CVPixelBufferGetHeightOfPlane(pixelBuffer, 0);
MTLPixelFormat pixelFormat = MTLPixelFormatR8Unorm;
CVMetalTextureRef texture = NULL;
CVReturn status = CVMetalTextureCacheCreateTextureFromImage(NULL, _textureCache, pixelBuffer, NULL, pixelFormat, width, height, 0, &texture);
if(status == kCVReturnSuccess)
{
textureY = CVMetalTextureGetTexture(texture);
}
if (texture != NULL)
{
CFRelease(texture);
}
}
// textureCbCr
{
const size_t width = CVPixelBufferGetWidthOfPlane(pixelBuffer, 1);
const size_t height = CVPixelBufferGetHeightOfPlane(pixelBuffer, 1);
MTLPixelFormat pixelFormat = MTLPixelFormatRG8Unorm;
CVMetalTextureRef texture = NULL;
CVReturn status = CVMetalTextureCacheCreateTextureFromImage(NULL, _textureCache, pixelBuffer, NULL, pixelFormat, width, height, 1, &texture);
if(status == kCVReturnSuccess)
{
textureCbCr = CVMetalTextureGetTexture(texture);
}
if (texture != NULL)
{
CFRelease(texture);
}
}
if (textureY != nil && textureCbCr != nil) {
dispatch_async(dispatch_get_main_queue(), ^{
// always assign the textures atomic
s_CapturedImageTextureY = textureY;
s_CapturedImageTextureCbCr = textureCbCr;
});
}
}
- (void)session:(ARSession *)session didFailWithError:(NSError *)error
{
if (_arSessionFailedCallback != NULL)
{
_arSessionFailedCallback(static_cast<const void*>([[error localizedDescription] UTF8String]));
}
}
- (void)session:(ARSession *)session didAddAnchors:(NSArray<ARAnchor*>*)anchors
{
[self sendAnchorAddedEventToUnity:anchors];
}
- (void)session:(ARSession *)session didUpdateAnchors:(NSArray<ARAnchor*>*)anchors
{
[self sendAnchorUpdatedEventToUnity:anchors];
}
- (void)session:(ARSession *)session didRemoveAnchors:(NSArray<ARAnchor*>*)anchors
{
[self sendAnchorRemovedEventToUnity:anchors];
}
- (void) sendAnchorAddedEventToUnity:(NSArray<ARAnchor*>*)anchors
{
for (ARAnchor* anchorPtr in anchors)
{
id<UnityARAnchorEventDispatcher> dispatcher = [_classToCallbackMap objectForKey:[anchorPtr class]];
[dispatcher sendAnchorAddedEvent:anchorPtr];
}
}
- (void)session:(ARSession *)session cameraDidChangeTrackingState:(ARCamera *)camera
{
if (_arSessionTrackingChanged != NULL)
{
UnityARCamera unityCamera;
GetUnityARCameraDataFromCamera(unityCamera, camera);
_arSessionTrackingChanged(unityCamera);
}
}
- (void)sessionWasInterrupted:(ARSession *)session
{
if (_arSessionInterrupted != NULL)
{
_arSessionInterrupted();
}
}
- (void)sessionInterruptionEnded:(ARSession *)session
{
if (_arSessionInterruptionEnded != NULL)
{
_arSessionInterruptionEnded();
}
}
- (BOOL)sessionShouldAttemptRelocalization:(ARSession *)session
{
if (_arSessionShouldRelocalize != NULL)
{
return _arSessionShouldRelocalize();
}
return NO;
}
- (void) sendAnchorRemovedEventToUnity:(NSArray<ARAnchor*>*)anchors
{
for (ARAnchor* anchorPtr in anchors)
{
id<UnityARAnchorEventDispatcher> dispatcher = [_classToCallbackMap objectForKey:[anchorPtr class]];
[dispatcher sendAnchorRemovedEvent:anchorPtr];
}
}
- (void) sendAnchorUpdatedEventToUnity:(NSArray<ARAnchor*>*)anchors
{
for (ARAnchor* anchorPtr in anchors)
{
id<UnityARAnchorEventDispatcher> dispatcher = [_classToCallbackMap objectForKey:[anchorPtr class]];
[dispatcher sendAnchorUpdatedEvent:anchorPtr];
}
}
@end
/// Create the native mirror to the C# ARSession object
extern "C" void* unity_CreateNativeARSession()
{
UnityARSession *nativeSession = [[UnityARSession alloc] init];
nativeSession->_session = [ARSession new];
nativeSession->_session.delegate = nativeSession;
unityCameraNearZ = .01;
unityCameraFarZ = 30;
s_UnityPixelBuffers.bEnable = false;
return (__bridge_retained void*)nativeSession;
}
extern "C" void session_SetSessionCallbacks(const void* session, UNITY_AR_FRAME_CALLBACK frameCallback,
UNITY_AR_SESSION_FAILED_CALLBACK sessionFailed,
UNITY_AR_SESSION_VOID_CALLBACK sessionInterrupted,
UNITY_AR_SESSION_VOID_CALLBACK sessionInterruptionEnded,
UNITY_AR_SESSION_RELOCALIZE_CALLBACK sessionShouldRelocalize,
UNITY_AR_SESSION_TRACKING_CHANGED trackingChanged,
UNITY_AR_SESSION_WORLD_MAP_COMPLETION_CALLBACK worldMapCompletionHandler,
UNITY_AR_SESSION_REF_OBJ_EXTRACT_COMPLETION_CALLBACK refObjExtractCompletionHandler)
{
UnityARSession* nativeSession = (__bridge UnityARSession*)session;
nativeSession->_frameCallback = frameCallback;
nativeSession->_arSessionFailedCallback = sessionFailed;
nativeSession->_arSessionInterrupted = sessionInterrupted;
nativeSession->_arSessionInterruptionEnded = sessionInterruptionEnded;
nativeSession->_arSessionShouldRelocalize = sessionShouldRelocalize;
nativeSession->_arSessionTrackingChanged = trackingChanged;
nativeSession->_arSessionWorldMapCompletionHandler = worldMapCompletionHandler;
nativeSession->_arSessionRefObjExtractCompletionHandler = refObjExtractCompletionHandler;
}
extern "C" void session_SetPlaneAnchorCallbacks(const void* session, UNITY_AR_ANCHOR_CALLBACK anchorAddedCallback,
UNITY_AR_ANCHOR_CALLBACK anchorUpdatedCallback,
UNITY_AR_ANCHOR_CALLBACK anchorRemovedCallback)
{
UnityARSession* nativeSession = (__bridge UnityARSession*)session;
UnityARAnchorCallbackWrapper* anchorCallbacks = [[UnityARAnchorCallbackWrapper alloc] init];
anchorCallbacks->_anchorAddedCallback = anchorAddedCallback;
anchorCallbacks->_anchorUpdatedCallback = anchorUpdatedCallback;
anchorCallbacks->_anchorRemovedCallback = anchorRemovedCallback;
[nativeSession->_classToCallbackMap setObject:anchorCallbacks forKey:[ARPlaneAnchor class]];
}
extern "C" void session_SetUserAnchorCallbacks(const void* session, UNITY_AR_USER_ANCHOR_CALLBACK userAnchorAddedCallback,
UNITY_AR_USER_ANCHOR_CALLBACK userAnchorUpdatedCallback,
UNITY_AR_USER_ANCHOR_CALLBACK userAnchorRemovedCallback)
{
UnityARSession* nativeSession = (__bridge UnityARSession*)session;
UnityARUserAnchorCallbackWrapper* userAnchorCallbacks = [[UnityARUserAnchorCallbackWrapper alloc] init];
userAnchorCallbacks->_anchorAddedCallback = userAnchorAddedCallback;
userAnchorCallbacks->_anchorUpdatedCallback = userAnchorUpdatedCallback;
userAnchorCallbacks->_anchorRemovedCallback = userAnchorRemovedCallback;
[nativeSession->_classToCallbackMap setObject:userAnchorCallbacks forKey:[ARAnchor class]];
}
extern "C" void session_SetFaceAnchorCallbacks(const void* session, UNITY_AR_FACE_ANCHOR_CALLBACK faceAnchorAddedCallback,
UNITY_AR_FACE_ANCHOR_CALLBACK faceAnchorUpdatedCallback,
UNITY_AR_FACE_ANCHOR_CALLBACK faceAnchorRemovedCallback)
{
#if ARKIT_USES_FACETRACKING
UnityARSession* nativeSession = (__bridge UnityARSession*)session;
UnityARFaceAnchorCallbackWrapper* faceAnchorCallbacks = [[UnityARFaceAnchorCallbackWrapper alloc] init];
faceAnchorCallbacks->_anchorAddedCallback = faceAnchorAddedCallback;
faceAnchorCallbacks->_anchorUpdatedCallback = faceAnchorUpdatedCallback;
faceAnchorCallbacks->_anchorRemovedCallback = faceAnchorRemovedCallback;
[nativeSession->_classToCallbackMap setObject:faceAnchorCallbacks forKey:[ARFaceAnchor class]];
#endif
}
extern "C" void session_SetImageAnchorCallbacks(const void* session, UNITY_AR_IMAGE_ANCHOR_CALLBACK imageAnchorAddedCallback,
UNITY_AR_IMAGE_ANCHOR_CALLBACK imageAnchorUpdatedCallback,
UNITY_AR_IMAGE_ANCHOR_CALLBACK imageAnchorRemovedCallback)
{
if (@available(iOS 11.3, *))
{
UnityARSession* nativeSession = (__bridge UnityARSession*)session;
UnityARImageAnchorCallbackWrapper* imageAnchorCallbacks = [[UnityARImageAnchorCallbackWrapper alloc] init];
imageAnchorCallbacks->_anchorAddedCallback = imageAnchorAddedCallback;
imageAnchorCallbacks->_anchorUpdatedCallback = imageAnchorUpdatedCallback;
imageAnchorCallbacks->_anchorRemovedCallback = imageAnchorRemovedCallback;
[nativeSession->_classToCallbackMap setObject:imageAnchorCallbacks forKey:[ARImageAnchor class]];
}
}
extern "C" void* session_GetARKitSessionPtr(const void* session)
{
UnityARSession* nativeSession = (__bridge UnityARSession*)session;
return (__bridge void*)nativeSession->_session;
}
extern "C" void* session_GetARKitFramePtr(const void* session)
{
UnityARSession* nativeSession = (__bridge UnityARSession*)session;
return (__bridge void*)nativeSession->_session.currentFrame;
}
extern "C" void StartWorldTrackingSessionWithOptions(void* nativeSession, ARKitWorldTrackingSessionConfiguration unityConfig, UnityARSessionRunOptions runOptions)
{
UnityARSession* session = (__bridge UnityARSession*)nativeSession;
ARWorldTrackingConfiguration* config = [ARWorldTrackingConfiguration new];
ARSessionRunOptions runOpts = GetARSessionRunOptionsFromUnityARSessionRunOptions(runOptions);
GetARSessionConfigurationFromARKitWorldTrackingSessionConfiguration(unityConfig, config);
session->_getPointCloudData = (BOOL) unityConfig.getPointCloudData;
session->_getLightEstimation = (BOOL) unityConfig.enableLightEstimation;
if(UnityIsARKit_1_5_Supported() && unityConfig.referenceImagesResourceGroup != NULL && strlen(unityConfig.referenceImagesResourceGroup) > 0)
{
NSString *strResourceGroup = [[NSString alloc] initWithUTF8String:unityConfig.referenceImagesResourceGroup];
if (@available(iOS 11.3, *)) {
NSSet<ARReferenceImage *> *referenceImages = [ARReferenceImage referenceImagesInGroupNamed:strResourceGroup bundle:nil];
config.detectionImages = referenceImages;
}
}
if(UnityIsARKit_2_0_Supported())
{
if (@available(iOS 12.0, *))
{
NSMutableSet<ARReferenceObject *> *referenceObjects = nullptr;
if (unityConfig.referenceObjectsResourceGroup != NULL && strlen(unityConfig.referenceObjectsResourceGroup) > 0)
{
NSString *strResourceGroup = [[NSString alloc] initWithUTF8String:unityConfig.referenceObjectsResourceGroup];
[referenceObjects setByAddingObjectsFromSet:[ARReferenceObject referenceObjectsInGroupNamed:strResourceGroup bundle:nil]];
}
if (unityConfig.ptrDynamicReferenceObjects != nullptr)
{
NSSet<ARReferenceObject *> *dynamicReferenceObjects = (__bridge NSSet<ARReferenceObject *> *)unityConfig.ptrDynamicReferenceObjects;
if (referenceObjects != nullptr)
{
[referenceObjects setByAddingObjectsFromSet:dynamicReferenceObjects];
}
else
{
referenceObjects = dynamicReferenceObjects;
}
}
config.detectionObjects = referenceObjects;
}
}
if (runOptions == UnityARSessionRunOptionsNone)
[session->_session runWithConfiguration:config];
else
[session->_session runWithConfiguration:config options:runOpts];
[session setupMetal];
}
extern "C" void StartWorldTrackingSession(void* nativeSession, ARKitWorldTrackingSessionConfiguration unityConfig)
{
StartWorldTrackingSessionWithOptions(nativeSession, unityConfig, UnityARSessionRunOptionsNone);
}
extern "C" void StartSessionWithOptions(void* nativeSession, ARKitSessionConfiguration unityConfig, UnityARSessionRunOptions runOptions)
{
UnityARSession* session = (__bridge UnityARSession*)nativeSession;
ARConfiguration* config = [AROrientationTrackingConfiguration new];
ARSessionRunOptions runOpts = GetARSessionRunOptionsFromUnityARSessionRunOptions(runOptions);
GetARSessionConfigurationFromARKitSessionConfiguration(unityConfig, config);
session->_getPointCloudData = (BOOL) unityConfig.getPointCloudData;
session->_getLightEstimation = (BOOL) unityConfig.enableLightEstimation;
[session->_session runWithConfiguration:config options:runOpts ];
[session setupMetal];
}
extern "C" void StartSession(void* nativeSession, ARKitSessionConfiguration unityConfig)
{
UnityARSession* session = (__bridge UnityARSession*)nativeSession;
ARConfiguration* config = [AROrientationTrackingConfiguration new];
GetARSessionConfigurationFromARKitSessionConfiguration(unityConfig, config);
session->_getPointCloudData = (BOOL) unityConfig.getPointCloudData;
session->_getLightEstimation = (BOOL) unityConfig.enableLightEstimation;
[session->_session runWithConfiguration:config];
[session setupMetal];
}
extern "C" void StartFaceTrackingSessionWithOptions(void* nativeSession, ARKitFaceTrackingConfiguration unityConfig, UnityARSessionRunOptions runOptions)
{
#if ARKIT_USES_FACETRACKING
UnityARSession* session = (__bridge UnityARSession*)nativeSession;
ARConfiguration* config = [ARFaceTrackingConfiguration new];
ARSessionRunOptions runOpts = GetARSessionRunOptionsFromUnityARSessionRunOptions(runOptions);
GetARFaceConfigurationFromARKitFaceConfiguration(unityConfig, config);
session->_getLightEstimation = (BOOL) unityConfig.enableLightEstimation;
[session->_session runWithConfiguration:config options:runOpts ];
[session setupMetal];
#else
[NSException raise:@"UnityARKitPluginFaceTrackingNotEnabled" format:@"UnityARKitPlugin: Trying to start FaceTracking session without enabling it in settings."];
#endif
}
extern "C" void StartFaceTrackingSession(void* nativeSession, ARKitFaceTrackingConfiguration unityConfig)
{
StartFaceTrackingSessionWithOptions(nativeSession, unityConfig, UnityARSessionRunOptionsNone);
}
extern "C" void PauseSession(void* nativeSession)
{
UnityARSession* session = (__bridge UnityARSession*)nativeSession;
[session->_session pause];
[session teardownMetal];
}
extern "C" void StopSession(void* nativeSession)
{
UnityARSession* session = (__bridge UnityARSession*)nativeSession;
[session teardownMetal];
}
extern "C" UnityARUserAnchorData SessionAddUserAnchor(void* nativeSession, UnityARUserAnchorData anchorData)
{
// create a native ARAnchor and add it to the session
// then return the data back to the user that they will
// need in case they want to remove it
UnityARSession* session = (__bridge UnityARSession*)nativeSession;
matrix_float4x4 anchor_transform = matrix_identity_float4x4;
UnityARMatrix4x4ToARKitMatrix(anchorData.transform, &anchor_transform);
ARAnchor *newAnchor = [[ARAnchor alloc] initWithTransform:anchor_transform];
[session->_session addAnchor:newAnchor];
UnityARUserAnchorData returnAnchorData;
UnityARUserAnchorDataFromARAnchorPtr(returnAnchorData, newAnchor);
return returnAnchorData;
}
extern "C" void SessionRemoveUserAnchor(void* nativeSession, const char * anchorIdentifier)
{
// go through anchors and find the right one
// then remove it from the session
UnityARSession* session = (__bridge UnityARSession*)nativeSession;
for (ARAnchor* a in session->_session.currentFrame.anchors)
{
if ([[a.identifier UUIDString] isEqualToString:[NSString stringWithUTF8String:anchorIdentifier]])
{
[session->_session removeAnchor:a];
return;
}
}
}
extern "C" void SessionSetWorldOrigin(void* nativeSession, UnityARMatrix4x4 worldMatrix)
{
if (@available(iOS 11.3, *))
{
UnityARSession* session = (__bridge UnityARSession*)nativeSession;
matrix_float4x4 arWorldMatrix;
UnityARMatrix4x4ToARKitMatrix(worldMatrix, &arWorldMatrix);
[session->_session setWorldOrigin:arWorldMatrix];
}
}