-
Notifications
You must be signed in to change notification settings - Fork 2
/
engine.all.js
4369 lines (3810 loc) · 166 KB
/
engine.all.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
/*
LittleJS - Debug Build
MIT License - Copyright 2021 Frank Force
*/
/**
* LittleJS Debug System
* <br> - Press ~ to show debug overlay with mouse pick
* <br> - Number keys toggle debug functions
* <br> - +/- apply time scale
* <br> - Debug primitive rendering
* <br> - Save a 2d canvas as an image
* @namespace Debug
*/
'use strict';
/** True if debug is enabled
* @default
* @memberof Debug */
const debug = 1;
/** True if asserts are enaled
* @default
* @memberof Debug */
const enableAsserts = 1;
/** Size to render debug points by default
* @default
* @memberof Debug */
const debugPointSize = .5;
/** True if watermark with FPS should be down, false in release builds
* @default
* @memberof Debug */
let showWatermark = 1;
/** True if god mode is enabled, handle this however you want
* @default
* @memberof Debug */
let godMode = 0;
// Engine internal variables not exposed to documentation
let debugPrimitives = [], debugOverlay = 0, debugPhysics = 0, debugRaycast = 0,
debugParticles = 0, debugGamepads = 0, debugMedals = 0, debugTakeScreenshot, downloadLink;
///////////////////////////////////////////////////////////////////////////////
// Debug helper functions
/** Asserts if the experssion is false, does not do anything in release builds
* @param {Boolean} assertion
* @param {Object} output
* @memberof Debug */
const ASSERT = enableAsserts ? (...assert)=> console.assert(...assert) : ()=>{};
/** Draw a debug rectangle in world space
* @param {Vector2} pos
* @param {Vector2} [size=new Vector2()]
* @param {String} [color='#fff']
* @param {Number} [time=0]
* @param {Number} [angle=0]
* @param {Boolean} [fill=0]
* @memberof Debug */
const debugRect = (pos, size=vec2(), color='#fff', time=0, angle=0, fill=0)=>
{
ASSERT(typeof color == 'string'); // pass in regular html strings as colors
debugPrimitives.push({pos, size:vec2(size), color, time:new Timer(time), angle, fill});
}
/** Draw a debug circle in world space
* @param {Vector2} pos
* @param {Number} [radius=0]
* @param {String} [color='#fff']
* @param {Number} [time=0]
* @param {Boolean} [fill=0]
* @memberof Debug */
const debugCircle = (pos, radius=0, color='#fff', time=0, fill=0)=>
{
ASSERT(typeof color == 'string'); // pass in regular html strings as colors
debugPrimitives.push({pos, size:radius, color, time:new Timer(time), angle:0, fill});
}
/** Draw a debug point in world space
* @param {Vector2} pos
* @param {String} [color='#fff']
* @param {Number} [time=0]
* @param {Number} [angle=0]
* @memberof Debug */
const debugPoint = (pos, color, time, angle)=> debugRect(pos, 0, color, time, angle);
/** Draw a debug line in world space
* @param {Vector2} posA
* @param {Vector2} posB
* @param {String} [color='#fff']
* @param {Number} [thickness=.1]
* @param {Number} [time=0]
* @memberof Debug */
const debugLine = (posA, posB, color, thickness=.1, time)=>
{
const halfDelta = vec2((posB.x - posA.x)/2, (posB.y - posA.y)/2);
const size = vec2(thickness, halfDelta.length()*2);
debugRect(posA.add(halfDelta), size, color, time, halfDelta.angle(), 1);
}
/** Draw a debug axis aligned bounding box in world space
* @param {Vector2} posA
* @param {Vector2} sizeA
* @param {Vector2} posB
* @param {Vector2} sizeB
* @param {String} [color='#fff']
* @memberof Debug */
const debugAABB = (pA, sA, pB, sB, color)=>
{
const minPos = vec2(min(pA.x - sA.x/2, pB.x - sB.x/2), min(pA.y - sA.y/2, pB.y - sB.y/2));
const maxPos = vec2(max(pA.x + sA.x/2, pB.x + sB.x/2), max(pA.y + sA.y/2, pB.y + sB.y/2));
debugRect(minPos.lerp(maxPos,.5), maxPos.subtract(minPos), color);
}
/** Draw a debug axis aligned bounding box in world space
* @param {String} text
* @param {Vector2} pos
* @param {Number} [size=1]
* @param {String} [color='#fff']
* @param {Number} [time=0]
* @param {Number} [angle=0]
* @param {String} [font='monospace']
* @memberof Debug */
const debugText = (text, pos, size=1, color='#fff', time=0, angle=0, font='monospace')=>
{
ASSERT(typeof color == 'string'); // pass in regular html strings as colors
debugPrimitives.push({text, pos, size, color, time:new Timer(time), angle, font});
}
/** Clear all debug primitives in the list
* @memberof Debug */
const debugClear = ()=> debugPrimitives = [];
/** Save a canvas to disk
* @param {HTMLCanvasElement} canvas
* @param {String} [filename]
* @memberof Debug */
const debugSaveCanvas = (canvas, filename = engineName + '.png') =>
{
downloadLink.download = 'screenshot.png';
downloadLink.href = canvas.toDataURL('image/png').replace('image/png','image/octet-stream');
downloadLink.click();
}
///////////////////////////////////////////////////////////////////////////////
// Engine debug function (called automatically)
const debugInit = ()=>
{
// create link for saving screenshots
document.body.appendChild(downloadLink = document.createElement('a'));
downloadLink.style.display = 'none';
}
const debugUpdate = ()=>
{
if (!debug)
return;
if (keyWasPressed(192)) // ~
debugOverlay = !debugOverlay;
if (debugOverlay)
{
if (keyWasPressed(48)) // 0
showWatermark = !showWatermark;
if (keyWasPressed(49)) // 1
debugPhysics = !debugPhysics, debugParticles = 0;
if (keyWasPressed(50)) // 2
debugParticles = !debugParticles, debugPhysics = 0;
if (keyWasPressed(51)) // 3
debugGamepads = !debugGamepads;
if (keyWasPressed(52)) // 4
godMode = !godMode;
if (keyWasPressed(53)) // 5
debugTakeScreenshot = 1;
//if (keyWasPressed(54)) // 6
//if (keyWasPressed(55)) // 7
//if (keyWasPressed(56)) // 8
//if (keyWasPressed(57)) // 9
}
}
const debugRender = ()=>
{
glCopyToContext(mainContext);
if (debugTakeScreenshot)
{
// composite canvas
glCopyToContext(mainContext, 1);
mainContext.drawImage(overlayCanvas, 0, 0);
overlayCanvas.width |= 0;
debugSaveCanvas(mainCanvas);
debugTakeScreenshot = 0;
}
if (debugGamepads && gamepadsEnable && navigator.getGamepads)
{
// gamepad debug display
const gamepads = navigator.getGamepads();
for (let i = gamepads.length; i--;)
{
const gamepad = gamepads[i];
if (gamepad)
{
const stickScale = 1;
const buttonScale = .2;
const centerPos = cameraPos;
const sticks = stickData[i];
for (let j = sticks.length; j--;)
{
const drawPos = centerPos.add(vec2(j*stickScale*2, i*stickScale*3));
const stickPos = drawPos.add(sticks[j].scale(stickScale));
debugCircle(drawPos, stickScale, '#fff7',0,1);
debugLine(drawPos, stickPos, '#f00');
debugPoint(stickPos, '#f00');
}
for (let j = gamepad.buttons.length; j--;)
{
const drawPos = centerPos.add(vec2(j*buttonScale*2, i*stickScale*3-stickScale-buttonScale));
const pressed = gamepad.buttons[j].pressed;
debugCircle(drawPos, buttonScale, pressed ? '#f00' : '#fff7', 0, 1);
debugText(j, drawPos, .2);
}
}
}
}
if (debugOverlay)
{
// mouse pick
let bestDistance = Infinity, bestObject;
for (const o of engineObjects)
{
if (o.canvas || o.destroyed)
continue; // skip tile layers
const size = o.size.copy();
if (!size.x || !size.y)
continue;
const distance = mousePos.distanceSquared(o.pos);
if (distance < bestDistance)
{
bestDistance = distance;
bestObject = o
}
// show object info
const color = new Color(
o.collideTiles?1:0,
o.collideSolidObjects?1:0,
o.isSolid?1:0,
o.parent ? .2 : .5);
size.x = max(size.x, .2);
size.y = max(size.y, .2);
drawRect(o.pos, size, color);
drawRect(o.pos, size.scale(.8), o.parent ? new Color(1,1,1,.5) : new Color(0,0,0,.8));
o.parent && drawLine(o.pos, o.parent.pos, .1, new Color(0,0,1,.5));
}
if (bestObject)
{
const saveContext = mainContext;
mainContext = overlayContext
const raycastHitPos = tileCollisionRaycast(bestObject.pos, mousePos);
raycastHitPos && drawRect(raycastHitPos.floor().add(vec2(.5)), vec2(1), new Color(0,1,1,.3));
drawRect(mousePos.floor().add(vec2(.5)), vec2(1), new Color(0,0,1,.5));
drawLine(mousePos, bestObject.pos, .1, !raycastHitPos ? new Color(0,1,0,.5) : new Color(1,0,0,.5));
const debugText = 'mouse pos = ' + mousePos +
'\nmouse collision = ' + getTileCollisionData(mousePos) +
'\n\n--- object info ---\n' +
bestObject.toString();
drawTextScreen(debugText, mousePosScreen, 24, new Color, .05, undefined, undefined, 'monospace');
mainContext = saveContext;
}
glCopyToContext(mainContext);
}
{
// draw debug primitives
overlayContext.lineWidth = 2;
const pointSize = debugPointSize * cameraScale;
debugPrimitives.forEach(p=>
{
overlayContext.save();
// create canvas transform from world space to screen space
const pos = worldToScreen(p.pos);
overlayContext.translate(pos.x|0, pos.y|0);
overlayContext.rotate(p.angle);
overlayContext.fillStyle = overlayContext.strokeStyle = p.color;
if (p.text != undefined)
{
overlayContext.font = p.size*cameraScale + 'px '+ p.font;
overlayContext.textAlign = 'center';
overlayContext.textBaseline = 'middle';
overlayContext.fillText(p.text, 0, 0);
}
else if (p.size == 0 || p.size.x === 0 && p.size.y === 0 )
{
// point
overlayContext.fillRect(-pointSize/2, -1, pointSize, 3);
overlayContext.fillRect(-1, -pointSize/2, 3, pointSize);
}
else if (p.size.x != undefined)
{
// rect
const w = p.size.x*cameraScale|0, h = p.size.y*cameraScale|0;
p.fill && overlayContext.fillRect(-w/2|0, -h/2|0, w, h);
overlayContext.strokeRect(-w/2|0, -h/2|0, w, h);
}
else
{
// circle
overlayContext.beginPath();
overlayContext.arc(0, 0, p.size*cameraScale, 0, 9);
p.fill && overlayContext.fill();
overlayContext.stroke();
}
overlayContext.restore();
});
// remove expired pritives
debugPrimitives = debugPrimitives.filter(r=>r.time.get()<0);
}
{
// draw debug overlay
overlayContext.save();
overlayContext.fillStyle = '#fff';
overlayContext.textAlign = 'left';
overlayContext.textBaseline = 'top';
overlayContext.font = '28px monospace';
overlayContext.shadowColor = '#000';
overlayContext.shadowBlur = 9;
let x = 9, y = -20, h = 30;
if (debugOverlay)
{
overlayContext.fillText(engineName, x, y += h);
overlayContext.fillText('Objects: ' + engineObjects.length, x, y += h);
overlayContext.fillText('Time: ' + formatTime(time), x, y += h);
overlayContext.fillText('---------', x, y += h);
overlayContext.fillStyle = '#f00';
overlayContext.fillText('~: Debug Overlay', x, y += h);
overlayContext.fillStyle = debugPhysics ? '#f00' : '#fff';
overlayContext.fillText('1: Debug Physics', x, y += h);
overlayContext.fillStyle = debugParticles ? '#f00' : '#fff';
overlayContext.fillText('2: Debug Particles', x, y += h);
overlayContext.fillStyle = debugGamepads ? '#f00' : '#fff';
overlayContext.fillText('3: Debug Gamepads', x, y += h);
overlayContext.fillStyle = godMode ? '#f00' : '#fff';
overlayContext.fillText('4: God Mode', x, y += h);
overlayContext.fillStyle = '#fff';
overlayContext.fillText('5: Save Screenshot', x, y += h);
let keysPressed = '';
for(const i in inputData[0])
{
if (i && keyIsDown(i, 0))
keysPressed += i + ' ' ;
}
keysPressed && overlayContext.fillText('Keys Down: ' + keysPressed, x, y += h);
let buttonsPressed = '';
if (inputData[1])
for(const i in inputData[1])
{
if (i && keyIsDown(i, 1))
buttonsPressed += i + ' ' ;
}
buttonsPressed && overlayContext.fillText('Gamepad: ' + buttonsPressed, x, y += h);
}
else
{
overlayContext.fillText(debugPhysics ? 'Debug Physics' : '', x, y += h);
overlayContext.fillText(debugParticles ? 'Debug Particles' : '', x, y += h);
overlayContext.fillText(godMode ? 'God Mode' : '', x, y += h);
overlayContext.fillText(debugGamepads ? 'Debug Gamepads' : '', x, y += h);
}
overlayContext.restore();
}
}
/**
* LittleJS Utility Classes and Functions
* <br> - General purpose math library
* <br> - Vector2 - fast, simple, easy 2D vector class
* <br> - Color - holds a rgba color with some math functions
* <br> - Timer - tracks time automatically
* @namespace Utilities
*/
'use strict';
/** A shortcut to get Math.PI
* @const
* @memberof Utilities */
const PI = Math.PI;
/** Returns absoulte value of value passed in
* @param {Number} value
* @return {Number}
* @memberof Utilities */
const abs = (a)=> a < 0 ? -a : a;
/** Returns lowest of two values passed in
* @param {Number} valueA
* @param {Number} valueB
* @return {Number}
* @memberof Utilities */
const min = (a, b)=> a < b ? a : b;
/** Returns highest of two values passed in
* @param {Number} valueA
* @param {Number} valueB
* @return {Number}
* @memberof Utilities */
const max = (a, b)=> a > b ? a : b;
/** Returns the sign of value passed in (also returns 1 if 0)
* @param {Number} value
* @return {Number}
* @memberof Utilities */
const sign = (a)=> a < 0 ? -1 : 1;
/** Returns first parm modulo the second param, but adjusted so negative numbers work as expected
* @param {Number} dividend
* @param {Number} [divisor=1]
* @return {Number}
* @memberof Utilities */
const mod = (a, b=1)=> ((a % b) + b) % b;
/** Clamps the value beween max and min
* @param {Number} value
* @param {Number} [min=0]
* @param {Number} [max=1]
* @return {Number}
* @memberof Utilities */
const clamp = (v, min=0, max=1)=> v < min ? min : v > max ? max : v;
/** Returns what percentage the value is between max and min
* @param {Number} value
* @param {Number} [min=0]
* @param {Number} [max=1]
* @return {Number}
* @memberof Utilities */
const percent = (v, min=0, max=1)=> max-min ? clamp((v-min) / (max-min)) : 0;
/** Linearly interpolates the percent value between max and min
* @param {Number} percent
* @param {Number} [min=0]
* @param {Number} [max=1]
* @return {Number}
* @memberof Utilities */
const lerp = (p, min=0, max=1)=> min + clamp(p) * (max-min);
/** Applies smoothstep function to the percentage value
* @param {Number} value
* @return {Number}
* @memberof Utilities */
const smoothStep = (p)=> p * p * (3 - 2 * p);
/** Returns the nearest power of two not less then the value
* @param {Number} value
* @return {Number}
* @memberof Utilities */
const nearestPowerOfTwo = (v)=> 2**Math.ceil(Math.log2(v));
/** Returns true if two axis aligned bounding boxes are overlapping
* @param {Vector2} pointA - Center of box A
* @param {Vector2} sizeA - Size of box A
* @param {Vector2} pointB - Center of box B
* @param {Vector2} [sizeB] - Size of box B
* @return {Boolean} - True if overlapping
* @memberof Utilities */
const isOverlapping = (pA, sA, pB, sB)=> abs(pA.x - pB.x)*2 < sA.x + sB.x & abs(pA.y - pB.y)*2 < sA.y + sB.y;
/** Returns an oscillating wave between 0 and amplitude with frequency of 1 Hz by default
* @param {Number} [frequency=1] - Frequency of the wave in Hz
* @param {Number} [amplitude=1] - Amplitude (max height) of the wave
* @param {Number} [t=time] - Value to use for time of the wave
* @return {Number} - Value waving between 0 and amplitude
* @memberof Utilities */
const wave = (frequency=1, amplitude=1, t=time)=> amplitude/2 * (1 - Math.cos(t*frequency*2*PI));
/** Formats seconds to mm:ss style for display purposes
* @param {Number} t - time in seconds
* @return {String}
* @memberof Utilities */
const formatTime = (t)=> (t/60|0)+':'+(t%60<10?'0':'')+(t%60|0);
///////////////////////////////////////////////////////////////////////////////
/** Random global functions
* @namespace Random */
/** Returns a random value between the two values passed in
* @param {Number} [valueA=1]
* @param {Number} [valueB=0]
* @return {Number}
* @memberof Random */
const rand = (a=1, b=0)=> b + (a-b)*Math.random();
/** Returns a floored random value the two values passed in
* @param {Number} [valueA=1]
* @param {Number} [valueB=0]
* @return {Number}
* @memberof Random */
const randInt = (a=1, b=0)=> rand(a,b)|0;
/** Randomly returns either -1 or 1
* @return {Number}
* @memberof Random */
const randSign = ()=> (rand(2)|0) * 2 - 1;
/** Returns a random Vector2 within a circular shape
* @param {Number} [radius=1]
* @param {Number} [minRadius=0]
* @return {Vector2}
* @memberof Random */
const randInCircle = (radius=1, minRadius=0)=> radius > 0 ? randVector(radius * rand(minRadius / radius, 1)**.5) : new Vector2;
/** Returns a random Vector2 with the passed in length
* @param {Number} [length=1]
* @return {Vector2}
* @memberof Random */
const randVector = (length=1)=> new Vector2().setAngle(rand(2*PI), length);
/** Returns a random color between the two passed in colors, combine components if linear
* @param {Color} [colorA=new Color(1,1,1,1)]
* @param {Color} [colorB=new Color(0,0,0,1)]
* @param {Boolean} [linear]
* @return {Color}
* @memberof Random */
const randColor = (cA = new Color, cB = new Color(0,0,0,1), linear)=>
linear ? cA.lerp(cB, rand()) : new Color(rand(cA.r,cB.r),rand(cA.g,cB.g),rand(cA.b,cB.b),rand(cA.a,cB.a));
/** The seed used by the randSeeded function, should not be 0
* @memberof Random */
let randSeed = 1;
/** Returns a seeded random value between the two values passed in using randSeed
* @param {Number} [valueA=1]
* @param {Number} [valueB=0]
* @return {Number}
* @memberof Random */
const randSeeded = (a=1, b=0)=>
{
randSeed ^= randSeed << 13; randSeed ^= randSeed >>> 17; randSeed ^= randSeed << 5; // xorshift
return b + (a-b) * abs(randSeed % 1e9) / 1e9;
}
///////////////////////////////////////////////////////////////////////////////
/**
* Create a 2d vector, can take another Vector2 to copy, 2 scalars, or 1 scalar
* @param {Number} [x=0]
* @param {Number} [y=0]
* @return {Vector2}
* @example
* let a = vec2(0, 1); // vector with coordinates (0, 1)
* let b = vec2(a); // copy a into b
* a = vec2(5); // set a to (5, 5)
* b = vec2(); // set b to (0, 0)
* @memberof Utilities
*/
const vec2 = (x=0, y)=> x.x == undefined ? new Vector2(x, y == undefined? x : y) : new Vector2(x.x, x.y);
/**
* 2D Vector object with vector math library
* <br> - Functions do not change this so they can be chained together
* @example
* let a = new Vector2(2, 3); // vector with coordinates (2, 3)
* let b = new Vector2; // vector with coordinates (0, 0)
* let c = vec2(4, 2); // use the vec2 function to make a Vector2
* let d = a.add(b).scale(5); // operators can be chained
*/
class Vector2
{
/** Create a 2D vector with the x and y passed in, can also be created with vec2()
* @param {Number} [x=0] - X axis location
* @param {Number} [y=0] - Y axis location */
constructor(x=0, y=0)
{
/** @property {Number} - X axis location */
this.x = x;
/** @property {Number} - Y axis location */
this.y = y;
}
/** Returns a new vector that is a copy of this
* @return {Vector2} */
copy() { return new Vector2(this.x, this.y); }
/** Returns a copy of this vector plus the vector passed in
* @param {Vector2} vector
* @return {Vector2} */
add(v) { ASSERT(v.x!=undefined); return new Vector2(this.x + v.x, this.y + v.y); }
/** Returns a copy of this vector minus the vector passed in
* @param {Vector2} vector
* @return {Vector2} */
subtract(v) { ASSERT(v.x!=undefined); return new Vector2(this.x - v.x, this.y - v.y); }
/** Returns a copy of this vector times the vector passed in
* @param {Vector2} vector
* @return {Vector2} */
multiply(v) { ASSERT(v.x!=undefined); return new Vector2(this.x * v.x, this.y * v.y); }
/** Returns a copy of this vector divided by the vector passed in
* @param {Vector2} vector
* @return {Vector2} */
divide(v) { ASSERT(v.x!=undefined); return new Vector2(this.x / v.x, this.y / v.y); }
/** Returns a copy of this vector scaled by the vector passed in
* @param {Number} scale
* @return {Vector2} */
scale(s) { ASSERT(s.x==undefined); return new Vector2(this.x * s, this.y * s); }
/** Returns the length of this vector
* @return {Number} */
length() { return this.lengthSquared()**.5; }
/** Returns the length of this vector squared
* @return {Number} */
lengthSquared() { return this.x**2 + this.y**2; }
/** Returns the distance from this vector to vector passed in
* @param {Vector2} vector
* @return {Number} */
distance(v) { return this.distanceSquared(v)**.5; }
/** Returns the distance squared from this vector to vector passed in
* @param {Vector2} vector
* @return {Number} */
distanceSquared(v) { return (this.x - v.x)**2 + (this.y - v.y)**2; }
/** Returns a new vector in same direction as this one with the length passed in
* @param {Number} [length=1]
* @return {Vector2} */
normalize(length=1) { const l = this.length(); return l ? this.scale(length/l) : new Vector2(0, length); }
/** Returns a new vector clamped to length passed in
* @param {Number} [length=1]
* @return {Vector2} */
clampLength(length=1) { const l = this.length(); return l > length ? this.scale(length/l) : this; }
/** Returns the dot product of this and the vector passed in
* @param {Vector2} vector
* @return {Number} */
dot(v) { ASSERT(v.x!=undefined); return this.x*v.x + this.y*v.y; }
/** Returns the cross product of this and the vector passed in
* @param {Vector2} vector
* @return {Number} */
cross(v) { ASSERT(v.x!=undefined); return this.x*v.y - this.y*v.x; }
/** Returns the angle of this vector, up is angle 0
* @return {Number} */
angle() { return Math.atan2(this.x, this.y); }
/** Sets this vector with angle and length passed in
* @param {Number} [angle=0]
* @param {Number} [length=1] */
setAngle(a=0, length=1) { this.x = length*Math.sin(a); this.y = length*Math.cos(a); return this; }
/** Returns copy of this vector rotated by the angle passed in
* @param {Number} angle
* @return {Vector2} */
rotate(a) { const c = Math.cos(a), s = Math.sin(a); return new Vector2(this.x*c-this.y*s, this.x*s+this.y*c); }
/** Returns the integer direction of this vector, corrosponding to multiples of 90 degree rotation (0-3)
* @return {Number} */
direction() { return abs(this.x) > abs(this.y) ? this.x < 0 ? 3 : 1 : this.y < 0 ? 2 : 0; }
/** Returns a copy of this vector that has been inverted
* @return {Vector2} */
invert() { return new Vector2(this.y, -this.x); }
/** Returns a copy of this vector with each axis floored
* @return {Vector2} */
floor() { return new Vector2(Math.floor(this.x), Math.floor(this.y)); }
/** Returns the area this vector covers as a rectangle
* @return {Number} */
area() { return abs(this.x * this.y); }
/** Returns a new vector that is p percent between this and the vector passed in
* @param {Vector2} vector
* @param {Number} percent
* @return {Vector2} */
lerp(v, p) { ASSERT(v.x!=undefined); return this.add(v.subtract(this).scale(clamp(p))); }
/** Returns true if this vector is within the bounds of an array size passed in
* @param {Vector2} arraySize
* @return {Boolean} */
arrayCheck(arraySize) { return this.x >= 0 && this.y >= 0 && this.x < arraySize.x && this.y < arraySize.y; }
/** Returns this vector expressed as a string
* @param {float} digits - precision to display
* @return {String} */
toString(digits=3)
{ return `(${(this.x<0?'':' ') + this.x.toFixed(digits)},${(this.y<0?'':' ') + this.y.toFixed(digits)} )`; }
}
///////////////////////////////////////////////////////////////////////////////
/**
* Color object (red, green, blue, alpha) with some helpful functions
* @example
* let a = new Color; // white
* let b = new Color(1, 0, 0); // red
* let c = new Color(0, 0, 0, 0); // transparent black
*/
class Color
{
/** Create a color with the components passed in, white by default
* @param {Number} [red=1]
* @param {Number} [green=1]
* @param {Number} [blue=1]
* @param {Number} [alpha=1] */
constructor(r=1, g=1, b=1, a=1)
{
/** @property {Number} - Red */
this.r = r;
/** @property {Number} - Green */
this.g = g;
/** @property {Number} - Blue */
this.b = b;
/** @property {Number} - Alpha */
this.a = a;
}
/** Returns a new color that is a copy of this
* @return {Color} */
copy() { return new Color(this.r, this.g, this.b, this.a); }
/** Returns a copy of this color plus the color passed in
* @param {Color} color
* @return {Color} */
add(c) { return new Color(this.r+c.r, this.g+c.g, this.b+c.b, this.a+c.a); }
/** Returns a copy of this color minus the color passed in
* @param {Color} color
* @return {Color} */
subtract(c) { return new Color(this.r-c.r, this.g-c.g, this.b-c.b, this.a-c.a); }
/** Returns a copy of this color times the color passed in
* @param {Color} color
* @return {Color} */
multiply(c) { return new Color(this.r*c.r, this.g*c.g, this.b*c.b, this.a*c.a); }
/** Returns a copy of this color divided by the color passed in
* @param {Color} color
* @return {Color} */
divide(c) { return new Color(this.r/c.r, this.g/c.g, this.b/c.b, this.a/c.a); }
/** Returns a copy of this color scaled by the value passed in, alpha can be scaled separately
* @param {Number} scale
* @param {Number} [alphaScale=scale]
* @return {Color} */
scale(s, a=s) { return new Color(this.r*s, this.g*s, this.b*s, this.a*a); }
/** Returns a copy of this color clamped to the valid range between 0 and 1
* @return {Color} */
clamp() { return new Color(clamp(this.r), clamp(this.g), clamp(this.b), clamp(this.a)); }
/** Returns a new color that is p percent between this and the color passed in
* @param {Color} color
* @param {Number} percent
* @return {Color} */
lerp(c, p) { return this.add(c.subtract(this).scale(clamp(p))); }
/** Sets this color given a hue, saturation, lightness, and alpha
* @param {Number} [hue=0]
* @param {Number} [saturation=0]
* @param {Number} [lightness=1]
* @param {Number} [alpha=1]
* @return {Color} */
setHSLA(h=0, s=0, l=1, a=1)
{
const q = l < .5 ? l*(1+s) : l+s-l*s, p = 2*l-q,
f = (p, q, t)=>
(t = ((t%1)+1)%1) < 1/6 ? p+(q-p)*6*t :
t < 1/2 ? q :
t < 2/3 ? p+(q-p)*(2/3-t)*6 : p;
this.r = f(p, q, h + 1/3);
this.g = f(p, q, h);
this.b = f(p, q, h - 1/3);
this.a = a;
return this;
}
/** Returns this color expressed in hsla format
* @return {Array} */
getHSLA()
{
const r = this.r;
const g = this.g;
const b = this.b;
const a = this.a;
const max = Math.max(r, g, b);
const min = Math.min(r, g, b);
const l = (max + min) / 2;
let h = 0, s = 0;
if (max != min)
{
let d = max - min;
s = l > .5 ? d / (2 - max - min) : d / (max + min);
if (r == max)
h = (g - b) / d + (g < b ? 6 : 0);
else if (g == max)
h = (b - r) / d + 2;
else if (b == max)
h = (r - g) / d + 4;
}
return [h / 6, s, l, a];
}
/** Returns a new color that has each component randomly adjusted
* @param {Number} [amount=.05]
* @param {Number} [alphaAmount=0]
* @return {Color} */
mutate(amount=.05, alphaAmount=0)
{
return new Color
(
this.r + rand(amount, -amount),
this.g + rand(amount, -amount),
this.b + rand(amount, -amount),
this.a + rand(alphaAmount, -alphaAmount)
).clamp();
}
/** Returns this color expressed as an CSS color value
* @return {String} */
toString()
{
ASSERT(this.r>=0 && this.r<=1 && this.g>=0 && this.g<=1 && this.b>=0 && this.b<=1 && this.a>=0 && this.a<=1);
return `rgb(${this.r*255|0},${this.g*255|0},${this.b*255|0},${this.a})`;
}
/** Returns this color expressed as 32 bit integer RGBA value
* @return {Number} */
rgbaInt()
{
ASSERT(this.r>=0 && this.r<=1 && this.g>=0 && this.g<=1 && this.b>=0 && this.b<=1 && this.a>=0 && this.a<=1);
return (this.r*255|0) + (this.g*255<<8) + (this.b*255<<16) + (this.a*255<<24);
}
/** Set this color from a hex code
* @param {String} hex - html hex code
* @return {Color} */
setHex(hex)
{
const fromHex = (a)=> parseInt(hex.slice(a,a+2), 16)/255;
this.r = fromHex(1);
this.g = fromHex(3),
this.b = fromHex(5);
this.a = 1;
ASSERT(this.r>=0 && this.r<=1 && this.g>=0 && this.g<=1 && this.b>=0 && this.b<=1);
return this;
}
/** Returns this color expressed as a hex code
* @return {String} */
getHex()
{
const toHex = (c)=> ((c=c*255|0)<16 ? '0' : '') + c.toString(16);
return '#' + toHex(this.r) + toHex(this.g) + toHex(this.b);
}
}
///////////////////////////////////////////////////////////////////////////////
/**
* Timer object tracks how long has passed since it was set
* @example
* let a = new Timer; // creates a timer that is not set
* a.set(3); // sets the timer to 3 seconds
*
* let b = new Timer(1); // creates a timer with 1 second left
* b.unset(); // unsets the timer
*/
class Timer
{
/** Create a timer object set time passed in
* @param {Number} [timeLeft] - How much time left before the timer elapses in seconds */
constructor(timeLeft) { this.time = timeLeft == undefined ? undefined : time + timeLeft; this.setTime = timeLeft; }
/** Set the timer with seconds passed in
* @param {Number} [timeLeft=0] - How much time left before the timer is elapsed in seconds */
set(timeLeft=0) { this.time = time + timeLeft; this.setTime = timeLeft; }
/** Unset the timer */
unset() { this.time = undefined; }
/** Returns true if set
* @return {Boolean} */
isSet() { return this.time != undefined; }
/** Returns true if set and has not elapsed
* @return {Boolean} */
active() { return time <= this.time; }
/** Returns true if set and elapsed
* @return {Boolean} */
elapsed() { return time > this.time; }
/** Get how long since elapsed, returns 0 if not set (returns negative if currently active)
* @return {Number} */
get() { return this.isSet()? time - this.time : 0; }
/** Get percentage elapsed based on time it was set to, returns 0 if not set
* @return {Number} */
getPercent() { return this.isSet()? percent(this.time - time, this.setTime, 0) : 0; }
/** Returns this timer expressed as a string
* @return {String} */
toString() { if (debug) { return this.unset() ? 'unset' : Math.abs(this.get()) + ' seconds ' + (this.get()<0 ? 'before' : 'after' ); } }
}
/**
* LittleJS Engine Settings
* @namespace Settings
*/
'use strict';
///////////////////////////////////////////////////////////////////////////////
// Display settings
/** The max size of the canvas, centered if window is larger
* @type {Vector2}
* @default
* @memberof Settings */
let canvasMaxSize = vec2(1920, 1200);
/** Fixed size of the canvas, if enabled canvas size never changes
* - you may also need to set mainCanvasSize if using screen space coords in startup
* @type {Vector2}
* @default
* @memberof Settings */
let canvasFixedSize = vec2();
/** Disables anti aliasing for pixel art if true
* @default
* @memberof Settings */
let cavasPixelated = 1;
/** Default font used for text rendering
* @default
* @memberof Settings */
let fontDefault = 'arial';
///////////////////////////////////////////////////////////////////////////////
// Tile sheet settings
/** Default size of tiles in pixels
* @type {Vector2}
* @default
* @memberof Settings */
let tileSizeDefault = vec2(16);
/** Prevent tile bleeding from neighbors in pixels
* @default
* @memberof Settings */
let tileFixBleedScale = .3;
///////////////////////////////////////////////////////////////////////////////
// Object settings
/** Default size of objects
* @type {Vector2}
* @default
* @memberof Settings */
let objectDefaultSize = vec2(1);
/** Enable physics solver for collisions between objects
* @default
* @memberof Settings */
let enablePhysicsSolver = 1;
/** Default object mass for collison calcuations (how heavy objects are)
* @default
* @memberof Settings */