kaplay 3001.0.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,80 @@
1
+ import type {
2
+ ImageSource,
3
+ } from "./types"
4
+
5
+ import {
6
+ GfxCtx,
7
+ Texture,
8
+ } from "./gfx"
9
+
10
+ import {
11
+ Vec2,
12
+ Quad,
13
+ } from "./math"
14
+
15
+ export default class TexPacker {
16
+ private textures: Texture[] = []
17
+ private bigTextures: Texture[] = []
18
+ private canvas: HTMLCanvasElement
19
+ private c2d: CanvasRenderingContext2D
20
+ private x: number = 0
21
+ private y: number = 0
22
+ private curHeight: number = 0
23
+ private gfx: GfxCtx
24
+ constructor(gfx: GfxCtx, w: number, h: number) {
25
+ this.gfx = gfx
26
+ this.canvas = document.createElement("canvas")
27
+ this.canvas.width = w
28
+ this.canvas.height = h
29
+ this.textures = [Texture.fromImage(gfx, this.canvas)]
30
+ this.bigTextures = []
31
+ this.c2d = this.canvas.getContext("2d")
32
+ }
33
+ add(img: ImageSource): [Texture, Quad] {
34
+ if (img.width > this.canvas.width || img.height > this.canvas.height) {
35
+ const tex = Texture.fromImage(this.gfx, img)
36
+ this.bigTextures.push(tex)
37
+ return [tex, new Quad(0, 0, 1, 1)]
38
+ }
39
+ // next row
40
+ if (this.x + img.width > this.canvas.width) {
41
+ this.x = 0
42
+ this.y += this.curHeight
43
+ this.curHeight = 0
44
+ }
45
+ // next texture
46
+ if (this.y + img.height > this.canvas.height) {
47
+ this.c2d.clearRect(0, 0, this.canvas.width, this.canvas.height)
48
+ this.textures.push(Texture.fromImage(this.gfx, this.canvas))
49
+ this.x = 0
50
+ this.y = 0
51
+ this.curHeight = 0
52
+ }
53
+ const curTex = this.textures[this.textures.length - 1]
54
+ const pos = new Vec2(this.x, this.y)
55
+ this.x += img.width
56
+ if (img.height > this.curHeight) {
57
+ this.curHeight = img.height
58
+ }
59
+ if (img instanceof ImageData) {
60
+ this.c2d.putImageData(img, pos.x, pos.y)
61
+ } else {
62
+ this.c2d.drawImage(img, pos.x, pos.y)
63
+ }
64
+ curTex.update(this.canvas)
65
+ return [curTex, new Quad(
66
+ pos.x / this.canvas.width,
67
+ pos.y / this.canvas.height,
68
+ img.width / this.canvas.width,
69
+ img.height / this.canvas.height,
70
+ )]
71
+ }
72
+ free() {
73
+ for (const tex of this.textures) {
74
+ tex.free()
75
+ }
76
+ for (const tex of this.bigTextures) {
77
+ tex.free()
78
+ }
79
+ }
80
+ }