-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathppmod.nut
More file actions
executable file
·3011 lines (2489 loc) · 111 KB
/
ppmod.nut
File metadata and controls
executable file
·3011 lines (2489 loc) · 111 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
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
/**
* ppmod version 4
* author: PortalRunner
*/
if (!("Entities" in this)) {
throw "ppmod: Tried to run in a scope without CEntities!";
}
if ("ppmod" in this) {
printl("[ppmod] Warning: ppmod is already loaded!");
return;
}
::ppmod <- {};
/********************/
// Global Utilities //
/********************/
// Returns the smallest of two values
::min <- function (a, b) return a > b ? b : a;
// Returns the largest of two values
::max <- function (a, b) return a < b ? b : a;
// Rounds the input float, optionally to a set precision
::round <- function (a, b = 0) {
if (b == 0) return floor(a + 0.5);
return floor(a * (b = pow(10, b)) + 0.5) / b;
}
// Holds the "not a number" and "infinity" constants for comparison
::nan <- fabs(0.0 / 0.0);
::inf <- 1.0 / 0.0;
// Extends the functionality of Squirrel arrays
class pparray {
arr = null;
constructor (size = 0, fill = null) {
if (typeof size == "array") arr = size;
else arr = array(size, fill);
}
// Overload operators to mimic a standard array
function _typeof () return "array";
function _get (idx) return arr[idx];
function _set (idx, val) return arr[idx] = val;
function _nexti (previdx) {
if (previdx < 0 || previdx >= this.len()) return null;
if (previdx == null) return 0;
return previdx + 1;
}
// Returns a representation of the array values as a string
function _tostring () {
local str = "[";
for (local i = 0; i < arr.len(); i ++) {
if (typeof arr[i] == "string") str += "\"" + arr[i] + "\"";
else str += arr[i];
if (i != arr.len() - 1) str += ", ";
}
return str + "]";
}
// Compares two arrays by their elements
function _cmp (other) {
local shortest = min(arr.len(), other.len());
for (local i = 0; i < shortest; i ++) {
if (arr[i] < other[i]) return -1;
else if (arr[i] > other[i]) return 1;
}
if (arr.len() < other.len()) return -1;
if (arr.len() > other.len()) return 1;
return 0;
}
// Implement standard Squirrel array methods
function len () return arr.len();
function append (val) return arr.append(val);
function push (val) return arr.push(val);
function extend (other) return arr.extend(other);
function pop () return arr.pop();
function top () return arr.top();
function insert (idx, val) return arr.insert(idx, val);
function remove (idx) return arr.remove(idx);
function resize (size, fill = null) return arr.resize(size, fill);
function sort (func = null) return func ? arr.sort(func) : arr.sort();
function reverse () return arr.reverse();
function slice (start, end = null) return pparray(arr.slice(start, end || arr.len()));
function tostring () return _tostring();
function clear () return arr.clear();
// Implement additional methods to extend array functionality
function shift () return arr.remove(0);
function unshift (val) return arr.insert(0, val);
// Joins the elements of the array into a string
function join (separator = ",") {
local str = "";
for (local i = 0; i < arr.len(); i ++) {
str += arr[i];
if (i != arr.len() - 1) str += separator;
}
return str;
}
// Checks if the contents of the two arrays are identical
function equals (other) {
if (arr.len() != other.len()) return 0;
for (local i = 0; i < arr.len(); i ++) {
if (typeof arr[i] == "array") {
if (arr[i].equals(other[i]) == 0) return 0;
} else {
if (arr[i] != other[i]) return 0;
}
}
return 1;
}
// Returns the index of the first element to match the input value
// Returns -1 if no such element is found
function indexof (match, start = 0) {
for (local i = start; i < arr.len(); i ++) {
if (arr[i] == match) return i;
}
return -1;
}
// Returns the index of the first element to pass the compare function
function find (match, start = 0) {
for (local i = start; i < arr.len(); i ++) {
if (match(arr[i])) return i;
}
return -1;
}
// Returns true if the array contains the element, false otherwise
function includes (match, start = 0) {
return indexof(match, start) != -1;
}
}
// Implements the heap data type
class ppheap {
arr = pparray([0]);
size = 0;
maxsize = 0;
comp = null;
constructor (maxs = 0, comparator = null) {
maxsize = maxs;
arr = pparray(maxsize * 4 + 1,0);
if (comparator) {
comp = comparator;
} else {
comp = function (a, b) { return a < b };
}
}
// Returns true if the heap is empty, false otherwise
function isempty () return size == 0;
// Sifts down the element at the given index to its correct position in the heap
function bubbledown (hole) {
local temp = arr[hole];
while (hole * 2 <= size) {
local child = hole * 2;
if (child != size && comp(arr[child + 1], arr[child])) child ++;
if (comp(arr[child], temp)) {
arr[hole] = arr[child]
} else {
break;
}
hole = child;
}
arr[hole] = temp;
}
// Removes the top element of the heap and returns it
function remove () {
if (isempty()) {
throw "ppheap: Heap is empty";
} else {
local tmp = arr[1];
arr[1] = arr[size--];
bubbledown(1);
return tmp;
}
}
// Returns the top element of the heap
function gettop () {
if (isempty()) {
throw "ppheap: Heap is empty";
} else {
return arr[1];
}
}
// Insers the given element into the heap
function insert (val) {
if (size == maxsize) {
throw "ppheap: Exceeded max heap size";
}
arr[0] = val;
local hole = ++size;
while (comp(val, arr[hole / 2])) {
arr[hole] = arr[hole / 2];
hole /= 2;
}
arr[hole] = val;
}
}
// Extends the functionality of Squirrel strings
class ppstring {
string = null;
constructor (str = "") {
string = str.tostring();
}
// Overload operators to mimic a standard string
function _typeof () return "string";
function _tostring () return string;
function _add (other) return ppstring(string + other.tostring());
function _get (idx) return string[idx];
function _set (idx, val) return string = string.slice(0, idx) + val.tochar() + string.slice(idx + 1);
function _cmp (other) {
if (string == other.tostring()) return 0;
if (string > other.tostring()) return 1;
return -1;
}
// Implement standard Squirrel string methods
function len () return string.len();
function tointeger () return string.tointeger();
function tofloat () return string.tofloat();
function tostring () return string;
function slice (start, end = null) return ppstring(string.slice(start, end || string.len()));
function find (substr, start = 0) return string.find(substr, start);
function tolower () return ppstring(string.tolower());
function toupper () return ppstring(string.toupper());
function strip () return ppstring(::strip(string));
function lstrip () return ppstring(::lstrip(string));
function rstrip () return ppstring(::rstrip(string));
// Returns a string which replaces all occurrences of one substring with another
function replace (substr, rep) {
local out = "", prev = 0, idx = 0;
while ((idx = string.find(substr, prev)) != null) {
out += string.slice(prev, idx);
out += rep;
prev = idx + substr.len();
}
return out + string.slice(prev);
}
// Returns a Squirrel array representing the string split up by a substring
function split (substr) {
local arr = [], curr = 0, prev = 0;
while ((curr = string.find(substr, curr)) != null) {
curr = max(curr, prev + 1);
arr.push(string.slice(prev, curr));
prev = curr += substr.len();
}
arr.push(string.slice(prev));
return arr;
}
// Returns true if the string includes the given substring
function includes (substr, start = 0) {
return string.find(substr, start) != null;
}
}
/**
* Because of a bug in how objects are restored from Portal 2 save files,
* using a class for ppromise causes crashes on save load. Instead, we
* mimic a class structure by returning a table from a function.
*/
// Methods for the ppromise prototypal class
local ppromise_methods = {
// Attaches a function to be executed when the promise fullfils
then = function (onthen, oncatch = function (x) { throw x }) {
if (typeof onthen != "function" || typeof oncatch != "function") {
throw "ppromise: Invalid arguments for .then handler";
}
// Run the function immediately if the promise has already fulfilled
if (state == "fulfilled") { onthen(value); return this }
if (state == "rejected") { oncatch(value); return this }
onfulfill.push(onthen);
onreject.push(oncatch);
return this;
},
// Attaches a function to be executed when the promise is rejected
except = function (oncatch) {
if (typeof oncatch != "function") {
throw "ppromise: Invalid argument for .except handler";
}
// Run the function immediately if the promise has already rejected
if (state == "rejected") return oncatch(value);
onreject.push(oncatch);
return this;
},
// Attaches a function to be executed when the promise resolves
finally = function (onfinally) {
if (typeof finally != "function") {
throw "ppromise: Invalid argument for .finally handler";
}
// Run the function immediately if the promise has already resolved
if (state != "pending") return onfinally(value);
onresolve.push(onfinally);
return this;
},
// Fulfills the given ppromise instance with the given value
resolve = function (inst, val) {
// If the promise has already been resolved, do nothing
if (inst.state != "pending") return;
// Update the promise state and value
inst.state = "fulfilled";
inst.value = val;
// Call all relevant functions attached to the promise
for (local i = 0; i < inst.onfulfill.len(); i ++) inst.onfulfill[i](val);
for (local i = 0; i < inst.onresolve.len(); i ++) inst.onresolve[i]();
},
// Rejects the given ppromise instance with the given value
reject = function (inst, err) {
// If the promise has already been resolved, do nothing
if (inst.state != "pending") return;
// Update the promise state and value
inst.state = "rejected";
inst.value = err;
// If no error handler has been attached, throw the error
if (inst.onreject.len() == 0) throw err;
// Call all relevant functions attached to the promise
for (local i = 0; i < inst.onreject.len(); i ++) inst.onreject[i](err);
for (local i = 0; i < inst.onresolve.len(); i ++) inst.onresolve[i]();
}
}
// Constructor for the ppromise prototypal class
::ppromise <- function (func):(ppromise_methods) {
// Create a table to act as the class instance
local inst = {
onresolve = [],
onfulfill = [],
onreject = [],
state = "pending",
value = null,
then = ppromise_methods.then,
except = ppromise_methods.except,
finally = ppromise_methods.finally
resolve = null,
reject = null
};
// Wrappers for the resolve/reject handlers, capturing this instance
inst.resolve = function (val = null):(ppromise_methods, inst) {
ppromise_methods.resolve(inst, val);
};
inst.reject = function (err = null):(ppromise_methods, inst) {
ppromise_methods.reject(inst, err);
};
// Run the input function
try { func(inst.resolve, inst.reject) }
catch (e) { inst.reject(e) }
// Return the table representing a ppromise class instance
return inst;
}
/**
* Asynchronous functions are implemented using Squirrel generators.
* Since a generator is essentially a function that can return some output
* without exiting, we can use this property to suspend code execution
* until another procedure is done processing the returned (yielded)
* output, at which point the generator is told to resume.
*/
// Holds generators used for async functions
::ppmod.asyncgen <- [];
// Holds the value of the last ppromise yielded from an async function
::yielded <- null;
// Runs an async generator over and over until end of scope is reached
::ppmod.asyncrun <- function (id, resolve, reject):(ppromise_methods) {
// Holds the yielded/returned value of the generator
local next;
try { next = resume ppmod.asyncgen[id] }
catch (e) { return reject(e) }
// If the generator has finished running, resolve the async function
if (ppmod.asyncgen[id].getstatus() == "dead") {
ppmod.asyncgen[id] = null;
return resolve(next);
}
// Ensure we're handling a ppromise instance
if (next.then != ppromise_methods.then) {
throw "async: Function did not yield a ppromise";
}
// Resume the generator when the promise resolves
next.then(function (val):(id, resolve, reject) {
::yielded <- val;
ppmod.asyncrun(id, resolve, reject);
});
}
// Converts a function to one that returns a ppromise
::async <- function (func) {
return function (...):(func) {
// Extract the arguments and format them for acall()
local args = array(vargc + 1);
for (local i = 0; i < vargc; i ++) args[i + 1] = vargv[i];
args[0] = this;
// Create a ppromise which runs the input function as a generator
return ppromise(function (resolve, reject):(func, args) {
// Find a free spot in ppmod.asyncgen to insert this function
for (local i = 0; i < ppmod.asyncgen.len(); i ++) {
if (ppmod.asyncgen[i] == null) {
ppmod.asyncgen[i] = func.acall(args);
ppmod.asyncrun(i, resolve, reject);
return;
}
}
// If no free space was found, extend the array by pushing to it
ppmod.asyncgen.push(func.acall(args));
ppmod.asyncrun(ppmod.asyncgen.len() - 1, resolve, reject);
});
};
}
// Extend Vector class functionality
try {
// Implement multiplication with other Vectors
function Vector::_mul (other) {
if (typeof other == "Vector") {
return Vector(this.x * other.x, this.y * other.y, this.z * other.z);
} else {
return Vector(this.x * other, this.y * other, this.z * other);
}
}
// Implement component-wise division with numbers and Vectors
function Vector::_div (other) {
if (typeof other == "Vector") {
return Vector(this.x / other.x, this.y / other.y, this.z / other.z);
} else {
return Vector(this.x / other, this.y / other, this.z / other);
}
}
// Implement unary minus
function Vector::_unm () {
return Vector() - this;
}
// Returns true if the components of the two vectors are identical, false otherwise
function Vector::equals (other) {
if (this.x == other.x && this.y == other.y && this.z == other.z) return true;
return false;
}
// Returns a string representation of the Vector as a Vector constructor
function Vector::_tostring () {
return "Vector(" + this.x + ", " + this.y + ", " + this.z + ")";
}
// Fixes the built-in ToKVString function by reimplementing it
function Vector::ToKVString () {
return this.x + " " + this.y + " " + this.z;
}
// Normalizes the vector and returns it
function Vector::Normalize () {
this.Norm();
return this;
}
// Normalizes the vector along just the X/Y axis and returns it
function Vector::Normalize2D () {
this.z = 0.0;
this.Norm();
return this;
}
// Creates a deep copy of the vector and returns it
function Vector::Copy () {
return Vector(this.x, this.y, this.z);
}
// Converts the direction vector(s) to a vector of pitch/yaw/roll angles
function Vector::ToAngles (uvec = null, rad = false) {
// Copy and normalize the forward vector (`this`)
local fvec = this.Copy();
fvec.Norm();
// Calculate yaw/pitch angles
local yaw = atan2(fvec.y, fvec.x);
local pitch = asin(-fvec.z);
local roll = 0.0;
// If an up vector is given, calculate roll
// Reference: https://www.jldoty.com/code/DirectX/YPRfromUF/YPRfromUF.html
if (typeof uvec == "Vector") {
// Copy and normalize the input up vector
uvec = uvec.Copy();
uvec.Norm();
// Calculate the current right vector
local rvec = uvec.Cross(fvec).Normalize();
// Ensure the up vector is orthonormal
uvec = fvec.Cross(rvec).Normalize();
// Calculate right/up vectors at zero roll
local x0 = Vector(0, 0, 1).Cross(fvec).Normalize();
local y0 = fvec.Cross(x0);
// Calculate the sine and cosine of the roll angle
local rollcos = y0.Dot(uvec);
local rollsin;
if (fabs(fabs(fvec.z) - 1.0) < 0.000001) {
// Edge case for the fvec.z +/- 1.0 singularity
rollsin = -uvec.x;
} else {
// Choose a denominator that won't divide by zero
local s = Vector(fabs(x0.x), fabs(x0.y), fabs(x0.z));
local c = (s.x > s.y) ? (s.x > s.z ? "x" : "z") : (s.y > s.z ? "y" : "z");
// Calculate the roll angle sine
rollsin = (y0[c] * rollcos - uvec[c]) / x0[c];
}
// Calculate the signed roll angle
roll = atan2(rollsin, rollcos);
}
// Return angles as a pitch/yaw/roll vector
if (rad) return Vector(pitch, yaw, roll);
return Vector(pitch, yaw, roll) * (180.0 / PI);
}
// Given a vector of pitch/yaw/roll angles, returns forward and up vectors
function Vector::FromAngles (rad = false) {
// Convert degrees to radians if necessary
local ang = this;
if (!rad) ang = this.Copy() * PI / 180.0;
// Precompute sines and cosines of angles
local cy = cos(ang.y), sy = sin(ang.y);
local cp = cos(ang.x), sp = sin(ang.x);
local cr = cos(ang.z), sr = sin(ang.z);
// Calculate the forward and up vectors
return {
fvec = Vector(cy * cp, sy * cp, -sp),
uvec = Vector(cy * sp * sr - sy * cr, sy * sp * sr + cy * cr, cp * sr)
};
}
} catch (e) {
printl("[ppmod] Warning: failed to modify Vector class: " + e);
}
/*********************/
// Entity management //
/*********************/
// Finds an entity which matches the given parameters
::ppmod.get <- function (arg1, arg2 = null, arg3 = null, arg4 = null) {
// Entity iterator
local curr = null;
// The type of the first argument determines the operation
switch (typeof arg1) {
case "string": {
// Try to first find a match by targetname
if (curr = Entities.FindByName(arg2, arg1)) return curr;
// Fall back to a match by classname
if (curr = Entities.FindByClassname(arg2, arg1)) return curr;
// Fall back to a match by model name
return Entities.FindByModel(arg2, arg1);
}
case "Vector": {
// The second argument is the radius, 32u by default
if (arg2 == null) arg2 = 32.0;
// The filter argument is optional, and thus the starting entity
// may be in either the third or fourth position. This makes sure
// that it is always in arg4.
if (typeof arg3 == "instance" && arg3 instanceof CBaseEntity) {
arg4 = arg3;
}
// Validate the starting entity (fourth argument)
if (arg4 != null && !(typeof arg4 == "instance" && arg4 instanceof CBaseEntity)) {
throw "get: Invalid starting entity";
}
// If no valid filter was provided, get the first entity in the radius
if (typeof arg3 != "string") {
return Entities.FindInSphere(arg4, arg1, arg2);
}
// If a filter was provided, find an entity in the radius that matches it
while (arg4 = Entities.FindInSphere(arg4, arg1, arg2)) {
if (!arg4.IsValid()) continue;
if (arg4.GetName() == arg3 || arg4.GetClassname() == arg3 || arg4.GetModelName() == arg3) {
return arg4;
}
}
// Return null if nothing was found
return null;
}
case "integer": {
// Iterate through all entities to find a matching entindex
while (curr = Entities.Next(curr)) {
if (!curr.IsValid()) continue;
if (curr.entindex() == arg1) return curr;
}
// Return null if no such entity exists
return null;
}
case "instance": {
// If provided an entity, validate it and echo it back
if (ppmod.validate(arg1)) return arg1;
else return null;
}
default:
throw "get: Invalid first argument";
}
}
// Returns true if the input is a valid entity handle, false otherwise
::ppmod.validate <- function (ent) {
// Entity handles must be of type "instance"
if (typeof ent != "instance") return false;
// Entity handles must be instances of CBaseEntity
if (ent instanceof CBaseEntity) return ent.IsValid();
return false;
}
// Iterates through all entities that match the given criteria
::ppmod.forent <- function (args, callback) {
// Convert the input to an array if it isn't already
if (typeof args != "array") args = [args];
// Prepare args for use with acall()
args.insert(0, this);
// If the last argument is not a valid starting entity, push null
local last = args.len() - 1;
if (!ppmod.validate(args[last]) && args[last] != null) {
args.push(null);
last ++;
}
// Iterate through entities, running the callback on each valid one
while (args[last] = ppmod.get.acall(args)) {
if (!args[last].IsValid()) continue;
callback(args[last]);
}
}
// Iterates over entities backwards using ppmod.get
::ppmod.prev <- function (...) {
// Set up entity iterators
local start = null, curr = null, prev = null;
// If the last argument is a valid starting entity, assign it
if (ppmod.validate(vargv[vargc - 1])) {
start = vargv[vargc - 1];
curr = start;
}
do {
// Keep track of the entity from the previous iteration
prev = curr;
// Because vargv isn't a typical array, we can't use acall() here
if (vargc < 3) curr = ppmod.get(vargv[0], curr);
else if (vargc == 3) curr = ppmod.get(vargv[0], vargv[1], curr);
else curr = ppmod.get(vargv[0], vargv[1], vargv[2], curr);
// Run until we end up where we started
} while (curr != start);
// Return the entity from the last iteration
return prev;
}
// Calls an input on an entity with optional default arguments
::ppmod.fire <- function (ent, action = "Use", value = "", delay = 0.0, activator = null, caller = null) {
// If a string was provided, use DoEntFire
if (typeof ent == "string") {
return DoEntFire(ent, action, value.tostring(), delay, activator, caller);
}
// If an entity handle was provided, use EntFireByHandle
if (typeof ent == "instance" && ent instanceof CBaseEntity) {
if (!ent.IsValid()) throw "fire: Invalid entity handle";
return EntFireByHandle(ent, action, value.tostring(), delay, activator, caller);
}
// If any other argument was provided, use ppmod.forent to search for handles
ppmod.forent(ent, function (curr):(action, value, delay, activator, caller) {
ppmod.fire(curr, action, value, delay, activator, caller);
});
}
// Sets an entity keyvalue by automatically determining input type
::ppmod.keyval <- function (ent, key, val) {
// Validate the key argument
if (typeof key != "string") throw "keyval: Invalid key argument";
// If not provided with an entity handle, use ppmod.forent to search for handles
if (!ppmod.validate(ent)) {
return ppmod.forent(ent, function (curr):(key, val) {
ppmod.keyval(curr, key, val);
});
}
// Use the appropriate method based on input type
switch (typeof val) {
case "integer":
case "bool":
ent.__KeyValueFromInt(key, val.tointeger());
break;
case "float":
ent.__KeyValueFromFloat(key, val);
break;
case "Vector":
ent.__KeyValueFromVector(key, val);
break;
default:
ent.__KeyValueFromString(key, val.tostring());
}
}
// Sets entity spawn flags from the argument list
::ppmod.flags <- function (ent, ...) {
// Sum up all entries in vargv
local sum = 0;
for (local i = 0; i < vargc; i ++) {
sum += vargv[i];
}
// Call ppmod.keyval to apply the SpawnFlags keyvalue
ppmod.keyval(ent, "SpawnFlags", sum);
}
// Creates an output to fire on the specified target with optional default arguments
::ppmod.addoutput <- function (ent, output, target, input = "Use", value = "", delay = 0, max = -1) {
// If the target is not a string, wrap a ppmod.fire call inside of
// ppmod.addscript to simulate an output whose target is a ppmod.forent argument.
if (typeof target != "string") {
return ppmod.addscript(ent, output, function ():(target, input, value) {
ppmod.fire(target, input, value, 0.0, activator, caller);
}, delay, max);
}
// Otherwise, assign the output as a keyvalue separated by x1B characters.
// This seems to be how entity outputs are represented internally, and
// should in theory be faster and safer than using the AddOutput input.
ppmod.keyval(ent, output, target+"\x1B"+input+"\x1B"+value+"\x1B"+delay+"\x1B"+max);
}
// Keep track of a "script queue" for inline functions
// This is used to keep global references to functions for use as callbacks
::ppmod.scrq <- [];
// Adds a function to the script queue, returns its script queue index
::ppmod.scrq_add <- function (scr, max = -1) {
// If the input is a string, compile it into a function
if (typeof scr == "string") scr = compilestring(scr);
// Validate the input script argument
if (typeof scr != "function") throw "scrq_add: Invalid script argument";
// Look for an free space in the script queue array
for (local i = 0; i < ppmod.scrq.len(); i ++) {
if (ppmod.scrq[i] == null) {
ppmod.scrq[i] = [scr, max];
return i;
}
}
// If no free space was found, push it to the end of the array
ppmod.scrq.push([scr, max]);
return ppmod.scrq.len() - 1;
}
// Retrieves a function from the script queue, deleting it if needed
::ppmod.scrq_get <- function (idx) {
// Validate the input script index
if (!(idx in ppmod.scrq)) throw "scrq_get: Invalid script index";
if (ppmod.scrq[idx] == null) throw "scrq_get: Invalid script index";
// Retrieve the function from the queue
local scr = ppmod.scrq[idx][0];
// Clear the script queue index if the max amount of retrievals has been reached
if (ppmod.scrq[idx][1] > 0 && --ppmod.scrq[idx][1] == 0) {
ppmod.scrq[idx] = null;
}
// Return the script queue function
return scr;
}
// Adds a script as an output to an entity with optional default arguments
::ppmod.addscript <- function (ent, output, scr = "", delay = 0, max = -1) {
if (typeof scr == "function") {
// If a function was provided, add it to the script queue
local scrq_idx = ppmod.scrq_add(scr, max);
local scrq_arr = ppmod.scrq[scrq_idx];
// Attach a destructor to clear the scrq entry when the entity dies
ppmod.onkill(ent, function ():(scrq_idx, scrq_arr) {
if (ppmod.scrq[scrq_idx] != scrq_arr) return;
ppmod.scrq[scrq_idx] = null;
});
// Convert the argument to a scrq_get call string
scr = "ppmod.scrq_get(" + scrq_idx + ")()";
}
// Attach the output as a keyvalue, similar to how ppmod.addoutput does it
// The script is targeted to worldspawn, as that makes activator and caller available
ppmod.keyval(ent, output, "worldspawn\x001BRunScriptCode\x1B"+scr+"\x1B"+delay+"\x1B"+max);
}
// Runs the specified script in the entity's script scope
::ppmod.runscript <- function (ent, scr) {
// If a function was provided, add it to the script queue
if (typeof scr == "function") {
scr = "ppmod.scrq_get(" + ppmod.scrq_add(scr, 1) + ")()";
}
// Fire the RunScriptCode output on the input entity
ppmod.fire(ent, "RunScriptCode", scr);
}
// Assigns or clears the movement parent of an entity
::ppmod.setparent <- function (child, _parent) {
// If the new parent value is falsy, clear the parent
if (!_parent) return ppmod.fire(child, "ClearParent");
// Validate the parent handle
if (!ppmod.validate(_parent)) throw "setparent: Invalid parent handle";
// If a valid parent handle was provided, assign the parent
return ppmod.fire(child, "SetParent", "!activator", 0, _parent);
}
// Iterates over the children of an entity
::ppmod.getchild <- function (_parent, ent = null) {
// Validate input arguments
if (!ppmod.validate(_parent)) throw "getchild: Invalid parent entity";
if (ent != null && !ppmod.validate(ent)) throw "getchild: Invalid iterator entity";
// Iterate over all world entities, looking for those with a common parent
while (ent = Entities.Next(ent)) {
if (!ent.IsValid()) continue;
if (ent.GetMoveParent() != _parent) continue;
return ent;
}
return ent;
}
// Hooks an entity input, running a test function each time it's fired
::ppmod.hook <- function (ent, input, scr, max = -1) {
// Validate arguments
if (typeof input != "string") throw "hook: Invalid input argument";
if (typeof max != "integer") throw "hook: Invalid max argument";
if (typeof scr == "string") scr = compilestring(scr);
if (scr != null && typeof scr != "function") throw "hook: Invalid script argument";
// If a valid entity handle was not provided, find handles with ppmod.forent
if (!ppmod.validate(ent)) {
return ppmod.forent(ent, function (curr):(input, scr, max) {
ppmod.hook(curr, input, scr, max);
});
}
// Ensure a script scope exists for the entity
if (!ent.ValidateScriptScope()) {
throw "hook: Could not validate entity script scope";
}
// If the new script is null, clear the hook
if (scr == null) delete ent.GetScriptScope()["Input"+input];
// Otherwise, assign a new hook function
else ent.GetScriptScope()["Input"+input] <- scr;
}
// Attaches a function to be called when the entity is Kill-ed
::ppmod.onkill <- function (ent, scr) {
// Validate arguments
if (typeof scr == "string") scr = compilestring(scr);
if (typeof scr != "function") throw "onkill: Invalid script argument";
// If a valid entity handle was not provided, find handles with ppmod.forent
if (!ppmod.validate(ent)) {
return ppmod.forent(ent, function (curr):(scr) {
ppmod.onkill(curr, scr);
});
}
// Create and retrieve the entity's script scope
if (!ent.ValidateScriptScope()) throw "onkill: Failed to create entity script scope";
local scope = ent.GetScriptScope();
if (!("__destructors" in scope)) {
// If this is the first destructor, initialize an array
scope.__destructors <- [];
// Hook the "Kill" and "KillHierarchy" inputs to call destructors
scope.InputKill <- function ():(scope) {
for (local i = 0; i < scope.__destructors.len(); i ++) {
scope.__destructors[i]();
}
return true;
};
scope.InputKillHierarchy <- scope.InputKill;
}
// Push the new destructor to the entity's destructors array
scope.__destructors.push(scr);
}
// Implement shorthands of the above functions into the entities as methods
local entclasses = [CBaseEntity, CBaseAnimating, CBaseFlex, CBasePlayer, CEnvEntityMaker, CLinkedPortalDoor, CPortal_Player, CPropLinkedPortalDoor, CSceneEntity, CTriggerCamera];
for (local i = 0; i < entclasses.len(); i ++) {
try {
// Allows for setting keyvalues as if they were object properties
entclasses[i]._set <- function (key, val) {
// This is mostly identical to ppmod.keyval
// However, having this be separate is slightly more performant
if (typeof key != "string") throw "Invalid slot name";
switch (typeof val) {
case "integer":
case "bool":
this.__KeyValueFromInt(key, val.tointeger());
break;
case "float":
this.__KeyValueFromFloat(key, val);
break;
case "Vector":
this.__KeyValueFromVector(key, val);
break;
default:
this.__KeyValueFromString(key, val.tostring());
}
return val;
}
// Allows for firing inputs/connecting outputs as if they were methods
entclasses[i]._get <- function (key) {
return function (value = "", delay = 0.0, activator = null, caller = null):(key) {
// If a function was provided, treat `key` as an output
if (typeof value == "function") return ::ppmod.addscript(this, key, value, delay, activator);
// Otherwise, treat `key` as an input
return ::EntFireByHandle(this, key, value.tostring(), delay, activator, caller);
}
}
// Self-explanatory wrappers for ppmod functions
entclasses[i].Fire <- function (action = "Use", value = "", delay = 0.0, activator = null, caller = null) {
return ::EntFireByHandle(this, action, value.tostring(), delay, activator, caller);
}
entclasses[i].AddOutput <- function (output, target, input = "Use", value = "", delay = 0, max = -1) {
return ::ppmod.addoutput(this, output, target, input, value, delay, max);
}
entclasses[i].AddScript <- function (output, scr = "", delay = 0, max = -1) {
return ::ppmod.addscript(this, output, scr, delay, max);
}
entclasses[i].RunScript <- function (scr) {
return ::ppmod.runscript(this, scr);
}
entclasses[i].SetMoveParent <- function (_parent) {
return ::ppmod.setparent(this, _parent);
}