@flare-engine/assets 0.2.1 → 0.3.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.
package/dist/index.mjs CHANGED
@@ -1,246 +1,380 @@
1
- // src/texture.ts
1
+ import { Signal } from "@flare-engine/events";
2
+ //#region src/asset-manager.ts
3
+ /**
4
+ * AssetManager — loads, caches, and provides access to game assets.
5
+ *
6
+ * Platform-agnostic: the actual loading is delegated to an `AssetLoader`
7
+ * function injected at construction. This allows Skia-dependent texture
8
+ * loading to live in the React layer while keeping this module testable.
9
+ */
10
+ var AssetManager = class {
11
+ /** Fires on each asset loaded with current progress (0-1). */
12
+ onProgress = new Signal();
13
+ /** Current loading progress 0-1. */
14
+ progress = 0;
15
+ _assets = /* @__PURE__ */ new Map();
16
+ _loader;
17
+ constructor(loader) {
18
+ this._loader = loader;
19
+ }
20
+ /**
21
+ * Load all assets in the manifest.
22
+ * Resolves when all assets are loaded and cached.
23
+ */
24
+ async load(manifest) {
25
+ if (manifest.length === 0) {
26
+ this.progress = 1;
27
+ this.onProgress.emit(1);
28
+ return;
29
+ }
30
+ let loaded = 0;
31
+ const total = manifest.length;
32
+ const promises = manifest.map(async (entry) => {
33
+ const asset = await this._loader(entry);
34
+ this._assets.set(entry.key, asset);
35
+ loaded++;
36
+ this.progress = loaded / total;
37
+ this.onProgress.emit(this.progress);
38
+ });
39
+ await Promise.all(promises);
40
+ }
41
+ /**
42
+ * Load all assets without rejecting on the first failure. Successful assets
43
+ * are cached; failures are collected and returned. Progress still advances to
44
+ * 1 once every entry has settled. Prefer this over {@link load} when a partial
45
+ * asset set is acceptable (e.g. optional/decorative assets).
46
+ */
47
+ async loadManifestSettled(manifest) {
48
+ const loaded = [];
49
+ const failed = [];
50
+ if (manifest.length === 0) {
51
+ this.progress = 1;
52
+ this.onProgress.emit(1);
53
+ return {
54
+ loaded,
55
+ failed
56
+ };
57
+ }
58
+ let settled = 0;
59
+ const total = manifest.length;
60
+ const promises = manifest.map(async (entry) => {
61
+ try {
62
+ const asset = await this._loader(entry);
63
+ this._assets.set(entry.key, asset);
64
+ loaded.push(entry.key);
65
+ } catch (error) {
66
+ failed.push({
67
+ key: entry.key,
68
+ error
69
+ });
70
+ } finally {
71
+ settled++;
72
+ this.progress = settled / total;
73
+ this.onProgress.emit(this.progress);
74
+ }
75
+ });
76
+ await Promise.all(promises);
77
+ return {
78
+ loaded,
79
+ failed
80
+ };
81
+ }
82
+ /** Get a loaded asset by key. Returns undefined if not found. */
83
+ get(key) {
84
+ return this._assets.get(key);
85
+ }
86
+ /** Check if an asset is loaded. */
87
+ has(key) {
88
+ return this._assets.has(key);
89
+ }
90
+ /** Remove an asset from the cache. */
91
+ unload(key) {
92
+ return this._assets.delete(key);
93
+ }
94
+ /** Clear all cached assets. */
95
+ clear() {
96
+ this._assets.clear();
97
+ this.progress = 0;
98
+ }
99
+ };
100
+ //#endregion
101
+ //#region src/decode-image.ts
102
+ /**
103
+ * Decode raw image bytes into a Skia SkImage.
104
+ *
105
+ * Returns null on failure — never throws. Callers are responsible for
106
+ * handling null (e.g. falling back to a placeholder texture).
107
+ */
108
+ function decodeImage(Skia, bytes) {
109
+ const data = Skia.Data.fromBytes(bytes);
110
+ return Skia.Image.MakeImageFromEncoded(data);
111
+ }
112
+ //#endregion
113
+ //#region src/texture.ts
114
+ /** Create a Texture from a Skia SkImage. */
2
115
  function createTexture(key, image) {
3
- return {
4
- key,
5
- image,
6
- width: image.width(),
7
- height: image.height()
8
- };
116
+ return {
117
+ key,
118
+ image,
119
+ width: image.width(),
120
+ height: image.height()
121
+ };
9
122
  }
