/
libcampaign.js
3217 lines (2980 loc) · 88.4 KB
/
libcampaign.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
//;; \section{libcampaign.js documentation}
//;;
//;; \texttt{libcampaign.js} is a JavaScript library supplied with the game,
//;; which contains reusable code for campaign scenarios. It is designed to
//;; make scenario development as high-level and declarative as possible.
//;; It also contains a few simple convenient wrappers.
//;; Public API functions of \texttt{libcampaign.js} are prefixed with
//;; `\texttt{cam}'. To use \texttt{libcampaign.js}, add the following include
//;; into your scenario code:
//;;
//;; \begin{lstlisting}
//;; include("script/campaign/libcampaign.js");
//;; \end{lstlisting}
//;;
//;; Also, most of the \texttt{libcampaign.js} features require some of the
//;; game events handled by the library. Transparent JavaScript pre-hooks are
//;; therefore injected into your global event handlers upon include. For
//;; example, if \texttt{camSetArtifacts()} was called to let
//;; \texttt{libcampaign.js} manage scenario artifacts, then
//;; \texttt{eventPickup()} will be first handled by the library, and only then
//;; your handler will be called, if any.
//;; All of this happens automagically and does not normally require
//;; your attention.
/*
Private vars and functions are prefixed with `__cam'.
Please do not use private stuff in scenario code, use only public API.
We CANNOT put our private vars into an anonymous namespace, even though
it's a common JS trick -
(function(global) {
var __camPrivateVar; // something like that
})(this);
because they would break on savegame-loadgame. So let's just agree
that we'd never use them anywhere outside the file, so that it'd be easier
to change them, and also think twice before we change the public API.
The lib is split into sections, each section is separated with a slash line:
////////////////////////////////////////////////////////////////////////////////
// Section name.
////////////////////////////////////////////////////////////////////////////////
yeah, like that. Also, it's exactly 80 characters wide.
In each section, public stuff is on TOP, and private stuff
is below, split from the public stuff with:
//////////// privates
, for easier reading (all the useful stuff on top).
Please leave camDebug() around if something that should never happen
occurs, indicating an actual bug in campaign. Then a sensible message
should be helpful as well. But normally, no warnings should ever be
printed.
In cheat mode, more warnings make sense, explaining what's going on
under the hood. Use camTrace() for such warnings - they'd auto-hide
outside cheat mode.
Lines prefixed with // followed by ;; are docstrings for JavaScript API
documentation. Visit
http://buildbot.wz2100.net/files/javascript/javascript.html
to see how it looks. The documentation is coded in TeX; but please
use only very simple TeX, because it would then be compiled to
HTML by HeVeA, which fails to support most of the complicated stuff.
*/
////////////////////////////////////////////////////////////////////////////////
// Library initialization.
////////////////////////////////////////////////////////////////////////////////
// Registers a private event namespace for this library, to avoid collisions with
// any event handling in code using this library. Make sure no other library uses
// the same namespace, or strange things will happen. After this, we can name our
// event handlers with the registered prefix, and they will still get called.
namespace("cam_");
////////////////////////////////////////////////////////////////////////////////
// Misc useful stuff.
////////////////////////////////////////////////////////////////////////////////
//These are campaign player numbers.
const CAM_HUMAN_PLAYER = 0;
const NEW_PARADIGM = 1;
const THE_COLLECTIVE = 2;
const NEXUS = 3;
const CAM_MAX_PLAYERS = 8;
const CAM_TICKS_PER_FRAME = 100;
//;; \subsection{camDef(something)}
//;; Returns false if something is JavaScript-undefined, true otherwise.
function camDef(something)
{
return typeof(something) !== "undefined";
}
//;; \subsection{camIsString(something)}
//;; Returns true if something is a string, false otherwise.
function camIsString(something)
{
return typeof(something) === "string";
}
//;; \subsection{camRand(max)}
//;; A non-synchronous random integer in range [0, max - 1].
function camRand(max)
{
if (max > 0)
return Math.floor(Math.random() * max);
camDebug("Max should be positive");
}
//;; \subsection{camCallOnce(function name)}
//;; Call a function by name, but only if it has not been called yet.
function camCallOnce(callback)
{
if (camDef(__camCalledOnce[callback]) && __camCalledOnce[callback])
return;
__camCalledOnce[callback] = true;
__camGlobalContext()[callback]();
}
//;; \subsection{camSafeRemoveObject(obj[, special effects?])}
//;; Remove a game object (by value or label) if it exists, do nothing otherwise.
function camSafeRemoveObject(obj, flashy)
{
if (__camLevelEnded)
return;
if (camIsString(obj))
obj = getObject(obj);
if (camDef(obj) && obj && (obj.id !== 0))
removeObject(obj, flashy);
}
//;; \subsection{camMakePos(x, y | label | object)}
//;; Make a POSITION-like object, unless already done. Often useful
//;; for making functions that would accept positions in both xx,yy and {x:xx,y:yy} forms.
//;; Also accepts labels. If label of AREA is given, returns the center of the area.
//;; If an existing object or label of such is given, returns a safe JavaScript
//;; object containing its x, y and id.
function camMakePos(xx, yy)
{
if (camDef(yy))
return { x : xx, y : yy };
if (!camDef(xx))
return undefined;
var obj = xx;
if (camIsString(xx))
obj = getObject(xx);
if (!camDef(obj) || !obj)
{
camDebug("Failed at", xx);
return undefined;
}
switch (obj.type)
{
case DROID:
case STRUCTURE:
case FEATURE:
// store ID for those as well.
return { x: obj.x, y: obj.y, id: obj.id };
case POSITION:
case RADIUS:
return obj;
case AREA:
return {
x: Math.floor((obj.x + obj.x2) / 2),
y: Math.floor((obj.y + obj.y2) / 2)
};
case GROUP:
default:
// already a pos-like object?
if (camDef(obj.x) && camDef(obj.y))
return { x: obj.x, y: obj.y };
camDebug("Not implemented:", obj.type);
return undefined;
}
}
//;; \subsection{camDist(x1, y1, x2, y2 | pos1, x2, y2 | x1, y1, pos2 | pos1, pos2)}
//;; A wrapper for \texttt{distBetweenTwoPoints()}.
function camDist(x1, y1, x2, y2)
{
if (camDef(y2)) // standard
return distBetweenTwoPoints(x1, y1, x2, y2);
var pos2 = camMakePos(x2, y2);
if (!camDef(pos2)) // pos1, pos2
return distBetweenTwoPoints(x1.x, x1.y, y1.x, y1.y);
if (camDef(pos2.x)) // x2 is pos2
return distBetweenTwoPoints(x1, y1, pos2.x, pos2.y);
else // pos1, x2, y2
return distBetweenTwoPoints(x1.x, x1.y, y1, x2);
}
//;; \subsection{camPlayerMatchesFilter(player, filter)}
//;; A function to handle player filters in a way similar to
//;; how JS API functions (eg. \texttt{enumDroid(filter, ...)}) handle them.
function camPlayerMatchesFilter(player, filter)
{
switch(filter) {
case ALL_PLAYERS:
return true;
case ALLIES:
return player === CAM_HUMAN_PLAYER;
case ENEMIES:
return player >= 0 && player < CAM_MAX_PLAYERS
&& player !== CAM_HUMAN_PLAYER;
default:
return player === filter;
}
}
//;; \subsection{camRemoveDuplicates(array)}
//;; Remove duplicate items from an array.
function camRemoveDuplicates(array)
{
var prims = {"boolean":{}, "number":{}, "string":{}};
var objs = [];
return array.filter(function(item) {
var type = typeof item;
if(type in prims)
return prims[type].hasOwnProperty(item) ? false : (prims[type][item] = true);
else
return objs.indexOf(item) >= 0 ? false : objs.push(item);
});
}
//;; \subsection{camCountStructuresInArea(label)}
//;; Mimics wzscript's numStructsButNotWallsInArea().
function camCountStructuresInArea(lab)
{
var list = enumArea(lab, CAM_HUMAN_PLAYER, false);
var ret = 0;
for (var i = 0, l = list.length; i < l; ++i)
{
if (list[i].type === STRUCTURE && list[i].stattype !== WALL
&& list[i].status === BUILT)
{
++ret;
}
}
return ret;
}
//;; \subsection{camChangeOnDiff(numeric value, [bool])}
//;; Change a numeric value based on campaign difficulty. If the second option is defined
//;; then the opposite effect will occur on that value.
function camChangeOnDiff(num, invert)
{
var modifier = 0;
if(!camDef(invert))
{
invert = false;
}
switch(difficulty)
{
case EASY:
modifier = (invert === false) ? 1.25 : 0.67;
break;
case MEDIUM:
modifier = 1.00;
break;
case HARD:
modifier = (invert === false) ? 0.80 : 1.50;
break;
case INSANE:
modifier = (invert === false) ? 0.67 : 2.50;
break
default:
modifier = 1.00;
break;
}
return Math.floor(num * modifier);
}
//;; \subsection{camIsSystemDroid(game object)}
//;; Determine if the passed in object is a non-weapon based droid.
function camIsSystemDroid(obj)
{
if(!camDef(obj) || !obj)
{
return false;
}
if (obj.type !== DROID)
{
camTrace("Non-droid: " + obj.type + " pl: " + obj.name);
return false;
}
return (obj.droidType === DROID_SENSOR
|| obj.droidType === DROID_CONSTRUCT
|| obj.droidType === DROID_REPAIR
);
}
//;; \subsection{camMakeGroup(what, filter)}
//;; Make a new group out of array of droids, single game object,
//;; or label string, with fuzzy auto-detection of argument type.
//;; Only droids would be added to the group. \textbf{filter} can be one of
//;; a player index, ALL_PLAYERS, ALLIES or ENEMIES; defaults to ENEMIES.
function camMakeGroup(what, filter)
{
if (!camDef(filter))
filter = ENEMIES;
var array;
var obj;
if (camIsString(what)) // label
obj = getObject(what);
else if (camDef(what.length)) // array
array = what;
else if (camDef(what.type)) // object
obj = what;
if (camDef(obj))
{
switch(obj.type) {
case POSITION:
obj = getObject(obj.x, obj.y);
// fall-through
case DROID:
case STRUCTURE:
case FEATURE:
array = [ obj ];
break;
case AREA:
array = enumArea(obj.x, obj.y, obj.x2, obj.y2,
ALL_PLAYERS, false);
break;
case RADIUS:
array = enumRange(obj.x, obj.y, obj.radius,
ALL_PLAYERS, false);
break;
case GROUP:
array = enumGroup(obj.id);
break;
default:
camDebug("Unknown object type", obj.type);
}
}
if (camDef(array))
{
var group = camNewGroup();
for (var i = 0, l = array.length; i < l; ++i)
{
var o = array[i];
if (!camDef(o) || !o)
{
camDebug("Trying to add", o);
continue;
}
if (o.type === DROID && camPlayerMatchesFilter(o.player, filter))
groupAdd(group, o);
}
return group;
}
camDebug("Cannot parse", what);
}
//////////// privates
var __camCalledOnce = {};
function __camGlobalContext()
{
return Function('return this')();
}
////////////////////////////////////////////////////////////////////////////////
// Research and structure related functions.
////////////////////////////////////////////////////////////////////////////////
//;; \subsection{camEnableRes(list, player)}
//;; Grants research from the given list to player
function camEnableRes(list, player)
{
for(var i = 0, l = list.length; i < l; ++i)
{
enableResearch(list[i], player);
completeResearch(list[i], player);
}
}
//;; \subsection{camCompleteRequiredResearch(items, player)}
//;; Grants research from the given list to player and also researches
//;; the required research for that item.
function camCompleteRequiredResearch(items, player)
{
dump("\n*Player " + player + " requesting accelerated research.");
for (var i = 0, l = items.length; i < l; ++i)
{
dump("Searching for required research of item: " + items[i]);
var reqRes = findResearch(items[i], player).reverse();
if (reqRes.length === 0)
{
continue;
}
reqRes = camRemoveDuplicates(reqRes);
for (var s = 0, r = reqRes.length; s < r; ++s)
{
dump(" Found: " + reqRes[s].name);
enableResearch(reqRes[s].name, player);
completeResearch(reqRes[s].name, player);
}
}
}
////////////////////////////////////////////////////////////////////////////////
// Debugging helpers.
////////////////////////////////////////////////////////////////////////////////
//;; \subsection{camMarkTiles(label | array of labels)}
//;; Mark area on the map by label(s), but only if debug mode is enabled.
//;; Otherwise, remember what to mark in case it is going to be.
function camMarkTiles(label)
{
if (camIsString(label))
{
__camMarkedTiles[label] = true;
}
else
{
for (var i = 0, l = label.length; i < l; ++i)
{
__camMarkedTiles[label[i]] = true;
}
}
// apply instantly
__camUpdateMarkedTiles();
}
//;; \subsection{camUnmarkTiles(label | array of labels)}
//;; No longer mark area(s) with given label(s) in debug mode.
function camUnmarkTiles(label)
{
if (camIsString(label))
{
delete __camMarkedTiles[label];
}
else
{
for (var i = 0, l = label.length; i < l; ++i)
{
delete __camMarkedTiles[label[i]];
}
}
// apply instantly
__camUpdateMarkedTiles();
}
//;; \subsection{camDebug(string...)}
//;; Pretty debug prints - a wrapper around \texttt{debug()}.
//;; Prints a function call stack and the argument message,
//;; prefixed with "DEBUG". Only use this function to indicate
//;; actual bugs in the scenario script, because game shouldn't
//;; print things when nothing is broken. If you want to keep
//;; some prints around to make debugging easier without distracting
//;; the user, use \texttt{camTrace()}.
function camDebug()
{
__camGenericDebug("DEBUG",
arguments.callee.caller.name,
arguments,
true,
__camBacktrace());
}
//;; \subsection{camDebugOnce(string...)}
//;; Same as \texttt{camDebug()}, but prints each message only once
//;; during script lifetime.
function camDebugOnce()
{
var str = arguments.callee.caller.name
+ ": " + Array.prototype.join.call(arguments, " ");
if (camDef(__camDebuggedOnce[str]))
return;
__camDebuggedOnce[str] = true;
__camGenericDebug("DEBUG",
arguments.callee.caller.name,
arguments,
true,
__camBacktrace());
}
//;; \subsection{camTrace(string...)}
//;; Same as \texttt{camDebug()}, but only warns in cheat mode.
//;; Prefixed with "TRACE". It's safe and natural to keep \texttt{camTrace()}
//;; calls in your code for easier debugging.
function camTrace()
{
if (!__camCheatMode)
return;
__camGenericDebug("TRACE",
arguments.callee.caller.name,
arguments);
}
//;; \subsection{camTraceOnce(string...)}
//;; Same as \texttt{camTrace()}, but prints each message only once
//;; during script lifetime.
function camTraceOnce()
{
if (!__camCheatMode)
return;
var str = arguments.callee.caller.name
+ ": " + Array.prototype.join.call(arguments, " ");
if (camDef(__camTracedOnce[str]))
return;
__camTracedOnce[str] = true;
__camGenericDebug("TRACE",
arguments.callee.caller.name,
arguments);
}
//;; \subsection{isCheating()}
//;; Check if the player is in cheat mode.
function isCheating()
{
return __camCheatMode;
}
//////////// privates
var __camMarkedTiles = {};
var __camCheatMode = false;
var __camDebuggedOnce = {};
var __camTracedOnce = {};
function __camUpdateMarkedTiles()
{
hackMarkTiles();
if (__camCheatMode && camDef(__camMarkedTiles))
{
for (var label in __camMarkedTiles)
{
hackMarkTiles(label);
}
}
}
function __camLetMeWin()
{
__camLetMeWinArtifacts();
hackMarkTiles(); // clear marked tiles, as they may actually remain
__camGameWon();
}
function __camWinInfo()
{
console("Picked up", __camNumArtifacts,
"artifacts out of", Object.keys(__camArtifacts).length);
console("Eliminated", __camNumEnemyBases,
"enemy bases out of", Object.keys(__camEnemyBases).length);
}
function __camGenericDebug(flag, func, args, err, bt)
{
if (camDef(bt) && bt)
{
for (var i = bt.length - 1; i >= 0; --i)
{
debug("STACK: from", [bt[i]]);
}
}
if (!func)
func = "<anonymous>";
var str = flag + ": " + func + ": " +
Array.prototype.join.call(args, " ");
debug(str);
if (camDef(err) && err)
dump(str);
}
function __camBacktrace()
{
var func = arguments.callee.caller;
var list = [];
while (camDef(func) && func)
{
if (func.name)
list.push(func.name);
else
list.push("<anonymous>");
func = func.caller;
}
return list;
}
////////////////////////////////////////////////////////////////////////////////
// Artifacts management.
////////////////////////////////////////////////////////////////////////////////
//;; \subsection{camSetArtifacts(artifacts)}
//;; Tell \texttt{libcampaign.js} to manage a certain set of artifacts.
//;; The argument is a JavaScript map from object labels to artifact
//;; description. If the label points to a game object, artifact will be
//;; placed when this object is destroyed; if the label is a position, the
//;; artifact will be placed instantly. Artifact description is a JavaScript
//;; object with the following fields:
//;; \begin{description}
//;; \item[tech] The technology to grant when the artifact is recovered.
//;; \end{description}
//;; On \textbf{let me win} cheat, all technologies stored in the artifacts
//;; managed by this function are automatically granted.
//;; Additionally, this function would call special event callbacks if they are
//;; defined in your script, which should be named as follows,
//;; where LABEL is the artifact label:
//;; \begin{description}
//;; \item[camArtifactPickup_LABEL] Called when the player picks up
//;; the artifact.
//;; \end{description}
function camSetArtifacts(artifacts)
{
__camArtifacts = artifacts;
for (var alabel in __camArtifacts)
{
var ai = __camArtifacts[alabel];
var pos = camMakePos(alabel);
if (camDef(pos.id))
{
// will place when object with this id is destroyed
ai.id = "" + pos.id;
ai.placed = false;
}
else
{
// received position or area, place immediately
var acrate = addFeature("Crate", pos.x, pos.y);
addLabel(acrate, __camGetArtifactLabel(alabel));
ai.placed = true;
}
}
}
//;; \subsection{camAllArtifactsPickedUp()}
//;; Returns true if all artifacts managed by \texttt{libcampaign.js}
//;; were picked up.
function camAllArtifactsPickedUp()
{
// FIXME: O(n) lookup here
return __camNumArtifacts === Object.keys(__camArtifacts).length;
}
//Returns the label of all existing artifacts
function getArtifacts()
{
var camArti = [];
for(var alabel in __camArtifacts)
{
if(camDef(__camArtifacts[alabel]))
{
camArti.push(__camGetArtifactLabel(alabel));
}
}
return camArti;
}
//////////// privates
var __camArtifacts;
var __camNumArtifacts;
function __camGetArtifactLabel(alabel)
{
return alabel + "_artifact_label";
}
function __camGetArtifactKey(objlabel)
{
return objlabel.replace("_artifact_label", "");
}
// called from eventDestroyed
function __camCheckPlaceArtifact(obj)
{
// FIXME: O(n) lookup here
var alabel = getLabel(obj);
if (!camDef(alabel) || !alabel)
return;
var ai = __camArtifacts[alabel];
if (!camDef(ai))
return;
if (ai.placed)
{
camDebug("Object to which artifact", alabel,
"is bound has died twice");
return;
}
camTrace("Placing", ai.tech);
var acrate = addFeature("Crate", obj.x, obj.y);
addLabel(acrate, __camGetArtifactLabel(alabel));
ai.placed = true;
}
function __camPickupArtifact(artifact)
{
if (artifact.stattype !== ARTIFACT)
{
camDebug("Not an artifact");
return;
}
// FIXME: O(n) lookup here
var alabel = __camGetArtifactKey(getLabel(artifact));
var ai = __camArtifacts[alabel];
if (!camDef(alabel) || !alabel || !camDef(ai))
{
camTrace("Artifact", artifact.id, "is not managed");
return;
}
camTrace("Picked up", ai.tech);
playSound("pcv352.ogg", artifact.x, artifact.y, artifact.z);
// artifacts are not self-removing...
camSafeRemoveObject(artifact);
enableResearch(ai.tech);
// bump counter before the callback, so that it was
// actual during the callback
++__camNumArtifacts;
var callback = __camGlobalContext()["camArtifactPickup_" + alabel];
if (camDef(callback))
callback();
}
function __camLetMeWinArtifacts()
{
for (var alabel in __camArtifacts)
{
var ai = __camArtifacts[alabel];
if (ai.placed)
{
var label = __camGetArtifactLabel(alabel);
var artifact = getObject(label);
if (!camDef(artifact) || !artifact)
continue;
__camPickupArtifact(artifact);
}
else
{
enableResearch(ai.tech);
}
}
}
////////////////////////////////////////////////////////////////////////////////
// Enemy base management.
////////////////////////////////////////////////////////////////////////////////
const CAM_REINFORCE_NONE = 0;
const CAM_REINFORCE_GROUND = 1;
const CAM_REINFORCE_TRANSPORT = 2;
//;; \subsection{camSetEnemyBases(bases)}
//;; Tell \texttt{libcampaign.js} to manage a certain set of enemy bases.
//;; Management assumes auto-cleanup of leftovers on destruction, and also
//;; counting how many bases have been successfully destroyed by the player.
//;; The argument is a JavaScript map from group labels to base descriptions.
//;; Each label points to a group of vital base structures. If no group label
//;; with this name is defined, a group is created automatically
//;; based on \textbf{cleanup} area and labeled. Base description
//;; is a JavaScript object with the following optional fields:
//;; \begin{description}
//;; \item[cleanup] An area label to clean up features in once base is
//;; destroyed. If base id is not a group label, this field is required
//;; in order to auto-create the group of stuff in the area which doesn't
//;; qualify as a valid leftover.
//;; \item[detectMsg] A PROX_MSG message id to play when the base is detected.
//;; \item[detectSnd] A sound file to play when the base is detected.
//;; \item[eliminateSnd] A sound file to play when the base is eliminated.
//;; The sound is played in the center of the cleanup area,
//;; which needs to be defined.
//;; \item{player} If base is detected by cleanup area, only objects
//;; matching this player filter would be added to the base group or
//;; cleaned up. Note that this most likely disables feature cleanup.
//;; \end{description}
//;; Additionally, this function would call special event callbacks if they are
//;; defined in your script, which should be named as follows,
//;; where LABEL is the label of the base group:
//;; \begin{description}
//;; \item[camEnemyBaseDetected_LABEL] Called when the player sees an object from
//;; the enemy base group for the first time.
//;; \item[camEnemyBaseEliminated_LABEL] Called when the base is eliminated,
//;; right after leftovers were cleaned up.
//;; \end{description}
function camSetEnemyBases(bases)
{
var reload = !camDef(bases);
if (!reload)
{
__camEnemyBases = bases;
__camNumEnemyBases = 0;
}
// convert label strings to groups and store
for (var blabel in __camEnemyBases)
{
var bi = __camEnemyBases[blabel];
var obj = getObject(blabel);
if (camDef(obj) && obj) // group already defined
{
if (!camDef(bi.group))
{
bi.group = obj.id;
}
else
{
var structures = enumGroup(bi.group);
addLabel({ type: GROUP, id: bi.group }, blabel);
for (var i = 0, l = structures.length; i < l; ++i)
{
var s = structures[i];
if (s.type !== STRUCTURE || __camIsValidLeftover(s))
continue;
if (!camDef(bi.player) ||
camPlayerMatchesFilter(s.player, bi.player))
{
camTrace("Auto-adding", s.id, "to base", blabel);
groupAdd(bi.group, s);
}
}
}
if (!camDef(bi.cleanup)) // auto-detect cleanup area
{
var objs = enumGroup(bi.group);
if (objs.length > 0)
{
var a = {
type: AREA,
x: mapWidth, y: mapHeight,
x2: 0, y2: 0
};
// smallest rectangle to contain all objects
for (var i = 0, l = objs.length; i < l; ++i)
{
var o = objs[i];
if (o.x < a.x) a.x = o.x;
if (o.y < a.y) a.y = o.y;
if (o.x > a.x2) a.x2 = o.x;
if (o.y > a.y2) a.y2 = o.y;
}
// but a bit wider
a.x -= 2; a.y -= 2; a.x2 += 2; a.y2 += 2;
camTrace("Auto-detected cleanup area for", blabel, ":",
a.x, a.y,
a.x2, a.y2);
bi.cleanup = "__cam_enemy_base_cleanup__" + blabel;
addLabel(a, bi.cleanup);
}
}
}
else // define a group automatically
{
if (!camDef(bi.cleanup))
{
camDebug("Neither group nor cleanup area found for", blabel);
continue;
}
bi.group = camNewGroup();
addLabel({ type: GROUP, id: bi.group }, blabel);
var structs = enumArea(bi.cleanup, ENEMIES, false);
for (var i = 0, l = structs.length; i < l; ++i)
{
var s = structs[i];
if (s.type !== STRUCTURE || __camIsValidLeftover(s))
continue;
if (!camDef(bi.player) ||
camPlayerMatchesFilter(s.player, bi.player))
{
camTrace("Auto-adding", s.id, "to base", blabel);
groupAdd(bi.group, s);
}
}
}
if (groupSize(bi.group) === 0)
camDebug("Base", blabel, "defined as empty group");
if(!reload)
{
bi.detected = false;
bi.eliminated = false;
}
camTrace("Resetting label", blabel);
resetLabel(blabel, CAM_HUMAN_PLAYER); // subscribe for eventGroupSeen
}
}
//;; \subsection{camDetectEnemyBase(base label)}
//;; Plays the "enemy base detected" message and places a beacon
//;; for the enemy base defined by the label, as if the base
//;; was actually found by the player.
function camDetectEnemyBase(blabel)
{
var bi = __camEnemyBases[blabel];
if (bi.detected || bi.eliminated)
return;
camTrace("Enemy base", blabel, "detected");
bi.detected = true;
if (camDef(bi.detectSnd))
{
var pos = camMakePos(bi.cleanup);
if (!camDef(pos)) // auto-detect sound position by group object pos
{
var objs = enumGroup(bi.group);
if (objs.length > 0)
pos = camMakePos(objs[0]);
}
if (camDef(pos))
playSound(bi.detectSnd, pos.x, pos.y, 0);
}
if (camDef(bi.detectMsg))
hackAddMessage(bi.detectMsg, PROX_MSG, 0, false);
var callback = __camGlobalContext()["camEnemyBaseDetected_" + blabel];
if (camDef(callback))
callback();
}
//;; \subsection{camAllEnemyBasesEliminated()}
//;; Returns true if all enemy bases managed by \texttt{libcampaign.js}
//;; are destroyed.
function camAllEnemyBasesEliminated()
{
// FIXME: O(n) lookup here
return __camNumEnemyBases === Object.keys(__camEnemyBases).length;
}
//;; \subsection{camSendReinforcement(player, position, droids, kind, data)}
//;; Give a single bunch of droids (template list) for a player at
//;; a position label. Kind can be one of:
//;; \begin{description}
//;; \item[CAM_REINFORCE_GROUND] Reinforcements magically appear
//;; on the ground.
//;; \item[CAM_REINFORCE_TRANSPORT] Reinforcements are unloaded from
//;; a transporter.
//;; \textbf{NOTE:} the game engine doesn't seem to support two simultaneous
//;; incoming transporters for the same player. Avoid this at all costs!
//;; The following data fields are required:
//;; \begin{description}
//;; \item[entry] Transporter entry position.
//;; \item[exit] Transporter exit position.
//;; \item[message] PROX_MSG to display when transport is landing.
//;; \item[order] Order to give to newly landed droids
//;; \item[data] Order data.
//;; \end{description}
//;; \textbf{NOTE:} the game engine doesn't seem to support two simultaneous
//;; incoming transporters for the same player. If a transporter is already
//;; on map, it will be correctly queued up and sent later.
//;; \end{description}
function camSendReinforcement(player, position, list, kind, data)
{
var pos = camMakePos(position);
var order = CAM_ORDER_ATTACK;
var order_data = { regroup: false, count: -1 };
if (camDef(data) && camDef(data.order))
{
order = data.order;
if (camDef(data.data))
{
order_data = data.data;
}
}
switch(kind)
{
case CAM_REINFORCE_GROUND:
var droids = [];
for (var i = 0, l = list.length; i < l; ++i)
{
droids[droids.length] = addDroid(player, pos.x, pos.y,
"Reinforcement", list[i].body,
list[i].prop, "", "", list[i].weap);
}
camManageGroup(camMakeGroup(droids), order, order_data);
break;
case CAM_REINFORCE_TRANSPORT:
__camTransporterQueue[__camTransporterQueue.length] = {
player: player,
position: position,
list: list,
data: data,
order: order,
order_data: order_data
};
__camDispatchTransporterSafe();
break;
default:
camTrace("Unknown reinforcement type");
break;
}
}
//;; \subsection{camSetBaseReinforcements(base label, interval, callback, kind, data)}