-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathKinect-1.8.0.js
2229 lines (1878 loc) · 109 KB
/
Kinect-1.8.0.js
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 file="Kinect-1.8.0.js" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
//////////////////////////////////////////////////////////////
// Create the global Kinect object
var Kinect = (function () {
"use strict";
//////////////////////////////////////////////////////////////
// SocketManager object constructor
// SocketManager(uri, onmessage(socket,message) [, onconnection(isConnected)] )
//
// uri: URI of websocket endpoint to connect to
// onmessage: callback function to call whenever a message is received
// onconnection: function to call back whenever socket connection status changes
// from disconnected to connected or vice versa
function SocketManager(uri, onmessage, onconnection) {
//////////////////////////////////////////////////////////////
// Private SocketExec properties
var onStatusChanged = null;
var statusMessage = "";
var socket = null;
var socketManager = this;
var wsUri = uri.replace(/^http(s)?:/i, "ws$1:");
//////////////////////////////////////////////////////////////
// Private SocketExec methods
function updateStatusChanged() {
if (onStatusChanged != null) {
onStatusChanged(statusMessage);
}
}
function updateStatus(message) {
statusMessage = message;
updateStatusChanged();
}
function tryConnection() {
if (!socketManager.isStarted) {
return;
}
if (socket != null) {
updateStatus("Already connected." + (new Date()).toTimeString());
return;
}
updateStatus("Connecting to server...");
// Initialize a new web socket.
socket = new WebSocket(wsUri);
// Receive binary data as ArrayBuffer rather than Blob
socket.binaryType = "arraybuffer";
// Connection established.
socket.onopen = function () {
if (typeof onconnection == "function") {
onconnection(true);
}
updateStatus("Connected to server.");
};
// Connection closed.
socket.onclose = function () {
if (typeof onconnection == "function") {
onconnection(false);
}
updateStatus("Connection closed.");
if (socketManager.isStarted) {
// Keep trying to reconnect as long as we're started
setTimeout(tryConnection, socketManager.retryTimeout, socketManager);
}
socket = null;
};
// Receive data FROM the server!
socket.onmessage = function(message) {
onmessage(socket, message);
};
}
//////////////////////////////////////////////////////////////
// Public SocketManager properties
// connection retry timeout, in milliseconds
this.retryTimeout = 5000;
// true if socket has been started
this.isStarted = false;
//////////////////////////////////////////////////////////////
// Public SocketManager functions
this.setOnStatusChanged = function (statusChangedCallback) {
onStatusChanged = statusChangedCallback;
updateStatusChanged();
};
this.start = function() {
this.isStarted = true;
tryConnection(this);
};
this.stop = function() {
this.isStarted = false;
if (socket != null) {
socket.close();
}
};
//////////////////////////////////////////////////////////////
// SocketManager initialization code
if (window.WebSocket == null) {
updateStatus("Your browser does not support web sockets!");
return;
}
}
//////////////////////////////////////////////////////////////
// KinectConnector object constructor
function KinectConnector() {
//////////////////////////////////////////////////////////////
// Private KinectConnector properties
// Configure default connection values
var DEFAULT_HOST_URI = "http://localhost";
var DEFAULT_HOST_PORT = 8181;
var DEFAULT_BASE_PATH = "Kinect";
var DEFAULT_SENSOR_NAME = "default";
// If connectionUri is null, it indicates that we're not connected yet
var connectionUri = null;
// If explicitDisconnect is true, it indicates that client has called
// "KinectConnector.disconnect" explicitly.
var explicitDisconnect = false;
// Mapping between sensor names and KinectSensor objects
var sensorMap = {};
// true if server requests to REST endpoint should be asynchronous
var asyncRequests = true;
var connector = this;
//////////////////////////////////////////////////////////////
// KinectSensor object constructor
// KinectSensor(baseEndpointUri, onconnection(sensor, isConnected))
//
// baseEndpointUri: base URI for web endpoints corresponding to sensor
// onconnection: Function to call back whenever status of connection to the
// server that owns this sensor changes from disconnected to
// connected or vice versa.
function KinectSensor(baseEndpointUri, onconnection) {
//////////////////////////////////////////////////////////////
// Private KinectSensor properties
// URI used to connect to endpoint used to configure sensor state
var stateEndpoint = baseEndpointUri + "/state";
// true if sensor connection to server is currently enabled, false otherwise
var isConnectionEnabled = false;
// Array of registered stream frame ready handlers
var streamFrameHandlers = [];
// Header portion of a two-part stream message that is still missing a binary payload
var pendingStreamFrame = null;
// Reference to this sensor object for use in internal functions
var sensor = this;
var streamSocketManager = new SocketManager(
baseEndpointUri + "/stream",
function(socket, message) {
//console.log(message);
function broadcastFrame(frame) {
for (var iHandler = 0; iHandler < streamFrameHandlers.length; ++iHandler) {
streamFrameHandlers[iHandler](frame);
}
}
if (message.data instanceof ArrayBuffer) {
if ((pendingStreamFrame == null) || (pendingStreamFrame.bufferLength != message.data.byteLength)) {
// Ignore any binary messages that were not preceded by a header message
console.log("Binary socket message received without corresponding header");
pendingStreamFrame = null;
return;
}
pendingStreamFrame.buffer = message.data;
broadcastFrame(pendingStreamFrame);
pendingStreamFrame = null;
} else if (typeof(message.data) == "string") {
pendingStreamFrame = null;
//try {
// Get the data in JSON format.
var frameData = JSON.parse(message.data);
// If message has a 'bufferLength' property, it means that this is a message header
// and we should wait for the binary payload before broadcasting this message.
if ("bufferLength" in frameData) {
pendingStreamFrame = frameData;
} else {
broadcastFrame(frameData);
}
//} catch(error) {
// console.log('Tried processing stream message, but failed with error: ' + error);
//}
} else {
// Ignore any messages of unexpected types.
console.log("Unexpected type for received socket message");
pendingStreamFrame = null;
return;
}
},
function(isConnected) {
// Use the existence of the stream channel connection to mean that a
// server exists and is ready to accept requests
sensor.isConnected = isConnected;
onconnection(sensor, isConnected);
});
// Array of registered event handlers
var eventHandlers = [];
var eventSocketManager = new SocketManager(baseEndpointUri + "/events", function(socket, message) {
// Get the data in JSON format.
var eventData = JSON.parse(message.data);
for (var iHandler = 0; iHandler < eventHandlers.length; ++iHandler) {
eventHandlers[iHandler](eventData);
}
});
// Registered hit test handler
var hitTestHandler = null;
var hitTestSocketManager = new SocketManager(baseEndpointUri + "/interaction/client", function (socket, message) {
// Get the data in JSON format.
var eventData = JSON.parse(message.data);
var id = eventData.id;
var name = eventData.name;
var args = eventData.args;
switch (name) {
case "getInteractionInfoAtLocation":
var handlerResult = null;
var defaultResult = { "isPressTarget": false, "isGripTarget": false };
if (hitTestHandler != null) {
try {
handlerResult = hitTestHandler.apply(sensor, args);
} catch(e) {
handlerResult = null;
}
}
socket.send(JSON.stringify({ "id": id, "result": ((handlerResult != null) ? handlerResult : defaultResult) }));
break;
case "ping":
socket.send(JSON.stringify({ "id": id, "result": true }));
break;
}
});
//////////////////////////////////////////////////////////////
// Private KinectSensor functions
// Perform ajax request
// ajax( method, uri, success(responseData) [, error(statusText)] )
//
// method: http method
// uri: target uri of ajax call
// requestData: data to send to uri as part of request (may be null)
// success: Callback function executed if request succeeds.
// error: Callback function executed if request fails (may be null)
function ajax(method, uri, requestData, success, error) {
if (!isConnectionEnabled) {
if (error != null) {
error("disconnected from server");
}
return;
}
var xhr = new XMLHttpRequest();
xhr.open(method, uri, asyncRequests);
xhr.onload = function (e) {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status == 200) {
success(JSON.parse(xhr.responseText));
} else if (error != null) {
error(xhr.statusText);
}
}
};
if (error != null) {
xhr.onerror = function (e) {
error(xhr.statusText);
};
}
xhr.send(requestData);
}
// Respond to changes in the connection enabled status
// onConnectionEnabledChanged( )
function onConnectionEnabledChanged() {
if (isConnectionEnabled && !streamSocketManager.isStarted) {
streamSocketManager.start();
} else if (!isConnectionEnabled && streamSocketManager.isStarted) {
streamSocketManager.stop();
}
}
// Respond to changes in the number of registered event handlers
// onEventHandlersChanged( )
function onEventHandlersChanged() {
if ((eventHandlers.length > 0) && !eventSocketManager.isStarted) {
eventSocketManager.start();
} else if ((eventHandlers.length == 0) && eventSocketManager.isStarted) {
eventSocketManager.stop();
}
}
// Respond to changes in the registered hit test handler
// onHitTestHandlerChanged( )
function onHitTestHandlerChanged() {
if ((hitTestHandler != null) && !hitTestSocketManager.isStarted) {
hitTestSocketManager.start();
} else if ((hitTestHandler == null) && hitTestSocketManager.isStarted) {
hitTestSocketManager.stop();
}
}
//////////////////////////////////////////////////////////////
// Public KinectSensor properties
this.isConnected = false;
//////////////////////////////////////////////////////////////
// Public KinectSensor functions
// Request current sensor configuration
// .getConfig( success(configData) [, error(statusText)] )
//
// success: Callback function executed if request succeeds.
// error: Callback function executed if request fails.
this.getConfig = function (success, error) {
if ((arguments.length < 1) || (typeof success != 'function')) {
throw new Error("first parameter must be specified and must be a function");
}
if ((arguments.length >= 2) && (typeof error != 'function')) {
throw new Error("if second parameter is specified, it must be a function");
}
ajax("GET", stateEndpoint, null,
function(response) { success(response); },
(error != null) ? function (statusText) { error(statusText); } : null
);
};
// Update current sensor configuration
// .postConfig( configData [, error(statusText [, data] )] )
//
// configData: New configuration property/value pairs to update
// for each sensor stream.
// error: Callback function executed if request fails.
// data parameter of error callback will be null if request
// could not be completed at all, but will be a JSON object
// giving failure details in case of semantic failure to
// satisfy request.
this.postConfig = function (configData, error) {
if ((arguments.length < 1) || (typeof configData != 'object')) {
throw new Error("first parameter must be specified and must be an object");
}
if ((arguments.length >= 2) && (typeof error != 'function')) {
throw new Error("if second parameter is specified, it must be a function");
}
ajax("POST", stateEndpoint, JSON.stringify(configData),
function(response) {
if (!response.success && (error != null)) {
error("semantic failure", response);
}
},
(error != null) ? function (statusText) { error(statusText); } : null
);
};
// Enable connections with server
// .connect()
this.connect = function () {
isConnectionEnabled = true;
onConnectionEnabledChanged();
onEventHandlersChanged();
onHitTestHandlerChanged();
};
// Disable connections with server
// .disconnect()
this.disconnect = function () {
isConnectionEnabled = false;
onConnectionEnabledChanged();
onEventHandlersChanged();
onHitTestHandlerChanged();
};
// Add a new stream frame handler.
// .addStreamFrameHandler( handler(streamFrame) )] )
//
// handler: Callback function to be executed when a stream frame is ready to
// be processed.
this.addStreamFrameHandler = function (handler) {
if (typeof(handler) != "function") {
throw new Error("first parameter must be specified and must be a function");
}
streamFrameHandlers.push(handler);
};
// Removes one (or all) stream frame handler(s).
// .removeStreamFrameHandler( [handler(streamFrame)] )] )
//
// handler: Stream frame handler callback function to be removed.
// If omitted, all stream frame handlers are removed.
this.removeStreamFrameHandler = function (handler) {
switch (typeof(handler)) {
case "undefined":
streamFrameHandlers = [];
break;
case "function":
var index = streamFrameHandlers.indexOf(handler);
if (index >= 0) {
streamFrameHandlers.slice(index, index + 1);
}
break;
default:
throw new Error("first parameter must either be a function or left unspecified");
}
};
// Add a new event handler.
// .addEventHandler( handler(event) )] )
//
// handler: Callback function to be executed when an event is ready to be processed.
this.addEventHandler = function (handler) {
if (typeof (handler) != "function") {
throw new Error("first parameter must be specified and must be a function");
}
eventHandlers.push(handler);
onEventHandlersChanged();
};
// Removes one (or all) event handler(s).
// .removeEventHandler( [handler(streamFrame)] )] )
//
// handler: Event handler callback function to be removed.
// If omitted, all event handlers are removed.
this.removeEventHandler = function (handler) {
switch (typeof (handler)) {
case "undefined":
eventHandlers = [];
break;
case "function":
var index = eventHandlers.indexOf(handler);
if (index >= 0) {
eventHandlers.slice(index, index + 1);
}
break;
default:
throw new Error("first parameter must either be a function or left unspecified");
}
onEventHandlersChanged();
};
// Set hit test handler.
// .setHitTestHandler( [handler(skeletonTrackingId, handType, x, y)] )] )
//
// handler: Callback function to be executed when interaction stream needs
// interaction information in order to adjust a hand pointer position
// relative to UI.
// If omitted, hit test handler is removed.
// - skeletonTrackingId: The skeleton tracking ID for which interaction
// information is being retrieved.
// - handType: "left" or "right" to represent hand type for which
// interaction information is being retrieved.
// - x: X-coordinate of UI location for which interaction information
// is being retrieved. 0.0 corresponds to left edge of interaction
// region and 1.0 corresponds to right edge of interaction region.
// - y: Y-coordinate of UI location for which interaction information
// is being retrieved. 0.0 corresponds to top edge of interaction
// region and 1.0 corresponds to bottom edge of interaction region.
this.setHitTestHandler = function (handler) {
switch (typeof (handler)) {
case "undefined":
case "function":
hitTestHandler = handler;
break;
default:
throw new Error("first parameter must be either a function or left unspecified");
}
onHitTestHandlerChanged();
};
}
//////////////////////////////////////////////////////////////
// Public KinectConnector properties
// Server connection defaults
this.DEFAULT_HOST_URI = DEFAULT_HOST_URI;
this.DEFAULT_HOST_PORT = DEFAULT_HOST_PORT;
this.DEFAULT_BASE_PATH = DEFAULT_BASE_PATH;
this.DEFAULT_SENSOR_NAME = DEFAULT_SENSOR_NAME;
// Supported stream names
this.INTERACTION_STREAM_NAME = "interaction";
this.USERVIEWER_STREAM_NAME = "userviewer";
this.BACKGROUNDREMOVAL_STREAM_NAME = "backgroundRemoval";
this.SKELETON_STREAM_NAME = "skeleton";
this.SENSORSTATUS_STREAM_NAME = "sensorStatus";
// Supported event categories and associated event types
this.USERSTATE_EVENT_CATEGORY = "userState";
this.PRIMARYUSERCHANGED_EVENT_TYPE = "primaryUserChanged";
this.USERSTATESCHANGED_EVENT_TYPE = "userStatesChanged";
this.SENSORSTATUS_EVENT_CATEGORY = "sensorStatus";
this.SENSORSTATUSCHANGED_EVENT_TYPE = "statusChanged";
//////////////////////////////////////////////////////////////
// Public KinectConnector methods
// Enable connections with server
// .connect( [ hostUri [, hostPort [, basePath ] ] ] )
//
// hostUri: URI for host that is serving Kinect data.
// Defaults to "http://localhost".
// hostPort: HTTP port from which Kinect data is being served.
// Defaults to 8181.
// basePath: base URI path for all endpoints that serve Kinect data.
// Defaults to "kinect".
this.connect = function (hostUri, hostPort, basePath) {
hostUri = (hostUri != null) ? hostUri : DEFAULT_HOST_URI;
hostPort = (hostPort != null) ? hostPort : DEFAULT_HOST_PORT;
basePath = (basePath != null) ? basePath : DEFAULT_BASE_PATH;
// Indicate we're now connected
connectionUri = hostUri + ":" + hostPort + "/" + basePath;
explicitDisconnect = false;
};
// Disable connections with server
// .disconnect()
this.disconnect = function () {
// stop all sensors currently tracked
for (var sensorKey in sensorMap) {
var sensor = sensorMap[sensorKey];
sensor.disconnect();
}
sensorMap = {};
// Indicate we're now disconnected
connectionUri = null;
explicitDisconnect = true;
};
// Gets an object representing a connection with a specific Kinect sensor.
// .sensor( [sensorName [, onconnection(sensor, isConnected)]] )
//
// sensorName: name used to refer to a specific Kinect sensor exposed by the server.
// Defaults to "default".
// onconnection: Function to call back whenever status of connection to the
// server that owns the sensor with specified name changes from
// disconnected to connected or vice versa.
//
// Remarks
// - If client has never called KinectConnector.connect or .disconnect, .connect() is
// called implicitly with default server URI parameters.
// - If client has explicitly called KinectConnector.disconnect, calling this method
// returns null.
// - If a non-null sensor is returned, it will already be in connected state (i.e.:
// there is no need to call KinectSensor.connect immediately after calling this
// method).
this.sensor = function (sensorName, onconnection) {
switch (typeof(sensorName)) {
case "undefined":
case "string":
break;
default:
throw new Error("first parameter must be a string or left unspecified");
}
switch (typeof (onconnection)) {
case "undefined":
// provide a guarantee to KinectSensor constructor that onconnection
// will exist and be a real function
onconnection = function() { };
break;
case "function":
break;
default:
throw new Error("second parameter must be a function or left unspecified");
}
if (explicitDisconnect) {
return null;
}
if (connectionUri == null) {
// If we're not connected yet, connect with default parameters
// when someone asks for a sensor.
this.connect();
}
sensorName = (sensorName != null) ? sensorName : DEFAULT_SENSOR_NAME;
// If sensor for specified name doesn't exist yet, create it
if (!sensorMap.hasOwnProperty(sensorName)) {
sensorMap[sensorName] = new KinectSensor(connectionUri + "/" + sensorName, onconnection);
// Start the sensors connected by default when they are requested
sensorMap[sensorName].connect();
}
return sensorMap[sensorName];
};
// Get whether server requests to REST endpoints should be asynchronous (true by default)
// .async()
//
// -------------------------------------------------------------------------------------
// Specify whether server requests to REST endpoints should be asynchronous
// .async( asyncRequests )
//
// isAsync: true if server requests to REST endpoints should be asynchronous
// false if server requests to REST endpoints should be synchronous
this.async = function(isAsync) {
if (typeof isAsync == 'undefined') {
return asyncRequests;
}
var newAsync = isAsync == true;
asyncRequests = newAsync;
};
}
// The global Kinect object is a singleton instance of our internal KinectConnector type
return new KinectConnector();
})();
//////////////////////////////////////////////////////////////
// Create the global Kinect UI factory object
var KinectUI = (function () {
"use strict";
//////////////////////////////////////////////////////////////
// KinectUIAdapter object constructor
function KinectUIAdapter() {
//////////////////////////////////////////////////////////////
// HandPointer object constructor
function HandPointer(trackingId, playerIndex, handType) {
//////////////////////////////////////////////////////////////
// Public HandPointer properties
this.trackingId = trackingId;
this.playerIndex = playerIndex;
this.handType = handType;
this.timestampOfLastUpdate = 0;
this.handEventType = "None";
this.isTracked = false;
this.isActive = false;
this.isInteractive = false;
this.isPressed = false;
this.isPrimaryHandOfUser = false;
this.isPrimaryUser = false;
this.isInGripInteraction = false;
this.captured = null;
this.x = 0.0;
this.y = 0.0;
this.pressExtent = 0.0;
this.rawX = 0.0;
this.rawY = 0.0;
this.rawZ = 0.0;
this.originalHandPointer = null;
this.updated = false;
//////////////////////////////////////////////////////////////
// Public HandPointer methods
// Get all DOM elements that this hand pointer has entered.
// .getEnteredElements()
this.getEnteredElements = function () {
var key = getHandPointerKey(this.trackingId, this.handType);
var data = internalHandPointerData[key];
if (data == null) {
return [];
}
return data.enteredElements;
};
// Determine whether this hand pointer is over the specified DOM element.
// .getIsOver( element )
//
// element: DOM element against which to check hand pointer position.
this.getIsOver = function (element) {
// Iterate over cached elements
var enteredElements = this.getEnteredElements();
for (var iElement = 0; iElement < enteredElements.length; ++iElement) {
if (enteredElements[iElement] === element) {
return true;
}
}
return false;
};
// Create a capture association between this hand pointer and the specified DOM
// element. This means that event handlers associated with element will receive
// events triggered by this hand pointer even if hand pointer is not directly
// over element.
// .capture( element )
//
// element: DOM element capturing hand pointer.
// If null, this hand pointer stops being captured and resumes normal
// event routing behavior.
this.capture = function (element) {
return captureHandPointer(this, element);
};
// Determine whether this hand pointer corresponds to the primary hand of the
// primary user.
// .getIsPrimaryHandOfPrimaryUser()
this.getIsPrimaryHandOfPrimaryUser = function () {
return this.isPrimaryUser && this.isPrimaryHandOfUser;
};
// Update this hand pointer's properties from the specified hand pointer received
// from the interaction stream.
// .update( streamHandPointer )
this.update = function (streamHandPointer) {
// save the stream hand pointer in case it has additional properties
// that clients might be interested in
this.originalHandPointer = streamHandPointer;
this.updated = true;
this.timestampOfLastUpdate = streamHandPointer.timestampOfLastUpdate;
this.handEventType = streamHandPointer.handEventType;
var pressedChanged = this.isPressed != streamHandPointer.isPressed;
this.isPressed = streamHandPointer.isPressed;
this.isTracked = streamHandPointer.isTracked;
this.isActive = streamHandPointer.isActive;
this.isInteractive = streamHandPointer.isInteractive;
var primaryHandOfPrimaryUserChanged = this.getIsPrimaryHandOfPrimaryUser() != (streamHandPointer.isPrimaryHandOfUser && streamHandPointer.isPrimaryUser);
this.isPrimaryHandOfUser = streamHandPointer.isPrimaryHandOfUser;
this.isPrimaryUser = streamHandPointer.isPrimaryUser;
var newPosition = interactionZoneToWindow({ "x": streamHandPointer.x, "y": streamHandPointer.y });
var positionChanged = !areUserInterfaceValuesClose(newPosition.x, this.x) ||
!areUserInterfaceValuesClose(newPosition.y, this.y) ||
!areUserInterfaceValuesClose(streamHandPointer.pressExtent, this.pressExtent);
this.x = newPosition.x;
this.y = newPosition.y;
this.pressExtent = streamHandPointer.pressExtent;
this.rawX = streamHandPointer.rawX;
this.rawY = streamHandPointer.rawY;
this.rawZ = streamHandPointer.rawZ;
return {
"pressedChanged": pressedChanged,
"primaryHandOfPrimaryUserChanged": primaryHandOfPrimaryUserChanged,
"positionChanged": positionChanged
};
};
}
//////////////////////////////////////////////////////////////
// ImageWorkerManager object constructor
// new ImageWorkerManager()
//
// Remarks
// Manages background thread work related to processing image
// stream frames to get them ready to be displayed in a canvas
// element.
function ImageWorkerManager() {
//////////////////////////////////////////////////////////////
// ImageMetadata object constructor
function ImageMetadata(imageCanvas) {
this.isProcessing = false;
this.canvas = imageCanvas;
this.width = 0;
this.height = 0;
}
//////////////////////////////////////////////////////////////
// Private ImageWorkerManager properties
var workerThread = null;
var imageMetadataMap = {};
//////////////////////////////////////////////////////////////
// Private ImageWorkerManager methods
function ensureInitialized() {
// Lazy-initialize web worker thread
if (workerThread == null) {
workerThread = new Worker(scriptRootURIPath + "KinectWorker-1.8.0.js");
workerThread.addEventListener("message", function (event) {
var imageName = event.data.imageName;
if (!imageMetadataMap.hasOwnProperty(imageName)) {
return;
}
var metadata = imageMetadataMap[imageName];
switch (event.data.message) {
case "imageReady":
// Put ready image data in associated canvas
var canvasContext = metadata.canvas.getContext("2d");
canvasContext.putImageData(event.data.imageData, 0, 0);
metadata.isProcessing = false;
break;
case "notProcessed":
metadata.isProcessing = false;
break;
}
});
}
}
//////////////////////////////////////////////////////////////
// Public ImageWorkerManager methods
// Send named image data to be processed by worker thread
// .processImageData(imageName, imageBuffer, width, height)
//
// imageName: Name of image to process
// imageBuffer: ArrayBuffer containing image data
// width: width of image corresponding to imageBuffer data
// height: height of image corresponding to imageBuffer data
this.processImageData = function (imageName, imageBuffer, width, height) {
ensureInitialized();
if (!imageMetadataMap.hasOwnProperty(imageName)) {
// We're not tracking this image, so no work to do
return;
}
var metadata = imageMetadataMap[imageName];
if (metadata.isProcessing || (width <= 0) || (height <= 0)) {
// Don't send more data to worker thread when we are in the middle
// of processing data already.
// Also, Only do work if image data to process is of the expected size
return;
}
metadata.isProcessing = true;
if ((width != metadata.width) || (height != metadata.height)) {
// Whenever the image width or height changes, update image tracking metadata
// and canvas ImageData associated with worker thread
var canvasContext = metadata.canvas.getContext("2d");
var imageData = canvasContext.createImageData(width, height);
metadata.width = width;
metadata.height = height;
metadata.canvas.width = width;
metadata.canvas.height = height;
workerThread.postMessage({ "message": "setImageData", "imageName": imageName, "imageData": imageData });
}
workerThread.postMessage({ "message": "processImageData", "imageName": imageName, "imageBuffer": imageBuffer });
};
// Associate specified image name with canvas ImageData object for future usage by
// worker thread
// .setImageData(imageName, canvas)
//
// imageName: Name of image stream to associate with ImageData object
// canvas: Canvas to bind to user viewer stream
this.setImageData = function (imageName, canvas) {
ensureInitialized();
if (canvas != null) {
var metadata = new ImageMetadata(canvas);
imageMetadataMap[imageName] = metadata;
} else if (imageMetadataMap.hasOwnProperty(imageName)) {
// If specified canvas is null but we're already tracking image data,
// remove metadata associated with this image.
delete imageMetadataMap[imageName];
}
};
}
//////////////////////////////////////////////////////////////
// Private KinectUIAdapter constants
var LAZYRELEASE_RADIUS = 0.3;
var LAZYRELEASE_YCUTOFF = LAZYRELEASE_RADIUS / 3;
//////////////////////////////////////////////////////////////
// Private KinectUIAdapter properties
var uiAdapter = this;
var isInInteractionFrame = false;
var isClearRequestPending = false;
var handPointerEventsEnabled = true;
// Property names of internalHandPointerData are keys that encode user tracking id and hand type.
// Property values are JSON objects with "handPointer" and "enteredElements" properties.
var internalHandPointerData = {};
var excludedElements = [];
var eventHandlers = {};
var bindableStreamNames = {};
bindableStreamNames[Kinect.USERVIEWER_STREAM_NAME] = true;
bindableStreamNames[Kinect.BACKGROUNDREMOVAL_STREAM_NAME] = true;
var imageWorkerManager = new ImageWorkerManager();
//////////////////////////////////////////////////////////////
// Private KinectUIAdapter methods
function interactionZoneToElement(point, element) {
return { "x": point.x * element.offsetWidth, "y": point.y * element.offsetHeight };
}
function elementToInteractionZone(point, element) {
return { "x": point.x / element.offsetWidth, "y": point.y / element.offsetHeight };
}
function interactionZoneToWindow(point) {
return { "x": point.x * window.innerWidth, "y": point.y * window.innerHeight };
}
function windowToInteractionZone(point) {
return { "x": point.x / window.innerWidth, "y": point.y / window.innerHeight };
}
function areUserInterfaceValuesClose(a, b) {
return Math.abs(a - b) < 0.5;
}
function getPressTargetPoint(element) {
// Hardcoded to always return the center point
return { "x": 0.5, "y": 0.5 };
}
function getHandPointerKey(trackingId, handType) {
return handType + trackingId;
}
function createInteractionEvent(eventName, detail) {
var event = document.createEvent("CustomEvent");
var canBubble = true;
var cancelable = false;
switch (eventName) {
case uiController.HANDPOINTER_ENTER:
case uiController.HANDPOINTER_LEAVE:
canBubble = false;
break;
}
event.initCustomEvent(eventName, canBubble, cancelable, detail);
return event;
}
function raiseHandPointerEvent(element, eventName, handPointer) {
if (!handPointerEventsEnabled) {