10
-
11
- // src/sprite-sheet.ts
123
+ //#endregion
124
+ //#region src/loaders.ts
125
+ /**
126
+ * A web `AssetLoader` backed by `fetch`. `texture` entries are decoded into a
127
+ * `Texture`; `binary` yields a `Uint8Array`; `json`/`spritesheet` yield the
128
+ * parsed JSON (feed a spritesheet result to `parseTexturePackerHash` etc.).
129
+ *
130
+ * Fail-fast: a non-OK response or a null decode throws, so `AssetManager.load`
131
+ * rejects. Use `AssetManager.loadManifestSettled` for partial-failure tolerance.
132
+ */
133
+ function createFetchAssetLoader(options) {
134
+ const { decodeImage } = options;
135
+ const fetchFn = options.fetch ?? globalThis.fetch;
136
+ return async (entry) => {
137
+ const response = await fetchFn(entry.path);
138
+ if (!response.ok) throw new Error(`[flare-engine/assets] fetch failed for "${entry.key}" (${entry.path}): ${response.status}`);
139
+ switch (entry.type) {
140
+ case "texture": {
141
+ const bytes = new Uint8Array(await response.arrayBuffer());
142
+ const image = decodeImage(bytes);
143
+ if (!image) throw new Error(`[flare-engine/assets] image decode failed for "${entry.key}" (${entry.path})`);
144
+ return createTexture(entry.key, image);
145
+ }
146
+ case "binary": return new Uint8Array(await response.arrayBuffer());
147
+ default: return response.json();
148
+ }
149
+ };
150
+ }
151
+ /**
152
+ * A native `AssetLoader` backed by an injected `readFile`. `texture` entries are
153
+ * decoded into a `Texture`; `binary` yields the raw `Uint8Array`;
154
+ * `json`/`spritesheet` yield the JSON parsed from UTF-8 bytes.
155
+ *
156
+ * Fail-fast: a null decode (or a rejecting `readFile`) throws.
157
+ */
158
+ function createFileAssetLoader(options) {
159
+ const { readFile, decodeImage } = options;
160
+ return async (entry) => {
161
+ const bytes = await readFile(entry.path);
162
+ switch (entry.type) {
163
+ case "texture": {
164
+ const image = decodeImage(bytes);
165
+ if (!image) throw new Error(`[flare-engine/assets] image decode failed for "${entry.key}" (${entry.path})`);
166
+ return createTexture(entry.key, image);
167
+ }
168
+ case "binary": return bytes;
169
+ default: return JSON.parse(new TextDecoder().decode(bytes));
170
+ }
171
+ };
172
+ }
173
+ //#endregion
174
+ //#region src/sprite-sheet.ts
175
+ /** Create an empty sprite sheet. */
12
176
  function createSpriteSheet() {
13
- return {
14
- frames: [],
15
- frameMap: /* @__PURE__ */ new Map(),
16
- animations: /* @__PURE__ */ new Map()
17
- };
177
+ return {
178
+ frames: [],
179
+ frameMap: /* @__PURE__ */ new Map(),
180
+ animations: /* @__PURE__ */ new Map()
181
+ };
18
182
  }
