packages/core/src/features/sprites/loader.ts
This is the source snapshot used to build these API details. View this revision on GitHub.
1 import { defineSpriteAnimation, makeFrame, type SpriteFrame, type SpriteFrameData, type SpriteSheetFormat } from './model.js';
2 import type { PibblAnimationDefinition } from '../../lib/animation/types.js';
3 /** Shared decoded atlas and immutable frames/clips. Dispose after all consumers unmount. See {@link SpriteFrame}. */
4 export interface SpriteSheet {
5 /** Frames indexed by atlas name or numeric grid index. */ readonly frames: Readonly<Record<string | number, SpriteFrame>>;
6 /** Named, seekable animation definitions from the atlas. */ readonly animations: Readonly<Record<string, PibblAnimationDefinition<SpriteFrame>>>;
7 /** Release decoded images; unmount every consumer before calling. */ readonly dispose: () => void;
8 }
9 /** Dimensions of a regular grid, in image pixels. See {@link SpriteFrame}. */
10 export interface SpriteGrid { /** Positive cell width in pixels. */ readonly frameWidth: number; /** Positive cell height in pixels. */ readonly frameHeight: number; /** Outer border width in pixels; defaults to zero. */ readonly margin?: number; /** Gap between cells in pixels; defaults to zero. */ readonly spacing?: number }
11 /** Load a grid image or metadata through an explicitly supplied import adapter. See {@link SpriteFrame}.
12 * @param url - Grid image URL or atlas metadata URL.
13 * @param options - Grid dimensions or an explicit metadata format adapter.
14 * @returns A decoded sprite sheet with explicit disposal ownership.
15 */
16 export async function loadSpriteSheet(
17 url: string,
18 options: { readonly grid: SpriteGrid } | { readonly format: SpriteSheetFormat },
19 ): Promise<SpriteSheet> {
20 const owner = { disposed: false };
21 const images: HTMLImageElement[] = [];
22 const dispose = () => { if (owner.disposed) return; owner.disposed = true; for (const image of images) image.removeAttribute('src'); };
23 const load = async (source: string) => {
24 const image = new globalThis.Image(); images.push(image); image.src = source; await image.decode(); return image;
25 };
26 try {
27 let specs: readonly SpriteFrameData[];
28 let clips: Readonly<Record<string, readonly { frame: string; duration: number }[]>> = {};
29 if ('grid' in options) {
30 const { frameWidth: w, frameHeight: h, margin = 0, spacing = 0 } = options.grid;
31 if (
32 !(
33 Number.isInteger(w) &&
34 Number.isInteger(h) &&
35 Number.isInteger(margin) &&
36 Number.isInteger(spacing)
37 ) ||
38 w <= 0 ||
39 h <= 0 ||
40 margin < 0 ||
41 spacing < 0
42 )
43 throw new RangeError('Invalid sprite grid dimensions.');
44 const image = await load(url);
45 const frames: SpriteFrameData[] = [];
46 for (let y = margin; y + h <= image.naturalHeight - margin; y += h + spacing)
47 for (let x = margin; x + w <= image.naturalWidth - margin; x += w + spacing)
48 frames.push({ name: String(frames.length), rect: { x, y, width: w, height: h } });
49 if (!frames.length) throw new RangeError('Sprite grid contains no complete frames.');
50 specs = frames;
51 } else {
52 const response = await fetch(url); if (!response.ok) throw new Error(`Sprite metadata failed: ${response.status}`);
53 const data = options.format.parse(await response.json());
54 for (const path of data.images) await load(new URL(path, new URL(url, document.baseURI)).href);
55 specs = data.frames; clips = data.animations ?? {};
56 }
57 const frames: Record<string, SpriteFrame> = Object.create(null);
58 for (const spec of specs) {
59 const image = images[spec.page ?? 0], r = spec.rect;
60 if (
61 !image ||
62 !(
63 Number.isFinite(r.x) &&
64 Number.isFinite(r.y) &&
65 Number.isFinite(r.width) &&
66 Number.isFinite(r.height)
67 ) ||
68 r.x < 0 ||
69 r.y < 0 ||
70 r.width <= 0 ||
71 r.height <= 0 ||
72 r.x + r.width > image.naturalWidth ||
73 r.y + r.height > image.naturalHeight
74 )
75 throw new RangeError(`Invalid sprite rectangle: ${spec.name}`);
76 if (frames[spec.name]) throw new Error(`Duplicate sprite frame: ${spec.name}`);
77 const width = spec.sourceSize?.width ?? (spec.rotated ? r.height : r.width);
78 const height = spec.sourceSize?.height ?? (spec.rotated ? r.width : r.height);
79 const trim = { x: spec.trim?.x ?? 0, y: spec.trim?.y ?? 0 };
80 if (
81 !(
82 Number.isFinite(width) &&
83 Number.isFinite(height) &&
84 Number.isFinite(trim.x) &&
85 Number.isFinite(trim.y)
86 ) ||
87 width <= 0 ||
88 height <= 0 ||
89 trim.x < 0 ||
90 trim.y < 0 ||
91 trim.x + (spec.rotated ? r.height : r.width) > width ||
92 trim.y + (spec.rotated ? r.width : r.height) > height
93 )
94 throw new RangeError(`Invalid sprite logical bounds: ${spec.name}`);
95 frames[spec.name] = makeFrame({ ...spec, rect: Object.freeze({ ...r }), sourceSize: Object.freeze({ width, height }), trim: Object.freeze(trim), image, owner });
96 }
97 const animations: Record<string, PibblAnimationDefinition<SpriteFrame>> = Object.create(null);
98 for (const [name, entries] of Object.entries(clips)) animations[name] = defineSpriteAnimation({ frames: entries.map(entry => {
99 if (!frames[entry.frame]) throw new Error(`Unknown sprite frame: ${entry.frame}`);
100 return { frame: frames[entry.frame], duration: entry.duration };
101 }) });
102 return Object.freeze({ frames: Object.freeze(frames), animations: Object.freeze(animations), dispose });
103 } catch (error) { dispose(); throw error; }
104 }
105
Documentation version
Section titled “Documentation version”Documentation built with @pibbl/core 0.0.2, revision a1dcf8e. ALPHA — NOT FOR PRODUCTION USE.