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(tilemap): polygon tile collision, end to end
esenginee5a917728a7d
diff --git a/desktop/src/panels/TilesetEditor.tsx b/desktop/src/panels/TilesetEditor.tsxindex b3208c33b..23c901778 100644--- a/desktop/src/panels/TilesetEditor.tsx+++ b/desktop/src/panels/TilesetEditor.tsx@@ -13,7 +13,10 @@* animation slot onto the same asset later (the schema already carries them).*/-import { useEffect, useRef, useState, useSyncExternalStore, type CSSProperties } from 'react';+import {+ useEffect, useRef, useState, useSyncExternalStore,+ type CSSProperties, type MouseEvent as ReactMouseEvent,+} from 'react';import { Save, Plus, Trash2 } from 'lucide-react';import {TB_N, TB_E, TB_S, TB_W, TB_NE, TB_SE, TB_SW, TB_NW,@@ -68,6 +71,72 @@ const ZONES: { gx: number; gy: number; bit: number; corner: boolean }[] = [{ gx: 0, gy: 0, bit: TB_NW, corner: true },];+/** A focused per-tile collision-polygon editor: a magnified tile + click-to-add /+ * click-a-point-to-remove vertices, committed live (≥3 points) as undo steps. */+function PolygonEditor(props: {+ asset: TilesetAsset; texUrl: string; natural: { w: number; h: number };+ tileId: number; cols: number; onClose: () => void;+}) {+ const { asset, texUrl, natural, tileId, cols, onClose } = props;+ const { tileWidth: tw, tileHeight: th, margin: mg, spacing: sp } = asset;+ const col = (tileId - 1) % cols;+ const row = Math.floor((tileId - 1) / cols);+ const tileX = mg + col * (tw + sp);+ const tileY = mg + row * (th + sp);+ const SIZE = 260;+ const sx = SIZE / tw;+ const sy = SIZE / th;+ const existing = asset.tiles[tileId]?.collision;+ const [pts, setPts] = useState<[number, number][]>(+ existing?.type === 'polygon' ? existing.points.map((p) => [p[0], p[1]] as [number, number]) : [],+ );++ const commit = (next: [number, number][]) => { setPts(next); TilesetCommands.setTilePolygon(tileId, next); };++ const addPoint = (e: ReactMouseEvent) => {+ const r = (e.currentTarget as HTMLElement).getBoundingClientRect();+ const px = Math.round(((e.clientX - r.left) / r.width) * tw);+ const py = Math.round(((e.clientY - r.top) / r.height) * th);+ commit([...pts, [Math.max(0, Math.min(tw, px)), Math.max(0, Math.min(th, py))]]);+ };++ return (+ <div className="ts-pe-backdrop" onPointerDown={(e) => { if (e.target === e.currentTarget) onClose(); }}>+ <div className="ts-pe">+ <div className="ts-pe-head">+ <span>碰撞多边形 · #{tileId}</span>+ <span className="ts-grow" />+ <button type="button" onClick={() => commit([])}>清除</button>+ <button type="button" onClick={onClose}>完成</button>+ </div>+ <div+ className="ts-pe-stage"+ style={{+ width: SIZE, height: SIZE,+ backgroundImage: `url(${texUrl})`,+ backgroundPosition: `-${tileX * sx}px -${tileY * sy}px`,+ backgroundSize: `${natural.w * sx}px ${natural.h * sy}px`,+ }}+ onClick={addPoint}+ >+ <svg className="ts-pe-svg" viewBox={`0 0 ${tw} ${th}`} width={SIZE} height={SIZE}>+ {pts.length >= 2 && (+ <polygon className="ts-pe-poly" points={pts.map((p) => `${p[0]},${p[1]}`).join(' ')} />+ )}+ {pts.map((p, i) => (+ <circle+ key={i} cx={p[0]} cy={p[1]} r={Math.max(1.2, tw * 0.06)} className="ts-pe-pt"+ onClick={(e) => { e.stopPropagation(); commit(pts.filter((_, j) => j !== i)); }}+ />+ ))}+ </svg>+ </div>+ <div className="ts-pe-hint">点击添加顶点 · 点顶点删除 · ≥3 点生效</div>+ </div>+ </div>+ );+}+export function TilesetEditor() {useSyncExternalStore(TilesetDocument.subscribe, TilesetDocument.getRevision);const asset = TilesetDocument.asset;@@ -79,6 +148,8 @@ export function TilesetEditor() {const [natural, setNatural] = useState<{ w: number; h: number } | null>(null);const [zoom, setZoom] = useState(2);const [mode, setMode] = useState<'collision' | 'terrain'>('collision');+ const [shape, setShape] = useState<'box' | 'polygon'>('box');+ const [polyTile, setPolyTile] = useState<number | null>(null);const [activeSet, setActiveSet] = useState(0);const [hovered, setHovered] = useState<number | null>(null);// Live collision paint stroke: which tiles + the target on/off state, one undo step.@@ -105,7 +176,8 @@ export function TilesetEditor() {const terrainColor = TERRAIN_COLORS[activeSet % TERRAIN_COLORS.length];const isSolid = (id: number): boolean =>- drag?.ids.has(id) ? drag.on : asset.tiles[id]?.collision !== undefined;+ drag?.ids.has(id) ? drag.on : asset.tiles[id]?.collision?.type === 'box';+ const hasPolygon = (id: number): boolean => asset.tiles[id]?.collision?.type === 'polygon';const commitDrag = () => {const d = dragRef.current;@@ -142,7 +214,17 @@ export function TilesetEditor() {const top = (mg + row * (th + sp)) * zoom;const w = tw * zoom;const h = th * zoom;- if (mode === 'collision') {+ if (mode === 'collision' && shape === 'polygon') {+ cells.push(+ <div+ key={id}+ className={'ts-cell ts-pcell' + (hasPolygon(id) ? ' is-poly' : '')}+ style={{ left, top, width: w, height: h }}+ title={`#${id} — 点击编辑碰撞多边形`}+ onPointerDown={(e) => { e.preventDefault(); setPolyTile(id); }}+ />,+ );+ } else if (mode === 'collision') {cells.push(<divkey={id}@@ -211,6 +293,12 @@ export function TilesetEditor() {<button type="button" className={mode === 'collision' ? 'is-active' : ''} onClick={() => setMode('collision')}>碰撞</button><button type="button" className={mode === 'terrain' ? 'is-active' : ''} onClick={() => setMode('terrain')}>地形</button></div>+ {mode === 'collision' && (+ <div className="ts-modes">+ <button type="button" className={shape === 'box' ? 'is-active' : ''} onClick={() => setShape('box')}>盒</button>+ <button type="button" className={shape === 'polygon' ? 'is-active' : ''} onClick={() => setShape('polygon')}>多边形</button>+ </div>+ )}<span className="ts-sep" /><label className="ts-field"><span>Zoom</span>@@ -280,6 +368,13 @@ export function TilesetEditor() {</div>)}</div>++ {mode === 'collision' && shape === 'polygon' && polyTile != null && texUrl && natural && (+ <PolygonEditor+ asset={asset} texUrl={texUrl} natural={natural} tileId={polyTile} cols={cols}+ onClose={() => setPolyTile(null)}+ />+ )}</div>);}diff --git a/desktop/src/theme/tileset.css b/desktop/src/theme/tileset.cssindex 784bae022..44140f8e5 100644--- a/desktop/src/theme/tileset.css+++ b/desktop/src/theme/tileset.css@@ -6,6 +6,7 @@display: flex;flex-direction: column;height: 100%;+ position: relative;background: var(--srf-1, #16181c);color: var(--text, #d6d9de);font-size: 12px;@@ -177,6 +178,51 @@.ts-zone-c { left: 33.34%; top: 33.34%; }.ts-zone-c:hover { background: rgba(255, 255, 255, 0.1); }+/* Polygon-collision cell marker + the focused polygon editor overlay */+.ts-pcell.is-poly { background: rgba(90, 200, 250, 0.22); border-color: rgba(90, 200, 250, 0.85); }+.ts-pcell:hover { border-color: var(--star, #4c8fd6); background: rgba(76, 143, 214, 0.12); }++.ts-pe-backdrop {+ position: absolute;+ inset: 0;+ display: flex;+ align-items: center;+ justify-content: center;+ background: rgba(0, 0, 0, 0.55);+ z-index: 20;+}+.ts-pe {+ background: var(--srf-2, #1b1e23);+ border: 1px solid var(--line, #2a2d33);+ border-radius: 6px;+ padding: 10px;+ display: flex;+ flex-direction: column;+ gap: 8px;+}+.ts-pe-head { display: flex; align-items: center; gap: 8px; color: var(--text, #d6d9de); }+.ts-pe-head button {+ background: var(--control, #24272d);+ border: 1px solid var(--line, #2a2d33);+ border-radius: 3px;+ color: var(--text-dim, #9aa0aa);+ padding: 3px 9px;+ cursor: pointer;+ font: inherit;+}+.ts-pe-head button:hover { color: var(--text, #d6d9de); }+.ts-pe-stage {+ position: relative;+ image-rendering: pixelated;+ border: 1px solid var(--line, #2a2d33);+ cursor: crosshair;+}+.ts-pe-svg { position: absolute; left: 0; top: 0; pointer-events: none; }+.ts-pe-poly { fill: rgba(90, 200, 250, 0.3); stroke: #5ac8fa; stroke-width: 0.5; }+.ts-pe-pt { fill: #fff; stroke: #5ac8fa; stroke-width: 0.5; pointer-events: auto; cursor: pointer; }+.ts-pe-pt:hover { fill: #f0645a; }+.ts-pe-hint { color: var(--text-faint, #6b717c); font-size: 11px; text-align: center; }+.ts-empty,.ts-warn {display: flex;diff --git a/desktop/src/tileset/TilesetCommands.ts b/desktop/src/tileset/TilesetCommands.tsindex 4ae11eaa9..0412d9d1c 100644--- a/desktop/src/tileset/TilesetCommands.ts+++ b/desktop/src/tileset/TilesetCommands.ts@@ -50,6 +50,22 @@ export const TilesetCommands = {});},+ /**+ * Set a tile's polygon collision outline (tile-local pixels) as ONE undo step. Fewer+ * than 3 points clears any polygon collision on the tile (parseTileset would drop it).+ */+ setTilePolygon(id: number, points: [number, number][]): void {+ if (id <= 0) return;+ TilesetDocument.edit('Edit Tile Collision Shape', (a) => {+ if (points.length >= 3) {+ a.tiles[id] = { ...(a.tiles[id] ?? {}), collision: { type: 'polygon', points } };+ } else if (a.tiles[id]?.collision?.type === 'polygon') {+ delete a.tiles[id].collision;+ pruneEmpty(a, id);+ }+ });+ },+/** Add a terrain (autotile) set; returns the new set's index. */addTerrain(name: string, mode: TerrainMode): void {TilesetDocument.edit('Add Terrain', (a) => {diff --git a/sdk/src/tilemap/index.ts b/sdk/src/tilemap/index.tsindex 2e48a8f42..1341ae94a 100644--- a/sdk/src/tilemap/index.ts+++ b/sdk/src/tilemap/index.ts@@ -5,7 +5,8 @@ export { TilemapAPI, initTilemapAPI, shutdownTilemapAPI } from './tilemapAPI';export { TilemapPlugin, tilemapPlugin } from './tilemapPlugin';export {parseTiledMap, parseTmjJson, loadTiledMap, loadTiledCollisionObjects,- generateTileCollision, generateLayerCollision, generateChunkCollision, resolveRelativePath,+ generateTileCollision, generateLayerCollision, generateChunkCollision,+ generateChunkPolygonCollision, polygonLocalVerts, resolveRelativePath,type TiledMapData, type TiledLayerData, type TiledTilesetData,type TiledObjectData, type TiledObjectGroupData, type TiledObjectShape,type TiledAnimFrame, type TilemapLoadOptions,diff --git a/sdk/src/tilemap/tiledLoader.ts b/sdk/src/tilemap/tiledLoader.tsindex 807cb522e..bf86ef091 100644--- a/sdk/src/tilemap/tiledLoader.ts+++ b/sdk/src/tilemap/tiledLoader.ts@@ -37,9 +37,10 @@ function uploadTiledLayerTiles(entity: Entity, layer: TiledLayerData): void {}}}-import { RigidBody, BoxCollider, CircleCollider, BodyType } from '../physics/PhysicsComponents';+import { RigidBody, BoxCollider, CircleCollider, PolygonCollider, BodyType } from '../physics/PhysicsComponents';import { mergeCollisionTiles } from './collisionMerge';import { CHUNK_SIZE } from './chunkCodec';+import { tileIdOf, tileFlagsOf } from './tileBits';import { log } from '../logger';import { withMalloc } from '../wasmScratch';@@ -657,6 +658,71 @@ export function generateChunkCollision(return entities;}+/**+ * Convert a tile's normalized polygon outline ([0,1], x right / y down) to entity-local+ * vertices (origin = cell center, y up), applying the cell's flip flags so the collider+ * matches the rendered tile. The flip is the inverse of the renderer's `applyTileFlip`+ * (texture→quad): undo V, then H, then the diagonal swap.+ */+export function polygonLocalVerts(+ norm: ReadonlyArray<readonly [number, number]>,+ tileW: number,+ tileH: number,+ flipH: boolean,+ flipV: boolean,+ flipD: boolean,+): { x: number; y: number }[] {+ return norm.map(([sx, syDown]) => {+ let s = sx;+ let t = 1 - syDown; // to texture-up normalized+ if (flipV) t = 1 - t;+ if (flipH) s = 1 - s;+ if (flipD) { const tmp = s; s = t; t = tmp; }+ return { x: (s - 0.5) * tileW, y: (t - 0.5) * tileH };+ });+}++/**+ * Spawn one static PolygonCollider per placed tile whose global id has a polygon shape+ * (slopes / partial tiles). Box-shaped tiles are handled by {@link generateChunkCollision};+ * the two run together. Flip flags on a cell flip its polygon to match the render.+ */+export function generateChunkPolygonCollision(+ world: World,+ chunks: { x: number; y: number; tiles: Uint16Array }[],+ polygonShapes: Map<number, readonly [number, number][]>,+ tileW: number,+ tileH: number,+ originX: number,+ originY: number,+): Entity[] {+ const entities: Entity[] = [];+ if (polygonShapes.size === 0) return entities;+ for (const chunk of chunks) {+ const baseX = chunk.x * CHUNK_SIZE;+ const baseY = chunk.y * CHUNK_SIZE;+ for (let i = 0; i < chunk.tiles.length; i++) {+ const raw = chunk.tiles[i];+ const id = tileIdOf(raw);+ const shape = polygonShapes.get(id);+ if (!shape) continue;+ const gx = baseX + (i % CHUNK_SIZE);+ const gy = baseY + Math.floor(i / CHUNK_SIZE);+ const f = tileFlagsOf(raw);+ const entity = world.spawn();+ world.insert(entity, Transform, {+ position: { x: originX + (gx + 0.5) * tileW, y: originY - (gy + 0.5) * tileH, z: 0 },+ });+ world.insert(entity, RigidBody, { bodyType: BodyType.Static });+ world.insert(entity, PolygonCollider, {+ vertices: polygonLocalVerts(shape, tileW, tileH, f.flipH, f.flipV, f.flipD),+ });+ entities.push(entity);+ }+ }+ return entities;+}+export function loadTiledMap(world: World,mapData: TiledMapData,diff --git a/sdk/src/tilemap/tilemapPlugin.ts b/sdk/src/tilemap/tilemapPlugin.tsindex 466303bfd..dbc9895d9 100644--- a/sdk/src/tilemap/tilemapPlugin.ts+++ b/sdk/src/tilemap/tilemapPlugin.ts@@ -10,7 +10,7 @@ import { Tilemap } from './components';import { registerSceneComponentCodec } from '../scene';import { getTilemapSource, getResolvedTileset } from './tilesetCache';import { resolveTilesetModel } from './tilesetResolve';-import { generateLayerCollision, generateChunkCollision } from './tiledLoader';+import { generateLayerCollision, generateChunkCollision, generateChunkPolygonCollision } from './tiledLoader';import { decodeTilemapChunks } from './chunkCodec';import { Assets, type AssetsData } from '../asset/AssetPlugin';import { Time } from '../resource';@@ -43,6 +43,8 @@ export class TilemapPlugin implements Plugin {private collisionEntities_ = new Map<number, Entity[]>();/** TilemapLayer entity → its baked collidable tile ids (out-of-band scene data; drives native collision). */private nativeCollisionIds_ = new Map<number, number[]>();+ /** TilemapLayer entity → per-tile polygon collision outlines (global id → normalized points). */+ private nativePolygonShapes_ = new Map<number, Map<number, [number, number][]>>();/** TilemapLayer entity → its `.estileset` ref (out-of-band; resolved live → table/collision/anim). */private tilesetRefs_ = new Map<number, string>();/** Entities whose `.estileset` has been resolved+applied (so we do it once per load). */@@ -56,6 +58,7 @@ export class TilemapPlugin implements Plugin {// teach the scene (de)serializer to carry them out-of-band instead of// hardcoding TilemapLayer knowledge in scene.ts.const nativeCollisionIds = this.nativeCollisionIds_;+ const nativePolygonShapes = this.nativePolygonShapes_;const tilesetRefs = this.tilesetRefs_;const liveResolved = this.liveResolved_;registerSceneComponentCodec('TilemapLayer', {@@ -127,6 +130,7 @@ export class TilemapPlugin implements Plugin {TilemapAPI.destroyLayer(entity);initializedLayers.delete(entity);nativeCollisionIds.delete(entity);+ nativePolygonShapes.delete(entity);tilesetRefs.delete(entity);liveResolved.delete(entity);const colliders = collisionEntities.get(entity);@@ -174,21 +178,38 @@ export class TilemapPlugin implements Plugin {if (model.collidableTileIds.length > 0) {nativeCollisionIds.set(entity, model.collidableTileIds);}+ if (model.polygonShapes.size > 0) {+ nativePolygonShapes.set(entity, model.polygonShapes);+ }liveResolved.add(entity);}}- // Native path: collidable tiles spawn merged static colliders once in play- // mode — using the live `.estileset` ids when resolved, else the baked set.+ // Native path: collidable tiles spawn static colliders once in play mode+ // — box tiles greedy-merged, polygon tiles one collider each — using the+ // live `.estileset` shapes when resolved, else the baked id set.const collIds = nativeCollisionIds.get(entity);- if (playMode && collIds && collIds.length > 0 && !collisionEntities.has(entity)) {+ const polyShapes = nativePolygonShapes.get(entity);+ const hasBox = collIds != null && collIds.length > 0;+ const hasPoly = polyShapes != null && polyShapes.size > 0;+ if (playMode && (hasBox || hasPoly) && !collisionEntities.has(entity)) {const chunks = decodeTilemapChunks(TilemapAPI.exportChunks(entity));const tf = world.tryGet(entity, Transform) as { position: { x: number; y: number } } | null;- const spawned = generateChunkCollision(- world, chunks, new Set(collIds),- layerData.cellSize.x, layerData.cellSize.y,- tf?.position.x ?? 0, tf?.position.y ?? 0,- );+ const ox = tf?.position.x ?? 0;+ const oy = tf?.position.y ?? 0;+ const spawned: Entity[] = [];+ if (hasBox) {+ spawned.push(...generateChunkCollision(+ world, chunks, new Set(collIds),+ layerData.cellSize.x, layerData.cellSize.y, ox, oy,+ ));+ }+ if (hasPoly) {+ spawned.push(...generateChunkPolygonCollision(+ world, chunks, polyShapes,+ layerData.cellSize.x, layerData.cellSize.y, ox, oy,+ ));+ }collisionEntities.set(entity, spawned);}}@@ -340,6 +361,7 @@ export class TilemapPlugin implements Plugin {// Collider entities die with the world on reset/teardown; just drop our bookkeeping.this.collisionEntities_.clear();this.nativeCollisionIds_.clear();+ this.nativePolygonShapes_.clear();this.tilesetRefs_.clear();this.liveResolved_.clear();}diff --git a/sdk/src/tilemap/tilesetResolve.ts b/sdk/src/tilemap/tilesetResolve.tsindex 45234c36e..a274373e6 100644--- a/sdk/src/tilemap/tilesetResolve.ts+++ b/sdk/src/tilemap/tilesetResolve.ts@@ -37,8 +37,13 @@ export interface TilesetModel {slots: TilesetModelSlot[];/** Animations keyed by GLOBAL tile id → frames (frame tile ids are global too). */animations: Map<number, { tileId: number; duration: number }[]>;- /** Global tile ids flagged collidable (sorted). */+ /** Global tile ids with a BOX collision shape (greedy-merged at runtime; sorted). */collidableTileIds: number[];+ /**+ * Global tile id → polygon collision outline, points NORMALIZED to the tile+ * ([0,1], x right / y down). Emitted as one collider per placed tile (not merged).+ */+ polygonShapes: Map<number, [number, number][]>;}/** Tiles in a tileset: explicit `tileCount`, else the highest authored tile id. */@@ -58,10 +63,13 @@ export function resolveTilesetModel(tilesets: ResolvedTileset[]): TilesetModel {const slots: TilesetModelSlot[] = [];const animations = new Map<number, { tileId: number; duration: number }[]>();const collidable: number[] = [];+ const polygonShapes = new Map<number, [number, number][]>();let firstId = 1;for (const { asset, textureHandle } of tilesets) {slots.push({ firstId, textureHandle, columns: asset.columns });+ const tw = asset.tileWidth || 1;+ const th = asset.tileHeight || 1;// Local tile ids are 1-based; global id = firstId + (localId - 1).for (const key of Object.keys(asset.tiles)) {@@ -69,7 +77,11 @@ export function resolveTilesetModel(tilesets: ResolvedTileset[]): TilesetModel {if (!Number.isInteger(localId) || localId <= 0) continue;const globalId = firstId + localId - 1;const tile = asset.tiles[localId];- if (tile.collision) collidable.push(globalId);+ if (tile.collision?.type === 'polygon') {+ polygonShapes.set(globalId, tile.collision.points.map(([px, py]) => [px / tw, py / th]));+ } else if (tile.collision) {+ collidable.push(globalId);+ }if (tile.animation && tile.animation.length > 0) {animations.set(globalId,@@ -85,5 +97,5 @@ export function resolveTilesetModel(tilesets: ResolvedTileset[]): TilesetModel {}collidable.sort((a, b) => a - b);- return { slots, animations, collidableTileIds: collidable };+ return { slots, animations, collidableTileIds: collidable, polygonShapes };}diff --git a/sdk/tests/tilemap-polygon-collision.test.ts b/sdk/tests/tilemap-polygon-collision.test.tsnew file mode 100644index 000000000..5b9d402bd--- /dev/null+++ b/sdk/tests/tilemap-polygon-collision.test.ts@@ -0,0 +1,103 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { describe, it, expect, vi } from 'vitest';+import { polygonLocalVerts, generateChunkPolygonCollision } from '../src/tilemap/tiledLoader';+import { resolveTilesetModel } from '../src/tilemap/tilesetResolve';+import { parseTileset } from '../src/tilemap/tilesetAsset';+import { encodeTile } from '../src/tilemap/tileBits';+import { CHUNK_SIZE } from '../src/tilemap/chunkCodec';+import type { World } from '../src/world';+import type { Entity } from '../src/types';++function mockWorld() {+ let nextId = 1;+ const comps = new Map<number, Map<string, any>>();+ const world = {+ spawn: vi.fn(() => { const id = nextId++ as Entity; comps.set(id, new Map()); return id; }),+ insert: vi.fn((e: Entity, c: any, d: any) => { comps.get(e)!.set(c._name, d); }),+ } as unknown as World;+ return { world, comps };+}++describe('resolveTilesetModel polygon shapes', () => {+ it('splits box vs polygon and normalizes polygon points', () => {+ const asset = parseTileset({+ texture: '@uuid:x', tileWidth: 16, tileHeight: 16, columns: 4,+ tiles: {+ 2: { collision: { type: 'box' } },+ 3: { collision: { type: 'polygon', points: [[0, 0], [16, 0], [16, 8]] } },+ },+ });+ const model = resolveTilesetModel([{ asset, textureHandle: 1 }]);+ expect(model.collidableTileIds).toEqual([2]); // box only+ expect(model.polygonShapes.get(3)).toEqual([[0, 0], [1, 0], [1, 0.5]]); // normalized+ expect(model.polygonShapes.has(2)).toBe(false);+ });++ it('re-keys polygon ids into the global id space across tilesets', () => {+ const a = parseTileset({+ texture: '@uuid:a', tileWidth: 16, tileHeight: 16, columns: 2, tileCount: 4,+ tiles: { 1: { collision: { type: 'polygon', points: [[0, 0], [16, 16], [0, 16]] } } },+ });+ const b = parseTileset({+ texture: '@uuid:b', tileWidth: 16, tileHeight: 16, columns: 2,+ tiles: { 1: { collision: { type: 'polygon', points: [[0, 0], [16, 0], [0, 16]] } } },+ });+ const model = resolveTilesetModel([{ asset: a, textureHandle: 1 }, { asset: b, textureHandle: 2 }]);+ expect(model.polygonShapes.has(1)).toBe(true); // tileset a, local 1 → global 1+ expect(model.polygonShapes.has(5)).toBe(true); // tileset b, local 1 → global 1+4 = 5+ });+});++describe('polygonLocalVerts flip transforms', () => {+ // A single corner point at the tile's top-left pixel (0,0).+ const TL = [[0, 0]] as const;++ it('identity puts the top-left pixel at the local top-left', () => {+ expect(polygonLocalVerts(TL, 16, 16, false, false, false)[0]).toEqual({ x: -8, y: 8 });+ });+ it('flipH mirrors to the top-right', () => {+ expect(polygonLocalVerts(TL, 16, 16, true, false, false)[0]).toEqual({ x: 8, y: 8 });+ });+ it('flipV mirrors to the bottom-left', () => {+ expect(polygonLocalVerts(TL, 16, 16, false, true, false)[0]).toEqual({ x: -8, y: -8 });+ });+ it('flipD (anti-diagonal) sends the top-left to the bottom-right', () => {+ // matches the renderer's applyTileFlip swap convention.+ expect(polygonLocalVerts(TL, 16, 16, false, false, true)[0]).toEqual({ x: 8, y: -8 });+ });+});++describe('generateChunkPolygonCollision', () => {+ it('spawns one PolygonCollider per polygon tile at the cell centre', () => {+ const { world, comps } = mockWorld();+ const tiles = new Uint16Array(CHUNK_SIZE * CHUNK_SIZE);+ tiles[0] = encodeTile(3); // (0,0) → polygon tile+ tiles[1] = encodeTile(2); // (1,0) → not a polygon (ignored here)+ const shapes = new Map<number, [number, number][]>([[3, [[0, 0], [1, 0], [1, 0.5]]]]);+ const ents = generateChunkPolygonCollision(world, [{ x: 0, y: 0, tiles }], shapes, 16, 16, 0, 0);+ expect(ents).toHaveLength(1);+ const c = comps.get(ents[0] as number)!;+ expect(c.get('Transform').position).toMatchObject({ x: 8, y: -8 }); // cell (0,0) centre+ expect(c.get('PolygonCollider').vertices).toHaveLength(3);+ expect(c.get('RigidBody').bodyType).toBeDefined();+ });++ it('flips the polygon when the placed cell carries flip flags', () => {+ const { world, comps } = mockWorld();+ const tiles = new Uint16Array(CHUNK_SIZE * CHUNK_SIZE);+ tiles[0] = encodeTile(1, { flipH: true, flipV: false, flipD: false });+ const shapes = new Map<number, [number, number][]>([[1, [[0, 0]]]]); // top-left point+ const ents = generateChunkPolygonCollision(world, [{ x: 0, y: 0, tiles }], shapes, 16, 16, 0, 0);+ const v = comps.get(ents[0] as number)!.get('PolygonCollider').vertices[0];+ expect(v).toEqual({ x: 8, y: 8 }); // top-left mirrored to top-right under flipH+ });++ it('is a no-op when no placed tile has a polygon shape', () => {+ const { world } = mockWorld();+ const tiles = new Uint16Array(CHUNK_SIZE * CHUNK_SIZE);+ tiles[0] = encodeTile(9);+ const shapes = new Map<number, [number, number][]>([[3, [[0, 0]]]]);+ expect(generateChunkPolygonCollision(world, [{ x: 0, y: 0, tiles }], shapes, 16, 16, 0, 0)).toHaveLength(0);+ });+});diff --git a/sdk/tests/tileset-resolve.test.ts b/sdk/tests/tileset-resolve.test.tsindex 657e22338..f43990ead 100644--- a/sdk/tests/tileset-resolve.test.ts+++ b/sdk/tests/tileset-resolve.test.ts@@ -22,7 +22,9 @@ describe('resolveTilesetModel', () => {};const m = resolveTilesetModel([rt]);expect(m.slots).toEqual([{ firstId: 1, textureHandle: 100, columns: 4 }]);- expect(m.collidableTileIds).toEqual([2, 7]);+ // box tiles greedy-merge (collidableTileIds); polygon tiles carry their own shape.+ expect(m.collidableTileIds).toEqual([2]);+ expect(m.polygonShapes.get(7)).toEqual([[0, 1], [1, 1], [0, 0]]); // normalized to the tileexpect(m.animations.size).toBe(0);});