183
+ /**
184
+ * Warn (dev builds only) when a TexturePacker frame is exported rotated.
185
+ * Rotated frames are not yet remapped, so they render sideways — the frame is
186
+ * named so the artist can re-export it. Full rotation support is post-launch.
187
+ */
188
+ function warnRotatedFrame(name) {
189
+ if (typeof __DEV__ !== "undefined" && __DEV__) console.warn(`[flare-engine/assets] sprite frame "${name}": rotation unsupported — re-export without rotation`);
190
+ }
191
+ /** Parse TexturePacker JSON hash format. */
19
192
  function parseTexturePackerHash(json) {
20
- const data = json;
21
- const sheet = createSpriteSheet();
22
- const entries = Object.entries(data.frames);
23
- for (let i = 0; i < entries.length; i++) {
24
- const entry = entries[i];
25
- if (!entry) continue;
26
- const [name, value] = entry;
27
- const f = value.frame;
28
- sheet.frames.push({ name, x: f.x, y: f.y, w: f.w, h: f.h });
29
- sheet.frameMap.set(name, i);
30
- }
31
- return sheet;
193
+ const data = json;
194
+ const sheet = createSpriteSheet();
195
+ const entries = Object.entries(data.frames);
196
+ for (let i = 0; i < entries.length; i++) {
197
+ const entry = entries[i];
198
+ if (!entry) continue;
199
+ const [name, value] = entry;
200
+ if (value.rotated) warnRotatedFrame(name);
201
+ const f = value.frame;
202
+ sheet.frames.push({
203
+ name,
204
+ x: f.x,
205
+ y: f.y,
206
+ w: f.w,
207
+ h: f.h
208
+ });
209
+ sheet.frameMap.set(name, i);
210
+ }
211
+ return sheet;
32
212
  }
213
+ /** Parse TexturePacker JSON array format. */
33
214
  function parseTexturePackerArray(json) {
34
- const data = json;
35
- const sheet = createSpriteSheet();
36
- for (let i = 0; i < data.frames.length; i++) {
37
- const entry = data.frames[i];
38
- if (!entry) continue;
39
- const f = entry.frame;
40
- sheet.frames.push({
41
- name: entry.filename,
42
- x: f.x,
43
- y: f.y,
44
- w: f.w,
45
- h: f.h
46
- });
47
- sheet.frameMap.set(entry.filename, i);
48
- }
49
- return sheet;
215
+ const data = json;
216
+ const sheet = createSpriteSheet();
217
+ for (let i = 0; i < data.frames.length; i++) {
218
+ const entry = data.frames[i];
219
+ if (!entry) continue;
220
+ if (entry.rotated) warnRotatedFrame(entry.filename);
221
+ const f = entry.frame;
222
+ sheet.frames.push({
223
+ name: entry.filename,
224
+ x: f.x,
225
+ y: f.y,
226
+ w: f.w,
227
+ h: f.h
228
+ });
229
+ sheet.frameMap.set(entry.filename, i);
230
+ }
231
+ return sheet;
50
232
  }
