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): per-layer physics material for collision layers

yhhfc5b49f0c661
diff --git a/desktop/src/i18n/messages/tile.ts b/desktop/src/i18n/messages/tile.ts
index 6612d3cb4..a3979cc6c 100644
--- a/desktop/src/i18n/messages/tile.ts
+++ b/desktop/src/i18n/messages/tile.ts
@@ -151,6 +151,9 @@ export const tileMessages = defineMessages({
en: 'Paint obstacle cells over your background — solid, slope, one-way, or trigger.',
zh: '在背景上刷障碍格——实心、斜坡、单向或触发器。',
},
+ 'tile.collision.friction': { en: 'Friction', zh: '摩擦力' },
+ 'tile.collision.bounce': { en: 'Bounce', zh: '弹性' },
+ 'tile.collision.default': { en: 'default', zh: '默认' },
'tile.solidCount': { en: '{count} solid', zh: '{count} 个实心' },
'tile.save': { en: 'Save', zh: '保存' },
'tile.done': { en: 'Done', zh: '完成' },
diff --git a/desktop/src/panels/CollisionBrushPalette.tsx b/desktop/src/panels/CollisionBrushPalette.tsx
index 8f540477b..10c98570f 100644
--- a/desktop/src/panels/CollisionBrushPalette.tsx
+++ b/desktop/src/panels/CollisionBrushPalette.tsx
@@ -9,8 +9,13 @@
* 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 {
+ COLLISION_BRUSHES, tileIdOf, parseCollisionMaterial, collisionRefWithMaterial,
+ type CollisionBrush, type CollisionMaterial,
+} from 'esengine';
import { useTilemapPaint } from '@/store/tilemapPaintStore';
+import { SceneCommands } from '@/engine/SceneCommands';
+import { layerTilesetRefs } from '@/tilemap/layerTilesetModel';
import { t } from '@/i18n';
/** Brush key → localized label. The six slope/half brushes share the `.estileset` slope
@@ -56,13 +61,26 @@ function BrushIcon({ brush }: { brush: CollisionBrush }) {
/** 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() {
+export function CollisionBrushPalette({ sourceId }: { sourceId: number }) {
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;
+ // The whole-layer physics material rides IN the `builtin:collision` ref (as a query
+ // string), so it reuses the tileset-ref out-of-band channel (save / undo / live-push) —
+ // no new field. Editing it re-writes the ref via the same setLayerTilesets door.
+ const material = parseCollisionMaterial(layerTilesetRefs(sourceId));
+ const setMaterial = (patch: Partial<CollisionMaterial>) => {
+ const next: CollisionMaterial = { ...material, ...patch };
+ for (const k of Object.keys(next) as (keyof CollisionMaterial)[]) {
+ if (next[k] === undefined || Number.isNaN(next[k])) delete next[k];
+ }
+ SceneCommands.setLayerTilesets(sourceId, [collisionRefWithMaterial(next)]);
+ };
+ const num = (v: string): number | undefined => (v.trim() === '' ? undefined : Number(v));
+
return (
<div className="cp-panel">
<div className="cp-hint">{t('tile.collision.hint')}</div>
@@ -85,6 +103,26 @@ export function CollisionBrushPalette() {
</button>
))}
</div>
+ {/* Whole-layer physics material (applies to every painted cell). Blank = engine
+ default; keyed on the value so an external change (undo) refreshes the input. */}
+ <div className="cp-mat" key={`${material.friction ?? ''}|${material.restitution ?? ''}`}>
+ <label className="cp-mat-field">
+ <span>{t('tile.collision.friction')}</span>
+ <input
+ type="number" step="0.1" min="0" placeholder={t('tile.collision.default')}
+ defaultValue={material.friction ?? ''}
+ onBlur={(e) => setMaterial({ friction: num(e.target.value) })}
+ />
+ </label>
+ <label className="cp-mat-field">
+ <span>{t('tile.collision.bounce')}</span>
+ <input
+ type="number" step="0.1" min="0" max="1" placeholder={t('tile.collision.default')}
+ defaultValue={material.restitution ?? ''}
+ onBlur={(e) => setMaterial({ restitution: num(e.target.value) })}
+ />
+ </label>
+ </div>
</div>
);
}
diff --git a/desktop/src/panels/TilemapPainter.tsx b/desktop/src/panels/TilemapPainter.tsx
index 82538480c..33077486e 100644
--- a/desktop/src/panels/TilemapPainter.tsx
+++ b/desktop/src/panels/TilemapPainter.tsx
@@ -565,7 +565,7 @@ export function TilemapPainter() {
<Dices size={15} />
</IconButton>
</div>
- {collisionLayer && <CollisionBrushPalette />}
+ {collisionLayer && selectedId != null && <CollisionBrushPalette sourceId={selectedId} />}
{tool !== 'terrain' && !collisionLayer && (
<div className="tp-stamps">
<IconButton size="sm" title={t('tile.saveStamp')} onClick={() => updateStamps(addStamp(savedStamps, stamp))}>
diff --git a/desktop/src/theme/tilemap.css b/desktop/src/theme/tilemap.css
index 7f40c58b1..e22c01225 100644
--- a/desktop/src/theme/tilemap.css
+++ b/desktop/src/theme/tilemap.css
@@ -386,3 +386,30 @@
}
.cp-brush svg { color: var(--text); }
.cp-brush-label { font-size: var(--fs-xs); text-align: center; line-height: 1.1; }
+/* Whole-layer physics material (friction / bounce) for a collision layer. */
+.cp-mat {
+ display: flex;
+ gap: 8px;
+ padding-top: 8px;
+ margin-top: 4px;
+ border-top: 1px solid var(--line);
+}
+.cp-mat-field {
+ display: flex;
+ flex-direction: column;
+ gap: 3px;
+ flex: 1 1 0;
+ font-size: var(--fs-2xs);
+ color: var(--text-faint);
+}
+.cp-mat-field input {
+ width: 100%;
+ height: 22px;
+ padding: 0 6px;
+ background: var(--srf-2);
+ border: 1px solid var(--line);
+ border-radius: 4px;
+ color: var(--text);
+ font-size: var(--fs-xs);
+}
+.cp-mat-field input:focus { border-color: var(--acc); outline: none; }
diff --git a/desktop/src/tilemap/layerTilesetModel.ts b/desktop/src/tilemap/layerTilesetModel.ts
index 3c195e086..b2a09c757 100644
--- a/desktop/src/tilemap/layerTilesetModel.ts
+++ b/desktop/src/tilemap/layerTilesetModel.ts
@@ -9,7 +9,7 @@
* world; the editor re-resolves independently for a picture).
*/
import {
- resolveTilesetModel, isCollisionPaletteRef, buildCollisionPaletteModel,
+ resolveTilesetModel, isCollisionPaletteRef, buildCollisionPaletteModel, parseCollisionMaterial,
type TilesetModel, type ResolvedTileset,
} from 'esengine';
import { SceneModel } from '@/engine/SceneModel';
@@ -49,7 +49,7 @@ export async function loadLayerTilesetModel(refs: string[]): Promise<TilesetMode
// 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();
+ if (isCollisionPaletteRef(refs)) return buildCollisionPaletteModel(parseCollisionMaterial(refs));
const list: ResolvedTileset[] = [];
for (const ref of refs) {
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 679518835..a86677683 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: 1302 stable · 17 beta · 0 deprecated
+Symbols: 1305 stable · 17 beta · 0 deprecated
## ABI_LAYOUT_HASH — const
```
@@ -1484,6 +1484,13 @@ pointX: number
pointY: number
```
+## CollisionMaterial — interface
+```
+density: number | undefined
+friction: number | undefined
+restitution: number | undefined
+```
+
## Color — interface
```
a: number
@@ -7993,7 +8000,7 @@ BtPlugin
## buildCollisionPaletteModel — function
```
-(): TilesetModel
+(material?: CollisionMaterial): TilesetModel
```
## buildTerrainIndices — function
@@ -8146,6 +8153,11 @@ BtPlugin
(shape: ColliderShape, center: Vec2, angle: number, ppu: number): ColliderOutline
```
+## collisionRefWithMaterial — function
+```
+(material: CollisionMaterial): string
+```
+
## color — const
```
(r?: number, g?: number, b?: number, a?: number) => Color
@@ -9121,6 +9133,11 @@ NavPlugin
(raw: unknown): BusEffectDef[]
```
+## parseCollisionMaterial — function
+```
+(refs: readonly string[]): CollisionMaterial
+```
+
## parseLocaleTable — function
```
(text: string, path: string): LocaleTableAsset
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index ae465faed..a422dca26 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: 1301 stable · 19 beta · 0 deprecated
+Symbols: 1304 stable · 19 beta · 0 deprecated
## ANCHOR_AXES — const
```
@@ -1479,6 +1479,13 @@ pointX: number
pointY: number
```
+## CollisionMaterial — interface
+```
+density: number | undefined
+friction: number | undefined
+restitution: number | undefined
+```
+
## Color — interface
```
a: number
@@ -7988,7 +7995,7 @@ BtPlugin
## buildCollisionPaletteModel — function
```
-(): TilesetModel
+(material?: CollisionMaterial): TilesetModel
```
## buildTerrainIndices — function
@@ -8141,6 +8148,11 @@ BtPlugin
(shape: ColliderShape, center: Vec2, angle: number, ppu: number): ColliderOutline
```
+## collisionRefWithMaterial — function
+```
+(material: CollisionMaterial): string
+```
+
## color — const
```
(r?: number, g?: number, b?: number, a?: number) => Color
@@ -9126,6 +9138,11 @@ NodePlatformAdapter
(raw: unknown): BusEffectDef[]
```
+## parseCollisionMaterial — function
+```
+(refs: readonly string[]): CollisionMaterial
+```
+
## parseLocaleTable — function
```
(text: string, path: string): LocaleTableAsset
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index d791895dd..6247ba61a 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: 1312 stable · 17 beta · 0 deprecated
+Symbols: 1315 stable · 17 beta · 0 deprecated
## ANCHOR_AXES — const
```
@@ -1479,6 +1479,13 @@ pointX: number
pointY: number
```
+## CollisionMaterial — interface
+```
+density: number | undefined
+friction: number | undefined
+restitution: number | undefined
+```
+
## Color — interface
```
a: number
@@ -8012,7 +8019,7 @@ BtPlugin
## buildCollisionPaletteModel — function
```
-(): TilesetModel
+(material?: CollisionMaterial): TilesetModel
```
## buildTerrainIndices — function
@@ -8165,6 +8172,11 @@ BtPlugin
(shape: ColliderShape, center: Vec2, angle: number, ppu: number): ColliderOutline
```
+## collisionRefWithMaterial — function
+```
+(material: CollisionMaterial): string
+```
+
## color — const
```
(r?: number, g?: number, b?: number, a?: number) => Color
@@ -9145,6 +9157,11 @@ NavPlugin
(raw: unknown): BusEffectDef[]
```
+## parseCollisionMaterial — function
+```
+(refs: readonly string[]): CollisionMaterial
+```
+
## parseLocaleTable — function
```
(text: string, path: string): LocaleTableAsset
diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.ts
index c92543f90..a23dd6d8c 100644
--- a/sdk/src/core-content.ts
+++ b/sdk/src/core-content.ts
@@ -445,6 +445,8 @@ export {
COLLISION_BRUSHES,
isCollisionPaletteRef,
buildCollisionPaletteModel,
+ parseCollisionMaterial,
+ collisionRefWithMaterial,
tileCellCenter,
tileCellOutline,
isNonOrthogonal,
@@ -505,6 +507,7 @@ export {
type DecodedChunk,
type TileCollisionPiece,
type CollisionBrush,
+ type CollisionMaterial,
type TileGridParams,
type Vec2Like,
type TilesetAnimFrame,
diff --git a/sdk/src/tilemap/collisionPalette.ts b/sdk/src/tilemap/collisionPalette.ts
index e28ae08a1..d46690a27 100644
--- a/sdk/src/tilemap/collisionPalette.ts
+++ b/sdk/src/tilemap/collisionPalette.ts
@@ -23,12 +23,53 @@
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. */
+ * Mirrors the `builtin:<id>` shader convention — resolved in code, never a project asset.
+ * A per-layer physics material rides as a query string: `builtin:collision?friction=0.1`. */
export const COLLISION_PALETTE_REF = 'builtin:collision';
+/** A collision layer's whole-layer physics material (absent = engine default). */
+export interface CollisionMaterial {
+ friction?: number;
+ restitution?: number;
+ density?: number;
+}
+
+/** True for a collision ref — the bare sentinel OR a material-carrying `...?friction=…`. */
+function isCollisionRef(r: string): boolean {
+ return r === COLLISION_PALETTE_REF || r.startsWith(COLLISION_PALETTE_REF + '?');
+}
+
/** 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);
+ return refs.some(isCollisionRef);
+}
+
+/** The per-layer material encoded in a collision ref list, if any (else engine defaults). */
+export function parseCollisionMaterial(refs: readonly string[]): CollisionMaterial {
+ const ref = refs.find(isCollisionRef) ?? '';
+ const q = ref.indexOf('?');
+ if (q < 0) return {};
+ const out: CollisionMaterial = {};
+ for (const pair of ref.slice(q + 1).split('&')) {
+ const eq = pair.indexOf('=');
+ if (eq < 0) continue;
+ const key = pair.slice(0, eq);
+ const val = Number(pair.slice(eq + 1));
+ if (!Number.isFinite(val)) continue;
+ if (key === 'friction') out.friction = val;
+ else if (key === 'restitution') out.restitution = val;
+ else if (key === 'density') out.density = val;
+ }
+ return out;
+}
+
+/** Build a collision ref carrying a per-layer material (the bare sentinel when empty). */
+export function collisionRefWithMaterial(material: CollisionMaterial): string {
+ const parts: string[] = [];
+ if (material.friction !== undefined) parts.push(`friction=${material.friction}`);
+ if (material.restitution !== undefined) parts.push(`restitution=${material.restitution}`);
+ if (material.density !== undefined) parts.push(`density=${material.density}`);
+ return parts.length > 0 ? `${COLLISION_PALETTE_REF}?${parts.join('&')}` : COLLISION_PALETTE_REF;
}
/**
@@ -74,12 +115,19 @@ function isPlainBox(c: ResolvedTileCollision): boolean {
* the plain solid box (greedy-merged), `tileShapes` the richer brushes (slopes / halves /
* one-way / sensor), one collider each.
*/
-export function buildCollisionPaletteModel(): TilesetModel {
+export function buildCollisionPaletteModel(material?: CollisionMaterial): TilesetModel {
+ // A per-layer material folds onto every brush's collision. With a material set, even the
+ // plain solid box carries it (density/friction/restitution) — so it stops being a "plain
+ // box", leaves the greedy-merge set, and spawns one collider per cell (the material is
+ // whole-layer, correctness over the merge optimization; the default path still merges).
+ const mat = material && (material.friction !== undefined || material.restitution !== undefined
+ || material.density !== undefined) ? material : undefined;
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);
+ const rc: ResolvedTileCollision = mat ? { ...b.collision, ...mat } : b.collision;
+ if (isPlainBox(rc)) collidableTileIds.push(b.id);
+ else tileShapes.set(b.id, rc);
}
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.ts
index 686b2a6a7..8e11ab994 100644
--- a/sdk/src/tilemap/index.ts
+++ b/sdk/src/tilemap/index.ts
@@ -18,7 +18,8 @@ export {
export { tileCollisionOutlines, type TileCollisionPiece } from './tileCollisionOutline';
export {
COLLISION_PALETTE_REF, COLLISION_BRUSHES, isCollisionPaletteRef, buildCollisionPaletteModel,
- type CollisionBrush,
+ parseCollisionMaterial, collisionRefWithMaterial,
+ type CollisionBrush, type CollisionMaterial,
} from './collisionPalette';
export {
tileCellCenter, tileCellOutline, isNonOrthogonal, usesStagger, isHexOrientation, TileOrientation,
diff --git a/sdk/src/tilemap/tilemapPlugin.ts b/sdk/src/tilemap/tilemapPlugin.ts
index 360af31bc..b69fd156d 100644
--- a/sdk/src/tilemap/tilemapPlugin.ts
+++ b/sdk/src/tilemap/tilemapPlugin.ts
@@ -11,7 +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 { isCollisionPaletteRef, buildCollisionPaletteModel, parseCollisionMaterial } from './collisionPalette';
import { _bindTileCollisionLookup, type LayerCollisionTable } from './tileQuery';
import type { ResolvedTileCollision } from './tilesetResolve';
import {
@@ -283,7 +283,7 @@ export class TilemapPlugin implements Plugin {
// 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();
+ const model = buildCollisionPaletteModel(parseCollisionMaterial(refs));
if (model.collidableTileIds.length > 0) nativeCollisionIds.set(entity, model.collidableTileIds);
else nativeCollisionIds.delete(entity);
if (model.tileShapes.size > 0) nativeTileShapes.set(entity, model.tileShapes);
diff --git a/sdk/tests/collision-palette.test.ts b/sdk/tests/collision-palette.test.ts
index 61e4b1221..cb26dcbea 100644
--- a/sdk/tests/collision-palette.test.ts
+++ b/sdk/tests/collision-palette.test.ts
@@ -10,6 +10,7 @@
import { describe, it, expect } from 'vitest';
import {
COLLISION_PALETTE_REF, COLLISION_BRUSHES, isCollisionPaletteRef, buildCollisionPaletteModel,
+ parseCollisionMaterial, collisionRefWithMaterial,
} from '../src/tilemap/collisionPalette';
import { tileColliderShape } from '../src/tilemap/tiledLoader';
@@ -22,6 +23,30 @@ describe('isCollisionPaletteRef', () => {
expect(isCollisionPaletteRef([])).toBe(false);
expect(isCollisionPaletteRef(['@uuid:abc', 'maps/a.estileset'])).toBe(false);
});
+ it('matches a material-carrying collision ref', () => {
+ expect(isCollisionPaletteRef([`${COLLISION_PALETTE_REF}?friction=0.1`])).toBe(true);
+ });
+});
+
+describe('collision material (encoded in the ref)', () => {
+ it('round-trips friction / restitution / density through the ref', () => {
+ const m = { friction: 0.1, restitution: 0.4, density: 2 };
+ expect(parseCollisionMaterial([collisionRefWithMaterial(m)])).toEqual(m);
+ });
+ it('a bare ref (or empty material) carries no material', () => {
+ expect(collisionRefWithMaterial({})).toBe(COLLISION_PALETTE_REF);
+ expect(parseCollisionMaterial([COLLISION_PALETTE_REF])).toEqual({});
+ });
+ it('parses only finite numeric params, ignoring junk', () => {
+ expect(parseCollisionMaterial([`${COLLISION_PALETTE_REF}?friction=0.3&bogus=x&restitution=nope`]))
+ .toEqual({ friction: 0.3 });
+ });
+ it('a material makes even the solid box carry it (leaves the merge set)', () => {
+ const model = buildCollisionPaletteModel({ friction: 0.05 });
+ expect(model.collidableTileIds).toEqual([]); // no plain box any more
+ expect(model.tileShapes.get(1)).toEqual({ shape: { type: 'box' }, friction: 0.05 });
+ expect(model.tileShapes.get(8)!.friction).toBe(0.05); // one-way carries it too
+ });
});
describe('COLLISION_BRUSHES (serialization contract)', () => {