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(tilemap): editor-convention muscle memory — modifiers, layer menu, tileset batch authoring

esenginebe76d5176865
diff --git a/desktop/src/i18n/messages/tile.ts b/desktop/src/i18n/messages/tile.ts
index eb8178788..78ede34a2 100644
--- a/desktop/src/i18n/messages/tile.ts
+++ b/desktop/src/i18n/messages/tile.ts
@@ -34,6 +34,11 @@ export const tileMessages = defineMessages({
// — Painter layer strip —
'tile.newLayerTip': { en: 'New layer on this tileset', zh: '在此瓦片集上新建层' },
+ 'tile.layerRename': { en: 'Rename', zh: '重命名' },
+ 'tile.layerDuplicate': { en: 'Duplicate layer', zh: '复制层' },
+ 'tile.layerMoveUp': { en: 'Move up', zh: '上移' },
+ 'tile.layerMoveDown': { en: 'Move down', zh: '下移' },
+ 'tile.layerDelete': { en: 'Delete layer', zh: '删除层' },
'tile.show': { en: 'Show', zh: '显示' },
'tile.hide': { en: 'Hide', zh: '隐藏' },
'tile.paintOn': { en: 'Paint on "{name}"', zh: '在“{name}”上绘制' },
@@ -84,6 +89,7 @@ export const tileMessages = defineMessages({
'tile.mode.collision': { en: 'Collision', zh: '碰撞' },
'tile.mode.terrain': { en: 'Terrain', zh: '地形' },
'tile.mode.animation': { en: 'Animation', zh: '动画' },
+ 'tile.mode.properties': { en: 'Properties', zh: '属性' },
'tile.shape.aria': { en: 'Collision shape', zh: '碰撞形状' },
'tile.shape.box': { en: 'Box', zh: '矩形' },
'tile.shape.polygon': { en: 'Polygon', zh: '多边形' },
@@ -95,7 +101,14 @@ export const tileMessages = defineMessages({
'tile.sensorTip': { en: 'Sensor: painted collision is a non-solid trigger (fires events, no physical response)', zh: '触发器:所画碰撞为非实心触发(触发事件、无物理响应)' },
'tile.friction': { en: 'friction', zh: '摩擦' },
'tile.restitution': { en: 'bounce', zh: '弹性' },
- 'tile.cell.circleTip': { en: 'Tile #{id} — click to fit a circle collider (click again to clear)', zh: '瓦片 #{id}——点击放入圆形碰撞(再点清除)' },
+ 'tile.density': { en: 'density', zh: '密度' },
+ 'tile.cell.circleTip': { en: 'Tile #{id} — drag paints fitted circle colliders (start on a circled tile to clear)', zh: '瓦片 #{id}——拖动铺设圆形碰撞(从已有圆形的瓦片起拖则清除)' },
+ 'tile.cell.propTip': { en: 'Tile #{id} — click to edit its custom properties', zh: '瓦片 #{id}——点击编辑自定义属性' },
+ 'tile.prop.pickHint': { en: 'Click a tile to edit its custom key/value properties.', zh: '点击一个瓦片以编辑它的自定义键值属性。' },
+ 'tile.prop.key': { en: 'key', zh: '键' },
+ 'tile.prop.value': { en: 'value', zh: '值' },
+ 'tile.prop.add': { en: 'Add property', zh: '添加属性' },
+ 'tile.prop.remove': { en: 'Remove property', zh: '移除属性' },
// Slope / half-tile presets (polygon mode): pick one, then click tiles to stamp it.
'tile.slope.presets': { en: 'Presets', zh: '预设' },
'tile.slope.freeform': { en: 'Custom…', zh: '自定义…' },
diff --git a/desktop/src/panels/TilemapPainter.tsx b/desktop/src/panels/TilemapPainter.tsx
index 86189e3f0..fa0648c7a 100644
--- a/desktop/src/panels/TilemapPainter.tsx
+++ b/desktop/src/panels/TilemapPainter.tsx
@@ -32,6 +32,7 @@ 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';
+import { ContextMenu } from '@/components/Menu';
import { t } from '@/i18n';
const TOOLS: { id: PaintTool; icon: typeof Brush; label: string }[] = [
@@ -100,6 +101,8 @@ export function TilemapPainter() {
// did not, so the palette-load effect below wouldn't otherwise re-read the new list.
const [reloadKey, setReloadKey] = useState(0);
const [addOpen, setAddOpen] = useState(false);
+ const [layerCtx, setLayerCtx] = useState<{ x: number; y: number; id: number } | null>(null);
+ const [renamingLayer, setRenamingLayer] = useState<number | null>(null);
// Saved-stamp library — per project (stamps carry gids only this project's tilesets
// mint), persisted in localStorage, pure logic in tools/stampLibrary.
@@ -261,6 +264,19 @@ export function TilemapPainter() {
const setLayerOpacity = (id: number, v: number) =>
SceneCommands.setField(id, 'TilemapLayer', 'opacity', 'number', v);
+ // Layer chip context menu (rename / duplicate / reorder / delete) — the layer
+ // bar is the tilemap home, so managing layers must not require the Outliner.
+ const layerMenuItems = (id: number) => {
+ const i = layers.findIndex((L) => L.id === id);
+ return [
+ { label: t('tile.layerRename'), onClick: () => setRenamingLayer(id) },
+ { label: t('tile.layerDuplicate'), onClick: () => SceneCommands.duplicateEntity(id) },
+ { label: t('tile.layerMoveUp'), disabled: i <= 0, onClick: () => SceneCommands.reorderEntity(id, layers[i - 1]!.id, true) },
+ { label: t('tile.layerMoveDown'), disabled: i < 0 || i >= layers.length - 1, onClick: () => SceneCommands.reorderEntity(id, layers[i + 1]!.id, false) },
+ { label: t('tile.layerDelete'), onClick: () => SceneCommands.deleteEntity(id) },
+ ];
+ };
+
const commitSel = (r: SelRect) => {
const w = r.c1 - r.c0 + 1;
const h = r.r1 - r.r0 + 1;
@@ -388,19 +404,45 @@ export function TilemapPainter() {
<Plus size={14} />
</IconButton>
{layers.map((L) => (
- <span key={L.id} className={'tp-layer' + (L.id === selectedId ? ' is-active' : '')}>
+ <span
+ key={L.id}
+ className={'tp-layer' + (L.id === selectedId ? ' is-active' : '')}
+ onContextMenu={(e) => {
+ e.preventDefault();
+ setLayerCtx({ x: e.clientX, y: e.clientY, id: L.id });
+ }}
+ >
<button
type="button" className="tp-layer-vis" title={L.hidden ? t('tile.show') : t('tile.hide')}
onClick={() => SceneCommands.setEntityVisible(L.id, L.hidden)}
>
{L.hidden ? <EyeOff size={12} /> : <Eye size={12} />}
</button>
- <button
- type="button" className="tp-layer-name" title={t('tile.paintOn', { name: L.name })}
- onClick={() => useSelection.getState().select(L.id)}
- >
- {L.name}
- </button>
+ {renamingLayer === L.id ? (
+ <input
+ className="tp-layer-rename"
+ defaultValue={L.name}
+ autoFocus
+ onFocus={(e) => e.target.select()}
+ onBlur={(e) => {
+ const name = e.target.value.trim();
+ if (name && name !== L.name) SceneCommands.renameEntity(L.id, name);
+ setRenamingLayer(null);
+ }}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter') (e.target as HTMLInputElement).blur();
+ if (e.key === 'Escape') setRenamingLayer(null);
+ }}
+ />
+ ) : (
+ <button
+ type="button" className="tp-layer-name" title={t('tile.paintOn', { name: L.name })}
+ onClick={() => useSelection.getState().select(L.id)}
+ onDoubleClick={() => setRenamingLayer(L.id)}
+ >
+ {L.name}
+ </button>
+ )}
<input
className="tp-layer-op" type="range" min={0} max={1} step={0.05} value={L.opacity}
title={t('tile.opacityPct', { pct: Math.round(L.opacity * 100) })}
@@ -416,6 +458,14 @@ export function TilemapPainter() {
</button>
</span>
))}
+ {layerCtx && (
+ <ContextMenu
+ x={layerCtx.x}
+ y={layerCtx.y}
+ onClose={() => setLayerCtx(null)}
+ items={layerMenuItems(layerCtx.id)}
+ />
+ )}
</div>
)}
<div className="tp-tools">
diff --git a/desktop/src/panels/TilesetEditor.tsx b/desktop/src/panels/TilesetEditor.tsx
index ac51f31e5..39b77f951 100644
--- a/desktop/src/panels/TilesetEditor.tsx
+++ b/desktop/src/panels/TilesetEditor.tsx
@@ -124,6 +124,36 @@ function PolygonEditor(props: {
);
}
+/** Key/value entry row for the tile-properties bar; commits on + or Enter. */
+function AddPropRow({ onAdd }: { onAdd: (k: string, v: string) => void }) {
+ const [k, setK] = useState('');
+ const [v, setV] = useState('');
+ const add = () => {
+ const key = k.trim();
+ if (!key) return;
+ onAdd(key, v);
+ setK('');
+ setV('');
+ };
+ return (
+ <span className="ts-prop-add">
+ <input
+ className="ts-prop-in" placeholder={t('tile.prop.key')} value={k} spellCheck={false}
+ onChange={(e) => setK(e.target.value)}
+ onKeyDown={(e) => { if (e.key === 'Enter') add(); }}
+ />
+ <input
+ className="ts-prop-in" placeholder={t('tile.prop.value')} value={v} spellCheck={false}
+ onChange={(e) => setV(e.target.value)}
+ onKeyDown={(e) => { if (e.key === 'Enter') add(); }}
+ />
+ <button type="button" className="ts-prop-btn" title={t('tile.prop.add')} onClick={add}>
+ <Plus size={12} />
+ </button>
+ </span>
+ );
+}
+
export function TilesetEditor() {
useSyncExternalStore(TilesetDocument.subscribe, TilesetDocument.getRevision);
const asset = TilesetDocument.asset;
@@ -134,8 +164,9 @@ export function TilesetEditor() {
const [natural, setNatural] = useState<{ w: number; h: number } | null>(null);
const [zoom, setZoom] = useState(2);
- const [mode, setMode] = useState<'collision' | 'terrain' | 'animation'>('collision');
+ const [mode, setMode] = useState<'collision' | 'terrain' | 'animation' | 'properties'>('collision');
const [animTile, setAnimTile] = useState<number | null>(null);
+ const [propTile, setPropTile] = useState<number | null>(null);
const [shape, setShape] = useState<'box' | 'polygon' | 'circle'>('box');
const [polyTile, setPolyTile] = useState<number | null>(null);
// In polygon mode, an active preset stamps that canned slope/half-tile on click;
@@ -147,12 +178,17 @@ export function TilesetEditor() {
const [sensorOn, setSensorOn] = useState(false);
const [frictionStr, setFrictionStr] = useState('');
const [restitutionStr, setRestitutionStr] = useState('');
+ const [densityStr, setDensityStr] = useState('');
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.
const [drag, setDrag] = useState<{ ids: Set<number>; on: boolean } | null>(null);
const dragRef = useRef(drag);
dragRef.current = drag;
+ // Circle / preset drag-stamp stroke — same drag-paint feel as box collision.
+ const [stampDrag, setStampDrag] = useState<{ ids: Set<number>; on: boolean; kind: 'circle' | 'preset' } | null>(null);
+ const stampDragRef = useRef(stampDrag);
+ stampDragRef.current = stampDrag;
useEffect(() => setNatural(null), [texUrl]);
@@ -174,7 +210,6 @@ export function TilesetEditor() {
const isSolid = (id: number): boolean =>
drag?.ids.has(id) ? drag.on : asset.tiles[id]?.collision?.type === 'box';
- const hasPolygon = (id: number): boolean => asset.tiles[id]?.collision?.type === 'polygon';
const polyPointsOf = (id: number): [number, number][] | null => {
const c = asset.tiles[id]?.collision;
return c?.type === 'polygon' ? c.points : null;
@@ -195,6 +230,7 @@ export function TilesetEditor() {
if (sensorOn) m.sensor = true;
const fr = numOrU(frictionStr); if (fr !== undefined) m.friction = fr;
const re = numOrU(restitutionStr); if (re !== undefined) m.restitution = re;
+ const de = numOrU(densityStr); if (de !== undefined) m.density = de;
return m;
})();
@@ -202,6 +238,22 @@ export function TilesetEditor() {
const d = dragRef.current;
if (d) TilesetCommands.paintCollision([...d.ids], d.on, brushMods);
setDrag(null);
+ const sd = stampDragRef.current;
+ if (sd) {
+ if (sd.kind === 'circle') {
+ TilesetCommands.stampCircles([...sd.ids], sd.on, tw / 2, th / 2, Math.min(tw, th) / 2, brushMods);
+ } else if (activePreset) {
+ TilesetCommands.stampPolygons([...sd.ids], presetPointsPx(activePreset, tw, th), brushMods);
+ }
+ setStampDrag(null);
+ }
+ };
+ const growStampDrag = (id: number) => {
+ const sd = stampDragRef.current;
+ if (!sd || sd.ids.has(id)) return;
+ const ids = new Set(sd.ids);
+ ids.add(id);
+ setStampDrag({ ...sd, ids });
};
// Grid edits recompute columns from the atlas so the asset stays consistent.
@@ -246,19 +298,22 @@ export function TilesetEditor() {
const w = tw * zoom;
const h = th * zoom;
if (mode === 'collision' && shape === 'polygon') {
- const pts = polyPointsOf(id);
+ // A preset drag-paints (live-previewed via stampDrag, one undo step on
+ // release); freeform click opens the vertex editor.
+ const inStamp = activePreset != null && stampDrag?.kind === 'preset' && stampDrag.ids.has(id);
+ const pts = inStamp ? presetPointsPx(activePreset!, tw, th) : polyPointsOf(id);
cells.push(
<div
key={id}
- className={'ts-cell ts-pcell' + (hasPolygon(id) ? ' is-poly' : '') + (hasOneWay(id) ? ' is-oneway' : '') + (hasSensor(id) ? ' is-sensor' : '')}
+ className={'ts-cell ts-pcell' + (pts ? ' is-poly' : '') + (hasOneWay(id) ? ' is-oneway' : '') + (hasSensor(id) ? ' is-sensor' : '')}
style={{ left, top, width: w, height: h }}
title={activePreset ? t('tile.slope.stampTip', { name: t(activePreset.labelKey) }) : t('tile.cell.polyTip', { id })}
onPointerDown={(e) => {
e.preventDefault();
- // A preset stamps directly; freeform opens the vertex editor.
- if (activePreset) TilesetCommands.setTilePolygon(id, presetPointsPx(activePreset, tw, th), brushMods);
+ if (activePreset) setStampDrag({ ids: new Set([id]), on: true, kind: 'preset' });
else setPolyTile(id);
}}
+ onPointerEnter={() => growStampDrag(id)}
>
{pts && (
<svg className="ts-pe-svg" width={w} height={h} viewBox={`0 0 ${tw} ${th}`} preserveAspectRatio="none">
@@ -272,7 +327,12 @@ export function TilesetEditor() {
</div>,
);
} else if (mode === 'collision' && shape === 'circle') {
- const circ = circleOf(id);
+ // Drag paints (or clears, when starting on a circled tile) fitted discs —
+ // the same stroke feel as box collision, one undo step on release.
+ const inStamp = stampDrag?.kind === 'circle' && stampDrag.ids.has(id);
+ const circ = inStamp
+ ? (stampDrag!.on ? { cx: tw / 2, cy: th / 2, r: Math.min(tw, th) / 2 } : null)
+ : circleOf(id);
cells.push(
<div
key={id}
@@ -281,10 +341,9 @@ export function TilesetEditor() {
title={t('tile.cell.circleTip', { id })}
onPointerDown={(e) => {
e.preventDefault();
- // Toggle: click a circle tile again to clear it; else stamp a fitted disc.
- if (circ) TilesetCommands.setTileCircle(id, 0, 0, 0);
- else TilesetCommands.setTileCircle(id, tw / 2, th / 2, Math.min(tw, th) / 2, brushMods);
+ setStampDrag({ ids: new Set([id]), on: !circleOf(id), kind: 'circle' });
}}
+ onPointerEnter={() => growStampDrag(id)}
>
{circ && (
<svg className="ts-pe-svg" width={w} height={h} viewBox={`0 0 ${tw} ${th}`} preserveAspectRatio="none">
@@ -325,6 +384,17 @@ export function TilesetEditor() {
}}
/>,
);
+ } else if (mode === 'properties') {
+ const hasProps = !!asset.tiles[id]?.properties && Object.keys(asset.tiles[id]!.properties!).length > 0;
+ cells.push(
+ <div
+ key={id}
+ className={'ts-cell ts-acell' + (hasProps ? ' has-anim' : '') + (propTile === id ? ' is-target' : '')}
+ style={{ left, top, width: w, height: h }}
+ title={t('tile.cell.propTip', { id })}
+ onPointerDown={(e) => { e.preventDefault(); setPropTile(id); }}
+ />,
+ );
} else {
const tt = tileTerrain(id);
const showZones = hovered === id || tt != null;
@@ -383,6 +453,7 @@ export function TilesetEditor() {
{ value: 'collision', label: t('tile.mode.collision') },
{ value: 'terrain', label: t('tile.mode.terrain') },
{ value: 'animation', label: t('tile.mode.animation') },
+ { value: 'properties', label: t('tile.mode.properties') },
]}
/>
{mode === 'collision' && (
@@ -504,6 +575,52 @@ export function TilesetEditor() {
</div>
)}
+ {mode === 'properties' && (
+ <div className="ts-anims ts-props">
+ {propTile == null ? (
+ <span className="ts-ahint">{t('tile.prop.pickHint')}</span>
+ ) : (
+ <>
+ <span className="ts-fthumb" style={thumb(propTile)} title={`#${propTile}`} />
+ <span className="ts-astat">#{propTile}</span>
+ <span className="ts-sep" />
+ {Object.entries(asset.tiles[propTile]?.properties ?? {}).map(([k, v]) => (
+ <span key={k} className="ts-prop">
+ <span className="ts-prop-key" title={k}>{k}</span>
+ <input
+ key={`${propTile}-${k}-${v}`}
+ className="ts-prop-in"
+ defaultValue={v}
+ spellCheck={false}
+ onBlur={(e) => {
+ if (e.target.value === v) return;
+ const next = { ...(asset.tiles[propTile]?.properties ?? {}) };
+ next[k] = e.target.value;
+ TilesetCommands.setTileProperties(propTile, next);
+ }}
+ onKeyDown={(e) => { if (e.key === 'Enter') (e.target as HTMLInputElement).blur(); }}
+ />
+ <button
+ type="button" className="ts-prop-btn" title={t('tile.prop.remove')}
+ onClick={() => {
+ const next = { ...(asset.tiles[propTile]?.properties ?? {}) };
+ delete next[k];
+ TilesetCommands.setTileProperties(propTile, next);
+ }}
+ >
+ <X size={11} />
+ </button>
+ </span>
+ ))}
+ <AddPropRow
+ onAdd={(k, v) =>
+ TilesetCommands.setTileProperties(propTile, { ...(asset.tiles[propTile]?.properties ?? {}), [k]: v })}
+ />
+ </>
+ )}
+ </div>
+ )}
+
{mode === 'collision' && (
<div className="ts-modbar">
<span className="ts-slabel">{t('tile.modifiers')}</span>
@@ -539,20 +656,31 @@ export function TilesetEditor() {
onChange={(e) => setRestitutionStr(e.target.value)}
/>
</label>
+ <label className="ts-modnum">
+ <span>{t('tile.density')}</span>
+ <input
+ type="text" inputMode="decimal" placeholder="1" value={densityStr} spellCheck={false}
+ onChange={(e) => setDensityStr(e.target.value)}
+ />
+ </label>
</div>
)}
- {mode === 'collision' && shape === 'polygon' && (
+ {mode === 'collision' && (
<div className="ts-slopes">
<span className="ts-slabel">{t('tile.slope.presets')}</span>
{SLOPE_PRESETS.map((p) => (
<button
key={p.id}
type="button"
- className={'ts-slope' + (activePreset?.id === p.id ? ' is-active' : '')}
+ className={'ts-slope' + (shape === 'polygon' && activePreset?.id === p.id ? ' is-active' : '')}
title={t(p.labelKey)}
aria-label={t(p.labelKey)}
- onClick={() => setActivePreset((cur) => (cur?.id === p.id ? null : p))}
+ onClick={() => {
+ // Arming a preset implies polygon shape — no mode dance first.
+ setShape('polygon');
+ setActivePreset((cur) => (shape === 'polygon' && cur?.id === p.id ? null : p));
+ }}
>
<svg width={20} height={20} viewBox="0 0 10 10" preserveAspectRatio="none" aria-hidden="true">
<polygon className="ts-pe-poly" points={p.points.map(([x, y]) => `${x * 10},${y * 10}`).join(' ')} style={{ vectorEffect: 'non-scaling-stroke' }} />
@@ -561,9 +689,9 @@ export function TilesetEditor() {
))}
<button
type="button"
- className={'ts-slope ts-slope-free' + (activePreset === null ? ' is-active' : '')}
+ className={'ts-slope ts-slope-free' + (shape === 'polygon' && activePreset === null ? ' is-active' : '')}
title={t('tile.slope.freeform')}
- onClick={() => setActivePreset(null)}
+ onClick={() => { setShape('polygon'); setActivePreset(null); }}
>
{t('tile.slope.freeform')}
</button>
diff --git a/desktop/src/theme/tilemap.css b/desktop/src/theme/tilemap.css
index ef9591cf8..a94325ac8 100644
--- a/desktop/src/theme/tilemap.css
+++ b/desktop/src/theme/tilemap.css
@@ -71,6 +71,17 @@
}
.tp-layer.is-active .tp-layer-name { color: var(--text); }
.tp-layer-name:hover { color: var(--text); }
+.tp-layer-rename {
+ font: inherit;
+ color: var(--text);
+ background: var(--srf-2);
+ border: 1px solid var(--acc);
+ border-radius: var(--r-sm);
+ padding: 2px 6px;
+ margin: 0 1px;
+ width: 110px;
+ outline: none;
+}
.tp-layer-op { width: 44px; margin: 0 4px; align-self: center; accent-color: var(--acc); cursor: pointer; }
.tp-grow { flex: 1 1 auto; }
.tp-sep { width: 1px; align-self: stretch; margin: 2px 4px; background: var(--line); }
diff --git a/desktop/src/theme/tileset.css b/desktop/src/theme/tileset.css
index 3dc707e76..9f82de3f5 100644
--- a/desktop/src/theme/tileset.css
+++ b/desktop/src/theme/tileset.css
@@ -333,3 +333,12 @@
color: var(--text-faint);
}
.ts-hint { font-size: var(--fs-xs); }
+
+/* Tile custom-properties bar (mode = properties). */
+.ts-prop { display: inline-flex; align-items: center; gap: 3px; background: var(--srf-3); border: 1px solid var(--border); border-radius: var(--r-sm); padding: 2px 4px; }
+.ts-prop-key { color: var(--text-dim); font-size: var(--fs-2xs); max-width: 90px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.ts-prop-in { width: 74px; font-size: var(--fs-2xs); color: var(--text); background: var(--srf-2); border: 1px solid var(--border); border-radius: var(--r-sm); padding: 2px 5px; }
+.ts-prop-in:focus { outline: none; border-color: var(--acc); }
+.ts-prop-btn { display: inline-flex; align-items: center; color: var(--text-dim); background: none; border: none; cursor: pointer; padding: 1px; }
+.ts-prop-btn:hover { color: var(--text); }
+.ts-prop-add { display: inline-flex; align-items: center; gap: 3px; }
diff --git a/desktop/src/tileset/TilesetCommands.ts b/desktop/src/tileset/TilesetCommands.ts
index 6a5386357..8b1f226e4 100644
--- a/desktop/src/tileset/TilesetCommands.ts
+++ b/desktop/src/tileset/TilesetCommands.ts
@@ -102,6 +102,48 @@ export const TilesetCommands = {
});
},
+ /** Stamp the same polygon onto a set of tiles as ONE undo step (preset drag-paint). */
+ stampPolygons(tileIds: number[], points: [number, number][], mods?: TileCollisionMods): void {
+ if (tileIds.length === 0 || points.length < 3) return;
+ TilesetDocument.edit('Stamp Tile Collision', (a) => {
+ for (const id of tileIds) {
+ if (id <= 0) continue;
+ const copy = points.map((p) => [p[0], p[1]] as [number, number]);
+ a.tiles[id] = { ...(a.tiles[id] ?? {}), collision: withMods({ type: 'polygon' as const, points: copy }, mods) };
+ }
+ });
+ },
+
+ /** Stamp (on) or clear (off) a fitted circle on a set of tiles as ONE undo step. */
+ stampCircles(tileIds: number[], on: boolean, cx: number, cy: number, r: number, mods?: TileCollisionMods): void {
+ if (tileIds.length === 0) return;
+ TilesetDocument.edit(on ? 'Stamp Tile Collision' : 'Remove Tile Collision', (a) => {
+ for (const id of tileIds) {
+ if (id <= 0) continue;
+ if (on) {
+ a.tiles[id] = { ...(a.tiles[id] ?? {}), collision: withMods({ type: 'circle' as const, cx, cy, r }, mods) };
+ } else if (a.tiles[id]?.collision?.type === 'circle') {
+ delete a.tiles[id].collision;
+ pruneEmpty(a, id);
+ }
+ }
+ });
+ },
+
+ /** Replace a tile's custom properties as ONE undo step; an empty record clears them. */
+ setTileProperties(id: number, props: Record<string, string>): void {
+ if (id <= 0) return;
+ TilesetDocument.edit('Edit Tile Properties', (a) => {
+ const clean = Object.fromEntries(Object.entries(props).filter(([k]) => k.trim() !== ''));
+ if (Object.keys(clean).length > 0) {
+ a.tiles[id] = { ...(a.tiles[id] ?? {}), properties: clean };
+ } else if (a.tiles[id]?.properties) {
+ delete a.tiles[id].properties;
+ 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/desktop/src/tools/tileTools.ts b/desktop/src/tools/tileTools.ts
index 8f9533c23..ed8e247f6 100644
--- a/desktop/src/tools/tileTools.ts
+++ b/desktop/src/tools/tileTools.ts
@@ -129,11 +129,36 @@ export function lineCells(x0: number, y0: number, x1: number, y1: number): { x:
return cells;
}
+/**
+ * Read the raw cell (id + flip flags) under the cursor into the brush; on a
+ * multi-tileset layer also switches the palette tab to the gid's owning tileset
+ * so the brush ghost resolves. Shared by the eyedropper tool and alt-picking.
+ */
+function pickTileIntoBrush(clientX: number, clientY: number): void {
+ const selId = selectedTilemap();
+ if (selId == null) return;
+ const tile = cursorTile(clientX, clientY, selId);
+ const rt = SceneModel.runtimeFor(selId);
+ if (!tile || rt == null) return;
+ const raw = TilemapAPI.getTile(rt, tile.x, tile.y);
+ const gid = tileIdOf(raw);
+ if (gid <= 0) return;
+ const ps = useTilemapPaint.getState();
+ let owner = ps.activeTileset;
+ for (let i = 0; i < ps.tilesets.length; i++) {
+ if (ps.tilesets[i].firstId <= gid) owner = i; else break;
+ }
+ if (owner !== ps.activeTileset) ps.setActiveTileset(owner);
+ ps.setStamp(singleStamp(raw));
+}
+
// ── Shared drag-stroke driver ────────────────────────────────────────────────
// begin() opens a per-stroke context (null aborts); onCell() runs once per newly
// entered tile during press+drag; end() commits. Used by brush/erase/terrain.
interface StrokeSpec<C> {
id: string;
+ /** Alt+click eyedrops instead of stroking (the raster-editor reflex). */
+ altEyedrop?: boolean;
begin(sourceId: number): C | null;
onCell(ctx: C, x: number, y: number): void;
end(ctx: C): void;
@@ -144,6 +169,10 @@ function makeStrokeTool<C>(spec: StrokeSpec<C>): EditorTool {
return {
id: spec.id,
onPointerDown(p, ctx) {
+ if (p.alt && spec.altEyedrop) {
+ pickTileIntoBrush(p.clientX, p.clientY);
+ return false; // one-shot pick, no stroke
+ }
const selId = selectedTilemap();
if (selId == null) return false;
const tile = cursorTile(p.clientX, p.clientY, selId);
@@ -186,6 +215,7 @@ function makeStrokeTool<C>(spec: StrokeSpec<C>): EditorTool {
const brushTool = makeStrokeTool<number>({
id: 'tilemap.brush',
+ altEyedrop: true,
begin: (selId) => { SceneCommands.beginTilePaint(selId); return selId; },
onCell: (selId, x, y) => {
for (const e of brushEdits(activeStamp(), x, y)) SceneCommands.paintTileLive(selId, e.x, e.y, e.tileId);
@@ -264,7 +294,29 @@ const terrainTool = makeStrokeTool<TerrainCtx>({
// ── Gesture tools (commit once on release / click) ───────────────────────────
-/** Rect fill: drag a rectangle, tile the active stamp across it on release (one step). */
+// Shift-constraints, matching every raster/tile editor's muscle memory: lines snap
+// to the 8 compass directions, rect/ellipse boxes snap square (circle).
+
+/** Snap (x,y) to the nearest horizontal / vertical / 45° ray from (sx,sy). */
+export function octantSnap(sx: number, sy: number, x: number, y: number): { x: number; y: number } {
+ const dx = x - sx;
+ const dy = y - sy;
+ const adx = Math.abs(dx);
+ const ady = Math.abs(dy);
+ if (adx >= 2 * ady) return { x, y: sy };
+ if (ady >= 2 * adx) return { x: sx, y };
+ const d = Math.max(adx, ady);
+ return { x: sx + Math.sign(dx) * d, y: sy + Math.sign(dy) * d };
+}
+
+/** Snap (x,y) so the (sx,sy)-cornered box is square, keeping the drag quadrant. */
+export function squareSnap(sx: number, sy: number, x: number, y: number): { x: number; y: number } {
+ const d = Math.max(Math.abs(x - sx), Math.abs(y - sy));
+ return { x: sx + (x >= sx ? d : -d), y: sy + (y >= sy ? d : -d) };
+}
+
+/** Rect fill: drag a rectangle, tile the active stamp across it on release (one step).
+ * Shift constrains the box square. */
function makeRectTool(): EditorTool {
let stroke: { sourceId: number; startX: number; startY: number } | null = null;
return {
@@ -281,15 +333,17 @@ function makeRectTool(): EditorTool {
},
onPointerMove(p) {
if (!stroke) return;
- const tile = cursorTile(p.clientX, p.clientY, stroke.sourceId);
+ let tile = cursorTile(p.clientX, p.clientY, stroke.sourceId);
if (!tile) return;
+ if (p.shift) tile = squareSnap(stroke.startX, stroke.startY, tile.x, tile.y);
TilePaintPreview.set({ kind: 'rect', x0: stroke.startX, y0: stroke.startY, x1: tile.x, y1: tile.y });
},
onPointerUp(p, ctx) {
if (!stroke) return;
ctx.release(p.pointerId);
TilePaintPreview.clear();
- const tile = cursorTile(p.clientX, p.clientY, stroke.sourceId);
+ let tile = cursorTile(p.clientX, p.clientY, stroke.sourceId);
+ if (tile && p.shift) tile = squareSnap(stroke.startX, stroke.startY, tile.x, tile.y);
if (tile) {
const x0 = Math.min(stroke.startX, tile.x);
const x1 = Math.max(stroke.startX, tile.x);
@@ -312,7 +366,8 @@ function makeRectTool(): EditorTool {
};
}
-/** Line: drag from press to release, stamp the brush along the Bresenham line (one step). */
+/** Line: drag from press to release, stamp the brush along the Bresenham line (one step).
+ * Shift constrains to horizontal / vertical / 45°. */
function makeLineTool(): EditorTool {
let stroke: { sourceId: number; startX: number; startY: number } | null = null;
return {
@@ -329,15 +384,17 @@ function makeLineTool(): EditorTool {
},
onPointerMove(p) {
if (!stroke) return;
- const tile = cursorTile(p.clientX, p.clientY, stroke.sourceId);
+ let tile = cursorTile(p.clientX, p.clientY, stroke.sourceId);
if (!tile) return;
+ if (p.shift) tile = octantSnap(stroke.startX, stroke.startY, tile.x, tile.y);
TilePaintPreview.set({ kind: 'line', cells: lineCells(stroke.startX, stroke.startY, tile.x, tile.y) });
},
onPointerUp(p, ctx) {
if (!stroke) return;
ctx.release(p.pointerId);
TilePaintPreview.clear();
- const tile = cursorTile(p.clientX, p.clientY, stroke.sourceId);
+ let tile = cursorTile(p.clientX, p.clientY, stroke.sourceId);
+ if (tile && p.shift) tile = octantSnap(stroke.startX, stroke.startY, tile.x, tile.y);
if (tile) {
// One tiled cell per line cell (like rect/ellipse), so the thin-line preview
// matches what lands — not the whole w×h footprint stamped at every point.
@@ -356,7 +413,8 @@ function makeLineTool(): EditorTool {
};
}
-/** Ellipse fill: drag the bounding box, fill its inscribed ellipse on release (one step). */
+/** Ellipse fill: drag the bounding box, fill its inscribed ellipse on release (one step).
+ * Shift constrains the box square — a circle. */
function makeEllipseTool(): EditorTool {
let stroke: { sourceId: number; startX: number; startY: number } | null = null;
return {
@@ -373,15 +431,17 @@ function makeEllipseTool(): EditorTool {
},
onPointerMove(p) {
if (!stroke) return;
- const tile = cursorTile(p.clientX, p.clientY, stroke.sourceId);
+ let tile = cursorTile(p.clientX, p.clientY, stroke.sourceId);
if (!tile) return;
+ if (p.shift) tile = squareSnap(stroke.startX, stroke.startY, tile.x, tile.y);
TilePaintPreview.set({ kind: 'line', cells: ellipseCells(stroke.startX, stroke.startY, tile.x, tile.y) });
},
onPointerUp(p, ctx) {
if (!stroke) return;
ctx.release(p.pointerId);
TilePaintPreview.clear();
- const tile = cursorTile(p.clientX, p.clientY, stroke.sourceId);
+ let tile = cursorTile(p.clientX, p.clientY, stroke.sourceId);
+ if (tile && p.shift) tile = squareSnap(stroke.startX, stroke.startY, tile.x, tile.y);
if (tile) {
const minX = Math.min(stroke.startX, tile.x);
const minY = Math.min(stroke.startY, tile.y);
@@ -485,25 +545,7 @@ function makeSelectTool(): EditorTool {
const eyedropperTool: EditorTool = {
id: 'tilemap.eyedropper',
onPointerDown(p) {
- const selId = selectedTilemap();
- if (selId == null) return false;
- const tile = cursorTile(p.clientX, p.clientY, selId);
- if (!tile) return false;
- const rt = SceneModel.runtimeFor(selId);
- const raw = rt != null ? TilemapAPI.getTile(rt, tile.x, tile.y) : 0;
- const gid = tileIdOf(raw);
- if (gid > 0) {
- const ps = useTilemapPaint.getState();
- // On a multi-tileset layer, switch the palette to the tileset that owns the
- // picked gid (tilesets are in ascending firstId order) so its atlas resolves
- // the brush ghost — otherwise the hover preview goes blank.
- let owner = ps.activeTileset;
- for (let i = 0; i < ps.tilesets.length; i++) {
- if (ps.tilesets[i].firstId <= gid) owner = i; else break;
- }
- if (owner !== ps.activeTileset) ps.setActiveTileset(owner);
- ps.setStamp(singleStamp(raw));
- }
+ pickTileIntoBrush(p.clientX, p.clientY);
return false; // no ongoing stroke
},
onPointerMove() {},
diff --git a/desktop/tests/tile-constraints.test.ts b/desktop/tests/tile-constraints.test.ts
new file mode 100644
index 000000000..fcc13db4c
--- /dev/null
+++ b/desktop/tests/tile-constraints.test.ts
@@ -0,0 +1,24 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { describe, it, expect } from 'vitest';
+import { octantSnap, squareSnap } from '@/tools/tileTools';
+
+describe('octantSnap (Shift-constrained lines)', () => {
+ it('snaps near-horizontal drags onto the row', () => {
+ expect(octantSnap(0, 0, 10, 2)).toEqual({ x: 10, y: 0 });
+ });
+ it('snaps near-vertical drags onto the column', () => {
+ expect(octantSnap(0, 0, -2, 9)).toEqual({ x: 0, y: 9 });
+ });
+ it('snaps diagonal-ish drags to a 45° ray with max extent', () => {
+ expect(octantSnap(0, 0, 7, 5)).toEqual({ x: 7, y: 7 });
+ expect(octantSnap(3, 3, -4, 8)).toEqual({ x: 3 - 7, y: 3 + 7 });
+ });
+});
+
+describe('squareSnap (Shift-constrained rect/ellipse)', () => {
+ it('squares the box to the larger extent, keeping the drag quadrant', () => {
+ expect(squareSnap(0, 0, 5, 2)).toEqual({ x: 5, y: 5 });
+ expect(squareSnap(10, 10, 6, 12)).toEqual({ x: 6, y: 14 });
+ });
+});
diff --git a/desktop/tests/tileset-commands.test.ts b/desktop/tests/tileset-commands.test.ts
index 35670f0c5..5b15bcffb 100644
--- a/desktop/tests/tileset-commands.test.ts
+++ b/desktop/tests/tileset-commands.test.ts
@@ -77,3 +77,38 @@ describe('TilesetCommands', () => {
expect(tiles()[5].collision).toEqual({ type: 'polygon', points: [[0, 16], [16, 16], [16, 0]], sensor: true });
});
});
+
+describe('TilesetCommands — stamps + properties', () => {
+ beforeEach(() => {
+ EditorHistory.clear();
+ TilesetDocument.open(freshTileset(), 'a.estileset');
+ });
+
+ it('stampPolygons stamps one polygon across many tiles as one undo step', () => {
+ const ramp: [number, number][] = [[0, 16], [16, 16], [16, 0]];
+ TilesetCommands.stampPolygons([2, 3, 4], ramp, { oneWay: { nx: 0, ny: 1 } });
+ expect(tiles()[3].collision).toEqual({ type: 'polygon', points: ramp, oneWay: { nx: 0, ny: 1 } });
+ // Points are copied, not aliased, across tiles.
+ expect((tiles()[2].collision as { points: unknown }).points).not.toBe((tiles()[3].collision as { points: unknown }).points);
+ EditorHistory.undo();
+ expect(Object.keys(tiles())).toEqual([]);
+ });
+
+ it('stampCircles paints fitted discs and clears them (on=false) as one step each', () => {
+ TilesetCommands.stampCircles([1, 2], true, 8, 8, 8);
+ expect(tiles()[1].collision).toEqual({ type: 'circle', cx: 8, cy: 8, r: 8 });
+ TilesetCommands.stampCircles([1, 2], false, 8, 8, 8);
+ expect(Object.keys(tiles())).toEqual([]);
+ EditorHistory.undo();
+ expect(tiles()[2].collision).toEqual({ type: 'circle', cx: 8, cy: 8, r: 8 });
+ });
+
+ it('setTileProperties round-trips, drops blank keys, and clears on empty', () => {
+ TilesetCommands.setTileProperties(7, { kind: 'spike', ' ': 'ignored' });
+ expect(tiles()[7].properties).toEqual({ kind: 'spike' });
+ TilesetCommands.setTileProperties(7, {});
+ expect(tiles()[7]).toBeUndefined();
+ EditorHistory.undo();
+ expect(tiles()[7].properties).toEqual({ kind: 'spike' });
+ });
+});