This repository was archived by the owner on Oct 3, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy pathPlayer.js
More file actions
668 lines (572 loc) · 20.3 KB
/
Player.js
File metadata and controls
668 lines (572 loc) · 20.3 KB
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
var Player = IgeEntity.extend({
classId: 'Player',
componentId: 'player',
init: function (data, entityIdFromServer) {
IgeEntity.prototype.init.call(this);
this.id(entityIdFromServer);
var self = this;
this._stats = data;
// dont save variables in _stats as _stats is stringified and synced
// and some variables of type unit, item, projectile may contain circular json objects
if (self._stats.variables) {
self.variables = self._stats.variables;
delete self._stats.variables;
}
self.previousAttributes = {};
self.lastCustomInput = '';
Player.prototype.log(`player created ${this.id()}`);
this.category('player');
this.mount(ige.$('baseScene'));
self.addComponent(AttributeComponent);
if (ige.isServer) {
this.streamMode(2);
// self._stats.unitId = self.getCurrentUnit().id()
self.addComponent(ControlComponent);
ige.server.totalPlayersCreated++;
} else if (ige.isClient) {
// if this player is "me"
if (self._stats.clientId == ige.network.id()) {
self.addComponent(ControlComponent);
// mouse move listener
ige.client.vp1.mouseMove(function (event, control) {
self.control.mouseMove();
});
this.setChatMute(this._stats.banChat);
}
// redraw name labels and textures of all units owned by this player
self.redrawUnits(function (unit) {
return unit && unit.getOwner() && unit.getOwner().id() === self.id();
}, ['texture', 'nameLabel']);
ige.entitiesToRender.trackEntityById[entityIdFromServer] = this;
}
},
// move to UI
joinGame: function () {
var self = this;
if (self._stats.userId) {
ige.clusterClient.userJoined(self._stats.userId);
}
if (self._stats.playerJoined != true) {
if (self._stats.controlledBy == 'human' && ige.script) // do not send trigger for neutral player
{
ige.trigger.fire('playerJoinsGame', { playerId: self.id() });
}
var clientId = self._stats.clientId;
var client = ige.server.clients[clientId];
var receivedJoinGame = client.receivedJoinGame;
var processedJoinGame = Date.now() - receivedJoinGame;
var dataLoadTime = self._stats.totalTime;
client.lastEventAt = Date.now();
var playerJoinStreamData = [
{ streamedOn: Date.now() },
{ playerJoined: true },
{ dataLoadTime: dataLoadTime },
{ processedJoinGame: processedJoinGame },
{ receivedJoinGame: receivedJoinGame }
];
console.log(`Player.joinGame(): sending ACK to client ${self._stats.clientId} ${self._stats.name} (time elapsed: ${Date.now() - client.lastEventAt})`, playerJoinStreamData);
self.streamUpdateData(playerJoinStreamData);
ige.clusterClient && ige.clusterClient.playerJoined(self._stats.userId);
} else {
console.log(`player joined again (menu closed?) ${self._stats.clientId} (${self._stats.name})`);
self.streamUpdateData([{ playerJoinedAgain: true }]);
}
},
createUnit: function (data) {
var self = this;
if (ige.isServer) {
var data = Object.assign(
data,
{
clientId: self._stats.clientId,
name: self._stats.name
});
var unit = new Unit(data);
unit.setOwnerPlayer(self.id());
// setOwner will add unitId to unitIds
// self._stats.unitIds.push(unit.id())
Player.prototype.log(`created unit ${unit.id()} for ${self._stats.name} (${self._stats.clientId})`);
return unit;
}
},
ownUnit: function (unit) {
if (this._stats.unitIds.indexOf(unit.id()) == -1 && unit.id() != 'ige') {
this._stats.unitIds.push(unit.id());
}
// if player has only 1 unit, then select that unit
if (this._stats.unitIds.length === 1) {
this.selectFirstAvailableUnit();
}
},
// remove unit from the array of units owned by this player
disownUnit: function (unit) {
var index = this._stats.unitIds.indexOf(unit.id());
if (index !== -1) {
this._stats.unitIds.splice(index, 1);
}
},
// make player select a unit and do the following:
// 1. camera track (if this is the only unit)
// 2. update inventory
// 3. update attribute bars
selectUnit: function (unitId) {
var self = this;
self._stats.selectedUnitId = unitId;
if (ige.isServer && self._stats.clientId) {
ige.network.send('makePlayerSelectUnit', { unitId: unitId }, self._stats.clientId);
var unit = ige.$(unitId);
}
if (ige.isClient) {
var unit = ige.$(unitId);
if (self._stats.clientId == ige.network.id() && unit && unit._category == 'unit') {
if (unit.inventory) {
unit.inventory.createInventorySlots();
}
if (unit.unitUi) {
unit.unitUi.updateAllAttributeBars();
}
if (unit && unit.inventory) {
unit.inventory.updateBackpackButton();
}
unit.renderMobileControl();
ige.client.selectedUnit = unit;
ige.client.eventLog.push([ige._currentTime, `my unit selected ${unitId}`]);
if (ige.env == 'local') {
var graphics = new PIXI.Graphics();
graphics.lineStyle(2, 0x0000FF, 0.5);
graphics.beginFill(0xFF700B, 0.3);
graphics.drawRect(0, 0, unit.width(), unit.height());
graphics = ige.pixi.app.renderer.generateTexture(graphics);
graphics = new PIXI.Sprite(graphics);
graphics.rotation = unit._rotate.z;
graphics.pivot.set(unit.width / 2, unit.height / 2);
var container = new PIXI.Container();
container.addChild(graphics);
container.position.set(unit._translate.x, unit._translate.y);
container.pivot.set(unit.width / 2, unit.height / 2);
container.zIndex = 10;
unit._debugEntity = container;
ige.pixi.box2dDebug.addChild(container);
}
}
}
},
cameraTrackUnit: function (unit) {
if (unit) {
// self._stats.selectedUnitId = unit.id()
if (ige.isServer && this._stats.clientId) {
ige.network.send(
'makePlayerCameraTrackUnit',
{ unitId: unit.id() },
this._stats.clientId
);
} else if (
ige.isClient &&
this._stats.clientId == ige.network.id()
&& unit
&& unit._category == 'unit'
) {
ige.client.myPlayer.currentFollowUnit = unit._id;
ige.client.emit('followUnit', unit);
}
}
},
changeCameraPanSpeed: function (panSpeed) {
var self = this;
if (ige.isServer && self._stats.clientId) {
ige.network.send('changePlayerCameraPanSpeed', { panSpeed: panSpeed }, self._stats.clientId);
} else if (ige.isClient && self._stats.clientId == ige.network.id() && panSpeed !== undefined) {
ige.client.vp1.camera.trackTranslateSmoothing(panSpeed);
}
},
// get selectedUnits' 0th index unit
selectFirstAvailableUnit: function () {
if (this._stats.unitIds) {
var unit = ige.$(this._stats.unitIds[0]);
if (unit) {
this.selectUnit(unit.id());
}
}
},
getSelectedUnit: function () {
return ige.$(this._stats.selectedUnitId);
},
castAbility: function (command) {
var self = this;
var units = ige.game.getUnitsByClientId(this._stats.clientId);
for (i in units) {
var unit = units[i];
if (unit) {
var unitType = ige.game.getAsset('unitTypes', unit._stats.type);
if (unitType && unitType.abilities) {
var ability = unitType.abilities[command];
if (ability) {
unit.ability.cast(ability);
}
}
}
}
},
updatePlayerType: function (data) {
var self = this;
// pass old attributes' values to new attributes (given that attributes have same ID)
if (self._stats.attributes != undefined) {
var oldAttributes = JSON.parse(JSON.stringify(self._stats.attributes));
for (attrId in data.attributes) {
if (oldAttributes[attrId] != undefined) {
data.attributes[attrId].value = oldAttributes[attrId].value;
data.attributes[attrId].max = oldAttributes[attrId].max;
}
}
}
self._stats.attributes = data.attributes;
if (data.variables) {
var variables = {};
for (var key in data.variables) {
if (self.variables && self.variables[key]) {
variables[key] = self.variables[key] == undefined ? data.variables[key] : self.variables[key];
} else {
variables[key] = data.variables[key];
}
}
self.variables = variables;
}
if (self._stats.variables) {
delete self._stats.variables;
}
if (ige.isClient) {
var isMyPlayerUpdated = self._stats.clientId == ige.network.id();
// show name label can be false for assignedPlyerType so updateNameLabel accordingly
self.redrawUnits(function (unit) {
var owner = unit.getOwner();
return owner && owner.id() === self.id();
}, ['nameLabel', 'texture']);
// update attr bars of all units
self.redrawUnits(function (unit) {
var ownerPlayer = unit.getOwner();
return isMyPlayerUpdated || ownerPlayer && ownerPlayer.id() === self.id();
}, ['attributeBars']);
if (isMyPlayerUpdated) {
// update UI
ige.playerUi.updatePlayerAttributesDiv(self._stats.attributes);
}
if (ige.scoreboard) {
ige.scoreboard.update();
}
}
},
getUnitCount: function () {
var units = this._stats.unitIds;
if (units)
return Object.keys(units).length;
return 0;
},
// if any player feels hostile towards another, then it's a hostile relationship
isHostileTo: function (player) {
if (player == undefined) {
return false;
}
var myPlayerType = ige.game.getAsset('playerTypes', this._stats.playerTypeId);
if (myPlayerType && myPlayerType.relationships) {
if (myPlayerType.relationships[player._stats.playerTypeId] == 'hostile')
return true;
}
return false;
},
// if both players are friendly to each other, then it's a friendly relationship
isFriendlyTo: function (player) {
if (player == undefined) {
return false;
}
var myPlayerType = ige.game.getAsset('playerTypes', this._stats.playerTypeId);
if (myPlayerType && myPlayerType.relationships) {
if (myPlayerType.relationships[player._stats.playerTypeId] == 'friendly') {
return true;
}
}
return false;
},
// if both players are non-hostile but not friendly, then it's a neutral relationship
isNeutralTo: function (player) {
return this.isHostileTo(player) == false && this.isFriendlyTo(player) == false;
},
remove: function () {
if (ige.isServer) {
const i = ige.server.developerClientIds.indexOf(this._stats.clientId);
if (i != -1) ige.server.developerClientIds.splice(i, 1);
}
if (this._stats.controlledBy == 'human' && ige.script) // do not send trigger for neutral player
{
ige.trigger.fire('playerLeavesGame', { playerId: this.id() });
}
// session is in second
ige.clusterClient && ige.clusterClient.emit('log-session-duration', (Date.now() - this._stats.jointsOn) / 1000);
if (this.variables && this.variables.progression != undefined && this.variables.progression.value != undefined) {
ige.clusterClient && ige.clusterClient.emit('log-progression', this.variables.progression.value);
}
this.streamDestroy();
this.destroy();
},
updateVisibility: function (playerId) {
var player = ige.$(playerId);
if (!player) {
return;
}
// make hostile-invisible units invisible and friendly & neutral units visible (and its item)
this.redrawUnits(function (unit) {
var owner = unit.getOwner();
return owner != undefined && owner.id() == playerId;
}, ['texture', 'nameLabel']);
// make the items visible/invisible that belongs to any unit of this player
ige.$$('item')
.forEach(function (item) {
var ownerUnit = item.getOwnerUnit();
var ownerPlayer = ownerUnit && ownerUnit.getOwner();
var belongsToCurrentPlayer = ownerPlayer && ownerPlayer.id() === playerId;
if (belongsToCurrentPlayer) {
item.updateTexture();
}
});
},
// update player's stats in the server side first, then update client side as well.
streamUpdateData: function (queuedData) {
var self = this;
var oldStats = JSON.parse(JSON.stringify(self._stats));
IgeEntity.prototype.streamUpdateData.call(this, queuedData);
for (var i = 0; i < queuedData.length; i++) {
var data = queuedData[i];
for (attrName in data) {
var newValue = data[attrName];
// if player's type changed, then update all of its base stats (speed, stamina, etc..)
if (attrName === 'playerTypeId') {
var playerTypeData = ige.game.getAsset('playerTypes', newValue);
if (playerTypeData) {
playerTypeData.playerTypeId = newValue;
if (ige.isClient) {
// change color of label of all units that belongs to updating player
self.redrawUnits(function (unit) {
// dont update color if unitType of my unit is changed on my screen as it will be always Lime
var isMyPlayerUpdated = self._stats.clientId === ige.network.id();
// update color of all units that belongs to player whose playerType just changed
var ownerPlayer = unit.getOwner();
var unitBelongsToUpdatingPlayer = ownerPlayer && ownerPlayer.id() === self.id();
return !isMyPlayerUpdated && unitBelongsToUpdatingPlayer;
}, ['nameLabel']);
}
self.updatePlayerType(playerTypeData);
}
}
if (ige.isServer) {
if (attrName === 'name' && oldStats.name !== newValue) {
// update all units
self._stats.unitIds.forEach(function (unitId) {
var unit = ige.$(unitId);
unit.streamUpdateData([{ name: newValue }]);
});
} else if (attrName === 'playerJoined' && newValue == false) {
// player's been kicked/removed
self.remove();
}
}
if (ige.isClient) {
if (attrName === 'name') {
// update here
if (typeof refreshUserName == 'function') {
refreshUserName(newValue);
}
}
if (attrName === 'equiped') {
var unit = self.getSelectedUnit();
if (unit) {
unit.equipSkin();
}
} else if (attrName === 'unEquiped') {
var unit = self.getSelectedUnit();
if (unit) {
unit.unEquipSkin(null, false, newValue);
}
}
if (self._stats.clientId == ige.network.id()) {
if (attrName === 'attributes') {
ige.playerUi.updatePlayerAttributesDiv(self._stats.attributes);
}
if (attrName === 'coins') {
ige.playerUi.updatePlayerCoin(newValue);
}
if (attrName === 'playerJoinedAgain') {
self.hideMenu();
}
if (attrName === 'banChat') {
self.setChatMute(newValue);
}
if (attrName === 'playerJoined') {
console.log('received player.playerJoined');
ige.client.eventLog.push([ige._currentTime, 'playerJoined received']);
// render name labels of all other units
self.redrawUnits(['nameLabel']);
self._stats.receivedJoinGame = data.receivedJoinGame;
ige.client.eventLog.push([ige._currentTime - ige.client.eventLogStartTime, '\'playerJoined\' received from server']);
self._stats.processedJoinGame = data.processedJoinGame;
var streamingDiff = `${Date.now() - data.streamedOn}ms`;
window.joinGameSent.end = Date.now();
window.joinGameSent.completed = window.joinGameSent.end - window.joinGameSent.start;
console.log(
`JoinGame took ${window.joinGameSent.completed}ms to join player` +
`, client to gs: ${self._stats.receivedJoinGame - window.joinGameSent.start}ms` +
`, gs loading player data: ${self._stats.totalTime}ms` +
`, gs processed request for: ${self._stats.processedJoinGame}ms` +
`, gs to client: ${streamingDiff
}, client sent on: ${window.joinGameSent.start
}, server sent back on: ${data.streamedOn}`
);
if (window.joinGameSent.completed > 7000) {
$.post('/api/log', {
event: 'rollbar',
text: `${Date.now()}:- JoinGame took ${window.joinGameSent.completed}ms to join player` +
`, client to gs: ${self._stats.receivedJoinGame - window.joinGameSent.start}ms` +
`, gs loading player data: ${self._stats.totalTime}ms` +
`, gs processed request for: ${self._stats.processedJoinGame}ms` +
`, gs to client: ${streamingDiff
}, client sent on: ${window.joinGameSent.start
}, server sent back on: ${data.streamedOn}`
});
}
if (self._stats.processedJoinGame > 7000) {
$.post('/api/log', {
event: 'rollbar',
text: `${Date.now()}JoinGame took ${window.joinGameSent.completed}ms to create player` +
`, client to gs: ${self._stats.receivedJoinGame - window.joinGameSent.start}ms` +
`, gs loading player data: ${self._stats.totalTime}ms` +
`, gs processed request for: ${self._stats.processedJoinGame}ms` +
`, gs to client: ${streamingDiff
}, client sent on: ${window.joinGameSent.start
}, server sent back on: ${data.streamedOn}`
});
}
self.hideMenu();
clearTimeout(window.errorLogTimer);
}
}
if (attrName === 'banChat' && (ige.game.data.isDeveloper || (ige.client.myPlayer && ige.client.myPlayer._stats.isUserMod))) {
ige.menuUi.kickPlayerFromGame();
}
}
}
}
},
setChatMute: function (value) {
if (ige.env == 'local') // don't mute users in dev env
return;
if (value) {
$('#message').attr('disabled', true);
$('#message').attr('placeholder', 'You are muted');
} else {
$('#message').attr('disabled', false);
$('#message').attr('placeholder', 'message');
}
},
redrawUnits: function (filterFn, properties) {
if (filterFn instanceof Array) {
properties = filterFn;
filterFn = null;
}
ige.$$('unit')
.filter(function (unit) {
return filterFn ? filterFn(unit) : true;
})
.forEach(function (unit) {
properties.forEach(function (property) {
switch (property) {
case 'nameLabel': {
unit.updateNameLabel();
break;
}
case 'texture': {
unit.updateTexture();
break;
}
case 'attributeBars': {
unit.redrawAttributeBars();
break;
}
}
});
});
},
updatePlayerHighscore: function () {
var self = this;
var scoreId = ige.game.data.settings.scoreAttributeId;
try {
// comparing player highscore with current highscore. if current highscore is greter then request it to update server
if (scoreId && self._stats && self._stats.attributes && self._stats.attributes[scoreId] && (self._stats.highscore < self._stats.newHighscore || self._stats.highscore < self._stats.attributes[scoreId].value)) {
var score = Math.max(self._stats.newHighscore || 0, self._stats.attributes[ige.game.data.settings.scoreAttributeId].value || 0);
if (score > self._stats.highscore) {
// highscore updated
ige.clusterClient && ige.clusterClient.updatePlayerHighscore({
userId: self._stats.userId,
gameId: ige.game.data.defaultData._id,
highscore: score,
});
}
}
} catch (e) {
Player.prototype.log(e);
}
},
tick: function (ctx) {
// if entity (unit/item/player/projectile) has attribute, run regenerate
if (ige.isServer) {
if (this.attribute) {
this.attribute.regenerate();
}
}
IgeEntity.prototype.tick.call(this, ctx);
},
loadPersistentData: function () {
var self = this;
var persistData = _.cloneDeep(self.persistedData);
if (persistData && persistData.data && persistData.data.player) {
IgeEntity.prototype.loadPersistentData.call(this, persistData.data.player);
}
console.log('load persisted data is now true');
self.persistentDataLoaded = true;
},
loadDataFromString: function (data) {
var self = this;
var persistData = data;
if (persistData) {
IgeEntity.prototype.loadPersistentData.call(this, persistData);
}
self.persistentDataLoaded = true;
},
hideMenu: function () {
if (ige.isClient) {
// UI related changes like hiding menu, etc...
$('#play-game-button').removeAttr('disabled');
var html = '<i class="fa fa-gamepad pr-2 py-3" aria-hidden="true"></i>Continue';
$('#play-game-button .content').html(html);
$('#modd-shop-div').addClass('d-flex');
ige.client.eventLog.push([ige._currentTime - ige.client.eventLogStartTime, 'hide menu called']);
ige.menuUi.hideMenu(); // if player's already joined the game, then just hide menu when "play game" button is clicked
if (!ige.client.guestmode) {
$('.open-menu-button').show();
}
if (typeof (userId) !== 'undefined' && typeof (sessionId) !== 'undefined') {
if (ige.game.data.isDeveloper) {
// dont show dev menu by default
// if (!ige.isMobile) {
// $("#dev-console").show() // if user has access of this game, show dev console
// }
// $('#game-suggestions-card').removeClass('d-xl-block');
// $("#invite-players-card").show();
$('#toggle-dev-panels').show();
$('#kick-player').show();
}
if (ige.client.myPlayer && ige.client.myPlayer._stats.isUserMod) {
$('#kick-player').show();
}
}
}
}
});
if (typeof (module) !== 'undefined' && typeof (module.exports) !== 'undefined') { module.exports = Player; }