-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathinpoot.js
3221 lines (2499 loc) · 126 KB
/
inpoot.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
/**
* inpoot.js
* @author john martin / [email protected] / johndavidfive.com
* Accepts a list of actions and number of max players and other options
* Provides an optional UI to allow the user to configure keyboard / mouse / gamepad inputs to those actions
* Provides an api to gather input values that are mapped to the configured actions
*/
/*global alert, console*/
//the namespace
var inpoot = {};
(function($) {
"use strict";
//========================================================================================================
// INITIALIZATION, GLOBAL VARIABLES, AND ACTUAL GAME LOOP FUNCTIONALITY
//========================================================================================================
/*======== SOME CROSS BROWSER LOGIC FROM GAMEPAD.JS ========*/
var contains = function(lookIn, forWhat) { return lookIn.indexOf(forWhat) !== -1; };
var userAgent = navigator.userAgent;
var isWindows = contains(userAgent, 'Windows NT');
var isMac = contains(userAgent, 'Macintosh');
var isChrome = contains(userAgent, 'Chrome/');
var isFirefox = contains(userAgent, 'Firefox/');
var currentKeyboard = {};
if (isFirefox) {
// todo; current moz nightly does not define this, so we'll always
// return true for .supported on that Firefox.
navigator.mozGamepads = [];
var mozConnectHandler = function(e) {
navigator.mozGamepads[e.gamepad.index] = e.gamepad;
};
var mozDisconnectHandler = function(e) {
navigator.mozGamepads[e.gamepad.index] = undefined;
};
window.addEventListener("MozGamepadConnected", mozConnectHandler);
window.addEventListener("MozGamepadDisconnected", mozDisconnectHandler);
}
var mapPad = function(raw) {
for (var gpadType in inpoot.gamepads) {
var entry = inpoot.gamepads[gpadType];
var idMatches = entry.idMatches;
for(var j=0; j < idMatches.length; j++){
var thisMatch = idMatches[j];
var isMatch = true;
for (var k=0; k < thisMatch.length; k++){
if (!contains(raw.id, thisMatch[k])) {
isMatch = false;
}
}
if(isMatch) {
raw.displayName = entry.displayName;
raw.gpadType = gpadType;
return;
}
}
}
raw.gpadType = raw.id;
raw.displayName = "Unknown gamepad";
};
/*======== ADDITIONAL GLOBALS ========*/
var gamepads = {};
var actions = {}; //just the actions... need to be passed in during initalization
var gamepadmaps = {}; //object containing configurations for gamepad types
var lastState = {}; // a copy of the current state used for changes
var currentState = {}; //holds event driven key state (keyboard mostly / mouse)
var uiOpen = false; //this flag helps the plugin stop tick events except for internal use when the UI is open
var mouseMoved = 0; //a flag to help us with tracking the mouse values
var defaultPlayers = false; //if the user sends these in during initalization or externally we want to hold on to them in case inpoot.resetConfigs is called
var defaultMappings = false; //if the user sends these in during initalization or externally we want to hold on to them in case inpoot.resetConfigs is called
//here are some values that can be set publicly
var maxPlayers = 1; //by default you have to have one player
var mouseNormalizer; //number of pixels that max out the mouse input to 1
// Current Inputs
var CI = {
'mouse':{},
'keyboard' : {},
'gamepad' : {}
};
// Last Inputs
var LI = {};
/*========= LISTENER DRIVEN FUNCTIONS ========*/
var onKeyDown = function (e) {
currentKeyboard[e.keyCode] = 1;
};
var onKeyUp = function (e) {
currentKeyboard[e.keyCode] = 0;
};
var mousemap = {
1 : 'mouse_button_left',
2 : 'mouse_button_middle',
3 : 'mouse_button_right'
};
var onMouseDown = function (e) {
CI['mouse'][mousemap[e.which]] = 1;
};
var onMouseUp = function (e) {
CI['mouse'][mousemap[e.which]] = 0;
};
var onMouseMove = function (e) {
//set the mouse move flag to 0
mouseMoved = 0;
var movementX = e.movementX ||
e.mozMovementX ||
e.webkitMovementX || 0;
var movementY = e.movementY ||
e.mozMovementY ||
e.webkitMovementY || 0;
//If we get these then let's use them (a must when pointer lock is on)
if(movementX || movementY){
CI['mouse']['mouseDX'] = movementX;
CI['mouse']['mouseDY'] = movementY;
} else {
CI['mouse']['mouseXL'] = CI['mouse']['mouseX'];
CI['mouse']['mouseYL'] = CI['mouse']['mouseY'];
CI['mouse']['mouseX'] = ( e.clientX / window.innerWidth ) * 2 - 1;
CI['mouse']['mouseY'] = ( e.clientY / window.innerHeight ) * 2 - 1;
CI['mouse']['mouseDX'] = CI['mouse']['mouseX'] - CI['mouse']['mouseXL'];
CI['mouse']['mouseDY'] = CI['mouse']['mouseY'] - CI['mouse']['mouseYL'];
}
};
//this just returns the raw gamepad objects
var getRawPads = function () {
var gamepadsPoll = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : (navigator.mozGetGamepads ? navigator.mozGetGamepads() : []));
window.gyayer = gamepadsPoll;
return gamepadsPoll;
};
//this is used if you want to return an array of active gamepads (somewhat filtered with added attributes)
var getGamePads = function () {
var gamePadList = [];
var tempList = getRawPads();
var count = 0;
for (var gpad in tempList) {
if(tempList[gpad] && gpad !== "length" && tempList.hasOwnProperty(gpad)){
count++;
//attach some details to the gamepad object
mapPad(tempList[gpad]);
//push it in our own stack of gamepads
gamePadList.push({
player: count,
gamepad: tempList[gpad],
gamepadIndex: gpad
});
//here we set up the basis for our current object
if(!CI['gamepad'][gpad]){
CI['gamepad'][gpad] = {
type: tempList[gpad].gpadType,
values: {}
};
}
}
}
return gamePadList;
};
/*========= INITIALIZATION ========*/
inpoot.initialize = function (options) {
//setup listeners
document.onkeydown = onKeyDown;
document.onkeyup = onKeyUp;
document.onmousemove = onMouseMove;
document.onmousedown = onMouseDown;
document.onmouseup = onMouseUp;
//detect gamepads
gamepads = getGamePads();
//get the actions
actions = options.actions;
//number of players
maxPlayers = options.maxPlayers || 1;
//mouse normalization factor
mouseNormalizer = options.mouseNormalizer || 3;
//grab the gamepad type maps from local storage
gamepadmaps = $.storage.getObject('gamepadmaps') || {};
//check to see if we have default mapping and if we need to set it
if(options.mappings && $.storage.getObject('inpoot_action_mappings') === null){
inpoot.setMappings(options.mappings);
}
//check to see if we have default player -> action mappings
if(options.players && $.storage.getObject('inpoot_stored_players') === null){
inpoot.setPlayers(options.players);
}
};
//support function to map gamepad raw inputs to stored gamepad type buttons
var updateGpadTypeMaps = function() {
gamepadmaps = $.storage.getObject('gamepadmaps') || {};
};
var getGPadTypeMapping = function (gpadType, inputType, inputIndex) {
return gamepadmaps[gpadType] ? gamepadmaps[gpadType].rawToButton[inputType][inputIndex] : false;
};
var getGamePadText = function (gpadType, buttonType, key) {
var gpadConfigs = getGamepadConfigurations(gpadType);
return gpadConfigs[buttonType][key].name || key;
};
var getGamePadInputInfo = function (gpadType, key, value) {
var refToAxisMap = gamepadmaps[gpadType].rawToButton.axesMap[key],
text;
if(!refToAxisMap) {
text = getGamePadText(gpadType, 'button', key);
var refToInfo = gamepadmaps[gpadType].rawToButton['buttons'][key];
return {
text: text,
value: key,
buttonType:'button',
subType: ''
};
} else {
text = getGamePadText(gpadType, 'axis_dual', refToAxisMap.bid);
var direction = refToAxisMap.subType == "y" ? (value <= 0 ? "down" : "up") : (value > 0 ? "right" : "left");
return {
text: text + ' ' + refToAxisMap.direction,
value: refToAxisMap.bid,
buttonType:'axis_dual',
subType: refToAxisMap.subType,
direction: refToAxisMap.direction
};
}
};
//Call this to scan all actions and update state
var tickInterval = 0;
//Here is a flag that is used to determine if we need to update the players and mappings used in action mapping (used internally mostly)
var refreshParamsFlag = false; //this is set to true internally if we need to refresh mappings
inpoot.refreshParams = function () {
refreshParamsFlag = true;
};
//this is the deadzone radius for gamepad axes (sometimes gamepads by default are worn down and axes can get stuck in an "on" position)
var threshold = 0.07;
inpoot.setThreshold = function (newThreshold) {
threshold = newThreshold;
};
//the main area to scan all inputs (note this is really only for gamegpads because mouse and keyboard mapping is done through browser events)
inpoot.tick = function (permission) {
//if the UI is open then we want to reserve ticks for the UI
if(uiOpen && !permission){return;}
//first check if the mouse has been idle so we can kill old values
mouseMoved++;
if(mouseMoved > 1){
CI['mouse']['mouseDX'] = 0;
CI['mouse']['mouseDY'] = 0;
}
//copy CI into LI
LI = $.extend(true, {}, CI);
//to allow for keypressed we need to take a snapshot from the currentKeyboard
CI.keyboard = $.extend(true, {}, currentKeyboard);
//we only need to get the gamepads every 10000 ticks or so (in case they turn one on later)
if(tickInterval === 0) {
gamepads = getGamePads();
updateActionLoopInfo();
}
//move our interval forward
tickInterval = (tickInterval + 1) % 1000;
//if this flag is set force the tickInterval to 0 so we get new references to player and action mappings
if (refreshParamsFlag) {
tickInterval = 0;
refreshParamsFlag = false;
}
//get the newly updated stuff
var rawPads = getRawPads();
//now search all gamepads (right now it is just buttons and axes)
for(var i=0; i < gamepads.length; i++){
var thisG = gamepads[i];
var rawDog = rawPads[thisG.gamepadIndex];
if (rawDog && rawDog.gpadType) {
//look at all buttons
for (var j = 0; j < rawDog.buttons.length; j++) {
try {
CI['gamepad'][thisG.gamepadIndex].values[getGPadTypeMapping(rawDog.gpadType, 'buttons', j).bid] = rawDog.buttons[j].value;
} catch (e) {}
}
//look at all axis
for (var k = 0; k < rawDog.axes.length; k++) {
var thisGMap = getGPadTypeMapping(rawDog.gpadType, 'axes', k);
var absValue = Math.abs(rawDog.axes[k]);
var threshValue = absValue > threshold ? absValue : 0;
if(thisGMap.subType === 'x'){
if(rawDog.axes[k] <= 0){
CI['gamepad'][thisG.gamepadIndex].values[thisGMap.bid + 'left'] = threshValue;
CI['gamepad'][thisG.gamepadIndex].values[thisGMap.bid + 'right'] = 0;
} else {
CI['gamepad'][thisG.gamepadIndex].values[thisGMap.bid + 'left'] = 0;
CI['gamepad'][thisG.gamepadIndex].values[thisGMap.bid + 'right'] = threshValue;
}
} else {
if(rawDog.axes[k] <= 0){
CI['gamepad'][thisG.gamepadIndex].values[thisGMap.bid + 'up'] = threshValue;
CI['gamepad'][thisG.gamepadIndex].values[thisGMap.bid + 'down'] = 0;
} else {
CI['gamepad'][thisG.gamepadIndex].values[thisGMap.bid + 'up'] = 0;
CI['gamepad'][thisG.gamepadIndex].values[thisGMap.bid + 'down'] = threshValue;
}
}
}
}
}
//not really needed but great for debugging
return CI;
};
var actionPolls = 0;
var playerMap = {};
var actionMaps = {};
var actionMapIdMap = {};
//a utility function to update all the global references to players and action maps
var updateActionLoopInfo = function () {
//first the player maps
playerMap = {};
var allPlayers = $.storage.getObject('inpoot_stored_players');
for(var playa in allPlayers) {
var thisPlaya = allPlayers[playa];
//set up the basics
playerMap[thisPlaya.number] = {
actionMapId : thisPlaya.actionMapId,
gamepad: thisPlaya.gamepad,
gamepadIndex: thisPlaya.options.gpadIndex,
invert : thisPlaya.options.axes
};
}
//actionMaps
actionMaps = $.storage.getObject('inpoot_action_mappings');
//then a map from actionMapId to the array position
for(var i=0; i < actionMaps.length; i++){
actionMapIdMap[actionMaps[i].id] = i;
}
};
//IMPORTANT: This is the main function developers will use to get action values. Was this action pressed? What is the current value? Delta?
inpoot.action = function (action, pNum, options) {
options = options || {};
//pNum is 1 by default if you don't include it
pNum = pNum || 1;
//the default values for the return values of this action
var returnObj = {
pressed: 0,
delta: 0,
val: 0
};
var thisPlayer = playerMap[pNum];
var actionRef, currentVal, oldVal;
if (thisPlayer && actionMaps[actionMapIdMap[thisPlayer.actionMapId]] && (actionRef = actionMaps[actionMapIdMap[thisPlayer.actionMapId]].mapping[action])) {
var theseInputs = actionRef.inputs || [];
for(var j=0; j < theseInputs.length; j++){
for(var k=0; k < theseInputs[j].inputs.length; k++){
if(theseInputs[j].inputs[k].type == "keyboard") {
if(CI['keyboard'][theseInputs[j].inputs[k].value] === undefined) {
CI['keyboard'][theseInputs[j].inputs[k].value] = 0;
}
currentVal = CI['keyboard'][theseInputs[j].inputs[k].value];
oldVal = LI['keyboard'][theseInputs[j].inputs[k].value];
returnObj.val = currentVal;
returnObj.pressed = !currentVal && oldVal;
returnObj.delta = currentVal - oldVal;
if(returnObj.pressed && options.clear){
CI['keyboard'][theseInputs[j].inputs[k].value] = 0;
LI['keyboard'][theseInputs[j].inputs[k].value] = 0;
}
} else if (theseInputs[j].inputs[k].type == "gamepad") {
if (CI['gamepad'][thisPlayer.gamepadIndex] !== false && CI['gamepad'][thisPlayer.gamepadIndex] !== undefined) {
if (theseInputs[j].inputs[k].buttonType == "axis_dual") {
//is this action inverted?
if(thisPlayer.invert && thisPlayer.invert[theseInputs[j].inputs[k].value] && (theseInputs[j].inputs[k].direction == "up" || theseInputs[j].inputs[k].direction == "down")){
if(theseInputs[j].inputs[k].direction == "up"){
currentVal = CI['gamepad'][thisPlayer.gamepadIndex].values[theseInputs[j].inputs[k].value + "down"];
oldVal = LI['gamepad'][thisPlayer.gamepadIndex] ? LI['gamepad'][thisPlayer.gamepadIndex].values[theseInputs[j].inputs[k].value + "down"] : 0;
} else {
currentVal = CI['gamepad'][thisPlayer.gamepadIndex].values[theseInputs[j].inputs[k].value + "up"];
oldVal = LI['gamepad'][thisPlayer.gamepadIndex] ? LI['gamepad'][thisPlayer.gamepadIndex].values[theseInputs[j].inputs[k].value + "up"] : 0;
}
} else {
currentVal = CI['gamepad'][thisPlayer.gamepadIndex].values[theseInputs[j].inputs[k].value + theseInputs[j].inputs[k].direction];
oldVal = LI['gamepad'][thisPlayer.gamepadIndex] ? LI['gamepad'][thisPlayer.gamepadIndex].values[theseInputs[j].inputs[k].value + theseInputs[j].inputs[k].direction] : 0;
}
returnObj.val = currentVal;
returnObj.pressed = !currentVal && oldVal;
returnObj.delta = currentVal - oldVal;
if(returnObj.pressed && options.clear){
CI['gamepad'][thisPlayer.gamepadIndex].values[theseInputs[j].inputs[k].value + theseInputs[j].inputs[k].direction] = 0;
LI['gamepad'][thisPlayer.gamepadIndex].values[theseInputs[j].inputs[k].value + theseInputs[j].inputs[k].direction] = 0;
}
} else {
currentVal = CI['gamepad'][thisPlayer.gamepadIndex].values[theseInputs[j].inputs[k].value];
oldVal = LI['gamepad'][thisPlayer.gamepadIndex] ? LI['gamepad'][thisPlayer.gamepadIndex].values[theseInputs[j].inputs[k].value] : 0;
returnObj.val = currentVal;
returnObj.pressed = !currentVal && oldVal;
returnObj.delta = currentVal - oldVal;
if(returnObj.pressed && options.clear){
CI['gamepad'][thisPlayer.gamepadIndex].values[theseInputs[j].inputs[k].value] = 0;
LI['gamepad'][thisPlayer.gamepadIndex].values[theseInputs[j].inputs[k].value] = 0;
}
}
}
} else if (theseInputs[j].inputs[k].type == "mouse") {
if(theseInputs[j].inputs[k].value == "mouse_up"){
currentVal = CI['mouse']['mouseDY'] < 0 ? Math.min(Math.abs(CI['mouse']['mouseDY']) / mouseNormalizer,1) : 0;
oldVal = LI['mouse']['mouseDY'] < 0 ? Math.min(Math.abs(CI['mouse']['mouseDY']) / mouseNormalizer,1) : 0;
} else if (theseInputs[j].inputs[k].value == "mouse_down") {
currentVal = CI['mouse']['mouseDY'] >= 0 ? Math.min(CI['mouse']['mouseDY'] / mouseNormalizer,1) : 0;
oldVal = LI['mouse']['mouseDY'] >= 0 ? Math.min(CI['mouse']['mouseDY'] / mouseNormalizer,1) : 0;
} else if (theseInputs[j].inputs[k].value == "mouse_left") {
currentVal = CI['mouse']['mouseDX'] < 0 ? Math.min(Math.abs(CI['mouse']['mouseDX']) / mouseNormalizer,1) : 0;
oldVal = LI['mouse']['mouseDX'] < 0 ? Math.min(Math.abs(CI['mouse']['mouseDX']) / mouseNormalizer,1) : 0;
} else if (theseInputs[j].inputs[k].value == "mouse_right") {
currentVal = CI['mouse']['mouseDX'] >= 0 ? Math.min(CI['mouse']['mouseDX'] / mouseNormalizer,1) : 0;
oldVal = LI['mouse']['mouseDX'] >= 0 ? Math.min(CI['mouse']['mouseDX'] / mouseNormalizer,1) : 0;
} else {
currentVal = CI['mouse'][theseInputs[j].inputs[k].value];
oldVal = LI['mouse'][theseInputs[j].inputs[k].value];
}
returnObj.val = currentVal;
returnObj.pressed = !currentVal && oldVal;
returnObj.delta = currentVal - oldVal;
}
}
}
}
//make sure that the val is 0 at minimum
if(!returnObj.val){
returnObj.val = 0;
}
if(!returnObj.pressed){
returnObj.pressed = 0;
}
if(!returnObj.delta){
returnObj.delta = 0;
}
return returnObj;
};
//========================================================================================================
// OTHER PUBLIC API METHODS
//========================================================================================================
/*========= RESET THE DEFAULT PLAYER AND MAPPING CONFIGURSTIONS ========*/
//If they were passed in we will overwrite any modifications to use the defaults passed in during initialization
inpoot.resetConfigs = function () {
if(defaultPlayers){
inpoot.setPlayers(defaultPlayers);
}
if(defaultMappings){
inpoot.setMappings(defaultMappings);
}
};
/*========= GET AND SET MAPPINGS (great for protecting your mappings and hardcoding them) ========*/
//This method is useful for copying your mappings as a developer so you can hard code them when you are done setting up initial mappings
inpoot.getMappings = function () {
var allMappings = $.storage.getObject('inpoot_action_mappings');
return JSON.stringify(allMappings);
};
//If you have hardcoded the mappings for your users then call this or pass it in during initialization as "mappings"
inpoot.setMappings = function (mappingInfo) {
if(typeof(mappingInfo) == 'string'){
mappingInfo = JSON.parse(mappingInfo);
}
defaultMappings = mappingInfo;
$.storage.setObject('inpoot_action_mappings', mappingInfo);
};
/*========= GET AND SET PLAYER CONFIGS (great for protecting your player options so you can hard code them) ========*/
//This method is useful for copying your player mappings/options as a developer so you can hard code them when you are done setting up player mappings
inpoot.getPlayers = function () {
var splayers = $.storage.getObject('inpoot_stored_players');
return JSON.stringify(splayers);
};
//If you have hardcoded the player configs for your users then call this or pass it in during initialization as "players"
inpoot.setPlayers = function (playerInfo) {
if(typeof(playerInfo) == 'string'){
playerInfo = JSON.parse(playerInfo);
}
defaultPlayers = playerInfo;
$.storage.setObject('inpoot_stored_players', playerInfo);
};
/*========= WEB SERVICE BASED API (Ways to get gamepad configurations from a remote repository) ========*/
//call this if you want the plugin to go search online for gamepad configurations for this browser/os combination
inpoot.getRemoteGamepadConfigs = function() {};
//========================================================================================================
// BELOW IS CODE FOR THE UI FOR MANAGING ACTION MAPPING AND PLAYER ASSIGNMENTS
//========================================================================================================
/*========= GAME PAD MAPPINGS (GAMEPAD BUTTONS => REPORTED BUTTON/AXES NUMBERS) ========*/
//generates a new mapping
var generateBlankGpadMap = function (gpadType) {
var padConfigs = inpoot.gamepads[gpadType];
var blankMap = {
'buttonToRaw':{button:{}, axis:{}, axis_dual:{}},
'rawToButton' : {buttons:{}, axes:{}, axesMap:{}}
};
if(!padConfigs){
alert('We do not have configurations stored for this type of gamepad:' + gpadType);
return;
}
for(var button in padConfigs.button){
blankMap['buttonToRaw']['button'][button] = false;
}
for(var axis in padConfigs.axis_dual){
blankMap['buttonToRaw']['axis_dual'][axis] = {x:false, y:false};
}
return blankMap;
};
//note gamepadmaps was populated from local storage during initialization()
var getGamepadMapping = function (gpadType) {
var gpadMap = gamepadmaps[gpadType];
if (!gpadMap) {
gpadMap = generateBlankGpadMap(gpadType);
if (!gpadMap) {
return false;
} else {
gamepadmaps[gpadType] = gpadMap;
$.storage.setObject('gamepadmaps', gamepadmaps);
return gpadMap;
}
} else {
return gpadMap;
}
};
//get just the stored button configuration for the gamepad
var getGamepadConfigurations = function (gpadType) {
return inpoot.gamepads[gpadType];
};
//quick function to save a copy of the current gamepadmaps into local storage
var saveGamepadMapping = function () {
$.storage.setObject('gamepadmaps', gamepadmaps);
};
/*========= MAIN MENU ========*/
var launch_main = function () {
//behavior for this view
var mainPP = function (item) {
var uiNode = $(item.nodes[0]);
uiNode.find('.inpoot-main-option.players').click(function(){
launch_players();
});
uiNode.find('.inpoot-main-option.settings').click(function(){
launch_calibrate();
});
uiNode.find('.inpoot-main-option.mappings').click(function(){
launch_mappings();
});
};
//render the content and add behavior
inpoot.utils.modal.show({template:'inpoot.main-content', data:{}, behavior: mainPP});
};
/*========= ACTION MAPPINGS menu ========*/
//get gamepadMapping uuid
var getNewActionMapId = function () {
var allActionMappings = getAllActionMappings();
var highest = -1;
for(var i=0; i < allActionMappings.length; i++){
if(highest < allActionMappings[i].id) {
highest = allActionMappings[i].id;
}
}
return highest + 1;
};
var getAllActionMappings = function (actionMapId) {
var allActionMappings = $.storage.getObject('inpoot_action_mappings');
if(!allActionMappings){
allActionMappings = [];
$.storage.setObject('inpoot_action_mappings', allActionMappings);
}
if(actionMapId === undefined || actionMapId === null){
return allActionMappings;
} else {
for(var i=0; i < allActionMappings.length; i++){
if(allActionMappings[i].id == actionMapId) {
return allActionMappings[i];
}
}
}
};
var deleteActionMap = function (actionMapId) {
var allActionMappings = getAllActionMappings();
for(var i=0; i < allActionMappings.length; i++){
if(allActionMappings[i].id == actionMapId) {
allActionMappings.splice(i,1);
$.storage.setObject('inpoot_action_mappings', allActionMappings);
}
}
};
var getNewActionMap = function () {
//make a copy of the actions TODO: use a copy of default mapping...
var newActionMap = $.extend({},actions);
return newActionMap;
};
//this view allows a user to edit a set of action mappings
var launch_edit_action_map = function (actionMapId) {
//let's make sure we update the mappings
updateGpadTypeMaps();
//first get all the mappings
var thisActionMap = getAllActionMappings(actionMapId);
var storedGamepads = $.storage.getObject('storedGamepads') || [];
//save changes to this map
var saveActionMap = function () {
var allActionMappings = getAllActionMappings();
for(var i=0; i < allActionMappings.length; i++) {
if(allActionMappings[i].id == actionMapId){
allActionMappings[i] = thisActionMap;
$.storage.setObject('inpoot_action_mappings', allActionMappings);
}
}
};
//the behavior for this view
var actionMapPP = function (item) {
var uiNode = $(item.nodes[0]);
var thisActionMap = item.data.actionMap;
//when they click back in this view send them back to the main menu
uiNode.find('.inpoot-top-option').click(launch_mappings);
//add this sweet @$$ new editing behavior to this item
uiNode.find('.inpoot-main-gamepad-options-message input').inpootEdit({
onChange: function(newValue){
thisActionMap.name = newValue;
saveActionMap();
},
defaultText : 'New Mapping'
});
//setup the gamepad options
var gamepadOptions = [{text: 'OFF', value: 'false', style: 'off', message:'Warning, this will remove all mappings that currently use the gamepad'}];
for(var i=0; i < storedGamepads.length; i++){
gamepadOptions.push({
text: storedGamepads[i].displayName,
value: storedGamepads[i].gpadType,
style: 'on',
message: 'Switching gamepads will remove all mappings from other gamepads',
ifNot:['false']
});
}
//setup the styled select containers
inpoot.utils.styledSelect({
container: $('.inpoot-input-selector.keyboard'),
selected: thisActionMap.keyboard,
options: [
{text: 'ON', value: 'true', style: 'on'},
{text: 'OFF', value: 'false', style: 'off', message:'Warning, this will remove all mappings that currently use the keyboard'}
],
callBack: function (newSelected) {thisActionMap.keyboard = newSelected.value; saveActionMap();}
});
inpoot.utils.styledSelect({
container: $('.inpoot-input-selector.mouse'),
selected: thisActionMap.mouse,
options : [
{text: 'ON', value: 'true', style: 'on'},
{text: 'OFF', value: 'false', style: 'off', message:'Warning, this will remove all mappings that currently use the mouse'}
],
callBack: function (newSelected) {thisActionMap.mouse = newSelected.value; saveActionMap();}
});
inpoot.utils.styledSelect({
container: $('.inpoot-input-selector.gamepad'),
selected: thisActionMap.gamepad,
options: gamepadOptions,
callBack: function (newSelected) {thisActionMap.gamepad = newSelected.value; saveActionMap();}
});
//==== NOW WE SETUP THE EDITING FOR THE MAPPINGS ====
//get a new input combination Id
var getNewInputCombinationId = function (inputs) {
var highest = -1;
for(var i=0; i < inputs.length; i++){
if(highest < inputs[i].id) {
highest = inputs[i].id;
}
}
return highest + 1;
};
//delete an input combination by actionId and mapId
var deleteInputCombination = function (actionId, mapId, callBack) {
var allInputs = thisActionMap.mapping[actionId].inputs;
var foundIndex = -1;
for(var i=0; i < allInputs.length; i++){
if(allInputs[i].id == mapId){
foundIndex = i;
break;
}
}
if(foundIndex != -1){
//slice and save
allInputs.splice(foundIndex,1);
saveActionMap();
callBack();
}
};
//get a specified input combination
var getInputCombination = function (allInputs, mapId) {
for(var i=0; i < allInputs.length; i++){
if(allInputs[i].id == mapId){
return allInputs[i];
}
}
};
//behavior for the mappings listed for an action
var drawMapPP = function (item) {
var drawNode = $(item.nodes[0]);
};
//a draw method to refresh the right side with current list of mappings
var drawMappings = function (actionId) {
$.tmpl('inpoot.action_map.action_list_mappings',thisActionMap, {rendered:drawMapPP}).appendTo($('.inpoot-map-form-right-inner').html(''));
};
//the logic to support live mapping
var startLiveMapping = function (item) {
var liveNode = $(item.nodes[0]);
var liveNodeData = item.data;
var gamepadArea = liveNode.find('.inpoot-edit-mapping-gather-inputs.gamepad');
var gamepadList = gamepadArea.find('.inpoot-edit-mapping-gather-input-list');
var keyboardArea = liveNode.find('.inpoot-edit-mapping-gather-inputs.keyboard');
var keyboardList = keyboardArea.find('.inpoot-edit-mapping-gather-input-list');
var mouseArea = liveNode.find('.inpoot-edit-mapping-gather-inputs.mouse');
var mouseList = mouseArea.find('.inpoot-edit-mapping-gather-input-list');
var actionMap = liveNodeData.actionMap;
var actionId = liveNodeData.actionId;
//first let's indicate visually that we are editing
$('.inpoot-map-form').addClass('editing');
//wire up the close edit button
$('.inpoot-editing-inputs-close').unbind('click').click(function(){
//then remove editing class
$('.inpoot-map-form').removeClass('editing');
//and redraw the originals
editAction(liveNodeData.actionId);
});
//when x'ed out, then we delete it.
var deleteInput = function (type, inputInfo) {
var allInputs = thisActionMap.mapping[actionId].inputs;
var thisMapId = liveNodeData.mapId;
var foundIndex = -1;
for(var i=0; i < allInputs.length; i++){
if(allInputs[i].id == thisMapId){
foundIndex = i;
break;
}
}
if(foundIndex != -1){
var thisInputCombination = allInputs[foundIndex];
for(var j=0; j < thisInputCombination.inputs.length; j++){
if(thisInputCombination.inputs[j].type == type && thisInputCombination.inputs[j].value == inputInfo.value){
thisInputCombination.inputs.splice(j,1);
saveActionMap();
}
}
}
};
//display input
var displayInput = function (type, inputInfo) {
var targetContainer = type == 'gamepad' ? gamepadList : (type == 'mouse' ? mouseList : keyboardList);
var inputPP = function (item) {
var inputNode = $(item.nodes[0]);
//wire up the removal
inputNode.find('.inpoot-x-out').click(function() {
deleteInput(type, inputInfo);
inputNode.fadeOut(function(){
inputNode.remove();
});
});
};
$.tmpl('inpoot.action_map.action_edit_action_map_item', {name: inputInfo.text}, {rendered: inputPP}).appendTo(targetContainer);