-
Notifications
You must be signed in to change notification settings - Fork 514
/
wormapp.ts
1453 lines (1231 loc) · 45.4 KB
/
wormapp.ts
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 (c) 2011-2013 Turbulenz Limited
/*global TurbulenzEngine: false*/
/*global Game: false*/
/*global TurbulenzServices: false*/
/*global RequestHandler: false*/
/*global TextureManager: false*/
/*global ShaderManager: false*/
/*global EffectManager: false*/
/*global FontManager: false*/
/*global GameBadges: false*/
/*global GameLeaderboards: false*/
/*global AppScene: false*/
/*global HtmlWriter: false*/
/*global window: false*/
interface Technique2DParameters extends TechniqueParameters
{
clipSpace: any; // v4
};
//
// Application: The global for the whole application (singleton)
//
class Application
{
// Ensures shutdown function is only called once
hasShutDown : boolean;
runInEngine : boolean; // TODO: seems not to be used
previousGameUpdateTime : number;
gameSession : GameSession;
userProfile : UserProfile;
multiplayerSession : MultiPlayerSession;
leaderboardManager : LeaderboardManager;
badgeManager : BadgeManager;
multiplayerSessionManager : MultiPlayerSessionManager;
leaderboards : GameLeaderboards;
badges : GameBadges;
htmlWriter : HtmlWriter;
appScene : AppScene;
game : Game;
devices : any;
managers : any;
others : any;
isHost : boolean;
connectionTime : number;
previousHeartbeatTime : number;
lastSentMessageTime : number;
frameCounter : number;
hostFrameCounter : number;
needToRender : boolean;
requestHandler : RequestHandler;
intervalID : number;
mappingTable : any;
// UI
font : Font;
technique2D : Technique;
technique2Dparameters : Technique2DParameters;
hasShutdown : boolean;
gameSettings = {
width : 30, // Must be a multiple of 2
height : 16, // Must be a multiple of 2
boardSpacing : 1.1,
maxPlayers : 3
};
gameTimeStep = 0.05;
networkIds = {
joining : 0,
update : 1,
leaving : 2,
ping : 3,
pong : 4
};
heartbeatTime = 0.5; // Should be lower than staleTime
staleTime = 1.5;
sceneSetup = false;
// Error callback - uses window alert
errorCallback(msg)
{
window.alert(msg);
}
// Initialise the application
init()
{
// Test for minimum engine version, device creation, and shader support
if (!this.createDevices() ||
!this.hasShaderSupport())
{
return;
}
var creationFunctions =
[
{func : this.createUserProfile, isDependent : false},
{func : this.createGameSession, isDependent : false},
{func : this.createMappingTable, isDependent : true},
{func : this.createLeaderboardManager, isDependent : true},
{func : this.createBadgeManager, isDependent : false, noCallback : true},
{func : this.createMultiplayerSessionManager, isDependent : false, noCallback : true},
{func : this.createGameLeaderboards, isDependent : true},
{func : this.createGameBadges, isDependent : false},
{func : this.createGame, isDependent : true, noCallback : true},
{func : this.createHTMLWriter, isDependent : true, noCallback : true},
{func : this.enterLoadingLoop, isDependent : true}
];
this.enterCallbackChain(this, creationFunctions);
}
// Update function called in main loop
update(currentTime)
{
var devices = this.devices;
devices.inputDevice.update();
devices.networkDevice.update();
var gameStep = false, heartbeat = false;
if ((currentTime - this.previousGameUpdateTime) > this.gameTimeStep)
{
this.previousGameUpdateTime = currentTime;
gameStep = true;
}
if ((currentTime - this.previousHeartbeatTime) > this.heartbeatTime)
{
this.previousHeartbeatTime = currentTime;
this.checkOthers();
heartbeat = true;
}
if (this.updateGame(gameStep, heartbeat))
{
this.appScene.update();
this.leaderboards.update(currentTime);
this.badges.update(currentTime);
this.htmlWriter.update();
return true;
}
return false;
}
// Update game state
updateGame(gameStep, heartbeat)
{
var isHost = this.isHost;
var game = this.game;
var gameSession = this.gameSession;
var sortedWorms, worm, playerId, index;
var ranks = ["1st", "2nd", "3rd"];
var theOthers = this.others;
var myID = this.userProfile.username;
game.update(isHost, gameStep);
var multiplayerSession = this.multiplayerSession;
if (multiplayerSession &&
game.myWormIndex >= 0)
{
var updateData = {
frame : undefined,
host : undefined,
others: undefined
};
var sendUpdate = ((TurbulenzEngine.time - this.lastSentMessageTime) > this.heartbeatTime);
if (this.hasOthers())
{
var needToSend = game.serializeDelta(isHost, updateData);
if (needToSend)
{
sendUpdate = true;
}
}
if (sendUpdate)
{
updateData.frame = this.frameCounter;
if (isHost)
{
updateData.host = true;
}
var others = {};
others[multiplayerSession.playerId] = game.myWormIndex;
updateData.others = others;
multiplayerSession.sendToAll(this.networkIds.update, JSON.stringify(updateData));
/*
if (heartbeat)
{
var pingData = {
ping : Math.floor(TurbulenzEngine.time * 1000)
};
multiplayerSession.sendToAll(this.networkIds.ping, JSON.stringify(pingData));
}
*/
this.lastSentMessageTime = TurbulenzEngine.time;
}
sortedWorms = game.worms.slice(0).sort(
function (wormA, wormB)
{
return wormB.playerInfo.score - wormA.playerInfo.score;
}
);
for (index = 0 ; index < sortedWorms.length; index += 1)
{
sortedWorms[index].playerInfo.rank = ranks[index] || index + 1 + "th";
sortedWorms[index].playerInfo.sortkey = index;
}
myID = multiplayerSession.playerId;
for (playerId in theOthers)
{
if (theOthers.hasOwnProperty(playerId))
{
worm = game.worms[theOthers[playerId].wormIndex];
gameSession.setPlayerInfo(playerId, worm.playerInfo);
}
}
}
// Set session status for main player
if (game.myWormIndex >= 0)
{
worm = game.worms[game.myWormIndex];
gameSession.setPlayerInfo(myID, worm.playerInfo);
}
if (gameStep)
{
this.frameCounter += 1;
this.needToRender = true;
}
return this.needToRender;
}
// Render function called in main loop
render(currentTime)
{
var appScene = this.appScene;
var renderer = appScene.renderer;
var graphicsDevice = this.devices.graphicsDevice;
renderer.update(graphicsDevice, appScene.camera, appScene.scene, currentTime);
// Start rendering a frame
if (graphicsDevice.beginFrame())
{
renderer.draw(graphicsDevice, appScene.clearColor);
this.drawUI();
graphicsDevice.endFrame();
}
this.needToRender = false;
}
// Load UI
loadUI()
{
var managers = this.managers;
managers.fontManager.load('fonts/hero.fnt');
managers.shaderManager.load('shaders/font.cgfx');
}
hasUILoaded()
{
var managers = this.managers;
var fontManager = managers.fontManager;
var shaderManager = managers.shaderManager;
if (fontManager.getNumPendingFonts() === 0 &&
shaderManager.getNumPendingShaders() === 0)
{
if (!this.technique2D)
{
var devices = this.devices;
this.font = fontManager.get('fonts/hero.fnt');
var shader = shaderManager.get('shaders/font.cgfx');
this.technique2D = shader.getTechnique('font');
this.technique2Dparameters = devices.graphicsDevice.createTechniqueParameters({
clipSpace: devices.mathDevice.v4BuildZero(),
alphaRef: 0.01,
color: devices.mathDevice.v4BuildOne()
});
}
return true;
}
return false;
}
// Draw UI
drawUI()
{
var msg = '';
var words = [];
var word;
var linecount;
var game = this.game;
var devices = this.devices;
var graphicsDevice = devices.graphicsDevice;
var mathDevice = devices.mathDevice;
var width = graphicsDevice.width;
var height = graphicsDevice.height;
var font = this.font;
var technique2Dparameters = this.technique2Dparameters;
graphicsDevice.setTechnique(this.technique2D);
technique2Dparameters.clipSpace = mathDevice.v4Build(2.0 / width, -2.0 / height, -1.0, 1.0,
technique2Dparameters.clipSpace);
graphicsDevice.setTechniqueParameters(technique2Dparameters);
// Draw score
font.drawTextRect('Score: ' + game.score, {
rect : [10, 10, (width * 0.5) - 10, 32],
scale : 1.0,
spacing : 0,
alignment : 0
});
font.drawTextRect('Kills: ' + game.kills, {
rect : [(width * 0.5), 10, (width * 0.5) - 10, 32],
scale : 1.0,
spacing : 0,
alignment : 2
});
// Draw error info
if (game.currentState === game.state.ERROR)
{
font.drawTextRect('Failed to join game', {
rect : [0, 40, (width - 10), 32],
scale : 1.5,
spacing : 0,
alignment : 1
});
words = game.join_error.split(' ');
linecount = 0;
while (words.length > 0)
{
msg = '';
while (msg.length < 40 && words.length > 0)
{
word = words.shift();
msg += word + ' ';
// Only dealing with simple case of newline either on its own or at end of word.
if (word.indexOf('\n') !== -1)
{
break;
}
}
font.drawTextRect(msg, {
rect : [0, 104 + (linecount * 33), (width - 10), 32],
scale : 1.0,
spacing : 0,
alignment : 1
});
linecount += 1;
}
font.drawTextRect('Press SPACE to start new game', {
rect : [0, 104 + (linecount * 33) + 20, (width - 10), 32],
scale : 1.0,
spacing : 0,
alignment : 1
});
}
// Draw dead info
else if (game.currentState === game.state.DEAD)
{
font.drawTextRect('DEAD', {
rect : [0, 20, (width - 10), 32],
scale : 1.5,
spacing : 0,
alignment : 1
});
font.drawTextRect('Press SPACE to continue', {
rect : [0, 84, (width - 10), 32],
scale : 1.0,
spacing : 0,
alignment : 1
});
}
// Draw connection and host status flags
if (!this.multiplayerSession)
{
if (game.currentState !== game.state.ERROR)
{
font.drawTextRect('No multiplayer servers. Playing solo!', {
rect : [0, (height - 32), (width - 10), 32],
scale : 0.5,
spacing : 0,
alignment : 1
});
}
}
else
{
if (this.isHost)
{
graphicsDevice.setScissor((width - 6), 2, 4, 4);
graphicsDevice.clear([1, 0, 0, 1]);
graphicsDevice.setScissor(0, 0, width, height);
}
if (!this.multiplayerSession.connected())
{
font.drawTextRect('Connection lost!', {
rect : [0, (height - 32), (width - 10), 32],
scale : 0.5,
spacing : 0,
alignment : 1
});
}
}
}
// Checks for shading language support
hasShaderSupport()
{
var graphicsDevice = this.devices.graphicsDevice;
if (!graphicsDevice.shadingLanguageVersion)
{
this.errorCallback("No shading language support detected.\n" +
"Please check your graphics drivers are up to date.");
graphicsDevice = null;
return false;
}
return true;
}
// Create the device interfaces required
createDevices()
{
var devices = this.devices;
var managers = this.managers;
var errorCallback = this.errorCallback;
var graphicsDeviceParameters = { multisample: 16 };
var graphicsDevice = TurbulenzEngine.createGraphicsDevice(graphicsDeviceParameters);
var mathDeviceParameters = {};
var mathDevice = TurbulenzEngine.createMathDevice(mathDeviceParameters);
var inputDeviceParameters = {};
var inputDevice = TurbulenzEngine.createInputDevice(inputDeviceParameters);
var networkDeviceParameters = {};
var networkDevice = TurbulenzEngine.createNetworkDevice(networkDeviceParameters);
devices.graphicsDevice = graphicsDevice;
devices.mathDevice = mathDevice;
devices.inputDevice = inputDevice;
devices.networkDevice = networkDevice;
var requestHandlerParameters = {};
var requestHandler = RequestHandler.create(requestHandlerParameters);
this.requestHandler = requestHandler;
managers.textureManager = TextureManager.create(graphicsDevice, requestHandler, null, errorCallback);
managers.shaderManager = ShaderManager.create(graphicsDevice, requestHandler, null, errorCallback);
managers.effectManager = EffectManager.create();
managers.fontManager = FontManager.create(graphicsDevice, requestHandler, null, errorCallback);
return true;
}
// Calls functions in order
enterCallbackChain(context, functions)
{
var length = functions.length;
var localCallback;
var callNextFunction;
// Invariant: currentFunction always refers to the last uncalled function
var currentFunction = 0;
// Invariant: activeCallbacks refers to the number of functions whose callbacks have not yet been received
var activeCallbacks = 0;
callNextFunction = function callNextFunctionFn()
{
if (!functions[currentFunction].noCallback)
{
activeCallbacks += 1;
}
functions[currentFunction].func.call(context, localCallback, arguments);
currentFunction += 1;
};
localCallback = function localCallbackFn()
{
activeCallbacks -= 1;
// If no callbacks are left then call functions consecutively until dependent (or blocker) function is seen
if (activeCallbacks === 0 &&
currentFunction < length)
{
// No active callbacks so immediately call next function
callNextFunction();
// Call functions until we hit a dependent (blocking) function
while (currentFunction < length &&
((0 === activeCallbacks) || (!functions[currentFunction].isDependent)))
{
callNextFunction();
}
}
};
// Start the async callback chain
callNextFunction();
}
// Creates the game with the settings provided
createGame()
{
var devices = this.devices;
var inputDevice = devices.inputDevice;
this.game = Game.create(this.gameSettings,
devices.graphicsDevice,
this.gameSession,
this.leaderboards,
this.badges,
inputDevice.keyCodes,
inputDevice.mouseCodes);
this.createInputDeviceCallbacks();
}
// Adds onKeyDown functions to inputDevice
createInputDeviceCallbacks()
{
var game = this.game;
var inputDevice = this.devices.inputDevice;
// Closure for keyDown callback
function onKeyDown(keynum)
{
game.onKeyDown(keynum);
}
function onMouseDown(keynum)
{
game.onMouseDown(keynum);
}
inputDevice.addEventListener('keydown', onKeyDown);
inputDevice.addEventListener('mousedown', onMouseDown);
}
// Create GameLeaderboards
createGameLeaderboards(callback)
{
this.leaderboards = GameLeaderboards.create(this.leaderboardManager, callback);
}
// Create GameBadges
createGameBadges(callback)
{
this.badges = GameBadges.create(this.badgeManager, callback);
}
// Create HTML Writer
createHTMLWriter()
{
// Must be created after badges, leaderboards, and game have been initialised
this.htmlWriter = HtmlWriter.create(this.leaderboards, this.badges, this.game);
}
// Create multiplayer session
startMultiplayerSession()
{
var that = this;
var queue = this.multiplayerSessionManager.getJoinRequestQueue();
var pendingJoinRequest = queue.shift();
function localConnectingStateLoop()
{
return that.connectingStateLoop();
}
function localMainStateLoop()
{
return that.mainStateLoop();
}
function onMultiplayerMessage(senderID, messageType, messageData)
{
that.onMessage(senderID, messageType, messageData);
}
function onMultiplayerClose()
{
that.errorCallback("Connection lost!");
}
// Called when a new multiplayer session is joined
function startNewGame()
{
var game = that.game;
var myPrevWormIndex = game.myWormIndex;
game.myWormIndex = -1;
if (that.sceneSetup && myPrevWormIndex >= 0)
{
that.appScene.resetWorm(myPrevWormIndex);
}
game.currentState = game.state.PLAY;
delete game.join_error;
that.gameSession.clearAllPlayerInfo();
}
function multiplayerSessionCreateError()
{
startNewGame();
if (that.multiplayerSession)
{
that.multiplayerSession.destroy();
that.multiplayerSession = null;
}
that.isHost = true;
that.game.badges = that.badges;
that.game.leaderboards = that.leaderboards;
that.game.start();
queue.clear();
queue.resume();
}
function multiplayerSessionSuccess(multiplayerSession, numplayers)
{
if (1 === numplayers)
{
that.isHost = true;
that.game.start();
}
that.multiplayerSession = multiplayerSession;
multiplayerSession.onmessage = onMultiplayerMessage;
multiplayerSession.onclose = onMultiplayerClose;
multiplayerSession.sendToAll(that.networkIds.joining);
that.connectionTime = TurbulenzEngine.time;
queue.clear();
queue.resume();
}
function multiplayerSessionJoinError(errMsg, status)
{
// Set up an error to display
that.game.currentState = that.game.state.ERROR;
that.game.join_error = 'I\'m sorry, something has gone wrong. Please try again. \n (Technical stuff: ' +
errMsg + ')';
if (status === 404)
{
that.game.join_error = 'I\'m sorry, that game has ended.';
}
if (status === 409 && errMsg.match('private'))
{
that.game.join_error = 'I\'m sorry, you can\'t join that game right now. You can only join your ' +
'friend\'s games or public games.';
}
if (status === 409 && errMsg.match('slot'))
{
that.game.join_error = 'I\'m sorry, you can\'t join that game right now as it is full.' +
' Try again later!';
}
// Make sure we have a game to display the message over
if (!that.sceneSetup)
{
that.appScene.setupScene();
that.sceneSetup = true;
}
TurbulenzEngine.clearInterval(that.intervalID);
that.intervalID = TurbulenzEngine.setInterval(localMainStateLoop, (1000 / 10));
// Allow user to try to join another game if required
queue.clear();
queue.resume();
that.game.join_error_cb = function () {
delete that.game.join_error_cb;
queue.pause();
TurbulenzEngine.clearInterval(that.intervalID);
that.intervalID = TurbulenzEngine.setInterval(localConnectingStateLoop, (1000 / 10));
that.game.currentState = that.game.state.PLAY;
that.multiplayerSessionManager.joinOrCreateSession(that.gameSettings.maxPlayers,
multiplayerSessionSuccess,
multiplayerSessionCreateError);
};
}
function onJoinEvent(multiplayerSessionId)
{
var oldMultiplayerSession = that.multiplayerSession;
if (!oldMultiplayerSession || oldMultiplayerSession.sessionId !== multiplayerSessionId)
{
if (oldMultiplayerSession)
{
oldMultiplayerSession.sendToAll(that.networkIds.leaving);
oldMultiplayerSession.destroy();
that.multiplayerSession = null;
that.others = {};
}
TurbulenzEngine.clearInterval(that.intervalID);
that.intervalID = TurbulenzEngine.setInterval(localConnectingStateLoop, (1000 / 10));
startNewGame();
queue.pause();
that.multiplayerSessionManager.joinSession(multiplayerSessionId,
multiplayerSessionSuccess,
multiplayerSessionJoinError);
}
}
queue.onEvent(onJoinEvent, this);
if (pendingJoinRequest)
{
this.multiplayerSessionManager.joinSession(pendingJoinRequest,
multiplayerSessionSuccess,
multiplayerSessionJoinError);
}
else
{
this.multiplayerSessionManager.joinOrCreateSession(this.gameSettings.maxPlayers,
multiplayerSessionSuccess,
multiplayerSessionCreateError);
}
}
// Create game session
createGameSession(callback)
{
this.gameSession = TurbulenzServices.createGameSession(this.requestHandler, callback);
// Setup static teamlist for ordering teams
this.gameSession.setTeamInfo(['Worms', 'Snakes']);
}
// Create a user profile
createUserProfile(callback)
{
this.userProfile = TurbulenzServices.createUserProfile(this.requestHandler, callback);
}
// Create mapping table
createMappingTable(callback)
{
this.mappingTable = TurbulenzServices.createMappingTable(this.requestHandler, this.gameSession, callback);
}
// Create leaderboard manager
createLeaderboardManager(callback)
{
var that = this;
function createLeaderboardManagerError()
{
that.leaderboardManager = null;
callback();
}
this.leaderboardManager = TurbulenzServices.createLeaderboardManager(this.requestHandler,
this.gameSession,
callback,
createLeaderboardManagerError);
}
// Create badge manager
createBadgeManager()
{
// Only create badge manager if leaderboardManager has been initialised successfully
if (this.leaderboardManager)
{
this.badgeManager = TurbulenzServices.createBadgeManager(this.requestHandler, this.gameSession);
}
}
createMultiplayerSessionManager()
{
this.multiplayerSessionManager = TurbulenzServices.createMultiplayerSessionManager(this.requestHandler,
this.gameSession);
}
// Starts loading scene and creates an interval to check loading progress
enterLoadingLoop()
{
var that = this;
var managers = this.managers;
var mappingTable = this.mappingTable;
var urlMapping = mappingTable.urlMapping;
var assetPrefix = mappingTable.assetPrefix;
managers.textureManager.setPathRemapping(urlMapping, assetPrefix);
managers.shaderManager.setPathRemapping(urlMapping, assetPrefix);
managers.fontManager.setPathRemapping(urlMapping, assetPrefix);
this.appScene = AppScene.create(this.devices, this.managers,
this.requestHandler, this.mappingTable,
this.game);
this.loadUI();
// Enter loading state
function localLoadingStateLoop()
{
return that.loadingStateLoop();
}
this.intervalID = TurbulenzEngine.setInterval(localLoadingStateLoop, (1000 / 10));
}
// Called until assets have been loaded at which point the connecting loop is entered
loadingStateLoop()
{
var that = this;
function localConnectingStateLoop()
{
return that.connectingStateLoop();
}
// If everything has finished loading/initialising
if (this.appScene.hasLoaded() &&
this.hasUILoaded())
{
TurbulenzEngine.clearInterval(this.intervalID);
this.startMultiplayerSession();
this.intervalID = TurbulenzEngine.setInterval(localConnectingStateLoop, (1000 / 10));
}
}
// Called until connected to the multiplayer session at which point the main loop is entered
connectingStateLoop()
{
var that = this;
function localMainStateLoop()
{
return that.mainStateLoop();
}
this.devices.networkDevice.update();
// If joined game
if (this.game.myWormIndex >= 0)
{
TurbulenzEngine.clearInterval(this.intervalID);
if (!this.sceneSetup)
{
this.appScene.setupScene();
this.sceneSetup = true;
}
this.intervalID = TurbulenzEngine.setInterval(localMainStateLoop, (1000 / 60));
}
else
{
// If connected to session
if (this.multiplayerSession)
{
var currentTime = TurbulenzEngine.time;
var connectionTime = this.connectionTime;
var staleTime = this.staleTime;
if ((connectionTime + staleTime) < currentTime)
{
this.isHost = true;
this.game.start();
}
else if ((connectionTime + (staleTime * 0.5)) < currentTime)
{
// Keep requesting to join to avoid problems when starting in the middle of a host transition
this.multiplayerSession.sendToAll(this.networkIds.joining);
}
}
}
}
mainStateLoop()
{
var currentTime = TurbulenzEngine.time;
if (this.update(currentTime))
{
this.render(currentTime);
}
}
onMessage(senderID, messageType, messageData)
{
//Utilities.log(senderID, messageType, messageData);
var networkIds = this.networkIds;
switch (messageType)
{
case networkIds.joining:
this.onJoiningMessage(senderID);
break;
case networkIds.update:
this.onUpdateMessage(senderID, messageData);
break;
case networkIds.leaving:
this.onLeavingMessage(senderID);
break;
case networkIds.ping:
this.onPingMessage(senderID, messageData);
break;
case networkIds.pong:
this.onPongMessage(senderID, messageData);
break;
}
}
onJoiningMessage(senderID)
{
var multiplayerSession = this.multiplayerSession;
var myID = multiplayerSession.playerId;
var networkIds = this.networkIds;
var theOthers = this.others;
var other = theOthers[senderID];
var game = this.game;
var updateData, others, n, otherID;
var wormIndex = game.myWormIndex;
var time = TurbulenzEngine.time;
if (other === undefined)
{
if (!this.isHost)
{
return;
}
var maxPlayers = this.gameSettings.maxPlayers;
var usedWormIndex = {};
usedWormIndex[wormIndex] = true;
var existingPlayers = [];
others = {};
others[myID] = wormIndex;
for (otherID in theOthers)
{