233
+ /** Parse Aseprite JSON export. */
51
234
  function parseAseprite(json) {
52
- const data = json;
53
- const sheet = createSpriteSheet();
54
- const frameEntries = Array.isArray(data.frames) ? data.frames : Object.values(data.frames);
55
- for (let i = 0; i < frameEntries.length; i++) {
56
- const entry = frameEntries[i];
57
- if (!entry) continue;
58
- const f = entry.frame;
59
- sheet.frames.push({
60
- name: entry.filename,
61
- x: f.x,
62
- y: f.y,
63
- w: f.w,
64
- h: f.h
65
- });
66
- sheet.frameMap.set(entry.filename, i);
67
- }
68
- const tags = data.meta?.frameTags;
69
- if (tags) {
70
- for (const tag of tags) {
71
- const indices = [];
72
- if (tag.direction === "reverse") {
73
- for (let i = tag.to; i >= tag.from; i--) {
74
- indices.push(i);
75
- }
76
- } else if (tag.direction === "pingpong") {
77
- for (let i = tag.from; i <= tag.to; i++) {
78
- indices.push(i);
79
- }
80
- for (let i = tag.to - 1; i > tag.from; i--) {
81
- indices.push(i);
82
- }
83
- } else {
84
- for (let i = tag.from; i <= tag.to; i++) {
85
- indices.push(i);
86
- }
87
- }
88
- const firstFrame = frameEntries[tag.from];
89
- const durationMs = firstFrame?.duration ?? 100;
90
- sheet.animations.set(tag.name, {
91
- name: tag.name,
92
- frameIndices: indices,
93
- frameDuration: durationMs / 1e3,
94
- loop: true
95
- });
96
- }
97
- }
98
- return sheet;
235
+ const data = json;
236
+ const sheet = createSpriteSheet();
237
+ const frameEntries = Array.isArray(data.frames) ? data.frames : Object.values(data.frames);
238
+ for (let i = 0; i < frameEntries.length; i++) {
239
+ const entry = frameEntries[i];
240
+ if (!entry) continue;
241
+ const f = entry.frame;
242
+ sheet.frames.push({
243
+ name: entry.filename,
244
+ x: f.x,
245
+ y: f.y,
246
+ w: f.w,
247
+ h: f.h
248
+ });
249
+ sheet.frameMap.set(entry.filename, i);
250
+ }
251
+ const tags = data.meta?.frameTags;
252
+ if (tags) for (const tag of tags) {
253
+ const indices = [];
254
+ if (tag.direction === "reverse") for (let i = tag.to; i >= tag.from; i--) indices.push(i);
255
+ else if (tag.direction === "pingpong") {
256
+ for (let i = tag.from; i <= tag.to; i++) indices.push(i);
257
+ for (let i = tag.to - 1; i > tag.from; i--) indices.push(i);
258
+ } else for (let i = tag.from; i <= tag.to; i++) indices.push(i);
259
+ const durationMs = frameEntries[tag.from]?.duration ?? 100;
260
+ sheet.animations.set(tag.name, {
261
+ name: tag.name,
262
+ frameIndices: indices,
263
+ frameDuration: durationMs / 1e3,
264
+ loop: true
265
+ });
266
+ }
267
+ return sheet;
99
268
  }
269
+ /**
270
+ * Add a custom animation sequence to a sprite sheet.
271
+ */
100
272
  function addAnimation(sheet, name, frameIndices, frameDuration, loop = true) {
101
- sheet.animations.set(name, { name, frameIndices, frameDuration, loop });
273
+ sheet.animations.set(name, {
274
+ name,
275
+ frameIndices,
276
+ frameDuration,
277
+ loop
278
+ });
102
279
  }
280
+ /** Get a frame by name. Returns undefined if not found. */
103
281
  function getFrame(sheet, name) {
104
- const idx = sheet.frameMap.get(name);
105
- if (idx === void 0) return void 0;
106
- return sheet.frames[idx];
282
+ const idx = sheet.frameMap.get(name);
283
+ if (idx === void 0) return void 0;
284
+ return sheet.frames[idx];
107
285
  }
