This repository has been archived by the owner on Nov 12, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 227
/
kaboom.ts
6941 lines (5904 loc) · 149 KB
/
kaboom.ts
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
const VERSION = "3000.0.15"
import initApp from "./app"
import {
sat,
vec2,
Rect,
Polygon,
Line,
Circle,
Color,
Vec2,
Mat4,
Quad,
RNG,
quad,
rgb,
hsl2rgb,
rand,
randi,
randSeed,
chance,
choose,
clamp,
lerp,
map,
mapc,
wave,
testLinePoint,
testLineLine,
testLineCircle,
testRectRect,
testRectLine,
testRectPoint,
testPolygonPoint,
testCirclePolygon,
deg2rad,
rad2deg,
} from "./math"
import easings from "./easings"
import {
IDList,
Event,
EventHandler,
download,
downloadText,
downloadJSON,
downloadBlob,
uid,
isDataURL,
getExt,
deepEq,
dataURLToArrayBuffer,
EventController,
// eslint-disable-next-line
warn,
// eslint-disable-next-line
benchmark,
// eslint-disable-next-line
comparePerf,
BinaryHeap,
} from "./utils"
import type {
GfxShader,
GfxFont,
RenderProps,
CharTransform,
TextureOpt,
ImageSource,
FormattedText,
FormattedChar,
DrawRectOpt,
DrawLineOpt,
DrawLinesOpt,
DrawTriangleOpt,
DrawPolygonOpt,
DrawCircleOpt,
DrawEllipseOpt,
DrawUVQuadOpt,
Vertex,
BitmapFontData,
ShaderData,
LoadSpriteSrc,
LoadSpriteOpt,
SpriteAtlasData,
LoadBitmapFontOpt,
KaboomCtx,
KaboomOpt,
AudioPlay,
AudioPlayOpt,
DrawSpriteOpt,
DrawTextOpt,
TextAlign,
GameObj,
SceneName,
SceneDef,
CompList,
Comp,
Tag,
Key,
MouseButton,
PosComp,
ScaleComp,
RotateComp,
ColorComp,
OpacityComp,
Anchor,
AnchorComp,
ZComp,
FollowComp,
OffScreenCompOpt,
OffScreenComp,
AreaCompOpt,
AreaComp,
SpriteComp,
SpriteCompOpt,
SpriteAnimPlayOpt,
SpriteAnims,
TextComp,
TextCompOpt,
RectComp,
RectCompOpt,
UVQuadComp,
CircleComp,
OutlineComp,
TimerComp,
BodyComp,
BodyCompOpt,
Uniform,
ShaderComp,
FixedComp,
StayComp,
HealthComp,
LifespanCompOpt,
StateComp,
Debug,
KaboomPlugin,
EmptyComp,
LevelComp,
Edge,
TileComp,
TileCompOpt,
LevelOpt,
Recording,
BoomOpt,
PeditFile,
Shape,
DoubleJumpComp,
TimerController,
TweenController,
LoadFontOpt,
AgentComp,
AgentCompOpt,
PathFindOpt,
GetOpt,
Vec2Args,
NineSlice,
LerpValue,
TexFilter,
} from "./types"
import Timer from "./timer"
// @ts-ignore
import beanSpriteSrc from "./assets/bean.png"
// @ts-ignore
import burpSoundSrc from "./assets/burp.mp3"
// @ts-ignore
import kaSpriteSrc from "./assets/ka.png"
// @ts-ignore
import boomSpriteSrc from "./assets/boom.png"
type EventList<M> = {
[event in keyof M]?: (event: M[event]) => void
}
interface SpriteCurAnim {
name: string,
timer: number,
loop: boolean,
speed: number,
pingpong: boolean,
onEnd: () => void,
}
// some default charsets for loading bitmap fonts
const ASCII_CHARS = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~"
const DEF_ANCHOR = "topleft"
const BG_GRID_SIZE = 64
const DEF_FONT = "monospace"
const DBG_FONT = "monospace"
const DEF_TEXT_SIZE = 36
const DEF_TEXT_CACHE_SIZE = 64
const MAX_TEXT_CACHE_SIZE = 256
const FONT_ATLAS_WIDTH = 2048
const FONT_ATLAS_HEIGHT = 2048
const SPRITE_ATLAS_WIDTH = 2048
const SPRITE_ATLAS_HEIGHT = 2048
// 0.1 pixel padding to texture coordinates to prevent artifact
const UV_PAD = 0.1
const DEF_HASH_GRID_SIZE = 64
const DEF_FONT_FILTER = "nearest"
const LOG_MAX = 1
const VERTEX_FORMAT = [
{ name: "a_pos", size: 2 },
{ name: "a_uv", size: 2 },
{ name: "a_color", size: 4 },
]
const STRIDE = VERTEX_FORMAT.reduce((sum, f) => sum + f.size, 0)
const MAX_BATCHED_QUAD = 2048
const MAX_BATCHED_VERTS = MAX_BATCHED_QUAD * 4 * STRIDE
const MAX_BATCHED_INDICES = MAX_BATCHED_QUAD * 6
// vertex shader template, replace {{user}} with user vertex shader code
const VERT_TEMPLATE = `
attribute vec2 a_pos;
attribute vec2 a_uv;
attribute vec4 a_color;
varying vec2 v_pos;
varying vec2 v_uv;
varying vec4 v_color;
vec4 def_vert() {
return vec4(a_pos, 0.0, 1.0);
}
{{user}}
void main() {
vec4 pos = vert(a_pos, a_uv, a_color);
v_pos = a_pos;
v_uv = a_uv;
v_color = a_color;
gl_Position = pos;
}
`
// fragment shader template, replace {{user}} with user fragment shader code
const FRAG_TEMPLATE = `
precision mediump float;
varying vec2 v_pos;
varying vec2 v_uv;
varying vec4 v_color;
uniform sampler2D u_tex;
vec4 def_frag() {
return v_color * texture2D(u_tex, v_uv);
}
{{user}}
void main() {
gl_FragColor = frag(v_pos, v_uv, v_color, u_tex);
if (gl_FragColor.a == 0.0) {
discard;
}
}
`
// default {{user}} vertex shader code
const DEF_VERT = `
vec4 vert(vec2 pos, vec2 uv, vec4 color) {
return def_vert();
}
`
// default {{user}} fragment shader code
const DEF_FRAG = `
vec4 frag(vec2 pos, vec2 uv, vec4 color, sampler2D tex) {
return def_frag();
}
`
const COMP_DESC = new Set([
"id",
"require",
])
const COMP_EVENTS = new Set([
"add",
"update",
"draw",
"destroy",
"inspect",
"drawInspect",
])
// convert anchor string to a vec2 offset
function anchorPt(orig: Anchor | Vec2): Vec2 {
switch (orig) {
case "topleft": return new Vec2(-1, -1)
case "top": return new Vec2(0, -1)
case "topright": return new Vec2(1, -1)
case "left": return new Vec2(-1, 0)
case "center": return new Vec2(0, 0)
case "right": return new Vec2(1, 0)
case "botleft": return new Vec2(-1, 1)
case "bot": return new Vec2(0, 1)
case "botright": return new Vec2(1, 1)
default: return orig
}
}
function alignPt(align: TextAlign): number {
switch (align) {
case "left": return 0
case "center": return 0.5
case "right": return 1
default: return 0
}
}
function createEmptyAudioBuffer(ctx: AudioContext) {
return ctx.createBuffer(1, 1, 44100)
}
// only exports one kaboom() which contains all the state
export default (gopt: KaboomOpt = {}): KaboomCtx => {
const root = gopt.root ?? document.body
// if root is not defined (which falls back to <body>) we assume user is using kaboom on a clean page, and modify <body> to better fit a full screen canvas
if (root === document.body) {
document.body.style["width"] = "100%"
document.body.style["height"] = "100%"
document.body.style["margin"] = "0px"
document.documentElement.style["width"] = "100%"
document.documentElement.style["height"] = "100%"
}
// create a <canvas> if user didn't provide one
const canvas = gopt.canvas ?? (() => {
const canvas = document.createElement("canvas")
root.appendChild(canvas)
return canvas
})()
// global pixel scale
const gscale = gopt.scale ?? 1
const fixedSize = gopt.width && gopt.height && !gopt.stretch && !gopt.letterbox
// adjust canvas size according to user size / viewport settings
if (fixedSize) {
canvas.width = gopt.width * gscale
canvas.height = gopt.height * gscale
} else {
canvas.width = canvas.parentElement.offsetWidth
canvas.height = canvas.parentElement.offsetHeight
}
const cw = canvas.width
const ch = canvas.height
const pixelDensity = gopt.pixelDensity || window.devicePixelRatio
canvas.width *= pixelDensity
canvas.height *= pixelDensity
// canvas css styles
const styles = [
"outline: none",
"cursor: default",
]
if (fixedSize) {
styles.push(`width: ${cw}px`)
styles.push(`height: ${ch}px`)
} else {
styles.push("width: 100%")
styles.push("height: 100%")
}
if (gopt.crisp) {
// chrome only supports pixelated and firefox only supports crisp-edges
styles.push("image-rendering: pixelated")
styles.push("image-rendering: crisp-edges")
}
canvas.style.cssText = styles.join(";")
// make canvas focusable
canvas.tabIndex = 0
const fontCacheCanvas = document.createElement("canvas")
fontCacheCanvas.width = MAX_TEXT_CACHE_SIZE
fontCacheCanvas.height = MAX_TEXT_CACHE_SIZE
const fontCacheCtx = fontCacheCanvas.getContext("2d", {
willReadFrequently: true,
})
const app = initApp({
canvas: canvas,
touchToMouse: gopt.touchToMouse,
gamepads: gopt.gamepads,
pixelDensity: gopt.pixelDensity,
maxFPS: gopt.maxFPS,
})
const gc: Array<() => void> = []
const gl = app.canvas()
.getContext("webgl", {
antialias: true,
depth: true,
stencil: true,
alpha: true,
preserveDrawingBuffer: true,
})
class Texture {
src: null | ImageSource = null
glTex: WebGLTexture
width: number
height: number
constructor(w: number, h: number, opt: TextureOpt = {}) {
this.glTex = gl.createTexture()
gc.push(() => this.free())
this.bind()
if (w && h) {
gl.texImage2D(
gl.TEXTURE_2D,
0, gl.RGBA,
w,
h,
0,
gl.RGBA,
gl.UNSIGNED_BYTE,
null,
)
}
this.width = w
this.height = h
const filter = (() => {
switch (opt.filter ?? gopt.texFilter) {
case "linear": return gl.LINEAR
case "nearest": return gl.NEAREST
default: return gl.NEAREST
}
})()
const wrap = (() => {
switch (opt.wrap) {
case "repeat": return gl.REPEAT
case "clampToEdge": return gl.CLAMP_TO_EDGE
default: return gl.CLAMP_TO_EDGE
}
})()
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filter)
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filter)
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, wrap)
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, wrap)
this.unbind()
}
static fromImage(img: ImageSource, opt: TextureOpt = {}): Texture {
const tex = new Texture(0, 0, opt)
tex.bind()
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, img)
tex.width = img.width
tex.height = img.height
tex.unbind()
tex.src = img
return tex
}
update(img: ImageSource, x = 0, y = 0) {
this.bind()
gl.texSubImage2D(gl.TEXTURE_2D, 0, x, y, gl.RGBA, gl.UNSIGNED_BYTE, img)
this.unbind()
}
bind() {
gl.bindTexture(gl.TEXTURE_2D, this.glTex)
}
unbind() {
gl.bindTexture(gl.TEXTURE_2D, null)
}
free() {
gl.deleteTexture(this.glTex)
}
}
class TexPacker {
private tex: Texture
private canvas: HTMLCanvasElement
private ctx: CanvasRenderingContext2D
private x: number = 0
private y: number = 0
private curHeight: number = 0
constructor(w: number, h: number) {
this.canvas = document.createElement("canvas")
this.canvas.width = w
this.canvas.height = h
this.tex = Texture.fromImage(this.canvas)
this.ctx = this.canvas.getContext("2d")
}
add(img: ImageSource): [Texture, Quad] {
if (img.width > this.canvas.width || img.height > this.canvas.height) {
throw new Error(`Texture size (${img.width} x ${img.height}) exceeds limit (${this.canvas.width} x ${this.canvas.height})`)
}
if (this.x + img.width > this.canvas.width) {
this.x = 0
this.y += this.curHeight
this.curHeight = 0
}
if (this.y + img.height > this.canvas.height) {
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height)
this.tex = Texture.fromImage(this.canvas)
this.x = 0
this.y = 0
this.curHeight = 0
}
const pos = new Vec2(this.x, this.y)
this.x += img.width
if (img.height > this.curHeight) {
this.curHeight = img.height
}
if (img instanceof ImageData) {
this.ctx.putImageData(img, pos.x, pos.y)
} else {
this.ctx.drawImage(img, pos.x, pos.y)
}
this.tex.update(this.canvas)
return [this.tex, new Quad(
pos.x / this.canvas.width,
pos.y / this.canvas.height,
img.width / this.canvas.width,
img.height / this.canvas.height,
)]
}
}
class FrameBuffer {
tex: Texture
glFrameBuffer: WebGLFramebuffer
glRenderBuffer: WebGLRenderbuffer
constructor(w: number, h: number, opt: TextureOpt = {}) {
this.tex = new Texture(w, h, opt)
this.glFrameBuffer = gl.createFramebuffer()
this.glRenderBuffer = gl.createRenderbuffer()
gc.push(() => this.free())
this.bind()
gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, w, h)
gl.framebufferTexture2D(
gl.FRAMEBUFFER,
gl.COLOR_ATTACHMENT0,
gl.TEXTURE_2D,
this.tex.glTex,
0,
)
gl.framebufferRenderbuffer(
gl.FRAMEBUFFER,
gl.DEPTH_STENCIL_ATTACHMENT,
gl.RENDERBUFFER,
this.glRenderBuffer,
)
this.unbind()
}
get width() {
return this.tex.width
}
get height() {
return this.tex.height
}
bind() {
gl.bindFramebuffer(gl.FRAMEBUFFER, this.glFrameBuffer)
gl.bindRenderbuffer(gl.RENDERBUFFER, this.glRenderBuffer)
}
unbind() {
gl.bindFramebuffer(gl.FRAMEBUFFER, null)
gl.bindRenderbuffer(gl.RENDERBUFFER, null)
}
free() {
gl.deleteFramebuffer(this.glFrameBuffer)
gl.deleteRenderbuffer(this.glRenderBuffer)
this.tex.free()
}
}
const gfx = (() => {
const defShader = makeShader(DEF_VERT, DEF_FRAG)
// a 1x1 white texture to draw raw shapes like rectangles and polygons
// we use a texture for those so we can use only 1 pipeline for drawing sprites + shapes
const emptyTex = Texture.fromImage(
new ImageData(new Uint8ClampedArray([ 255, 255, 255, 255 ]), 1, 1),
)
const frameBuffer = (gopt.width && gopt.height)
? new FrameBuffer(gopt.width * pixelDensity, gopt.height * pixelDensity)
: new FrameBuffer(gl.drawingBufferWidth, gl.drawingBufferHeight)
let bgColor: null | Color = null
let bgAlpha = 1
if (gopt.background) {
bgColor = Color.fromArray(gopt.background)
bgAlpha = gopt.background[3] ?? 1
gl.clearColor(
bgColor.r / 255,
bgColor.g / 255,
bgColor.b / 255,
bgAlpha,
)
}
gl.enable(gl.BLEND)
gl.enable(gl.SCISSOR_TEST)
gl.blendFuncSeparate(
gl.SRC_ALPHA,
gl.ONE_MINUS_SRC_ALPHA,
gl.ONE,
gl.ONE_MINUS_SRC_ALPHA,
)
// we only use one vertex and index buffer that batches all draw calls
const vbuf = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, vbuf)
gl.bufferData(gl.ARRAY_BUFFER, MAX_BATCHED_VERTS * 4, gl.DYNAMIC_DRAW)
VERTEX_FORMAT.reduce((offset, f, i) => {
gl.vertexAttribPointer(i, f.size, gl.FLOAT, false, STRIDE * 4, offset)
gl.enableVertexAttribArray(i)
return offset + f.size * 4
}, 0)
gl.bindBuffer(gl.ARRAY_BUFFER, null)
const ibuf = gl.createBuffer()
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, ibuf)
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, MAX_BATCHED_INDICES * 4, gl.DYNAMIC_DRAW)
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null)
// a checkerboard texture used for the default background
const bgTex = Texture.fromImage(
new ImageData(new Uint8ClampedArray([
128, 128, 128, 255,
190, 190, 190, 255,
190, 190, 190, 255,
128, 128, 128, 255,
]), 2, 2), {
wrap: "repeat",
filter: "nearest",
},
)
return {
// keep track of how many draw calls we're doing this frame
drawCalls: 0,
// how many draw calls we're doing last frame, this is the number we give to users
lastDrawCalls: 0,
// gfx states
defShader: defShader,
curShader: defShader,
frameBuffer: frameBuffer,
postShader: null,
postShaderUniform: null,
defTex: emptyTex,
curTex: emptyTex,
curUniform: {},
vbuf: vbuf,
ibuf: ibuf,
// local vertex / index buffer queue
vqueue: [],
iqueue: [],
transform: new Mat4(),
transformStack: [],
bgTex: bgTex,
bgColor: bgColor,
bgAlpha: bgAlpha,
width: gopt.width ?? gl.drawingBufferWidth / pixelDensity / gscale,
height: gopt.height ?? gl.drawingBufferHeight / pixelDensity / gscale,
viewport: {
x: 0,
y: 0,
width: gl.drawingBufferWidth,
height: gl.drawingBufferHeight,
},
fixed: false,
}
})()
class SpriteData {
tex: Texture
frames: Quad[] = [ new Quad(0, 0, 1, 1) ]
anims: SpriteAnims = {}
slice9: NineSlice | null = null
constructor(
tex: Texture,
frames?: Quad[],
anims: SpriteAnims = {},
slice9: NineSlice = null,
) {
this.tex = tex
if (frames) this.frames = frames
this.anims = anims
this.slice9 = slice9
}
static from(src: LoadSpriteSrc, opt: LoadSpriteOpt = {}): Promise<SpriteData> {
return typeof src === "string"
? SpriteData.fromURL(src, opt)
: Promise.resolve(SpriteData.fromImage(src, opt))
}
static fromImage(data: ImageSource, opt: LoadSpriteOpt = {}): SpriteData {
const [tex, quad] = assets.packer.add(data)
const frames = opt.frames ? opt.frames.map((f) => new Quad(
quad.x + f.x * quad.w,
quad.y + f.y * quad.h,
f.w * quad.w,
f.h * quad.h,
)) : slice(opt.sliceX || 1, opt.sliceY || 1, quad.x, quad.y, quad.w, quad.h)
return new SpriteData(tex, frames, opt.anims, opt.slice9)
}
static fromURL(url: string, opt: LoadSpriteOpt = {}): Promise<SpriteData> {
return loadImg(url).then((img) => SpriteData.fromImage(img, opt))
}
}
class SoundData {
buf: AudioBuffer
constructor(buf: AudioBuffer) {
this.buf = buf
}
static fromArrayBuffer(buf: ArrayBuffer): Promise<SoundData> {
return new Promise((resolve, reject) =>
audio.ctx.decodeAudioData(buf, resolve, reject),
).then((buf: AudioBuffer) => new SoundData(buf))
}
static fromURL(url: string): Promise<SoundData> {
if (isDataURL(url)) {
return SoundData.fromArrayBuffer(dataURLToArrayBuffer(url))
} else {
return fetchArrayBuffer(url).then((buf) => SoundData.fromArrayBuffer(buf))
}
}
}
const audio = (() => {
// TODO: handle when audio context is unavailable
const ctx = new (
window.AudioContext || (window as any).webkitAudioContext
)() as AudioContext
const masterNode = ctx.createGain()
masterNode.connect(ctx.destination)
// by default browsers can only load audio async, we don't deal with that and just start with an empty audio buffer
const burpSnd = new SoundData(createEmptyAudioBuffer(ctx))
// load that burp sound
ctx.decodeAudioData(burpSoundSrc.buffer.slice(0)).then((buf) => {
burpSnd.buf = buf
}).catch((err) => {
console.error("Failed to load burp: ", err)
})
return {
ctx,
masterNode,
burpSnd,
}
})()
class Asset<D> {
loaded: boolean = false
data: D | null = null
error: Error | null = null
private onLoadEvents: Event<[D]> = new Event()
private onErrorEvents: Event<[Error]> = new Event()
private onFinishEvents: Event<[]> = new Event()
constructor(loader: Promise<D>) {
loader.then((data) => {
this.data = data
this.onLoadEvents.trigger(data)
}).catch((err) => {
this.error = err
if (this.onErrorEvents.numListeners() > 0) {
this.onErrorEvents.trigger(err)
} else {
throw err
}
}).finally(() => {
this.onFinishEvents.trigger()
this.loaded = true
})
}
static loaded<D>(data: D): Asset<D> {
const asset = new Asset(Promise.resolve(data)) as Asset<D>
asset.data = data
asset.loaded = true
return asset
}
onLoad(action: (data: D) => void) {
if (this.loaded && this.data) {
action(this.data)
} else {
this.onLoadEvents.add(action)
}
return this
}
onError(action: (err: Error) => void) {
if (this.loaded && this.error) {
action(this.error)
} else {
this.onErrorEvents.add(action)
}
return this
}
onFinish(action: () => void) {
if (this.loaded) {
action()
} else {
this.onFinishEvents.add(action)
}
return this
}
then(action: (data: D) => void): Asset<D> {
return this.onLoad(action)
}
catch(action: (err: Error) => void): Asset<D> {
return this.onError(action)
}
finally(action: () => void): Asset<D> {
return this.onFinish(action)
}
}
class AssetBucket<D> {
assets: Map<string, Asset<D>> = new Map()
lastUID: number = 0
add(name: string | null, loader: Promise<D>): Asset<D> {
// if user don't provide a name we use a generated one
const id = name ?? (this.lastUID++ + "")
const asset = new Asset(loader)
this.assets.set(id, asset)
return asset
}
addLoaded(name: string | null, data: D): Asset<D> {
const id = name ?? (this.lastUID++ + "")
const asset = Asset.loaded(data)
this.assets.set(id, asset)
return asset
}
get(handle: string): Asset<D> | void {
return this.assets.get(handle)
}
progress(): number {
if (this.assets.size === 0) {
return 1
}
let loaded = 0
this.assets.forEach((asset) => {
if (asset.loaded) {
loaded++
}
})
return loaded / this.assets.size
}
}
const assets = {
// prefix for when loading from a url
urlPrefix: "",
// asset holders
sprites: new AssetBucket<SpriteData>(),
fonts: new AssetBucket<FontData>(),
bitmapFonts: new AssetBucket<BitmapFontData>(),
sounds: new AssetBucket<SoundData>(),
shaders: new AssetBucket<ShaderData>(),
custom: new AssetBucket<any>(),
packer: new TexPacker(SPRITE_ATLAS_WIDTH, SPRITE_ATLAS_HEIGHT),
// if we finished initially loading all assets
loaded: false,
}
const game = {
// general events
events: new EventHandler<{
mouseMove: [],
mouseDown: [MouseButton],
mousePress: [MouseButton],
mouseRelease: [MouseButton],
charInput: [string],
keyPress: [Key],
keyDown: [Key],
keyPressRepeat: [Key],
keyRelease: [Key],
touchStart: [Vec2, Touch],
touchMove: [Vec2, Touch],
touchEnd: [Vec2, Touch],
gamepadButtonDown: [string],
gamepadButtonPress: [string],
gamepadButtonRelease: [string],
gamepadStick: [string, Vec2],
gamepadConnect: [Gamepad],
gamepadDisconnect: [Gamepad],
scroll: [Vec2],
add: [GameObj],
destroy: [GameObj],
load: [],
loading: [number],
error: [Error],
input: [],
frameEnd: [],
resize: [],
sceneLeave: [string],
}>(),
// object events
objEvents: new EventHandler(),
// root game object
root: make([]),
// misc
gravity: 0,
scenes: {},
// on screen log
logs: [],
// camera
cam: {
pos: null,
scale: new Vec2(1),
angle: 0,
shake: 0,
transform: new Mat4(),
},
}
// TODO: accept Asset<T>?
// wrap individual loaders with global loader counter, for stuff like progress bar
function load<T>(prom: Promise<T>): Asset<T> {
return assets.custom.add(null, prom)
}
// get current load progress
function loadProgress(): number {
const buckets = [
assets.sprites,
assets.sounds,
assets.shaders,