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(sdk): .esanim sheet slicing - grid cells become first-class flipbook frames
esengine428908182bf6
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex e82d3a664..9f0003861 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -1,7 +1,7 @@# API surface — esengine/index<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 1131 stable · 17 beta · 1 deprecated+Symbols: 1140 stable · 17 beta · 1 deprecated## ABI_LAYOUT_HASH — const```@@ -13,6 +13,11 @@ Symbols: 1131 stable · 17 beta · 1 deprecatedreadonly AnchorAxis[]```+## ANIM_CLIP_FORMAT_VERSION — const+```+"1.2"+```+## ActionDef — interface```bindings: Binding[]@@ -188,10 +193,30 @@ v: AnchorAxisfps: number | undefinedframes: AnimClipFrameData[]loop: boolean | undefined+sheet: AnimClipSheetData | undefinedtype: "animation-clip"version: string```+## AnimClipFrameData — interface+```+atlasFrame: { x: number; y: number; width: number; height: number; pageWidth: number; pageHeight: number; } | undefined+cell: number | undefined+duration: number | undefined+texture: string | undefined+```++## AnimClipSheetData — interface+```+cellHeight: number+cellWidth: number+margin: number+pageHeight: number+pageWidth: number+spacing: number+texture: string+```+## AnimFramesTrack — interface```childPath: string@@ -7049,6 +7074,21 @@ AiRegistry<AiContext>(preset: AnchorPreset): AnchorFields```+## animClipCellRect — function+```+(sheet: AnimClipSheetData, cell: number): { x: number; y: number; width: number; height: number; }+```++## animClipSheetCols — function+```+(sheet: AnimClipSheetData): number+```++## animClipSheetRows — function+```+(sheet: AnimClipSheetData): number+```+## animationPlugin — const```AnimationPlugin@@ -7294,6 +7334,11 @@ BtPluginPlugin```+## createAnimClip — function+```+(texture: string, cellWidth: number, cellHeight: number, pageWidth: number, pageHeight: number): AnimClipAssetData+```+## createBtRunState — function```(): BtRunState@@ -8124,6 +8169,11 @@ NavPlugin(flags: TileFlags): Perm```+## parseAnimClipAsset — function+```+(raw: any): AnimClipAssetData+```+## parseAnimClipData — function```(clipPath: string, data: AnimClipAssetData, textureHandles: Map<string, number>): SpriteAnimClip@@ -8484,6 +8534,11 @@ Plugin(ox: number, oy: number, facing: number, tx: number, ty: number, range: number, halfFov: number, isBlocked?: (ox: number, oy: number, tx: number, ty: number) => boolean): SenseResult```+## serializeAnimClip — function+```+(asset: AnimClipAssetData): Record<string, unknown>+```+## serializeScene — function```(world: World, sceneName?: string): SceneDatadiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex 9251a905a..daab4de36 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -1,13 +1,18 @@# API surface — esengine/index.node<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 1130 stable · 19 beta · 1 deprecated+Symbols: 1139 stable · 19 beta · 1 deprecated## ANCHOR_AXES — const```readonly AnchorAxis[]```+## ANIM_CLIP_FORMAT_VERSION — const+```+"1.2"+```+## ActionDef — interface```bindings: Binding[]@@ -183,10 +188,30 @@ v: AnchorAxisfps: number | undefinedframes: AnimClipFrameData[]loop: boolean | undefined+sheet: AnimClipSheetData | undefinedtype: "animation-clip"version: string```+## AnimClipFrameData — interface+```+atlasFrame: { x: number; y: number; width: number; height: number; pageWidth: number; pageHeight: number; } | undefined+cell: number | undefined+duration: number | undefined+texture: string | undefined+```++## AnimClipSheetData — interface+```+cellHeight: number+cellWidth: number+margin: number+pageHeight: number+pageWidth: number+spacing: number+texture: string+```+## AnimFramesTrack — interface```childPath: string@@ -7044,6 +7069,21 @@ AiRegistry<AiContext>(preset: AnchorPreset): AnchorFields```+## animClipCellRect — function+```+(sheet: AnimClipSheetData, cell: number): { x: number; y: number; width: number; height: number; }+```++## animClipSheetCols — function+```+(sheet: AnimClipSheetData): number+```++## animClipSheetRows — function+```+(sheet: AnimClipSheetData): number+```+## animationPlugin — const```AnimationPlugin@@ -7289,6 +7329,11 @@ BtPluginPlugin```+## createAnimClip — function+```+(texture: string, cellWidth: number, cellHeight: number, pageWidth: number, pageHeight: number): AnimClipAssetData+```+## createBtRunState — function```(): BtRunState@@ -8129,6 +8174,11 @@ NodePlatformAdapter(flags: TileFlags): Perm```+## parseAnimClipAsset — function+```+(raw: any): AnimClipAssetData+```+## parseAnimClipData — function```(clipPath: string, data: AnimClipAssetData, textureHandles: Map<string, number>): SpriteAnimClip@@ -8489,6 +8539,11 @@ Plugin(ox: number, oy: number, facing: number, tx: number, ty: number, range: number, halfFov: number, isBlocked?: (ox: number, oy: number, tx: number, ty: number) => boolean): SenseResult```+## serializeAnimClip — function+```+(asset: AnimClipAssetData): Record<string, unknown>+```+## serializeScene — function```(world: World, sceneName?: string): SceneDatadiff --git a/sdk/src/animation/AnimClipLoader.ts b/sdk/src/animation/AnimClipLoader.tsindex 9c7d2a5cc..1d307211e 100644--- a/sdk/src/animation/AnimClipLoader.ts+++ b/sdk/src/animation/AnimClipLoader.ts@@ -2,17 +2,39 @@// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team/*** @file AnimClipLoader.ts- * @brief .esanim asset loading and parsing+ * @brief .esanim asset format: parsing, serialization, and sheet-grid math*/import type { SpriteAnimClip, SpriteAnimFrame } from './SpriteAnimator';+import { log } from '../logger';// =============================================================================// .esanim File Format// =============================================================================-export interface AnimClipFrameData {+export const ANIM_CLIP_FORMAT_VERSION = '1.2';++/**+ * Sprite-sheet slicing grid. When present, frames may reference grid cells+ * instead of per-frame textures; all cell frames share `texture`.+ * `pageWidth`/`pageHeight` are baked by the editor from the image's natural+ * size (UV normalization needs them; the runtime never reads the image).+ */+export interface AnimClipSheetData {texture: string;+ cellWidth: number;+ cellHeight: number;+ margin: number;+ spacing: number;+ pageWidth: number;+ pageHeight: number;+}++export interface AnimClipFrameData {+ /** Per-frame texture ref; absent on sheet-cell frames. */+ texture?: string;+ /** Sheet cell index (row-major, 0-based); requires a `sheet` section. */+ cell?: number;duration?: number;atlasFrame?: {x: number;@@ -29,17 +51,142 @@ export interface AnimClipAssetData {type: 'animation-clip';fps?: number;loop?: boolean;+ sheet?: AnimClipSheetData;frames: AnimClipFrameData[];}// =============================================================================-// Parsing+// Sheet grid math+// =============================================================================++/** Columns the sheet grid fits (same stride math as the tileset atlas grid). */+export function animClipSheetCols(sheet: AnimClipSheetData): number {+ const stride = sheet.cellWidth + sheet.spacing;+ return stride > 0 ? Math.max(1, Math.floor((sheet.pageWidth - sheet.margin + sheet.spacing) / stride)) : 1;+}++/** Rows the sheet grid fits. At least 1 so cell 0 always resolves. */+export function animClipSheetRows(sheet: AnimClipSheetData): number {+ const stride = sheet.cellHeight + sheet.spacing;+ return stride > 0 ? Math.max(1, Math.floor((sheet.pageHeight - sheet.margin + sheet.spacing) / stride)) : 1;+}++/** Pixel rect of a grid cell, clamped into the valid cell range. */+export function animClipCellRect(+ sheet: AnimClipSheetData,+ cell: number,+): { x: number; y: number; width: number; height: number } {+ const cols = animClipSheetCols(sheet);+ const rows = animClipSheetRows(sheet);+ const clamped = Math.min(Math.max(0, Math.floor(cell)), cols * rows - 1);+ const col = clamped % cols;+ const row = Math.floor(clamped / cols);+ return {+ x: sheet.margin + col * (sheet.cellWidth + sheet.spacing),+ y: sheet.margin + row * (sheet.cellHeight + sheet.spacing),+ width: sheet.cellWidth,+ height: sheet.cellHeight,+ };+}++// =============================================================================+// Parsing / serialization// =============================================================================const DEFAULT_FPS = 12;+function posInt(v: unknown, fallback: number): number {+ return typeof v === 'number' && Number.isInteger(v) && v > 0 ? v : fallback;+}++function nonNeg(v: unknown, fallback: number): number {+ return typeof v === 'number' && Number.isFinite(v) && v >= 0 ? v : fallback;+}++/** Parse arbitrary JSON into a normalized {@link AnimClipAssetData} (tolerant of missing fields). */+export function parseAnimClipAsset(raw: any): AnimClipAssetData {+ let sheet: AnimClipSheetData | undefined;+ const rs = raw?.sheet;+ if (rs && typeof rs.texture === 'string' && rs.texture) {+ sheet = {+ texture: rs.texture,+ cellWidth: posInt(rs.cellWidth, 32),+ cellHeight: posInt(rs.cellHeight, 32),+ margin: nonNeg(rs.margin, 0),+ spacing: nonNeg(rs.spacing, 0),+ pageWidth: posInt(rs.pageWidth, 1),+ pageHeight: posInt(rs.pageHeight, 1),+ };+ }+ const frames: AnimClipFrameData[] = [];+ for (const f of Array.isArray(raw?.frames) ? raw.frames : []) {+ if (!f) continue;+ const duration = typeof f.duration === 'number' && f.duration > 0 ? f.duration : undefined;+ if (sheet && typeof f.cell === 'number' && Number.isInteger(f.cell) && f.cell >= 0) {+ frames.push({ cell: f.cell, ...(duration !== undefined ? { duration } : {}) });+ } else if (typeof f.texture === 'string' && f.texture) {+ const frame: AnimClipFrameData = { texture: f.texture };+ if (duration !== undefined) frame.duration = duration;+ const af = f.atlasFrame;+ if (af && [af.x, af.y, af.width, af.height, af.pageWidth, af.pageHeight]+ .every((n: unknown) => typeof n === 'number' && Number.isFinite(n))) {+ frame.atlasFrame = {+ x: af.x, y: af.y, width: af.width, height: af.height,+ pageWidth: af.pageWidth, pageHeight: af.pageHeight,+ };+ }+ frames.push(frame);+ }+ }+ return {+ version: typeof raw?.version === 'string' ? raw.version : ANIM_CLIP_FORMAT_VERSION,+ type: 'animation-clip',+ fps: posInt(raw?.fps, DEFAULT_FPS),+ loop: typeof raw?.loop === 'boolean' ? raw.loop : true,+ ...(sheet ? { sheet } : {}),+ frames,+ };+}++/** Serialize an {@link AnimClipAssetData} to a plain JSON-ready object (drops empty/undefined). */+export function serializeAnimClip(asset: AnimClipAssetData): Record<string, unknown> {+ return {+ version: asset.version || ANIM_CLIP_FORMAT_VERSION,+ type: 'animation-clip',+ fps: asset.fps ?? DEFAULT_FPS,+ loop: asset.loop ?? true,+ ...(asset.sheet ? { sheet: { ...asset.sheet } } : {}),+ frames: asset.frames.map(f => ({ ...f })),+ };+}++/** A fresh sheet-sliced clip over a texture (no frames yet). */+export function createAnimClip(+ texture: string,+ cellWidth: number,+ cellHeight: number,+ pageWidth: number,+ pageHeight: number,+): AnimClipAssetData {+ return {+ version: ANIM_CLIP_FORMAT_VERSION,+ type: 'animation-clip',+ fps: DEFAULT_FPS,+ loop: true,+ sheet: { texture, cellWidth, cellHeight, margin: 0, spacing: 0, pageWidth, pageHeight },+ frames: [],+ };+}++// =============================================================================+// Runtime clip resolution+// =============================================================================+export function extractAnimClipTexturePaths(data: AnimClipAssetData): string[] {const paths = new Set<string>();+ if (data.sheet?.texture) {+ paths.add(data.sheet.texture);+ }for (const frame of data.frames) {if (frame.texture) {paths.add(frame.texture);@@ -48,30 +195,53 @@ export function extractAnimClipTexturePaths(data: AnimClipAssetData): string[] {return Array.from(paths);}+function uvFromRect(+ rect: { x: number; y: number; width: number; height: number },+ pageWidth: number,+ pageHeight: number,+): Pick<SpriteAnimFrame, 'uvOffset' | 'uvScale'> {+ return {+ uvOffset: {+ x: rect.x / pageWidth,+ y: 1.0 - (rect.y + rect.height) / pageHeight,+ },+ uvScale: {+ x: rect.width / pageWidth,+ y: rect.height / pageHeight,+ },+ };+}+export function parseAnimClipData(clipPath: string,data: AnimClipAssetData,textureHandles: Map<string, number>,): SpriteAnimClip {+ const sheet = data.sheet;+ const cellCount = sheet ? animClipSheetCols(sheet) * animClipSheetRows(sheet) : 0;return {name: clipPath,fps: data.fps ?? DEFAULT_FPS,loop: data.loop ?? true,frames: data.frames.map(f => {+ if (sheet && f.cell !== undefined) {+ if (f.cell >= cellCount) {+ log.warn('asset', `${clipPath}: frame cell ${f.cell} outside the ${cellCount}-cell sheet grid; clamped`);+ }+ const frame: SpriteAnimFrame = {+ texture: textureHandles.get(sheet.texture) ?? 0,+ duration: f.duration,+ ...uvFromRect(animClipCellRect(sheet, f.cell), sheet.pageWidth, sheet.pageHeight),+ };+ return frame;+ }const frame: SpriteAnimFrame = {- texture: textureHandles.get(f.texture) ?? 0,+ texture: textureHandles.get(f.texture ?? '') ?? 0,duration: f.duration,};if (f.atlasFrame) {const af = f.atlasFrame;- frame.uvOffset = {- x: af.x / af.pageWidth,- y: 1.0 - (af.y + af.height) / af.pageHeight,- };- frame.uvScale = {- x: af.width / af.pageWidth,- y: af.height / af.pageHeight,- };+ Object.assign(frame, uvFromRect(af, af.pageWidth, af.pageHeight));}return frame;}),diff --git a/sdk/src/animation/index.ts b/sdk/src/animation/index.tsindex c4d9a5c52..63ac88c54 100644--- a/sdk/src/animation/index.ts+++ b/sdk/src/animation/index.ts@@ -84,6 +84,15 @@ export {export {parseAnimClipData,+ parseAnimClipAsset,+ serializeAnimClip,+ createAnimClip,extractAnimClipTexturePaths,+ animClipSheetCols,+ animClipSheetRows,+ animClipCellRect,+ ANIM_CLIP_FORMAT_VERSION,type AnimClipAssetData,+ type AnimClipFrameData,+ type AnimClipSheetData,} from './AnimClipLoader';diff --git a/sdk/src/asset/loaders/AnimClipAssetLoader.ts b/sdk/src/asset/loaders/AnimClipAssetLoader.tsindex 3ec84700d..6b876f43b 100644--- a/sdk/src/asset/loaders/AnimClipAssetLoader.ts+++ b/sdk/src/asset/loaders/AnimClipAssetLoader.ts@@ -1,7 +1,7 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Teamimport type { AssetLoader, LoadContext, AnimClipResult } from '../AssetLoader';-import { extractAnimClipTexturePaths, parseAnimClipData, type AnimClipAssetData } from '../../animation/AnimClipLoader';+import { extractAnimClipTexturePaths, parseAnimClipAsset, parseAnimClipData } from '../../animation/AnimClipLoader';import { log } from '../../logger';export class AnimClipAssetLoader implements AssetLoader<AnimClipResult> {@@ -11,7 +11,7 @@ export class AnimClipAssetLoader implements AssetLoader<AnimClipResult> {async load(path: string, ctx: LoadContext): Promise<AnimClipResult> {const buildPath = ctx.catalog.getBuildPath(path);const text = await ctx.loadText(buildPath);- const data: AnimClipAssetData = JSON.parse(text);+ const data = parseAnimClipAsset(JSON.parse(text));const texturePaths = extractAnimClipTexturePaths(data);const textureHandles = new Map<string, number>();diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.tsindex 0194d5e79..793ae923a 100644--- a/sdk/src/core-content.ts+++ b/sdk/src/core-content.ts@@ -262,8 +262,17 @@ export {type SpriteAnimEvent,type SpriteAnimEventHandler,parseAnimClipData,+ parseAnimClipAsset,+ serializeAnimClip,+ createAnimClip,extractAnimClipTexturePaths,+ animClipSheetCols,+ animClipSheetRows,+ animClipCellRect,+ ANIM_CLIP_FORMAT_VERSION,type AnimClipAssetData,+ type AnimClipFrameData,+ type AnimClipSheetData,TweenGroup,TweenSequence,type Completable,diff --git a/sdk/tests/anim-clip-asset.test.ts b/sdk/tests/anim-clip-asset.test.tsindex 443a46d12..6d4263dd8 100644--- a/sdk/tests/anim-clip-asset.test.ts+++ b/sdk/tests/anim-clip-asset.test.ts@@ -8,8 +8,15 @@ import {} from '../src/assetTypes';import {parseAnimClipData,+ parseAnimClipAsset,+ serializeAnimClip,+ createAnimClip,extractAnimClipTexturePaths,+ animClipSheetCols,+ animClipSheetRows,+ animClipCellRect,type AnimClipAssetData,+ type AnimClipSheetData,} from '../src/animation/AnimClipLoader';import {getComponentAssetFields,@@ -163,3 +170,118 @@ describe('parseAnimClipData', () => {expect(paths.length).toBe(2); // deduplicated});});++// =============================================================================+// Sheet grid (format 1.2)+// =============================================================================++const SHEET: AnimClipSheetData = {+ texture: '@uuid:sheet',+ cellWidth: 32,+ cellHeight: 48,+ margin: 2,+ spacing: 1,+ pageWidth: 134, // 2 + 4*(32+1) = 134 → exactly 4 columns+ pageHeight: 100, // 2 + 2*(48+1) = 100 → exactly 2 rows+};++describe('sheet grid math', () => {+ it('derives columns and rows honoring margin and spacing', () => {+ expect(animClipSheetCols(SHEET)).toBe(4);+ expect(animClipSheetRows(SHEET)).toBe(2);+ });++ it('computes row-major cell rects', () => {+ expect(animClipCellRect(SHEET, 0)).toEqual({ x: 2, y: 2, width: 32, height: 48 });+ expect(animClipCellRect(SHEET, 3)).toEqual({ x: 2 + 3 * 33, y: 2, width: 32, height: 48 });+ expect(animClipCellRect(SHEET, 4)).toEqual({ x: 2, y: 2 + 49, width: 32, height: 48 });+ });++ it('clamps out-of-range cells to the last valid cell', () => {+ expect(animClipCellRect(SHEET, 99)).toEqual(animClipCellRect(SHEET, 7));+ expect(animClipCellRect(SHEET, -5)).toEqual(animClipCellRect(SHEET, 0));+ });+});++describe('parseAnimClipData with sheet cells', () => {+ const data: AnimClipAssetData = {+ version: '1.2',+ type: 'animation-clip',+ fps: 10,+ loop: true,+ sheet: SHEET,+ frames: [{ cell: 0 }, { cell: 5, duration: 0.2 }],+ };++ it('resolves all cell frames to the shared sheet texture handle', () => {+ const clip = parseAnimClipData('run.esanim', data, new Map([['@uuid:sheet', 7]]));+ expect(clip.frames[0].texture).toBe(7);+ expect(clip.frames[1].texture).toBe(7);+ expect(clip.frames[1].duration).toBe(0.2);+ });++ it('derives flipY-space uv from the cell rect', () => {+ const clip = parseAnimClipData('run.esanim', data, new Map([['@uuid:sheet', 7]]));+ // cell 5 = row 1, col 1 → rect x=35, y=51+ const f = clip.frames[1];+ expect(f.uvOffset!.x).toBeCloseTo(35 / 134);+ expect(f.uvOffset!.y).toBeCloseTo(1 - (51 + 48) / 100);+ expect(f.uvScale!.x).toBeCloseTo(32 / 134);+ expect(f.uvScale!.y).toBeCloseTo(48 / 100);+ });++ it('supports mixing cell frames with per-texture frames', () => {+ const mixed: AnimClipAssetData = {+ ...data,+ frames: [{ cell: 1 }, { texture: 'assets/pow.png' }],+ };+ const clip = parseAnimClipData('mix.esanim', mixed, new Map([+ ['@uuid:sheet', 7],+ ['assets/pow.png', 9],+ ]));+ expect(clip.frames[0].texture).toBe(7);+ expect(clip.frames[0].uvOffset).toBeDefined();+ expect(clip.frames[1].texture).toBe(9);+ expect(clip.frames[1].uvOffset).toBeUndefined();+ });++ it('includes the sheet texture in extracted paths', () => {+ const paths = extractAnimClipTexturePaths(data);+ expect(paths).toEqual(['@uuid:sheet']);+ });+});++describe('parseAnimClipAsset (tolerant parse)', () => {+ it('normalizes a well-formed sheet clip round-trip through serializeAnimClip', () => {+ const clip = createAnimClip('@uuid:sheet', 32, 48, 134, 100);+ clip.frames.push({ cell: 0 }, { cell: 1, duration: 0.25 });+ const parsed = parseAnimClipAsset(JSON.parse(JSON.stringify(serializeAnimClip(clip))));+ expect(parsed).toEqual(clip);+ });++ it('drops cell frames when there is no sheet section', () => {+ const parsed = parseAnimClipAsset({ frames: [{ cell: 3 }, { texture: 'a.png' }] });+ expect(parsed.frames).toEqual([{ texture: 'a.png' }]);+ });++ it('drops frames with neither texture nor cell', () => {+ const parsed = parseAnimClipAsset({ frames: [{}, null, { duration: 0.5 }] });+ expect(parsed.frames).toEqual([]);+ });++ it('keeps legacy atlasFrame frames intact', () => {+ const af = { x: 1, y: 2, width: 3, height: 4, pageWidth: 10, pageHeight: 20 };+ const parsed = parseAnimClipAsset({ frames: [{ texture: 'a.png', atlasFrame: af }] });+ expect(parsed.frames[0].atlasFrame).toEqual(af);+ });++ it('defaults fps/loop and fills sheet defaults', () => {+ const parsed = parseAnimClipAsset({ sheet: { texture: 't.png' }, frames: [] });+ expect(parsed.fps).toBe(12);+ expect(parsed.loop).toBe(true);+ expect(parsed.sheet).toEqual({+ texture: 't.png', cellWidth: 32, cellHeight: 32,+ margin: 0, spacing: 0, pageWidth: 1, pageHeight: 1,+ });+ });+});