Skip to content

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.

feat(editor): show tilemap collision in the scene viewport

yhh100f5c7ee817
diff --git a/desktop/src/commands/editorCommands.ts b/desktop/src/commands/editorCommands.ts
index 2afcca8c1..a274b17c6 100644
--- a/desktop/src/commands/editorCommands.ts
+++ b/desktop/src/commands/editorCommands.ts
@@ -324,6 +324,13 @@ commands.register({
isChecked: () => editor().showColliders,
run: () => editor().toggleColliders(),
});
+commands.register({
+ id: 'view.toggleTileCollision',
+ label: t('cmd.view.toggleTileCollision'),
+ category: t('cat.view'),
+ isChecked: () => editor().showTileCollision,
+ run: () => editor().toggleTileCollision(),
+});
commands.register({
id: 'view.toggleCoordSpace',
label: t('cmd.view.toggleCoordSpace'),
diff --git a/desktop/src/engine/ViewportController.ts b/desktop/src/engine/ViewportController.ts
index ccbfcbe2f..4913f7d38 100644
--- a/desktop/src/engine/ViewportController.ts
+++ b/desktop/src/engine/ViewportController.ts
@@ -5,6 +5,8 @@ import {
ParticleEmitter, OneWayPlatform,
RevoluteJoint, DistanceJoint, PrismaticJoint, WeldJoint, WheelJoint, MotorJoint,
UINode, UICameraInfo, screenToUiWorld, uiWorldToScreen, uiPickAllWorld, type UICameraData,
+ TilemapLayer, TilemapAPI, decodeTilemapChunks, tileCollisionOutlines,
+ type TilesetModel, type TileCollisionPiece,
} from 'esengine';
import type { EntityId } from '@/types';
import { EngineHost } from './EngineHost';
@@ -692,6 +694,108 @@ export const ViewportController = {
return { kind: 'circle', cx: center.x, cy: center.y, r: Math.hypot(edge.x - center.x, edge.y - center.y), pts: [], handle: handle ?? null, sizeHandle: null, oneWay };
},
+ /**
+ * World-space collision outlines for a selected TilemapLayer's placed tiles — the
+ * SAME merged boxes + flip-aware rich shapes (slopes / circles / one-way / sensors)
+ * the runtime spawns at Play, but as a picture (nothing is spawned). `model` is the
+ * layer's resolved {@link TilesetModel} (re-resolved by the editor, not read from the
+ * plugin's private map). Empty when the entity isn't a live infinite tilemap layer.
+ * The per-frame projection is {@link projectTileCollision}; this is the cacheable half.
+ */
+ tilemapColliderOutlines(sourceId: EntityId, model: TilesetModel): TileCollisionPiece[] {
+ const world = EngineHost.world;
+ const rt = SceneModel.runtimeFor(sourceId);
+ if (!world || rt == null || !world.valid(rt) || !world.has(rt, TilemapLayer) || !world.has(rt, Transform)) return [];
+ const layer = world.get(rt, TilemapLayer) as { cellSize: { x: number; y: number } };
+ const tw = layer.cellSize.x;
+ const th = layer.cellSize.y;
+ if (!(tw > 0) || !(th > 0)) return [];
+ const t = world.get(rt, Transform);
+ const chunks = decodeTilemapChunks(TilemapAPI.exportChunks(rt) || '');
+ return tileCollisionOutlines(chunks, model, tw, th, t.worldPosition.x, t.worldPosition.y);
+ },
+
+ /**
+ * Project world-space tile-collision {@link TileCollisionPiece}s to screen SVG path
+ * data (CSS px), culling pieces whose centre falls outside the visible world rect so a
+ * large map only pays for what's on-screen. Returns four `d` strings: solid outlines,
+ * sensor outlines (styled dashed), and the one-way arrows split into shafts + heads.
+ * Null when there's no camera view.
+ */
+ projectTileCollision(
+ pieces: TileCollisionPiece[],
+ ): { solid: string; sensor: string; onewayLine: string; onewayHead: string } | null {
+ const canvas = EngineHost.canvas;
+ if (!canvas || !cameraView()) return null;
+ // Visible world AABB from the canvas corners (page coords → world), padded a couple
+ // of tiles so a piece straddling the edge still draws. If the projection is degenerate
+ // (no bounds), fall back to drawing everything.
+ const rect = canvas.getBoundingClientRect();
+ const corners = [
+ this.canvasToWorld(rect.left, rect.top),
+ this.canvasToWorld(rect.right, rect.top),
+ this.canvasToWorld(rect.left, rect.bottom),
+ this.canvasToWorld(rect.right, rect.bottom),
+ ];
+ let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
+ for (const c of corners) {
+ if (!c) continue;
+ minX = Math.min(minX, c.x); maxX = Math.max(maxX, c.x);
+ minY = Math.min(minY, c.y); maxY = Math.max(maxY, c.y);
+ }
+ const cull = Number.isFinite(minX);
+ const PAD = 128;
+ minX -= PAD; minY -= PAD; maxX += PAD; maxY += PAD;
+
+ let solid = '';
+ let sensor = '';
+ let onewayLine = '';
+ let onewayHead = '';
+ for (const piece of pieces) {
+ if (cull && (piece.center.x < minX || piece.center.x > maxX || piece.center.y < minY || piece.center.y > maxY)) continue;
+
+ for (const line of piece.polylines) {
+ let d = '';
+ for (let i = 0; i < line.length; i++) {
+ const s = this.worldToClient(line[i].x, line[i].y);
+ if (!s) { d = ''; break; }
+ d += `${i ? 'L' : 'M'}${s.x},${s.y}`;
+ }
+ if (d) { if (piece.sensor) sensor += `${d} `; else solid += `${d} `; }
+ }
+ for (const c of piece.circles) {
+ const ctr = this.worldToClient(c.c.x, c.c.y);
+ const edge = this.worldToClient(c.c.x + c.r, c.c.y);
+ if (!ctr || !edge) continue;
+ const r = Math.hypot(edge.x - ctr.x, edge.y - ctr.y);
+ // A full circle as two half-arcs (SVG has no closed-circle path primitive).
+ const arc = `M${ctr.x - r},${ctr.y}a${r},${r} 0 1,0 ${2 * r},0a${r},${r} 0 1,0 ${-2 * r},0 `;
+ if (piece.sensor) sensor += arc; else solid += arc;
+ }
+ // One-way: a short arrow out of the centre along the solid-side normal (world y-up
+ // → screen y-down). Screen-fixed length so it reads at any zoom, like the collider
+ // gizmo's one-way arrow. The side a body can land on; it passes through from behind.
+ if (piece.oneWay) {
+ const c = this.worldToClient(piece.center.x, piece.center.y);
+ if (c) {
+ const dx = piece.oneWay.nx;
+ const dy = -piece.oneWay.ny;
+ const len = Math.hypot(dx, dy) || 1;
+ const ux = dx / len;
+ const uy = dy / len;
+ const L = 14;
+ const bx = c.x + ux * L;
+ const by = c.y + uy * L;
+ onewayLine += `M${c.x},${c.y}L${bx},${by} `;
+ const px = -uy;
+ const py = ux;
+ onewayHead += `M${bx + ux * 6},${by + uy * 6}L${bx + px * 3.2},${by + py * 3.2}L${bx - px * 3.2},${by - py * 3.2}Z `;
+ }
+ }
+ }
+ return { solid, sensor, onewayLine, onewayHead };
+ },
+
/** (entity, joint-type) pairs for every scene-authored joint — the joint-gizmo set. */
jointGizmoKeys(): Array<{ id: EntityId; type: JointGizmoType }> {
const world = EngineHost.world;
diff --git a/desktop/src/i18n/messages/commands.ts b/desktop/src/i18n/messages/commands.ts
index c87f66b36..bab486e14 100644
--- a/desktop/src/i18n/messages/commands.ts
+++ b/desktop/src/i18n/messages/commands.ts
@@ -49,6 +49,7 @@ export const commandMessages = defineMessages({
'cmd.view.toggleGizmos': { en: 'Show Gizmos', zh: '显示 Gizmo' },
'cmd.view.togglePreviewFx': { en: 'Preview FX', zh: '预览特效' },
'cmd.view.toggleColliders': { en: 'Show Physics Gizmos', zh: '显示物理 Gizmo' },
+ 'cmd.view.toggleTileCollision': { en: 'Show Tile Collision', zh: '显示瓦片碰撞' },
'cmd.view.toggleCoordSpace': { en: 'Local Axes', zh: '局部坐标轴' },
'cmd.view.togglePivotMode': { en: 'Pivot (vs Center)', zh: '轴心(而非中心)' },
'cmd.view.toggleSnapping': { en: 'Snapping', zh: '吸附' },
diff --git a/desktop/src/i18n/messages/viewport.ts b/desktop/src/i18n/messages/viewport.ts
index 8a5779b9c..42387a4c3 100644
--- a/desktop/src/i18n/messages/viewport.ts
+++ b/desktop/src/i18n/messages/viewport.ts
@@ -69,6 +69,7 @@ export const viewportMessages = defineMessages({
'vp.flag.grid': { en: 'Grid', zh: '网格' },
'vp.flag.gizmos': { en: 'Gizmos', zh: 'Gizmo' },
'vp.flag.colliders': { en: 'Physics', zh: '物理' },
+ 'vp.flag.tileCollision': { en: 'Tile Collision', zh: '瓦片碰撞' },
'vp.flag.previewFx': { en: 'Preview FX', zh: '预览特效' },
'vp.flag.perf': { en: 'Perf', zh: '性能' },
diff --git a/desktop/src/layout/MenuBar.tsx b/desktop/src/layout/MenuBar.tsx
index 6fe34e370..e5e1f9c1d 100644
--- a/desktop/src/layout/MenuBar.tsx
+++ b/desktop/src/layout/MenuBar.tsx
@@ -131,6 +131,7 @@ export function MenuBar() {
cmdItem('view.toggleGrid'),
cmdItem('view.toggleGizmos'),
cmdItem('view.toggleColliders'),
+ cmdItem('view.toggleTileCollision'),
cmdItem('view.togglePreviewFx'),
{ sep: true },
cmdItem('view.toggleCoordSpace'),
diff --git a/desktop/src/panels/TilemapPainter.tsx b/desktop/src/panels/TilemapPainter.tsx
index 126a0b170..86189e3f0 100644
--- a/desktop/src/panels/TilemapPainter.tsx
+++ b/desktop/src/panels/TilemapPainter.tsx
@@ -28,6 +28,7 @@ import { buildStampGhost } from '@/tools/tileStampGhost';
import { colsFor, rowsFor, TERRAIN_COLORS } from '@/tools/tileMath';
import { loadTilesetAsset } from '@/tileset/loadTileset';
import { createTilemapFromTileset } from '@/tilemap/createTilemap';
+import { layerTilesetRefs } from '@/tilemap/layerTilesetModel';
import { AnimPreview, tileThumbStyle, type TileAtlas } from '@/tools/tileThumb';
import { parseStampLibrary, serializeStampLibrary, stampLibraryKey, addStamp, removeStampAt, type SavedStamp } from '@/tools/stampLibrary';
import { IconButton } from '@/components/IconButton';
@@ -45,19 +46,6 @@ const TOOLS: { id: PaintTool; icon: typeof Brush; label: string }[] = [
{ id: 'terrain', icon: Mountain, label: t('tile.tool.terrain') },
];
-/** Resolve the .estileset ref(s) a selected TilemapLayer references — the `tilesetAssets`
- * list (multi-tileset) or the singular `tilesetAsset` — as @uuid refs (not yet paths). */
-function selectedTilemapTilesetRefs(selectedId: number | null): string[] {
- if (selectedId == null) return [];
- const e = SceneModel.entityBySource(selectedId);
- const layer = e?.components.find((c) => c.type === 'TilemapLayer');
- if (!layer) return [];
- const data = layer.data as Record<string, unknown>;
- const list = data.tilesetAssets;
- if (Array.isArray(list)) return list.filter((r): r is string => typeof r === 'string' && r !== '');
- return typeof data.tilesetAsset === 'string' && data.tilesetAsset ? [data.tilesetAsset] : [];
-}
-
/** Natural pixel size of an image URL (for deriving a tileset's rows → tile count). */
function loadImageDims(url: string): Promise<{ w: number; h: number }> {
return new Promise((resolve) => {
@@ -127,7 +115,7 @@ export function TilemapPainter() {
// each assigned its firstId (matching resolveTilesetModel's running sum), so the tab
// bar can switch between them and painted cells encode to the right global gid.
useEffect(() => {
- const paths = selectedTilemapTilesetRefs(selectedId)
+ const paths = layerTilesetRefs(selectedId)
.map((r) => ProjectStore.assetInfo(r)?.path).filter((p): p is string => !!p);
if (paths.length === 0) { setTilesets([]); return; }
let alive = true;
@@ -328,18 +316,18 @@ export function TilemapPainter() {
// runtime), then reload the palette. Refs are @uuid, in firstId order == tab order.
const addTileset = (ref: string) => {
if (selectedId == null) return;
- SceneCommands.setLayerTilesets(selectedId, [...selectedTilemapTilesetRefs(selectedId), ref]);
+ SceneCommands.setLayerTilesets(selectedId, [...layerTilesetRefs(selectedId), ref]);
setAddOpen(false);
setReloadKey((k) => k + 1);
};
const removeTilesetAt = (i: number) => {
if (selectedId == null) return;
- SceneCommands.setLayerTilesets(selectedId, selectedTilemapTilesetRefs(selectedId).filter((_, j) => j !== i));
+ SceneCommands.setLayerTilesets(selectedId, layerTilesetRefs(selectedId).filter((_, j) => j !== i));
setReloadKey((k) => k + 1);
};
// The project's .estileset assets not already on this layer (populated on open).
const addable = addOpen
- ? ProjectStore.listAssets('tileset').filter((a) => !selectedTilemapTilesetRefs(selectedId).includes(a.ref))
+ ? ProjectStore.listAssets('tileset').filter((a) => !layerTilesetRefs(selectedId).includes(a.ref))
: [];
const atlas: TileAtlas | null = texUrl && natural
diff --git a/desktop/src/panels/Viewport.tsx b/desktop/src/panels/Viewport.tsx
index 130795bfa..8ade52fdb 100644
--- a/desktop/src/panels/Viewport.tsx
+++ b/desktop/src/panels/Viewport.tsx
@@ -15,7 +15,7 @@ import { activeMode, activeModeOverlays } from '@/mode/activeMode';
import { useEditorMode } from '@/store/editorModeStore';
import { RESOLUTION_PRESETS, RESOLUTION_PRESET_BY_ID, DESIGN_RESOLUTION_PRESETS, deviceDims } from '@/mode/resolutionPresets';
import { buildStampGhost } from '@/tools/tileStampGhost';
-import { TilemapAPI, tileIdOf, UINode, DimensionUnit, computeEffectiveOrthoSize } from 'esengine';
+import { TilemapAPI, tileIdOf, UINode, DimensionUnit, computeEffectiveOrthoSize, type TileCollisionPiece, type TilesetModel } from 'esengine';
import { commands } from '@/commands';
import { MOD_LABEL } from '@/commands/keybinding';
import { EngineHost } from '@/engine/EngineHost';
@@ -26,6 +26,7 @@ import { createFromSource, sourceById, SOURCE_DND_MIME } from '@/engine/entitySo
import { resizeUINodeAxis, type ResizeSide, type AxisResizeWrites } from '@/engine/uiResize';
import { IMAGE_RE } from '@/project/assetMeta';
import { createTilemapFromTileset } from '@/tilemap/createTilemap';
+import { layerTilesetRefs, loadLayerTilesetModel } from '@/tilemap/layerTilesetModel';
import { createAnimatedSpriteFromClip } from '@/flipbook/createAnimatedSprite';
import { SceneModel } from '@/engine/SceneModel';
import { SceneCommands } from '@/engine/SceneCommands';
@@ -581,6 +582,7 @@ export function Viewport() {
const showGrid = useEditorStore((s) => s.showGrid);
const showGizmos = useEditorStore((s) => s.showGizmos);
const showColliders = useEditorStore((s) => s.showColliders);
+ const showTileCollision = useEditorStore((s) => s.showTileCollision);
const previewFx = useEditorStore((s) => s.previewFx);
const activeGizmoAxis = useEditorStore((s) => s.activeGizmoAxis);
const coordSpace = useEditorStore((s) => s.coordSpace);
@@ -700,6 +702,40 @@ export function Viewport() {
() => (engine.status === 'ready' && showColliders ? ViewportController.colliderIds() : []),
[structRev, engine.status, showColliders],
);
+ // Tile-collision overlay: the selected TilemapLayer's per-tile collision, drawn into
+ // ONE SVG (not one per tile). Its world-space outlines are (re)built into a ref by the
+ // effect below whenever the layer / its content changes; the rAF projects them each
+ // frame. The tileset model is cached (keyed by the layer's tileset refs) so a paint
+ // stroke rebuilds outlines without re-reading the .estileset(s) from disk.
+ const tileColRef = useRef<SVGSVGElement | null>(null);
+ const tileColPiecesRef = useRef<TileCollisionPiece[]>([]);
+ const tileColModelRef = useRef<{ key: string; model: TilesetModel | null }>({ key: '', model: null });
+ useEffect(() => {
+ const clear = () => { tileColPiecesRef.current = []; };
+ if (engine.status !== 'ready' || !showTileCollision || !tilemapSelected || primaryId == null) {
+ clear();
+ tileColModelRef.current = { key: '', model: null };
+ return;
+ }
+ const refs = layerTilesetRefs(primaryId);
+ const key = refs.join('|');
+ const build = () => {
+ const model = tileColModelRef.current.model;
+ tileColPiecesRef.current = model ? ViewportController.tilemapColliderOutlines(primaryId, model) : [];
+ };
+ // Same tileset list as last time → reuse the cached model, just re-read the tiles.
+ if (tileColModelRef.current.key === key && tileColModelRef.current.model) { build(); return; }
+ // Tileset refs changed (or first show): reload the model, then build once it lands.
+ let alive = true;
+ clear();
+ void loadLayerTilesetModel(refs).then((model) => {
+ if (!alive) return;
+ tileColModelRef.current = { key, model };
+ build();
+ });
+ return () => { alive = false; };
+ }, [engine.status, showTileCollision, tilemapSelected, primaryId, dataRev]);
+
// Scene-authored joints are equally invisible — draw each as an anchor link (plus
// axis/velocity direction). Keyed by entity + joint type; same physics show flag.
const jointRefs = useRef(new Map<string, SVGSVGElement | null>());
@@ -1169,6 +1205,26 @@ export function Viewport() {
}
}
+ // Tile-collision overlay — the selected layer's per-tile collision, all in one SVG.
+ // Pieces are prebuilt in world space (the effect above); here we only project them
+ // to screen paths, culled to the visible world rect. Empty (flag off / no layer /
+ // still loading) clears the paths cheaply.
+ const tcSvg = tileColRef.current;
+ if (tcSvg) {
+ const pieces = tileColPiecesRef.current;
+ const paths = ready && !useEditorStore.getState().isPlaying && pieces.length > 0
+ ? ViewportController.projectTileCollision(pieces)
+ : null;
+ const setD = (sel: string, d: string) => {
+ const el = tcSvg.querySelector(sel) as SVGPathElement | null;
+ if (el) el.setAttribute('d', d);
+ };
+ setD('.tc-solid', paths?.solid ?? '');
+ setD('.tc-sensor', paths?.sensor ?? '');
+ setD('.tc-oneway', paths?.onewayLine ?? '');
+ setD('.tc-oneway-head', paths?.onewayHead ?? '');
+ }
+
// Joint gizmos — the anchor-to-anchor link (own body ↔ connected body), the
// prismatic/wheel slide axis, and the motor joint's target-velocity arrow.
// Unlinked joints (no connectedEntity yet) show just their own anchor dot.
@@ -1556,6 +1612,7 @@ export function Viewport() {
<DdCheck on={showGrid} label={t('vp.flag.grid')} onClick={() => commands.run('view.toggleGrid')} />
<DdCheck on={showGizmos} label={t('vp.flag.gizmos')} onClick={() => commands.run('view.toggleGizmos')} />
<DdCheck on={showColliders} label={t('vp.flag.colliders')} onClick={() => commands.run('view.toggleColliders')} />
+ <DdCheck on={showTileCollision} label={t('vp.flag.tileCollision')} onClick={() => commands.run('view.toggleTileCollision')} />
<DdCheck on={previewFx} label={t('vp.flag.previewFx')} onClick={() => commands.run('view.togglePreviewFx')} />
<DdCheck on={perfVisible} label={t('vp.flag.perf')} onClick={() => PerfMonitor.toggleOverlay()} />
</OvDropdown>
@@ -1759,6 +1816,16 @@ export function Viewport() {
);
})}
+ {/* Tile-collision overlay: ONE viewport-spanning SVG for the selected layer's whole
+ collision (solid outlines + dashed sensors + one-way arrows). The rAF writes the
+ combined path data each frame; empty when the flag's off or no tilemap is picked. */}
+ <svg className="viewport__tilecol-gizmo" ref={tileColRef} aria-hidden="true">
+ <path className="tc-solid" d="" />
+ <path className="tc-sensor" d="" />
+ <path className="tc-oneway" d="" />
+ <path className="tc-oneway-head" d="" />
+ </svg>
+
{/* Collider gizmos: a full-viewport SVG per collider (box polygon / circle),
positioned in absolute canvas-relative CSS px by the rAF. */}
{colliderIds.map((id) => (
diff --git a/desktop/src/store/editorStore.ts b/desktop/src/store/editorStore.ts
index 95d9c68aa..9ff5e24c6 100644
--- a/desktop/src/store/editorStore.ts
+++ b/desktop/src/store/editorStore.ts
@@ -41,6 +41,9 @@ interface EditorState {
showGizmos: boolean;
/** Draw collider outlines in the viewport (off declutters a physics-heavy scene). */
showColliders: boolean;
+ /** Draw the selected TilemapLayer's tile collision (slopes / circles / one-way /
+ * sensors) in the viewport, so tile collision is visible without entering Play. */
+ showTileCollision: boolean;
/** Simulate particle emitters live in edit mode (authoring preview). */
previewFx: boolean;
snapping: boolean;
@@ -66,6 +69,7 @@ interface EditorState {
toggleGrid: () => void;
toggleGizmos: () => void;
toggleColliders: () => void;
+ toggleTileCollision: () => void;
togglePreviewFx: () => void;
toggleSnapping: () => void;
setSnapStep: (step: number) => void;
@@ -128,6 +132,7 @@ export const useEditorStore = create<EditorState>((set) => ({
showGrid: true,
showGizmos: true,
showColliders: true,
+ showTileCollision: true,
previewFx: true,
snapping: false,
snapStep: 32,
@@ -142,6 +147,7 @@ export const useEditorStore = create<EditorState>((set) => ({
toggleGrid: () => set((s) => ({ showGrid: !s.showGrid })),
toggleGizmos: () => set((s) => ({ showGizmos: !s.showGizmos })),
toggleColliders: () => set((s) => ({ showColliders: !s.showColliders })),
+ toggleTileCollision: () => set((s) => ({ showTileCollision: !s.showTileCollision })),
togglePreviewFx: () => set((s) => ({ previewFx: !s.previewFx })),
toggleSnapping: () => set((s) => ({ snapping: !s.snapping })),
setSnapStep: (snapStep) => set({ snapStep, snapping: true }),
diff --git a/desktop/src/theme/app.css b/desktop/src/theme/app.css
index 2474ad1b7..ebe68597e 100644
--- a/desktop/src/theme/app.css
+++ b/desktop/src/theme/app.css
@@ -425,6 +425,41 @@ body.thumb-capture .viewport > :not(.viewport__stage):not(.viewport__play) {
opacity: 0;
}
+/* Tile-collision overlay: the selected TilemapLayer's per-tile collision — solid
+ outlines, dashed sensors, one-way arrows — all in ONE viewport-spanning SVG whose
+ path data the rAF writes each frame. Shares the collider colour: tile and entity
+ collision are the same concept, one visual language. */
+.viewport__tilecol-gizmo {
+ position: absolute;
+ inset: 0;
+ width: 100%;
+ height: 100%;
+ z-index: 2;
+ pointer-events: none;
+ overflow: visible;
+}
+.viewport__tilecol-gizmo .tc-solid {
+ fill: color-mix(in srgb, var(--gizmo-collider) 8%, transparent);
+ stroke: var(--gizmo-collider);
+ stroke-width: 1.25;
+ stroke-linejoin: round;
+}
+.viewport__tilecol-gizmo .tc-sensor {
+ fill: none;
+ stroke: var(--gizmo-collider);
+ stroke-width: 1.25;
+ stroke-dasharray: 4 3;
+ opacity: 0.8;
+}
+.viewport__tilecol-gizmo .tc-oneway {
+ stroke: var(--gizmo-collider);
+ stroke-width: 1.5;
+ stroke-linecap: round;
+}
+.viewport__tilecol-gizmo .tc-oneway-head {
+ fill: var(--gizmo-collider);
+}
+
/* Joint link gizmo: anchor dots + link line (own body ↔ connected body), the
prismatic/wheel slide axis, and the motor target-velocity arrow. The SVG spans
the viewport; the rAF writes absolute canvas-relative px. */
diff --git a/desktop/src/theme/viewport.css b/desktop/src/theme/viewport.css
index 414eb98d3..b68425ce4 100644
--- a/desktop/src/theme/viewport.css
+++ b/desktop/src/theme/viewport.css
@@ -218,6 +218,7 @@
.viewport--play .viewport__cam-gizmo,
.viewport--play .viewport__light-gizmo,
.viewport--play .viewport__collider-gizmo,
+.viewport--play .viewport__tilecol-gizmo,
.viewport--play .viewport__particle-gizmo {
display: none;
}
diff --git a/desktop/src/tilemap/layerTilesetModel.ts b/desktop/src/tilemap/layerTilesetModel.ts
new file mode 100644
index 000000000..ba17deda4
--- /dev/null
+++ b/desktop/src/tilemap/layerTilesetModel.ts
@@ -0,0 +1,68 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file layerTilesetModel.ts
+ * @brief Resolve a scene `TilemapLayer`'s `.estileset` reference(s) into the runtime
+ * {@link TilesetModel} — the SAME model `resolveTilesetModel` builds at Play, so
+ * the editor's tile-collision overlay draws exactly what will spawn. Kept out of
+ * `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 { SceneModel } from '@/engine/SceneModel';
+import { ProjectStore } from '@/project/ProjectStore';
+import { loadTilesetAsset } from '@/tileset/loadTileset';
+
+/** The `.estileset` ref(s) a TilemapLayer entity references — its `tilesetAssets` list
+ * (multi-tileset) or singular `tilesetAsset`, as @uuid refs (paths resolved by the caller). */
+export function layerTilesetRefs(sourceId: number | null): string[] {
+ if (sourceId == null) return [];
+ const layer = SceneModel.entityBySource(sourceId)?.components.find((c) => c.type === 'TilemapLayer');
+ if (!layer) return [];
+ const data = layer.data as Record<string, unknown>;
+ const list = data.tilesetAssets;
+ if (Array.isArray(list)) return list.filter((r): r is string => typeof r === 'string' && r !== '');
+ return typeof data.tilesetAsset === 'string' && data.tilesetAsset ? [data.tilesetAsset] : [];
+}
+
+/** Natural pixel height of an image URL — lets a tileset's tile count (and thus its
+ * global firstId span) be derived when the asset has no explicit `tileCount`. */
+function imageHeight(url: string): Promise<number> {
+ return new Promise((resolve) => {
+ const img = new Image();
+ img.onload = () => resolve(img.naturalHeight);
+ img.onerror = () => resolve(0);
+ img.src = url;
+ });
+}
+
+/**
+ * Load + resolve a layer's tileset refs into the runtime {@link TilesetModel}. The list
+ * is resolved together (contiguous firstId ranges) exactly like the runtime; each atlas'
+ * height is loaded only when the asset lacks a `tileCount`, so single-tileset layers
+ * (firstId 1) never touch the network. Returns null when nothing resolves.
+ */
+export async function loadLayerTilesetModel(refs: string[]): Promise<TilesetModel | null> {
+ const list: ResolvedTileset[] = [];
+ for (const ref of refs) {
+ const path = ProjectStore.assetInfo(ref)?.path;
+ if (!path) continue;
+ let asset;
+ try {
+ asset = await loadTilesetAsset(path);
+ } catch {
+ continue; // skip an unreadable tileset
+ }
+ let textureHeight: number | undefined;
+ if (!(typeof asset.tileCount === 'number' && asset.tileCount > 0)) {
+ const texPath = ProjectStore.assetInfo(asset.texture)?.path;
+ if (texPath) {
+ const h = await imageHeight(`estella://project/${texPath}`);
+ if (h > 0) textureHeight = h;
+ }
+ }
+ list.push({ asset, textureHandle: 0, textureHeight });
+ }
+ if (list.length === 0) return null;
+ return resolveTilesetModel(list);
+}
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 2fb1ab45c..7b5cc8ef5 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: 1179 stable · 17 beta · 1 deprecated
+Symbols: 1187 stable · 17 beta · 1 deprecated
## ABI_LAYOUT_HASH — const
```
@@ -1096,6 +1096,11 @@ sprite: number | undefined
16
```
+## CHUNK_SIZE — const
+```
+16
+```
+
## CacheAsBitmap — const
```
ComponentDef<CacheAsBitmapData>
@@ -1828,6 +1833,13 @@ Int3 = 7
Int4 = 8
```
+## DecodedChunk — interface
+```
+tiles: Uint16Array<ArrayBufferLike>
+x: number
+y: number
+```
+
## DecodedPixels — interface
```
height: number
@@ -2765,7 +2777,7 @@ number
## GeometryOptions — interface
```
dynamic: boolean | undefined
-indices: Uint32Array<ArrayBufferLike> | Uint16Array<ArrayBufferLike> | undefined
+indices: Uint16Array<ArrayBufferLike> | Uint32Array<ArrayBufferLike> | undefined
layout: VertexAttributeDescriptor[]
vertices: Float32Array<ArrayBufferLike>
```
@@ -4980,6 +4992,14 @@ sensor: boolean | undefined
shape: { type: "box"; } | { type: "polygon"; points: [number, number][]; } | { type: "circle"; cx: number; cy: number; r: number; }
```
+## ResolvedTileset — interface
+```
+asset: TilesetAsset
+textureHandle: number
+textureHeight: number | undefined
+textureWidth: number | undefined
+```
+
## ResourceDef — interface
```
_default: T
@@ -6229,6 +6249,15 @@ label: number
title: number
```
+## TileCollisionPiece — interface
+```
+center: Vec2
+circles: { c: Vec2; r: number; }[]
+oneWay: { nx: number; ny: number; } | null
+polylines: Vec2[][]
+sensor: boolean
+```
+
## TileCollisionShape — type
```
| { type: 'box' }
@@ -6383,6 +6412,14 @@ TileCollisionShape & {
}
```
+## TilesetModel — interface
+```
+animations: Map<number, { tileId: number; duration: number; }[]>
+collidableTileIds: number[]
+slots: TilesetModelSlot[]
+tileShapes: Map<number, ResolvedTileCollision>
+```
+
## TilesetTerrain — interface
```
color: string | undefined
@@ -7732,6 +7769,11 @@ Plugin
(src: ImageBitmapSource): Promise<DecodedPixels>
```
+## decodeTilemapChunks — function
+```
+(blob: string): DecodedChunk[]
+```
+
## defaultFrameStats — function
```
(): FrameStats
@@ -8767,6 +8809,11 @@ ReplicationPlugin
(basePath: string, relativePath: string): string
```
+## resolveTilesetModel — function
+```
+(tilesets: ResolvedTileset[]): TilesetModel
+```
+
## rotateFlagsCW — function
```
(flags: TileFlags): TileFlags
@@ -9102,6 +9149,11 @@ TextPlugin
<Ctx>(def: BtDefinition, ctx: Ctx, bb: Blackboard, registry: AiRegistry<Ctx>, rs: BtRunState, dt: number): Status
```
+## tileCollisionOutlines — function
+```
+(chunks: DecodedChunk[], model: TilesetModel, tileW: number, tileH: number, originX: number, originY: number): TileCollisionPiece[]
+```
+
## tileFlagsOf — function
```
(raw: number): TileFlags
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index fcdf952b6..af0cbfb44 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: 1178 stable · 19 beta · 1 deprecated
+Symbols: 1186 stable · 19 beta · 1 deprecated
## ANCHOR_AXES — const
```
@@ -1091,6 +1091,11 @@ sprite: number | undefined
16
```
+## CHUNK_SIZE — const
+```
+16
+```
+
## CacheAsBitmap — const
```
ComponentDef<CacheAsBitmapData>
@@ -1823,6 +1828,13 @@ Int3 = 7
Int4 = 8
```
+## DecodedChunk — interface
+```
+tiles: Uint16Array<ArrayBufferLike>
+x: number
+y: number
+```
+
## DecodedPixels — interface
```
height: number
@@ -2760,7 +2772,7 @@ number
## GeometryOptions — interface
```
dynamic: boolean | undefined
-indices: Uint32Array<ArrayBufferLike> | Uint16Array<ArrayBufferLike> | undefined
+indices: Uint16Array<ArrayBufferLike> | Uint32Array<ArrayBufferLike> | undefined
layout: VertexAttributeDescriptor[]
vertices: Float32Array<ArrayBufferLike>
```
@@ -4975,6 +4987,14 @@ sensor: boolean | undefined
shape: { type: "box"; } | { type: "polygon"; points: [number, number][]; } | { type: "circle"; cx: number; cy: number; r: number; }
```
+## ResolvedTileset — interface
+```
+asset: TilesetAsset
+textureHandle: number
+textureHeight: number | undefined
+textureWidth: number | undefined
+```
+
## ResourceDef — interface
```
_default: T
@@ -6224,6 +6244,15 @@ label: number
title: number
```
+## TileCollisionPiece — interface
+```
+center: Vec2
+circles: { c: Vec2; r: number; }[]
+oneWay: { nx: number; ny: number; } | null
+polylines: Vec2[][]
+sensor: boolean
+```
+
## TileCollisionShape — type
```
| { type: 'box' }
@@ -6378,6 +6407,14 @@ TileCollisionShape & {
}
```
+## TilesetModel — interface
+```
+animations: Map<number, { tileId: number; duration: number; }[]>
+collidableTileIds: number[]
+slots: TilesetModelSlot[]
+tileShapes: Map<number, ResolvedTileCollision>
+```
+
## TilesetTerrain — interface
```
color: string | undefined
@@ -7727,6 +7764,11 @@ Plugin
(src: ImageBitmapSource): Promise<DecodedPixels>
```
+## decodeTilemapChunks — function
+```
+(blob: string): DecodedChunk[]
+```
+
## defaultFrameStats — function
```
(): FrameStats
@@ -8772,6 +8814,11 @@ ReplicationPlugin
(basePath: string, relativePath: string): string
```
+## resolveTilesetModel — function
+```
+(tilesets: ResolvedTileset[]): TilesetModel
+```
+
## rotateFlagsCW — function
```
(flags: TileFlags): TileFlags
@@ -9107,6 +9154,11 @@ TextPlugin
<Ctx>(def: BtDefinition, ctx: Ctx, bb: Blackboard, registry: AiRegistry<Ctx>, rs: BtRunState, dt: number): Status
```
+## tileCollisionOutlines — function
+```
+(chunks: DecodedChunk[], model: TilesetModel, tileW: number, tileH: number, originX: number, originY: number): TileCollisionPiece[]
+```
+
## tileFlagsOf — function
```
(raw: number): TileFlags
diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.ts
index aa516472c..daf8687c9 100644
--- a/sdk/src/core-content.ts
+++ b/sdk/src/core-content.ts
@@ -399,6 +399,10 @@ export {
serializeTileset,
createTileset,
collidableTileIds,
+ resolveTilesetModel,
+ decodeTilemapChunks,
+ CHUNK_SIZE,
+ tileCollisionOutlines,
TB_N,
TB_E,
TB_S,
@@ -445,6 +449,10 @@ export {
type TilesetCollision,
type TileCollisionShape,
type ResolvedTileCollision,
+ type ResolvedTileset,
+ type TilesetModel,
+ type DecodedChunk,
+ type TileCollisionPiece,
type TilesetAnimFrame,
type TerrainMode,
type TilesetTerrain,
diff --git a/sdk/src/tilemap/index.ts b/sdk/src/tilemap/index.ts
index dfd26945f..899799b25 100644
--- a/sdk/src/tilemap/index.ts
+++ b/sdk/src/tilemap/index.ts
@@ -8,12 +8,13 @@ export {
parseTmjJson, parseTmjWithExternals, loadTiledMap, loadTiledCollisionObjects,
generateTileCollision, generateLayerCollision, generateChunkCollision,
generateChunkPolygonCollision, generateChunkTileShapes, generateObjectCollision, isCollisionObjectGroup,
- polygonLocalVerts, resolveRelativePath, packCollectionGrid,
+ polygonLocalVerts, tileColliderShape, oneWayNormalWorld, resolveRelativePath, packCollectionGrid,
type TiledMapData, type TiledLayerData, type TiledTilesetData,
type TiledCollectionTile, type CollectionGridTile,
type TiledObjectData, type TiledObjectGroupData, type TiledObjectShape,
type TiledAnimFrame, type TilemapLoadOptions,
} from './tiledLoader';
+export { tileCollisionOutlines, type TileCollisionPiece } from './tileCollisionOutline';
export { mergeCollisionTiles, type MergedRect } from './collisionMerge';
export { decodeTilemapChunks, CHUNK_SIZE, type DecodedChunk } from './chunkCodec';
export {
diff --git a/sdk/src/tilemap/tileCollisionOutline.ts b/sdk/src/tilemap/tileCollisionOutline.ts
new file mode 100644
index 000000000..523e33491
--- /dev/null
+++ b/sdk/src/tilemap/tileCollisionOutline.ts
@@ -0,0 +1,123 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file tileCollisionOutline.ts
+ * @brief Project a tilemap layer's per-tile collision into WORLD-space outlines —
+ * without spawning anything. The editor's viewport overlay renders these so a
+ * tile's collision (slopes / circles / one-way / sensors) is visible while
+ * authoring, not only after entering Play.
+ *
+ * This mirrors the runtime spawn EXACTLY: plain solid boxes greedy-merge through the
+ * same {@link mergeCollisionTiles} the native collider path uses, and richer shapes go
+ * through the same {@link tileColliderShape} + one-way normal reorientation that
+ * {@link generateChunkTileShapes} spawns from — so the overlay is what you get out of
+ * Play. Geometry is world PIXELS (`colliderShapeOutline` at ppu = 1); the caller
+ * projects it to the screen. No physics units here — the overlay is a picture, not a body.
+ */
+import type { Vec2 } from '../types';
+import type { DecodedChunk } from './chunkCodec';
+import { CHUNK_SIZE } from './chunkCodec';
+import { tileIdOf, tileFlagsOf } from './tileBits';
+import { mergeCollisionTiles } from './collisionMerge';
+import { tileColliderShape, oneWayNormalWorld } from './tiledLoader';
+import { colliderShapeOutline, shapeCenter } from '../physics/ColliderShape';
+import type { ColliderShape } from '../physics/ColliderShape';
+import type { TilesetModel } from './tilesetResolve';
+
+/**
+ * One tile-collision outline in world pixels — the polylines/circles a backend strokes,
+ * plus the flags the overlay styles by. `center` is the shape's world centre, carried so
+ * the caller can cull off-screen pieces before projecting each point. `oneWay` is the
+ * solid-side normal (world y-up, unit length), reoriented for the cell's flips.
+ */
+export interface TileCollisionPiece {
+ center: Vec2;
+ polylines: Vec2[][];
+ circles: { c: Vec2; r: number }[];
+ sensor: boolean;
+ oneWay: { nx: number; ny: number } | null;
+}
+
+/** World outline of a pixel-space collider shape at `worldCenter` (no rotation — tiles
+ * carry flips, not continuous angles, and flips are already baked into the shape). */
+function outlineAt(shape: ColliderShape, worldCenter: Vec2): { polylines: Vec2[][]; circles: { c: Vec2; r: number }[] } {
+ const center = shapeCenter(shape, worldCenter, 0, 1);
+ return colliderShapeOutline(shape, center, 0, 1);
+}
+
+/**
+ * Build world-pixel collision outlines for every placed collidable cell of a layer, given
+ * its decoded chunks + resolved {@link TilesetModel}. `tileW/tileH` are the layer cell
+ * size; `originX/originY` the layer's world origin (its Transform position, world y-up) —
+ * the same convention the native spawn uses, so an outline sits where its collider would.
+ */
+export function tileCollisionOutlines(
+ chunks: DecodedChunk[],
+ model: TilesetModel,
+ tileW: number,
+ tileH: number,
+ originX: number,
+ originY: number,
+): TileCollisionPiece[] {
+ const pieces: TileCollisionPiece[] = [];
+ const boxIds = new Set(model.collidableTileIds);
+ const shapes = model.tileShapes;
+ const hasBoxes = boxIds.size > 0;
+ const hasShapes = shapes.size > 0;
+ if (!hasBoxes && !hasShapes) return pieces;
+
+ for (const chunk of chunks) {
+ const baseX = chunk.x * CHUNK_SIZE;
+ const baseY = chunk.y * CHUNK_SIZE;
+
+ // Plain solid boxes: greedy-merge per chunk (matching generateChunkCollision), one
+ // outline per merged rectangle — so a solid platform reads as a few big rects.
+ if (hasBoxes) {
+ for (const rect of mergeCollisionTiles(chunk.tiles, CHUNK_SIZE, CHUNK_SIZE, boxIds)) {
+ const x0 = baseX + rect.col;
+ const y0 = baseY + rect.row;
+ const x1 = x0 + rect.width - 1;
+ const y1 = y0 + rect.height - 1;
+ const cx = originX + ((x0 + x1 + 1) / 2) * tileW;
+ const cy = originY - ((y0 + y1 + 1) / 2) * tileH;
+ const shape: ColliderShape = {
+ kind: 'box',
+ halfExtents: { x: rect.width * tileW * 0.5, y: rect.height * tileH * 0.5 },
+ offset: { x: 0, y: 0 },
+ };
+ const o = outlineAt(shape, { x: cx, y: cy });
+ pieces.push({ center: { x: cx, y: cy }, polylines: o.polylines, circles: o.circles, sensor: false, oneWay: null });
+ }
+ }
+
+ // Rich shapes: one outline per placed cell (polygon / circle / a box carrying a
+ // one-way, sensor, or material modifier), flip-applied like the spawned collider.
+ if (hasShapes) {
+ for (let i = 0; i < chunk.tiles.length; i++) {
+ const raw = chunk.tiles[i];
+ const rc = shapes.get(tileIdOf(raw));
+ if (!rc) continue;
+ const gx = baseX + (i % CHUNK_SIZE);
+ const gy = baseY + Math.floor(i / CHUNK_SIZE);
+ const cellCenter = { x: originX + (gx + 0.5) * tileW, y: originY - (gy + 0.5) * tileH };
+ const f = tileFlagsOf(raw);
+ const shape = tileColliderShape(rc, tileW, tileH, f.flipH, f.flipV, f.flipD);
+ const o = outlineAt(shape, cellCenter);
+ let oneWay: { nx: number; ny: number } | null = null;
+ if (rc.oneWay) {
+ const n = oneWayNormalWorld(rc.oneWay.nx, rc.oneWay.ny, f.flipH, f.flipV, f.flipD);
+ const len = Math.hypot(n.x, n.y);
+ if (len > 1e-4) oneWay = { nx: n.x / len, ny: n.y / len };
+ }
+ pieces.push({
+ center: shapeCenter(shape, cellCenter, 0, 1),
+ polylines: o.polylines,
+ circles: o.circles,
+ sensor: !!rc.sensor,
+ oneWay,
+ });
+ }
+ }
+ }
+ return pieces;
+}
diff --git a/sdk/src/tilemap/tiledLoader.ts b/sdk/src/tilemap/tiledLoader.ts
index 71639b7f9..b010da9a2 100644
--- a/sdk/src/tilemap/tiledLoader.ts
+++ b/sdk/src/tilemap/tiledLoader.ts
@@ -38,6 +38,7 @@ function uploadTiledLayerTiles(entity: Entity, layer: TiledLayerData): void {
}
}
import { RigidBody, BoxCollider, CircleCollider, PolygonCollider, ChainCollider, OneWayPlatform, BodyType } from '../physics/PhysicsComponents';
+import type { ColliderShape } from '../physics/ColliderShape';
import type { ResolvedTileCollision } from './tilesetResolve';
import { mergeCollisionTiles } from './collisionMerge';
import { CHUNK_SIZE } from './chunkCodec';
@@ -830,6 +831,35 @@ export function polygonLocalVerts(
});
}
+/**
+ * The pixel-space {@link ColliderShape} for a resolved tile collision, the cell's flip
+ * flags applied (origin = cell center, y up). The SINGLE tile→geometry definition shared
+ * by the runtime spawn ({@link generateChunkTileShapes}, which divides by ppu into a
+ * collider component) and the editor's tile-collision overlay (which feeds it to
+ * `colliderShapeOutline`). A box is flip-symmetric so its geometry ignores the flags; a
+ * polygon and a circle's centre go through {@link polygonLocalVerts}, matching the render.
+ */
+export function tileColliderShape(
+ rc: ResolvedTileCollision,
+ tileW: number,
+ tileH: number,
+ flipH: boolean,
+ flipV: boolean,
+ flipD: boolean,
+): ColliderShape {
+ const s = rc.shape;
+ if (s.type === 'polygon') {
+ return { kind: 'polygon', vertices: polygonLocalVerts(s.points, tileW, tileH, flipH, flipV, flipD) };
+ }
+ if (s.type === 'circle') {
+ // Reuse the polygon transform on the single centre point to apply flips; the
+ // radius is a tile-width fraction (assumes square-ish cells).
+ const c = polygonLocalVerts([[s.cx, s.cy]], tileW, tileH, flipH, flipV, flipD)[0];
+ return { kind: 'circle', radius: s.r * tileW, offset: c };
+ }
+ return { kind: 'box', halfExtents: { x: tileW * 0.5, y: tileH * 0.5 }, offset: { x: 0, y: 0 } };
+}
+
/**
* 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};
@@ -876,8 +906,9 @@ export function generateChunkPolygonCollision(
}
/** A one-way solid-side normal (world y-up; {0,1} = solid-top), reoriented by cell flips
- * so a flipped platform's solid side follows the render. */
-function oneWayNormalWorld(nx: number, ny: number, fH: boolean, fV: boolean, fD: boolean): { x: number; y: number } {
+ * so a flipped platform's solid side follows the render. Shared with the editor overlay,
+ * so a flipped one-way tile's arrow matches the side a body actually lands on at Play. */
+export function oneWayNormalWorld(nx: number, ny: number, fH: boolean, fV: boolean, fD: boolean): { x: number; y: number } {
let x = nx;
let y = ny;
if (fH) x = -x;
@@ -929,25 +960,24 @@ export function generateChunkTileShapes(
if (rc.restitution !== undefined) mat.restitution = rc.restitution;
if (rc.sensor) mat.isSensor = true;
- const s = rc.shape;
- if (s.type === 'polygon') {
+ // One pixel-space shape definition (flip-applied), scaled to physics units
+ // (÷ppu) into the matching collider component — the same geometry the editor
+ // overlay draws, so what you see out of Play is what spawns.
+ const shape = tileColliderShape(rc, tileW, tileH, f.flipH, f.flipV, f.flipD);
+ if (shape.kind === 'polygon') {
world.insert(entity, PolygonCollider, {
- vertices: polygonLocalVerts(s.points, tileW, tileH, f.flipH, f.flipV, f.flipD)
- .map((v) => ({ x: v.x / ppu, y: v.y / ppu })),
+ vertices: shape.vertices.map((v) => ({ x: v.x / ppu, y: v.y / ppu })),
...mat,
});
- } else if (s.type === 'circle') {
- // Reuse the polygon transform on the single centre point to apply flips; the
- // radius is a tile-width fraction (assumes square-ish cells).
- const c = polygonLocalVerts([[s.cx, s.cy]], tileW, tileH, f.flipH, f.flipV, f.flipD)[0];
+ } else if (shape.kind === 'circle') {
world.insert(entity, CircleCollider, {
- radius: (s.r * tileW) / ppu,
- offset: { x: c.x / ppu, y: c.y / ppu },
+ radius: shape.radius / ppu,
+ offset: { x: shape.offset.x / ppu, y: shape.offset.y / ppu },
...mat,
});
- } else {
+ } else if (shape.kind === 'box') {
world.insert(entity, BoxCollider, {
- halfExtents: { x: (tileW * 0.5) / ppu, y: (tileH * 0.5) / ppu },
+ halfExtents: { x: shape.halfExtents.x / ppu, y: shape.halfExtents.y / ppu },
...mat,
});
}
diff --git a/sdk/tests/tile-collision-outline.test.ts b/sdk/tests/tile-collision-outline.test.ts
new file mode 100644
index 000000000..4864b72b4
--- /dev/null
+++ b/sdk/tests/tile-collision-outline.test.ts
@@ -0,0 +1,124 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Editor tile-collision overlay geometry (unified-collision Phase 1b): the pure
+ * world-space outline projection that lets a tile's collision (slopes / circles /
+ * one-way / sensors) be seen in the scene viewport without entering Play. Asserts
+ * it mirrors the runtime spawn — the same merged boxes + flip-aware rich shapes.
+ */
+import { describe, it, expect } from 'vitest';
+import { tileColliderShape, oneWayNormalWorld } from '../src/tilemap/tiledLoader';
+import { tileCollisionOutlines } from '../src/tilemap/tileCollisionOutline';
+import { resolveTilesetModel, type ResolvedTileCollision, type TilesetModel } 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 { DecodedChunk } from '../src/tilemap/chunkCodec';
+
+/** A 16×16 chunk with cell index → raw tile value. */
+function chunk(x: number, y: number, cells: Record<number, number>): DecodedChunk {
+ const tiles = new Uint16Array(CHUNK_SIZE * CHUNK_SIZE);
+ for (const [i, v] of Object.entries(cells)) tiles[Number(i)] = v;
+ return { x, y, tiles };
+}
+
+/** A one-tile model keyed at global id 1 (the tile the tests place). */
+function modelOf(collision: ResolvedTileCollision['shape'], extra: Partial<ResolvedTileCollision> = {}): TilesetModel {
+ // Round-trip through the real resolver so the tests exercise the same split
+ // (plain box → collidableTileIds; rich → tileShapes) the runtime resolve does.
+ const model: TilesetModel = { slots: [], animations: new Map(), collidableTileIds: [], tileShapes: new Map() };
+ model.tileShapes.set(1, { shape: collision, ...extra });
+ return model;
+}
+
+describe('tileColliderShape (shared tile→geometry seam)', () => {
+ it('box → full-cell half extents, no offset (flip-symmetric)', () => {
+ const s = tileColliderShape({ shape: { type: 'box' } }, 16, 16, true, true, true);
+ expect(s).toEqual({ kind: 'box', halfExtents: { x: 8, y: 8 }, offset: { x: 0, y: 0 } });
+ });
+
+ it('circle → radius = r·tileW, centre offset via the flip transform', () => {
+ const s = tileColliderShape({ shape: { type: 'circle', cx: 0.5, cy: 0.5, r: 0.5 } }, 16, 16, false, false, false);
+ expect(s).toEqual({ kind: 'circle', radius: 8, offset: { x: 0, y: 0 } });
+ });
+
+ it('circle offset follows a horizontal flip', () => {
+ // Centre at the tile's left quarter → flipH sends it to the right quarter.
+ const s = tileColliderShape({ shape: { type: 'circle', cx: 0.25, cy: 0.5, r: 0.25 } }, 16, 16, true, false, false);
+ expect(s.kind).toBe('circle');
+ if (s.kind === 'circle') expect(s.offset.x).toBeCloseTo(4); // (0.75-0.5)·16
+ });
+
+ it('polygon → local px vertices from the flip-aware transform', () => {
+ const s = tileColliderShape({ shape: { type: 'polygon', points: [[0, 0], [1, 0], [1, 0.5]] } }, 16, 16, false, false, false);
+ expect(s.kind).toBe('polygon');
+ if (s.kind === 'polygon') expect(s.vertices[0]).toEqual({ x: -8, y: 8 }); // top-left pixel → local top-left
+ });
+});
+
+describe('tileCollisionOutlines', () => {
+ it('merges plain solid boxes into one rect outline (matching the native spawn)', () => {
+ const asset = parseTileset({
+ texture: '@uuid:x', tileWidth: 16, tileHeight: 16, columns: 4,
+ tiles: { 2: { collision: { type: 'box' } } },
+ });
+ const model = resolveTilesetModel([{ asset, textureHandle: 1 }]);
+ // Two adjacent solid-box cells (global id 2) → one 2×1 merged rect.
+ const pieces = tileCollisionOutlines([chunk(0, 0, { 0: encodeTile(2), 1: encodeTile(2) })], model, 16, 16, 0, 0);
+ expect(pieces).toHaveLength(1);
+ const p = pieces[0];
+ expect(p.sensor).toBe(false);
+ expect(p.oneWay).toBeNull();
+ // Same centre/extents generateChunkCollision spawns: centre (16,-8), half (16,8).
+ expect(p.center).toEqual({ x: 16, y: -8 });
+ expect(p.polylines).toHaveLength(1);
+ const ring = p.polylines[0];
+ expect(ring).toHaveLength(5); // 4 corners + closing point
+ expect(ring[0]).toEqual({ x: 0, y: -16 });
+ expect(ring[2]).toEqual({ x: 32, y: 0 });
+ });
+
+ it('emits a polygon ring per placed slope cell at the cell centre', () => {
+ const model = modelOf({ type: 'polygon', points: [[0, 1], [1, 1], [1, 0]] });
+ const pieces = tileCollisionOutlines([chunk(0, 0, { 0: encodeTile(1) })], model, 16, 16, 0, 0);
+ expect(pieces).toHaveLength(1);
+ expect(pieces[0].center).toEqual({ x: 8, y: -8 }); // cell (0,0) centre, world y-up
+ expect(pieces[0].polylines[0]).toHaveLength(4); // 3 verts + close
+ expect(pieces[0].circles).toHaveLength(0);
+ });
+
+ it('emits a circle for a circle-collision tile', () => {
+ const model = modelOf({ type: 'circle', cx: 0.5, cy: 0.5, r: 0.5 });
+ const pieces = tileCollisionOutlines([chunk(0, 0, { 0: encodeTile(1) })], model, 16, 16, 0, 0);
+ expect(pieces[0].circles).toEqual([{ c: { x: 8, y: -8 }, r: 8 }]);
+ expect(pieces[0].polylines).toHaveLength(0);
+ });
+
+ it('carries the sensor flag and the normalized one-way normal', () => {
+ const model = modelOf({ type: 'box' }, { sensor: true, oneWay: { nx: 0, ny: 1 } });
+ const pieces = tileCollisionOutlines([chunk(0, 0, { 0: encodeTile(1) })], model, 16, 16, 0, 0);
+ expect(pieces[0].sensor).toBe(true);
+ expect(pieces[0].oneWay).toEqual({ nx: 0, ny: 1 });
+ });
+
+ it('reorients the one-way normal for a flipped cell (matches oneWayNormalWorld)', () => {
+ const model = modelOf({ type: 'box' }, { oneWay: { nx: 0, ny: 1 } });
+ const raw = encodeTile(1, { flipH: false, flipV: true, flipD: false });
+ const pieces = tileCollisionOutlines([chunk(0, 0, { 0: raw })], model, 16, 16, 0, 0);
+ const n = oneWayNormalWorld(0, 1, false, true, false);
+ expect(pieces[0].oneWay).toEqual({ nx: n.x, ny: n.y });
+ expect(pieces[0].oneWay).toEqual({ nx: 0, ny: -1 });
+ });
+
+ it('offsets outlines by the layer world origin', () => {
+ const model = modelOf({ type: 'circle', cx: 0.5, cy: 0.5, r: 0.5 });
+ const pieces = tileCollisionOutlines([chunk(1, 0, { 0: encodeTile(1) })], model, 16, 16, 100, 200);
+ // chunk (1,0) local (0,0) → absolute tile (16,0): cx = 100 + (16+0.5)·16 = 364, cy = 200 - 0.5·16 = 192
+ expect(pieces[0].circles[0].c).toEqual({ x: 364, y: 192 });
+ });
+
+ it('is empty when the model has no collision', () => {
+ const model: TilesetModel = { slots: [], animations: new Map(), collidableTileIds: [], tileShapes: new Map() };
+ expect(tileCollisionOutlines([chunk(0, 0, { 0: encodeTile(1) })], model, 16, 16, 0, 0)).toEqual([]);
+ });
+});