-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathLeapServiceProvider.cs
574 lines (485 loc) · 19.2 KB
/
LeapServiceProvider.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
/******************************************************************************
* Copyright (C) Ultraleap, Inc. 2011-2020. *
* *
* Use subject to the terms of the Apache License 2.0 available at *
* http://www.apache.org/licenses/LICENSE-2.0, or another agreement *
* between Ultraleap and you, your company or other organization. *
******************************************************************************/
using System;
using System.Collections.Generic;
using UnityEngine;
namespace Leap.Unity {
using Attributes;
/// <summary>
/// The LeapServiceProvider provides tracked Leap Hand data and images from the device
/// via the Leap service running on the client machine.
/// </summary>
public class LeapServiceProvider : LeapProvider {
#region Constants
/// <summary>
/// Converts nanoseconds to seconds.
/// </summary>
protected const double NS_TO_S = 1e-6;
/// <summary>
/// Converts seconds to nanoseconds.
/// </summary>
protected const double S_TO_NS = 1e6;
/// <summary>
/// The transform array used for late-latching.
/// </summary>
protected const string HAND_ARRAY_GLOBAL_NAME = "_LeapHandTransforms";
/// <summary>
/// The maximum number of times the provider will
/// attempt to reconnect to the service before giving up.
/// </summary>
protected const int MAX_RECONNECTION_ATTEMPTS = 5;
/// <summary>
/// The number of frames to wait between each
/// reconnection attempt.
/// </summary>
protected const int RECONNECTION_INTERVAL = 180;
const int _port = 6437;
#endregion
#region Inspector
[SerializeField] protected bool _remoteConnection;
[SerializeField] protected string _ip = "127.0.0.1";
[SerializeField] protected int _jsonVersion = 6;
public enum InteractionVolumeVisualization {
None,
LeapMotionController,
StereoIR170,
Automatic
}
[Tooltip("Displays a representation of the interaction volume in the scene view")]
[SerializeField]
protected InteractionVolumeVisualization _interactionVolumeVisualization = InteractionVolumeVisualization.LeapMotionController;
public InteractionVolumeVisualization SelectedInteractionVolumeVisualization => _interactionVolumeVisualization;
public enum FrameOptimizationMode {
None,
ReuseUpdateForPhysics,
ReusePhysicsForUpdate,
}
[Tooltip("When enabled, the provider will only calculate one leap frame instead of two.")]
[SerializeField]
protected FrameOptimizationMode _frameOptimization = FrameOptimizationMode.None;
public enum PhysicsExtrapolationMode {
None,
Auto,
Manual
}
[Tooltip("The mode to use when extrapolating physics.\n" +
" None - No extrapolation is used at all.\n" +
" Auto - Extrapolation is chosen based on the fixed timestep.\n" +
" Manual - Extrapolation time is chosen manually by the user.")]
[SerializeField]
protected PhysicsExtrapolationMode _physicsExtrapolation = PhysicsExtrapolationMode.Auto;
[Tooltip("The amount of time (in seconds) to extrapolate the physics data by.")]
[SerializeField]
protected float _physicsExtrapolationTime = 1.0f / 90.0f;
#if UNITY_2017_3_OR_NEWER
[Tooltip("When checked, profiling data from the LeapCSharp worker thread will be used to populate the UnityProfiler.")]
[EditTimeOnly]
#else
[Tooltip("Worker thread profiling requires a Unity version of 2017.3 or greater.")]
[Disable]
#endif
[SerializeField]
protected bool _workerThreadProfiling = false;
#endregion
#region Internal Settings & Memory
protected bool _useInterpolation = true;
// Extrapolate on Android to compensate for the latency introduced by its graphics
// pipeline.
#if UNITY_ANDROID && !UNITY_EDITOR
protected int ExtrapolationAmount = 15;
protected int BounceAmount = 70;
#else
protected int ExtrapolationAmount = 0;
protected int BounceAmount = 0;
#endif
protected IController _leapController;
protected bool _isDestroyed;
protected SmoothedFloat _fixedOffset = new SmoothedFloat();
protected SmoothedFloat _smoothedTrackingLatency = new SmoothedFloat();
protected long _unityToLeapOffset;
protected Frame _untransformedUpdateFrame;
protected Frame _transformedUpdateFrame;
protected Frame _untransformedFixedFrame;
protected Frame _transformedFixedFrame;
#endregion
#region Edit-time Frame Data
private Action<Device> _onDeviceSafe;
/// <summary>
/// A utility event to get a callback whenever a new device is connected to the service.
/// This callback will ALSO trigger a callback upon subscription if a device is already
/// connected.
///
/// For situations with multiple devices OnDeviceSafe will be dispatched once for each device.
/// </summary>
public event Action<Device> OnDeviceSafe {
add {
if (_leapController != null && _leapController.IsConnected) {
foreach (var device in _leapController.Devices) {
value(device);
}
}
_onDeviceSafe += value;
}
remove {
_onDeviceSafe -= value;
}
}
#if UNITY_EDITOR
private Frame _backingUntransformedEditTimeFrame = null;
private Frame _untransformedEditTimeFrame {
get {
if (_backingUntransformedEditTimeFrame == null) {
_backingUntransformedEditTimeFrame = new Frame();
}
return _backingUntransformedEditTimeFrame;
}
}
private Frame _backingEditTimeFrame = null;
private Frame _editTimeFrame {
get {
if (_backingEditTimeFrame == null) {
_backingEditTimeFrame = new Frame();
}
return _backingEditTimeFrame;
}
}
private Dictionary<TestHandFactory.TestHandPose, Hand> _cachedLeftHands
= new Dictionary<TestHandFactory.TestHandPose, Hand>();
private Hand _editTimeLeftHand {
get {
if (_cachedLeftHands.TryGetValue(editTimePose, out Hand cachedHand)) {
return cachedHand;
}
else {
cachedHand = TestHandFactory.MakeTestHand(isLeft: true, pose: editTimePose);
_cachedLeftHands[editTimePose] = cachedHand;
return cachedHand;
}
}
}
private Dictionary<TestHandFactory.TestHandPose, Hand> _cachedRightHands
= new Dictionary<TestHandFactory.TestHandPose, Hand>();
private Hand _editTimeRightHand {
get {
if (_cachedRightHands.TryGetValue(editTimePose, out Hand cachedHand)) {
return cachedHand;
}
else {
cachedHand = TestHandFactory.MakeTestHand(isLeft: false, pose: editTimePose);
_cachedRightHands[editTimePose] = cachedHand;
return cachedHand;
}
}
}
#endif
#endregion
#region LeapProvider Implementation
public override Frame CurrentFrame {
get {
#if UNITY_EDITOR
if (!Application.isPlaying) {
_editTimeFrame.Hands.Clear();
_untransformedEditTimeFrame.Hands.Clear();
_untransformedEditTimeFrame.Hands.Add(_editTimeLeftHand);
_untransformedEditTimeFrame.Hands.Add(_editTimeRightHand);
transformFrame(_untransformedEditTimeFrame, _editTimeFrame);
return _editTimeFrame;
}
#endif
if (_frameOptimization == FrameOptimizationMode.ReusePhysicsForUpdate) {
return _transformedFixedFrame;
} else {
return _transformedUpdateFrame;
}
}
}
public override Frame CurrentFixedFrame {
get {
#if UNITY_EDITOR
if (!Application.isPlaying) {
_editTimeFrame.Hands.Clear();
_untransformedEditTimeFrame.Hands.Clear();
_untransformedEditTimeFrame.Hands.Add(_editTimeLeftHand);
_untransformedEditTimeFrame.Hands.Add(_editTimeRightHand);
transformFrame(_untransformedEditTimeFrame, _editTimeFrame);
return _editTimeFrame;
}
#endif
if (_frameOptimization == FrameOptimizationMode.ReuseUpdateForPhysics) {
return _transformedUpdateFrame;
} else {
return _transformedFixedFrame;
}
}
}
#endregion
#region Unity Events
protected virtual void Reset() {
editTimePose = TestHandFactory.TestHandPose.DesktopModeA;
}
protected virtual void Awake() {
_fixedOffset.delay = 0.4f;
_smoothedTrackingLatency.SetBlend(0.99f, 0.0111f);
}
protected virtual void Start() {
createController();
_transformedUpdateFrame = new Frame();
_transformedFixedFrame = new Frame();
_untransformedUpdateFrame = new Frame();
_untransformedFixedFrame = new Frame();
}
protected virtual void Update() {
if (_workerThreadProfiling) {
LeapProfiling.Update();
}
if (!checkConnectionIntegrity()) { return; }
#if UNITY_EDITOR
if (UnityEditor.EditorApplication.isCompiling) {
UnityEditor.EditorApplication.isPlaying = false;
Debug.LogWarning("Unity hot reloading not currently supported. Stopping Editor Playback.");
return;
}
#endif
_fixedOffset.Update(Time.time - Time.fixedTime, Time.deltaTime);
if (_frameOptimization == FrameOptimizationMode.ReusePhysicsForUpdate) {
DispatchUpdateFrameEvent(_transformedFixedFrame);
return;
}
if (_useInterpolation) {
#if !UNITY_ANDROID || UNITY_EDITOR
_smoothedTrackingLatency.value = Mathf.Min(_smoothedTrackingLatency.value, 30000f);
_smoothedTrackingLatency.Update((float)(_leapController.Now() - _leapController.FrameTimestamp()), Time.deltaTime);
#endif
long timestamp = CalculateInterpolationTime() + (ExtrapolationAmount * 1000);
_unityToLeapOffset = timestamp - (long)(Time.time * S_TO_NS);
_leapController.GetInterpolatedFrameFromTime(_untransformedUpdateFrame, timestamp, CalculateInterpolationTime() - (BounceAmount * 1000));
}
else {
_leapController.Frame(_untransformedUpdateFrame);
}
if (_untransformedUpdateFrame != null) {
transformFrame(_untransformedUpdateFrame, _transformedUpdateFrame);
DispatchUpdateFrameEvent(_transformedUpdateFrame);
}
}
protected virtual void FixedUpdate() {
if (_frameOptimization == FrameOptimizationMode.ReuseUpdateForPhysics) {
DispatchFixedFrameEvent(_transformedUpdateFrame);
return;
}
if (_useInterpolation) {
long timestamp;
switch (_frameOptimization) {
case FrameOptimizationMode.None:
// By default we use Time.fixedTime to ensure that our hands are on the same
// timeline as Update. We add an extrapolation value to help compensate
// for latency.
float extrapolatedTime = Time.fixedTime + CalculatePhysicsExtrapolation();
timestamp = (long)(extrapolatedTime * S_TO_NS) + _unityToLeapOffset;
break;
case FrameOptimizationMode.ReusePhysicsForUpdate:
// If we are re-using physics frames for update, we don't even want to care
// about Time.fixedTime, just grab the most recent interpolated timestamp
// like we are in Update.
timestamp = CalculateInterpolationTime() + (ExtrapolationAmount * 1000);
break;
default:
throw new System.InvalidOperationException(
"Unexpected frame optimization mode: " + _frameOptimization);
}
_leapController.GetInterpolatedFrame(_untransformedFixedFrame, timestamp);
}
else {
_leapController.Frame(_untransformedFixedFrame);
}
if (_untransformedFixedFrame != null) {
transformFrame(_untransformedFixedFrame, _transformedFixedFrame);
DispatchFixedFrameEvent(_transformedFixedFrame);
}
}
protected virtual void OnDestroy() {
destroyController();
_isDestroyed = true;
}
protected virtual void OnApplicationPause(bool isPaused) {
if (_leapController != null) {
if (isPaused) {
_leapController.StopConnection();
}
else {
_leapController.StartConnection();
}
}
}
protected virtual void OnApplicationQuit() {
destroyController();
_isDestroyed = true;
}
public float CalculatePhysicsExtrapolation() {
switch (_physicsExtrapolation) {
case PhysicsExtrapolationMode.None:
return 0;
case PhysicsExtrapolationMode.Auto:
return Time.fixedDeltaTime;
case PhysicsExtrapolationMode.Manual:
return _physicsExtrapolationTime;
default:
throw new System.InvalidOperationException(
"Unexpected physics extrapolation mode: " + _physicsExtrapolation);
}
}
#endregion
#region Public API
/// <summary>
/// Returns the Leap Controller instance.
/// </summary>
public IController GetLeapController() {
#if UNITY_EDITOR
// Null check to deal with hot reloading.
if (!_isDestroyed && _leapController == null) {
createController();
}
#endif
return _leapController;
}
/// <summary>
/// Returns true if the Leap Motion hardware is plugged in and this application is
/// connected to the Leap Motion service.
/// </summary>
public bool IsConnected() {
return GetLeapController().IsConnected;
}
/// <summary>
/// Retransforms hand data from Leap space to the space of the Unity transform.
/// This is only necessary if you're moving the LeapServiceProvider around in a
/// custom script and trying to access Hand data from it directly afterward.
/// </summary>
public void RetransformFrames() {
transformFrame(_untransformedUpdateFrame, _transformedUpdateFrame);
transformFrame(_untransformedFixedFrame, _transformedFixedFrame);
}
/// <summary>
/// Copies property settings from this LeapServiceProvider to the target
/// LeapXRServiceProvider where applicable. Does not modify any XR-specific settings
/// that only exist on the LeapXRServiceProvider.
/// </summary>
public void CopySettingsToLeapXRServiceProvider(
LeapXRServiceProvider leapXRServiceProvider) {
leapXRServiceProvider._interactionVolumeVisualization = _interactionVolumeVisualization;
leapXRServiceProvider._frameOptimization = _frameOptimization;
leapXRServiceProvider._physicsExtrapolation = _physicsExtrapolation;
leapXRServiceProvider._physicsExtrapolationTime = _physicsExtrapolationTime;
leapXRServiceProvider._workerThreadProfiling = _workerThreadProfiling;
}
#endregion
#region Internal Methods
protected virtual long CalculateInterpolationTime(bool endOfFrame = false) {
#if UNITY_ANDROID && !UNITY_EDITOR
return _leapController.Now() - 16000;
#else
if (_leapController != null) {
return _leapController.Now() - (long)_smoothedTrackingLatency.value;
} else {
return 0;
}
#endif
}
/// <summary>
/// Initializes Leap Motion policy flags.
/// </summary>
protected virtual void initializeFlags() {
if (_leapController == null) {
return;
}
_leapController.ClearPolicy(Controller.PolicyFlag.POLICY_DEFAULT);
}
/// <summary>
/// Creates an instance of a Controller, initializing its policy flags and
/// subscribing to its connection event.
/// </summary>
protected void createController() {
if (_leapController != null) {
return;
}
if (!_remoteConnection) {
_leapController = new Controller();
} else {
_leapController = new RemoteController($"ws://{_ip}:{_port}/v{_jsonVersion}.json");
}
_leapController.Device += (s, e) => {
if (_onDeviceSafe != null) {
_onDeviceSafe(e.Device);
}
};
if (_leapController.IsConnected) {
initializeFlags();
} else {
_leapController.Device += onHandControllerConnect;
}
if (_workerThreadProfiling) {
//A controller will report profiling statistics for the duration of it's lifetime
//so these events will never be unsubscribed from.
_leapController.EndProfilingBlock += LeapProfiling.EndProfilingBlock;
_leapController.BeginProfilingBlock += LeapProfiling.BeginProfilingBlock;
_leapController.EndProfilingForThread += LeapProfiling.EndProfilingForThread;
_leapController.BeginProfilingForThread += LeapProfiling.BeginProfilingForThread;
}
}
/// <summary>
/// Stops the connection for the existing instance of a Controller, clearing old
/// policy flags and resetting the Controller to null.
/// </summary>
protected void destroyController() {
if (_leapController != null) {
if (_leapController.IsConnected) {
_leapController.ClearPolicy(Controller.PolicyFlag.POLICY_OPTIMIZE_HMD);
}
_leapController.StopConnection();
_leapController = null;
}
}
private int _framesSinceServiceConnectionChecked = 0;
private int _numberOfReconnectionAttempts = 0;
/// <summary>
/// Checks whether this provider is connected to a service;
/// If it is not, attempt to reconnect at regular intervals
/// for MAX_RECONNECTION_ATTEMPTS
/// </summary>
protected bool checkConnectionIntegrity() {
if (_leapController.IsServiceConnected) {
_framesSinceServiceConnectionChecked = 0;
_numberOfReconnectionAttempts = 0;
return true;
} else if (_numberOfReconnectionAttempts < MAX_RECONNECTION_ATTEMPTS) {
_framesSinceServiceConnectionChecked++;
if (_framesSinceServiceConnectionChecked > RECONNECTION_INTERVAL) {
_framesSinceServiceConnectionChecked = 0;
_numberOfReconnectionAttempts++;
Debug.LogWarning("Leap Service not connected; attempting to reconnect for try " +
_numberOfReconnectionAttempts + "/" + MAX_RECONNECTION_ATTEMPTS +
"...", this);
using (new ProfilerSample("Reconnection Attempt")) {
destroyController();
createController();
}
}
}
return false;
}
protected void onHandControllerConnect(object sender, LeapEventArgs args) {
initializeFlags();
if (_leapController != null) {
_leapController.Device -= onHandControllerConnect;
}
}
protected virtual void transformFrame(Frame source, Frame dest) {
dest.CopyFrom(source).Transform(transform.GetLeapMatrix());
}
#endregion
}
}