108
-
109
- // src/asset-manager.ts
110
- import { Signal } from "@flare-engine/events";
111
- var AssetManager = class {
112
- /** Fires on each asset loaded with current progress (0-1). */
113
- onProgress = new Signal();
114
- /** Current loading progress 0-1. */
115
- progress = 0;
116
- _assets = /* @__PURE__ */ new Map();
117
- _loader;
118
- constructor(loader) {
119
- this._loader = loader;
120
- }
121
- /**
122
- * Load all assets in the manifest.
123
- * Resolves when all assets are loaded and cached.
124
- */
125
- async load(manifest) {
126
- if (manifest.length === 0) {
127
- this.progress = 1;
128
- this.onProgress.emit(1);
129
- return;
130
- }
131
- let loaded = 0;
132
- const total = manifest.length;
133
- const promises = manifest.map(async (entry) => {
134
- const asset = await this._loader(entry);
135
- this._assets.set(entry.key, asset);
136
- loaded++;
137
- this.progress = loaded / total;
138
- this.onProgress.emit(this.progress);
139
- });
140
- await Promise.all(promises);
141
- }
142
- /** Get a loaded asset by key. Returns undefined if not found. */
143
- get(key) {
144
- return this._assets.get(key);
145
- }
146
- /** Check if an asset is loaded. */
147
- has(key) {
148
- return this._assets.has(key);
149
- }
150
- /** Remove an asset from the cache. */
151
- unload(key) {
152
- return this._assets.delete(key);
153
- }
154
- /** Clear all cached assets. */
155
- clear() {
156
- this._assets.clear();
157
- this.progress = 0;
158
- }
159
- };
160
-
161
- // src/decode-image.ts
162
- function decodeImage(Skia, bytes) {
163
- const data = Skia.Data.fromBytes(bytes);
164
- return Skia.Image.MakeImageFromEncoded(data);
165
- }
166
-
167
- // src/procedural-atlas.ts
286
+ //#endregion
287
+ //#region src/procedural-atlas.ts
288
+ /**
289
+ * Build a flat atlas `SkImage` from a list of colored rectangles.
290
+ *
291
+ * Row-packs frames left-to-right until `maxWidth` is exceeded, then wraps
292
+ * to a new row. Returns both the backing image and a `SpriteSheet` whose
293
+ * frames match the packed positions, so consumers can look up frames by
294
+ * name exactly as with a real `parseTexturePacker*` sheet.
295
+ *
296
+ * Useful for:
297
+ * - bootstrapping gameplay before final art lands (replace with one
298
+ * `parseTexturePackerHash` call once the real atlas arrives),
299
+ * - engine tests / benchmarks that need a valid `SkImage` without
300
+ * shipping any binary asset.
301
+ *
302
+ * **Canonical placeholder-atlas pattern:** a game can ship a full "shape
303
+ * atlas" that draws every entity (enemies, bosses, ships, pickups) as
304
+ * composed primitives onto an offscreen Skia surface, then wraps the result
305
+ * in a `SpriteSheet`.
306
+ * That pattern (declarative shape spec → Skia draw calls → `SpriteSheet`
307
+ * with one named frame per shape) is the recommended way to build a
308
+ * manifest-swappable placeholder atlas: when final art lands, swap the
309
+ * shape draw-calls for `parseTexturePackerHash(jsonText)` with no other
310
+ * code changes.
311
+ */
168
312
  function createProceduralAtlas(Skia, frames, options = {}) {
169
- const maxWidth = options.maxWidth ?? 1024;
170
- const padding = options.padding ?? 0;
171
- const positions = layoutRows(frames, maxWidth, padding);
172
- const surface = Skia.Surface.Make(positions.width, positions.height);
173
- if (surface === null) {
174
- throw new Error(`Skia.Surface.Make returned null for ${positions.width}x${positions.height}`);
175
- }
176
- const canvas = surface.getCanvas();
177
- const paint = Skia.Paint();
178
- const color = new Float32Array(4);
179
- const sheet = createSpriteSheet();
180
- for (let i = 0; i < frames.length; i++) {
181
- const spec = frames[i];
182
- const pos = positions.rects[i];
183
- if (spec === void 0 || pos === void 0) continue;
184
- writeArgb(color, spec.color);
185
- paint.setColor(color);
186
- canvas.drawRect(Skia.XYWHRect(pos.x, pos.y, spec.w, spec.h), paint);
187
- const frame = {
188
- name: spec.name,
189
- x: pos.x,
190
- y: pos.y,
191
- w: spec.w,
192
- h: spec.h
193
- };
194
- sheet.frames.push(frame);
195
- sheet.frameMap.set(spec.name, i);
196
- }
197
- return {
198
- image: surface.makeImageSnapshot(),
199
- sheet,
200
- width: positions.width,
201
- height: positions.height
202
- };
313
+ const positions = layoutRows(frames, options.maxWidth ?? 1024, options.padding ?? 0);
314
+ const surface = Skia.Surface.Make(positions.width, positions.height);
315
+ if (surface === null) throw new Error(`Skia.Surface.Make returned null for ${positions.width}x${positions.height}`);
316
+ const canvas = surface.getCanvas();
317
+ const paint = Skia.Paint();
318
+ const color = /* @__PURE__ */ new Float32Array(4);
319
+ const sheet = createSpriteSheet();
320
+ for (let i = 0; i < frames.length; i++) {
321
+ const spec = frames[i];
322
+ const pos = positions.rects[i];
323
+ if (spec === void 0 || pos === void 0) continue;
324
+ writeArgb(color, spec.color);
325
+ paint.setColor(color);
326
+ canvas.drawRect(Skia.XYWHRect(pos.x, pos.y, spec.w, spec.h), paint);
327
+ const frame = {
328
+ name: spec.name,
329
+ x: pos.x,
330
+ y: pos.y,
331
+ w: spec.w,
332
+ h: spec.h
333
+ };
334
+ sheet.frames.push(frame);
335
+ sheet.frameMap.set(spec.name, i);
336
+ }
337
+ return {
338
+ image: surface.makeImageSnapshot(),
339
+ sheet,
340
+ width: positions.width,
341
+ height: positions.height
342
+ };
203
343
  }
