This repository has been archived by the owner on Mar 21, 2023. It is now read-only.
/
WorldAnchorCoordinateService.cs
281 lines (240 loc) · 10.1 KB
/
WorldAnchorCoordinateService.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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
#pragma warning disable CS0618 // 'WorldAnchorStore' is obsolete: 'Support for built-in VR will be removed in Unity 2020.1.
using Microsoft.MixedReality.SpatialAlignment;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using UnityEngine;
#if UNITY_WSA&&!(WINMR||OPENXR)
using UnityEngine.XR.WSA;
using UnityEngine.XR.WSA.Persistence;
#endif
namespace Microsoft.MixedReality.SpectatorView
{
/// <summary>
/// Represents an <see cref="Microsoft.MixedReality.SpatialAlignment.ISpatialCoordinateService"/> that creates and stores
/// coordinates based on WorldAnchors stored in a WorldAnchorStore on the device.
/// </summary>
public class WorldAnchorCoordinateService : SpatialCoordinateServiceUnityBase<string>
{
private static Task<WorldAnchorCoordinateService> sharedCoordinateService;
private readonly Transform parentTransform;
#if UNITY_WSA&&!(WINMR||OPENXR)
private Task<WorldAnchorStore> worldAnchorStoreTask;
#endif
/// <summary>
/// Constructs the coordinate service. Access to the coordinate service
/// should be done through GetSharedCoordinateServiceAsync.
/// </summary>
private WorldAnchorCoordinateService(Transform parentTransform)
{
this.parentTransform = parentTransform;
}
protected override bool SupportsDiscovery => false;
public static Task<WorldAnchorCoordinateService> GetSharedCoordinateServiceAsync(Transform parentTransform)
{
if (sharedCoordinateService == null)
{
sharedCoordinateService = InitializeSharedCoordinateServiceAsync(parentTransform);
}
return sharedCoordinateService;
}
private static async Task<WorldAnchorCoordinateService> InitializeSharedCoordinateServiceAsync(Transform parentTransform)
{
WorldAnchorCoordinateService service = new WorldAnchorCoordinateService(parentTransform);
await service.InitializeKnownCoordinatesAsync();
return service;
}
protected override Task OnDiscoverCoordinatesAsync(CancellationToken cancellationToken, string[] idsToLocate = null)
{
throw new NotSupportedException("WorldAnchorCoordinateService does not support discovery");
}
protected override bool TryParse(string id, out string result)
{
result = id;
return true;
}
public async Task InitializeKnownCoordinatesAsync()
{
#if UNITY_WSA&&!(WINMR||OPENXR)
WorldAnchorStore store = await GetWorldAnchorStoreAsync();
foreach (string knownId in store.GetAllIds())
{
GameObject anchorGameObject = new GameObject(knownId);
anchorGameObject.transform.parent = parentTransform;
WorldAnchor anchor = store.Load(knownId, anchorGameObject);
if (anchor == null)
{
Debug.LogError($"Unexpected WorldAnchor {knownId} was enumerated but failed to load");
continue;
}
OnNewCoordinate(knownId, new WorldAnchorSpatialCoordinate(knownId, anchor));
}
#else
await Task.CompletedTask;
#endif
}
public async Task<ISpatialCoordinate> CreateCoordinateAsync(string id, Vector3 worldPosition, Quaternion worldRotation, CancellationToken cancellationToken)
{
#if UNITY_WSA&&!(WINMR||OPENXR)
await TryDeleteCoordinateAsync(id, cancellationToken);
GameObject gameObject = new GameObject(id);
gameObject.transform.parent = parentTransform;
gameObject.transform.position = worldPosition;
gameObject.transform.rotation = worldRotation;
WorldAnchor anchor = gameObject.AddComponent<WorldAnchor>();
if (anchor.isLocated)
{
WorldAnchorStore store = await GetWorldAnchorStoreAsync();
store.Save(id, anchor);
}
else
{
anchor.OnTrackingChanged += Anchor_OnTrackingChanged;
}
WorldAnchorSpatialCoordinate coordinate = new WorldAnchorSpatialCoordinate(id, anchor);
OnNewCoordinate(id, coordinate);
return coordinate;
#else
Debug.LogError("Current platform does not support creating WorldAnchor coordinates");
return await Task.FromResult<ISpatialCoordinate>(null);
#endif
}
public override async Task<bool> TryDeleteCoordinateAsync(string key, CancellationToken cancellationToken)
{
#if UNITY_WSA&&!(WINMR||OPENXR)
if (TryGetKnownCoordinate(key, out ISpatialCoordinate coordinate))
{
WorldAnchorSpatialCoordinate worldAnchorCoordinate = (WorldAnchorSpatialCoordinate)coordinate;
WorldAnchorStore anchorStore = await GetWorldAnchorStoreAsync();
anchorStore.Delete(key);
worldAnchorCoordinate.Destroy();
}
#endif
return await base.TryDeleteCoordinateAsync(key, cancellationToken);
}
#if UNITY_WSA&&!(WINMR||OPENXR)
private async void Anchor_OnTrackingChanged(WorldAnchor worldAnchor, bool located)
{
if (located)
{
worldAnchor.OnTrackingChanged -= Anchor_OnTrackingChanged;
WorldAnchorStore store = await GetWorldAnchorStoreAsync();
store.Save(worldAnchor.name, worldAnchor);
}
}
protected override void OnManagedDispose()
{
base.OnManagedDispose();
foreach (WorldAnchorSpatialCoordinate coordinate in KnownCoordinates)
{
coordinate.Destroy();
}
if (worldAnchorStoreTask.IsCompleted)
{
worldAnchorStoreTask.Result.Dispose();
worldAnchorStoreTask = null;
}
}
private Task<WorldAnchorStore> GetWorldAnchorStoreAsync()
{
if (worldAnchorStoreTask == null)
{
worldAnchorStoreTask = InitializeWorldAnchorStoreAsync();
}
return worldAnchorStoreTask;
}
private Task<WorldAnchorStore> InitializeWorldAnchorStoreAsync()
{
TaskCompletionSource<WorldAnchorStore> taskSource = new TaskCompletionSource<WorldAnchorStore>();
WorldAnchorStore.GetAsync(store => taskSource.SetResult(store));
return taskSource.Task;
}
private class WorldAnchorSpatialCoordinate : SpatialCoordinateUnityBase<string>
{
private WorldAnchor worldAnchor;
public WorldAnchorSpatialCoordinate(string id, WorldAnchor worldAnchor)
: base(id)
{
this.worldAnchor = worldAnchor;
this.worldAnchor.OnTrackingChanged += WorldAnchor_OnTrackingChanged;
}
public override LocatedState State
{
get
{
#if UNITY_EDITOR
return LocatedState.Tracking;
#else
if (worldAnchor == null)
{
// Once the WorldAnchor has been destroyed,
// the coordinate will live in a Resolved state
// at the last-known position of the WorldAnchor.
return LocatedState.Resolved;
}
else if (!worldAnchor.isLocated)
{
// When the WorldAnchor exists but is no longer located,
// report the state of the coordinate as Inhibited.
return LocatedState.Inhibited;
}
else
{
// The WorldAnchor exists and is currently located,
// so report the state of the coordinate as Tracking.
return LocatedState.Tracking;
}
#endif
}
}
private void WorldAnchor_OnTrackingChanged(WorldAnchor worldAnchor, bool located)
{
OnStateChanged();
}
protected override Quaternion CoordinateToWorldSpace(Quaternion quaternion)
{
if (worldAnchor != null)
{
return worldAnchor.transform.rotation * quaternion;
}
return base.CoordinateToWorldSpace(quaternion);
}
protected override Vector3 CoordinateToWorldSpace(Vector3 vector)
{
if (worldAnchor != null)
{
return worldAnchor.transform.TransformPoint(vector);
}
return base.CoordinateToWorldSpace(vector);
}
protected override Quaternion WorldToCoordinateSpace(Quaternion quaternion)
{
if (worldAnchor != null)
{
return Quaternion.Inverse(worldAnchor.transform.rotation) * quaternion;
}
return base.WorldToCoordinateSpace(quaternion);
}
protected override Vector3 WorldToCoordinateSpace(Vector3 vector)
{
if (worldAnchor != null)
{
return worldAnchor.transform.InverseTransformPoint(vector);
}
return base.WorldToCoordinateSpace(vector);
}
public void Destroy()
{
worldAnchor.OnTrackingChanged -= WorldAnchor_OnTrackingChanged;
SetCoordinateWorldTransform(worldAnchor.transform.position, worldAnchor.transform.rotation);
GameObject.Destroy(worldAnchor.gameObject);
worldAnchor = null;
}
}
#endif
}
}