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): collision (obstacle) layer — paint colliders over any background
yhh80b516ae33af
diff --git a/desktop/src/commands/editorCommands.ts b/desktop/src/commands/editorCommands.tsindex 0fece1eea..2884b868e 100644--- a/desktop/src/commands/editorCommands.ts+++ b/desktop/src/commands/editorCommands.ts@@ -171,6 +171,16 @@ commands.register({editor().setTilemapPickerOpen(true);},});+commands.register({+ id: 'tilemap.newCollisionLayer',+ label: t('cmd.tilemap.newCollisionLayer'),+ category: t('cat.entity'),+ isEnabled: () => !!ProjectStore.getSnapshot(),+ // An obstacle grid over any background: a TilemapLayer painting the built-in collision+ // palette (no tileset). Lazy import — createTilemap pulls a large graph (dockApi/stores)+ // that would cycle back through the command registry at module init.+ run: () => { void import('@/tilemap/createTilemap').then((m) => m.createCollisionLayer()); },+});commands.register({id: 'entity.duplicate',label: t('cmd.entity.duplicate'),diff --git a/desktop/src/i18n/messages/commands.ts b/desktop/src/i18n/messages/commands.tsindex ee6b115bf..80fbd369c 100644--- a/desktop/src/i18n/messages/commands.ts+++ b/desktop/src/i18n/messages/commands.ts@@ -27,6 +27,7 @@ export const commandMessages = defineMessages({// — Entity —'cmd.entity.add': { en: 'Add Entity', zh: '添加实体' },'cmd.tilemap.new': { en: 'New Tilemap', zh: '新建瓦片地图' },+ 'cmd.tilemap.newCollisionLayer': { en: 'New Collision Layer', zh: '新建碰撞层' },'cmd.entity.duplicate': { en: 'Duplicate', zh: '创建副本' },'cmd.entity.delete': { en: 'Delete', zh: '删除' },'cmd.entity.copy': { en: 'Copy', zh: '复制' },diff --git a/desktop/src/i18n/messages/tile.ts b/desktop/src/i18n/messages/tile.tsindex 5b1d32a26..6612d3cb4 100644--- a/desktop/src/i18n/messages/tile.ts+++ b/desktop/src/i18n/messages/tile.ts@@ -143,6 +143,14 @@ export const tileMessages = defineMessages({'tile.slope.halfTop': { en: 'Half (top)', zh: '半砖(上)' },'tile.slope.halfLeft': { en: 'Half (left)', zh: '半砖(左)' },'tile.slope.halfRight': { en: 'Half (right)', zh: '半砖(右)' },+ 'tile.collision.title': { en: 'Collision brushes', zh: '碰撞笔刷' },+ 'tile.collision.solid': { en: 'Solid', zh: '实心' },+ 'tile.collision.oneWay': { en: 'One-way ↑', zh: '单向 ↑' },+ 'tile.collision.sensor': { en: 'Trigger', zh: '触发器' },+ 'tile.collision.hint': {+ en: 'Paint obstacle cells over your background — solid, slope, one-way, or trigger.',+ zh: '在背景上刷障碍格——实心、斜坡、单向或触发器。',+ },'tile.solidCount': { en: '{count} solid', zh: '{count} 个实心' },'tile.save': { en: 'Save', zh: '保存' },'tile.done': { en: 'Done', zh: '完成' },@@ -243,6 +251,10 @@ export const tileMessages = defineMessages({en: 'Created tilemap — pick a brush to paint in the viewport',zh: '已创建瓦片地图——选择笔刷即可在视口中绘制',},+ 'tile.toast.collisionCreated': {+ en: 'Created collision layer — paint obstacle cells over your background',+ zh: '已创建碰撞层——在背景上刷障碍格',+ },'tile.toast.untracked': { en: 'Tileset is not tracked by the project', zh: '瓦片集未被项目跟踪' },'tile.toast.readFailed': { en: 'Failed to read tileset: {error}', zh: '读取瓦片集失败:{error}' },'tile.toast.openFailed': { en: 'Failed to open tileset: {error}', zh: '打开瓦片集失败:{error}' },diff --git a/desktop/src/layout/MenuBar.tsx b/desktop/src/layout/MenuBar.tsxindex ca97aef94..18edad974 100644--- a/desktop/src/layout/MenuBar.tsx+++ b/desktop/src/layout/MenuBar.tsx@@ -112,6 +112,7 @@ export function MenuBar() {items: [cmdItem('entity.add'),cmdItem('tilemap.new'),+ cmdItem('tilemap.newCollisionLayer'),{ sep: true },cmdItem('entity.duplicate'),cmdItem('entity.delete'),diff --git a/desktop/src/main.tsx b/desktop/src/main.tsxindex d7e723224..1a1b5e675 100644--- a/desktop/src/main.tsx+++ b/desktop/src/main.tsx@@ -49,7 +49,8 @@ import { Particle, getComponent } from 'esengine';import { applyFxPreview, initFxPreviewEditRestart } from './engine/fxPreview';import { commands } from './commands/registry';import { ENTITY_SOURCES, sourceById, createFromSource, type TileGridConfig } from './engine/entitySources';-import { createTilemapFromTileset } from './tilemap/createTilemap';+import { createTilemapFromTileset, createCollisionLayer } from './tilemap/createTilemap';+import { layerTilesetRefs, loadLayerTilesetModel } from './tilemap/layerTilesetModel';import { SceneCommands } from './engine/SceneCommands';import { useTilemapPaint } from './store/tilemapPaintStore';import { ViewportController } from './engine/ViewportController';@@ -140,9 +141,28 @@ if (new URLSearchParams(location.search).has('automation')) {/** Create a TilemapLayer from an .estileset with an optional grid layout* (orientation/stagger/hex) — drives the New-Tilemap flow headlessly. */createTilemap: (tilesetPath: string, grid?: TileGridConfig) => createTilemapFromTileset(tilesetPath, grid),+ /** Create a collision (obstacle) layer and return its selected source id — drives the+ * obstacle-grid flow headlessly (no tileset needed). */+ createCollisionLayer: async () => { await createCollisionLayer(); return useSelection.getState().selectedId; },/** Paint tiles into a TilemapLayer SOURCE entity (one undo step) — for shot tests. */paintTiles: (sourceId: number, edits: { x: number; y: number; tileId: number }[]) =>SceneCommands.paintTiles(sourceId, edits),+ /** Probe a layer's resolved tile-collision overlay — the SAME pieces the viewport+ * draws + Play spawns. Returns null if nothing resolves; else piece counts by kind.+ * Verifies the collision-layer pipeline end-to-end (refs → palette model → outlines). */+ probeTileCollision: async (sourceId: number) => {+ const refs = layerTilesetRefs(sourceId);+ const model = await loadLayerTilesetModel(refs);+ if (!model) return null;+ const pieces = ViewportController.tilemapColliderOutlines(sourceId, model);+ return {+ refs,+ total: pieces.length,+ sensors: pieces.filter((p) => p.sensor).length,+ oneWay: pieces.filter((p) => p.oneWay).length,+ polygons: pieces.filter((p) => p.polylines.length > 0 && !p.sensor && !p.oneWay).length,+ };+ },/** Drive the tilemap paint store (tool / terrain set / wang color) — for shot tests. */setTilePaint: (patch: { tool?: unknown; terrainSet?: number; wangColor?: number }) => {const s = useTilemapPaint.getState();diff --git a/desktop/src/panels/CollisionBrushPalette.tsx b/desktop/src/panels/CollisionBrushPalette.tsxnew file mode 100644index 000000000..8f540477b--- /dev/null+++ b/desktop/src/panels/CollisionBrushPalette.tsx@@ -0,0 +1,90 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file CollisionBrushPalette.tsx+ * @brief The palette for a COLLISION (obstacle) layer — the fixed built-in collision+ * brushes (solid / slopes / halves / one-way / trigger) in place of a texture+ * atlas. Picking a brush sets a 1×1 stamp of that brush's global id; the Viewport+ * paints it like any tile and the tile-collision overlay draws the resulting+ * collider. The brush set + its gids come from the SDK ({@link COLLISION_BRUSHES}),+ * so the palette can't drift from what the runtime spawns.+ */+import { COLLISION_BRUSHES, tileIdOf, type CollisionBrush } from 'esengine';+import { useTilemapPaint } from '@/store/tilemapPaintStore';+import { t } from '@/i18n';++/** Brush key → localized label. The six slope/half brushes share the `.estileset` slope+ * preset labels (same shapes); solid / one-way / trigger are collision-layer specific. */+const BRUSH_LABEL: Record<string, string> = {+ solid: t('tile.collision.solid'),+ rampR: t('tile.slope.rampR'),+ rampL: t('tile.slope.rampL'),+ halfBottom: t('tile.slope.halfBottom'),+ halfTop: t('tile.slope.halfTop'),+ halfLeft: t('tile.slope.halfLeft'),+ halfRight: t('tile.slope.halfRight'),+ oneWay: t('tile.collision.oneWay'),+ sensor: t('tile.collision.sensor'),+};++/** A 24×24 glyph of a brush's collision — a filled polygon/box, dashed for a sensor,+ * with a top arrow for a one-way floor — so the shape you'll paint is legible at a glance. */+function BrushIcon({ brush }: { brush: CollisionBrush }) {+ const { shape } = brush.collision;+ const sensor = !!brush.collision.sensor;+ const oneWay = !!brush.collision.oneWay;+ const fill = sensor ? 'none' : 'currentColor';+ const S = 24;+ const body = shape.type === 'polygon'+ ? <polygon points={shape.points.map(([x, y]) => `${x * S},${y * S}`).join(' ')}+ fill={fill} stroke="currentColor" strokeWidth={sensor ? 1.5 : 0}+ strokeDasharray={sensor ? '3 2' : undefined} />+ : <rect x={0.5} y={0.5} width={S - 1} height={S - 1} rx={1}+ fill={fill} stroke="currentColor" strokeWidth={sensor ? 1.5 : 0}+ strokeDasharray={sensor ? '3 2' : undefined} />;+ return (+ <svg viewBox={`0 0 ${S} ${S}`} width={26} height={26} aria-hidden="true">+ {body}+ {oneWay && (+ // Solid-top marker: an up arrow along the solid side (world y-up ⇒ top edge).+ <path d="M12 3 l4 5 h-3 v4 h-2 v-4 h-3 z" fill="var(--acc, #4ea1ff)" />+ )}+ </svg>+ );+}++/** The collision-layer brush grid. Reads/writes the shared paint store: the active brush is+ * the current 1×1 stamp's tile id; clicking a brush sets it (and switches to the brush tool+ * if none is armed, so the first click paints). */+export function CollisionBrushPalette() {+ const stamp = useTilemapPaint((s) => s.stamp);+ const tool = useTilemapPaint((s) => s.tool);+ const setBrushTile = useTilemapPaint((s) => s.setBrushTile);+ const setTool = useTilemapPaint((s) => s.setTool);+ const activeId = stamp.w === 1 && stamp.h === 1 ? tileIdOf(stamp.cells[0]) : -1;++ return (+ <div className="cp-panel">+ <div className="cp-hint">{t('tile.collision.hint')}</div>+ <div className="cp-grid" role="listbox" aria-label={t('tile.collision.title')}>+ {COLLISION_BRUSHES.map((brush) => (+ <button+ key={brush.id}+ type="button"+ role="option"+ aria-selected={brush.id === activeId}+ className={'cp-brush' + (brush.id === activeId ? ' is-active' : '')}+ title={BRUSH_LABEL[brush.key] ?? brush.key}+ onClick={() => {+ setBrushTile(brush.id);+ if (!tool || tool === 'eyedropper' || tool === 'select') setTool('brush');+ }}+ >+ <BrushIcon brush={brush} />+ <span className="cp-brush-label">{BRUSH_LABEL[brush.key] ?? brush.key}</span>+ </button>+ ))}+ </div>+ </div>+ );+}diff --git a/desktop/src/panels/TilemapPainter.tsx b/desktop/src/panels/TilemapPainter.tsxindex 18cf574ad..82538480c 100644--- a/desktop/src/panels/TilemapPainter.tsx+++ b/desktop/src/panels/TilemapPainter.tsx@@ -15,7 +15,7 @@ import {FlipHorizontal, FlipVertical, RotateCw, Mountain, Plus, X, MousePointer2, Dices,Eye, EyeOff, Lock, Unlock, Bookmark,} from 'lucide-react';-import { encodeTile, TilemapAPI, type TilesetAsset, type TileStamp } from 'esengine';+import { encodeTile, TilemapAPI, isCollisionPaletteRef, type TilesetAsset, type TileStamp } from 'esengine';import { useTilemapPaint, type PaintTool, type PaletteTileset, type AtlasInfo } from '@/store/tilemapPaintStore';import { useSelection } from '@/store/selectionStore';import { SceneModel } from '@/engine/SceneModel';@@ -32,6 +32,7 @@ import { TilesetDocument } from '@/tileset/TilesetDocument';import { useTilesetView } from '@/tileset/tilesetView';import { createTilemapFromTileset } from '@/tilemap/createTilemap';import { layerTilesetRefs } from '@/tilemap/layerTilesetModel';+import { CollisionBrushPalette } from '@/panels/CollisionBrushPalette';import { planTilesetRemovalFromBlob } from '@/tilemap/tilesetRemoval';import { confirm } from '@/components/confirm';import { AnimPreview, tileThumbStyle, type TileAtlas } from '@/tools/tileThumb';@@ -102,6 +103,9 @@ export function TilemapPainter() {const selectedId = useSelection((s) => s.selectedId);const hasTilemap = selectedId != null&& !!SceneModel.entityBySource(selectedId)?.components.some((c) => c.type === 'TilemapLayer');+ // A collision (obstacle) layer references the built-in collision palette, not an+ // `.estileset` — the palette below swaps the texture atlas for the fixed brush set.+ const collisionLayer = selectedId != null && isCollisionPaletteRef(layerTilesetRefs(selectedId));// Bumped after add/remove tileset: the layer's `tilesetAssets` changed but selectedId// did not, so the palette-load effect below wouldn't otherwise re-read the new list.const [reloadKey, setReloadKey] = useState(0);@@ -561,7 +565,8 @@ export function TilemapPainter() {<Dices size={15} /></IconButton></div>- {tool !== 'terrain' && (+ {collisionLayer && <CollisionBrushPalette />}+ {tool !== 'terrain' && !collisionLayer && (<div className="tp-stamps"><IconButton size="sm" title={t('tile.saveStamp')} onClick={() => updateStamps(addStamp(savedStamps, stamp))}><Bookmark size={13} />@@ -589,8 +594,9 @@ export function TilemapPainter() {</div>)}{/* Tileset tabs stay in every tool — the terrain list below is the ACTIVE- tileset's, so switching tilesets is legitimate mid-terrain-paint. */}- <div className="tp-tilesets">+ tileset's, so switching tilesets is legitimate mid-terrain-paint. A collision+ layer has no `.estileset` tabs (it paints the built-in palette above). */}+ {!collisionLayer && <div className="tp-tilesets">{tilesets.map((ts, i) => (<spankey={ts.path}@@ -633,8 +639,8 @@ export function TilemapPainter() {</Popover>)}</div>- </div>- {tool === 'terrain' && (+ </div>}+ {tool === 'terrain' && !collisionLayer && (<div className="tp-terrains">{(asset?.terrains ?? []).length === 0 ? (<div className="tp-warn">@@ -685,8 +691,9 @@ export function TilemapPainter() {</div>)}{/* The atlas palette stays in every tool — hiding it in terrain mode read- as "my tiles are gone"; picking a tile here switches back to the brush. */}- {texUrl && (+ as "my tiles are gone"; picking a tile here switches back to the brush. A+ collision layer replaced it with the brush palette above. */}+ {!collisionLayer && texUrl && (<div className="tp-palbar">{/* Active-brush preview lives with the palette it's picked from + the zoom itscales with — always visible (the tools row above no longer steals it). */}@@ -698,6 +705,7 @@ export function TilemapPainter() {<ZoomControl zoom={zoom} onZoom={setZoom} onFit={fitZoom} fitTitle={t('tile.fitWidth')} /></div>)}+ {!collisionLayer && (<divclassName="tp-palette"ref={paletteRef}@@ -725,6 +733,7 @@ export function TilemapPainter() {</div>)}</div>+ )}</div>);}diff --git a/desktop/src/theme/tilemap.css b/desktop/src/theme/tilemap.cssindex 1e26c484e..7f40c58b1 100644--- a/desktop/src/theme/tilemap.css+++ b/desktop/src/theme/tilemap.css@@ -351,3 +351,38 @@color: var(--text-faint);}.tp-hint { font-size: var(--fs-xs); max-width: 280px; }++/* Collision-layer palette — the fixed obstacle brushes, in place of a texture atlas. */+.cp-panel {+ display: flex;+ flex-direction: column;+ gap: 8px;+ padding: 10px;+ overflow-y: auto;+}+.cp-hint { font-size: var(--fs-xs); color: var(--text-faint); line-height: 1.4; }+.cp-grid {+ display: grid;+ grid-template-columns: repeat(3, 1fr);+ gap: 6px;+}+.cp-brush {+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: 3px;+ padding: 8px 4px;+ background: var(--srf-2);+ border: 1px solid var(--line);+ border-radius: 6px;+ color: var(--text-faint);+ cursor: pointer;+}+.cp-brush:hover { background: var(--srf-4); color: var(--text); }+.cp-brush.is-active {+ border-color: var(--acc);+ background: color-mix(in srgb, var(--acc) 16%, var(--srf-2));+ color: var(--text);+}+.cp-brush svg { color: var(--text); }+.cp-brush-label { font-size: var(--fs-xs); text-align: center; line-height: 1.1; }diff --git a/desktop/src/tilemap/createTilemap.ts b/desktop/src/tilemap/createTilemap.tsindex ce525bfa8..e815895cb 100644--- a/desktop/src/tilemap/createTilemap.ts+++ b/desktop/src/tilemap/createTilemap.ts@@ -9,8 +9,8 @@* undoable 'Set Tilesets' step so redo re-pushes) and opens the painter. The* tileset stays the reusable asset the map references (Unity/Godot model).*/-import { parseTileset } from 'esengine';-import { Grid3x3 } from 'lucide-react';+import { parseTileset, COLLISION_PALETTE_REF } from 'esengine';+import { Grid3x3, Shapes } from 'lucide-react';import { createFromSource, tilemapPrefab, type EntitySource, type TileGridConfig } from '@/engine/entitySources';import { useSelection } from '@/store/selectionStore';import { useTilemapPaint } from '@/store/tilemapPaintStore';@@ -66,3 +66,29 @@ export async function createTilemapFromTileset(tilesetPath: string, grid?: TileGtilesetSource(tilesetPath, tilesetRef, asset.tileWidth, asset.tileHeight, grid), { parent: null },);}++/**+ * Create a COLLISION (obstacle) layer — a TilemapLayer that paints from the built-in+ * collision palette ({@link COLLISION_PALETTE_REF}) instead of an `.estileset`. It renders+ * nothing (no atlas); you paint solid / slope / one-way / sensor cells over a background+ * image and they become static colliders at Play, shown live via the tile-collision+ * overlay. Same create pipeline as a tileset map — the sentinel ref just routes the runtime+ * to the fixed palette. Seeds a 32px grid (editable in the Inspector).+ */+export async function createCollisionLayer(): Promise<void> {+ await createFromSource({+ id: 'collision-layer',+ label: 'Collision Layer',+ category: '2D',+ icon: Shapes,+ build: () => tilemapPrefab('Collision', { x: 32, y: 32 }, COLLISION_PALETTE_REF),+ afterCreate: (_ctx, rootId) => {+ useSelection.getState().select(rootId);+ // Start on the solid brush (palette gid 1) with the brush tool, painter open.+ useTilemapPaint.getState().setBrushTile(1);+ useTilemapPaint.getState().setTool('brush');+ dockApi.openSidePanel('tilemap', 'tilemap', t('panel.tilemap'), 'left', 300);+ Toasts.push(t('tile.toast.collisionCreated'), 'info');+ },+ }, { parent: null });+}diff --git a/desktop/src/tilemap/layerTilesetModel.ts b/desktop/src/tilemap/layerTilesetModel.tsindex ba17deda4..3c195e086 100644--- a/desktop/src/tilemap/layerTilesetModel.ts+++ b/desktop/src/tilemap/layerTilesetModel.ts@@ -8,7 +8,10 @@* `TilemapPlugin`'s private per-entity map (the plugin resolves for the running* world; the editor re-resolves independently for a picture).*/-import { resolveTilesetModel, type TilesetModel, type ResolvedTileset } from 'esengine';+import {+ resolveTilesetModel, isCollisionPaletteRef, buildCollisionPaletteModel,+ type TilesetModel, type ResolvedTileset,+} from 'esengine';import { SceneModel } from '@/engine/SceneModel';import { ProjectStore } from '@/project/ProjectStore';import { loadTilesetAsset } from '@/tileset/loadTileset';@@ -43,6 +46,11 @@ function imageHeight(url: string): Promise<number> {* (firstId 1) never touch the network. Returns null when nothing resolves.*/export async function loadLayerTilesetModel(refs: string[]): Promise<TilesetModel | null> {+ // A collision (obstacle) layer paints from the fixed built-in palette, not an+ // `.estileset` — resolve it to the SAME model the runtime installs, so the overlay+ // draws exactly the colliders that will spawn.+ if (isCollisionPaletteRef(refs)) return buildCollisionPaletteModel();+const list: ResolvedTileset[] = [];for (const ref of refs) {const path = ProjectStore.assetInfo(ref)?.path;diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex bb007ed2c..2e429a969 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: 1295 stable · 17 beta · 0 deprecated+Symbols: 1300 stable · 17 beta · 0 deprecated## ABI_LAYOUT_HASH — const```@@ -1152,6 +1152,16 @@ sprite: number | undefined16```+## COLLISION_BRUSHES — const+```+CollisionBrush[]+```++## COLLISION_PALETTE_REF — const+```+"builtin:collision"+```+## CacheAsBitmap — const```ComponentDef<CacheAsBitmapData>@@ -1446,6 +1456,13 @@ polylines: Vec2[][]| { kind: 'chain'; points: Vec2[]; isLoop: boolean }```+## CollisionBrush — interface+```+collision: ResolvedTileCollision+id: number+key: string+```+## CollisionEnterEvent — interface```contactX: number@@ -7962,6 +7979,11 @@ BtPlugin(overrides: readonly PrefabOverride[]): Map<PrefabEntityId, PrefabOverride[]>```+## buildCollisionPaletteModel — function+```+(): TilesetModel+```+## buildTerrainIndices — function```(asset: TilesetAsset): TerrainIndices@@ -8787,6 +8809,11 @@ InputRouter(comp: AnyComponentDef): comp is BuiltinComponentDef<any>```+## isCollisionPaletteRef — function+```+(refs: readonly string[]): boolean+```+## isCustomExtension — function```(path: string): booleandiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex a4b622e72..4d0722e7a 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -1,7 +1,7 @@# API surface — esengine/index.node<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 1294 stable · 19 beta · 0 deprecated+Symbols: 1299 stable · 19 beta · 0 deprecated## ANCHOR_AXES — const```@@ -1147,6 +1147,16 @@ sprite: number | undefined16```+## COLLISION_BRUSHES — const+```+CollisionBrush[]+```++## COLLISION_PALETTE_REF — const+```+"builtin:collision"+```+## CacheAsBitmap — const```ComponentDef<CacheAsBitmapData>@@ -1441,6 +1451,13 @@ polylines: Vec2[][]| { kind: 'chain'; points: Vec2[]; isLoop: boolean }```+## CollisionBrush — interface+```+collision: ResolvedTileCollision+id: number+key: string+```+## CollisionEnterEvent — interface```contactX: number@@ -7957,6 +7974,11 @@ BtPlugin(overrides: readonly PrefabOverride[]): Map<PrefabEntityId, PrefabOverride[]>```+## buildCollisionPaletteModel — function+```+(): TilesetModel+```+## buildTerrainIndices — function```(asset: TilesetAsset): TerrainIndices@@ -8782,6 +8804,11 @@ InputRouter(comp: AnyComponentDef): comp is BuiltinComponentDef<any>```+## isCollisionPaletteRef — function+```+(refs: readonly string[]): boolean+```+## isCustomExtension — function```(path: string): booleandiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 5dfaf7c99..aee4c9ae6 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -1,7 +1,7 @@# API surface — esengine/wechat<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 1305 stable · 17 beta · 0 deprecated+Symbols: 1310 stable · 17 beta · 0 deprecated## ANCHOR_AXES — const```@@ -1147,6 +1147,16 @@ sprite: number | undefined16```+## COLLISION_BRUSHES — const+```+CollisionBrush[]+```++## COLLISION_PALETTE_REF — const+```+"builtin:collision"+```+## CacheAsBitmap — const```ComponentDef<CacheAsBitmapData>@@ -1441,6 +1451,13 @@ polylines: Vec2[][]| { kind: 'chain'; points: Vec2[]; isLoop: boolean }```+## CollisionBrush — interface+```+collision: ResolvedTileCollision+id: number+key: string+```+## CollisionEnterEvent — interface```contactX: number@@ -7981,6 +7998,11 @@ BtPlugin(overrides: readonly PrefabOverride[]): Map<PrefabEntityId, PrefabOverride[]>```+## buildCollisionPaletteModel — function+```+(): TilesetModel+```+## buildTerrainIndices — function```(asset: TilesetAsset): TerrainIndices@@ -8811,6 +8833,11 @@ InputRouter(comp: AnyComponentDef): comp is BuiltinComponentDef<any>```+## isCollisionPaletteRef — function+```+(refs: readonly string[]): boolean+```+## isCustomExtension — function```(path: string): booleandiff --git a/sdk/src/core-content.ts b/sdk/src/core-content.tsindex ff37de94d..c92543f90 100644--- a/sdk/src/core-content.ts+++ b/sdk/src/core-content.ts@@ -441,6 +441,10 @@ export {decodeTilemapChunks,CHUNK_SIZE,tileCollisionOutlines,+ COLLISION_PALETTE_REF,+ COLLISION_BRUSHES,+ isCollisionPaletteRef,+ buildCollisionPaletteModel,tileCellCenter,tileCellOutline,isNonOrthogonal,@@ -500,6 +504,7 @@ export {type TilesetModel,type DecodedChunk,type TileCollisionPiece,+ type CollisionBrush,type TileGridParams,type Vec2Like,type TilesetAnimFrame,diff --git a/sdk/src/tilemap/collisionPalette.ts b/sdk/src/tilemap/collisionPalette.tsnew file mode 100644index 000000000..e28ae08a1--- /dev/null+++ b/sdk/src/tilemap/collisionPalette.ts@@ -0,0 +1,86 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file collisionPalette.ts+ * @brief The built-in COLLISION-LAYER palette — a fixed set of collision brushes a+ * TilemapLayer paints when it references {@link COLLISION_PALETTE_REF} instead of+ * an `.estileset`. This is the "obstacle grid" primitive: paint solid / slope /+ * one-way / sensor cells over any background (a single big image) with NO render+ * tileset, and the exact same runtime that spawns tile colliders + draws the+ * editor overlay handles it — the brush id is a global tile id and this palette+ * IS the layer's {@link TilesetModel} (render slots empty ⇒ nothing draws).+ *+ * Reuse, not a second system: a collision layer is an ordinary TilemapLayer whose tileset+ * ref is the sentinel {@link COLLISION_PALETTE_REF}. The chunk store, paint tools, chunk+ * codec, flip/rotate, greedy box merge, one-way / sensor handling, and the world-space+ * collision overlay all key off the painted gid → this palette's collision — identical to+ * the `.estileset` path (`resolveTilesetModel`), only sourced from a fixed in-code table.+ *+ * STABILITY: a brush `id` is painted into (and saved in) a layer's chunk blob, so the+ * id → shape mapping is a serialization contract. Only APPEND brushes; never renumber or+ * repurpose an existing id, or existing collision maps silently change shape.+ */+import type { ResolvedTileCollision, TilesetModel } from './tilesetResolve';++/** The sentinel tileset ref that turns a TilemapLayer into a collision (obstacle) layer.+ * Mirrors the `builtin:<id>` shader convention — resolved in code, never a project asset. */+export const COLLISION_PALETTE_REF = 'builtin:collision';++/** True when a layer's tileset ref list is the built-in collision palette. */+export function isCollisionPaletteRef(refs: readonly string[]): boolean {+ return refs.some((r) => r === COLLISION_PALETTE_REF);+}++/**+ * One collision brush. `id` is the global tile id painted into the cell; `key` is a stable+ * string the editor maps to a label + icon; `collision` is what the cell resolves to —+ * consumed by the same spawn / overlay path as an `.estileset` tile.+ */+export interface CollisionBrush {+ id: number;+ key: string;+ collision: ResolvedTileCollision;+}++// Polygon points are tile-normalized [0,1], y-DOWN (top-left origin) — the same convention+// `resolveTilesetModel` produces after dividing `.estileset` pixels by tile size, so+// `tileColliderShape` / `tileCollisionOutlines` consume them unchanged. The four ramp/half+// polygons match the editor's `.estileset` slope presets.+export const COLLISION_BRUSHES: CollisionBrush[] = [+ { id: 1, key: 'solid', collision: { shape: { type: 'box' } } },+ { id: 2, key: 'rampR', collision: { shape: { type: 'polygon', points: [[0, 1], [1, 1], [1, 0]] } } },+ { id: 3, key: 'rampL', collision: { shape: { type: 'polygon', points: [[0, 0], [0, 1], [1, 1]] } } },+ { id: 4, key: 'halfBottom', collision: { shape: { type: 'polygon', points: [[0, 0.5], [1, 0.5], [1, 1], [0, 1]] } } },+ { id: 5, key: 'halfTop', collision: { shape: { type: 'polygon', points: [[0, 0], [1, 0], [1, 0.5], [0, 0.5]] } } },+ { id: 6, key: 'halfLeft', collision: { shape: { type: 'polygon', points: [[0, 0], [0.5, 0], [0.5, 1], [0, 1]] } } },+ { id: 7, key: 'halfRight', collision: { shape: { type: 'polygon', points: [[0.5, 0], [1, 0], [1, 1], [0.5, 1]] } } },+ // One-way (jump-through) floor: solid-top normal in world y-up ({0,1}); flips reorient it.+ { id: 8, key: 'oneWay', collision: { shape: { type: 'box' }, oneWay: { nx: 0, ny: 1 } } },+ // Trigger volume: non-solid sensor box (fires contact events, no physical response).+ { id: 9, key: 'sensor', collision: { shape: { type: 'box' }, sensor: true } },+];++/** A brush is a plain solid box (no modifier) exactly when the greedy rectangle merge may+ * fuse it — mirrors `isPlainBox` in tilesetResolve so the two paths agree. */+function isPlainBox(c: ResolvedTileCollision): boolean {+ return c.shape.type === 'box' && !c.oneWay && !c.sensor+ && c.density === undefined && c.friction === undefined && c.restitution === undefined;+}++/**+ * The collision palette AS a {@link TilesetModel} — the same model `resolveTilesetModel`+ * derives from `.estileset`(s), so a collision layer feeds the identical spawn + overlay+ * code. `slots` is empty (no atlas ⇒ the renderer draws nothing); `collidableTileIds` holds+ * the plain solid box (greedy-merged), `tileShapes` the richer brushes (slopes / halves /+ * one-way / sensor), one collider each.+ */+export function buildCollisionPaletteModel(): TilesetModel {+ const collidableTileIds: number[] = [];+ const tileShapes = new Map<number, ResolvedTileCollision>();+ for (const b of COLLISION_BRUSHES) {+ if (isPlainBox(b.collision)) collidableTileIds.push(b.id);+ else tileShapes.set(b.id, b.collision);+ }+ collidableTileIds.sort((a, b) => a - b);+ return { slots: [], animations: new Map(), collidableTileIds, tileShapes };+}diff --git a/sdk/src/tilemap/index.ts b/sdk/src/tilemap/index.tsindex 65d889857..f0525d321 100644--- a/sdk/src/tilemap/index.ts+++ b/sdk/src/tilemap/index.ts@@ -16,6 +16,10 @@ export {type TiledAnimFrame, type TilemapLoadOptions,} from './tiledLoader';export { tileCollisionOutlines, type TileCollisionPiece } from './tileCollisionOutline';+export {+ COLLISION_PALETTE_REF, COLLISION_BRUSHES, isCollisionPaletteRef, buildCollisionPaletteModel,+ type CollisionBrush,+} from './collisionPalette';export {tileCellCenter, tileCellOutline, isNonOrthogonal, usesStagger, isHexOrientation, TileOrientation,type TileGridParams, type Vec2Like,diff --git a/sdk/src/tilemap/tilemapPlugin.ts b/sdk/src/tilemap/tilemapPlugin.tsindex 7bb5f2dc2..1f656c17e 100644--- a/sdk/src/tilemap/tilemapPlugin.ts+++ b/sdk/src/tilemap/tilemapPlugin.ts@@ -11,6 +11,7 @@ import { Tilemap } from './components';import { registerSceneComponentCodec } from '../scene';import { getTilemapSource, getResolvedTileset, type LoadedTilemapSource } from './tilesetCache';import { resolveTilesetModel } from './tilesetResolve';+import { isCollisionPaletteRef, buildCollisionPaletteModel } from './collisionPalette';import { _bindTileCollisionLookup, type LayerCollisionTable } from './tileQuery';import type { ResolvedTileCollision } from './tilesetResolve';import {@@ -276,11 +277,25 @@ export class TilemapPlugin implements Plugin {appliedGrid.set(entity, gridKey);}+ // Collision (obstacle) layer: the sentinel `builtin:collision` ref means+ // this layer paints from the fixed collision palette, not an `.estileset`.+ // Install its collision model directly — NO render slots (nothing draws)+ // and no atlas load — so the same spawn + overlay path handles it as any+ // painted collision. The gate above passed because refs is non-empty.+ if (refs && refs.length > 0 && isCollisionPaletteRef(refs) && !liveResolved.has(entity)) {+ const model = buildCollisionPaletteModel();+ if (model.collidableTileIds.length > 0) nativeCollisionIds.set(entity, model.collidableTileIds);+ else nativeCollisionIds.delete(entity);+ if (model.tileShapes.size > 0) nativeTileShapes.set(entity, model.tileShapes);+ else nativeTileShapes.delete(entity);+ liveResolved.add(entity);+ }+// Live tileset(s): when ALL the layer's `.estileset` refs have loaded,// derive its multi-slot render table + animations + collision LIVE (once// per load) — replacing copied columns + the baked collidableTileIds. The// whole list must resolve together so firstId ranges are contiguous.- if (refs && refs.length > 0 && !liveResolved.has(entity)) {+ else if (refs && refs.length > 0 && !liveResolved.has(entity)) {const resolvedList = [];for (const ref of refs) {const key = resolveAssetKey(assets, ref);diff --git a/sdk/tests/collision-palette.test.ts b/sdk/tests/collision-palette.test.tsnew file mode 100644index 000000000..61e4b1221--- /dev/null+++ b/sdk/tests/collision-palette.test.ts@@ -0,0 +1,66 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file The built-in collision-layer palette: the fixed brush set a TilemapLayer paints+ * when it references `builtin:collision`. Pins the serialization contract (brush id+ * → shape) and that the palette IS a valid TilesetModel the collision spawn/overlay+ * path consumes — render slots empty (nothing draws), plain box merges, rich shapes+ * spawn one collider each.+ */+import { describe, it, expect } from 'vitest';+import {+ COLLISION_PALETTE_REF, COLLISION_BRUSHES, isCollisionPaletteRef, buildCollisionPaletteModel,+} from '../src/tilemap/collisionPalette';+import { tileColliderShape } from '../src/tilemap/tiledLoader';++describe('isCollisionPaletteRef', () => {+ it('matches the sentinel ref, alone or in a list', () => {+ expect(isCollisionPaletteRef([COLLISION_PALETTE_REF])).toBe(true);+ expect(isCollisionPaletteRef(['@uuid:abc', COLLISION_PALETTE_REF])).toBe(true);+ });+ it('rejects ordinary tileset refs', () => {+ expect(isCollisionPaletteRef([])).toBe(false);+ expect(isCollisionPaletteRef(['@uuid:abc', 'maps/a.estileset'])).toBe(false);+ });+});++describe('COLLISION_BRUSHES (serialization contract)', () => {+ it('assigns contiguous 1-based ids in a stable order', () => {+ expect(COLLISION_BRUSHES.map((b) => b.id)).toEqual([1, 2, 3, 4, 5, 6, 7, 8, 9]);+ // The key order is the contract — appending is allowed, renumbering is not.+ expect(COLLISION_BRUSHES.map((b) => b.key)).toEqual([+ 'solid', 'rampR', 'rampL', 'halfBottom', 'halfTop', 'halfLeft', 'halfRight', 'oneWay', 'sensor',+ ]);+ });+ it('id 1 is the only plain solid box; one-way/sensor carry modifiers', () => {+ const solid = COLLISION_BRUSHES.find((b) => b.id === 1)!;+ expect(solid.collision).toEqual({ shape: { type: 'box' } });+ expect(COLLISION_BRUSHES.find((b) => b.key === 'oneWay')!.collision.oneWay).toEqual({ nx: 0, ny: 1 });+ expect(COLLISION_BRUSHES.find((b) => b.key === 'sensor')!.collision.sensor).toBe(true);+ });+});++describe('buildCollisionPaletteModel', () => {+ const model = buildCollisionPaletteModel();++ it('has NO render slots or animations (a collision layer never draws)', () => {+ expect(model.slots).toEqual([]);+ expect(model.animations.size).toBe(0);+ });++ it('splits plain box → merge set, rich shapes → per-tile shapes', () => {+ // Only the solid box (id 1) may greedy-merge; slopes/halves/one-way/sensor spawn one each.+ expect(model.collidableTileIds).toEqual([1]);+ expect([...model.tileShapes.keys()].sort((a, b) => a - b)).toEqual([2, 3, 4, 5, 6, 7, 8, 9]);+ });++ it('every rich brush resolves to a collider shape (consumed by the spawn seam)', () => {+ for (const [id, rc] of model.tileShapes) {+ const shape = tileColliderShape(rc, 32, 32, false, false, false);+ expect(shape.kind, `brush #${id}`).toBeDefined();+ }+ // A ramp is a polygon; a one-way stays a box (its normal rides on the piece, not the shape).+ expect(tileColliderShape(model.tileShapes.get(2)!, 32, 32, false, false, false).kind).toBe('polygon');+ expect(tileColliderShape(model.tileShapes.get(8)!, 32, 32, false, false, false).kind).toBe('box');+ });+});