@flare-engine/assets 0.2.0 → 0.3.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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/texture.ts","../src/sprite-sheet.ts","../src/asset-manager.ts","../src/decode-image.ts","../src/procedural-atlas.ts"],"sourcesContent":["/** Minimal interface for the Skia SkImage we wrap. */\nexport interface SkImageLike {\n width(): number;\n height(): number;\n readPixels(): Float32Array | Uint8Array | null;\n /**\n * Optional — present on GPU-backed SkImages returned by RN-Skia's\n * MakeOffscreen surfaces. Copies the texture into a CPU-raster image so it\n * can be safely sampled from a different GrDirectContext (e.g. the on-screen\n * Canvas). Must be called before the image crosses a context boundary.\n */\n makeNonTextureImage?(): SkImageLike;\n}\n\n/** A loaded texture wrapping a Skia SkImage. */\nexport interface Texture {\n /** Unique key for this texture in the asset manager. */\n readonly key: string;\n /** The underlying Skia SkImage. */\n readonly image: SkImageLike;\n /** Width in pixels. */\n readonly width: number;\n /** Height in pixels. */\n readonly height: number;\n}\n\n/** Create a Texture from a Skia SkImage. */\nexport function createTexture(key: string, image: SkImageLike): Texture {\n return {\n key,\n image,\n width: image.width(),\n height: image.height(),\n };\n}\n","/** A single frame rectangle in a sprite sheet. */\nexport interface SpriteFrame {\n /** Name/key of the frame. */\n name: string;\n /** X offset in the source texture (pixels). */\n x: number;\n /** Y offset in the source texture (pixels). */\n y: number;\n /** Width of the frame (pixels). */\n w: number;\n /** Height of the frame (pixels). */\n h: number;\n}\n\n/** A named animation sequence within a sprite sheet. */\nexport interface AnimationSequence {\n /** Sequence name (e.g. \"walk\", \"idle\"). */\n name: string;\n /** Indices into the SpriteSheet.frames array. */\n frameIndices: number[];\n /** Duration per frame in seconds. */\n frameDuration: number;\n /** Whether to loop the sequence. */\n loop: boolean;\n}\n\n/** Parsed sprite sheet data — pure data, no Skia dependency. */\nexport interface SpriteSheet {\n /** Ordered array of all frames. */\n frames: SpriteFrame[];\n /** Map from frame name to index in frames[]. */\n frameMap: Map<string, number>;\n /** Named animation sequences. */\n animations: Map<string, AnimationSequence>;\n}\n\n/** Create an empty sprite sheet. */\nexport function createSpriteSheet(): SpriteSheet {\n return {\n frames: [],\n frameMap: new Map(),\n animations: new Map(),\n };\n}\n\n// ----- TexturePacker JSON (hash format) -----\n\ninterface TPHashFrame {\n frame: { x: number; y: number; w: number; h: number };\n}\n\ninterface TPHashJSON {\n frames: Record<string, TPHashFrame>;\n}\n\n/** Parse TexturePacker JSON hash format. */\nexport function parseTexturePackerHash(json: unknown): SpriteSheet {\n const data = json as TPHashJSON;\n const sheet = createSpriteSheet();\n const entries = Object.entries(data.frames);\n for (let i = 0; i < entries.length; i++) {\n const entry = entries[i];\n if (!entry) continue;\n const [name, value] = entry;\n const f = value.frame;\n sheet.frames.push({ name, x: f.x, y: f.y, w: f.w, h: f.h });\n sheet.frameMap.set(name, i);\n }\n return sheet;\n}\n\n// ----- TexturePacker JSON (array format) -----\n\ninterface TPArrayFrame {\n filename: string;\n frame: { x: number; y: number; w: number; h: number };\n}\n\ninterface TPArrayJSON {\n frames: TPArrayFrame[];\n}\n\n/** Parse TexturePacker JSON array format. */\nexport function parseTexturePackerArray(json: unknown): SpriteSheet {\n const data = json as TPArrayJSON;\n const sheet = createSpriteSheet();\n for (let i = 0; i < data.frames.length; i++) {\n const entry = data.frames[i];\n if (!entry) continue;\n const f = entry.frame;\n sheet.frames.push({\n name: entry.filename,\n x: f.x,\n y: f.y,\n w: f.w,\n h: f.h,\n });\n sheet.frameMap.set(entry.filename, i);\n }\n return sheet;\n}\n\n// ----- Aseprite JSON -----\n\ninterface AsepriteFrame {\n filename: string;\n frame: { x: number; y: number; w: number; h: number };\n duration: number; // ms\n}\n\ninterface AsepriteTag {\n name: string;\n from: number;\n to: number;\n direction: string;\n}\n\ninterface AsepriteJSON {\n frames: AsepriteFrame[] | Record<string, AsepriteFrame>;\n meta?: {\n frameTags?: AsepriteTag[];\n };\n}\n\n/** Parse Aseprite JSON export. */\nexport function parseAseprite(json: unknown): SpriteSheet {\n const data = json as AsepriteJSON;\n const sheet = createSpriteSheet();\n\n // Aseprite can export frames as array or object\n const frameEntries: AsepriteFrame[] = Array.isArray(data.frames)\n ? data.frames\n : Object.values(data.frames);\n\n for (let i = 0; i < frameEntries.length; i++) {\n const entry = frameEntries[i];\n if (!entry) continue;\n const f = entry.frame;\n sheet.frames.push({\n name: entry.filename,\n x: f.x,\n y: f.y,\n w: f.w,\n h: f.h,\n });\n sheet.frameMap.set(entry.filename, i);\n }\n\n // Parse frame tags as animation sequences\n const tags = data.meta?.frameTags;\n if (tags) {\n for (const tag of tags) {\n const indices: number[] = [];\n if (tag.direction === 'reverse') {\n for (let i = tag.to; i >= tag.from; i--) {\n indices.push(i);\n }\n } else if (tag.direction === 'pingpong') {\n for (let i = tag.from; i <= tag.to; i++) {\n indices.push(i);\n }\n for (let i = tag.to - 1; i > tag.from; i--) {\n indices.push(i);\n }\n } else {\n // \"forward\" or default\n for (let i = tag.from; i <= tag.to; i++) {\n indices.push(i);\n }\n }\n\n // Use the first frame's duration as the uniform frame duration\n const firstFrame = frameEntries[tag.from];\n const durationMs = firstFrame?.duration ?? 100;\n\n sheet.animations.set(tag.name, {\n name: tag.name,\n frameIndices: indices,\n frameDuration: durationMs / 1000,\n loop: true,\n });\n }\n }\n\n return sheet;\n}\n\n/**\n * Add a custom animation sequence to a sprite sheet.\n */\nexport function addAnimation(\n sheet: SpriteSheet,\n name: string,\n frameIndices: number[],\n frameDuration: number,\n loop = true,\n): void {\n sheet.animations.set(name, { name, frameIndices, frameDuration, loop });\n}\n\n/** Get a frame by name. Returns undefined if not found. */\nexport function getFrame(sheet: SpriteSheet, name: string): SpriteFrame | undefined {\n const idx = sheet.frameMap.get(name);\n if (idx === undefined) return undefined;\n return sheet.frames[idx];\n}\n","import { Signal } from '@flare-engine/events';\nimport type { SpriteSheet } from './sprite-sheet.js';\nimport type { Texture } from './texture.js';\n\n/** Types of assets the manager can store. */\nexport type AssetType = 'texture' | 'spritesheet' | 'json' | 'binary';\n\n/** A single entry in an asset manifest. */\nexport interface ManifestEntry {\n /** Unique key to retrieve this asset. */\n key: string;\n /** Asset type. */\n type: AssetType;\n /** Path or URI to the asset. */\n path: string;\n}\n\n/** A load function provided by the platform to actually fetch+decode assets. */\nexport type AssetLoader = (entry: ManifestEntry) => Promise<Texture | SpriteSheet | unknown>;\n\n/**\n * AssetManager — loads, caches, and provides access to game assets.\n *\n * Platform-agnostic: the actual loading is delegated to an `AssetLoader`\n * function injected at construction. This allows Skia-dependent texture\n * loading to live in the React layer while keeping this module testable.\n */\nexport class AssetManager {\n /** Fires on each asset loaded with current progress (0-1). */\n readonly onProgress = new Signal<number>();\n\n /** Current loading progress 0-1. */\n progress = 0;\n\n private _assets = new Map<string, unknown>();\n private _loader: AssetLoader;\n\n constructor(loader: AssetLoader) {\n this._loader = loader;\n }\n\n /**\n * Load all assets in the manifest.\n * Resolves when all assets are loaded and cached.\n */\n async load(manifest: ManifestEntry[]): Promise<void> {\n if (manifest.length === 0) {\n this.progress = 1;\n this.onProgress.emit(1);\n return;\n }\n\n let loaded = 0;\n const total = manifest.length;\n\n const promises = manifest.map(async (entry) => {\n const asset = await this._loader(entry);\n this._assets.set(entry.key, asset);\n loaded++;\n this.progress = loaded / total;\n this.onProgress.emit(this.progress);\n });\n\n await Promise.all(promises);\n }\n\n /** Get a loaded asset by key. Returns undefined if not found. */\n get<T = unknown>(key: string): T | undefined {\n return this._assets.get(key) as T | undefined;\n }\n\n /** Check if an asset is loaded. */\n has(key: string): boolean {\n return this._assets.has(key);\n }\n\n /** Remove an asset from the cache. */\n unload(key: string): boolean {\n return this._assets.delete(key);\n }\n\n /** Clear all cached assets. */\n clear(): void {\n this._assets.clear();\n this.progress = 0;\n }\n}\n","import type { SkImageLike } from './texture.js';\n\n/** Opaque handle for a Skia SkData object. */\nexport interface SkDataLike {\n readonly __skData: unique symbol;\n}\n\n/**\n * Narrow view of the Skia module — only the factories this helper needs.\n * Injected by the caller so @flare-engine/assets stays runtime-agnostic.\n */\nexport interface SkiaImageDecodeModuleLike {\n Data: {\n fromBytes(bytes: Uint8Array): SkDataLike;\n };\n Image: {\n MakeImageFromEncoded(data: SkDataLike): SkImageLike | null;\n };\n}\n\n/**\n * Decode raw image bytes into a Skia SkImage.\n *\n * Returns null on failure — never throws. Callers are responsible for\n * handling null (e.g. falling back to a placeholder texture).\n */\nexport function decodeImage(\n Skia: SkiaImageDecodeModuleLike,\n bytes: Uint8Array,\n): SkImageLike | null {\n const data = Skia.Data.fromBytes(bytes);\n return Skia.Image.MakeImageFromEncoded(data);\n}\n","import { type SpriteFrame, type SpriteSheet, createSpriteSheet } from './sprite-sheet.js';\nimport type { SkImageLike } from './texture.js';\n\n/** One entry in a procedural atlas — a named colored rectangle. */\nexport interface ProceduralFrameSpec {\n /** Frame name (used as the SpriteFrame name for lookup). */\n name: string;\n /** Width in pixels. */\n w: number;\n /** Height in pixels. */\n h: number;\n /** Color as ARGB int (0xAARRGGBB). */\n color: number;\n}\n\n/** Options controlling atlas layout. */\nexport interface ProceduralAtlasOptions {\n /** Max atlas width before wrapping to a new row. Default 1024. */\n maxWidth?: number;\n /** Gap between frames in pixels. Default 0. */\n padding?: number;\n}\n\n/** Result of a procedural atlas build. */\nexport interface ProceduralAtlas {\n /** Backing Skia image with all rects drawn. */\n image: SkImageLike;\n /** SpriteSheet whose frames describe the rect positions. */\n sheet: SpriteSheet;\n /** Total atlas width in pixels. */\n width: number;\n /** Total atlas height in pixels. */\n height: number;\n}\n\n/** Opaque Skia color value — a Float32Array of length 4 (r, g, b, a in [0,1]). */\ntype SkColorLike = Float32Array;\n\n/** Narrow paint interface — only the setter we use. */\nexport interface SkPaintLike {\n setColor(color: SkColorLike): void;\n}\n\n/** Narrow rect interface — a rect value object passed to drawRect. */\nexport interface SkRectLike {\n readonly x: number;\n readonly y: number;\n readonly width: number;\n readonly height: number;\n}\n\n/** Narrow canvas interface — only the method we use. */\nexport interface SkCanvasLike {\n drawRect(rect: SkRectLike, paint: SkPaintLike): void;\n}\n\n/** Narrow surface interface — getCanvas + snapshot. */\nexport interface SkSurfaceLike {\n getCanvas(): SkCanvasLike;\n makeImageSnapshot(): SkImageLike;\n}\n\n/**\n * Narrow view of the Skia module — only the factories this helper needs.\n * Declared locally so unit tests can supply a plain mock without pulling\n * in the full `@shopify/react-native-skia` surface.\n */\nexport interface SkiaAtlasModuleLike {\n Surface: { Make(width: number, height: number): SkSurfaceLike | null };\n Paint(): SkPaintLike;\n XYWHRect(x: number, y: number, w: number, h: number): SkRectLike;\n}\n\n/**\n * Build a flat atlas `SkImage` from a list of colored rectangles.\n *\n * Row-packs frames left-to-right until `maxWidth` is exceeded, then wraps\n * to a new row. Returns both the backing image and a `SpriteSheet` whose\n * frames match the packed positions, so consumers can look up frames by\n * name exactly as with a real `parseTexturePacker*` sheet.\n *\n * Useful for:\n * - bootstrapping gameplay before final art lands (replace with one\n * `parseTexturePackerHash` call once the real atlas arrives),\n * - engine tests / benchmarks that need a valid `SkImage` without\n * shipping any binary asset.\n *\n * **Canonical placeholder-atlas example (Phase 11.14):** Pan Tvardowski\n * (github.com/grzott/Pan-Tvardowski) ships a full \"shape atlas\" that draws\n * every enemy / miniboss / boss / ship / pickup as composed primitives onto\n * an offscreen Skia surface, then wraps the result in a `SpriteSheet` — see\n * `src/shape-atlas.ts` in that repo.\n * That pattern (declarative `ShapeSpec` → `Skia` draw calls → `SpriteSheet`\n * with one named frame per shape) is the recommended way to build a\n * manifest-swappable placeholder atlas: when final art lands, drop the\n * shape draw-calls for `parseTexturePackerHash(jsonText)` with no other\n * code changes.\n */\nexport function createProceduralAtlas(\n Skia: SkiaAtlasModuleLike,\n frames: readonly ProceduralFrameSpec[],\n options: ProceduralAtlasOptions = {},\n): ProceduralAtlas {\n const maxWidth = options.maxWidth ?? 1024;\n const padding = options.padding ?? 0;\n\n const positions = layoutRows(frames, maxWidth, padding);\n const surface = Skia.Surface.Make(positions.width, positions.height);\n if (surface === null) {\n throw new Error(`Skia.Surface.Make returned null for ${positions.width}x${positions.height}`);\n }\n\n const canvas = surface.getCanvas();\n const paint = Skia.Paint();\n const color: SkColorLike = new Float32Array(4);\n\n const sheet = createSpriteSheet();\n\n for (let i = 0; i < frames.length; i++) {\n const spec = frames[i];\n const pos = positions.rects[i];\n if (spec === undefined || pos === undefined) continue;\n\n writeArgb(color, spec.color);\n paint.setColor(color);\n canvas.drawRect(Skia.XYWHRect(pos.x, pos.y, spec.w, spec.h), paint);\n\n const frame: SpriteFrame = {\n name: spec.name,\n x: pos.x,\n y: pos.y,\n w: spec.w,\n h: spec.h,\n };\n sheet.frames.push(frame);\n sheet.frameMap.set(spec.name, i);\n }\n\n return {\n image: surface.makeImageSnapshot(),\n sheet,\n width: positions.width,\n height: positions.height,\n };\n}\n\ninterface PackedPosition {\n x: number;\n y: number;\n}\n\ninterface PackedLayout {\n rects: PackedPosition[];\n width: number;\n height: number;\n}\n\nfunction layoutRows(\n frames: readonly ProceduralFrameSpec[],\n maxWidth: number,\n padding: number,\n): PackedLayout {\n const rects: PackedPosition[] = [];\n let x = 0;\n let y = 0;\n let rowHeight = 0;\n let atlasWidth = 0;\n\n for (const spec of frames) {\n if (x > 0 && x + spec.w > maxWidth) {\n y += rowHeight + padding;\n x = 0;\n rowHeight = 0;\n }\n rects.push({ x, y });\n x += spec.w + padding;\n if (spec.h > rowHeight) rowHeight = spec.h;\n if (x - padding > atlasWidth) atlasWidth = x - padding;\n }\n\n const atlasHeight = y + rowHeight;\n return {\n rects,\n width: atlasWidth > 0 ? atlasWidth : 1,\n height: atlasHeight > 0 ? atlasHeight : 1,\n };\n}\n\nfunction writeArgb(out: SkColorLike, argb: number): void {\n out[0] = ((argb >>> 16) & 0xff) / 255;\n out[1] = ((argb >>> 8) & 0xff) / 255;\n out[2] = (argb & 0xff) / 255;\n out[3] = ((argb >>> 24) & 0xff) / 255;\n}\n"],"mappings":";AA2BO,SAAS,cAAc,KAAa,OAA6B;AACt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UAAU;AAAA,EACpB;AACF;AAaA,SAAS,WACP,QACA,UACA,SACc;AACd,QAAM,QAA0B,CAAC;AACjC,MAAI,IAAI;AACR,MAAI,IAAI;AACR,MAAI,YAAY;AAChB,MAAI,aAAa;AAEjB,aAAW,QAAQ,QAAQ;AACzB,QAAI,IAAI,KAAK,IAAI,KAAK,IAAI,UAAU;AAClC,WAAK,YAAY;AACjB,UAAI;AACJ,kBAAY;AAAA,IACd;AACA,UAAM,KAAK,EAAE,GAAG,EAAE,CAAC;AACnB,SAAK,KAAK,IAAI;AACd,QAAI,KAAK,IAAI,UAAW,aAAY,KAAK;AACzC,QAAI,IAAI,UAAU,WAAY,cAAa,IAAI;AAAA,EACjD;AAEA,QAAM,cAAc,IAAI;AACxB,SAAO;AAAA,IACL;AAAA,IACA,OAAO,aAAa,IAAI,aAAa;AAAA,IACrC,QAAQ,cAAc,IAAI,cAAc;AAAA,EAC1C;AACF;AAEA,SAAS,UAAU,KAAkB,MAAoB;AACvD,MAAI,CAAC,KAAM,SAAS,KAAM,OAAQ;AAClC,MAAI,CAAC,KAAM,SAAS,IAAK,OAAQ;AACjC,MAAI,CAAC,KAAK,OAAO,OAAQ;AACzB,MAAI,CAAC,KAAM,SAAS,KAAM,OAAQ;AACpC;","names":[]}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../src/asset-manager.ts","../src/decode-image.ts","../src/texture.ts","../src/loaders.ts","../src/sprite-sheet.ts","../src/procedural-atlas.ts"],"sourcesContent":["import { Signal } from '@flare-engine/events';\nimport type { SpriteSheet } from './sprite-sheet.js';\nimport type { Texture } from './texture.js';\n\n/** Types of assets the manager can store. */\nexport type AssetType = 'texture' | 'spritesheet' | 'json' | 'binary';\n\n/** A single entry in an asset manifest. */\nexport interface ManifestEntry {\n /** Unique key to retrieve this asset. */\n key: string;\n /** Asset type. */\n type: AssetType;\n /** Path or URI to the asset. */\n path: string;\n}\n\n/** A load function provided by the platform to actually fetch+decode assets. */\nexport type AssetLoader = (entry: ManifestEntry) => Promise<Texture | SpriteSheet | unknown>;\n\n/** A single entry that failed during {@link AssetManager.loadManifestSettled}. */\nexport interface ManifestLoadFailure {\n /** Key of the manifest entry that failed. */\n key: string;\n /** The value thrown by the loader (an `Error` or otherwise). */\n error: unknown;\n}\n\n/** Partial-failure summary returned by {@link AssetManager.loadManifestSettled}. */\nexport interface ManifestLoadResult {\n /** Keys of entries that loaded and were cached. */\n loaded: string[];\n /** Entries that threw, with the captured error. */\n failed: ManifestLoadFailure[];\n}\n\n/**\n * AssetManager — loads, caches, and provides access to game assets.\n *\n * Platform-agnostic: the actual loading is delegated to an `AssetLoader`\n * function injected at construction. This allows Skia-dependent texture\n * loading to live in the React layer while keeping this module testable.\n */\nexport class AssetManager {\n /** Fires on each asset loaded with current progress (0-1). */\n readonly onProgress = new Signal<number>();\n\n /** Current loading progress 0-1. */\n progress = 0;\n\n private _assets = new Map<string, unknown>();\n private _loader: AssetLoader;\n\n constructor(loader: AssetLoader) {\n this._loader = loader;\n }\n\n /**\n * Load all assets in the manifest.\n * Resolves when all assets are loaded and cached.\n */\n async load(manifest: ManifestEntry[]): Promise<void> {\n if (manifest.length === 0) {\n this.progress = 1;\n this.onProgress.emit(1);\n return;\n }\n\n let loaded = 0;\n const total = manifest.length;\n\n const promises = manifest.map(async (entry) => {\n const asset = await this._loader(entry);\n this._assets.set(entry.key, asset);\n loaded++;\n this.progress = loaded / total;\n this.onProgress.emit(this.progress);\n });\n\n await Promise.all(promises);\n }\n\n /**\n * Load all assets without rejecting on the first failure. Successful assets\n * are cached; failures are collected and returned. Progress still advances to\n * 1 once every entry has settled. Prefer this over {@link load} when a partial\n * asset set is acceptable (e.g. optional/decorative assets).\n */\n async loadManifestSettled(manifest: ManifestEntry[]): Promise<ManifestLoadResult> {\n const loaded: string[] = [];\n const failed: ManifestLoadFailure[] = [];\n\n if (manifest.length === 0) {\n this.progress = 1;\n this.onProgress.emit(1);\n return { loaded, failed };\n }\n\n let settled = 0;\n const total = manifest.length;\n\n const promises = manifest.map(async (entry) => {\n try {\n const asset = await this._loader(entry);\n this._assets.set(entry.key, asset);\n loaded.push(entry.key);\n } catch (error) {\n failed.push({ key: entry.key, error });\n } finally {\n settled++;\n this.progress = settled / total;\n this.onProgress.emit(this.progress);\n }\n });\n\n await Promise.all(promises);\n return { loaded, failed };\n }\n\n /** Get a loaded asset by key. Returns undefined if not found. */\n get<T = unknown>(key: string): T | undefined {\n return this._assets.get(key) as T | undefined;\n }\n\n /** Check if an asset is loaded. */\n has(key: string): boolean {\n return this._assets.has(key);\n }\n\n /** Remove an asset from the cache. */\n unload(key: string): boolean {\n return this._assets.delete(key);\n }\n\n /** Clear all cached assets. */\n clear(): void {\n this._assets.clear();\n this.progress = 0;\n }\n}\n","import type { SkImageLike } from './texture.js';\n\n/** Opaque handle for a Skia SkData object. */\nexport interface SkDataLike {\n readonly __skData: unique symbol;\n}\n\n/**\n * Narrow view of the Skia module — only the factories this helper needs.\n * Injected by the caller so @flare-engine/assets stays runtime-agnostic.\n */\nexport interface SkiaImageDecodeModuleLike {\n Data: {\n fromBytes(bytes: Uint8Array): SkDataLike;\n };\n Image: {\n MakeImageFromEncoded(data: SkDataLike): SkImageLike | null;\n };\n}\n\n/**\n * Decode raw image bytes into a Skia SkImage.\n *\n * Returns null on failure — never throws. Callers are responsible for\n * handling null (e.g. falling back to a placeholder texture).\n */\nexport function decodeImage(\n Skia: SkiaImageDecodeModuleLike,\n bytes: Uint8Array,\n): SkImageLike | null {\n const data = Skia.Data.fromBytes(bytes);\n return Skia.Image.MakeImageFromEncoded(data);\n}\n","/** Minimal interface for the Skia SkImage we wrap. */\nexport interface SkImageLike {\n width(): number;\n height(): number;\n readPixels(): Float32Array | Uint8Array | null;\n /**\n * Optional — present on GPU-backed SkImages returned by RN-Skia's\n * MakeOffscreen surfaces. Copies the texture into a CPU-raster image so it\n * can be safely sampled from a different GrDirectContext (e.g. the on-screen\n * Canvas). Must be called before the image crosses a context boundary.\n */\n makeNonTextureImage?(): SkImageLike;\n}\n\n/** A loaded texture wrapping a Skia SkImage. */\nexport interface Texture {\n /** Unique key for this texture in the asset manager. */\n readonly key: string;\n /** The underlying Skia SkImage. */\n readonly image: SkImageLike;\n /** Width in pixels. */\n readonly width: number;\n /** Height in pixels. */\n readonly height: number;\n}\n\n/** Create a Texture from a Skia SkImage. */\nexport function createTexture(key: string, image: SkImageLike): Texture {\n return {\n key,\n image,\n width: image.width(),\n height: image.height(),\n };\n}\n","import type { AssetLoader, ManifestEntry } from './asset-manager.js';\nimport type { SkImageLike } from './texture.js';\nimport { createTexture } from './texture.js';\n\n/**\n * Decodes raw image bytes into an SkImage. Returns `null` on failure.\n * Wire it to `decodeImage(Skia, bytes)` (native) or `kit.MakeImageFromEncoded`\n * (CanvasKit / web) — see the package README for both.\n */\nexport type DecodeImage = (bytes: Uint8Array) => SkImageLike | null;\n\n/** Minimal structural view of a fetch `Response` — only what the loader reads. */\nexport interface FetchResponseLike {\n readonly ok: boolean;\n readonly status: number;\n arrayBuffer(): Promise<ArrayBuffer>;\n json(): Promise<unknown>;\n}\n\n/**\n * Minimal structural `fetch`. The global `fetch` (web / RN / Bun) satisfies it,\n * so the package needs no DOM/Bun fetch typing of its own.\n */\nexport type FetchLike = (path: string) => Promise<FetchResponseLike>;\n\n/** Options for {@link createFetchAssetLoader}. */\nexport interface FetchAssetLoaderOptions {\n /** Decodes fetched image bytes into an SkImage. */\n decodeImage: DecodeImage;\n /** `fetch` implementation; defaults to the global `fetch`. */\n fetch?: FetchLike;\n}\n\n/** Options for {@link createFileAssetLoader}. */\nexport interface FileAssetLoaderOptions {\n /**\n * Reads a file path into raw bytes — structural, so any native filesystem\n * (e.g. expo-file-system) satisfies it without a hard dependency here.\n */\n readFile: (path: string) => Promise<Uint8Array>;\n /** Decodes read image bytes into an SkImage. */\n decodeImage: DecodeImage;\n}\n\n/**\n * A web `AssetLoader` backed by `fetch`. `texture` entries are decoded into a\n * `Texture`; `binary` yields a `Uint8Array`; `json`/`spritesheet` yield the\n * parsed JSON (feed a spritesheet result to `parseTexturePackerHash` etc.).\n *\n * Fail-fast: a non-OK response or a null decode throws, so `AssetManager.load`\n * rejects. Use `AssetManager.loadManifestSettled` for partial-failure tolerance.\n */\nexport function createFetchAssetLoader(options: FetchAssetLoaderOptions): AssetLoader {\n const { decodeImage } = options;\n const fetchFn: FetchLike = options.fetch ?? globalThis.fetch;\n return async (entry: ManifestEntry) => {\n const response = await fetchFn(entry.path);\n if (!response.ok) {\n throw new Error(\n `[flare-engine/assets] fetch failed for \"${entry.key}\" (${entry.path}): ${response.status}`,\n );\n }\n switch (entry.type) {\n case 'texture': {\n const bytes = new Uint8Array(await response.arrayBuffer());\n const image = decodeImage(bytes);\n if (!image) {\n throw new Error(\n `[flare-engine/assets] image decode failed for \"${entry.key}\" (${entry.path})`,\n );\n }\n return createTexture(entry.key, image);\n }\n case 'binary':\n return new Uint8Array(await response.arrayBuffer());\n default:\n return response.json();\n }\n };\n}\n\n/**\n * A native `AssetLoader` backed by an injected `readFile`. `texture` entries are\n * decoded into a `Texture`; `binary` yields the raw `Uint8Array`;\n * `json`/`spritesheet` yield the JSON parsed from UTF-8 bytes.\n *\n * Fail-fast: a null decode (or a rejecting `readFile`) throws.\n */\nexport function createFileAssetLoader(options: FileAssetLoaderOptions): AssetLoader {\n const { readFile, decodeImage } = options;\n return async (entry: ManifestEntry) => {\n const bytes = await readFile(entry.path);\n switch (entry.type) {\n case 'texture': {\n const image = decodeImage(bytes);\n if (!image) {\n throw new Error(\n `[flare-engine/assets] image decode failed for \"${entry.key}\" (${entry.path})`,\n );\n }\n return createTexture(entry.key, image);\n }\n case 'binary':\n return bytes;\n default:\n return JSON.parse(new TextDecoder().decode(bytes));\n }\n };\n}\n","/** A single frame rectangle in a sprite sheet. */\nexport interface SpriteFrame {\n /** Name/key of the frame. */\n name: string;\n /** X offset in the source texture (pixels). */\n x: number;\n /** Y offset in the source texture (pixels). */\n y: number;\n /** Width of the frame (pixels). */\n w: number;\n /** Height of the frame (pixels). */\n h: number;\n}\n\n/** A named animation sequence within a sprite sheet. */\nexport interface AnimationSequence {\n /** Sequence name (e.g. \"walk\", \"idle\"). */\n name: string;\n /** Indices into the SpriteSheet.frames array. */\n frameIndices: number[];\n /** Duration per frame in seconds. */\n frameDuration: number;\n /** Whether to loop the sequence. */\n loop: boolean;\n}\n\n/** Parsed sprite sheet data — pure data, no Skia dependency. */\nexport interface SpriteSheet {\n /** Ordered array of all frames. */\n frames: SpriteFrame[];\n /** Map from frame name to index in frames[]. */\n frameMap: Map<string, number>;\n /** Named animation sequences. */\n animations: Map<string, AnimationSequence>;\n}\n\n/** Create an empty sprite sheet. */\nexport function createSpriteSheet(): SpriteSheet {\n return {\n frames: [],\n frameMap: new Map(),\n animations: new Map(),\n };\n}\n\n// ----- Rotated-frame dev warning -----\n\ndeclare const __DEV__: boolean | undefined;\n\n/**\n * Warn (dev builds only) when a TexturePacker frame is exported rotated.\n * Rotated frames are not yet remapped, so they render sideways — the frame is\n * named so the artist can re-export it. Full rotation support is post-launch.\n */\nfunction warnRotatedFrame(name: string): void {\n if (typeof __DEV__ !== 'undefined' && __DEV__) {\n console.warn(\n `[flare-engine/assets] sprite frame \"${name}\": rotation unsupported — re-export without rotation`,\n );\n }\n}\n\n// ----- TexturePacker JSON (hash format) -----\n\ninterface TPHashFrame {\n frame: { x: number; y: number; w: number; h: number };\n rotated?: boolean;\n}\n\ninterface TPHashJSON {\n frames: Record<string, TPHashFrame>;\n}\n\n/** Parse TexturePacker JSON hash format. */\nexport function parseTexturePackerHash(json: unknown): SpriteSheet {\n const data = json as TPHashJSON;\n const sheet = createSpriteSheet();\n const entries = Object.entries(data.frames);\n for (let i = 0; i < entries.length; i++) {\n const entry = entries[i];\n if (!entry) continue;\n const [name, value] = entry;\n if (value.rotated) warnRotatedFrame(name);\n const f = value.frame;\n sheet.frames.push({ name, x: f.x, y: f.y, w: f.w, h: f.h });\n sheet.frameMap.set(name, i);\n }\n return sheet;\n}\n\n// ----- TexturePacker JSON (array format) -----\n\ninterface TPArrayFrame {\n filename: string;\n frame: { x: number; y: number; w: number; h: number };\n rotated?: boolean;\n}\n\ninterface TPArrayJSON {\n frames: TPArrayFrame[];\n}\n\n/** Parse TexturePacker JSON array format. */\nexport function parseTexturePackerArray(json: unknown): SpriteSheet {\n const data = json as TPArrayJSON;\n const sheet = createSpriteSheet();\n for (let i = 0; i < data.frames.length; i++) {\n const entry = data.frames[i];\n if (!entry) continue;\n if (entry.rotated) warnRotatedFrame(entry.filename);\n const f = entry.frame;\n sheet.frames.push({\n name: entry.filename,\n x: f.x,\n y: f.y,\n w: f.w,\n h: f.h,\n });\n sheet.frameMap.set(entry.filename, i);\n }\n return sheet;\n}\n\n// ----- Aseprite JSON -----\n\ninterface AsepriteFrame {\n filename: string;\n frame: { x: number; y: number; w: number; h: number };\n duration: number; // ms\n}\n\ninterface AsepriteTag {\n name: string;\n from: number;\n to: number;\n direction: string;\n}\n\ninterface AsepriteJSON {\n frames: AsepriteFrame[] | Record<string, AsepriteFrame>;\n meta?: {\n frameTags?: AsepriteTag[];\n };\n}\n\n/** Parse Aseprite JSON export. */\nexport function parseAseprite(json: unknown): SpriteSheet {\n const data = json as AsepriteJSON;\n const sheet = createSpriteSheet();\n\n // Aseprite can export frames as array or object\n const frameEntries: AsepriteFrame[] = Array.isArray(data.frames)\n ? data.frames\n : Object.values(data.frames);\n\n for (let i = 0; i < frameEntries.length; i++) {\n const entry = frameEntries[i];\n if (!entry) continue;\n const f = entry.frame;\n sheet.frames.push({\n name: entry.filename,\n x: f.x,\n y: f.y,\n w: f.w,\n h: f.h,\n });\n sheet.frameMap.set(entry.filename, i);\n }\n\n // Parse frame tags as animation sequences\n const tags = data.meta?.frameTags;\n if (tags) {\n for (const tag of tags) {\n const indices: number[] = [];\n if (tag.direction === 'reverse') {\n for (let i = tag.to; i >= tag.from; i--) {\n indices.push(i);\n }\n } else if (tag.direction === 'pingpong') {\n for (let i = tag.from; i <= tag.to; i++) {\n indices.push(i);\n }\n for (let i = tag.to - 1; i > tag.from; i--) {\n indices.push(i);\n }\n } else {\n // \"forward\" or default\n for (let i = tag.from; i <= tag.to; i++) {\n indices.push(i);\n }\n }\n\n // Use the first frame's duration as the uniform frame duration\n const firstFrame = frameEntries[tag.from];\n const durationMs = firstFrame?.duration ?? 100;\n\n sheet.animations.set(tag.name, {\n name: tag.name,\n frameIndices: indices,\n frameDuration: durationMs / 1000,\n loop: true,\n });\n }\n }\n\n return sheet;\n}\n\n/**\n * Add a custom animation sequence to a sprite sheet.\n */\nexport function addAnimation(\n sheet: SpriteSheet,\n name: string,\n frameIndices: number[],\n frameDuration: number,\n loop = true,\n): void {\n sheet.animations.set(name, { name, frameIndices, frameDuration, loop });\n}\n\n/** Get a frame by name. Returns undefined if not found. */\nexport function getFrame(sheet: SpriteSheet, name: string): SpriteFrame | undefined {\n const idx = sheet.frameMap.get(name);\n if (idx === undefined) return undefined;\n return sheet.frames[idx];\n}\n","import { createSpriteSheet, type SpriteFrame, type SpriteSheet } from './sprite-sheet.js';\nimport type { SkImageLike } from './texture.js';\n\n/** One entry in a procedural atlas — a named colored rectangle. */\nexport interface ProceduralFrameSpec {\n /** Frame name (used as the SpriteFrame name for lookup). */\n name: string;\n /** Width in pixels. */\n w: number;\n /** Height in pixels. */\n h: number;\n /** Color as ARGB int (0xAARRGGBB). */\n color: number;\n}\n\n/** Options controlling atlas layout. */\nexport interface ProceduralAtlasOptions {\n /** Max atlas width before wrapping to a new row. Default 1024. */\n maxWidth?: number;\n /** Gap between frames in pixels. Default 0. */\n padding?: number;\n}\n\n/** Result of a procedural atlas build. */\nexport interface ProceduralAtlas {\n /** Backing Skia image with all rects drawn. */\n image: SkImageLike;\n /** SpriteSheet whose frames describe the rect positions. */\n sheet: SpriteSheet;\n /** Total atlas width in pixels. */\n width: number;\n /** Total atlas height in pixels. */\n height: number;\n}\n\n/** Opaque Skia color value — a Float32Array of length 4 (r, g, b, a in [0,1]). */\ntype SkColorLike = Float32Array;\n\n/** Narrow paint interface — only the setter we use. */\nexport interface SkPaintLike {\n setColor(color: SkColorLike): void;\n}\n\n/** Narrow rect interface — a rect value object passed to drawRect. */\nexport interface SkRectLike {\n readonly x: number;\n readonly y: number;\n readonly width: number;\n readonly height: number;\n}\n\n/** Narrow canvas interface — only the method we use. */\nexport interface SkCanvasLike {\n drawRect(rect: SkRectLike, paint: SkPaintLike): void;\n}\n\n/** Narrow surface interface — getCanvas + snapshot. */\nexport interface SkSurfaceLike {\n getCanvas(): SkCanvasLike;\n makeImageSnapshot(): SkImageLike;\n}\n\n/**\n * Narrow view of the Skia module — only the factories this helper needs.\n * Declared locally so unit tests can supply a plain mock without pulling\n * in the full `@shopify/react-native-skia` surface.\n */\nexport interface SkiaAtlasModuleLike {\n Surface: { Make(width: number, height: number): SkSurfaceLike | null };\n Paint(): SkPaintLike;\n XYWHRect(x: number, y: number, w: number, h: number): SkRectLike;\n}\n\n/**\n * Build a flat atlas `SkImage` from a list of colored rectangles.\n *\n * Row-packs frames left-to-right until `maxWidth` is exceeded, then wraps\n * to a new row. Returns both the backing image and a `SpriteSheet` whose\n * frames match the packed positions, so consumers can look up frames by\n * name exactly as with a real `parseTexturePacker*` sheet.\n *\n * Useful for:\n * - bootstrapping gameplay before final art lands (replace with one\n * `parseTexturePackerHash` call once the real atlas arrives),\n * - engine tests / benchmarks that need a valid `SkImage` without\n * shipping any binary asset.\n *\n * **Canonical placeholder-atlas pattern:** a game can ship a full \"shape\n * atlas\" that draws every entity (enemies, bosses, ships, pickups) as\n * composed primitives onto an offscreen Skia surface, then wraps the result\n * in a `SpriteSheet`.\n * That pattern (declarative shape spec → Skia draw calls → `SpriteSheet`\n * with one named frame per shape) is the recommended way to build a\n * manifest-swappable placeholder atlas: when final art lands, swap the\n * shape draw-calls for `parseTexturePackerHash(jsonText)` with no other\n * code changes.\n */\nexport function createProceduralAtlas(\n Skia: SkiaAtlasModuleLike,\n frames: readonly ProceduralFrameSpec[],\n options: ProceduralAtlasOptions = {},\n): ProceduralAtlas {\n const maxWidth = options.maxWidth ?? 1024;\n const padding = options.padding ?? 0;\n\n const positions = layoutRows(frames, maxWidth, padding);\n const surface = Skia.Surface.Make(positions.width, positions.height);\n if (surface === null) {\n throw new Error(`Skia.Surface.Make returned null for ${positions.width}x${positions.height}`);\n }\n\n const canvas = surface.getCanvas();\n const paint = Skia.Paint();\n const color: SkColorLike = new Float32Array(4);\n\n const sheet = createSpriteSheet();\n\n for (let i = 0; i < frames.length; i++) {\n const spec = frames[i];\n const pos = positions.rects[i];\n if (spec === undefined || pos === undefined) continue;\n\n writeArgb(color, spec.color);\n paint.setColor(color);\n canvas.drawRect(Skia.XYWHRect(pos.x, pos.y, spec.w, spec.h), paint);\n\n const frame: SpriteFrame = {\n name: spec.name,\n x: pos.x,\n y: pos.y,\n w: spec.w,\n h: spec.h,\n };\n sheet.frames.push(frame);\n sheet.frameMap.set(spec.name, i);\n }\n\n return {\n image: surface.makeImageSnapshot(),\n sheet,\n width: positions.width,\n height: positions.height,\n };\n}\n\ninterface PackedPosition {\n x: number;\n y: number;\n}\n\ninterface PackedLayout {\n rects: PackedPosition[];\n width: number;\n height: number;\n}\n\nfunction layoutRows(\n frames: readonly ProceduralFrameSpec[],\n maxWidth: number,\n padding: number,\n): PackedLayout {\n const rects: PackedPosition[] = [];\n let x = 0;\n let y = 0;\n let rowHeight = 0;\n let atlasWidth = 0;\n\n for (const spec of frames) {\n if (x > 0 && x + spec.w > maxWidth) {\n y += rowHeight + padding;\n x = 0;\n rowHeight = 0;\n }\n rects.push({ x, y });\n x += spec.w + padding;\n if (spec.h > rowHeight) rowHeight = spec.h;\n if (x - padding > atlasWidth) atlasWidth = x - padding;\n }\n\n const atlasHeight = y + rowHeight;\n return {\n rects,\n width: atlasWidth > 0 ? atlasWidth : 1,\n height: atlasHeight > 0 ? atlasHeight : 1,\n };\n}\n\nfunction writeArgb(out: SkColorLike, argb: number): void {\n out[0] = ((argb >>> 16) & 0xff) / 255;\n out[1] = ((argb >>> 8) &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AG,KAAK,GAAG,KAAK,CAAC,GAAG,KAAK;EAElE,MAAM,QAAqB;GACzB,MAAM,KAAK;GACX,GAAG,IAAI;GACP,GAAG,IAAI;GACP,GAAG,KAAK;GACR,GAAG,KAAK;EACV;EACA,MAAM,OAAO,KAAK,KAAK;EACvB,MAAM,SAAS,IAAI,KAAK,MAAM,CAAC;CACjC;CAEA,OAAO;EACL,OAAO,QAAQ,kBAAkB;EACjC;EACA,OAAO,UAAU;EACjB,QAAQ,UAAU;CACpB;AACF;AAaA,SAAS,WACP,QACA,UACA,SACc;CACd,MAAM,QAA0B,CAAC;CACjC,IAAI,IAAI;CACR,IAAI,IAAI;CACR,IAAI,YAAY;CAChB,IAAI,aAAa;CAEjB,KAAK,MAAM,QAAQ,QAAQ;EACzB,IAAI,IAAI,KAAK,IAAI,KAAK,IAAI,UAAU;GAClC,KAAK,YAAY;GACjB,IAAI;GACJ,YAAY;EACd;EACA,MAAM,KAAK;GAAE;GAAG;EAAE,CAAC;EACnB,KAAK,KAAK,IAAI;EACd,IAAI,KAAK,IAAI,WAAW,YAAY,KAAK;EACzC,IAAI,IAAI,UAAU,YAAY,aAAa,IAAI;CACjD;CAEA,MAAM,cAAc,IAAI;CACxB,OAAO;EACL;EACA,OAAO,aAAa,IAAI,aAAa;EACrC,QAAQ,cAAc,IAAI,cAAc;CAC1C;AACF;AAEA,SAAS,UAAU,KAAkB,MAAoB;CACvD,IAAI,MAAO,SAAS,KAAM,OAAQ;CAClC,IAAI,MAAO,SAAS,IAAK,OAAQ;CACjC,IAAI,MAAM,OAAO,OAAQ;CACzB,IAAI,MAAO,SAAS,KAAM,OAAQ;AACpC"}
package/package.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "@flare-engine/assets",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Asset loading, sprite sheet parsing",
5
5
  "keywords": ["flare-engine", "assets", "sprite-sheet", "loader"],