204
344
  function layoutRows(frames, maxWidth, padding) {
205
- const rects = [];
206
- let x = 0;
207
- let y = 0;
208
- let rowHeight = 0;
209
- let atlasWidth = 0;
210
- for (const spec of frames) {
211
- if (x > 0 && x + spec.w > maxWidth) {
212
- y += rowHeight + padding;
213
- x = 0;
214
- rowHeight = 0;
215
- }
216
- rects.push({ x, y });
217
- x += spec.w + padding;
218
- if (spec.h > rowHeight) rowHeight = spec.h;
219
- if (x - padding > atlasWidth) atlasWidth = x - padding;
220
- }
221
- const atlasHeight = y + rowHeight;
222
- return {
223
- rects,
224
- width: atlasWidth > 0 ? atlasWidth : 1,
225
- height: atlasHeight > 0 ? atlasHeight : 1
226
- };
345
+ const rects = [];
346
+ let x = 0;
347
+ let y = 0;
348
+ let rowHeight = 0;
349
+ let atlasWidth = 0;
350
+ for (const spec of frames) {
351
+ if (x > 0 && x + spec.w > maxWidth) {
352
+ y += rowHeight + padding;
353
+ x = 0;
354
+ rowHeight = 0;
355
+ }
356
+ rects.push({
357
+ x,
358
+ y
359
+ });
360
+ x += spec.w + padding;
361
+ if (spec.h > rowHeight) rowHeight = spec.h;
362
+ if (x - padding > atlasWidth) atlasWidth = x - padding;
363
+ }
364
+ const atlasHeight = y + rowHeight;
365
+ return {
366
+ rects,
367
+ width: atlasWidth > 0 ? atlasWidth : 1,
368
+ height: atlasHeight > 0 ? atlasHeight : 1
369
+ };
227
370
  }
228
371
  function writeArgb(out, argb) {
229
- out[0] = (argb >>> 16 & 255) / 255;
230
- out[1] = (argb >>> 8 & 255) / 255;
231
- out[2] = (argb & 255) / 255;
232
- out[3] = (argb >>> 24 & 255) / 255;
372
+ out[0] = (argb >>> 16 & 255) / 255;
373
+ out[1] = (argb >>> 8 & 255) / 255;
374
+ out[2] = (argb & 255) / 255;
375
+ out[3] = (argb >>> 24 & 255) / 255;
233
376
  }
234
- export {
235
- AssetManager,
236
- addAnimation,
237
- createProceduralAtlas,
238
- createSpriteSheet,
239
- createTexture,
240
- decodeImage,
241
- getFrame,
242
- parseAseprite,
243
- parseTexturePackerArray,
244
- parseTexturePackerHash
245
- };
377
+ //#endregion
378
+ export { AssetManager, addAnimation, createFetchAssetLoader, createFileAssetLoader, createProceduralAtlas, createSpriteSheet, createTexture, decodeImage, getFrame, parseAseprite, parseTexturePackerArray, parseTexturePackerHash };
379
+
246
380
  //# sourceMappingURL=index.mjs.map