-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathAvatarMovementHandlerMotif.cs
333 lines (284 loc) · 10.4 KB
/
AvatarMovementHandlerMotif.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
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
* All rights reserved.
*
* Licensed under the Oculus SDK License Agreement (the "License");
* you may not use the Oculus SDK except in compliance with the License,
* which is provided at the time of installation or download, or which
* otherwise accompanies this software in either electronic or hard copy form.
*
* You may obtain a copy of the License at
*
* https://developer.oculus.com/licenses/oculussdk/
*
* Unless required by applicable law or agreed to in writing, the Oculus SDK
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if FUSION2
using Fusion;
using System;
using UnityEngine;
using System.Collections;
using Oculus.Interaction;
using System.Collections.Generic;
using Meta.XR.MultiplayerBlocks.Fusion;
using Meta.XR.MultiplayerBlocks.Shared;
/// <summary>
/// Handles synchronization of avatar positions and rotations across networked clients.
/// Manages the interaction between avatars and the object of interest, ensuring avatars
/// are correctly positioned relative to the object and updated whenever the object is moved.
/// </summary>
public class AvatarMovementHandlerMotif : NetworkBehaviour
{
/// <summary>
/// Stores the relative positions of avatars. Each entry represents an avatar's position relative
/// to the object of interest, and these positions are synchronized across networked clients.
/// </summary>
[Networked, Capacity(8)] private NetworkArray<Vector3> AvatarPositions => default;
/// <summary>
/// Stores the relative rotations of avatars. Each entry represents an avatar's rotation relative
/// to the object of interest, and these rotations are synchronized across networked clients.
/// </summary>
[Networked, Capacity(8)] private NetworkArray<Quaternion> AvatarRotations => default;
private SpawnManagerMotif _spawnManagerMotif;
private GameObject _objectOfInterest;
private NetworkRunner _networkRunner;
private AvatarBehaviourFusion _localAvatar;
private InteractableUnityEventWrapper _interactableUnityEventWrapper;
private bool _hasObjectMoved;
public bool HasSpawned { get; private set; }
public bool AvatarsInitialized { get; private set; }
public event Action<AvatarBehaviourFusion> OnRemoteAvatarAdded;
private readonly List<AvatarBehaviourFusion> _remoteAvatars = new();
public override void Spawned()
{
base.Spawned();
HasSpawned = true;
_networkRunner = Runner;
_spawnManagerMotif = FindObjectOfType<SpawnManagerMotif>();
_objectOfInterest = _spawnManagerMotif.ObjectOfInterest;
_interactableUnityEventWrapper = _objectOfInterest.GetComponent<InteractableUnityEventWrapper>();
if (_spawnManagerMotif == null || _interactableUnityEventWrapper == null)
{
Debug.LogError("Either SpawnManagerMotif or InteractableUnityEventWrapper is missing.");
return;
}
AvatarEntity.OnSpawned += AddAvatarToList;
_interactableUnityEventWrapper.WhenSelect.AddListener(() => ToggleObjectMoved(true));
_interactableUnityEventWrapper.WhenUnselect.AddListener(() => ToggleObjectMoved(false));
InitializeAvatars();
}
public override void Despawned(NetworkRunner runner, bool hasState)
{
base.Despawned(runner, hasState);
AvatarEntity.OnSpawned -= AddAvatarToList;
_interactableUnityEventWrapper.WhenSelect.RemoveListener(() => ToggleObjectMoved(true));
_interactableUnityEventWrapper.WhenUnselect.RemoveListener(() => ToggleObjectMoved(false));
}
private void InitializeAvatars()
{
var avatars = FindObjectsOfType<AvatarBehaviourFusion>();
foreach (var avatar in avatars)
{
if (avatar.Object.HasStateAuthority)
{
_localAvatar = avatar;
}
else
{
_remoteAvatars.Add(avatar);
ParentAvatarToObjectOfInterest(avatar);
StartCoroutine(SetAvatarToSpawnLocation(avatar));
DisableNetworkTransform(avatar);
}
}
}
private void AddAvatarToList(AvatarEntity avatarEntity)
{
StartCoroutine(AddAvatarToListWhenReady(avatarEntity));
}
private IEnumerator AddAvatarToListWhenReady(AvatarEntity avatarEntity)
{
// Additional delay required since Avatars v28+ require some additional time to be loaded
// No event to await the full "readiness" of the avatar is available yet
yield return new WaitForSeconds(1.5f);
while (!avatarEntity)
{
yield return null;
}
while (avatarEntity && avatarEntity.IsPendingAvatar)
{
yield return null;
}
if (!avatarEntity)
{
yield break;
}
var avatar = avatarEntity.GetComponent<AvatarBehaviourFusion>();
if (!avatar)
{
yield break;
}
if (avatar.Object.HasStateAuthority)
{
_localAvatar = avatar;
SendAvatarOffset();
}
else
{
_remoteAvatars.Add(avatar);
ParentAvatarToObjectOfInterest(avatar);
StartCoroutine(SetAvatarToSpawnLocation(avatar));
DisableNetworkTransform(avatar);
}
}
private void ParentAvatarToObjectOfInterest(AvatarBehaviourFusion avatar)
{
avatar.transform.parent = _objectOfInterest.transform;
}
private void DisableNetworkTransform(AvatarBehaviourFusion avatar)
{
var networkTransform = avatar.GetComponent<NetworkTransform>();
if (networkTransform)
{
networkTransform.enabled = false;
}
}
private IEnumerator SetAvatarToSpawnLocation(AvatarBehaviourFusion avatar)
{
if (!_spawnManagerMotif)
{
yield break;
}
var clientId = 0;
foreach (var unused in _networkRunner.ActivePlayers)
{
clientId++;
}
var occupiedCount = GetOccupiedPlayerCount();
while (occupiedCount <= clientId - 1)
{
yield return new WaitForEndOfFrame();
occupiedCount = GetOccupiedPlayerCount();
}
var avatarIndex = GetAvatarIndex(avatar);
if (avatarIndex < 0)
{
yield break;
}
SendAvatarOffset();
yield return new WaitForEndOfFrame();
AvatarsInitialized = true;
OnRemoteAvatarAdded?.Invoke(avatar);
}
private int GetOccupiedPlayerCount()
{
var occupiedCount = 0;
for (var i = 0; i < _spawnManagerMotif.OccupyingPlayers.Length; i++)
{
if (_spawnManagerMotif.OccupyingPlayers.Get(i) != PlayerRef.None)
{
occupiedCount++;
}
}
return occupiedCount;
}
private void ToggleObjectMoved(bool hasMoved)
{
_hasObjectMoved = hasMoved;
}
private void Update()
{
if (_hasObjectMoved)
{
SendAvatarOffset();
}
UpdateRemoteAvatars();
}
private void SendAvatarOffset()
{
var relativePosition = _objectOfInterest.transform.InverseTransformPoint(_localAvatar.transform.position);
var relativeRotation = Quaternion.Inverse(_objectOfInterest.transform.rotation) * _localAvatar.transform.rotation;
var avatarIndex = GetLocalPlayerIndex();
if (avatarIndex < 0 || avatarIndex >= AvatarPositions.Length)
{
return;
}
SendPositionAndRotationRpc(avatarIndex, relativePosition, relativeRotation);
}
[Rpc(RpcSources.All, RpcTargets.StateAuthority)]
private void SendPositionAndRotationRpc(int avatarIndex, Vector3 pos, Quaternion rot)
{
AvatarPositions.Set(avatarIndex, pos);
AvatarRotations.Set(avatarIndex, rot);
}
private void UpdateRemoteAvatars()
{
for (var i = _remoteAvatars.Count - 1; i >= 0; i--)
{
var remoteAvatar = _remoteAvatars[i];
if (!remoteAvatar || !remoteAvatar.Object)
{
_remoteAvatars.RemoveAt(i);
continue;
}
var avatarIndex = GetAvatarIndex(remoteAvatar);
if (avatarIndex < 0 || avatarIndex >= AvatarPositions.Length)
{
// Skip this avatar if the index is invalid or out of bounds
// to prevent accessing arrays with invalid indices and causing exceptions
continue;
}
var newPosition = AvatarPositions.Get(avatarIndex);
var newRotation = AvatarRotations.Get(avatarIndex);
var worldPosition = _objectOfInterest.transform.TransformPoint(newPosition);
var worldRotation = _objectOfInterest.transform.rotation * newRotation;
remoteAvatar.transform.position = worldPosition;
remoteAvatar.transform.rotation = worldRotation;
}
}
private int GetLocalPlayerIndex()
{
for (var i = 0; i < _spawnManagerMotif.OccupyingPlayers.Length; i++)
{
if (_spawnManagerMotif.OccupyingPlayers.Get(i) == _networkRunner.LocalPlayer)
{
return i;
}
}
return -1;
}
private int GetAvatarIndex(AvatarBehaviourFusion avatar)
{
for (var i = 0; i < _spawnManagerMotif.OccupyingPlayers.Length; i++)
{
if (_spawnManagerMotif.OccupyingPlayers.Get(i) == avatar.Object.StateAuthority)
{
return i;
}
}
return -1;
}
/// <summary>
/// This method is used by the <see cref="AvatarSpawnerHandlerMotif"/> class, in
/// order to free up the spawn location again after a player has left the experience.
/// </summary>
public void RemoveRemoteAvatarByPlayer(PlayerRef player)
{
AvatarBehaviourFusion avatarToRemove = null;
foreach (var avatar in _remoteAvatars)
{
if (avatar == null || avatar.Object == null || avatar.Object.StateAuthority != player) continue;
avatarToRemove = avatar;
break;
}
if (avatarToRemove != null)
{
_remoteAvatars.Remove(avatarToRemove);
}
}
}
#endif