kaplay 3000.1.17

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,73 @@
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 canvas: HTMLCanvasElement
18
+ private c2d: CanvasRenderingContext2D
19
+ private x: number = 0
20
+ private y: number = 0
21
+ private curHeight: number = 0
22
+ private gfx: GfxCtx
23
+ constructor(gfx: GfxCtx, w: number, h: number) {
24
+ this.gfx = gfx
25
+ this.canvas = document.createElement("canvas")
26
+ this.canvas.width = w
27
+ this.canvas.height = h
28
+ this.textures = [Texture.fromImage(gfx, this.canvas)]
29
+ this.c2d = this.canvas.getContext("2d")
30
+ }
31
+ add(img: ImageSource): [Texture, Quad] {
32
+ if (img.width > this.canvas.width || img.height > this.canvas.height) {
33
+ throw new Error(`Texture size (${img.width} x ${img.height}) exceeds limit (${this.canvas.width} x ${this.canvas.height})`)
34
+ }
35
+ // next row
36
+ if (this.x + img.width > this.canvas.width) {
37
+ this.x = 0
38
+ this.y += this.curHeight
39
+ this.curHeight = 0
40
+ }
41
+ // next texture
42
+ if (this.y + img.height > this.canvas.height) {
43
+ this.c2d.clearRect(0, 0, this.canvas.width, this.canvas.height)
44
+ this.textures.push(Texture.fromImage(this.gfx, this.canvas))
45
+ this.x = 0
46
+ this.y = 0
47
+ this.curHeight = 0
48
+ }
49
+ const curTex = this.textures[this.textures.length - 1]
50
+ const pos = new Vec2(this.x, this.y)
51
+ this.x += img.width
52
+ if (img.height > this.curHeight) {
53
+ this.curHeight = img.height
54
+ }
55
+ if (img instanceof ImageData) {
56
+ this.c2d.putImageData(img, pos.x, pos.y)
57
+ } else {
58
+ this.c2d.drawImage(img, pos.x, pos.y)
59
+ }
60
+ curTex.update(this.canvas)
61
+ return [curTex, new Quad(
62
+ pos.x / this.canvas.width,
63
+ pos.y / this.canvas.height,
64
+ img.width / this.canvas.width,
65
+ img.height / this.canvas.height,
66
+ )]
67
+ }
68
+ free() {
69
+ for (const tex of this.textures) {
70
+ tex.free()
71
+ }
72
+ }
73
+ }