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(editor): Flipbook editor - sprite sheets slice into .esanim clips
esengine0ab2a6459f54
diff --git a/desktop/electron/assetDb.ts b/desktop/electron/assetDb.tsindex f93dacdd2..8be6b4837 100644--- a/desktop/electron/assetDb.ts+++ b/desktop/electron/assetDb.ts@@ -85,8 +85,10 @@ async function* walkMeta(root: string, rel = ''): AsyncGenerator<string> {* pull in (a material's shader + textures, a tileset's atlas, a tilemap's tileset* images, …).*/+// 'animation' covers .estimeline (AnimFrames tracks reference textures) and+// legacy .esanim metas written before the type split to 'animclip'.const JSON_REF_TYPES = new Set([- 'scene', 'prefab', 'material', 'tileset', 'tilemap', 'animclip', 'statemachine', 'behaviortree',+ 'scene', 'prefab', 'material', 'tileset', 'tilemap', 'animclip', 'animation', 'statemachine', 'behaviortree',]);/**diff --git a/desktop/electron/importAssets.ts b/desktop/electron/importAssets.tsindex 127f74b70..cd45ef0d4 100644--- a/desktop/electron/importAssets.ts+++ b/desktop/electron/importAssets.ts@@ -23,7 +23,7 @@ const EXT_TO_TYPE: Record<string, string> = {'.png': 'texture', '.jpg': 'texture', '.jpeg': 'texture', '.webp': 'texture', '.bmp': 'texture','.wav': 'audio', '.mp3': 'audio', '.ogg': 'audio', '.aac': 'audio', '.flac': 'audio', '.m4a': 'audio', '.webm': 'audio','.esprefab': 'prefab', '.esscene': 'scene', '.esshader': 'shader', '.esmaterial': 'material', '.esmat': 'material',- '.esanim': 'animation', '.esanimclip': 'animation', '.estimeline': 'animation',+ '.esanim': 'animclip', '.esanimclip': 'animclip', '.estimeline': 'animation','.fnt': 'bitmapFont', '.bmfont': 'bitmapFont', '.ttf': 'font', '.otf': 'font', '.woff': 'font', '.woff2': 'font','.tmx': 'tilemap', '.tmj': 'tilemap','.skel': 'spine', '.atlas': 'spine',diff --git a/desktop/src/components/GridField.tsx b/desktop/src/components/GridField.tsxnew file mode 100644index 000000000..e6b300d0d--- /dev/null+++ b/desktop/src/components/GridField.tsx@@ -0,0 +1,35 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file GridField.tsx+ * @brief A grid-geometry number field that commits on blur/Enter (one undo+ * step per edit) — shared by the Tileset and Flipbook editors.+ */+import { useEffect, useState } from 'react';++export function GridField(props: {+ label: string;+ value: number;+ min?: number;+ className?: string;+ onCommit: (n: number) => void;+}) {+ const [text, setText] = useState(String(props.value));+ useEffect(() => setText(String(props.value)), [props.value]);+ const commit = () => {+ const n = Number(text);+ if (Number.isFinite(n) && n !== props.value) props.onCommit(Math.max(props.min ?? 0, Math.floor(n)));+ else setText(String(props.value));+ };+ return (+ <label className={props.className ?? 'ts-field'}>+ <span>{props.label}</span>+ <input+ type="number" value={text} min={props.min ?? 0}+ onChange={(e) => setText(e.target.value)}+ onBlur={commit}+ onKeyDown={(e) => { if (e.key === 'Enter') (e.target as HTMLInputElement).blur(); }}+ />+ </label>+ );+}diff --git a/desktop/src/flipbook/AnimClipCommands.ts b/desktop/src/flipbook/AnimClipCommands.tsnew file mode 100644index 000000000..cbc4afe4a--- /dev/null+++ b/desktop/src/flipbook/AnimClipCommands.ts@@ -0,0 +1,107 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file AnimClipCommands.ts+ * @brief Undoable mutations on the open .esanim flipbook.+ * Each routes through AnimClipDocument.edit → one EditorHistory snapshot+ * step; the panel never mutates the asset directly.+ */++import { serializeAnimClip, type AnimClipSheetData } from 'esengine';+import { AnimClipDocument } from './AnimClipDocument';+import { Toasts } from '@/store/Toasts';+import { t } from '@/i18n';++type GridPatch = Partial<Pick<AnimClipSheetData, 'cellWidth' | 'cellHeight' | 'margin' | 'spacing'>>;++export const AnimClipCommands = {+ /** Edit the sheet grid geometry; every cell frame follows the new slicing. */+ setGrid(patch: GridPatch): void {+ AnimClipDocument.edit('Edit Sheet Grid', (a) => {+ if (!a.sheet) return;+ for (const k of Object.keys(patch) as (keyof GridPatch)[]) {+ const v = patch[k];+ if (typeof v === 'number' && Number.isFinite(v) && v >= 0) a.sheet[k] = Math.floor(v);+ }+ if (a.sheet.cellWidth < 1) a.sheet.cellWidth = 1;+ if (a.sheet.cellHeight < 1) a.sheet.cellHeight = 1;+ });+ },++ /** Re-bake the sheet's page size from the image's natural size (UV math reads it). */+ bakePageSize(pageWidth: number, pageHeight: number): void {+ const sheet = AnimClipDocument.asset?.sheet;+ if (!sheet || (sheet.pageWidth === pageWidth && sheet.pageHeight === pageHeight)) return;+ AnimClipDocument.edit('Re-bake Sheet Size', (a) => {+ if (!a.sheet) return;+ a.sheet.pageWidth = Math.max(1, Math.floor(pageWidth));+ a.sheet.pageHeight = Math.max(1, Math.floor(pageHeight));+ });+ },++ /** Append sheet cells as frames (one stroke = one undo step). */+ appendFrames(cells: number[]): void {+ const clean = cells.filter((c) => Number.isInteger(c) && c >= 0);+ if (clean.length === 0) return;+ AnimClipDocument.edit('Add Frames', (a) => {+ for (const cell of clean) a.frames.push({ cell });+ });+ },++ removeFrame(index: number): void {+ AnimClipDocument.edit('Remove Frame', (a) => {+ if (index >= 0 && index < a.frames.length) a.frames.splice(index, 1);+ });+ },++ clearFrames(): void {+ AnimClipDocument.edit('Clear Frames', (a) => {+ a.frames.length = 0;+ });+ },++ moveFrame(from: number, to: number): void {+ AnimClipDocument.edit('Reorder Frames', (a) => {+ if (from === to || from < 0 || to < 0 || from >= a.frames.length || to >= a.frames.length) return;+ const [f] = a.frames.splice(from, 1);+ a.frames.splice(to, 0, f);+ });+ },++ /** Per-frame duration in seconds; `undefined` falls back to 1/fps. */+ setFrameDuration(index: number, seconds: number | undefined): void {+ AnimClipDocument.edit('Edit Frame Duration', (a) => {+ const f = a.frames[index];+ if (!f) return;+ if (seconds !== undefined && Number.isFinite(seconds) && seconds > 0) f.duration = seconds;+ else delete f.duration;+ });+ },++ setFps(fps: number): void {+ if (!Number.isFinite(fps) || fps < 1) return;+ AnimClipDocument.edit('Edit FPS', (a) => {+ a.fps = Math.min(240, Math.floor(fps));+ });+ },++ setLoop(loop: boolean): void {+ AnimClipDocument.edit(loop ? 'Enable Loop' : 'Disable Loop', (a) => {+ a.loop = loop;+ });+ },++ /** Persist the open flipbook to its file. */+ async save(): Promise<void> {+ const asset = AnimClipDocument.asset;+ const path = AnimClipDocument.filePath;+ if (!asset || !path) return;+ try {+ await window.estella.fs.write(path, JSON.stringify(serializeAnimClip(asset), null, 2) + '\n');+ AnimClipDocument.markSaved();+ Toasts.push(t('fb.toast.saved'), 'info');+ } catch (e) {+ Toasts.push(t('fb.toast.saveFailed', { error: String(e) }), 'error');+ }+ },+};diff --git a/desktop/src/flipbook/AnimClipDocument.ts b/desktop/src/flipbook/AnimClipDocument.tsnew file mode 100644index 000000000..be5c24c6e--- /dev/null+++ b/desktop/src/flipbook/AnimClipDocument.ts@@ -0,0 +1,39 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file AnimClipDocument.ts+ * @brief The open .esanim sprite flipbook as a reactive editor document.+ * Same shape as TilesetDocument: a pure asset (binds to no scene+ * entity), so the generic reactive + snapshot-undo core carries it.+ */++import { parseAnimClipAsset, type AnimClipAssetData } from 'esengine';+import { AssetDocument } from '@/document/AssetDocument';++export interface AnimClipDocMeta {+ filePath: string | null;+ dirty: boolean;+}++export class AnimClipDocumentImpl extends AssetDocument<AnimClipAssetData> {+ get meta(): AnimClipDocMeta {+ return { filePath: this.filePath, dirty: this.dirty };+ }++ /** Open an already-parsed clip asset. */+ open(asset: AnimClipAssetData, filePath: string | null): void {+ this.openAsset(asset, filePath);+ }++ /** Open from raw .esanim JSON (normalized by the SDK parser). */+ openJson(raw: unknown, filePath: string | null): void {+ this.open(parseAnimClipAsset(raw), filePath);+ }++ close(): void {+ this.closeAsset();+ }+}++/** The app's default flipbook document (the one the Flipbook editor panel drives). */+export const AnimClipDocument = new AnimClipDocumentImpl();diff --git a/desktop/src/flipbook/openFlipbook.ts b/desktop/src/flipbook/openFlipbook.tsnew file mode 100644index 000000000..f93751986--- /dev/null+++ b/desktop/src/flipbook/openFlipbook.ts@@ -0,0 +1,78 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file openFlipbook.ts+ * @brief Open / create a .esanim sprite flipbook from the Content Browser.+ * Mirrors openTileset.ts (open + create-next-to-texture + .meta + re-scan).+ */++import { createAnimClip, serializeAnimClip } from 'esengine';+import { AnimClipDocument } from './AnimClipDocument';+import { ProjectStore } from '@/project/ProjectStore';+import { dockApi } from '@/layout/dockApi';+import { baseName } from '@/project/assetMeta';+import { Toasts } from '@/store/Toasts';+import { t } from '@/i18n';++/** Open an existing .esanim into the Flipbook editor and reveal the panel. */+export async function openFlipbook(path: string): Promise<void> {+ try {+ const text = await window.estella.fs.read(path);+ AnimClipDocument.openJson(JSON.parse(text), path);+ dockApi.openDocument('flipbook', 'flipbook', t('fb.panelTitle'));+ } catch (e) {+ Toasts.push(t('fb.toast.openFailed', { error: String(e) }), 'error');+ }+}++function imageSize(url: string): Promise<{ w: number; h: number }> {+ return new Promise((resolve, reject) => {+ const img = new Image();+ img.onload = () => resolve({ w: img.naturalWidth, h: img.naturalHeight });+ img.onerror = () => reject(new Error('image load failed'));+ img.src = url;+ });+}++/** A strip of square cells is the most common sheet shape; fall back to 32px. */+function guessCell(w: number, h: number): number {+ if (h > 0 && w % h === 0 && w / h <= 256) return h;+ return 32;+}++/** Create a .esanim next to a texture (slicing it), then open it. */+export async function createFlipbookFromTexture(texturePath: string): Promise<void> {+ const ref = ProjectStore.assetRef(texturePath);+ if (!ref) {+ Toasts.push(t('fb.toast.texUntracked'), 'error');+ return;+ }+ let size: { w: number; h: number };+ try {+ size = await imageSize(`estella://project/${texturePath}`);+ } catch {+ size = { w: 32, h: 32 };+ }+ const cell = guessCell(size.w, size.h);++ const dir = texturePath.includes('/') ? texturePath.slice(0, texturePath.lastIndexOf('/') + 1) : '';+ const base = baseName(texturePath).replace(/\.[^.]+$/, '') || 'Animation';+ let rel = `${dir}${base}.esanim`;+ for (let n = 1; ProjectStore.assetRef(rel); n++) rel = `${dir}${base}-${n}.esanim`;++ const asset = createAnimClip(ref, cell, cell, size.w, size.h);+ const uuid = crypto.randomUUID();+ try {+ await window.estella.fs.write(rel, JSON.stringify(serializeAnimClip(asset), null, 2) + '\n');+ await window.estella.fs.write(+ rel + '.meta',+ JSON.stringify({ uuid, version: '1.0', type: 'animclip', importer: { autoMigrate: true } }, null, 2) + '\n',+ );+ } catch (e) {+ Toasts.push(t('fb.toast.createFailed', { error: String(e) }), 'error');+ return;+ }+ await ProjectStore.refreshAssets(); // re-scan so the new clip is tracked+ Toasts.push(t('fb.toast.created', { name: rel.split('/').pop() ?? rel }), 'info');+ await openFlipbook(rel);+}diff --git a/desktop/src/i18n/messages/content.ts b/desktop/src/i18n/messages/content.tsindex c3a9dfe70..bfc25982d 100644--- a/desktop/src/i18n/messages/content.ts+++ b/desktop/src/i18n/messages/content.ts@@ -72,6 +72,7 @@ export const contentMessages = defineMessages({'cb.menuSetStartupScene': { en: 'Set as Startup Scene', zh: '设为启动场景' },'cb.menuIncludeInExport': { en: 'Include in Export', zh: '包含在导出中' },'cb.menuExcludeFromExport': { en: 'Exclude from Export', zh: '从导出中排除' },+ 'cb.menuCreateSpriteAnim': { en: 'Create Sprite Animation', zh: '创建精灵动画' },'cb.menuCreateTileset': { en: 'Create Tileset', zh: '创建瓦片集' },'cb.menuCreateTilemap': { en: 'Create Tilemap', zh: '创建瓦片地图' },'cb.menuCreateMaterialInstance': { en: 'Create Material Instance', zh: '创建材质实例' },diff --git a/desktop/src/i18n/messages/flipbook.ts b/desktop/src/i18n/messages/flipbook.tsnew file mode 100644index 000000000..7f30436d9--- /dev/null+++ b/desktop/src/i18n/messages/flipbook.ts@@ -0,0 +1,58 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file flipbook.ts — Flipbook editor: sheet slicing grid, frame strip, preview.+ */+import { defineMessages } from './types';++export const flipbookMessages = defineMessages({+ 'fb.panelTitle': { en: 'Sprite Animation', zh: '精灵动画' },+ 'fb.noOpen': { en: 'No sprite animation open.', zh: '未打开精灵动画。' },+ 'fb.noOpenHint': {+ en: 'Right-click a texture in the Content Browser and choose "Create Sprite Animation", or double-click a .esanim asset.',+ zh: '在内容浏览器中右键纹理并选择「创建精灵动画」,或双击 .esanim 资产。',+ },+ 'fb.noSheet': {+ en: 'This clip uses per-frame textures (no sheet to slice).',+ zh: '此剪辑使用逐帧纹理(没有可切片的精灵表)。',+ },++ // — Toolbar —+ 'fb.field.cellW': { en: 'Cell W', zh: '格宽' },+ 'fb.field.cellH': { en: 'Cell H', zh: '格高' },+ 'fb.field.margin': { en: 'Margin', zh: '边距' },+ 'fb.field.spacing': { en: 'Spacing', zh: '间距' },+ 'fb.field.fps': { en: 'FPS', zh: '帧率' },+ 'fb.field.zoom': { en: 'Zoom', zh: '缩放' },+ 'fb.loop': { en: 'Loop', zh: '循环' },+ 'fb.frameCount': { en: '{count} frames', zh: '{count} 帧' },+ 'fb.save': { en: 'Save', zh: '保存' },++ // — Sheet canvas —+ 'fb.cell.appendTip': { en: 'Click or drag to append frame #{cell}', zh: '点击或拖动以追加帧 #{cell}' },+ 'fb.texNotFound': { en: 'Sheet texture not found: {ref}', zh: '未找到精灵表纹理:{ref}' },+ 'fb.refEmpty': { en: '(empty)', zh: '(空)' },++ // — Frame strip —+ 'fb.preview': { en: 'Looping preview', zh: '循环预览' },+ 'fb.addFrames': { en: 'Click sheet cells to add frames', zh: '点击精灵表格子以添加帧' },+ 'fb.appendFrames': { en: 'Click cells to append · drag frames to reorder', zh: '点击格子追加 · 拖动帧以重排' },+ 'fb.frame.durTip': { en: 'Frame duration in ms (empty = 1000 / FPS)', zh: '帧时长(毫秒,留空 = 1000 / 帧率)' },+ 'fb.frame.remove': { en: 'Remove frame', zh: '移除帧' },+ 'fb.frame.invalidTip': {+ en: 'Cell #{cell} is outside the current grid — re-slice or remove the frame',+ zh: '格子 #{cell} 超出当前网格——请重新切片或移除该帧',+ },+ 'fb.clearFrames': { en: 'Clear all frames', zh: '清空所有帧' },++ // — Toasts —+ 'fb.toast.saved': { en: 'Sprite animation saved', zh: '精灵动画已保存' },+ 'fb.toast.saveFailed': { en: 'Save failed: {error}', zh: '保存失败:{error}' },+ 'fb.toast.openFailed': { en: 'Failed to open sprite animation: {error}', zh: '打开精灵动画失败:{error}' },+ 'fb.toast.createFailed': { en: 'Failed to create sprite animation: {error}', zh: '创建精灵动画失败:{error}' },+ 'fb.toast.created': { en: 'Created {name}', zh: '已创建 {name}' },+ 'fb.toast.texUntracked': {+ en: 'This texture is not in the asset database yet (missing .meta)',+ zh: '该纹理尚未进入资产数据库(缺少 .meta)',+ },+});diff --git a/desktop/src/i18n/messages/index.ts b/desktop/src/i18n/messages/index.tsindex e4f057f04..6fe9d56ec 100644--- a/desktop/src/i18n/messages/index.ts+++ b/desktop/src/i18n/messages/index.ts@@ -32,6 +32,7 @@ import { logsMessages } from './logs';import { sequencerMessages } from './sequencer';import { nodegraphMessages } from './nodegraph';import { tileMessages } from './tile';+import { flipbookMessages } from './flipbook';import { materialMessages } from './material';import { projectMessages } from './project';@@ -51,6 +52,7 @@ export const messageModules = {sequencer: sequencerMessages,nodegraph: nodegraphMessages,tile: tileMessages,+ flipbook: flipbookMessages,material: materialMessages,project: projectMessages,} as const;@@ -70,6 +72,7 @@ export const editorMessages = {...sequencerMessages,...nodegraphMessages,...tileMessages,+ ...flipbookMessages,...materialMessages,...projectMessages,} as const;diff --git a/desktop/src/layout/DockLayout.tsx b/desktop/src/layout/DockLayout.tsxindex 2a342c781..325e02c82 100644--- a/desktop/src/layout/DockLayout.tsx+++ b/desktop/src/layout/DockLayout.tsx@@ -19,6 +19,7 @@ import { OutputLog } from '@/panels/OutputLog';import { GamePanel, GameClientPanel } from '@/panels/GamePanel';import { Sequencer } from '@/panels/Sequencer';import { TilesetEditor } from '@/panels/TilesetEditor';+import { FlipbookEditor } from '@/panels/FlipbookEditor';import { TilemapPainter } from '@/panels/TilemapPainter';import { UIWidgetsPanel } from '@/panels/UIWidgetsPanel';import { MaterialGraphEditor } from '@/panels/MaterialGraphEditor';@@ -45,6 +46,7 @@ const components: Record<string, FC<IDockviewPanelProps>> = {log: () => panel('log', <OutputLog />),sequencer: () => panel('sequencer', <Sequencer />),tileset: () => panel('tileset', <TilesetEditor />),+ flipbook: () => panel('flipbook', <FlipbookEditor />),tilemap: () => panel('tilemap', <TilemapPainter />),uiWidgets: () => panel('uiWidgets', <UIWidgetsPanel />),materialgraph: () => panel('materialgraph', <MaterialGraphEditor />),@@ -142,6 +144,7 @@ const PANEL_TITLES: Record<string, () => string> = {profiler: () => t('layout.panel.profiler'),game: () => t('layout.panel.game'),tileset: () => t('tile.panelTileset'),+ flipbook: () => t('fb.panelTitle'),tilemap: () => t('panel.tilemap'),'ui-widgets': () => t('panel.uiWidgets'),materialgraph: () => t('mat.panelTitle'),diff --git a/desktop/src/layout/panelDirty.ts b/desktop/src/layout/panelDirty.tsindex 54d9f0e30..7ffde5b52 100644--- a/desktop/src/layout/panelDirty.ts+++ b/desktop/src/layout/panelDirty.ts@@ -10,6 +10,7 @@ import { FsmGraphDocument } from '@/fsm/FsmGraphDocument';import { BtDocument } from '@/bt/BtDocument';import { MaterialGraphDocument } from '@/material/MaterialGraphDocument';import { TilesetDocument } from '@/tileset/TilesetDocument';+import { AnimClipDocument } from '@/flipbook/AnimClipDocument';import { TimelineDocument } from '@/timeline/TimelineDocument';export interface DirtySource {@@ -22,6 +23,7 @@ const SOURCES: Record<string, DirtySource> = {behaviortree: { subscribe: BtDocument.subscribe, isDirty: () => BtDocument.dirty },materialgraph: { subscribe: MaterialGraphDocument.subscribe, isDirty: () => MaterialGraphDocument.dirty },tileset: { subscribe: TilesetDocument.subscribe, isDirty: () => TilesetDocument.dirty },+ flipbook: { subscribe: AnimClipDocument.subscribe, isDirty: () => AnimClipDocument.dirty },sequencer: { subscribe: TimelineDocument.subscribe, isDirty: () => TimelineDocument.dirty },};diff --git a/desktop/src/main.tsx b/desktop/src/main.tsxindex 8307c6a96..3173b5f9b 100644--- a/desktop/src/main.tsx+++ b/desktop/src/main.tsx@@ -25,6 +25,7 @@ import './theme/content.css';import './theme/sequencer.css';import './theme/profiler.css';import './theme/tileset.css';+import './theme/flipbook.css';import './theme/tilemap.css';import './theme/ui-palette.css';import './theme/material.css';diff --git a/desktop/src/panels/ContentBrowser.tsx b/desktop/src/panels/ContentBrowser.tsxindex 15ab7a059..92f3b525a 100644--- a/desktop/src/panels/ContentBrowser.tsx+++ b/desktop/src/panels/ContentBrowser.tsx@@ -17,6 +17,7 @@ import { ASSET_OPEN } from '@/project/assetOpen';import { referencingPaths } from '@/project/assetRefs';import { parseAssetQuery, filterAndSortAssets, type AssetSort } from '@/project/assetFilter';import { createTilesetFromTexture } from '@/tileset/openTileset';+import { createFlipbookFromTexture } from '@/flipbook/openFlipbook';import { createTilemapFromTileset } from '@/tilemap/createTilemap';import { BUILTIN_SHADER_TEMPLATES } from 'esengine';import { createMaterial, createMaterialInstance } from '@/material/openMaterial';@@ -886,7 +887,10 @@ export function ContentBrowser() {]: []),...(isTexture- ? [{ label: t('cb.menuCreateTileset'), onClick: () => void createTilesetFromTexture(path) }]+ ? [+ { label: t('cb.menuCreateSpriteAnim'), onClick: () => void createFlipbookFromTexture(path) },+ { label: t('cb.menuCreateTileset'), onClick: () => void createTilesetFromTexture(path) },+ ]: []),...(isTileset? [{ label: t('cb.menuCreateTilemap'), onClick: () => void createTilemapFromTileset(path) }]diff --git a/desktop/src/panels/FlipbookEditor.tsx b/desktop/src/panels/FlipbookEditor.tsxnew file mode 100644index 000000000..63a3942fa--- /dev/null+++ b/desktop/src/panels/FlipbookEditor.tsx@@ -0,0 +1,270 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file FlipbookEditor.tsx+ * @brief The .esanim sprite-flipbook editor panel — the sheet texture with a+ * slicing-grid overlay (click or drag cells to append frames) over a+ * frame strip with per-frame durations, fps/loop, and a live looping+ * preview. Subscribes to the reactive AnimClipDocument; mutations go+ * through AnimClipCommands (one undo step each).+ */++import {+ useEffect, useRef, useState, useSyncExternalStore,+ type CSSProperties, type DragEvent,+} from 'react';+import { Save, Trash2, X } from 'lucide-react';+import {+ animClipSheetCols, animClipSheetRows,+ type AnimClipFrameData, type AnimClipSheetData,+} from 'esengine';+import { DirtyDot } from '@/components/DirtyDot';+import { GridField } from '@/components/GridField';+import { AnimClipDocument } from '@/flipbook/AnimClipDocument';+import { AnimClipCommands } from '@/flipbook/AnimClipCommands';+import { ProjectStore } from '@/project/ProjectStore';+import { t } from '@/i18n';++const THUMB = 34;++/** CSS crop of one sheet cell, width-fit to `size` px (height follows the cell aspect). */+function cellThumbStyle(+ url: string, sheet: AnimClipSheetData, cols: number, cell: number, size: number,+): CSSProperties {+ const c = cell % cols;+ const r = Math.floor(cell / cols);+ const s = size / sheet.cellWidth;+ return {+ width: size,+ height: Math.max(8, Math.round(size * (sheet.cellHeight / sheet.cellWidth))),+ backgroundImage: `url(${url})`,+ backgroundPosition:+ `${-(sheet.margin + c * (sheet.cellWidth + sheet.spacing)) * s}px ` ++ `${-(sheet.margin + r * (sheet.cellHeight + sheet.spacing)) * s}px`,+ backgroundSize: `${sheet.pageWidth * s}px ${sheet.pageHeight * s}px`,+ };+}++/** Loops the frame strip with per-frame durations (1/fps when a frame has none). */+function FlipbookPreview(props: {+ frames: AnimClipFrameData[];+ fps: number;+ thumb: (f: AnimClipFrameData) => CSSProperties;+}) {+ const { frames, fps, thumb } = props;+ const [i, setI] = useState(0);+ useEffect(() => {+ setI(0);+ if (frames.length < 2) return;+ const durMs = (j: number) => Math.max(16, (frames[j].duration ?? 1 / fps) * 1000);+ let idx = 0;+ let live = true;+ let h: ReturnType<typeof setTimeout>;+ const tick = () => {+ if (!live) return;+ idx = (idx + 1) % frames.length;+ setI(idx);+ h = setTimeout(tick, durMs(idx));+ };+ h = setTimeout(tick, durMs(0));+ return () => {+ live = false;+ clearTimeout(h);+ };+ }, [frames, fps]);+ if (frames.length === 0) return null;+ return <span className="fb-thumb fb-preview" style={thumb(frames[Math.min(i, frames.length - 1)])} title={t('fb.preview')} />;+}++export function FlipbookEditor() {+ useSyncExternalStore(AnimClipDocument.subscribe, AnimClipDocument.getRevision);+ const asset = AnimClipDocument.asset;+ const meta = AnimClipDocument.meta;++ const sheet = asset?.sheet;+ const info = sheet ? ProjectStore.assetInfo(sheet.texture) : null;+ const texUrl = info ? `estella://project/${info.path}` : null;++ const [zoom, setZoom] = useState(2);+ // Live append stroke: ordered cells picked in one pointer gesture, one undo step.+ const [stroke, setStroke] = useState<number[] | null>(null);+ const strokeRef = useRef(stroke);+ strokeRef.current = stroke;+ const [dragFrame, setDragFrame] = useState<number | null>(null);++ if (!asset) {+ return (+ <div className="fb-empty">+ <p>{t('fb.noOpen')}</p>+ <p className="fb-hint">{t('fb.noOpenHint')}</p>+ </div>+ );+ }++ const fps = asset.fps ?? 12;+ const cols = sheet ? animClipSheetCols(sheet) : 0;+ const rows = sheet ? animClipSheetRows(sheet) : 0;+ const cellCount = cols * rows;++ const thumbFor = (f: AnimClipFrameData): CSSProperties => {+ if (sheet && texUrl && f.cell !== undefined) {+ return cellThumbStyle(texUrl, sheet, cols, Math.min(f.cell, Math.max(0, cellCount - 1)), THUMB);+ }+ // Legacy per-texture frame: show the whole referenced image.+ const fi = f.texture ? ProjectStore.assetInfo(f.texture) : null;+ return fi+ ? { width: THUMB, height: THUMB, backgroundImage: `url(estella://project/${fi.path})`, backgroundSize: 'contain' }+ : { width: THUMB, height: THUMB };+ };++ const commitStroke = () => {+ const s = strokeRef.current;+ if (s && s.length > 0) AnimClipCommands.appendFrames(s);+ setStroke(null);+ };++ const frameUse = new Set(asset.frames.map((f) => f.cell).filter((c): c is number => c !== undefined));+ const defaultMs = Math.round(1000 / fps);++ const cells = [];+ if (sheet && texUrl) {+ for (let row = 0; row < rows; row++) {+ for (let col = 0; col < cols; col++) {+ const cell = row * cols + col;+ const left = (sheet.margin + col * (sheet.cellWidth + sheet.spacing)) * zoom;+ const top = (sheet.margin + row * (sheet.cellHeight + sheet.spacing)) * zoom;+ const pending = stroke?.includes(cell);+ cells.push(+ <div+ key={cell}+ className={'fb-cell' + (frameUse.has(cell) ? ' is-used' : '') + (pending ? ' is-pending' : '')}+ style={{ left, top, width: sheet.cellWidth * zoom, height: sheet.cellHeight * zoom }}+ title={t('fb.cell.appendTip', { cell })}+ onPointerDown={(e) => { e.preventDefault(); setStroke([cell]); }}+ onPointerEnter={() => {+ const s = strokeRef.current;+ if (s && !s.includes(cell)) setStroke([...s, cell]);+ }}+ />,+ );+ }+ }+ }++ return (+ <div className="fb-editor">+ <div className="fb-toolbar">+ {sheet && (+ <>+ <GridField label={t('fb.field.cellW')} value={sheet.cellWidth} min={1} onCommit={(n) => AnimClipCommands.setGrid({ cellWidth: n })} />+ <GridField label={t('fb.field.cellH')} value={sheet.cellHeight} min={1} onCommit={(n) => AnimClipCommands.setGrid({ cellHeight: n })} />+ <GridField label={t('fb.field.margin')} value={sheet.margin} onCommit={(n) => AnimClipCommands.setGrid({ margin: n })} />+ <GridField label={t('fb.field.spacing')} value={sheet.spacing} onCommit={(n) => AnimClipCommands.setGrid({ spacing: n })} />+ <span className="fb-sep" />+ </>+ )}+ <GridField label={t('fb.field.fps')} value={fps} min={1} onCommit={(n) => AnimClipCommands.setFps(n)} />+ <label className="fb-field fb-loop">+ <input+ type="checkbox" checked={asset.loop ?? true}+ onChange={(e) => AnimClipCommands.setLoop(e.target.checked)}+ />+ <span>{t('fb.loop')}</span>+ </label>+ <span className="fb-sep" />+ <label className="fb-field">+ <span>{t('fb.field.zoom')}</span>+ <input type="range" min={1} max={8} step={1} value={zoom}+ onChange={(e) => setZoom(Number(e.target.value))} />+ </label>+ <span className="fb-grow" />+ <span className="fb-stat">+ {sheet ? `${cols}×${rows} · ` : ''}{t('fb.frameCount', { count: asset.frames.length })}+ </span>+ <button type="button" className="fb-save" onClick={() => void AnimClipCommands.save()} disabled={!meta.dirty}>+ <Save size={13} /> {t('fb.save')}{meta.dirty && <DirtyDot />}+ </button>+ </div>++ <div className="fb-frames">+ <FlipbookPreview frames={asset.frames} fps={fps} thumb={thumbFor} />+ {asset.frames.map((f, i) => {+ const invalid = f.cell !== undefined && f.cell >= cellCount;+ return (+ <span+ key={`${i}-${f.cell ?? f.texture}`}+ className={'fb-frame' + (invalid ? ' is-invalid' : '') + (dragFrame === i ? ' is-dragging' : '')}+ draggable+ onDragStart={(e: DragEvent) => { e.dataTransfer.setData('text/plain', String(i)); setDragFrame(i); }}+ onDragEnd={() => setDragFrame(null)}+ onDragOver={(e) => e.preventDefault()}+ onDrop={(e: DragEvent) => {+ e.preventDefault();+ const from = Number(e.dataTransfer.getData('text/plain'));+ if (Number.isInteger(from)) AnimClipCommands.moveFrame(from, i);+ setDragFrame(null);+ }}+ title={invalid ? t('fb.frame.invalidTip', { cell: f.cell ?? 0 }) : undefined}+ >+ <span className="fb-thumb" style={thumbFor(f)} />+ <input+ key={`${i}-${f.duration ?? ''}`}+ className="fb-dur"+ defaultValue={f.duration !== undefined ? Math.round(f.duration * 1000) : ''}+ placeholder={String(defaultMs)}+ title={t('fb.frame.durTip')}+ spellCheck={false}+ onBlur={(e) => {+ const raw = e.target.value.trim();+ if (raw === '') {+ if (f.duration !== undefined) AnimClipCommands.setFrameDuration(i, undefined);+ return;+ }+ const n = parseInt(raw, 10);+ if (Number.isFinite(n) && n > 0 && n / 1000 !== f.duration) AnimClipCommands.setFrameDuration(i, n / 1000);+ }}+ onKeyDown={(e) => { if (e.key === 'Enter') (e.target as HTMLInputElement).blur(); }}+ />+ <button+ type="button" className="fb-fx" title={t('fb.frame.remove')}+ onClick={() => AnimClipCommands.removeFrame(i)}+ >+ <X size={11} strokeWidth={2.2} />+ </button>+ </span>+ );+ })}+ <span className="fb-hint">+ {!sheet ? t('fb.noSheet') : asset.frames.length === 0 ? t('fb.addFrames') : t('fb.appendFrames')}+ </span>+ <span className="fb-grow" />+ {asset.frames.length > 0 && (+ <button type="button" className="fb-clear" title={t('fb.clearFrames')} onClick={() => AnimClipCommands.clearFrames()}>+ <Trash2 size={13} />+ </button>+ )}+ </div>++ {sheet && (+ <div className="fb-canvas" onPointerUp={commitStroke} onPointerLeave={commitStroke}>+ {!texUrl ? (+ <div className="fb-warn">{t('fb.texNotFound', { ref: String(sheet.texture) || t('fb.refEmpty') })}</div>+ ) : (+ <div className="fb-stage" style={{ width: sheet.pageWidth * zoom, height: sheet.pageHeight * zoom }}>+ <img+ className="fb-img" src={texUrl} alt="" draggable={false}+ onLoad={(e) => {+ // The image's natural size is the UV page size; re-bake if the+ // texture changed on disk since the clip was authored.+ const el = e.currentTarget;+ AnimClipCommands.bakePageSize(el.naturalWidth, el.naturalHeight);+ }}+ />+ {cells}+ </div>+ )}+ </div>+ )}+ </div>+ );+}diff --git a/desktop/src/panels/TilesetEditor.tsx b/desktop/src/panels/TilesetEditor.tsxindex 1f230e49d..6f181f663 100644--- a/desktop/src/panels/TilesetEditor.tsx+++ b/desktop/src/panels/TilesetEditor.tsx@@ -25,6 +25,7 @@ import {import { Segmented } from '@/components/Segmented';import { Select } from '@/components/Select';import { DirtyDot } from '@/components/DirtyDot';+import { GridField } from '@/components/GridField';import { TilesetDocument } from '@/tileset/TilesetDocument';import { TilesetCommands } from '@/tileset/TilesetCommands';import { ProjectStore } from '@/project/ProjectStore';@@ -32,28 +33,6 @@ import { colsFor, rowsFor, TERRAIN_COLORS } from '@/tools/tileMath';import { AnimPreview, tileThumbStyle, type TileAtlas } from '@/tools/tileThumb';import { t } from '@/i18n';-/** A grid-geometry number field that commits on blur/Enter (one undo step per edit). */-function GridField(props: { label: string; value: number; min?: number; onCommit: (n: number) => void }) {- const [text, setText] = useState(String(props.value));- useEffect(() => setText(String(props.value)), [props.value]);- const commit = () => {- const n = Number(text);- if (Number.isFinite(n) && n !== props.value) props.onCommit(Math.max(props.min ?? 0, Math.floor(n)));- else setText(String(props.value));- };- return (- <label className="ts-field">- <span>{props.label}</span>- <input- type="number" value={text} min={props.min ?? 0}- onChange={(e) => setText(e.target.value)}- onBlur={commit}- onKeyDown={(e) => { if (e.key === 'Enter') (e.target as HTMLInputElement).blur(); }}- />- </label>- );-}-// Peering zones in the cell's 3×3 grid; center (membership) is handled separately.const ZONES: { gx: number; gy: number; bit: number; corner: boolean; dir: string }[] = [{ gx: 1, gy: 0, bit: TB_N, corner: false, dir: t('tile.dir.north') },diff --git a/desktop/src/project/ProjectStore.ts b/desktop/src/project/ProjectStore.tsindex 1632e5fc6..ec29e5a2f 100644--- a/desktop/src/project/ProjectStore.ts+++ b/desktop/src/project/ProjectStore.ts@@ -43,7 +43,10 @@ function assetMatchesSlot(type: AssetType, path: string, fieldType?: string): bo// extension, through the SDK's own classification (.skel vs .atlas) — the// same vocabulary the cook's dep scan uses.if (fieldType === 'spine-skeleton' || fieldType === 'spine-atlas') return getEditorType(path) === fieldType;- return type === fieldType;+ if (type === fieldType) return true;+ // Slots named in the SDK's editorType vocabulary rather than the+ // Content-Browser type name (anim-clip for .esanim, timeline for .estimeline).+ return getEditorType(path) === fieldType;}/** A pickable asset for the inspector's asset picker. */diff --git a/desktop/src/project/assetOpen.ts b/desktop/src/project/assetOpen.tsindex 330c199f6..95ff641ac 100644--- a/desktop/src/project/assetOpen.ts+++ b/desktop/src/project/assetOpen.ts@@ -13,6 +13,7 @@ import { confirmDiscard } from './discardGuard';import { t } from '@/i18n';import { toggleAudioPreview } from './audioPreview';import { openAnimationClip } from '@/timeline/openClip';+import { openFlipbook } from '@/flipbook/openFlipbook';import { openTileset } from '@/tileset/openTileset';import { openMaterial } from '@/material/openMaterial';import { openMaterialGraph } from '@/material/openMaterialGraph';@@ -27,6 +28,7 @@ export const ASSET_OPEN: Partial<Record<AssetType, (path: string, name: string)},audio: (path) => toggleAudioPreview(path),animation: (path) => void openAnimationClip(path),+ animclip: (path) => void openFlipbook(path),tileset: (path) => void openTileset(path),material: (path) => void openMaterial(path),materialgraph: (path) => void openMaterialGraph(path),diff --git a/desktop/src/project/assetTypes.ts b/desktop/src/project/assetTypes.tsindex 598976784..2631342c5 100644--- a/desktop/src/project/assetTypes.ts+++ b/desktop/src/project/assetTypes.ts@@ -13,7 +13,7 @@*/import {Folder, Film, Image, FileImage, PersonStanding, Music,- Component, Blend, FileCode2, Clapperboard, Grid3x3, File, Workflow, Gamepad2, GitBranch, ListTree, Languages,+ Component, Blend, FileCode2, Clapperboard, Grid3x3, File, Workflow, Gamepad2, GitBranch, ListTree, Languages, Images,type LucideIcon,} from 'lucide-react';import type { AssetType } from '@/types';@@ -43,8 +43,10 @@ export const ASSET_TYPES: Record<AssetType, AssetTypeDef> = {material: { extensions: ['esmaterial', 'esmat'], badge: 'MAT', icon: Blend, tint: '#c0917a' },materialgraph: { extensions: ['esmatgraph'], badge: 'MGR', icon: Workflow, tint: '#c0917a' },script: { extensions: ['ts', 'js'], badge: 'TS', icon: FileCode2, tint: '#93a3bf' },- // Unified animation clip (.esanim) + legacy multi-track timeline (.estimeline).- animation: { extensions: ['esanim', 'estimeline'], badge: 'ANM', icon: Clapperboard, tint: '#9bb39a' },+ // Two animation documents, two editors: .estimeline is the Sequencer's+ // multi-track timeline; .esanim is the sprite flipbook (Flipbook editor).+ animation: { extensions: ['estimeline'], badge: 'SEQ', icon: Clapperboard, tint: '#9bb39a' },+ animclip: { extensions: ['esanim'], badge: 'CLP', icon: Images, tint: '#9bb39a' },tileset: { extensions: ['estileset'], badge: 'TST', icon: Grid3x3, tint: '#9b8fc0' },tilemap: { extensions: ['estilemap'], badge: 'TMP', icon: Grid3x3, tint: '#7fa6c4' },inputmap: { extensions: ['inputmap'], badge: 'INP', icon: Gamepad2, tint: '#a0b88f' },diff --git a/desktop/src/theme/flipbook.css b/desktop/src/theme/flipbook.cssnew file mode 100644index 000000000..ec553784b--- /dev/null+++ b/desktop/src/theme/flipbook.css@@ -0,0 +1,176 @@+/* SPDX-License-Identifier: Apache-2.0 */+/* SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team */+/* The .esanim sprite-flipbook editor panel (docs/REARCH_SPRITE_ANIMATION.md F2). */++.fb-editor {+ display: flex;+ flex-direction: column;+ height: 100%;+ position: relative;+ background: var(--srf-1);+ color: var(--text);+ font-size: var(--fs-sm);+}++.fb-empty {+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ height: 100%;+ color: var(--text-dim);+ gap: 4px;+}+.fb-empty .fb-hint { max-width: 420px; text-align: center; }++.fb-toolbar {+ display: flex;+ align-items: center;+ gap: 10px;+ padding: 6px 10px;+ border-bottom: 1px solid var(--line);+ background: var(--srf-2);+ flex: 0 0 auto;+}++.fb-field,+.fb-toolbar .ts-field {+ display: inline-flex;+ align-items: center;+ gap: 5px;+ color: var(--text-dim);+}+.fb-field span { user-select: none; }+.fb-toolbar input[type='number'] {+ width: 46px;+ background: var(--inset);+ border: 1px solid var(--line);+ border-radius: var(--r-sm);+ color: var(--text);+ padding: 2px 4px;+ font: inherit;+}+.fb-field input[type='range'] { width: 90px; }+.fb-loop input { accent-color: var(--star); }++.fb-sep { width: 1px; align-self: stretch; background: var(--line); margin: 0 2px; }+.fb-grow { flex: 1 1 auto; }+.fb-stat { color: var(--text-faint); font-variant-numeric: tabular-nums; }+.fb-hint { color: var(--text-faint); }++.fb-save {+ display: inline-flex;+ align-items: center;+ gap: 5px;+ background: transparent;+ color: var(--star-hi);+ border: 1px solid var(--star-line);+ border-radius: var(--r-sm);+ padding: 4px 9px;+ cursor: pointer;+ font: inherit;+ font-weight: 600;+ transition: background var(--t-fast);+}+.fb-save:not(:disabled):hover { background: var(--star-dim); }+.fb-save:not(:disabled):active { background: var(--star-soft); }+.fb-save:disabled { opacity: 0.45; cursor: default; }++/* Frame strip */+.fb-frames {+ display: flex;+ align-items: center;+ gap: 6px;+ flex-wrap: wrap;+ padding: 6px 10px;+ border-bottom: 1px solid var(--line);+ background: var(--srf-2);+ flex: 0 0 auto;+ min-height: 34px;+}+.fb-frame {+ display: inline-flex;+ align-items: center;+ gap: 4px;+ background: var(--srf-3);+ border: 1px solid var(--line);+ border-radius: var(--r-sm);+ padding: 2px 4px;+ cursor: grab;+}+.fb-frame.is-dragging { opacity: 0.4; }+.fb-frame.is-invalid { border-color: var(--error-hi); }+.fb-thumb {+ display: inline-block;+ background-repeat: no-repeat;+ background-position: center;+ image-rendering: pixelated;+ border-radius: var(--r-xs);+}+.fb-preview {+ border: 1px solid var(--star-line);+ background-color: var(--inset);+ margin-right: 4px;+}+.fb-dur {+ width: 40px;+ background: var(--inset);+ border: 1px solid var(--line);+ border-radius: var(--r-sm);+ color: var(--text);+ padding: 1px 4px;+ font: inherit;+ font-size: var(--fs-2xs);+ text-align: right;+}+.fb-fx,+.fb-clear {+ background: none;+ border: 1px solid var(--line);+ border-radius: var(--r-sm);+ color: var(--text-dim);+ padding: 2px 4px;+ cursor: pointer;+ display: inline-flex;+ align-items: center;+}+.fb-fx { border: none; padding: 1px; }+.fb-fx:hover,+.fb-clear:hover { color: var(--error-hi); }+.fb-clear:hover { border-color: var(--error-hi); }++/* Sheet canvas */+.fb-canvas {+ flex: 1 1 auto;+ overflow: auto;+ padding: 16px;+ /* A checkerboard so transparent sheet regions read clearly. */+ background:+ linear-gradient(45deg, var(--srf-0) 25%, transparent 25%) 0 0 / 16px 16px,+ linear-gradient(-45deg, var(--srf-0) 25%, transparent 25%) 0 8px / 16px 16px,+ linear-gradient(45deg, transparent 75%, var(--srf-0) 75%) 8px -8px / 16px 16px,+ linear-gradient(-45deg, transparent 75%, var(--srf-0) 75%) -8px 0 / 16px 16px,+ var(--srf-1);+}+.fb-stage { position: relative; }+.fb-img {+ display: block;+ width: 100%;+ height: 100%;+ image-rendering: pixelated;+ user-select: none;+}+.fb-warn { color: var(--error-hi); }++.fb-cell {+ position: absolute;+ box-sizing: border-box;+ border: 1px solid var(--line);+ cursor: pointer;+}+.fb-cell:hover { border-color: var(--star); background: var(--star-dim); }+.fb-cell.is-used { border-color: var(--star-line); }+.fb-cell.is-pending {+ background: var(--star-soft);+ border-color: var(--star);+}diff --git a/desktop/src/timeline/openClip.ts b/desktop/src/timeline/openClip.tsindex caad5d7a1..e7be62d4e 100644--- a/desktop/src/timeline/openClip.ts+++ b/desktop/src/timeline/openClip.ts@@ -2,12 +2,12 @@// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team/*** @file openClip.ts- * @brief Open an animation clip (.esanim / legacy .estimeline) from disk into- * the Sequencer.+ * @brief Open a multi-track timeline (.estimeline) from disk into the Sequencer.*- * Reads the project file, parses it through the unified clip loader (rich- * multi-track or legacy flipbook), opens it as the editor TimelineDocument bound+ * Reads the project file, parses it through the unified clip loader (tolerating+ * legacy flipbook-shaped files), opens it as the editor TimelineDocument bound* to the current selection as its preview root, and reveals the Sequencer.+ * Sprite flipbooks (.esanim) open in the Flipbook editor instead.*/import { parseAnimationClip } from 'esengine';@@ -38,11 +38,11 @@ export async function openAnimationClip(path: string): Promise<void> {// reads (the Sequencer fills it by recording keys on a selected entity).const BLANK_CLIP = { version: '1.1', type: 'timeline', duration: 5, wrapMode: 'loop', tracks: [] };-/** Create an empty `.esanim` timeline in @p dir and open it in the Sequencer. */+/** Create an empty `.estimeline` timeline in @p dir and open it in the Sequencer. */export async function createAnimationClip(dir: string): Promise<void> {const folder = dir ? (dir.endsWith('/') ? dir : `${dir}/`) : '';- let rel = `${folder}NewAnimation.esanim`;- for (let n = 1; ProjectStore.assetRef(rel); n++) rel = `${folder}NewAnimation-${n}.esanim`;+ let rel = `${folder}NewAnimation.estimeline`;+ for (let n = 1; ProjectStore.assetRef(rel); n++) rel = `${folder}NewAnimation-${n}.estimeline`;try {await window.estella.fs.write(rel, JSON.stringify(BLANK_CLIP, null, 2) + '\n');await window.estella.fs.write(diff --git a/desktop/src/types.ts b/desktop/src/types.tsindex dbf25a144..71adffa32 100644--- a/desktop/src/types.ts+++ b/desktop/src/types.ts@@ -160,6 +160,7 @@ export type AssetType =| 'materialgraph'| 'script'| 'animation'+ | 'animclip'| 'tileset'| 'tilemap'| 'inputmap'diff --git a/desktop/tests/asset-types.test.ts b/desktop/tests/asset-types.test.tsindex 091a8d550..1a67c71b1 100644--- a/desktop/tests/asset-types.test.ts+++ b/desktop/tests/asset-types.test.ts@@ -19,7 +19,7 @@ describe('asset type registry', () => {expect(assetTypeOf('a.esmaterial')).toBe('material'); // real ext (SDK loader)expect(assetTypeOf('a.esmat')).toBe('material'); // legacy aliasexpect(assetTypeOf('a.esmat')).toBe('material');- expect(assetTypeOf('a.esanim')).toBe('animation');+ expect(assetTypeOf('a.esanim')).toBe('animclip');expect(assetTypeOf('a.estimeline')).toBe('animation');expect(assetTypeOf('a.estileset')).toBe('tileset');expect(assetTypeOf('a.estilemap')).toBe('tilemap');diff --git a/desktop/tests/flipbook-commands.test.ts b/desktop/tests/flipbook-commands.test.tsnew file mode 100644index 000000000..d40e886cb--- /dev/null+++ b/desktop/tests/flipbook-commands.test.ts@@ -0,0 +1,75 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { describe, it, expect, beforeEach } from 'vitest';+import { createAnimClip } from 'esengine';+import { AnimClipDocument } from '@/flipbook/AnimClipDocument';+import { AnimClipCommands } from '@/flipbook/AnimClipCommands';+import { EditorHistory } from '@/engine/EditorHistory';++function freshClip() {+ // 4×2 grid of 32px cells on a 128×64 sheet.+ return createAnimClip('@uuid:sheet', 32, 32, 128, 64);+}++const asset = () => AnimClipDocument.asset!;++describe('AnimClipCommands', () => {+ beforeEach(() => {+ EditorHistory.clear();+ AnimClipDocument.open(freshClip(), 'run.esanim');+ });++ it('appendFrames adds a whole stroke as one undo step', () => {+ AnimClipCommands.appendFrames([0, 1, 2]);+ expect(asset().frames.map((f) => f.cell)).toEqual([0, 1, 2]);+ EditorHistory.undo();+ expect(asset().frames).toEqual([]);+ });++ it('appendFrames drops negative and non-integer cells', () => {+ AnimClipCommands.appendFrames([-1, 1.5, 3]);+ expect(asset().frames.map((f) => f.cell)).toEqual([3]);+ });++ it('removeFrame and moveFrame reorder the strip', () => {+ AnimClipCommands.appendFrames([0, 1, 2, 3]);+ AnimClipCommands.moveFrame(3, 0);+ expect(asset().frames.map((f) => f.cell)).toEqual([3, 0, 1, 2]);+ AnimClipCommands.removeFrame(1);+ expect(asset().frames.map((f) => f.cell)).toEqual([3, 1, 2]);+ EditorHistory.undo();+ EditorHistory.undo();+ expect(asset().frames.map((f) => f.cell)).toEqual([0, 1, 2, 3]);+ });++ it('setFrameDuration sets seconds and clears back to the fps default', () => {+ AnimClipCommands.appendFrames([0]);+ AnimClipCommands.setFrameDuration(0, 0.25);+ expect(asset().frames[0].duration).toBe(0.25);+ AnimClipCommands.setFrameDuration(0, undefined);+ expect(asset().frames[0].duration).toBeUndefined();+ });++ it('setGrid keeps cells positive and re-slices without touching frames', () => {+ AnimClipCommands.appendFrames([0, 5]);+ AnimClipCommands.setGrid({ cellWidth: 0, spacing: 2 });+ expect(asset().sheet!.cellWidth).toBe(1);+ expect(asset().sheet!.spacing).toBe(2);+ expect(asset().frames.map((f) => f.cell)).toEqual([0, 5]);+ });++ it('bakePageSize updates only on a real change', () => {+ AnimClipCommands.bakePageSize(128, 64); // same as authored — no edit, stays clean+ expect(AnimClipDocument.dirty).toBe(false);+ AnimClipCommands.bakePageSize(256, 64);+ expect(asset().sheet!.pageWidth).toBe(256);+ expect(AnimClipDocument.dirty).toBe(true);+ });++ it('setFps floors and clamps; setLoop toggles', () => {+ AnimClipCommands.setFps(24.9);+ expect(asset().fps).toBe(24);+ AnimClipCommands.setLoop(false);+ expect(asset().loop).toBe(false);+ });+});