@ohmygame/level-editor 0.0.0-stage → 0.1.0

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,112 @@
1
+ // The New map dialog: a Tiled map with a Ground tile layer, an Objects
2
+ // layer and an embedded tileset cut from a PNG in the project.
3
+ import * as tmj from "./tmj.js";
4
+ import { h } from "./dom.js";
5
+
6
+ let dialog;
7
+
8
+ /**
9
+ * Shows the New map dialog. `files` are the project's files, for the next
10
+ * free name and the PNGs to cut a tileset from; `created(path)` opens the
11
+ * map once it is written.
12
+ */
13
+ export function showNewMapDialog({ host, t, files: entries, created }) {
14
+ const files = new Set(entries.map((entry) => entry.path));
15
+ let n = 1;
16
+ while (files.has(`levels/level-${n}.tmj`)) n++;
17
+ const pngs = entries.filter((entry) => /\.png$/i.test(entry.path)).map((entry) => entry.path).sort((a, b) => a.localeCompare(b));
18
+ const d = t.dialog;
19
+ const field = (label, value, attributes = {}) => h("omg-input", { label, value, ...attributes });
20
+ const fields = {
21
+ file: field(d.file, `levels/level-${n}.tmj`, { hint: d.fileHint }),
22
+ columns: field(d.columns, "30", { type: "number", min: "1", max: "4096", step: "1" }),
23
+ rows: field(d.rows, "20", { type: "number", min: "1", max: "4096", step: "1" }),
24
+ tileWidth: field(d.tileWidth, "16", { type: "number", min: "1", max: "4096", step: "1" }),
25
+ tileHeight: field(d.tileHeight, "16", { type: "number", min: "1", max: "4096", step: "1" }),
26
+ image: h(
27
+ pngs.length > 12 ? "omg-combobox" : "omg-select",
28
+ { label: d.tilesetImage, hint: d.tilesetHint, value: pngs.find((path) => /tile/i.test(tmj.basename(path))) ?? pngs[0] ?? "", placeholder: d.search, "empty-label": d.noImages },
29
+ h("option", { value: "" }, d.noImage),
30
+ pngs.map((path) => h("option", { value: path }, path)),
31
+ ),
32
+ };
33
+ const create = h("omg-button", { variant: "primary", on: { click: () => void createMap({ host, t, fields, files, button: create, created }) } }, d.create);
34
+ dialog?.remove();
35
+ dialog = h(
36
+ "omg-dialog",
37
+ { heading: d.heading, description: d.description, "close-label": d.cancel },
38
+ h("div", { class: "dialog-fields" }, fields.file, h("div", { class: "field-grid" }, fields.columns, fields.rows, fields.tileWidth, fields.tileHeight), fields.image),
39
+ h("omg-button", { slot: "footer", variant: "ghost", on: { click: () => (dialog.open = false) } }, d.cancel),
40
+ h("span", { slot: "footer" }, create),
41
+ );
42
+ document.body.append(dialog);
43
+ dialog.open = true;
44
+ requestAnimationFrame(() => fields.file.focus?.());
45
+ }
46
+
47
+ async function createMap({ host, t, fields, files, button, created }) {
48
+ const d = t.dialog;
49
+ for (const element of Object.values(fields)) element.removeAttribute("error");
50
+ const path = fields.file.value.trim().replace(/^\.?\/+/, "").replaceAll("\\", "/");
51
+ let valid = true;
52
+ if (!/\.(?:tmj|json)$/i.test(path) || path.split("/").some((part) => !part || part === ".." || part.startsWith("."))) {
53
+ fields.file.setAttribute("error", d.badName);
54
+ valid = false;
55
+ } else if (files.has(path)) {
56
+ fields.file.setAttribute("error", d.exists);
57
+ valid = false;
58
+ }
59
+ const numbers = {};
60
+ for (const key of ["columns", "rows", "tileWidth", "tileHeight"]) {
61
+ const value = Number(fields[key].value);
62
+ if (!Number.isInteger(value) || value < 1 || value > 4096) {
63
+ fields[key].setAttribute("error", d.badNumber);
64
+ valid = false;
65
+ }
66
+ numbers[key] = value;
67
+ }
68
+ if (!valid) return;
69
+ button.busy = true;
70
+ try {
71
+ let tileset;
72
+ const imagePath = fields.image.value;
73
+ if (imagePath) {
74
+ let picture;
75
+ try {
76
+ const url = await host.files.url(imagePath);
77
+ picture = new Image();
78
+ picture.src = url;
79
+ await picture.decode();
80
+ } catch {
81
+ fields.image.setAttribute("error", d.imageFailed);
82
+ return;
83
+ }
84
+ if (picture.naturalWidth < numbers.tileWidth || picture.naturalHeight < numbers.tileHeight) {
85
+ fields.image.setAttribute("error", d.imageTooSmall);
86
+ return;
87
+ }
88
+ tileset = {
89
+ name: tmj.basename(imagePath).replace(/\.[^.]+$/, ""),
90
+ image: tmj.relativePath(path, imagePath),
91
+ imagewidth: picture.naturalWidth,
92
+ imageheight: picture.naturalHeight,
93
+ };
94
+ }
95
+ // Something may have been written there since the dialog opened.
96
+ try {
97
+ await host.files.text(path);
98
+ fields.file.setAttribute("error", d.exists);
99
+ return;
100
+ } catch {
101
+ // Free.
102
+ }
103
+ const doc = tmj.createMap({ width: numbers.columns, height: numbers.rows, tilewidth: numbers.tileWidth, tileheight: numbers.tileHeight, tileset });
104
+ await host.files.write(path, tmj.formatJson(doc, tmj.newMapStyle(doc)));
105
+ dialog.open = false;
106
+ await created(path);
107
+ } catch (error) {
108
+ fields.file.setAttribute("error", error instanceof Error ? error.message : String(error));
109
+ } finally {
110
+ button.busy = false;
111
+ }
112
+ }
@@ -0,0 +1,196 @@
1
+ // The tileset palette: one tileset's tiles on a canvas, where a click picks a
2
+ // tile and a drag picks a rectangle of them as a stamp.
3
+ import { stampOf } from "./tmj.js";
4
+ import { drawTile } from "./render.js";
5
+
6
+ /** Collection tiles are shown in cells this many CSS pixels wide. */
7
+ const COLLECTION_CELL = 44;
8
+
9
+ export class Palette {
10
+ /** `onPick(stamp)` hears each pick; `theme()` gives the colours to draw with. */
11
+ constructor({ onPick, theme }) {
12
+ this.onPick = onPick;
13
+ this.theme = theme;
14
+ this.canvas = document.createElement("canvas");
15
+ this.canvas.className = "palette-canvas";
16
+ this.scroller = document.createElement("div");
17
+ this.scroller.className = "palette-scroll";
18
+ this.scroller.append(this.canvas);
19
+ this.tileset = undefined;
20
+ this.selection = undefined;
21
+ this.hover = undefined;
22
+ this.drag = undefined;
23
+ this.canvas.addEventListener("pointerdown", (event) => this.#down(event));
24
+ this.canvas.addEventListener("pointermove", (event) => this.#move(event));
25
+ this.canvas.addEventListener("pointerup", (event) => this.#up(event));
26
+ this.canvas.addEventListener("pointerleave", () => {
27
+ this.hover = undefined;
28
+ this.draw();
29
+ });
30
+ new ResizeObserver(() => this.draw()).observe(this.scroller);
31
+ }
32
+
33
+ /** Shows a runtime tileset (see main.js `loadTilesets`), keeping the selection if it is the same one. */
34
+ show(tileset) {
35
+ const key = (item) => item && `${item.firstgid}:${item.base}:${item.ids.length}`;
36
+ if (key(tileset) !== key(this.tileset)) this.selection = undefined;
37
+ this.tileset = tileset;
38
+ this.draw();
39
+ }
40
+
41
+ /** Marks the tile `gid` if it is in this tileset, as when the eyedropper picks it. */
42
+ mark(gid) {
43
+ const tileset = this.tileset;
44
+ this.selection = undefined;
45
+ if (tileset) {
46
+ const at = this.#cellOf(gid - tileset.firstgid);
47
+ if (at) this.selection = { c0: at[0], r0: at[1], c1: at[0], r1: at[1] };
48
+ }
49
+ this.draw();
50
+ }
51
+
52
+ clear() {
53
+ this.selection = undefined;
54
+ this.draw();
55
+ }
56
+
57
+ /** How the palette lays out its tileset: columns, rows and cell size in CSS pixels. */
58
+ #layout() {
59
+ const tileset = this.tileset;
60
+ const available = Math.max(80, this.scroller.clientWidth - 2);
61
+ if (!tileset) return undefined;
62
+ if (tileset.atlas) {
63
+ const columns = Math.max(1, tileset.columns);
64
+ const rows = Math.ceil(tileset.ids.length / columns);
65
+ let scale = available / (columns * tileset.tilewidth);
66
+ scale = scale >= 1 ? Math.min(Math.floor(scale), 3) : Math.max(scale, 12 / tileset.tilewidth);
67
+ return { columns, rows, cw: tileset.tilewidth * scale, ch: tileset.tileheight * scale };
68
+ }
69
+ const columns = Math.max(1, Math.floor(available / COLLECTION_CELL));
70
+ return { columns, rows: Math.ceil(tileset.ids.length / columns), cw: COLLECTION_CELL, ch: COLLECTION_CELL };
71
+ }
72
+
73
+ #cellOf(id) {
74
+ const tileset = this.tileset;
75
+ const layout = this.#layout();
76
+ if (!layout) return undefined;
77
+ const index = tileset.atlas ? id : tileset.ids.indexOf(id);
78
+ if (index < 0 || index >= (tileset.atlas ? tileset.ids.length : Infinity)) return undefined;
79
+ return [index % layout.columns, Math.floor(index / layout.columns)];
80
+ }
81
+
82
+ #idAt(column, row, layout) {
83
+ const index = row * layout.columns + column;
84
+ if (column < 0 || row < 0 || column >= layout.columns || index >= this.tileset.ids.length) return undefined;
85
+ return this.tileset.ids[index];
86
+ }
87
+
88
+ draw() {
89
+ const tileset = this.tileset;
90
+ const layout = this.#layout();
91
+ const dpr = window.devicePixelRatio || 1;
92
+ const canvas = this.canvas;
93
+ if (!tileset || !layout) {
94
+ canvas.width = canvas.height = 0;
95
+ return;
96
+ }
97
+ const width = Math.ceil(layout.columns * layout.cw);
98
+ const height = Math.max(1, Math.ceil(layout.rows * layout.ch));
99
+ canvas.style.width = `${width}px`;
100
+ canvas.style.height = `${height}px`;
101
+ canvas.width = Math.round(width * dpr);
102
+ canvas.height = Math.round(height * dpr);
103
+ const ctx = canvas.getContext("2d");
104
+ ctx.imageSmoothingEnabled = !tileset.atlas;
105
+ const theme = this.theme();
106
+ ctx.fillStyle = theme.background;
107
+ ctx.fillRect(0, 0, canvas.width, canvas.height);
108
+ tileset.ids.forEach((id, index) => {
109
+ const tile = tileset.tile(id);
110
+ if (!tile) return;
111
+ const column = index % layout.columns;
112
+ const row = Math.floor(index / layout.columns);
113
+ let x = column * layout.cw;
114
+ let y = row * layout.ch;
115
+ let w = layout.cw;
116
+ let h = layout.ch;
117
+ if (!tileset.atlas) {
118
+ // Fit each image in its cell, keeping its shape.
119
+ const fit = Math.min((layout.cw - 4) / tile.width, (layout.ch - 4) / tile.height, 4);
120
+ w = tile.width * fit;
121
+ h = tile.height * fit;
122
+ x += (layout.cw - w) / 2;
123
+ y += (layout.ch - h) / 2;
124
+ }
125
+ drawTile(ctx, tile, 0, x * dpr, y * dpr, (x + w) * dpr, (y + h) * dpr);
126
+ });
127
+ const outline = (rect, color, chosen) => {
128
+ const x0 = Math.round(Math.min(rect.c0, rect.c1) * layout.cw * dpr);
129
+ const y0 = Math.round(Math.min(rect.r0, rect.r1) * layout.ch * dpr);
130
+ const x1 = Math.round((Math.max(rect.c0, rect.c1) + 1) * layout.cw * dpr);
131
+ const y1 = Math.round((Math.max(rect.r0, rect.r1) + 1) * layout.ch * dpr);
132
+ if (chosen) {
133
+ ctx.fillStyle = theme.selectionFill;
134
+ ctx.fillRect(x0, y0, x1 - x0, y1 - y0);
135
+ }
136
+ const inset = chosen ? dpr : dpr / 2;
137
+ ctx.lineWidth = chosen ? 2 * dpr : dpr;
138
+ ctx.setLineDash(chosen ? [] : [3 * dpr, 2 * dpr]);
139
+ ctx.strokeStyle = color;
140
+ ctx.strokeRect(x0 + inset, y0 + inset, x1 - x0 - inset * 2, y1 - y0 - inset * 2);
141
+ ctx.setLineDash([]);
142
+ };
143
+ if (this.hover && !this.drag) outline({ c0: this.hover[0], r0: this.hover[1], c1: this.hover[0], r1: this.hover[1] }, theme.hover, false);
144
+ const selection = this.drag ?? this.selection;
145
+ if (selection) outline(selection, theme.selection, true);
146
+ }
147
+
148
+ #cellAt(event) {
149
+ const layout = this.#layout();
150
+ const rect = this.canvas.getBoundingClientRect();
151
+ const column = Math.floor((event.clientX - rect.left) / layout.cw);
152
+ const row = Math.floor((event.clientY - rect.top) / layout.ch);
153
+ return [Math.max(0, Math.min(layout.columns - 1, column)), Math.max(0, Math.min(layout.rows - 1, row))];
154
+ }
155
+
156
+ #down(event) {
157
+ if (!this.tileset || event.button !== 0) return;
158
+ const [column, row] = this.#cellAt(event);
159
+ if (this.#idAt(column, row, this.#layout()) === undefined) return;
160
+ this.canvas.setPointerCapture(event.pointerId);
161
+ this.drag = { c0: column, r0: row, c1: column, r1: row };
162
+ this.draw();
163
+ }
164
+
165
+ #move(event) {
166
+ if (!this.tileset) return;
167
+ const [column, row] = this.#cellAt(event);
168
+ if (this.drag) {
169
+ // A collection's tiles aren't a picture, so only one is picked.
170
+ if (this.tileset.atlas) Object.assign(this.drag, { c1: column, r1: row });
171
+ } else this.hover = [column, row];
172
+ this.draw();
173
+ }
174
+
175
+ #up(event) {
176
+ if (!this.drag) return;
177
+ this.canvas.releasePointerCapture?.(event.pointerId);
178
+ const layout = this.#layout();
179
+ const { c0, r0, c1, r1 } = this.drag;
180
+ const left = Math.min(c0, c1);
181
+ const top = Math.min(r0, r1);
182
+ const width = Math.abs(c1 - c0) + 1;
183
+ const height = Math.abs(r1 - r0) + 1;
184
+ const gids = [];
185
+ for (let row = top; row < top + height; row++) {
186
+ for (let column = left; column < left + width; column++) {
187
+ const id = this.#idAt(column, row, layout);
188
+ gids.push(id === undefined ? 0 : this.tileset.firstgid + id);
189
+ }
190
+ }
191
+ this.selection = { c0: left, r0: top, c1: left + width - 1, r1: top + height - 1 };
192
+ this.drag = undefined;
193
+ this.draw();
194
+ if (gids.some(Boolean)) this.onPick(stampOf(width, height, gids));
195
+ }
196
+ }
@@ -0,0 +1,321 @@
1
+ // Draws a map on the panel's canvas, and finds the object under a point.
2
+ // Everything is drawn in device pixels with tile edges rounded, so tiles
3
+ // meet without seams at any zoom; only what is in view is drawn.
4
+ import { FLIP_D, FLIP_H, FLIP_V } from "./tmj.js";
5
+
6
+ /** `#rrggbb` or Tiled's `#aarrggbb` as a CSS colour. */
7
+ export function cssColor(value, fallback) {
8
+ const match = /^#?([0-9a-f]{6}|[0-9a-f]{8})$/i.exec(String(value ?? ""));
9
+ if (!match) return fallback;
10
+ const hex = match[1];
11
+ if (hex.length === 6) return `#${hex}`;
12
+ return `#${hex.slice(2)}${hex.slice(0, 2)}`;
13
+ }
14
+
15
+ const COLLISION = /collision|collide|solid|wall|block/i;
16
+
17
+ /** The colour an object layer is drawn in: its own `color`, else one by what it seems to be for. */
18
+ export function layerColor(layer, theme) {
19
+ return cssColor(layer.color, COLLISION.test(layer.name ?? "") ? theme.collision : theme.objects);
20
+ }
21
+
22
+ /**
23
+ * Draws the scene. `scene` has the canvas size in device pixels (`width`,
24
+ * `height`), `dpr`, the view (`zoom`, `x`, `y`: the map's origin in CSS
25
+ * pixels), the map `doc` and its decoded `tiles`, `tile(gid)` giving what to
26
+ * draw a tile from, `image(path)` for image layers, `theme` colours, `grid`,
27
+ * and `overlay(ctx, toDevice)` for the tool's preview.
28
+ */
29
+ export function drawScene(ctx, scene) {
30
+ const { doc, dpr, zoom, theme } = scene;
31
+ const scale = zoom * dpr;
32
+ const ox = scene.x * dpr;
33
+ const oy = scene.y * dpr;
34
+ const tw = doc.tilewidth;
35
+ const th = doc.tileheight;
36
+ ctx.setTransform(1, 0, 0, 1, 0, 0);
37
+ ctx.globalAlpha = 1;
38
+ ctx.clearRect(0, 0, scene.width, scene.height);
39
+ ctx.imageSmoothingEnabled = false;
40
+
41
+ const bounds = mapBounds(scene);
42
+ const left = Math.round(ox + bounds.x * scale);
43
+ const top = Math.round(oy + bounds.y * scale);
44
+ const right = Math.round(ox + (bounds.x + bounds.width) * scale);
45
+ const bottom = Math.round(oy + (bounds.y + bounds.height) * scale);
46
+ ctx.fillStyle = cssColor(doc.backgroundcolor, theme.background);
47
+ ctx.fillRect(left, top, right - left, bottom - top);
48
+
49
+ const view = { left: -ox / scale, top: -oy / scale, right: (scene.width - ox) / scale, bottom: (scene.height - oy) / scale };
50
+ const drawLayers = (layers, opacity, offsetX, offsetY) => {
51
+ for (const layer of layers ?? []) {
52
+ if (layer.visible === false) continue;
53
+ const alpha = opacity * (layer.opacity ?? 1);
54
+ const dx = offsetX + (layer.offsetx ?? 0);
55
+ const dy = offsetY + (layer.offsety ?? 0);
56
+ if (layer.type === "group") drawLayers(layer.layers, alpha, dx, dy);
57
+ else if (layer.type === "tilelayer") drawTileLayer(ctx, scene, layer, alpha, dx, dy, view, scale, ox, oy);
58
+ else if (layer.type === "objectgroup") drawObjectLayer(ctx, scene, layer, alpha, dx, dy, scale, ox, oy);
59
+ else if (layer.type === "imagelayer") drawImageLayer(ctx, scene, layer, alpha, dx, dy, scale, ox, oy);
60
+ }
61
+ };
62
+ drawLayers(doc.layers, 1, 0, 0);
63
+ ctx.globalAlpha = 1;
64
+
65
+ if (scene.grid && tw * scale >= 4 && th * scale >= 4) {
66
+ ctx.beginPath();
67
+ const c0 = Math.max(Math.floor((view.left - bounds.x) / tw), 0);
68
+ const c1 = Math.min(Math.ceil((view.right - bounds.x) / tw), bounds.width / tw);
69
+ const r0 = Math.max(Math.floor((view.top - bounds.y) / th), 0);
70
+ const r1 = Math.min(Math.ceil((view.bottom - bounds.y) / th), bounds.height / th);
71
+ for (let c = c0; c <= c1; c++) {
72
+ const x = Math.round(ox + (bounds.x + c * tw) * scale) + 0.5;
73
+ ctx.moveTo(x, Math.max(top, 0));
74
+ ctx.lineTo(x, Math.min(bottom, scene.height));
75
+ }
76
+ for (let r = r0; r <= r1; r++) {
77
+ const y = Math.round(oy + (bounds.y + r * th) * scale) + 0.5;
78
+ ctx.moveTo(Math.max(left, 0), y);
79
+ ctx.lineTo(Math.min(right, scene.width), y);
80
+ }
81
+ ctx.lineWidth = 1;
82
+ ctx.strokeStyle = theme.grid;
83
+ ctx.stroke();
84
+ }
85
+ ctx.lineWidth = 1;
86
+ ctx.strokeStyle = theme.bounds;
87
+ ctx.strokeRect(left + 0.5, top + 0.5, right - left - 1, bottom - top - 1);
88
+
89
+ const toDevice = (wx, wy) => [ox + wx * scale, oy + wy * scale];
90
+ scene.overlay?.(ctx, toDevice, scale);
91
+ }
92
+
93
+ /** The map's extent in pixels; for an infinite map, that of its chunks. */
94
+ export function mapBounds({ doc, tiles }) {
95
+ const tw = doc.tilewidth;
96
+ const th = doc.tileheight;
97
+ if (!doc.infinite) return { x: 0, y: 0, width: doc.width * tw, height: doc.height * th };
98
+ let x0 = Infinity;
99
+ let y0 = Infinity;
100
+ let x1 = -Infinity;
101
+ let y1 = -Infinity;
102
+ for (const state of tiles.values()) {
103
+ for (const chunk of state.chunks ?? []) {
104
+ x0 = Math.min(x0, chunk.x);
105
+ y0 = Math.min(y0, chunk.y);
106
+ x1 = Math.max(x1, chunk.x + chunk.width);
107
+ y1 = Math.max(y1, chunk.y + chunk.height);
108
+ }
109
+ }
110
+ if (x0 === Infinity) return { x: 0, y: 0, width: (doc.width || 16) * tw, height: (doc.height || 16) * th };
111
+ return { x: x0 * tw, y: y0 * th, width: (x1 - x0) * tw, height: (y1 - y0) * th };
112
+ }
113
+
114
+ function drawTileLayer(ctx, scene, layer, alpha, dx, dy, view, scale, ox, oy) {
115
+ const state = scene.tiles.get(layer);
116
+ if (!state) return;
117
+ ctx.globalAlpha = alpha;
118
+ const parts = state.gids ? [{ x: 0, y: 0, width: state.width, height: state.height, gids: state.gids }] : (state.chunks ?? []);
119
+ const { tilewidth: tw, tileheight: th } = scene.doc;
120
+ // Tiles taller or wider than the grid reach into neighbouring cells.
121
+ const pad = scene.tilePad ?? 1;
122
+ for (const part of parts) {
123
+ const c0 = Math.max(0, Math.floor((view.left - dx) / tw) - part.x - pad);
124
+ const c1 = Math.min(part.width - 1, Math.ceil((view.right - dx) / tw) - part.x + pad);
125
+ const r0 = Math.max(0, Math.floor((view.top - dy) / th) - part.y - 1);
126
+ const r1 = Math.min(part.height - 1, Math.ceil((view.bottom - dy) / th) - part.y + pad);
127
+ for (let r = r0; r <= r1; r++) {
128
+ for (let c = c0; c <= c1; c++) {
129
+ const gid = part.gids[r * part.width + c];
130
+ if (!gid) continue;
131
+ const tile = scene.tile(gid);
132
+ if (!tile) continue;
133
+ const cellX = dx + (part.x + c) * tw;
134
+ const cellY = dy + (part.y + r) * th;
135
+ let x, y, w, h;
136
+ if (tile.grid) {
137
+ [x, y, w, h] = [cellX, cellY, tw, th];
138
+ } else {
139
+ w = tile.width;
140
+ h = tile.height;
141
+ x = cellX + tile.offsetX;
142
+ y = cellY + th - h + tile.offsetY;
143
+ }
144
+ drawTile(ctx, tile, gid, ox + x * scale, oy + y * scale, ox + (x + w) * scale, oy + (y + h) * scale);
145
+ }
146
+ }
147
+ }
148
+ }
149
+
150
+ /** Draws one tile into the device rectangle (x0, y0)–(x1, y1), applying its flip flags. */
151
+ export function drawTile(ctx, tile, gid, x0, y0, x1, y1) {
152
+ const left = Math.round(x0);
153
+ const top = Math.round(y0);
154
+ const width = Math.round(x1) - left;
155
+ const height = Math.round(y1) - top;
156
+ if (width <= 0 || height <= 0) return;
157
+ if (!(gid & (FLIP_H | FLIP_V | FLIP_D))) {
158
+ ctx.drawImage(tile.image, tile.sx, tile.sy, tile.sw, tile.sh, left, top, width, height);
159
+ return;
160
+ }
161
+ ctx.save();
162
+ ctx.translate(left + width / 2, top + height / 2);
163
+ ctx.scale(gid & FLIP_H ? -1 : 1, gid & FLIP_V ? -1 : 1);
164
+ // The diagonal flip swaps x and y before the other flips (Tiled's order).
165
+ if (gid & FLIP_D) ctx.transform(0, 1, 1, 0, 0, 0);
166
+ const [w, h] = gid & FLIP_D ? [height, width] : [width, height];
167
+ ctx.drawImage(tile.image, tile.sx, tile.sy, tile.sw, tile.sh, -w / 2, -h / 2, w, h);
168
+ ctx.restore();
169
+ }
170
+
171
+ function drawImageLayer(ctx, scene, layer, alpha, dx, dy, scale, ox, oy) {
172
+ const image = scene.image(layer.image);
173
+ if (!image) return;
174
+ ctx.globalAlpha = alpha;
175
+ const x = dx + (layer.x ?? 0);
176
+ const y = dy + (layer.y ?? 0);
177
+ ctx.drawImage(image, Math.round(ox + x * scale), Math.round(oy + y * scale), Math.round(image.naturalWidth * scale), Math.round(image.naturalHeight * scale));
178
+ }
179
+
180
+ function drawObjectLayer(ctx, scene, layer, alpha, dx, dy, scale, ox, oy) {
181
+ const color = layerColor(layer, scene.theme);
182
+ const { dpr } = scene;
183
+ const objects = layer.objects ?? [];
184
+ for (const object of objects) {
185
+ if (object.visible === false) continue;
186
+ ctx.globalAlpha = alpha * (object.opacity ?? 1);
187
+ ctx.setTransform(scale, 0, 0, scale, ox + (dx + object.x) * scale, oy + (dy + object.y) * scale);
188
+ if (object.rotation) ctx.rotate((object.rotation * Math.PI) / 180);
189
+ const line = (1.5 * dpr) / scale;
190
+ ctx.lineWidth = line;
191
+ ctx.strokeStyle = color;
192
+ ctx.fillStyle = withAlpha(color, 0.22);
193
+ const width = object.width ?? 0;
194
+ const height = object.height ?? 0;
195
+ if (object.gid) {
196
+ const tile = scene.tile(object.gid);
197
+ ctx.setTransform(1, 0, 0, 1, 0, 0);
198
+ if (tile && !object.rotation) {
199
+ const x = ox + (dx + object.x) * scale;
200
+ const y = oy + (dy + object.y) * scale;
201
+ const w = (width || tile.width) * scale;
202
+ const h = (height || tile.height) * scale;
203
+ drawTile(ctx, tile, object.gid, x, y - h, x + w, y);
204
+ } else {
205
+ ctx.setTransform(scale, 0, 0, scale, ox + (dx + object.x) * scale, oy + (dy + object.y) * scale);
206
+ if (object.rotation) ctx.rotate((object.rotation * Math.PI) / 180);
207
+ if (tile) {
208
+ ctx.scale(object.gid & FLIP_H ? -1 : 1, object.gid & FLIP_V ? -1 : 1);
209
+ ctx.drawImage(tile.image, tile.sx, tile.sy, tile.sw, tile.sh, object.gid & FLIP_H ? -width : 0, object.gid & FLIP_V ? 0 : -height, width, height);
210
+ } else ctx.strokeRect(0, -height, width, height);
211
+ }
212
+ } else if (object.point || (!width && !height && !object.polygon && !object.polyline && !object.text)) {
213
+ ctx.setTransform(1, 0, 0, 1, 0, 0);
214
+ const [x, y] = [ox + (dx + object.x) * scale, oy + (dy + object.y) * scale];
215
+ drawPin(ctx, x, y, color, dpr);
216
+ } else if (object.polygon || object.polyline) {
217
+ const points = object.polygon ?? object.polyline;
218
+ ctx.beginPath();
219
+ points.forEach((point, i) => (i ? ctx.lineTo(point.x, point.y) : ctx.moveTo(point.x, point.y)));
220
+ if (object.polygon) {
221
+ ctx.closePath();
222
+ ctx.fill();
223
+ }
224
+ ctx.stroke();
225
+ } else if (object.ellipse || object.capsule) {
226
+ ctx.beginPath();
227
+ ctx.ellipse(width / 2, height / 2, width / 2, height / 2, 0, 0, Math.PI * 2);
228
+ ctx.fill();
229
+ ctx.stroke();
230
+ } else if (object.text) {
231
+ const text = object.text;
232
+ ctx.fillStyle = cssColor(text.color, scene.theme.text);
233
+ ctx.font = `${text.bold ? "bold " : ""}${text.italic ? "italic " : ""}${text.pixelsize ?? 16}px ${text.fontfamily ?? "sans-serif"}`;
234
+ ctx.textBaseline = "top";
235
+ ctx.fillText(String(text.text ?? ""), 0, 0, width || undefined);
236
+ } else {
237
+ ctx.fillRect(0, 0, width, height);
238
+ ctx.strokeRect(line / 2, line / 2, Math.max(0, width - line), Math.max(0, height - line));
239
+ }
240
+ ctx.setTransform(1, 0, 0, 1, 0, 0);
241
+ const label = object.name || object.type || object.class;
242
+ if (label && scale >= 0.75 * dpr) {
243
+ const [x, y] = [ox + (dx + object.x) * scale, oy + (dy + object.y) * scale];
244
+ const anchorY = object.gid ? y - (height || 0) * scale : y;
245
+ drawLabel(ctx, label, x, anchorY - (object.point ? 17 * dpr : 3 * dpr), scene);
246
+ }
247
+ }
248
+ ctx.globalAlpha = 1;
249
+ }
250
+
251
+ function drawPin(ctx, x, y, color, dpr) {
252
+ const r = 6 * dpr;
253
+ ctx.beginPath();
254
+ ctx.moveTo(x, y);
255
+ ctx.bezierCurveTo(x - r * 1.3, y - r * 1.6, x - r, y - r * 2.6, x, y - r * 2.6);
256
+ ctx.bezierCurveTo(x + r, y - r * 2.6, x + r * 1.3, y - r * 1.6, x, y);
257
+ ctx.fillStyle = color;
258
+ ctx.fill();
259
+ ctx.lineWidth = dpr;
260
+ ctx.strokeStyle = "rgba(0,0,0,0.45)";
261
+ ctx.stroke();
262
+ ctx.beginPath();
263
+ ctx.arc(x, y - r * 1.75, r * 0.45, 0, Math.PI * 2);
264
+ ctx.fillStyle = "rgba(255,255,255,0.9)";
265
+ ctx.fill();
266
+ }
267
+
268
+ function drawLabel(ctx, text, x, y, scene) {
269
+ const { dpr, theme } = scene;
270
+ ctx.font = `${11 * dpr}px ${theme.font}`;
271
+ ctx.textBaseline = "bottom";
272
+ const width = ctx.measureText(text).width;
273
+ const pad = 3 * dpr;
274
+ ctx.fillStyle = theme.labelBackground;
275
+ ctx.fillRect(Math.round(x - pad), Math.round(y - 14 * dpr), Math.round(width + pad * 2), Math.round(14 * dpr));
276
+ ctx.fillStyle = theme.labelText;
277
+ ctx.fillText(text, Math.round(x), Math.round(y - 2 * dpr));
278
+ }
279
+
280
+ export function withAlpha(color, alpha) {
281
+ const hex = /^#([0-9a-f]{6})([0-9a-f]{2})?$/i.exec(color);
282
+ if (!hex) return color;
283
+ const n = Number.parseInt(hex[1], 16);
284
+ const a = hex[2] ? (Number.parseInt(hex[2], 16) / 255) * alpha : alpha;
285
+ return `rgba(${n >> 16}, ${(n >> 8) & 255}, ${n & 255}, ${a})`;
286
+ }
287
+
288
+ /** An object's bounding box in map pixels, ignoring rotation; `pointRadius` is in map pixels. */
289
+ export function objectBox(object, pointRadius = 6) {
290
+ const width = object.width ?? 0;
291
+ const height = object.height ?? 0;
292
+ if (object.gid) return { x: object.x, y: object.y - height, width, height };
293
+ if (object.polygon || object.polyline) {
294
+ const points = object.polygon ?? object.polyline;
295
+ const xs = points.map((point) => point.x);
296
+ const ys = points.map((point) => point.y);
297
+ const x0 = Math.min(...xs);
298
+ const y0 = Math.min(...ys);
299
+ return { x: object.x + x0, y: object.y + y0, width: Math.max(...xs) - x0, height: Math.max(...ys) - y0 };
300
+ }
301
+ if (object.point || (!width && !height && !object.text)) {
302
+ return { x: object.x - pointRadius, y: object.y - pointRadius * 2.6, width: pointRadius * 2, height: pointRadius * 2.6 };
303
+ }
304
+ return { x: object.x, y: object.y, width, height };
305
+ }
306
+
307
+ /** Whether map point (x, y) is on `object`, its rotation taken into account. */
308
+ export function hitsObject(object, x, y, pointRadius) {
309
+ let px = x;
310
+ let py = y;
311
+ if (object.rotation && !object.point) {
312
+ const angle = (-object.rotation * Math.PI) / 180;
313
+ const rx = x - object.x;
314
+ const ry = y - object.y;
315
+ px = object.x + rx * Math.cos(angle) - ry * Math.sin(angle);
316
+ py = object.y + rx * Math.sin(angle) + ry * Math.cos(angle);
317
+ }
318
+ const box = objectBox(object, pointRadius);
319
+ const slack = Math.min(pointRadius / 2, 3);
320
+ return px >= box.x - slack && px <= box.x + box.width + slack && py >= box.y - slack && py <= box.y + box.height + slack;
321
+ }