6
- "license": "MIT",
6
+ "license": "Apache-2.0",
7
7
  "author": "Grzegorz Otto",
8
8
  "homepage": "https://github.com/grzott/flare-engine#readme",
9
9
  "bugs": {
@@ -19,24 +19,28 @@
19
19
  "types": "dist/index.d.ts",
20
20
  "exports": {
21
21
  ".": {
22
- "types": "./dist/index.d.ts",
23
- "import": "./dist/index.mjs",
24
- "require": "./dist/index.js"
22
+ "import": {
23
+ "types": "./dist/index.d.mts",
24
+ "default": "./dist/index.mjs"
25
+ },
26
+ "require": {
27
+ "types": "./dist/index.d.ts",
28
+ "default": "./dist/index.js"
29
+ }
25
30
  }
26
31
  },
27
- "files": ["dist", "README.md", "LICENSE"],
32
+ "files": ["dist", "README.md", "LICENSE", "NOTICE"],
28
33
  "scripts": {
29
- "build": "tsup",
34
+ "build": "tsdown",
30
35
  "test": "bun test",
31
36
  "lint": "biome check src/",
32
37
  "typecheck": "tsc --noEmit"
33
38
  },
34
39
  "dependencies": {
35
- "@flare-engine/core": "^0.2.0",
36
- "@flare-engine/events": "^0.2.0"
40
+ "@flare-engine/events": "^0.3.0"
37
41
  },
38
- "peerDependencies": {
39
- "@shopify/react-native-skia": ">=1.0.0"
42
+ "engines": {
43
+ "node": ">=20"
40
44
  },
41
45
  "publishConfig": {
42
46
  "access": "restricted",