-
Notifications
You must be signed in to change notification settings - Fork 47
/
ColoDiscoMan.cs
1501 lines (1162 loc) · 48 KB
/
ColoDiscoMan.cs
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
// Copyright (c) Meta Platforms, Inc. and affiliates.
// This code is licensed under the MIT license (see LICENSE for details).
using Oculus.Platform;
using User = Oculus.Platform.Models.User;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using TMPro;
using UnityEngine;
using UnityEngine.Assertions;
using UnityEngine.SceneManagement;
using UnityEngine.Serialization;
using UnityEngine.UI;
using Sampleton = SampleController; // only transitional
public class ColoDiscoMan : MonoBehaviour // AKA ColocationSessionDiscoveryAndGroupSharingManager
{
//
// public interface
#region Static section
public static ulong CurrentUserID => s_Instance && s_Instance.m_My != null ? s_Instance.m_My.ID : 0;
public static Transform TrackingSpaceRoot
{
get
{
if (!s_Instance)
return null;
if (s_Instance.m_TrackingSpaceRoot)
return s_Instance.m_TrackingSpaceRoot;
if (!OVRManager.instance)
return null;
s_Instance.m_TrackingSpaceRoot = OVRManager.instance.GetComponentInChildren<OVRCameraRig>().trackingSpace;
return s_Instance.m_TrackingSpaceRoot;
}
}
public static void NotifyAnchorLocalized(ColoDiscoAnchor anchor)
{
Assert.IsNotNull(s_Instance, "s_Instance should be initialized!");
var uuid = anchor.Uuid;
if (s_Instance.m_KnownAnchors.TryGetValue(uuid, out var existing) && existing)
{
Sampleton.Log($"{nameof(NotifyAnchorLocalized)}: SKIPPING known anchor {uuid.Brief()}");
return;
}
s_Instance.m_KnownAnchors[uuid] = anchor;
Sampleton.Log($"{nameof(NotifyAnchorLocalized)}: {uuid.Brief()}");
s_Instance.NotifyAnchorLocalizedAsync(anchor);
}
public static void NotifyAnchorErased(Guid uuid)
{
Assert.IsNotNull(s_Instance, "s_Instance should be initialized!");
s_Instance.m_KnownAnchors.Remove(uuid);
foreach (var group in s_Instance.m_KnownGroups.Values)
{
_ = group.SharedAnchors.Remove(uuid);
}
}
public static void NotifyAnchorAlignment(ColoDiscoAnchor anchor, ColoDiscoAnchor previous)
{
Assert.IsNotNull(s_Instance, "s_Instance should be initialized!");
_ = previous;
s_Instance.AlignPlayer(anchor.transform);
}
public static void ShareToActiveGroup(ColoDiscoAnchor anchor)
{
Assert.IsNotNull(s_Instance, "s_Instance should be initialized!");
Sampleton.Log($"{nameof(ShareToActiveGroup)}{(s_Instance.ForceShareAnchors ? "(force=true)" : "")}:\n+ anchor: {anchor.Uuid}");
s_Instance.ShareAnchorsToActiveGroupsAsync(new[] { anchor });
}
public static IEnumerable<Guid> GetGroupsFor(Guid anchorId)
{
Assert.IsNotNull(s_Instance, "s_Instance should be initialized!");
return from g in s_Instance.m_KnownGroups.Values
where g.SharedAnchors.Contains(anchorId)
select g.Uuid;
}
public static IEnumerable<string> GetDisplayNamesFor(IEnumerable<Guid> groupIds)
{
Assert.IsNotNull(s_Instance, "s_Instance should be initialized!");
foreach (var groupId in groupIds)
{
if (s_Instance.m_KnownGroups.TryGetValue(groupId, out var group))
{
yield return FixupDisplayName(group.Metadata.DisplayName, groupId);
}
else
{
yield return "(invalid group)";
}
}
}
#endregion Static section
#region UnityEvent (UI) listeners
// The following are attached to hidden toggles, which you can enable in the scene hierarchy.
public bool ShareAutomatically { get; set; } = false;
public bool ApplyToAllGroups { get; set; } = false;
public bool LoadOnGroupSwitch { get; set; } = true;
public bool AdvertiseNullData { get; set; } = false;
public bool ForceShareAnchors { get; set; } = false;
public bool OnlyRememberedAnchors { get; set; } = false;
/// <summary>
/// Explicitly localizes loaded anchors before they are bound to GameObjects, so that initial poses can be
/// calculated before they are bound, thus avoiding the quirk that auto-localized anchors typically spend one or
/// more frames at the world origin before snapping to their proper (localized) pose
/// (AKA, the "teleporting anchors" glitch).
/// </summary>
/// <remarks>
/// https://developers.meta.com/horizon/documentation/unity/unity-spatial-anchors-persist-content#localize-each-anchor
/// </remarks>
public bool LocalizeBeforeBinding { get; set; } = true;
public void ToggleAdvertising()
{
if (m_IsAdvertising)
StopAdvertising();
else
StartAdvertising();
}
public void StartAdvertising(bool spammable = false)
{
Sampleton.Log($"{nameof(StartAdvertising)}:");
var newGroup = new Group
{
IsMine = true,
};
if (AdvertiseNullData || m_My is null)
newGroup.Metadata = new CustomAdvertData(null, 0, anchors: null);
else
newGroup.Metadata = new CustomAdvertData(m_My.OculusID, m_My.ID, anchors: null);
var alignmentAnchor = ColoDiscoAnchor.Alignment;
if (alignmentAnchor)
{
newGroup.Metadata.Anchors.Add(alignmentAnchor.Uuid);
var worldToLocal = alignmentAnchor.transform.ToOVRPose().Inverse();
foreach (var spawn in m_Spawned)
{
var ovrPose = worldToLocal * spawn.transform.ToOVRPose();
newGroup.Metadata.Poses.Add(new Pose(ovrPose.position, ovrPose.orientation));
}
}
byte[] bytes = null;
if (AdvertiseNullData)
Sampleton.Log("+ Advertising NULL for custom data");
else if (newGroup.Metadata.TryWrite(out bytes))
Sampleton.Log($"+ Advertising {bytes.Length} bytes of custom data~");
else
Sampleton.Log("- Advertising 0 bytes (I hope this was expected?)", LogType.Warning);
if (!spammable)
m_AdvertBtn.interactable = false;
StartAdvertisingAsync(bytes, newGroup);
}
public void StopAdvertising(bool spammable = false)
{
Sampleton.Log($"{nameof(StopAdvertising)}:");
if (!spammable)
m_AdvertBtn.interactable = false;
StopAdvertisingAsync();
}
public void ToggleDiscovering()
{
if (m_IsDiscovering)
StopDiscovering();
else
StartDiscovering();
}
public void StartDiscovering(bool spammable = false)
{
Sampleton.Log($"{nameof(StartDiscovering)}:");
if (!spammable)
m_DiscoBtn.interactable = false;
StartDiscoveringAsync();
}
public void StopDiscovering(bool spammable = false)
{
Sampleton.Log($"{nameof(StopDiscovering)}:");
if (!spammable)
m_DiscoBtn.interactable = false;
StopDiscoveringAsync();
}
public void ShareKnownAnchors()
{
if (m_KnownAnchors.Count == 0 && !ForceShareAnchors)
{
Sampleton.Log($"{nameof(ShareKnownAnchors)}: SKIPPING: No known anchors localized.");
return;
}
Sampleton.Log($"{nameof(ShareKnownAnchors)}{(ForceShareAnchors ? "(force=true)" : "")}: {m_KnownAnchors.Count} known anchors:");
ShareAnchorsToActiveGroupsAsync(m_KnownAnchors.Values);
}
public void LoadGroupAnchors()
{
if (ApplyToAllGroups)
{
var groupIds = m_KnownGroups.Keys;
if (groupIds.Count == 0)
{
Sampleton.Log($"{nameof(LoadGroupAnchors)}: SKIPPING: No known groups exist yet.\n- Create one by advertising, or find one by discovering.");
return;
}
Sampleton.Log($"{nameof(LoadGroupAnchors)}: Requesting anchors from {groupIds.Count} group(s)..");
foreach (var groupId in groupIds)
{
LoadGroupAnchorsAsync(groupId);
}
return;
}
if (m_ActiveGroup == Guid.Empty)
{
Sampleton.Log($"{nameof(LoadGroupAnchors)}: SKIPPING: No active group.\n- Create one by Advertising, or find one by Discovering a session.");
return;
}
Sampleton.Log($"{nameof(LoadGroupAnchors)}: Requesting anchors from {m_ActiveGroup.Brief()}");
LoadGroupAnchorsAsync(m_ActiveGroup);
}
public void UseHardcodedGroup()
{
var guid = new Guid(m_HardcodedGroupUUID);
if (!m_KnownGroups.ContainsKey(guid))
{
m_KnownGroups[guid] = new Group
{
Uuid = guid,
Metadata = new CustomAdvertData(m_HardcodedGroupName, m_My?.ID ?? 0, m_KnownAnchors.Keys)
};
UIAddDiscoveryItem(m_HardcodedGroupName, guid, isSelected: true);
}
SetActiveGroup(guid);
if (!LoadOnGroupSwitch)
return;
Sampleton.Log("[x] Load Anchors On Select:");
LoadGroupAnchorsAsync(guid);
}
public void LoadRememberedAnchors()
{
if (!ColoDiscoAnchor.HasRememberedAnchor)
{
Sampleton.LogError($"{nameof(LoadRememberedAnchors)}: No remembered anchors.");
return;
}
Sampleton.Log($"{nameof(LoadRememberedAnchors)}: Requesting the last remembered anchor..");
LoadAnchorsById(new[] { ColoDiscoAnchor.RememberedAnchorId });
}
// more boilerplate-y button listeners:
public void LoadScene(int idx)
{
Debug.Log($"{nameof(LoadScene)}({idx}) ...", this);
SceneManager.LoadScene(idx);
}
public void AdvanceLogPage(int n)
{
if (n == 0)
return;
var log = SampleController.Instance.logText;
if (!log)
return;
int nPages = log.textInfo.pageCount;
int page = Mathf.Clamp(log.pageToDisplay + n, 1, nPages);
if (page == log.pageToDisplay)
return;
log.pageToDisplay = page;
var pageText = SampleController.Instance.pageText;
if (pageText)
pageText.text = $"{log.pageToDisplay}/{nPages}";
}
public void ToggleGreenTint(Image icon)
{
icon.color = (icon.color == Color.green) ? Color.white : Color.green;
}
#endregion UnityEvent (UI) listeners
//
// private impl.
sealed class Group // aka Session
{
public Guid Uuid;
public bool IsMine;
public CustomAdvertData Metadata;
public Button ListButton;
public readonly HashSet<Guid> SharedAnchors = new();
}
#region Fields
[Header("[Variation Control]")]
[SerializeField]
[Tooltip("This scene doesn't technically require Oculus usernames / IDs, but it can make use of them to help identify peers when testing.")]
bool m_RequireLoggedInUser = false;
[SerializeField, Delayed]
[Tooltip("Only used if you find \"Button: Use Hardcoded Group\" in the hierarchy and activate it.\n\nThe special value \"build\" automatically uses the current Application.buildGuid.")]
string m_HardcodedGroupUUID = "build";
[SerializeField, Delayed]
[Tooltip("Only used if you find \"Button: Use Hardcoded Group\" in the hierarchy and activate it.")]
string m_HardcodedGroupName = "HARDCODED";
[Header("[Optional] - certain behaviors off if missing:")]
[SerializeField]
GameObject m_SpawnWithA;
[Header("[Manual] - you MAY need to fixup these refs:")]
[SerializeField, FormerlySerializedAs("m_PlayerFace")]
Transform m_TrackingSpaceRoot;
[SerializeField]
Transform m_RigAnchor;
[Header("[ReadOnly] - no need to touch these manually:")]
[SerializeField]
Button m_AdvertBtn;
[SerializeField]
Button m_DiscoBtn;
[SerializeField]
Button m_ShareAllBtn;
[SerializeField]
TMP_Text m_AdvertBtnLabel, m_DiscoBtnLabel;
[SerializeField]
TMP_Text m_StatusLabel;
[SerializeField]
TMP_Text m_GroupListLabel;
[SerializeField]
Image m_AdvertBtnIcon, m_DiscoBtnIcon;
[SerializeField]
GameObject m_GroupListItem;
[SerializeField]
[Tooltip("Depends on the value of 'Require Logged In User'.")]
Selectable[] m_DisabledWithoutValidUser = Array.Empty<Selectable>();
static ColoDiscoMan s_Instance;
bool m_AutoShare;
bool m_IsAdvertising, m_IsDiscovering;
User m_My;
Guid m_ActiveGroup;
readonly Dictionary<Guid, Group> m_KnownGroups = new();
readonly Dictionary<Guid, ColoDiscoAnchor> m_KnownAnchors = new();
readonly List<GameObject> m_Spawned = new();
readonly List<(int, string)> m_StatusLines = new(); // TODO status text should be encapsulated outta here
#endregion Fields
#region Unity messages
void OnValidate()
{
if (string.IsNullOrEmpty(m_HardcodedGroupUUID))
{
m_HardcodedGroupUUID = Guid.NewGuid().ToString("N");
}
else if (m_HardcodedGroupUUID.Equals("build", StringComparison.InvariantCultureIgnoreCase))
{
// uses build guid at runtime so that clients sharing the same APK can use a hardcoded group
}
else if (!Guid.TryParse(m_HardcodedGroupUUID, out _))
{
Debug.LogError($"\"{m_HardcodedGroupUUID}\" is not parseable as a Guid!", this);
}
if (!m_TrackingSpaceRoot)
{
var find = FindObjectOfType<OVRCameraRig>();
if (find)
m_TrackingSpaceRoot = find.trackingSpace;
}
if (!m_RigAnchor)
{
var find = GameObject.Find("Ref Point");
if (find)
m_RigAnchor = find.transform;
}
if (gameObject.scene.IsValid() && !m_RigAnchor) // avoids erroring in prefab view
{
Debug.LogError($"\"{name}\" seems to be improperly set-up.", this);
}
var child = transform.FindChildRecursive("Text: Status Text");
if (!child || !child.TryGetComponent(out m_StatusLabel))
{
Debug.LogError($"\"{name}\" seems to be improperly set-up.", this);
}
child = transform.FindChildRecursive("Text: Group List");
if (!child || !child.TryGetComponent(out m_GroupListLabel))
{
Debug.LogError($"\"{name}\" seems to be improperly set-up.", this);
}
var commandsRoot = transform.FindChildRecursive("Commands");
m_DisabledWithoutValidUser = commandsRoot.GetComponentsInChildren<Selectable>(includeInactive: true);
foreach (var uiThing in m_DisabledWithoutValidUser)
{
switch (uiThing.name)
{
case "Button: Advertise":
m_AdvertBtn = uiThing as Button;
m_AdvertBtnLabel = uiThing.GetComponentInChildren<TMP_Text>(includeInactive: true);
break;
case "Button: Discover":
m_DiscoBtn = uiThing as Button;
m_DiscoBtnLabel = uiThing.GetComponentInChildren<TMP_Text>(includeInactive: true);
break;
case "Button: Group List Item":
m_GroupListItem = uiThing.gameObject;
break;
case "Button: Share All":
m_ShareAllBtn = uiThing as Button;
break;
}
}
if (!m_AdvertBtn || !m_AdvertBtnLabel || !m_DiscoBtn || !m_DiscoBtnLabel || !m_GroupListItem)
{
Debug.LogError($"\"{name}\" seems to be improperly set-up.", this);
return;
}
m_AdvertBtnIcon = m_AdvertBtnLabel.transform.parent.Find("Icon").GetComponent<Image>();
m_DiscoBtnIcon = m_DiscoBtnLabel.transform.parent.Find("Icon").GetComponent<Image>();
}
void Awake()
{
Assert.IsNull(s_Instance, "s_Instance already exists");
s_Instance = this;
if (m_HardcodedGroupUUID?.Equals("build", StringComparison.InvariantCultureIgnoreCase) == true)
{
m_HardcodedGroupUUID = UnityEngine.Application.buildGUID;
}
UISetStatusText("Active Group UUID:\n(none)", order: 0);
foreach (var uiThing in m_DisabledWithoutValidUser)
{
uiThing.interactable = !m_RequireLoggedInUser || m_My != null;
}
if (m_GroupListItem && m_GroupListItem.activeSelf)
{
m_GroupListItem.SetActive(false);
m_GroupListItem.GetComponentInParent<RectTransform>().sizeDelta = new(-17f, 32f); // screwy
}
if (!m_RigAnchor)
return;
transform.SetParent(m_RigAnchor, worldPositionStays: false);
}
void OnDestroy()
{
s_Instance = null;
if (m_IsAdvertising)
{
// KEY API CALL: static OVRColocationSession.StopAdvertisementAsync()
_ = OVRColocationSession.StopAdvertisementAsync();
}
if (m_IsDiscovering)
{
// KEY API CALL: static OVRColocationSession.StopDiscoveryAsync()
_ = OVRColocationSession.StopDiscoveryAsync();
}
// KEY API CALL: static event OVRColocationSession.ColocationSessionDiscovered
OVRColocationSession.ColocationSessionDiscovered -= ReceivedSessionData;
}
IEnumerator Start()
{
Sampleton.Log($"Scene loaded: {gameObject.scene.name}\n({gameObject.scene.path})");
Sampleton.Log($"OVRPlugin.version: {OVRPlugin.version}");
// API call: static Oculus.Platform.Core.Initialize()
Core.Initialize();
string log = "Attempting to get logged in user info, " +
(m_RequireLoggedInUser ? "which is REQUIRED"
: "though it is NOT REQUIRED") +
" by this version of the sample...";
Sampleton.Log(log);
#if UNITY_EDITOR || UNITY_STANDALONE
Sampleton.Log(" <color=\"grey\">* this may take upwards of several minutes when using PC Link...</color>");
#endif
// API call: static Oculus.Platform.Users.GetLoggedInUser()
Users.GetLoggedInUser().OnComplete(ReceivedLoggedInUser);
// KEY API CALL: static event OVRColocationSession.ColocationSessionDiscovered
OVRColocationSession.ColocationSessionDiscovered += ReceivedSessionData;
yield return null;
var buildInfoRequest = Resources.LoadAsync<TextAsset>("buildInfo");
yield return buildInfoRequest;
const int kOrder = 10;
if (buildInfoRequest.asset is not TextAsset textAsset || textAsset.dataSize < 10)
{
UISetStatusText("<build unknown>", kOrder);
}
else
{
string text = textAsset.text;
int hash = text.IndexOf('#');
if (hash > 0)
text = $"rev {text.Substring(hash)}\nbuilt {text.Remove(hash - 1)}";
UISetStatusText(text, kOrder);
}
}
void Update()
{
PoseOrigin.UseLocalCoords = OVRInput.Get(OVRInput.RawButton.LShoulder);
if (OVRInput.IsControllerConnected(OVRInput.Controller.RTouch))
{
// the pinch gesture gets quietly mapped to (A), which makes hands annoying to use with this hidden functionality.
// (hence the IsControllerConnected check)
SpawnWithButton(OVRInput.RawButton.A, m_SpawnWithA);
}
}
void SpawnWithButton(OVRInput.RawButton btn, GameObject prefab)
{
if (!prefab || !ColoDiscoAnchor.Alignment || !OVRInput.GetUp(btn))
return;
if (!OVRManager.instance.TryGetComponent(out OVRCameraRig rig))
{
Sampleton.LogError($"{nameof(SpawnWithButton)}: No OVRCameraRig attached to OVRManager!");
return;
}
var rightHand = rig.rightControllerAnchor;
var spawn = Instantiate(
original: prefab,
position: rightHand.position,
rotation: rightHand.rotation
);
if (spawn.TryGetComponent(out PoseOrigin poo))
{
poo.UpdateCoordsNow();
}
Sampleton.Log($"{nameof(SpawnWithButton)}: created \"{spawn.name}\"");
m_Spawned.Add(spawn);
}
#endregion Unity messages
#region Alignment
// TODO refactor alignment-related code (from all scenes) into its own sample scene
// (these other scenes will do automatic alignment if necessary, to remain focused on the subject matter)
void AlignPlayer(Transform anchor)
{
var player = TrackingSpaceRoot;
if (!player)
{
Sampleton.LogError($"{nameof(AlignPlayer)}: No OVRCameraRig.trackingSpace?");
return;
}
var toLocal = player.worldToLocalMatrix;
var rot = Quaternion.Inverse(anchor.rotation);
player.SetPositionAndRotation(
position: rot * -anchor.position,
rotation: Quaternion.Euler(0, rot.eulerAngles.y, 0)
);
if (m_Spawned.Count == 0)
return;
var toWorld = player.localToWorldMatrix;
foreach (var spawn in m_Spawned)
{
var matr = toWorld * (toLocal * spawn.transform.localToWorldMatrix);
var pos = matr.GetPosition();
rot = matr.rotation;
if (spawn.TryGetComponent(out PoseOrigin poe))
{
poe.TweenTo(
pos: pos,
rot: rot,
overSec: Mathf.Min((pos - poe.transform.position).magnitude, 7.5f)
);
}
else
{
spawn.transform.SetPositionAndRotation(
position: pos,
rotation: rot
);
}
}
}
void ProcessSpawnQueueAligned(Transform anchor, ICollection<Pose> queue)
{
if (!m_SpawnWithA || queue.Count == 0)
return;
Sampleton.Log($"{nameof(ProcessSpawnQueueAligned)}:");
foreach (var pose in queue)
{
var spawn = Instantiate(
original: m_SpawnWithA,
position: anchor.position + anchor.rotation * pose.position,
rotation: anchor.rotation * pose.rotation
);
spawn.name = spawn.name.Replace("(Clone)", $"{m_Spawned.Count}");
if (spawn.TryGetComponent(out PoseOrigin poo))
{
poo.UpdateCoordsNow();
}
Sampleton.Log($"+ created \"{spawn.name}\"");
m_Spawned.Add(spawn);
}
}
#endregion Alignment
#region UI helpers
void SetActiveGroup(Guid groupId)
{
if (groupId == m_ActiveGroup)
return;
bool wasEmpty = Guid.Empty == m_ActiveGroup;
bool isEmpty = Guid.Empty == groupId;
Sampleton.Log($"{nameof(SetActiveGroup)}:");
if (!wasEmpty)
Sampleton.Log($"- {m_ActiveGroup}");
if (!isEmpty)
Sampleton.Log($"+ {groupId}");
// UI updates:
if (m_KnownGroups.TryGetValue(m_ActiveGroup, out var currGroup) && currGroup.ListButton)
currGroup.ListButton.interactable = true;
if (m_KnownGroups.TryGetValue(groupId, out var nextGroup) && nextGroup.ListButton)
nextGroup.ListButton.interactable = false;
UISetStatusText(
$"Active Group UUID:\n{(isEmpty ? "(none)" : groupId.ToString())}",
order: 0
);
if (m_IsAdvertising)
{
Sampleton.Log($"* NOTICE: Active group changed while you are still advertising!", LogType.Warning);
}
m_ActiveGroup = groupId;
if (nextGroup is not null && ColoDiscoAnchor.Alignment)
{
ProcessSpawnQueueAligned(ColoDiscoAnchor.Alignment.transform, nextGroup.Metadata.Poses);
}
}
/// <summary>
/// In most cases outputs 1 group (the active), except when you enable <see cref="ApplyToAllGroups"/>,
/// which must be done through code or by activating the hidden toggle in the UI.
/// </summary>
/// <returns>
/// False if there are no group UUIDs active and <see cref="ForceShareAnchors"/> is off (default).
/// </returns>
bool AnyActiveGroups(out Guid[] groupIds)
{
groupIds = Array.Empty<Guid>();
var allGroups = m_KnownGroups.Keys;
if ((allGroups.Count == 0 || m_ActiveGroup == Guid.Empty) && !ForceShareAnchors)
{
Sampleton.LogError("- Cannot share anchor; no active group!");
Sampleton.Log("* You must <b>Advertise or Discover</b> sessions in order to work with groups.", LogType.Warning);
return false;
}
if (ApplyToAllGroups)
{
groupIds = new Guid[allGroups.Count];
allGroups.CopyTo(groupIds, 0);
}
else
{
groupIds = new[] { m_ActiveGroup };
}
return true;
}
static string FixupDisplayName(string orig, Guid groupId)
{
const int kMaxOrigLen = 15;
if (string.IsNullOrEmpty(orig))
orig = "<err>";
else if (orig.Length > kMaxOrigLen)
orig = orig.Remove(kMaxOrigLen);
return $"{orig} ({groupId.Brief()})";
}
void UISetStatusText(string text, int order)
{
Action<int> replace;
Func<int, bool> insert;
if (string.IsNullOrEmpty(text))
{
replace = i => m_StatusLines.RemoveAt(i);
insert = _ => false;
}
else
{
replace = i => m_StatusLines[i] = (order, text);
insert = i => { m_StatusLines.Insert(i, (order, text)); return true; };
}
int i = m_StatusLines.Count;
while (i-- > 0)
{
var current = m_StatusLines[i].Item1;
if (order == current)
{
replace(i);
goto Apply;
}
if (order > current && insert(i + 1))
{
goto Apply;
}
}
insert(0);
Apply:
m_StatusLabel.text = string.Join("\n\n", m_StatusLines.Select(p => p.Item2));
}
void UIAddDiscoveryItem(string labelTxt, Guid groupId, bool isSelected)
{
if (!m_GroupListItem || !m_KnownGroups.TryGetValue(groupId, out var group) || group.ListButton)
return;
labelTxt = FixupDisplayName(labelTxt, groupId);
var item = Instantiate(m_GroupListItem, m_GroupListItem.transform.parent);
item.SetActive(false);
item.name = labelTxt;
var label = item.GetComponentInChildren<TMP_Text>(includeInactive: true);
label.text = labelTxt;
var btn = item.GetComponent<Button>();
btn.interactable = !isSelected;
btn.onClick.AddListener(() =>
{
SetActiveGroup(groupId);
if (!LoadOnGroupSwitch)
return;
Sampleton.Log("(attempting to auto-load current group anchors)");
LoadGroupAnchorsAsync(groupId);
});
group.ListButton = btn;
item.SetActive(true);
if (m_GroupListLabel)
m_GroupListLabel.gameObject.SetActive(false);
}
void UIStateAdvertStart(bool warning)
{
bool hasAdvertised = m_KnownGroups.Values.Any(g => g.IsMine);
m_AdvertBtnLabel.text = hasAdvertised ? "Advertise NEW Uuid" : "Start Advertising";
if (m_AdvertBtnIcon)
m_AdvertBtnIcon.color = warning ? Color.yellow : Color.white;
m_AdvertBtn.interactable = !m_IsDiscovering;
m_DiscoBtn.interactable = true;
}
void UIStateAdvertStop(bool warning)
{
m_AdvertBtnLabel.text = "Stop Advertising";
if (m_AdvertBtnIcon)
m_AdvertBtnIcon.color = warning ? Color.yellow : Color.green;
m_AdvertBtn.interactable = true;
m_DiscoBtn.interactable = m_IsDiscovering || warning;
}
void UIStateDiscoStart(bool warning)
{
m_DiscoBtnLabel.text = "Start Discovering";
if (m_DiscoBtnIcon)
m_DiscoBtnIcon.color = warning ? Color.yellow : Color.white;
m_DiscoBtn.interactable = !m_IsAdvertising;
m_AdvertBtn.interactable = true;
}
void UIStateDiscoStop(bool warning)
{
m_DiscoBtnLabel.text = "Stop Discovering";
if (m_DiscoBtnIcon)
m_DiscoBtnIcon.color = warning ? Color.yellow : Color.green;
m_DiscoBtn.interactable = true;
m_AdvertBtn.interactable = m_IsAdvertising || warning;
}
#endregion UI helpers
#region HOT: API callbacks
void ReceivedLoggedInUser(Message msg)
{
if (msg.IsError)
{
var err = msg.GetError();
string codeStr = err.Code switch // lol ever heard of an enum?
{
2 => $"AUTHENTICATION_ERROR({err.Code})",
3 => $"NETWORK_ERROR({err.Code})",
4 => $"STORE_INSTALLATION_ERROR({err.Code})",
5 => $"CALLER_NOT_SIGNED({err.Code})",
6 => $"UNKNOWN_SERVER_ERROR({err.Code})",
7 => $"PERMISSIONS_FAILURE({err.Code})",
_ => $"UNKNOWN_ERROR({err.Code})"
};
Sampleton.LogError($"{nameof(ReceivedLoggedInUser)} FAILED: code={codeStr} message=\"{err.Message}\"");
#if UNITY_EDITOR || UNITY_STANDALONE
if (err.Code == 1)
{
Sampleton.Log("- Did you remember to enter your test user credentials into the OculusPlatformSettings asset?");
}
#endif
if (!m_RequireLoggedInUser)
{
Sampleton.Log("* No worries! This build does not have a hard requirement for user login.\n<color=\"yellow\">* However, expect some elements of the sample to be less consistent without this info!</color>");
}
return;
}
Sampleton.Log($"{nameof(ReceivedLoggedInUser)} success:");
Assert.AreEqual(Message.MessageType.User_GetLoggedInUser, msg.Type, "msg.Type");
m_My = msg.GetUser();
Assert.IsNotNull(m_My, "msg.GetUser()");
Sampleton.Log($"+ Oculus Username: \'{m_My.OculusID}\'\n+ Oculus User ID: {m_My.ID}");
if (m_My.ID == 0)
{
Sampleton.LogError("- You are not authenticated to use this app.\n- Shared Spatial Anchors will not work.");
return;
}
foreach (var uiThing in m_DisabledWithoutValidUser)
{
uiThing.interactable = true;
}
}
void ReceivedSessionData(OVRColocationSession.Data data)
{