A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(import): what a .aseprite becomes, and the tags that survive it
esenginea1f2b580d15f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 24e1e9bf5..70170d36f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -47,6 +47,31 @@ published separately; it ships inside the editor.### Added+- **An `.aseprite` file imports.** Aseprite is where most pixel art is drawn, and its+ documents are frames and tags — "walk is 1 to 6, and it ping-pongs" — where a PSD is+ a stack. Bringing one into a project meant exporting a sheet by hand, typing the cell+ size into the texture's settings, and then re-typing each tag's range as a clip; three+ transcriptions of facts the file already carried, all of them stale the next time the+ artist added a frame.++ Dropping one in now writes the composited sheet and one `.esanim` per tag beside it,+ with each frame's own duration, the direction the tag states (a ping-pong turns around+ on its ends rather than repeating them), and the anchor of a slice that carries a+ pivot. Re-importing is the same door, so an edited file reaches the game by saving it.++ The frame composite is the artwork: layers exist so the artist can work, and what+ plays is what they see — so the stack collapses at import, with every blend mode the+ format can store, the group switches that hide what is inside them, and linked cels+ resolved. A tilemap layer is drawn from a tileset rather than from pixels and says so+ instead of arriving blank.++ The sheet arrives asking for `nearest` filtering and no GPU compression, which is the+ one kind of image where both defaults are wrong: a bilinear filter blurs the pixels+ the artist placed, and a lossy format invents colours a small palette does not have.+ Its cell grid is re-derived on every import — a resized canvas that kept the old cell+ size would leave every cell index in the project pointing at the wrong pixels — while+ the filter and the compression stay whatever the project set them to.+- **A polygon collider can take the sprite's own silhouette.** Drawing a collideraround art by hand is the one authoring step where the answer is already in thefile: the artist drew the shape, and every vertex placed by eye is a chance todiff --git a/desktop b/desktopindex 2711e1b23..62baf00fa 160000--- a/desktop+++ b/desktop@@ -1 +1 @@-Subproject commit 2711e1b23c6ba9c7159e7bf9305c8b334607b0de+Subproject commit 62baf00fa35ef8249950c20929a14fd961b25668diff --git a/docs/astro/src/content/docs/animation/overview.mdx b/docs/astro/src/content/docs/animation/overview.mdxindex e3ca124c8..9c4d674c5 100644--- a/docs/astro/src/content/docs/animation/overview.mdx+++ b/docs/astro/src/content/docs/animation/overview.mdx@@ -121,6 +121,28 @@ The **frame under the playhead** has its own section in the Details inspectorduration, size, offset, anchor — alongside the clip's fps, loop mode, and thetwo switches below.+### From an Aseprite file++Drop a `.aseprite` (or `.ase`) into the project and the import writes the products+for you: the composited sheet as a `.png` beside it, and one `.esanim` per tag —+`hero_walk.esanim`, `hero_jump.esanim` — carrying each frame's own duration and the+direction the tag plays in. A tag with no repeat count loops; one that counts its+plays does not. A file with no tags gets a single clip over every frame.++What is composited is what the artist sees: every layer they left visible, with its+blend mode and opacity, and nothing from a group they switched off. A tilemap layer+is drawn from a tileset rather than from pixels and is reported instead of silently+arriving blank.++The sheet's texture arrives set to **nearest** filtering with compression off —+the two settings pixel art always wants and never gets by default — and with its+cell grid filled in, so a `Sprite` can pick a frame of it straight away. Change+either setting and it stays changed; the grid is re-derived on every import,+because it is the source's canvas size rather than a preference.++Editing the file and saving it re-imports it in place: same uuids, same refs, new+pixels. Right-click → **Reimport** does the same on demand.+### Per-frame sizes and offsetsA sheet's cells are all the same size, so one `Sprite.size` fits every frame ofdiff --git a/docs/astro/src/content/docs/assets/textures.mdx b/docs/astro/src/content/docs/assets/textures.mdxindex 49bce6fae..9e71bfcd6 100644--- a/docs/astro/src/content/docs/assets/textures.mdx+++ b/docs/astro/src/content/docs/assets/textures.mdx@@ -24,6 +24,10 @@ For the general asset system (refs, groups, the manifest), see [Assets](/docs/as| `.bmp` | Uncompressed; works, but rarely what you want to ship. || `.ktx2` | Basis Universal, already GPU-compressed. What the cook step **produces** — you can also author one directly. |+An `.aseprite` / `.ase` file is not a texture — importing one **produces** a sheet+`.png` (plus a clip per tag) and that is what a scene references. See+[Sprite animation](/animation/overview/#from-an-aseprite-file).+`.png`, `.jpg` and `.webp` are the ones to author in. A build's cook step turns theminto `.ktx2` when compression is on (see [Import settings](#import-settings)).diff --git a/docs/astro/src/content/docs/zh-cn/animation/overview.mdx b/docs/astro/src/content/docs/zh-cn/animation/overview.mdxindex bf853c059..21c4fc81d 100644--- a/docs/astro/src/content/docs/zh-cn/animation/overview.mdx+++ b/docs/astro/src/content/docs/zh-cn/animation/overview.mdx@@ -109,6 +109,24 @@ const listen = defineSystem([Res(SpriteAnimation)], (anim) => {**播放头所在的那一帧**在检视器里有自己的一节——时长、尺寸、偏移、锚点,和剪辑的帧率、循环模式以及下面这两个开关并排。+### 从 Aseprite 文件导入++把 `.aseprite`(或 `.ase`)拖进项目,导入会替你写好产物:合成后的精灵表 `.png` 落在+它旁边,每个 tag 一个 `.esanim` —— `hero_walk.esanim`、`hero_jump.esanim` ——+带着每帧自己的时长与 tag 声明的播放方向。没有重复次数的 tag 会循环,数着播放次数的+不循环。没有 tag 的文件得到一个覆盖全部帧的剪辑。++合成出来的就是画师看到的那一张:所有他们留着可见的图层,连同各自的混合模式与不透明度,+而被关掉的组里的东西一概不进来。tilemap 图层是从 tileset 画出来的而不是像素,导入会+明确报出来,而不是让它悄悄变成空白。++精灵表的纹理导入设置到达时就是 **nearest** 过滤 + 关闭压缩 —— 像素画永远想要、+却从来不是默认值的两项 —— 并且格子尺寸已经填好,`Sprite` 可以直接选一帧。这两项改了+就保持你改的样子;格子则每次导入都重新推导,因为它是源文件的画布尺寸而不是一项偏好。++编辑源文件并保存会原地重新导入:uuid 不变、引用不变、像素是新的。右键 →+**重新导入**可以随时手动触发。+### 逐帧尺寸与偏移精灵表的格子都一样大,所以整段剪辑共用一个 `Sprite.size` 是对的。多张独立diff --git a/docs/astro/src/content/docs/zh-cn/assets/textures.mdx b/docs/astro/src/content/docs/zh-cn/assets/textures.mdxindex 9ebc77aeb..32c66a71d 100644--- a/docs/astro/src/content/docs/zh-cn/assets/textures.mdx+++ b/docs/astro/src/content/docs/zh-cn/assets/textures.mdx@@ -23,6 +23,9 @@ import { Aside } from '@astrojs/starlight/components';| `.bmp` | 未压缩;能用,但基本不该发出去。 || `.ktx2` | Basis Universal,已经是 GPU 压缩格式。这是构建的 cook 步骤**产出**的东西——你也可以直接提供。 |+`.aseprite` / `.ase` 不是纹理——导入它**产出**一张精灵表 `.png`(以及每个 tag 一个剪辑),+场景引用的是产物。见[精灵动画](/zh-cn/animation/overview/#从-aseprite-文件导入)。+日常创作用 `.png`、`.jpg`、`.webp`。开了压缩时,构建的 cook 步骤会把它们转成 `.ktx2`(见[导入设置](#导入设置))。diff --git a/pipeline/src/assets/asepriteBlend.ts b/pipeline/src/assets/asepriteBlend.tsnew file mode 100644index 000000000..a505ae6d8--- /dev/null+++ b/pipeline/src/assets/asepriteBlend.ts@@ -0,0 +1,153 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file Aseprite's layer blending, on 8-bit non-premultiplied RGBA.+ *+ * Every mode the format can store is here rather than a subset with a+ * warning attached, because a composite that is silently NOT what the+ * artist drew is the one failure a pixel-art import must not have. The+ * arithmetic is the editor's own — integer, with its rounding — so a+ * frame composited here matches the one Aseprite shows, byte for byte.+ */+import { AsepriteBlend } from './asepriteFile';++/** Aseprite's rounded 8-bit multiply: exactly round(a*b/255). */+function mul8(a: number, b: number): number {+ const t = a * b + 0x80;+ return ((t >> 8) + t) >> 8;+}++/** Aseprite's 8-bit divide, rounded — only called where b < s, so it stays in range. */+function div8(a: number, b: number): number {+ return Math.min(255, Math.floor((a * 255 + Math.floor(b / 2)) / b));+}++const screen = (b: number, s: number): number => b + s - mul8(b, s);+const hardLight = (b: number, s: number): number =>+ (s < 128 ? mul8(b, s << 1) : screen(b, (s << 1) - 255));++function softLight(b: number, s: number): number {+ const bd = b / 255;+ const sd = s / 255;+ const d = bd <= 0.25 ? ((16 * bd - 12) * bd + 4) * bd : Math.sqrt(bd);+ const r = sd <= 0.5+ ? bd - (1 - 2 * sd) * bd * (1 - bd)+ : bd + (2 * sd - 1) * (d - bd);+ return Math.max(0, Math.min(255, Math.round(r * 255)));+}++function colorDodge(b: number, s: number): number {+ if (b === 0) return 0;+ const inv = 255 - s;+ return b >= inv ? 255 : div8(b, inv);+}++function colorBurn(b: number, s: number): number {+ if (b === 255) return 255;+ const inv = 255 - b;+ return inv >= s ? 0 : 255 - div8(inv, s);+}++function divide(b: number, s: number): number {+ if (b === 0) return 0;+ return b >= s ? 255 : div8(b, s);+}++// The four HSL modes work on all three channels at once, so they carry their own+// triple-valued helpers. Photoshop's definitions, which is what Aseprite implements.++const luminosity = (c: number[]): number => 0.3 * c[0]! + 0.59 * c[1]! + 0.11 * c[2]!;+const saturation = (c: number[]): number => Math.max(...c) - Math.min(...c);++function clipColor(c: number[]): number[] {+ const l = luminosity(c);+ const min = Math.min(...c);+ const max = Math.max(...c);+ let out = c;+ if (min < 0) out = out.map((v) => l + ((v - l) * l) / (l - min || 1));+ if (max > 1) out = out.map((v) => l + ((v - l) * (1 - l)) / ((max - l) || 1));+ return out;+}++function setLum(c: number[], l: number): number[] {+ const d = l - luminosity(c);+ return clipColor(c.map((v) => v + d));+}++function setSat(c: number[], s: number): number[] {+ const max = Math.max(...c);+ const min = Math.min(...c);+ const range = max - min;+ return c.map((v) => (range > 0 ? ((v - min) * s) / range : 0));+}++/** The blended colour of one mode, before the alpha compositing every mode shares. */+function blendChannels(mode: AsepriteBlend, b: number[], s: number[]): number[] {+ switch (mode) {+ case AsepriteBlend.Multiply: return b.map((v, i) => mul8(v, s[i]!));+ case AsepriteBlend.Screen: return b.map((v, i) => screen(v, s[i]!));+ case AsepriteBlend.Overlay: return b.map((v, i) => hardLight(s[i]!, v));+ case AsepriteBlend.Darken: return b.map((v, i) => Math.min(v, s[i]!));+ case AsepriteBlend.Lighten: return b.map((v, i) => Math.max(v, s[i]!));+ case AsepriteBlend.ColorDodge: return b.map((v, i) => colorDodge(v, s[i]!));+ case AsepriteBlend.ColorBurn: return b.map((v, i) => colorBurn(v, s[i]!));+ case AsepriteBlend.HardLight: return b.map((v, i) => hardLight(v, s[i]!));+ case AsepriteBlend.SoftLight: return b.map((v, i) => softLight(v, s[i]!));+ case AsepriteBlend.Difference: return b.map((v, i) => Math.abs(v - s[i]!));+ case AsepriteBlend.Exclusion: return b.map((v, i) => v + s[i]! - 2 * mul8(v, s[i]!));+ case AsepriteBlend.Addition: return b.map((v, i) => Math.min(255, v + s[i]!));+ case AsepriteBlend.Subtract: return b.map((v, i) => Math.max(0, v - s[i]!));+ case AsepriteBlend.Divide: return b.map((v, i) => divide(v, s[i]!));+ case AsepriteBlend.Hue:+ case AsepriteBlend.Saturation:+ case AsepriteBlend.Color:+ case AsepriteBlend.Luminosity: {+ const bf = b.map((v) => v / 255);+ const sf = s.map((v) => v / 255);+ const out = mode === AsepriteBlend.Hue+ ? setLum(setSat(sf, saturation(bf)), luminosity(bf))+ : mode === AsepriteBlend.Saturation+ ? setLum(setSat(bf, saturation(sf)), luminosity(bf))+ : mode === AsepriteBlend.Color+ ? setLum(sf, luminosity(bf))+ : setLum(bf, luminosity(sf));+ return out.map((v) => Math.max(0, Math.min(255, Math.round(v * 255))));+ }+ default: return s;+ }+}++/**+ * Blend one source pixel over one backdrop pixel, in place in `dst` at `di`.+ *+ * `opacity` is the layer's times the cel's — the two multipliers Aseprite applies+ * before any mode sees the pixel. Alpha stays straight, never premultiplied: that+ * is what the format stores and what a PNG expects.+ */+export function blendPixel(dst: Uint8Array, di: number, src: Uint8Array, si: number,+ mode: AsepriteBlend, opacity: number): void {+ const sa = mul8(src[si + 3]!, opacity);+ if (sa === 0) return;+ const ba = dst[di + 3]!;++ let sr = src[si]!;+ let sg = src[si + 1]!;+ let sb = src[si + 2]!;+ if (mode !== AsepriteBlend.Normal && ba !== 0) {+ const [r, g, b] = blendChannels(mode, [dst[di]!, dst[di + 1]!, dst[di + 2]!], [sr, sg, sb]);+ sr = r!; sg = g!; sb = b!;+ }++ if (ba === 0) {+ dst[di] = sr; dst[di + 1] = sg; dst[di + 2] = sb; dst[di + 3] = sa;+ return;+ }++ // Straight-alpha "over": the result's alpha first, because the colour is a+ // walk from backdrop to source weighted by how much of the result is source.+ const ra = sa + ba - mul8(ba, sa);+ dst[di] = dst[di]! + Math.round(((sr - dst[di]!) * sa) / ra);+ dst[di + 1] = dst[di + 1]! + Math.round(((sg - dst[di + 1]!) * sa) / ra);+ dst[di + 2] = dst[di + 2]! + Math.round(((sb - dst[di + 2]!) * sa) / ra);+ dst[di + 3] = ra;+}diff --git a/pipeline/src/assets/asepriteFile.ts b/pipeline/src/assets/asepriteFile.tsnew file mode 100644index 000000000..72cb0481e--- /dev/null+++ b/pipeline/src/assets/asepriteFile.ts@@ -0,0 +1,373 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file Reading a `.aseprite` document: chunks in, structure out.+ *+ * Only the format lives here — frames, layers, cels, tags, slices and the+ * palette, named the way the file names them. What any of it becomes is+ * the import's question, which is the same line the FBX read draws+ * against the model import.+ *+ * The format is small and stable enough to read directly (the spec is+ * published with the editor), and doing so keeps the one pixel-art+ * pipeline free of a dependency that would have to be trusted with every+ * byte of an artist's work.+ */+import { inflateSync } from 'node:zlib';++/** Aseprite's own blend-mode numbering, in the order the format assigns. */+export enum AsepriteBlend {+ Normal = 0, Multiply = 1, Screen = 2, Overlay = 3, Darken = 4, Lighten = 5,+ ColorDodge = 6, ColorBurn = 7, HardLight = 8, SoftLight = 9, Difference = 10,+ Exclusion = 11, Hue = 12, Saturation = 13, Color = 14, Luminosity = 15,+ Addition = 16, Subtract = 17, Divide = 18,+}++/** How a tag walks its own frame range. */+export type AsepriteDirection = 'forward' | 'reverse' | 'pingpong' | 'pingpong-reverse';++export interface AsepriteLayer {+ name: string;+ /** Nesting depth; a layer belongs to the nearest preceding group one level up. */+ childLevel: number;+ isGroup: boolean;+ isTilemap: boolean;+ isBackground: boolean;+ /** The layer's own switch, before any group above it is taken into account. */+ visible: boolean;+ opacity: number;+ blend: AsepriteBlend;+}++export interface AsepriteCel {+ layer: number;+ x: number;+ y: number;+ width: number;+ height: number;+ opacity: number;+ /** Drawing order offset within the frame, added to the layer's own (format 1.3). */+ zIndex: number;+ /** RGBA8, row-major, `width * height * 4` — already resolved out of the file's+ * colour depth and palette. Null for a cel this read does not decode. */+ pixels: Uint8Array | null;+ /** True for a tilemap cel, whose pixels are tile indices this read does not expand. */+ tilemap: boolean;+}++export interface AsepriteFrame {+ /** How long this frame is held, in milliseconds — the file's own per-frame timing. */+ durationMs: number;+ cels: AsepriteCel[];+}++export interface AsepriteTag {+ name: string;+ from: number;+ to: number;+ direction: AsepriteDirection;+ /** How many times the tag's range plays; 0 means "forever" (format 1.3). */+ repeat: number;+}++/** A named rectangle the artist marked on the canvas, per the frame it changes on. */+export interface AsepriteSliceKey {+ frame: number;+ x: number;+ y: number;+ width: number;+ height: number;+ /** 9-slice centre rect, relative to the key's own rect; null when the slice has none. */+ center: { x: number; y: number; width: number; height: number } | null;+ /** Pivot in the key's own pixels from its top-left; null when the slice has none. */+ pivot: { x: number; y: number } | null;+}++export interface AsepriteSlice {+ name: string;+ keys: AsepriteSliceKey[];+}++export interface AsepriteDocument {+ width: number;+ height: number;+ /** 32 = RGBA, 16 = grayscale, 8 = indexed. */+ colorDepth: number;+ layers: AsepriteLayer[];+ frames: AsepriteFrame[];+ tags: AsepriteTag[];+ slices: AsepriteSlice[];+ /** What the read could not carry; never dropped silently. */+ warnings: string[];+}++const HEADER_MAGIC = 0xa5e0;+const FRAME_MAGIC = 0xf1fa;++const CHUNK_LAYER = 0x2004;+const CHUNK_CEL = 0x2005;+const CHUNK_PALETTE = 0x2019;+const CHUNK_OLD_PALETTE = 0x0004;+const CHUNK_TAGS = 0x2018;+const CHUNK_SLICE = 0x2022;++const CEL_RAW = 0;+const CEL_LINKED = 1;+const CEL_COMPRESSED = 2;+const CEL_COMPRESSED_TILEMAP = 3;++const LAYER_FLAG_VISIBLE = 1;+const LAYER_FLAG_BACKGROUND = 8;++const LAYER_TYPE_GROUP = 1;+const LAYER_TYPE_TILEMAP = 2;++const DIRECTIONS: AsepriteDirection[] = ['forward', 'reverse', 'pingpong', 'pingpong-reverse'];++/** A little-endian cursor over the file — every field in the format is one. */+class Reader {+ private view: DataView;+ private pos = 0;++ constructor(private bytes: Uint8Array, start = 0, private end = bytes.length) {+ this.view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);+ this.pos = start;+ }++ get offset(): number { return this.pos; }+ get remaining(): number { return this.end - this.pos; }++ skip(n: number): void { this.pos += n; }+ seek(n: number): void { this.pos = n; }++ u8(): number { return this.view.getUint8(this.pos++); }+ u16(): number { const v = this.view.getUint16(this.pos, true); this.pos += 2; return v; }+ i16(): number { const v = this.view.getInt16(this.pos, true); this.pos += 2; return v; }+ u32(): number { const v = this.view.getUint32(this.pos, true); this.pos += 4; return v; }+ i32(): number { const v = this.view.getInt32(this.pos, true); this.pos += 4; return v; }++ /** WORD length followed by that many UTF-8 bytes. */+ string(): string {+ const len = this.u16();+ const text = Buffer.from(this.bytes.buffer, this.bytes.byteOffset + this.pos, len).toString('utf8');+ this.pos += len;+ return text;+ }++ bytesOf(len: number): Uint8Array {+ const slice = this.bytes.subarray(this.pos, this.pos + len);+ this.pos += len;+ return slice;+ }+}++/**+ * Expand one cel's stored pixels to RGBA8.+ *+ * The sprite's transparent index becomes a hole — except on a background layer,+ * where that index is a colour like any other, which is what "background" means.+ */+function toRgba(raw: Uint8Array, count: number, depth: number,+ palette: Uint8Array, transparentIndex: number, background: boolean): Uint8Array {+ const out = new Uint8Array(count * 4);+ if (depth === 32) {+ out.set(raw.subarray(0, count * 4));+ return out;+ }+ if (depth === 16) {+ for (let i = 0; i < count; i++) {+ const value = raw[i * 2] ?? 0;+ out[i * 4] = value; out[i * 4 + 1] = value; out[i * 4 + 2] = value;+ out[i * 4 + 3] = raw[i * 2 + 1] ?? 0;+ }+ return out;+ }+ for (let i = 0; i < count; i++) {+ const index = raw[i] ?? 0;+ if (index === transparentIndex && !background) continue;+ out[i * 4] = palette[index * 4] ?? 0;+ out[i * 4 + 1] = palette[index * 4 + 1] ?? 0;+ out[i * 4 + 2] = palette[index * 4 + 2] ?? 0;+ out[i * 4 + 3] = palette[index * 4 + 3] ?? 255;+ }+ return out;+}++/**+ * Read `bytes` as an Aseprite document.+ *+ * @throws when the file is not one — a caller that guessed from the extension+ * needs to hear that rather than receive an empty document.+ */+export function parseAseprite(bytes: Uint8Array): AsepriteDocument {+ const r = new Reader(bytes);+ r.skip(4); // file size, which the chunk walk does not need+ if (r.u16() !== HEADER_MAGIC) throw new Error('not an Aseprite file (bad header magic)');++ const frameCount = r.u16();+ const width = r.u16();+ const height = r.u16();+ const colorDepth = r.u16();+ r.u32(); // flags: only says whether layer opacity is meaningful, and it always is here+ r.u16(); // the deprecated whole-sprite speed; per-frame durations replace it+ r.u32(); r.u32();+ const transparentIndex = r.u8();+ r.skip(3);+ r.u16(); // palette entry count, which the palette chunk restates+ r.skip(2); // pixel aspect ratio: a display hint, not the pixels+ r.skip(92); // the grid's origin and size, then the reserved tail — to byte 128++ const layers: AsepriteLayer[] = [];+ const frames: AsepriteFrame[] = [];+ const tags: AsepriteTag[] = [];+ const slices: AsepriteSlice[] = [];+ const warnings: string[] = [];+ const palette = new Uint8Array(256 * 4);+ let modernPalette = false;++ for (let f = 0; f < frameCount; f++) {+ const frameStart = r.offset;+ const frameBytes = r.u32();+ if (r.u16() !== FRAME_MAGIC) throw new Error(`frame ${f} is not a frame (bad magic)`);+ const oldChunks = r.u16();+ const durationMs = r.u16();+ r.skip(2);+ const newChunks = r.u32();+ const chunks = newChunks !== 0 ? newChunks : oldChunks;++ const frame: AsepriteFrame = { durationMs, cels: [] };+ frames.push(frame);++ for (let c = 0; c < chunks; c++) {+ const chunkStart = r.offset;+ const chunkSize = r.u32();+ const type = r.u16();+ const next = chunkStart + chunkSize;++ if (type === CHUNK_LAYER) {+ const flags = r.u16();+ const layerType = r.u16();+ const childLevel = r.u16();+ r.u16(); r.u16(); // default width/height, which the format itself calls ignorable+ const blend = r.u16() as AsepriteBlend;+ const opacity = r.u8();+ r.skip(3);+ layers.push({+ name: r.string(),+ childLevel,+ isGroup: layerType === LAYER_TYPE_GROUP,+ isTilemap: layerType === LAYER_TYPE_TILEMAP,+ isBackground: (flags & LAYER_FLAG_BACKGROUND) !== 0,+ visible: (flags & LAYER_FLAG_VISIBLE) !== 0,+ opacity,+ blend,+ });+ } else if (type === CHUNK_CEL) {+ const layerIndex = r.u16();+ const x = r.i16();+ const y = r.i16();+ const opacity = r.u8();+ const celType = r.u16();+ const zIndex = r.i16();+ r.skip(5);+ const background = layers[layerIndex]?.isBackground === true;++ if (celType === CEL_LINKED) {+ const source = r.u16();+ const linked = frames[source]?.cels.find((cel) => cel.layer === layerIndex);+ // A linked cel IS the other frame's pixels; copying the reference keeps+ // one decode per image however many frames hold it.+ if (linked) {+ frame.cels.push({ ...linked, opacity, zIndex, x, y });+ }+ } else if (celType === CEL_RAW || celType === CEL_COMPRESSED) {+ const w = r.u16();+ const h = r.u16();+ const stored = r.bytesOf(next - r.offset);+ const raw = celType === CEL_COMPRESSED+ ? new Uint8Array(inflateSync(Buffer.from(stored.buffer, stored.byteOffset, stored.byteLength)))+ : stored;+ frame.cels.push({+ layer: layerIndex, x, y, width: w, height: h, opacity, zIndex, tilemap: false,+ pixels: toRgba(raw, w * h, colorDepth, palette, transparentIndex, background),+ });+ } else if (celType === CEL_COMPRESSED_TILEMAP) {+ const w = r.u16();+ const h = r.u16();+ frame.cels.push({+ layer: layerIndex, x, y, width: w, height: h, opacity, zIndex,+ tilemap: true, pixels: null,+ });+ }+ } else if (type === CHUNK_PALETTE) {+ modernPalette = true;+ r.u32(); // new size, which the first/last pair already bounds+ const first = r.u32();+ const last = r.u32();+ r.skip(8);+ for (let i = first; i <= last && i < 256; i++) {+ const entryFlags = r.u16();+ palette[i * 4] = r.u8();+ palette[i * 4 + 1] = r.u8();+ palette[i * 4 + 2] = r.u8();+ palette[i * 4 + 3] = r.u8();+ if ((entryFlags & 1) !== 0) r.string();+ }+ } else if (type === CHUNK_OLD_PALETTE && !modernPalette) {+ // A file saved by an old build has only this chunk, and without it every+ // indexed pixel would resolve to black. The modern one wins where both are+ // present: it is the one that carries alpha.+ const packets = r.u16();+ let index = 0;+ for (let p = 0; p < packets; p++) {+ index += r.u8();+ const stated = r.u8();+ const count = stated === 0 ? 256 : stated;+ for (let i = 0; i < count && index < 256; i++, index++) {+ palette[index * 4] = r.u8();+ palette[index * 4 + 1] = r.u8();+ palette[index * 4 + 2] = r.u8();+ palette[index * 4 + 3] = 255;+ }+ }+ } else if (type === CHUNK_TAGS) {+ const count = r.u16();+ r.skip(8);+ for (let t = 0; t < count; t++) {+ const from = r.u16();+ const to = r.u16();+ const direction = DIRECTIONS[r.u8()] ?? 'forward';+ const repeat = r.u16();+ r.skip(6);+ r.skip(4); // the deprecated tag colour+ tags.push({ name: r.string(), from, to, direction, repeat });+ }+ } else if (type === CHUNK_SLICE) {+ const keyCount = r.u32();+ const sliceFlags = r.u32();+ r.u32();+ const name = r.string();+ const keys: AsepriteSliceKey[] = [];+ for (let k = 0; k < keyCount; k++) {+ const keyFrame = r.u32();+ const x = r.i32();+ const y = r.i32();+ const w = r.u32();+ const h = r.u32();+ const center = (sliceFlags & 1) !== 0+ ? { x: r.i32(), y: r.i32(), width: r.u32(), height: r.u32() }+ : null;+ const pivot = (sliceFlags & 2) !== 0 ? { x: r.i32(), y: r.i32() } : null;+ keys.push({ frame: keyFrame, x, y, width: w, height: h, center, pivot });+ }+ slices.push({ name, keys });+ }++ r.seek(next);+ }++ r.seek(frameStart + frameBytes);+ }++ return { width, height, colorDepth, layers, frames, tags, slices, warnings };+}diff --git a/pipeline/src/assets/asepriteImport.ts b/pipeline/src/assets/asepriteImport.tsnew file mode 100644index 000000000..0c54d10c4--- /dev/null+++ b/pipeline/src/assets/asepriteImport.ts@@ -0,0 +1,266 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file What a `.aseprite` becomes: one sprite sheet and one `.esanim` per tag.+ *+ * An Aseprite document is frames and tags where a PSD is a stack, so the+ * products differ even though the division is the same one the PSD and+ * model imports draw — {@link ./asepriteFile} reads the format, and the+ * translation into project files happens here.+ *+ * The frame composite is the artwork: layers exist so the artist can+ * work, and what plays is what they see. So the layer stack collapses+ * here, and the sheet's cells are frames rather than parts.+ */+import { PNG } from 'pngjs';+import type { AnimClipAssetData, AnimClipFrameData } from 'esengine';+import {+ parseAseprite, type AsepriteDocument, type AsepriteTag,+} from './asepriteFile';+import { blendPixel } from './asepriteBlend';++/** Widest sheet this import will lay out before it wraps to another row. */+const MAX_SHEET_SIDE = 4096;++export interface AsepriteSheetImage {+ /** `<stem>.png`, written beside the clips. */+ file: string;+ bytes: Uint8Array;+ width: number;+ height: number;+}++export interface AsepriteClipFile {+ file: string;+ data: AnimClipAssetData;+}++/**+ * The sheet's import settings. Pixel art is the one kind of image where the+ * defaults are all wrong: a bilinear filter blurs the pixels the artist placed,+ * and a lossy GPU compression invents colours a small palette does not have.+ */+export interface AsepriteSheetSettings {+ filterMode: 'nearest';+ compress: false;+ sheet: { cellWidth: number; cellHeight: number; margin: number; spacing: number };+}++export interface AsepriteImportResult {+ sheet: AsepriteSheetImage;+ settings: AsepriteSheetSettings;+ /** One per tag, or a single clip over every frame when the file has no tags. */+ clips: AsepriteClipFile[];+ /** What the document says that the products cannot carry. Never dropped. */+ warnings: string[];+}++/** How a document or tag name becomes a file name: one spelling, so two passes agree. */+function fileStem(name: string): string {+ const cleaned = name.trim().replace(/[^\w.-]+/g, '-').replace(/^-+|-+$/g, '');+ return cleaned === '' ? 'clip' : cleaned;+}++/**+ * Whether layer `index` is visible once the groups above it have their say.+ *+ * A group's switch hides everything inside it, and the format states nesting as+ * a child level rather than a tree: the enclosing group is the nearest preceding+ * layer one level up.+ */+function layerVisible(doc: AsepriteDocument, index: number): boolean {+ const layer = doc.layers[index];+ if (!layer) return false;+ if (!layer.visible) return false;+ let level = layer.childLevel;+ for (let i = index - 1; i >= 0 && level > 0; i--) {+ const above = doc.layers[i]!;+ if (above.childLevel === level - 1) {+ if (!above.visible) return false;+ level = above.childLevel;+ }+ }+ return true;+}++/**+ * Composite frame `index` into `dst` at cell origin (`ox`,`oy`) of a `stride`-wide+ * RGBA image.+ *+ * Cels draw in layer order, shifted by the per-cel z-index that lets one frame+ * reorder what the stack says.+ */+function compositeFrame(doc: AsepriteDocument, index: number, visible: boolean[],+ dst: Uint8Array, stride: number, ox: number, oy: number): void {+ const frame = doc.frames[index];+ if (!frame) return;+ const order = frame.cels+ .map((cel, i) => ({ cel, i }))+ .filter(({ cel }) => cel.pixels !== null && visible[cel.layer] === true)+ .sort((a, b) => (a.cel.layer + a.cel.zIndex) - (b.cel.layer + b.cel.zIndex)+ || a.cel.layer - b.cel.layer || a.i - b.i);++ for (const { cel } of order) {+ const layer = doc.layers[cel.layer]!;+ const opacity = Math.round((layer.opacity * cel.opacity) / 255);+ for (let y = 0; y < cel.height; y++) {+ const cy = cel.y + y;+ if (cy < 0 || cy >= doc.height) continue;+ for (let x = 0; x < cel.width; x++) {+ const cx = cel.x + x;+ if (cx < 0 || cx >= doc.width) continue;+ blendPixel(dst, ((oy + cy) * stride + ox + cx) * 4,+ cel.pixels!, (y * cel.width + x) * 4, layer.blend, opacity);+ }+ }+ }+}++/** The frame indices a tag plays, in order — its direction spelled out as a sequence. */+function tagSequence(tag: AsepriteTag): number[] {+ const forward: number[] = [];+ for (let i = tag.from; i <= tag.to; i++) forward.push(i);+ switch (tag.direction) {+ case 'reverse': return [...forward].reverse();+ // A ping-pong turns around ON its end frames rather than repeating them, so+ // the return leg drops both — which is also what makes a two-frame ping-pong+ // the same as playing it forward.+ case 'pingpong': return [...forward, ...forward.slice(1, -1).reverse()];+ case 'pingpong-reverse': {+ const back = [...forward].reverse();+ return [...back, ...back.slice(1, -1).reverse()];+ }+ default: return forward;+ }+}++/**+ * Read `bytes` and produce what a project can hold.+ *+ * `stem` names the products. `refPrefix` is what a texture ref has to carry to+ * resolve from the project root — the clips are written beside the sheet, so it+ * is the destination folder.+ */+export function importAseprite(bytes: Uint8Array, stem: string,+ refPrefix = ''): AsepriteImportResult {+ const doc = parseAseprite(bytes);+ const warnings = [...doc.warnings];++ const frameCount = doc.frames.length;+ const cols = Math.max(1, Math.min(frameCount, Math.floor(MAX_SHEET_SIDE / Math.max(1, doc.width))));+ const rows = Math.ceil(frameCount / cols);+ const pageWidth = cols * doc.width;+ const pageHeight = rows * doc.height;++ const visible = doc.layers.map((_, i) => layerVisible(doc, i));+ if (doc.layers.some((l) => l.isTilemap)) {+ warnings.push('tilemap layers are drawn from a tileset rather than pixels and are not '+ + 'composited — flatten them in Aseprite, or keep the map in a .tmx tilemap');+ }++ const pixels = new Uint8Array(pageWidth * pageHeight * 4);+ for (let f = 0; f < frameCount; f++) {+ compositeFrame(doc, f, visible, pixels, pageWidth,+ (f % cols) * doc.width, Math.floor(f / cols) * doc.height);+ }++ const png = new PNG({ width: pageWidth, height: pageHeight });+ Buffer.from(pixels.buffer, pixels.byteOffset, pixels.byteLength).copy(png.data);+ const sheetFile = `${stem}.png`;++ const sheet: AnimClipAssetData['sheet'] = {+ texture: `${refPrefix}${sheetFile}`,+ cellWidth: doc.width, cellHeight: doc.height,+ margin: 0, spacing: 0,+ pageWidth, pageHeight,+ };++ const pivot = clipPivot(doc, warnings);+ const frameData = (index: number): AnimClipFrameData => ({+ cell: index,+ // The file times each frame on its own, in milliseconds; a clip's are seconds.+ duration: Math.max(0, doc.frames[index]?.durationMs ?? 0) / 1000,+ });++ const clips: AsepriteClipFile[] = [];+ const used = new Set<string>();+ const claim = (name: string): string => {+ let file = name;+ for (let n = 2; used.has(file.toLowerCase()); n++) file = `${name}-${n}`;+ used.add(file.toLowerCase());+ return `${file}.esanim`;+ };++ const clip = (frames: AnimClipFrameData[], loop: boolean): AnimClipAssetData => ({+ version: '1.5', type: 'animation-clip', loop, sheet, frames,+ ...(pivot !== null ? { pivot } : {}),+ });++ if (doc.tags.length === 0) {+ clips.push({+ file: claim(stem),+ data: clip(doc.frames.map((_, i) => frameData(i)), true),+ });+ } else {+ for (const tag of doc.tags) {+ // Aseprite counts a tag's plays; a clip only knows whether it repeats. Zero is+ // the editor's "forever", and anything else has an end, which `loop: false` is.+ clips.push({+ file: claim(`${stem}_${fileStem(tag.name)}`),+ data: clip(tagSequence(tag).map(frameData), tag.repeat === 0),+ });+ if (tag.repeat > 1) {+ warnings.push(`tag "${tag.name}" repeats ${tag.repeat} times, which a clip cannot `+ + 'state — it plays once and stops');+ }+ }+ }++ return {+ sheet: { file: sheetFile, bytes: new Uint8Array(PNG.sync.write(png)), width: pageWidth, height: pageHeight },+ settings: {+ filterMode: 'nearest', compress: false,+ sheet: { cellWidth: doc.width, cellHeight: doc.height, margin: 0, spacing: 0 },+ },+ clips,+ warnings,+ };+}++/**+ * The anchor every frame inherits, from the first slice the artist gave a pivot.+ *+ * A slice's pivot is the one place an Aseprite document says where its artwork is+ * held — "the feet", "the hand" — and it is stated in canvas pixels from the+ * top-left, where a clip's anchor is normalized inside the frame with Y up.+ */+function clipPivot(doc: AsepriteDocument, warnings: string[]): { x: number; y: number } | null {+ if (doc.slices.some((s) => s.keys.some((k) => k.center !== null))) {+ warnings.push('a slice carries a 9-slice centre, which belongs to a texture rather than '+ + 'an animation — set the borders on the sheet\'s import settings');+ }+ for (const slice of doc.slices) {+ const key = slice.keys.find((k) => k.pivot !== null);+ if (!key || !key.pivot) continue;+ if (slice.keys.length > 1) {+ warnings.push(`slice "${slice.name}" moves between frames; a clip's anchor is one `+ + 'value, so the first key\'s is used');+ }+ const height = Math.max(1, doc.height);+ return {+ x: (key.x + key.pivot.x) / Math.max(1, doc.width),+ // Measured from the bottom by subtracting first: `1 - y/h` is the same+ // anchor and a worse number, and this one is written into a file.+ y: (height - (key.y + key.pivot.y)) / height,+ };+ }+ return null;+}++/** The extensions this import claims. */+export const ASEPRITE_EXTENSIONS = ['.aseprite', '.ase'];++export function isAsepriteSource(file: string): boolean {+ const dot = file.lastIndexOf('.');+ return dot >= 0 && ASEPRITE_EXTENSIONS.includes(file.slice(dot).toLowerCase());+}diff --git a/pipeline/tests/aseprite-import.test.ts b/pipeline/tests/aseprite-import.test.tsnew file mode 100644index 000000000..b4602cbdf--- /dev/null+++ b/pipeline/tests/aseprite-import.test.ts@@ -0,0 +1,249 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file What a `.aseprite` becomes — the claims a picture of the sheet cannot make.+ *+ * The fixtures are ENCODED (see ./asepriteWriter) rather than checked in as+ * binaries: a blob would make every expectation below a number nobody could check.+ *+ * What carries the import and is invisible in the result: that a frame is the+ * COMPOSITE of the layers the artist left on, that cell N of the sheet is frame+ * N of the file, and that a tag's direction survives as the order its clip plays.+ */+import { describe, it, expect } from 'vitest';+import { PNG } from 'pngjs';+import { importAseprite, isAsepriteSource } from '../src/assets/asepriteImport';+import { writeAseprite, fill, type CelSpec, type FrameSpec } from './asepriteWriter';++/** The sheet, decoded — what a reader of the products actually gets. */+function sheetPixels(bytes: Uint8Array): { width: number; height: number; at: (x: number, y: number) => number[] } {+ const png = PNG.sync.read(Buffer.from(bytes));+ return {+ width: png.width,+ height: png.height,+ at: (x, y) => Array.from(png.data.subarray((y * png.width + x) * 4, (y * png.width + x) * 4 + 4)),+ };+}++// ---------------------------------------------------------------------------++describe('isAsepriteSource', () => {+ it('claims .aseprite and .ase, whatever the case, and nothing else', () => {+ expect(isAsepriteSource('art/Hero.ASEPRITE')).toBe(true);+ expect(isAsepriteSource('hero.ase')).toBe(true);+ expect(isAsepriteSource('hero.png')).toBe(false);+ expect(isAsepriteSource('aseprite')).toBe(false);+ });+});++describe('importAseprite', () => {+ it('composites the layers the artist left on, in stack order', () => {+ const doc = writeAseprite({+ width: 2, height: 1,+ layers: [{ name: 'bg' }, { name: 'fg' }, { name: 'off', visible: false }],+ frames: [{ duration: 100, cels: [+ { layer: 0, x: 0, y: 0, w: 2, h: 1, pixels: fill(2, 1, [255, 0, 0, 255]) },+ { layer: 1, x: 1, y: 0, w: 1, h: 1, pixels: fill(1, 1, [0, 0, 255, 255]) },+ { layer: 2, x: 0, y: 0, w: 2, h: 1, pixels: fill(2, 1, [0, 255, 0, 255]) },+ ] }],+ });+ const sheet = sheetPixels(importAseprite(doc, 'hero').sheet.bytes);+ expect(sheet.at(0, 0)).toEqual([255, 0, 0, 255]);+ expect(sheet.at(1, 0)).toEqual([0, 0, 255, 255]);+ });++ it('blends a half-transparent layer the way the editor does', () => {+ const doc = writeAseprite({+ width: 1, height: 1,+ layers: [{ name: 'bg' }, { name: 'fg', opacity: 128 }],+ frames: [{ duration: 100, cels: [+ { layer: 0, x: 0, y: 0, w: 1, h: 1, pixels: [0, 0, 0, 255] },+ { layer: 1, x: 0, y: 0, w: 1, h: 1, pixels: [255, 255, 255, 255] },+ ] }],+ });+ // 128/255 of the way from black to white, rounded as Aseprite rounds it.+ expect(sheetPixels(importAseprite(doc, 'x').sheet.bytes).at(0, 0)).toEqual([128, 128, 128, 255]);+ });++ it('hides everything inside a group the artist turned off', () => {+ const doc = writeAseprite({+ width: 1, height: 1,+ layers: [+ { name: 'shown', group: true, childLevel: 0 },+ { name: 'a', childLevel: 1 },+ { name: 'hidden', group: true, childLevel: 0, visible: false },+ { name: 'b', childLevel: 1 },+ ],+ frames: [{ duration: 100, cels: [+ { layer: 1, x: 0, y: 0, w: 1, h: 1, pixels: [10, 20, 30, 255] },+ { layer: 3, x: 0, y: 0, w: 1, h: 1, pixels: [200, 200, 200, 255] },+ ] }],+ });+ expect(sheetPixels(importAseprite(doc, 'x').sheet.bytes).at(0, 0)).toEqual([10, 20, 30, 255]);+ });++ it('lays frames out as sheet cells, in the order the clip addresses them', () => {+ const frame = (rgba: number[]): FrameSpec =>+ ({ duration: 50, cels: [{ layer: 0, x: 0, y: 0, w: 2, h: 2, pixels: fill(2, 2, rgba) }] });+ const doc = writeAseprite({+ width: 2, height: 2,+ layers: [{ name: 'a' }],+ frames: [frame([255, 0, 0, 255]), frame([0, 255, 0, 255]), frame([0, 0, 255, 255])],+ });+ const result = importAseprite(doc, 'walk');+ const sheet = sheetPixels(result.sheet.bytes);+ expect([sheet.width, sheet.height]).toEqual([6, 2]);+ expect(sheet.at(0, 0)).toEqual([255, 0, 0, 255]);+ expect(sheet.at(2, 0)).toEqual([0, 255, 0, 255]);+ expect(sheet.at(4, 0)).toEqual([0, 0, 255, 255]);++ const clip = result.clips[0]!.data;+ expect(clip.sheet).toMatchObject({ cellWidth: 2, cellHeight: 2, margin: 0, spacing: 0, pageWidth: 6, pageHeight: 2 });+ expect(clip.frames.map((f) => f.cell)).toEqual([0, 1, 2]);+ });++ it('wraps to a second row rather than exceed the sheet width', () => {+ const frame = (): FrameSpec =>+ ({ duration: 50, cels: [{ layer: 0, x: 0, y: 0, w: 1, h: 1, pixels: [1, 2, 3, 255] }] });+ const doc = writeAseprite({+ width: 2100, height: 1,+ layers: [{ name: 'a' }],+ frames: [frame(), frame()],+ });+ const result = importAseprite(doc, 'wide');+ expect([result.sheet.width, result.sheet.height]).toEqual([2100, 2]);+ });++ it('keeps each frame\'s own timing, in seconds', () => {+ const cel = (): CelSpec => ({ layer: 0, x: 0, y: 0, w: 1, h: 1, pixels: [9, 9, 9, 255] });+ const doc = writeAseprite({+ width: 1, height: 1,+ layers: [{ name: 'a' }],+ frames: [{ duration: 100, cels: [cel()] }, { duration: 250, cels: [cel()] }],+ });+ expect(importAseprite(doc, 'x').clips[0]!.data.frames.map((f) => f.duration)).toEqual([0.1, 0.25]);+ });++ it('gives every tag its own clip, playing the direction the tag states', () => {+ const cel = (): CelSpec => ({ layer: 0, x: 0, y: 0, w: 1, h: 1, pixels: [9, 9, 9, 255] });+ const doc = writeAseprite({+ width: 1, height: 1,+ layers: [{ name: 'a' }],+ frames: Array.from({ length: 4 }, () => ({ duration: 100, cels: [cel()] })),+ tags: [+ { name: 'walk', from: 0, to: 2, direction: 0 },+ { name: 'back', from: 0, to: 2, direction: 1 },+ { name: 'breathe', from: 0, to: 3, direction: 2 },+ ],+ });+ const clips = importAseprite(doc, 'hero').clips;+ expect(clips.map((c) => c.file)).toEqual(['hero_walk.esanim', 'hero_back.esanim', 'hero_breathe.esanim']);+ expect(clips[0]!.data.frames.map((f) => f.cell)).toEqual([0, 1, 2]);+ expect(clips[1]!.data.frames.map((f) => f.cell)).toEqual([2, 1, 0]);+ // A ping-pong turns around on its ends rather than repeating them.+ expect(clips[2]!.data.frames.map((f) => f.cell)).toEqual([0, 1, 2, 3, 2, 1]);+ });++ it('loops a tag that plays forever and stops one that counts its plays', () => {+ const cel = (): CelSpec => ({ layer: 0, x: 0, y: 0, w: 1, h: 1, pixels: [9, 9, 9, 255] });+ const doc = writeAseprite({+ width: 1, height: 1,+ layers: [{ name: 'a' }],+ frames: [{ duration: 100, cels: [cel()] }],+ tags: [+ { name: 'idle', from: 0, to: 0, direction: 0, repeat: 0 },+ { name: 'hit', from: 0, to: 0, direction: 0, repeat: 1 },+ ],+ });+ const clips = importAseprite(doc, 'x').clips;+ expect(clips[0]!.data.loop).toBe(true);+ expect(clips[1]!.data.loop).toBe(false);+ });++ it('covers every frame with one clip when the file has no tags', () => {+ const cel = (): CelSpec => ({ layer: 0, x: 0, y: 0, w: 1, h: 1, pixels: [9, 9, 9, 255] });+ const doc = writeAseprite({+ width: 1, height: 1,+ layers: [{ name: 'a' }],+ frames: [{ duration: 100, cels: [cel()] }, { duration: 100, cels: [cel()] }],+ });+ const clips = importAseprite(doc, 'idle').clips;+ expect(clips.map((c) => c.file)).toEqual(['idle.esanim']);+ expect(clips[0]!.data.frames.map((f) => f.cell)).toEqual([0, 1]);+ });++ it('resolves an indexed palette, and the transparent index it names', () => {+ const doc = writeAseprite({+ width: 3, height: 1, depth: 8, transparentIndex: 3,+ palette: [[0, 0, 0, 255], [255, 0, 0, 255], [0, 255, 0, 255], [1, 2, 3, 255]],+ layers: [{ name: 'a' }],+ frames: [{ duration: 100, cels: [{ layer: 0, x: 0, y: 0, w: 3, h: 1, pixels: [1, 2, 3] }] }],+ });+ const sheet = sheetPixels(importAseprite(doc, 'x').sheet.bytes);+ expect(sheet.at(0, 0)).toEqual([255, 0, 0, 255]);+ expect(sheet.at(1, 0)).toEqual([0, 255, 0, 255]);+ // Index 3 is the sprite's transparent one — a hole, not the palette's colour.+ expect(sheet.at(2, 0)[3]).toBe(0);+ });++ it('paints the transparent index on a background layer, where it is a colour', () => {+ const doc = writeAseprite({+ width: 1, height: 1, depth: 8, transparentIndex: 0,+ palette: [[1, 2, 3, 255], [9, 9, 9, 255]],+ layers: [{ name: 'Background', background: true }],+ frames: [{ duration: 100, cels: [{ layer: 0, x: 0, y: 0, w: 1, h: 1, pixels: [0] }] }],+ });+ expect(sheetPixels(importAseprite(doc, 'x').sheet.bytes).at(0, 0)).toEqual([1, 2, 3, 255]);+ });++ it('draws a linked cel with the pixels it links to', () => {+ const doc = writeAseprite({+ width: 1, height: 1,+ layers: [{ name: 'a' }],+ frames: [+ { duration: 100, cels: [{ layer: 0, x: 0, y: 0, w: 1, h: 1, pixels: [7, 8, 9, 255] }] },+ { duration: 100, cels: [{ layer: 0, x: 0, y: 0, w: 1, h: 1, pixels: [], linkTo: 0 }] },+ ],+ });+ const sheet = sheetPixels(importAseprite(doc, 'x').sheet.bytes);+ expect(sheet.at(0, 0)).toEqual([7, 8, 9, 255]);+ expect(sheet.at(1, 0)).toEqual([7, 8, 9, 255]);+ });++ it('asks for the import settings pixel art needs, and the grid it was cut on', () => {+ const doc = writeAseprite({+ width: 8, height: 16,+ layers: [{ name: 'a' }],+ frames: [{ duration: 100, cels: [{ layer: 0, x: 0, y: 0, w: 1, h: 1, pixels: [1, 1, 1, 255] }] }],+ });+ expect(importAseprite(doc, 'x').settings).toEqual({+ filterMode: 'nearest', compress: false,+ sheet: { cellWidth: 8, cellHeight: 16, margin: 0, spacing: 0 },+ });+ });++ it('takes a slice pivot as the clip\'s anchor, in the clip\'s own space', () => {+ const doc = writeAseprite({+ width: 10, height: 20,+ layers: [{ name: 'a' }],+ frames: [{ duration: 100, cels: [{ layer: 0, x: 0, y: 0, w: 1, h: 1, pixels: [1, 1, 1, 255] }] }],+ slices: [{ name: 'feet', x: 2, y: 4, w: 6, h: 12, pivot: { x: 3, y: 12 } }],+ });+ // The slice says the anchor is 5px across and 16px down from the top-left;+ // a clip anchors from the bottom-left, normalized.+ expect(importAseprite(doc, 'x').clips[0]!.data.pivot).toEqual({ x: 0.5, y: 0.2 });+ });++ it('says so when a tilemap layer cannot be composited', () => {+ const doc = writeAseprite({+ width: 1, height: 1,+ layers: [{ name: 'map', tilemap: true }],+ frames: [{ duration: 100, cels: [] }],+ });+ expect(importAseprite(doc, 'x').warnings.join(' ')).toMatch(/tilemap/i);+ });++ it('refuses a file that is not one', () => {+ expect(() => importAseprite(new Uint8Array(200), 'x')).toThrow(/not an Aseprite file/);+ });+});diff --git a/pipeline/tests/asepriteWriter.ts b/pipeline/tests/asepriteWriter.tsnew file mode 100644index 000000000..955f48d02--- /dev/null+++ b/pipeline/tests/asepriteWriter.ts@@ -0,0 +1,162 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file A minimal Aseprite writer for tests: the chunks the import reads, and+ * nothing else.+ *+ * Fixtures are encoded rather than checked in as binaries, for the reason+ * the PSD test writes its own — a blob would make every expectation a+ * number nobody could check. It states the layout independently of the+ * reader (it shares no constant with it), so a reader that drifts off the+ * published format cannot drag the fixture along with it.+ */+import { deflateSync } from 'node:zlib';++class Bytes {+ private parts: number[] = [];+ u8(v: number): this { this.parts.push(v & 0xff); return this; }+ u16(v: number): this { return this.u8(v).u8(v >> 8); }+ i16(v: number): this { return this.u16(v < 0 ? v + 0x10000 : v); }+ u32(v: number): this { return this.u16(v).u16(v >>> 16); }+ i32(v: number): this { return this.u32(v < 0 ? v + 0x100000000 : v); }+ zeros(n: number): this { for (let i = 0; i < n; i++) this.u8(0); return this; }+ str(s: string): this {+ const b = Buffer.from(s, 'utf8');+ this.u16(b.length);+ for (const v of b) this.u8(v);+ return this;+ }+ raw(bytes: Uint8Array | Buffer): this { for (const v of bytes) this.u8(v); return this; }+ get length(): number { return this.parts.length; }+ toBuffer(): Buffer { return Buffer.from(this.parts); }+}++function chunk(type: number, body: Bytes): Bytes {+ return new Bytes().u32(body.length + 6).u16(type).raw(body.toBuffer());+}++export interface LayerSpec {+ name: string;+ visible?: boolean;+ group?: boolean;+ childLevel?: number;+ opacity?: number;+ blend?: number;+ background?: boolean;+ tilemap?: boolean;+}++export interface CelSpec {+ layer: number;+ x: number;+ y: number;+ w: number;+ h: number;+ /** RGBA quadruples for depth 32, palette indices for depth 8. */+ pixels: number[];+ opacity?: number;+ zIndex?: number;+ /** Frame this cel takes its pixels from, instead of carrying its own. */+ linkTo?: number;+}++export interface FrameSpec { duration: number; cels: CelSpec[] }++export interface TagSpec { name: string; from: number; to: number; direction: number; repeat?: number }++export interface SliceSpec {+ name: string;+ x: number; y: number; w: number; h: number;+ pivot?: { x: number; y: number };+ center?: { x: number; y: number; w: number; h: number };+}++export interface DocSpec {+ width: number;+ height: number;+ depth?: 32 | 16 | 8;+ transparentIndex?: number;+ palette?: number[][];+ layers: LayerSpec[];+ frames: FrameSpec[];+ tags?: TagSpec[];+ slices?: SliceSpec[];+}++export function writeAseprite(doc: DocSpec): Uint8Array {+ const depth = doc.depth ?? 32;+ const body = new Bytes();++ for (const [index, frame] of doc.frames.entries()) {+ const chunks: Bytes[] = [];++ if (index === 0) {+ if (doc.palette) {+ const p = new Bytes().u32(doc.palette.length).u32(0).u32(doc.palette.length - 1).zeros(8);+ for (const [r, g, b, a] of doc.palette) p.u16(0).u8(r!).u8(g!).u8(b!).u8(a ?? 255);+ chunks.push(chunk(0x2019, p));+ }+ for (const layer of doc.layers) {+ chunks.push(chunk(0x2004, new Bytes()+ .u16((layer.visible === false ? 0 : 1) | (layer.background === true ? 8 : 0))+ .u16(layer.group === true ? 1 : layer.tilemap === true ? 2 : 0)+ .u16(layer.childLevel ?? 0)+ .u16(0).u16(0)+ .u16(layer.blend ?? 0)+ .u8(layer.opacity ?? 255)+ .zeros(3)+ .str(layer.name)));+ }+ for (const tag of doc.tags ?? []) {+ const t = new Bytes().u16(1).zeros(8)+ .u16(tag.from).u16(tag.to).u8(tag.direction).u16(tag.repeat ?? 0)+ .zeros(6).zeros(3).u8(0).str(tag.name);+ chunks.push(chunk(0x2018, t));+ }+ for (const slice of doc.slices ?? []) {+ const flags = (slice.center ? 1 : 0) | (slice.pivot ? 2 : 0);+ const s = new Bytes().u32(1).u32(flags).u32(0).str(slice.name)+ .u32(0).i32(slice.x).i32(slice.y).u32(slice.w).u32(slice.h);+ if (slice.center) s.i32(slice.center.x).i32(slice.center.y).u32(slice.center.w).u32(slice.center.h);+ if (slice.pivot) s.i32(slice.pivot.x).i32(slice.pivot.y);+ chunks.push(chunk(0x2022, s));+ }+ }++ for (const cel of frame.cels) {+ const head = new Bytes()+ .u16(cel.layer).i16(cel.x).i16(cel.y).u8(cel.opacity ?? 255)+ .u16(cel.linkTo !== undefined ? 1 : 2)+ .i16(cel.zIndex ?? 0).zeros(5);+ if (cel.linkTo !== undefined) {+ head.u16(cel.linkTo);+ } else {+ head.u16(cel.w).u16(cel.h).raw(deflateSync(Buffer.from(cel.pixels)));+ }+ chunks.push(chunk(0x2005, head));+ }++ const payload = new Bytes();+ for (const c of chunks) payload.raw(c.toBuffer());+ body+ .u32(payload.length + 16).u16(0xf1fa).u16(0).u16(frame.duration).zeros(2).u32(chunks.length)+ .raw(payload.toBuffer());+ }++ const header = new Bytes()+ .u32(body.length + 128).u16(0xa5e0).u16(doc.frames.length)+ .u16(doc.width).u16(doc.height).u16(depth)+ .u32(1).u16(100).u32(0).u32(0)+ .u8(doc.transparentIndex ?? 0).zeros(3)+ .u16(doc.palette?.length ?? 0)+ .u8(1).u8(1)+ .i16(0).i16(0).u16(16).u16(16)+ .zeros(84);+ if (header.length !== 128) throw new Error(`header is ${header.length} bytes, not 128`);++ return new Uint8Array(Buffer.concat([header.toBuffer(), body.toBuffer()]));+}++/** RGBA pixels of a `w`x`h` block, one colour. */+export const fill = (w: number, h: number, rgba: number[]): number[] =>+ Array.from({ length: w * h }, () => rgba).flat();diff --git a/tools/assetMetaTable.js b/tools/assetMetaTable.jsindex 59b700d77..e3348d352 100644--- a/tools/assetMetaTable.js+++ b/tools/assetMetaTable.js@@ -74,6 +74,10 @@ export const EXT_TO_TYPE = Object.freeze({// prefab that stacks them, and those are what a scene references.'.psd': 'layered','.psb': 'layered',+ // Its animated cousin: an Aseprite document is frames and tags, so it+ // produces a sprite sheet plus one clip per tag instead of a stack.+ '.aseprite': 'animated',+ '.ase': 'animated','.esenv': 'environment','.esmesh': 'mesh','.esanim': 'animclip',