-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstuff.js
1081 lines (1012 loc) · 30.8 KB
/
stuff.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
ig.module("nightmarsh")
.requires("game.feature.party.entities.party-member-entity",
"game.feature.puzzle.entities.push-pull-block",
"impact.base.game").defines(()=>{
// to be used as a nav destination
class FakeEntityForNav {
constructor() {
this.jumping = false;
this.coll = { pos: {}, size: {x:0, y:0, z:0} };
this.updatePos(0,0,0);
}
updatePos(x,y,z) {
const pos = this.coll.pos;
pos.x = x || 0;
pos.y = y || 0;
pos.z = pos.baseZPos = z || 0;
}
getCenter(vector) {
vector.x = this.coll.pos.x;
vector.y = this.coll.pos.y;
}
};
const MOVE_INCREMENT = 4;
let nightmarsh = null;
// deps: "game.feature.party.entities.party-member-entity"
let IASTATES = {
GOTOBOX: {
start: (me, box, targetStats, stateData)=>{
//this.setDefaultConfig(this.configs.normal);
me.updateDefaultConfig();
stateData.realTarget = new FakeEntityForNav();
// FIXME: once we select a direction for a boxen,
// we should STICK TO IT and don't attempt to guess
// it every time, because it is unstable.
const dir = nightmarsh.getPreferredDirectionForBox(box);
if (!dir) {
console.error("no dir on GOTOBOX start ?!?");
return;
}
const pos = box.getPosForUser(dir, me);
stateData.realTarget.updatePos(pos.x, pos.y,
box.coll.pos.z);
// this variable is used by the game to cache
// that the nav target was already set.
// set setNavTarget() for details.
me.navTarget = 42;
me.nav.path.toEntity(stateData.realTarget, 6);
},
update: (me, box, targetStats, stateData) => {
me.updateDefaultConfig();
if (!me.myTargetIsABox() || !me.hasValidTarget())
return IASTATES.IDLE;
const dir = nightmarsh.getPreferredDirectionForBox(box);
if (!dir)
return IASTATES.IDLE;
const pos = box.getPosForUser(dir, me);
const my_pos = me.getCenter({});
stateData.realTarget.updatePos(pos.x, pos.y,
box.coll.pos.z)
// full speed ! onward to them boxen !
me.nav.path.startRelativeVel = 1;
if (me.nav.path.moveEntity()) {
// here we have the direction, otherwise, we
// do not even have the garantee that this
// direction will be chosen next time, because
// of a certain user blocking the way ... (us)
// REPEAT AFTER ME: DO NOT ADD ACTIONS TO THE
// ENTITY
// if you do it, all states are dropped.
// so you better move carefully to the point
// where you go, instead of addAndMoveUser.
//
// ANYWAY, LET THE PUSH PULLING BEGINS !
box.pushPullable.addUser(dir, me);
me.setFace(ig.ActorEntity.FACE8[dir]);
return IASTATES.MOVEBOX;
}
}
},
MOVEBOX: {
start: (me, box, targetStats, stateData) => {
me.tryAnotherDirForBox = false;
},
update: (me, box, targetStat, stateData)=>{
if (me.tryAnotherDirForBox) {
me.tryAnotherDirForBox = false;
const nm = nightmarsh;
const dir = nm.getPreferredDirectionForBox(box);
if (dir)
return IASTATES.GOTOBOX;
else {
// HACK HACK HACK
// normally, we must return the
// new default state, but we don't
// have access to the state that we
// want, so we change the state ourself
// but we return nothing. This
// does the same.
me.returnToDefaultState();
return;
}
}
// FIXME: we should be kicked from the box on stun
// we should be kicked from the box on
}
}
};
const requiredAnimations = ['gripStand', 'gripPush', 'gripPull'];
// idea: if under combat, then allow selectTarget to select boxes
// if not under combat, then regardless of state, just tell them to
// find some good boxes to push and stop on the next changeState.
sc.PartyMemberEntity.inject({
init: function(...args) {
this.parent.apply(this, args);
// we always start in idle, so steal the idle state.
IASTATES.IDLE=this.state;
this.canPushBoxes = false;
if (this.animSheet
&& requiredAnimations.every(x =>
this.animSheet.hasAnimation(x))
&& ig.nightmarshPartyPush.active)
this.canPushBoxes = true;
else
return;
this.mustChangeToMoveBox = false;
},
findBestBox: function() {
const box = nightmarsh.getClosestUsefulBox(this.coll.pos);
if (!box)
return;
// don't worry, things will work out fine...
// most notably, this will remove the previous target
// properly.
this.setTarget(box);
this.mustChangeToMoveBox = true;
},
myTargetIsABox: function() {
return this.target instanceof ig.ENTITY.MultiplayerPushBlock;
},
hasValidTarget: function() {
if (this.myTargetIsABox())
return this.target.canBeTargetted();
else
return this.parent();
},
changeState: function(new_state) {
if (this.myTargetIsABox()) {
if (this.state === IASTATES.MOVEBOX)
this.target.pushPullable.removeUser(this);
if (this.mustChangeToMoveBox) {
// normally, new_state is COMBAT_IDLE
// but i can't check that reliably.
new_state = IASTATES.GOTOBOX;
this.mustChangeToMoveBox = false;
}
if (new_state !== IASTATES.GOTOBOX
&& new_state !== IASTATES.MOVEBOX)
// this is more a safety measure than
// something useful. most likely, the caller
// will call this afterward too.
this.endCombat();
}
this.parent(new_state);
},
maybeSelectBoxTarget: function() {
// a target was selected a target, find out why.
if (this.hasValidTarget() && this.target.annotate) {
switch (this.target.annotate.passive) {
case sc.ENEMY_ANNO_PASSIVE.VULNERABLE:
case sc.ENEMY_ANNO_PASSIVE.WEAK:
// the ennemy is weak or vulnerable.
// the AI may have noticed it or it could be
// luck, in any case, don't try to push them
// boxes.
return;
}
// it is probably chosen randomly.
// let's add a bit of random
// FIXME: should probably instead look at the number
// of people targetting this one.
if (Math.random() < 0.8) return;
}
this.findBestBox();
},
setTarget: function(new_target) {
if (this.myTargetIsABox())
this.target.pushPullable.removeUser(this);
return this.parent(new_target);
},
// should not change the target is the current one is valid
// this is only called when in combat
selectTarget: function() {
if (!this.canPushBoxes)
return this.parent();
const target_is_valid = this.hasValidTarget();
this.parent();
if (!target_is_valid)
this.maybeSelectBoxTarget();
},
// could change the target, or drop the target entirely if the
// current one is not valid.
// this is only called when in combat
reselectTarget: function() {
this.parent();
if (this.canPushBoxes && !this.myTargetIsABox())
this.maybeSelectBoxTarget();
},
update: function() {
this.parent();
if (this.myTargetIsABox()) {
if (this.state !== IASTATES.MOVEBOX)
this.target.pushPullable.removeUser(this);
if (this.state !== IASTATES.MOVEBOX
&& this.state !== IASTATES.GOTOBOX)
this.endCombat();
}
},
// check if we should 'go to combat'.
// except an invariant in this game is that you can only have a target
// if you are 'in combat'...
goToCombat: function() {
const parent_result = this.parent();
if (!parent_result) {
// are there boxes that are in need of some pushing ?
if (nightmarsh.hasAnyUsefulBox())
return true; // LET'S PUSH SOME BOXEN
}
return parent_result;
},
returnToDefaultState: function() {
// this means, 'should we go to combat ?'
if (this.goToCombat())
this.startCombat();
else
this.endCombat();
},
/*
startCombat: function() {
this.parent();
// calls selectTarget()
// may call changeState(COMBAT_IDLE if target selected)
if (this.inCombat)
IASTATES.COMBAT_IDLE = this.state;
},
*/
/*
endCombat: function() {
this.parent();
// clears the target, change state to IDLE
// may need to reselect a box here.
},*/
// we can't push/pull anymore
notifyPushIsBlocked: function() {
this.tryAnotherDirForBox = true;
},
// we are not applying any force (i.e. box is placed or on the right
// coordinate)
notifyNoForce: function() {
this.tryAnotherDirForBox = true;
}
});
/*
// boxes
"game.feature.puzzle.components.push-pullable"
sc.PushPullable
"game.feature.interact.gui.interact-gui"
defines interaction button popups
need to register them into sc.MapInteract
also, PushPullBlock
*/
const l1_distance = (a,b) => Math.abs(a.x - b.x) + Math.abs(a.y - b.y);
// deps: impact.base.game
const PartyPushableOrganiser = ig.GameAddon.extend({
boxes:[],
dests:[],
box_to_dest_plan: {},
active: false,
init: function() {
this.parent();
},
onTeleport: function() {
// that's more like leaving a map, right ?
console.log("teleporting");
},
onLevelLoaded: function() {
console.log("level loaded");
this.findThemBoxes();
console.log("boxes: ", this.boxes.length, this.dests.length);
},
recalculatePlans: function() {
// if this sounds like an assignment problem, maybe it's because
// it is. and i'm too lazy to implement a proper alg
const dist_maps = [];
this.dests.forEach((dest,destid) => {
if (dest.placed)
return;
const dest_dists = [];
this.boxes.forEach((box,boxid) => {
if (box.isPlacedOnADest())
return;
const distance = l1_distance(dest.coll.pos,
box.coll.pos);
dest_dists.push({boxid, distance});
});
// sort them closest first.
dest_dists.sort(entry=>entry.distance);
dist_maps.push({destid, boxes: dest_dists});
});
const assigned_boxes = {};
// now we have our cost matrix, let's use a greedy shit alg
// that's probably n*m and does not find the best shit.
// but if that's human enough, it should be good for an ai.
while (dist_maps.length) {
let best_destid = null;
let best_boxid = null;
let best_distance = Infinity;
dist_maps.forEach(destentry => {
let boxes = destentry.boxes;
while (boxes[0].boxid in assigned_boxes)
boxes.unshift();
if (boxes[0].distance < best_distance) {
best_destid = destentry.destid;
best_boxid = boxes[0].boxid;
best_distance = boxes[0].distance;
}
});
assigned_boxes[best_boxid] = best_destid;
dist_maps.splice(best_destid, 1);
}
this.box_to_dest_plan = assigned_boxes;
},
findThemBoxes: function() {
const boxentype = ig.ENTITY.MultiplayerPushBlock;
const desttype = ig.ENTITY.PushPullDest;
this.boxes = ig.game.getEntitiesByType(boxentype);
this.dests = ig.game.getEntitiesByType(desttype);
this.boxes.forEach((box, i) => { box.organizer_id = i; });
this.dests.forEach((dest, i) => { dest.organizer_id = i; });
this.active = false;
if (this.boxes.length == 0 || this.dests.length == 0)
return;
if (this.boxes < this.dests.length)
// dude, your puzzle is like ... unsolvable ?
return; // the alg is not prepared for that
this.active = true;
this.recalculatePlans();
},
hasAnyUsefulBox: function() {
return this.boxes.some((box, boxid) => {
if (!(boxid in this.box_to_dest_plan)
|| !box.canBeTargetted())
return false;
if (!this.getPreferredDirectionForBox(box))
return false;
return true;
});
},
getClosestUsefulBox: function(position) {
let target = null;
let smallest_distance = Infinity;
this.boxes.forEach((box, boxid) => {
if (!(boxid in this.box_to_dest_plan)
|| !box.canBeTargetted())
return;
const dist = Vec2.squareDistance(position,
box.coll.pos);
if (dist >= smallest_distance)
return;
// is it useful to move that box ?
if (!this.getPreferredDirectionForBox(box))
return;
target = box;
smallest_distance = dist;
});
return target;
},
getPlannedDest: function(box) {
const dest = this.box_to_dest_plan[box.organizer_id];
if (dest !== undefined)
return this.dests[dest];
return null;
},
getPreferredDirectionForBox: function(box) {
const dest = this.getPlannedDest(box);
if (!dest)
return null;
// vector from box to destination
const dist = Vec2.sub(dest.coll.pos, box.coll.pos, {});
// assume the box is correctly placed if the difference is
// neglible
if (dist.x > -MOVE_INCREMENT+1 && dist.x < MOVE_INCREMENT -1)
dist.x = 0;
if (dist.y > -MOVE_INCREMENT+1 && dist.y < MOVE_INCREMENT -1)
dist.y = 0;
// find the order in which to try the dirs.
const directions_to_try = [];
add_dirs = (principal, reverse, swap) => {
if (swap) {
const tmp = principal;
principal = reverse;
reverse = tmp;
}
if (!box.canMoveBoxInDirection(principal))
// whatever face you choose, you can't move.
return;
directions_to_try.push(principal, reverse);
};
// remember, these are faces, not dirs relative to box.
// e.g. SOUTH is like grab the box by the top.
const try_x = add_dirs.bind(null, "EAST", "WEST", dist.x < 0);
const try_y = add_dirs.bind(null, "SOUTH", "NORTH", dist.y < 0);
if (dist.x && dist.y) {
// i think we should try the smallest distance first
// this seems more natural
if (Math.abs(dist.x) < Math.abs(dist.y)) {
try_x();
try_y();
} else {
try_y();
try_x();
}
} else if (dist.x)
try_x();
else if (dist.y)
try_y();
for (let direction of directions_to_try) {
// PROBLEM:
// if the idiot IA is currently in the opposite
// direction, it... effectively blocks the moving of
// the box. Actually, the ia can even block the
// movement while attempting to halp.
if (box.faceAvailable(direction))
return direction;
}
return null;
},
getIAForces: function(box, current_force) {
const dest = this.getPlannedDest(box);
if (!dest)
return {x:0, y:0};
const dist = Vec2.sub(dest.coll.pos, box.coll.pos, {});
dist.x = dist.x.limit(-1, 1);
dist.y = dist.y.limit(-1, 1);
if (current_force) {
// oppose the idiot player
if (dist.x == 0 && current_force.x != 0)
dist.x = -current_force.limit(-1, 1);
if (dist.y == 0 && current_force.y != 0)
dist.y = -current_force.limit(-1, 1);
}
return dist;
},
notifyBoxPlaced: function(box) {
if (this.active)
this.recalculatePlans();
}
});
ig.addGameAddon(() => {
nightmarsh = ig.nightmarshPartyPush = new PartyPushableOrganiser();
return nightmarsh;
});
const stolenInteractIcons = {
vertical:new sc.MapInteractIcon(new ig.TileSheet("media/gui/map-icon.png",24,24),{FOCUS:[40,41,42,41],NEAR:[43],RUNNING:[46,47]},0.2),
horizontal:new sc.MapInteractIcon(new ig.TileSheet("media/gui/map-icon.png",24,24),{FOCUS:[40,41,42,41],NEAR:[43],RUNNING:[44,45]},0.2)
};
const MultiplayerPushable = ig.Class.extend({
// used by mapInteract
entity: null,
interactEntry: null,
users: [], // player always first
finalPos: null,
timer: null,
navBlocker: null,
awaitingPlacement: false,
placed: false,
active: false,
init:function(entity) {
this.entity = entity;
this.navBlocker = ig.navigation.getNavBlock(entity);
},
canBeUsed: function() {
return this.active && this.users.length < 2;
},
updateInteractivityState: function() {
const enable_this = this.canBeUsed();
if (!enable_this && this.interactEntry) {
sc.mapInteract.removeEntry(this.interactEntry);
this.interactEntry = null;
} else if (enable_this && !this.interactEntry) {
const icons = stolenInteractIcons;
const zcond = sc.INTERACT_Z_CONDITION;
let inter = new sc.MapInteractEntry(this.entity,
this /* handler*/,
icons.horizontal,
zcond.SAME_Z,
/* interrupting*/
false);
this.interactEntry = inter;
sc.mapInteract.addEntry(inter);
}
},
// PushPullBlock: active mean it can be used.
setActive: function(yesorno) {
this.active = yesorno;
if (!yesorno)
while (this.users.length)
this.removeUserByIndex(0);
this.updateInteractivityState();
},
isActive: function() {
return this.active;
},
// idiot clicked on map interaction, sc.MapInteract
onInteraction: function() {
this.addAndMoveUser(ig.game.playerEntity);
},
// apparently called when the user leaves the mouse button,
// except i don't know how the leave event happens.
onInteractionEnd: function() {
// FIXME
this.removeUser(ig.game.playerEntity);
},
// user has been forced out of interacting, e.g. was punched in the face
onInteractObjectDrop: function() {
const player = ig.game.playerEntity;
// why would we set it to true ?
// player.coll.ignoreCollision = false;
// why ?
if (player.coll.pos.z - player.coll.baseZPos >= 1)
player.setPos(undefined, undefined,
player.coll.baseZPos);
// this.entity.coll.groundSlip = false ?
player.cancelInteract();
this.removeUser(player);
player.animationFixed = false;
},
// still sc.MapInteract
isInteractionBlocked: function() {
const userpos = Vec2.create();
if (this.usedByPlayer())
return false; // don't block if using.
const player = ig.game.playerEntity;
const dir = this.getDirectionFromPos(player);
const possible = this.getDirectionRestriction();
if (!this.directionCompatible(dir, possible))
// wrong dir.
return true;
const whatever = {};
const trace = ig.game.physics.initTraceResult({});
const dest_pos = this.basePositionFromDirection(dir, player);
// now, dest_pos is the rough destination of where to go
Vec2.sub(dest_pos, player.getCenter());
// now dest_pos is a vector from player to destination.
let not_accessible
= ig.game.traceEntity(trace, player,
dest_pos.x, dest_pos.y,
0, 0,
ig.COLLISION.HEIGHT_TOLERATE,
ig.COLLTYPE.VIRTUAL);
return not_accessible;
},
addAndMoveUser : function(entity, direction) {
if (!direction)
direction = this.getDirectionFromPos(entity);
const userentry = this.addUser(direction, entity);
if (!userentry)
return;
const userpos = Vec2.create(this.entity.coll.pos);
Vec2.add(userpos, userentry.relpos);
const actions
= new ig.Action("gripmultiblock",
[{type:"MOVE_TO_POINT",
target:userpos,
precise: false},
{type:"SET_FACE",
face: direction},
{type:"SHOW_ANIMATION",
anim:"gripStand"}]);
entity.setAction(actions,true);
},
getDirectionFromPos : function(entity) {
const userpos = Vec2.create();
let user_pos = entity.getCenter(userpos);
const ourpos = Vec2.create();
this.entity.getCenter(ourpos);
user_pos = Vec2.sub(user_pos, ourpos);
if (Math.abs(user_pos.x) > Math.abs(user_pos.y))
return user_pos.x < 0 ? "EAST" : "WEST";
else
return user_pos.y < 0 ? "SOUTH": "NORTH";
},
usedByPlayer: function() {
return this.users[0] === ig.game.playerEntity;
},
addUser: function(grip_direction, entity) {
// grip_direction: NORTH SOUTH EAST WEST
const entry = {entity: entity, dir: grip_direction,
relpos: Vec2.create(),
force: Vec2.create()};
if (entity === ig.game.playerEntity)
this.users.unshift(entry);
else
this.users.push(entry);
this.updateInteractivityState();
this.updateRelativePositions();
if (entity === ig.game.playerEntity)
// This blocks control, but where are the controls ?
entity.interactObject = this;
return entry;
},
removeUserByIndex: function(index) {
const entity = this.users.splice(index, 1)[0].entity;
this.updateRelativePositions();
if (entity === ig.game.playerEntity)
// regain control to player.
entity.interactObject = null;
if (entity.hasAction())
entity.cancelAction();
this.updateInteractivityState();
},
removeUser: function(entity) {
const match = x => x.entity === entity;
const index = this.users.findIndex(match);
if (index === -1) {
// we do this way more than necessary now, for 'safety'
// reason (i.e. we do crap without understanding shit)
//console.warn("non-existent entity removed");
return;
}
this.removeUserByIndex(index);
},
directionToRestriction: function(face) {
switch (face) {
case "WEST":
case "EAST":
return sc.PUSH_PULL_DIRECTION.LEFT_RIGHT;
case "NORTH":
case "SOUTH":
return sc.PUSH_PULL_DIRECTION.UP_DOWN;
}
},
directionCompatible: function(face, possible_dirs) {
if (possible_dirs == sc.PUSH_PULL_DIRECTION.ALL)
return true;
const restriction = this.directionToRestriction(face);
return possible_dirs === restriction;
},
getDirectionRestriction : function() {
const reductor = (possible, user) => {
let ret = this.directionToRestriction(user.dir);
console.assert(this.directionCompatible(user.dir,
possible));
return ret;
};
return this.users.reduce(reductor,
this.entity.pushPullDirection);
},
dirToOffset: function(direction, amountX, amountY) {
if (amountX === undefined)
amountX = 1;
if (amountY === undefined)
amountY = amountX;
switch (direction) {
case "EAST": return { x: amountX, y: 0};
case "WEST": return { x: -amountX, y: 0};
case "SOUTH": return { x: 0, y: amountY};
case "NORTH": return { x: 0, y: -amountY};
}
return null;
},
// get relative position of a would-be lone user.
// add this to entity.coll.pos to get the center position of the user
baseRelativePosFromDirection: function(direction, entity) {
const usersize = entity.coll.size;
const pushablesize = this.entity.coll.size;
// center of box to center of user.
const xshift = usersize.x/2 + pushablesize.x/2;
const yshift = usersize.y/2 + pushablesize.y/2;
// from box topleft to box center: + pushablesize/2
// from box center to user center:
const ret = this.dirToOffset(direction, -xshift, -yshift);
// from user center to user topleft: -usersize.x/2
// but we don't apply it here.
Vec2.addC(ret,
pushablesize.x / 2,
pushablesize.y / 2);
return ret;
},
// like baseRelativePosFromDirection except it's not relative
basePositionFromDirection: function(direction, entity) {
return Vec2.add(this.baseRelativePosFromDirection(direction,
entity),
this.entity.coll.pos);
},
// assumes two users limit.
updateRelativePositions : function() {
let sideshift = {x:0, y:0};
if (this.users.length === 2
&& this.users[0].dir === this.users[1].dir) {
// assume the first user has correct size.
const size = this.users[0].entity.coll.size;
if (this.directionToRestriction(this.users[0].dir)
== sc.PUSH_PULL_DIRECTION.LEFT_RIGHT)
sideshift.y = size.y/2;
else
sideshift.x = size.x/2;
}
this.users.forEach((user, index) => {
const entity = user.entity;
const rel = this.baseRelativePosFromDirection(user.dir,
entity);
if (index)
Vec2.add(rel, sideshift);
else
Vec2.sub(rel, sideshift);
user.relpos = rel;
});
},
updateForces: function() {
let force = Vec2.create();
this.users.forEach((user) => {
if (user.entity.hasAction())
return;
if (user.entity == ig.game.playerEntity) {
sc.control.moveDir(user.force, 1);
} else {
const box = this.entity;
user.force = nightmarsh.getIAForces(box, force);
}
let face = this.dirToOffset(user.dir);
if (face.y == 0)
user.force.y = 0;
else
user.force.x = 0;
if (user.force.x === 0 && user.force.y === 0
&& user.entity.notifyNoForce)
user.entity.notifyNoForce();
Vec2.add(force, user.force);
});
return force;
},
// should only be used when a move increment is finished,
// no need to use it while moving, unless for the IA.
canMoveBox: function(amount) {
const trace = ig.game.physics.initTraceResult({});
let ret = true;
const restore_collision = [];
const temporarily_disable_collision = entity => {
restore_collision.push(entity);
entity.coll.ignoreCollision = true;
};
this.users.forEach(user => {
if (user.entity.hasAction())
// not participating.
return;
if (Vec2.dot(amount, this.dirToOffset(user.dir)) >= 0)
// pushing
return;
// someone is pulling
temporarily_disable_collision(user.entity);
if (ig.game.traceEntity(trace, user.entity,
amount.x, amount.y,
0, 0,
ig.COLLISION.HEIGHT_TOLERATE,
ig.COLLTYPE.BLOCK))
ret = false;
});
if (ret && ig.game.traceEntity(trace, this.entity,
amount.x, amount.y,
0, 0, 1,
ig.COLLTYPE.BLOCK))
ret = false;
restore_collision.forEach(entity =>
entity.coll.ignoreCollision = false);
return ret;
},
// this does not mean that a player can fit, or the box can be moved
// in this dir, it just check for obvious obstacles.
// this should only be used by the IA
canMoveBoxInDirection: function(direction) {
const offset = this.dirToOffset(direction, MOVE_INCREMENT);
return this.canMoveBox(offset);
},
// Return true if there is a chance that this face can be used by an AI
// make sure that the IA has his collision ignored first...
faceAvailable: function(direction) {
const restriction = this.getDirectionRestriction();
if (!this.directionCompatible(direction, restriction))
return false;
if (this.users.some(user => user.direction == direction))
return true; // it's already used, so it should be ok
// assume a player is 20 pixel wide, even if in practice, this
// is is less than that.
const offset = this.dirToOffset(direction, -20);
// we don't need to hack up the ignoreCollision of users this
// time.
const trace = ig.game.physics.initTraceResult({});
if (ig.game.traceEntity(trace, this.entity,
offset.x, offset.y,
0, 0, 1,
ig.COLLTYPE.BLOCK))
return false;
// can't think of anything else for now.
return true;
},
setPositionsOfUsers: function(position, final_pos) {
const move = Vec2.create(position);
Vec2.sub(move, this.entity.coll.pos);
const userpos = Vec2.create();
this.users.forEach(user => {
if (user.entity.hasAction())
return;
Vec2.assign(userpos, this.entity.coll.pos);
Vec2.add(userpos, user.relpos);
// userpos: old ideal center position
// lerp that with the current center position.
// 0: ideal, 1: never ideal
Vec2.lerp(userpos, user.entity.getCenter(), 0.5);
// now advance that to new position
Vec2.add(userpos, move);
// finally, convert to top-left coord
Vec2.subC(userpos,
user.entity.coll.size.x/2,
user.entity.coll.size.y/2);
user.entity.setPos(userpos.x, userpos.y,
this.entity.coll.pos.z);
});
this.entity.setPos(position.x, position.y);
const new_pos = move; // treat as uninitialized.
if (final_pos) {
if (this.navBlocker)
this.navBlocker.update();
const ground
= ig.EntityTools.getGroundEntity(this.entity);
if (!ground)
return true;
if (this.awaitingPlacement) {
this.awaitingPlacement = false;
ground.onPushPullablePlaced(this.entity);
this.placed = true;
ig.nightmarshPartyPush.notifyBoxPlaced(this);
return false;
} else if (ground.onPushPullableDetect
&& ground.onPushPullableDetect(this.entity,
new_pos)) {
this.finalPos = new_pos;
this.setActive(false);
this.awaitingPlacement = true;
return false;
}
}
return true;
},
getNextFinalPosition(force, increment) {
// increment must be a multiple of MOVE_INCREMENT.
// might double it for more users ? as it influence momentum
let ret = Vec2.create();
if (force.x == 0)
ret.y = force.y > 0 ? increment : -increment;
else
ret.x = force.x > 0 ? increment : -increment;
const round_me
= x => Math.round(x / MOVE_INCREMENT) * MOVE_INCREMENT;
const current_pos = this.entity.coll.pos;
Vec2.addC(ret,
round_me(current_pos.x),
round_me(current_pos.y));
return ret;
},
moveBox: function(force) {
if (this.finalPos !== null) {
// continue moving the box
const base_speed = 100 * ig.system.tick;
const left_to_move = Vec2.create(this.finalPos);
Vec2.sub(left_to_move, this.entity.coll.pos);
const dist_left = Vec2.length(left_to_move);
const force_length = Vec2.length(force);
const step = force_length.limit(0.75,2) * base_speed;
if (dist_left <= step) {
const final_pos = this.finalPos;
this.finalPos = null;
// may reset the final position in some weird
// cases.
this.setPositionsOfUsers(final_pos, true);
// consume the force
Vec2.length(force,
(1-(dist_left / step)).limit(0,1));
} else {
// not enough force for final pos.
Vec2.length(left_to_move, step);
Vec2.add(left_to_move, this.entity.coll.pos);
this.setPositionsOfUsers(left_to_move);
}
}
if (this.finalPos !== null)
return true;
if (force.x || force.y) {
// start moving the box
this.finalPos
= this.getNextFinalPosition(force,
MOVE_INCREMENT);
const move = Vec2.create(this.finalPos);
Vec2.sub(move, this.entity.coll.pos);
if (!this.canMoveBox(move)) {
this.finalPos = null;
return false;
}/* else
// move us with the remaining force
// except the IA is not prepared for this,
// and will overshoot
return this.moveBox(force);
*/
} else
// need the lerp when not doing anything
this.setPositionsOfUsers(this.entity.coll.pos);
return true;
},
updateUserAnims: function(force, blocked) {
this.users.forEach(user => {
let face = this.dirToOffset(user.dir);
let grip_consider = 0;
if (face.y == 0)
grip_consider = force.x * face.x;
else
grip_consider = force.y * face.y;
if (grip_consider === 0 || blocked)
user.anim = "gripStand";
else if (grip_consider > 0)
user.anim = "gripPush";
else
user.anim = "gripPull";
// could add some anims like gripPushBlocked,
// which would be the first frame of gripPush or
// something
user.entity.setCurrentAnim(user.anim);