From d9073e75a5308318d91606d23a61d5b24f17d3fb Mon Sep 17 00:00:00 2001 From: "nori-sessions[bot]" <264258699+nori-sessions[bot]@users.noreply.github.com> Date: Mon, 2 Nov 2026 07:08:08 +0000 Subject: [PATCH 1/4] Edit coaster track from a selected piece Select any placed piece (click its rails in the track tool, or Edit from this piece in the ride window), step with Previous/Next piece, then demolish that piece or build from its open end. Removing a middle piece splits the track into sections instead of refusing; placements join any open end and close the circuit once one ring remains. Track edits are refused while the ride is open, testing, has a train out or riders aboard. Removing a station detaches a stranded entrance or exit. Co-authored-by: Nori --- e2e/support/track-edit-park.ts | 73 +++++ e2e/track-edit-selection.spec.ts | 320 ++++++++++++++++++++++ src/app/bootstrap/index.ts | 14 +- src/app/tools/index.ts | 43 ++- src/app/tools/track-selection-outline.ts | 71 +++++ src/input/object-picking.test.ts | 52 +++- src/input/object-picking.ts | 43 ++- src/render/coaster-scene.ts | 31 ++- src/sim/rides/coaster.test.ts | 19 +- src/sim/rides/ride-boarding.ts | 23 ++ src/sim/rides/ride-commands.ts | 3 +- src/sim/rides/track-edit-safety.test.ts | 169 ++++++++++++ src/sim/track/construction.test.ts | 3 +- src/sim/track/construction.ts | 288 ++++++++++---------- src/sim/track/track-commands.ts | 48 +++- src/sim/track/track-editing.test.ts | 226 ++++++++++++++++ src/sim/track/track-types.ts | 9 +- src/ui/coaster-panel.ts | 327 +++++++++++++++++++++-- src/ui/game-ui.ts | 9 +- src/ui/track-preview.ts | 25 +- src/ui/track-selection.test.ts | 174 ++++++++++++ src/ui/track-selection.ts | 153 +++++++++++ src/ui/track-tool.ts | 52 +++- src/ui/ui-types.ts | 9 +- src/ui/ui.css | 23 ++ src/ui/windows/ride-window.ts | 8 + src/worker/snapshot.test.ts | 2 +- src/worker/snapshot.ts | 10 + 28 files changed, 2013 insertions(+), 214 deletions(-) create mode 100644 e2e/support/track-edit-park.ts create mode 100644 e2e/track-edit-selection.spec.ts create mode 100644 src/app/tools/track-selection-outline.ts create mode 100644 src/sim/rides/track-edit-safety.test.ts create mode 100644 src/sim/track/track-editing.test.ts create mode 100644 src/ui/track-selection.test.ts create mode 100644 src/ui/track-selection.ts diff --git a/e2e/support/track-edit-park.ts b/e2e/support/track-edit-park.ts new file mode 100644 index 000000000..9127d66b8 --- /dev/null +++ b/e2e/support/track-edit-park.ts @@ -0,0 +1,73 @@ +import { TRACK_STEPS_PER_LEVEL } from '../../src/sim/core/constants'; +import type { Simulation } from '../../src/sim/core/simulation'; +import { RideType } from '../../src/sim/rides/ride-types'; +import { + GROUND, + buildCircuit, + connectStation, + createCoaster, + flatOwnedSim, + run, +} from '../../src/sim/rides/coaster-fixtures'; +import { pieceByName } from '../../src/sim/track/catalog'; +import { getConstructionCursor } from '../../src/sim/track/construction'; +import { PieceMode } from '../../src/sim/track/track-types'; +import { serialize } from '../../src/save/save'; + +/** Unfinished coaster: station then straights running +x from this tile at ground level. */ +export const UNFINISHED_START = { x: 8, y: 36 }; +export const UNFINISHED_PIECES = ['station', 'flat', 'flat', 'flat', 'flat', 'flat', 'flat']; +/** Overpass: straights running +y across the unfinished coaster's fourth piece, four levels up. */ +export const OVERPASS_START = { x: 11, y: 33 }; +export const OVERPASS_LEVELS = 4; + +function line( + sim: Simulation, + rideId: number, + names: readonly string[], + start: { x: number; y: number }, + level: number, + dir: number, +): void { + for (const name of names) { + const cursor = getConstructionCursor(sim.world, rideId); + sim.enqueue({ + type: 'placeTrack', + rideId, + pieceType: pieceByName(name)!.id, + x: cursor.hasTrack ? cursor.x : start.x, + y: cursor.hasTrack ? cursor.y : start.y, + z: cursor.hasTrack ? cursor.z : level * TRACK_STEPS_PER_LEVEL, + dir: cursor.hasTrack ? cursor.dir : dir, + mode: PieceMode.Normal, + }); + sim.step(); + } +} + +/** + * A paused-friendly park for track editing: a tested, closed coaster with its entrance and exit + * (ride 1), an unfinished coaster (ride 2), and a second unfinished coaster passing over ride 2's + * track four levels up (ride 3). + */ +export function trackEditPark(): Uint8Array { + const sim = flatOwnedSim(1); + const circuit = createCoaster(sim, RideType.WoodenCoaster); + buildCircuit(sim, circuit); + connectStation(sim, circuit); + sim.enqueue({ type: 'setRideStatus', rideId: circuit, status: 'test' }); + run(sim, 8000); + const unfinished = createCoaster(sim, RideType.WoodenCoaster, 4, 40); + line(sim, unfinished, UNFINISHED_PIECES, UNFINISHED_START, GROUND, 0); + const overpass = createCoaster(sim, RideType.WoodenCoaster, 4, 44); + line( + sim, + overpass, + ['flat', 'flat', 'flat', 'flat', 'flat', 'flat'], + OVERPASS_START, + GROUND + OVERPASS_LEVELS, + 1, + ); + run(sim, 10); + return serialize(sim.world); +} diff --git a/e2e/track-edit-selection.spec.ts b/e2e/track-edit-selection.spec.ts new file mode 100644 index 000000000..c5b1a0ddc --- /dev/null +++ b/e2e/track-edit-selection.spec.ts @@ -0,0 +1,320 @@ +import { mkdir, writeFile } from 'node:fs/promises'; +import { dirname } from 'node:path'; +import { expect, test, type Page, type TestInfo } from './support/test'; +import { openPage, toolbarAction } from './support/park'; +import { UNFINISHED_PIECES, trackEditPark } from './support/track-edit-park'; + +type Backend = 'WebGL2' | 'Canvas2D'; + +interface Piece { + id: number; + prev: number; + next: number; +} + +async function forceCanvas2D(page: Page): Promise { + await page.addInitScript(() => { + const original = HTMLCanvasElement.prototype.getContext; + HTMLCanvasElement.prototype.getContext = function (type: string, ...args: unknown[]) { + if (type === 'webgl2' || type === 'webgl' || type === 'experimental-webgl') return null; + return original.call(this, type as '2d', ...(args as [])); + } as typeof HTMLCanvasElement.prototype.getContext; + }); +} + +async function loadPark(page: Page, testInfo: TestInfo): Promise { + const savePath = testInfo.outputPath('track-edit.ocsave'); + await mkdir(dirname(savePath), { recursive: true }); + await writeFile(savePath, trackEditPark()); + await page.goto('/'); + await page.getByRole('button', { name: 'Sandbox' }).click(); + await toolbarAction(page, 'Game options'); + await page.getByRole('button', { name: 'Save, load and quit…' }).click(); + await page.getByRole('button', { name: 'Import save file' }).click(); + await page.locator('.save-menu input[type="file"]').setInputFiles(savePath); + await expect(page.locator('.save-menu')).toBeHidden(); + const close = page.locator('.ui-window button[aria-label^="Close"]'); + while (await close.count()) await close.first().click(); + await expect + .poll(() => + page.evaluate(() => { + const snapshot = ( + window as unknown as { + __snapshot?: { rides: { count: number }; tracks: { count: number } }; + } + ).__snapshot; + return snapshot ? `${snapshot.rides.count}:${snapshot.tracks.count}` : ''; + }), + ) + .toBe('3:27'); +} + +/** The ride's pieces, in track order from the first piece of its first section (or its station). */ +async function ridePieces(page: Page, rideId: number): Promise { + // A snapshot handed back to the worker for reuse has detached buffers; wait for a live one. + await page.waitForFunction(() => { + const snapshot = ( + window as unknown as { __snapshot?: { tracks: { data: Int32Array }; trackLinks: Int32Array } } + ).__snapshot; + return !!snapshot && snapshot.tracks.data.length > 0 && snapshot.trackLinks.length > 0; + }); + const rows = await page.evaluate((rideId) => { + const snapshot = ( + window as unknown as { + __snapshot: { tracks: { count: number; data: Int32Array }; trackLinks: Int32Array }; + } + ).__snapshot; + const out: Array<{ id: number; prev: number; next: number; type: number }> = []; + for (let i = 0; i < snapshot.tracks.count; i++) { + const word = snapshot.tracks.data[i * 4 + 3]; + if (word >>> 16 !== rideId) continue; + out.push({ + id: snapshot.trackLinks[i * 3], + prev: snapshot.trackLinks[i * 3 + 1], + next: snapshot.trackLinks[i * 3 + 2], + type: word & 0xff, + }); + } + return out; + }, rideId); + const byId = new Map(rows.map((row) => [row.id, row])); + const first = rows.find((row) => row.prev < 0) ?? rows.find((row) => row.type === 0) ?? rows[0]; + const ordered: Piece[] = []; + for (let at = first; at && ordered.length < rows.length; at = byId.get(at.next)!) + ordered.push({ id: at.id, prev: at.prev, next: at.next }); + for (const row of rows) + if (!ordered.some((piece) => piece.id === row.id)) + ordered.push({ id: row.id, prev: row.prev, next: row.next }); + return ordered; +} + +/** Centres the camera on a piece's rails and returns a viewport point where they are on top. */ +async function pointOnPiece(page: Page, pieceId: number): Promise<{ x: number; y: number }> { + const find = () => + page.locator('#game').evaluate(async (canvas, pieceId) => { + const [{ buildObjectPickTargets, pickTrackPiece }, { spritePages }] = await Promise.all([ + import('/src/input/object-picking.ts'), + import('/src/render/sprite-pages.ts'), + ]); + const state = window as unknown as { + __camera: { x: number; y: number; zoom: number; rotation: 0 | 1 | 2 | 3 }; + __map: Parameters[1]; + __snapshot: Parameters[0]; + }; + const { __camera: camera, __map: map, __snapshot: snapshot } = state; + if (!snapshot) return null; + const rect = canvas.getBoundingClientRect(); + const viewport = { width: rect.width, height: rect.height }; + const mine = (t: ReturnType[number]) => + t.coasterPart === 'track' && t.pieceId === pieceId; + camera.zoom = 2; + // Centre the piece in the part of the map no window or sheet covers. + let top = rect.top; + while (top < rect.bottom && document.elementFromPoint(rect.left + 2, top) !== canvas) + top += 4; + let bottom = top; + while (bottom < rect.bottom && document.elementFromPoint(rect.left + 2, bottom) === canvas) + bottom += 4; + let targets = buildObjectPickTargets(snapshot, map, camera, viewport, spritePages); + const first = targets.find(mine); + if (!first) return null; + camera.x += (first.x + first.width / 2 - viewport.width / 2) / camera.zoom; + camera.y += (first.y + first.height / 2 - ((top + bottom) / 2 - rect.top)) / camera.zoom; + targets = buildObjectPickTargets(snapshot, map, camera, viewport, spritePages); + for (const target of targets.filter(mine)) { + for (let i = 0; i < target.alpha.length; i += 3) { + if (target.alpha[i] === 0) continue; + const x = target.x + (((i % target.alphaWidth) + 0.5) / target.alphaWidth) * target.width; + const y = + target.y + + ((Math.floor(i / target.alphaWidth) + 0.5) / target.alphaHeight) * target.height; + if (document.elementFromPoint(rect.left + x, rect.top + y) !== canvas) continue; + const hit = pickTrackPiece(targets, x, y); + if (hit && 'pieceId' in hit && hit.pieceId === pieceId) + return { x: rect.left + x, y: rect.top + y }; + } + } + return null; + }, pieceId); + await expect.poll(find, { timeout: 30_000 }).not.toBeNull(); + const point = await find(); + if (!point) throw new Error(`Piece ${pieceId} has no visible rail pixel`); + return point; +} + +async function tapOrClick(page: Page, mobile: boolean, point: { x: number; y: number }) { + if (mobile) await page.touchscreen.tap(point.x, point.y); + else await page.mouse.click(point.x, point.y); +} + +const construction = (page: Page) => + page.locator('[data-window-id="construction"], .coaster-panel'); +const selectionLine = (page: Page) => page.locator('.coaster-selection-line'); +const rideInfo = (page: Page) => page.locator('.coaster-info'); + +async function expectHighlightAt(page: Page, point: { x: number; y: number }): Promise { + const outline = page.locator('.track-selection-outline'); + await expect(outline).toBeVisible(); + const box = (await outline.boundingBox())!; + expect(point.x).toBeGreaterThanOrEqual(box.x - 2); + expect(point.x).toBeLessThanOrEqual(box.x + box.width + 2); + expect(point.y).toBeGreaterThanOrEqual(box.y - 2); + expect(point.y).toBeLessThanOrEqual(box.y + box.height + 2); +} + +async function shot(page: Page, testInfo: TestInfo, name: string, point: { x: number; y: number }) { + const viewport = page.viewportSize()!; + const width = Math.min(560, viewport.width); + const height = Math.min(380, viewport.height); + const left = Math.max(0, Math.min(viewport.width - width, point.x - width / 2)); + const top = Math.max(0, Math.min(viewport.height - height, point.y - height / 2)); + await page.screenshot({ + path: testInfo.outputPath(`${name}.png`), + clip: { x: left, y: top, width, height }, + timeout: 60_000, + }); + await page.screenshot({ path: testInfo.outputPath(`${name}-full.png`), timeout: 60_000 }); +} + +async function fastForward(page: Page): Promise { + for (let i = 0; i < 3; i++) await page.keyboard.press('+'); +} + +async function editClosedCircuit(page: Page, mobile: boolean, testInfo: TestInfo): Promise { + await toolbarAction(page, 'Pause'); + const circuit = await ridePieces(page, 0); + expect(circuit).toHaveLength(14); + const middle = circuit[6]; + const point = await pointOnPiece(page, middle.id); + + await tapOrClick(page, mobile, point); + const rideWindow = page.locator('[data-panel^="ride-"]:visible'); + await expect(rideWindow).toHaveCount(1); + await page.getByRole('button', { name: 'Edit from this piece' }).click(); + await expect(selectionLine(page)).toContainText('Selected piece 7 of 14'); + await expect(rideInfo(page)).toContainText('Track 14 pieces'); + await expectHighlightAt(page, point); + await shot(page, testInfo, 'circuit-selected', point); + + await page.getByRole('button', { name: 'Next piece' }).click(); + await expect(selectionLine(page)).toContainText('Selected piece 8 of 14'); + await page.getByRole('button', { name: 'Previous piece' }).click(); + await expect(selectionLine(page)).toContainText('Selected piece 7 of 14'); + + await page.getByRole('button', { name: 'Demolish selected piece' }).click(); + await expect(rideInfo(page)).toContainText('Track 13 pieces'); + const after = (await ridePieces(page, 0)).map((piece) => piece.id); + expect(after).not.toContain(middle.id); + for (const piece of circuit) if (piece !== middle) expect(after).toContain(piece.id); + await expect(selectionLine(page)).toContainText('of 13'); + await shot(page, testInfo, 'circuit-gap', point); + + await page.getByRole('button', { name: 'Right small' }).click(); + await page.getByRole('button', { name: 'Level', exact: true }).click(); + await page.getByRole('button', { name: 'No bank' }).click(); + await page.getByRole('button', { name: 'Build piece' }).click(); + await expect(rideInfo(page)).toContainText('Track 14 pieces'); + await expect(rideInfo(page)).toContainText('Circuit complete'); + await expect(selectionLine(page)).toContainText('Building from the end of the track'); + await shot(page, testInfo, 'circuit-rebuilt', point); + + await toolbarAction(page, 'Resume'); + await fastForward(page); + await construction(page).getByRole('button', { name: 'Test', exact: true }).click(); + await expect(rideInfo(page)).toContainText('Excitement', { timeout: 240_000 }); + await construction(page).getByRole('button', { name: 'Open', exact: true }).click(); + await expect(rideInfo(page)).toContainText('Open'); + await toolbarAction(page, 'Pause'); + + const busy = await pointOnPiece(page, circuit[3].id); + await tapOrClick(page, mobile, busy); + await expect(selectionLine(page)).toContainText('Selected piece 4 of 14'); + await page.getByRole('button', { name: 'Demolish selected piece' }).click(); + await expect(page.locator('.coaster-feedback')).toContainText( + 'Close the ride and wait for its train', + ); + await expect(rideInfo(page)).toContainText('Track 14 pieces'); +} + +async function editUnfinished(page: Page, mobile: boolean, testInfo: TestInfo): Promise { + await toolbarAction(page, 'Pause'); + const unfinished = await ridePieces(page, 1); + const overpass = await ridePieces(page, 2); + expect(unfinished).toHaveLength(UNFINISHED_PIECES.length); + + const upper = await pointOnPiece(page, overpass[3].id); + await tapOrClick(page, mobile, upper); + await page.getByRole('button', { name: 'Edit from this piece' }).click(); + await expect(selectionLine(page)).toContainText('Selected piece 4 of 6'); + await expectHighlightAt(page, upper); + + const lower = await pointOnPiece(page, unfinished[3].id); + await tapOrClick(page, mobile, lower); + await expect(selectionLine(page)).toContainText('Selected piece 4 of 7'); + await expect(rideInfo(page)).toContainText('Track 7 pieces'); + await expectHighlightAt(page, lower); + await shot(page, testInfo, 'stacked-lower-selected', lower); + + await page.getByRole('button', { name: 'Demolish selected piece' }).click(); + await expect(rideInfo(page)).toContainText('Track 6 pieces'); + const remaining = (await ridePieces(page, 1)).map((piece) => piece.id); + for (const piece of unfinished) + expect(remaining.includes(piece.id)).toBe(piece !== unfinished[3]); + await expect(selectionLine(page)).toContainText('Selected piece 3 of 3'); + + await page.getByRole('button', { name: 'Straight' }).click(); + await page.getByRole('button', { name: 'Build piece' }).click(); + await expect(rideInfo(page)).toContainText('Track 7 pieces'); + await expect(selectionLine(page)).toContainText('Selected piece 4 of 7'); + await shot(page, testInfo, 'unfinished-reconnected', lower); + + await toolbarAction(page, 'Rotate right'); + const rotated = await pointOnPiece(page, unfinished[5].id); + await tapOrClick(page, mobile, rotated); + await expect(selectionLine(page)).toContainText('Selected piece 6 of 7'); + await expectHighlightAt(page, rotated); + await shot(page, testInfo, 'rotated-selected', rotated); + + for (let i = 0; i < 5; i++) await page.getByRole('button', { name: 'Previous piece' }).click(); + await expect(selectionLine(page)).toContainText('Selected piece 1 of 7'); + await expect(page.getByRole('button', { name: 'Previous piece' })).toBeDisabled(); + await page.getByRole('button', { name: 'Build before this piece' }).click(); + await page.getByRole('button', { name: 'Straight' }).click(); + await page.getByRole('button', { name: 'Build piece' }).click(); + await expect(rideInfo(page)).toContainText('Track 8 pieces'); + await expect(selectionLine(page)).toContainText('Selected piece 1 of 8'); + + await page.getByRole('button', { name: 'Track end' }).click(); + await expect(selectionLine(page)).toContainText('Building from the end of the track'); + await expect(page.locator('.track-selection-outline')).toBeHidden(); + await page.getByRole('button', { name: 'Demolish last piece' }).click(); + await expect(rideInfo(page)).toContainText('Track 7 pieces'); + const last = await ridePieces(page, 1); + expect(last.map((piece) => piece.id)).not.toContain(unfinished[6].id); +} + +for (const backend of ['WebGL2', 'Canvas2D'] as const satisfies readonly Backend[]) { + for (const mobile of [false, true]) { + const where = `${backend} on ${mobile ? 'Pixel 8' : 'desktop'}`; + test.describe(`editing track from a chosen piece in ${where}`, () => { + for (const [name, run] of [ + ['rebuilds a removed piece of a closed circuit, retests and reopens it', editClosedCircuit], + ['edits unfinished and stacked track from the clicked piece', editUnfinished], + ] as const) { + test(name, async ({ browser }, testInfo) => { + test.setTimeout(480_000); + const page = await openPage(browser, mobile); + try { + if (!mobile) await page.setViewportSize({ width: 1280, height: 800 }); + if (backend === 'Canvas2D') await forceCanvas2D(page); + await loadPark(page, testInfo); + await expect(page.locator('.hud')).toContainText(backend); + await run(page, mobile, testInfo); + } finally { + await page.context().close(); + } + }); + } + }); + } +} diff --git a/src/app/bootstrap/index.ts b/src/app/bootstrap/index.ts index 019aeb61c..9f21e80e5 100644 --- a/src/app/bootstrap/index.ts +++ b/src/app/bootstrap/index.ts @@ -18,6 +18,7 @@ import { DEFAULT_MAP_SIZE, TRACK_STEPS_PER_LEVEL } from '../../sim/core/constant import { SceneryItem } from '../../sim/map/scenery'; import { CoasterPanel } from '../../ui/coaster-panel'; import { rideGhostSprites, TrackPreviewOverlay } from '../../ui/track-preview'; +import { TrackSelectionOutline } from '../tools/track-selection-outline'; import { displayOptionEnabled } from '../../ui/display-options'; import { TerrainAidOverlay } from '../terrain-aids'; import type { ConstructionTarget } from '../terrain-aids'; @@ -115,6 +116,7 @@ export async function bootstrap(): Promise { status: (text) => gameUi.setToolStatus(text), }); const trackPreview = new TrackPreviewOverlay(root); + const trackSelectionOutline = new TrackSelectionOutline(root); const terrainAids = new TerrainAidOverlay(root); const heightReadout = new HeightReadoutTip(root); const scenerySpot = new ScenerySpotPreview(root, sim); @@ -207,9 +209,10 @@ export async function bootstrap(): Promise { chooseRideType(type) { rideSetupState.current.chooseRideType(type); }, - editTrack(rideId) { + editTrack(rideId, pieceId) { coasterPanel.setActiveRide(rideId); gameUi.selectTool('track'); + if (pieceId !== undefined) gameUi.setToolStatus(coasterPanel.selectPiece(rideId, pieceId)); }, map: () => sim.map, camera: () => camera, @@ -413,6 +416,7 @@ export async function bootstrap(): Promise { patrolStaffId: () => patrolStaffId, clearRideSetupNotice: rideSetupState.current.clearNotice, rideTileClick: rideSetupState.current.rideTileClick, + trackGhostAt: (x, y) => trackPreview.hits(x, y), }); const resolution = new AdaptiveResolution(); @@ -704,6 +708,13 @@ export async function bootstrap(): Promise { capDevicePixelRatio(window.devicePixelRatio || 1) * appliedScale, pathGhost ?? hoverGhost, ); + trackSelectionOutline.update( + coasterPanel.selectedPiece(), + renderer, + latest, + camera, + canvas.getBoundingClientRect(), + ); let construction: ConstructionTarget | null = null; if (displayOptionEnabled('construction-marker')) { if (selectedTool === 'path') construction = pathTool.buildTarget; @@ -748,6 +759,7 @@ export async function bootstrap(): Promise { audio.dispose(); coasterPanel.dispose(); trackPreview.dispose(); + trackSelectionOutline.dispose(); terrainAids.dispose(); heightReadout.dispose(); scenerySpot.dispose(); diff --git a/src/app/tools/index.ts b/src/app/tools/index.ts index 9d274e096..18a6e3134 100644 --- a/src/app/tools/index.ts +++ b/src/app/tools/index.ts @@ -2,7 +2,7 @@ import type { Camera, Renderer } from '../../render/renderer'; import { pickTile } from '../../render/projection'; import type { GameUI, GuestSelection, ToolMode } from '../../ui/game-ui'; import type { SimClient } from '../../worker/sim-client'; -import { findRideIdAtTile } from '../../input/object-picking'; +import { findRideIdAtTile, pickTrackPiece } from '../../input/object-picking'; import type { CoasterPanel } from '../../ui/coaster-panel'; import type { SceneryItem } from '../../sim/map/scenery'; import { isWallScenery } from '../../sim/map/scenery'; @@ -77,6 +77,8 @@ export interface ToolControllerDependencies { patrolStaffId: () => number | null; clearRideSetupNotice: () => void; rideTileClick: (x: number, y: number) => void; + /** Whether a viewport point lies on the track tool's build preview. */ + trackGhostAt: (x: number, y: number) => boolean; } export function createToolController(deps: ToolControllerDependencies) { @@ -572,13 +574,16 @@ export function createToolController(deps: ToolControllerDependencies) { else if (selectedTool === 'flowerbed') handleFlowerbedTool(handlerDeps, x, y, shiftKey); else if (selectedTool === 'patrol') handlePatrolTool(handlerDeps, x, y, shiftKey); else if (selectedTool === 'ride') deps.rideTileClick(x, y); - else deps.gameUi.setToolStatus(deps.coasterPanel.handleTileClick(x, y)); + else trackToolClick(localX, localY, x, y, rect); return; } if (object) { deps.setSelectedGuest(null); if (object.kind === 'ride' && object.rideId !== undefined) { - deps.gameUi.openRide(object.rideId); + deps.gameUi.openRide( + object.rideId, + object.coasterPart === 'track' ? object.pieceId : undefined, + ); deps.gameUi.setToolStatus(`${object.name} information opened.`); } else if (object.kind === 'guest' && object.personId !== undefined) { const guest = findGuestAt( @@ -661,6 +666,38 @@ export function createToolController(deps: ToolControllerDependencies) { deps.gameUi.update(deps.sim.latest, deps.sim.stats, deps.selectedGuest()); } + /** + * Track tool: a click on the rails of a coaster selects that piece to edit from; a click on the + * build preview or open ground builds as before. + */ + function trackToolClick( + localX: number, + localY: number, + x: number, + y: number, + rect: DOMRect, + ): void { + const snapshot = deps.sim.latest; + if (snapshot && deps.coasterPanel.buildsTrack() && !deps.trackGhostAt(localX, localY)) { + const targets = deps.renderer.objectTargets(snapshot, deps.camera, { + width: rect.width, + height: rect.height, + }); + const hit = pickTrackPiece(targets, localX, localY); + if (hit && 'pieceId' in hit) { + deps.gameUi.setToolStatus(deps.coasterPanel.selectPiece(hit.rideId, hit.pieceId)); + return; + } + if (hit) { + deps.gameUi.setToolStatus( + `That is the ride's ${hit.part === 'support' ? 'support' : 'train'}. Click the rails to select a piece of track.`, + ); + return; + } + } + deps.gameUi.setToolStatus(deps.coasterPanel.handleTileClick(x, y)); + } + function personDragStart(clientX: number, clientY: number): boolean { if (deps.selectedTool() !== 'select' || !deps.sim.latest) return false; if (!deps.sim.map) return false; diff --git a/src/app/tools/track-selection-outline.ts b/src/app/tools/track-selection-outline.ts new file mode 100644 index 000000000..51033b3d4 --- /dev/null +++ b/src/app/tools/track-selection-outline.ts @@ -0,0 +1,71 @@ +import type { Camera, Renderer } from '../../render/renderer'; +import type { Snapshot } from '../../worker/snapshot'; +import { snapshotPiece } from '../../ui/track-selection'; +import { drawSpriteOutline } from './object-overlay'; + +/** + * Outlines the track piece selected in the construction window over the game canvas, from the same + * sprite masks both renderers pick with. Redraws only when the piece, its geometry or the camera + * changes. + */ +export class TrackSelectionOutline { + private readonly canvas: HTMLCanvasElement; + private key = ''; + private origin = { x: 0, y: 0 }; + + constructor(parent: HTMLElement) { + this.canvas = document.createElement('canvas'); + this.canvas.className = 'track-selection-outline'; + this.canvas.setAttribute('aria-hidden', 'true'); + this.canvas.hidden = true; + parent.append(this.canvas); + } + + update( + selected: { rideId: number; pieceId: number } | null, + renderer: Renderer, + snapshot: Snapshot | null, + camera: Camera, + rect: DOMRect, + ): void { + const piece = selected && snapshot ? snapshotPiece(snapshot, selected.pieceId) : null; + if (!piece || !snapshot) { + this.canvas.hidden = true; + this.key = ''; + return; + } + const viewport = { width: rect.width, height: rect.height }; + const key = [ + piece.id, + piece.pieceType, + piece.x, + piece.y, + piece.z, + piece.dir, + camera.x, + camera.y, + camera.zoom, + camera.rotation, + viewport.width, + viewport.height, + ].join(':'); + if (key !== this.key) { + const targets = renderer + .objectTargets(snapshot, camera, viewport) + .filter((target) => target.coasterPart === 'track' && target.pieceId === piece.id); + if (targets.length === 0) { + this.canvas.hidden = true; + return; + } + this.origin = drawSpriteOutline(this.canvas, targets); + this.key = key; + } + this.canvas.style.left = `${rect.left + this.origin.x}px`; + this.canvas.style.top = `${rect.top + this.origin.y}px`; + this.canvas.hidden = false; + } + + dispose(): void { + this.canvas.remove(); + } +} diff --git a/src/input/object-picking.test.ts b/src/input/object-picking.test.ts index 1e81104bd..624e26f0a 100644 --- a/src/input/object-picking.test.ts +++ b/src/input/object-picking.test.ts @@ -1,5 +1,11 @@ import { describe, expect, it } from 'vitest'; -import { findRideIdAtTile, pickTopmostObject, pickTopmostSprite } from './object-picking'; +import { + findRideIdAtTile, + pickTopmostObject, + pickTopmostSprite, + pickTrackPiece, +} from './object-picking'; +import type { ObjectPickTarget } from './object-picking'; import { RideType } from '../sim/rides/ride-types'; import { RideInfo, SNAPSHOT_STRIDE, createSnapshot } from '../worker/snapshot'; @@ -102,3 +108,47 @@ describe('sprite picking', () => { expect(pickTopmostObject([scenery, person], 12, 10.5)).toBeNull(); }); }); + +describe('track piece picking', () => { + const sprite = (over: Partial): ObjectPickTarget => ({ + id: 'ride:3', + kind: 'ride', + name: 'Wooden coaster', + tileX: 0, + tileY: 0, + sortDepth: 0, + x: 10, + y: 10, + width: 2, + height: 2, + alphaWidth: 2, + alphaHeight: 2, + alpha: Uint8Array.of(255, 255, 255, 255), + rideId: 3, + ...over, + }); + + it('returns the rail piece drawn on top, ignoring scenery and guests in front of it', () => { + const lower = sprite({ coasterPart: 'track', pieceId: 4, sortDepth: 1 }); + const upper = sprite({ + coasterPart: 'track', + pieceId: 9, + sortDepth: 1, + alpha: Uint8Array.of(0, 255, 0, 0), + }); + const tree = sprite({ id: 'scenery:1', kind: 'scenery', rideId: undefined, sortDepth: 5 }); + + expect(pickTrackPiece([lower, upper, tree], 11.5, 10.5)).toEqual({ rideId: 3, pieceId: 9 }); + expect(pickTrackPiece([lower, upper, tree], 10.5, 10.5)).toEqual({ rideId: 3, pieceId: 4 }); + expect(pickTrackPiece([tree], 10.5, 10.5)).toBeNull(); + }); + + it('does not turn a click on a train or a support into a track piece', () => { + const rail = sprite({ coasterPart: 'track', pieceId: 4 }); + const car = sprite({ coasterPart: 'car', sortDepth: 2 }); + const support = sprite({ coasterPart: 'support', pieceId: 4, sortDepth: 2 }); + + expect(pickTrackPiece([rail, car], 10.5, 10.5)).toEqual({ rideId: 3, part: 'car' }); + expect(pickTrackPiece([rail, support], 10.5, 10.5)).toEqual({ rideId: 3, part: 'support' }); + }); +}); diff --git a/src/input/object-picking.ts b/src/input/object-picking.ts index ec45a3273..646e402bc 100644 --- a/src/input/object-picking.ts +++ b/src/input/object-picking.ts @@ -15,6 +15,7 @@ import { } from '../worker/snapshot'; import { peopleSpriteKey } from '../render/people-art'; import { CoasterScene } from '../render/coaster-scene'; +import type { CoasterPart } from '../render/coaster-scene'; import { RideCellScene, isSlicedRide } from '../render/ride-scene'; import { sceneryBox, @@ -61,6 +62,9 @@ export interface ObjectPickTarget extends SpritePickTarget { tileX: number; tileY: number; rideId?: number; + /** Which part of a coaster the sprite shows, and the track piece of a rail or support sprite. */ + coasterPart?: CoasterPart; + pieceId?: number; personId?: number; sceneryIndex?: number; pathIndex?: number; @@ -104,7 +108,17 @@ export function buildObjectPickTargets( tileY: number, sortDepth: number, meta: Partial< - Pick + Pick< + ObjectPickTarget, + | 'id' + | 'rideId' + | 'coasterPart' + | 'pieceId' + | 'personId' + | 'sceneryIndex' + | 'pathIndex' + | 'state' + > > = {}, boxed?: { width: number; height: number }, ) => { @@ -262,6 +276,8 @@ export function buildObjectPickTargets( if (!name || x < 0 || y < 0 || x >= map.width || y >= map.height) continue; add(item.key, item.x, item.y, item.z, 'ride', name, x, y, item.depth, { rideId: item.rideId, + coasterPart: item.part, + ...(item.pieceId >= 0 ? { pieceId: item.pieceId } : {}), }); } const gateX = snapshot.park.entranceX; @@ -452,6 +468,31 @@ export function pickTopmostObject( return null; } +/** What a construction click on a coaster hit: a rail piece, or another part of the ride. */ +export type TrackPick = + { rideId: number; pieceId: number } | { rideId: number; part: Exclude }; + +/** + * The coaster sprite on top at this screen position, looking only at coaster sprites so scenery and + * guests in front of the track do not get in the way. Rails name their piece; trains, riders and + * supports report the part instead of standing in for a piece. + */ +export function pickTrackPiece( + targets: readonly ObjectPickTarget[], + screenX: number, + screenY: number, +): TrackPick | null { + const hit = pickTopmostObject( + targets.filter((target) => target.coasterPart !== undefined), + screenX, + screenY, + ); + if (!hit || hit.rideId === undefined || !hit.coasterPart) return null; + if (hit.coasterPart === 'track' && hit.pieceId !== undefined) + return { rideId: hit.rideId, pieceId: hit.pieceId }; + return { rideId: hit.rideId, part: hit.coasterPart === 'track' ? 'support' : hit.coasterPart }; +} + export function findRideIdAtTile(snapshot: Snapshot, tileX: number, tileY: number): number | null { for (let i = 0; i < snapshot.rides.count; i++) { const offset = i * RIDE_INFO_STRIDE; diff --git a/src/render/coaster-scene.ts b/src/render/coaster-scene.ts index 29fe95797..814ae6ab8 100644 --- a/src/render/coaster-scene.ts +++ b/src/render/coaster-scene.ts @@ -1,7 +1,7 @@ import { TILE_UNITS, TRACK_Z_STEP, Z_STEP } from '../sim/core/constants'; import { decodeCarPose } from '../worker/car-poses'; import type { CarPose } from '../worker/car-poses'; -import { RideInfo, RIDE_INFO_STRIDE, SNAPSHOT_STRIDE } from '../worker/snapshot'; +import { RideInfo, RIDE_INFO_STRIDE, SNAPSHOT_STRIDE, TRACK_LINK_STRIDE } from '../worker/snapshot'; import type { Snapshot } from '../worker/snapshot'; import { carSpriteKey, @@ -22,10 +22,16 @@ const NO_TRENCHES: ReadonlyMap = new Map(); import type { Rotation } from './projection'; import { rotateDirection, viewDepth } from './projection'; +/** What a coaster sprite shows: a piece's rails, a support under it, a car, or a seated rider. */ +export type CoasterPart = 'track' | 'support' | 'car' | 'rider'; + /** One sprite to draw: the atlas key with its anchor at world (x, y, z), sorted by `depth`. */ export interface CoasterDrawItem { key: string; rideId: number; + part: CoasterPart; + /** Stable id of the track piece a rail or support sprite belongs to; -1 for cars and riders. */ + pieceId: number; x: number; y: number; z: number; @@ -64,6 +70,8 @@ export class CoasterScene { private push( key: string, rideId: number, + part: CoasterPart, + pieceId: number, x: number, y: number, z: number, @@ -72,11 +80,13 @@ export class CoasterScene { ): void { let item = this.items[this.count]; if (!item) { - item = { key, rideId, x, y, z, depth, xray }; + item = { key, rideId, part, pieceId, x, y, z, depth, xray }; this.items.push(item); } else { item.key = key; item.rideId = rideId; + item.part = part; + item.pieceId = pieceId; item.x = x; item.y = y; item.z = z; @@ -133,6 +143,7 @@ export class CoasterScene { const family = this.families.get(rideId); const transport = this.transports.get(rideId); if (!family && !transport) continue; + const pieceId = snapshot.trackLinks[i * TRACK_LINK_STRIDE]; const pieceType = word & 0xff; const dir = (word >> 8) & 3; const mode = (word >> 10) & 7; @@ -152,19 +163,20 @@ export class CoasterScene { const x = tileX * TILE_UNITS + TILE_UNITS / 2; const y = tileY * TILE_UNITS + TILE_UNITS / 2; const depth = tileDepth(x, y, map, rotation); - this.push(cells[c].key, rideId, x, y, z, depth + TRACK_OFFSET); + this.push(cells[c].key, rideId, 'track', pieceId, x, y, z, depth + TRACK_OFFSET); if ( hidden && hidden.includes(tileY * map.width + tileX) && !trenches.has(tileY * map.width + tileX) ) - this.push(cells[c].key, rideId, x, y, z, depth + TRACK_OFFSET, true); + this.push(cells[c].key, rideId, 'track', pieceId, x, y, z, depth + TRACK_OFFSET, true); if (family && family !== 'log-flume' && family !== 'river-rapids') this.addSupports( pieceType, c, family, rideId, + pieceId, dir, rotation, map, @@ -182,6 +194,7 @@ export class CoasterScene { cell: number, family: CoasterFamily, rideId: number, + pieceId: number, dir: number, rotation: Rotation, map: MapData, @@ -201,6 +214,8 @@ export class CoasterScene { this.push( `${prefix}-column/view-${view}`, rideId, + 'support', + pieceId, x, y, (ground + level) * Z_STEP, @@ -210,6 +225,8 @@ export class CoasterScene { this.push( `${prefix}-cap${stack.quarters}/view-${view}`, rideId, + 'support', + pieceId, x, y, (ground + stack.full) * Z_STEP, @@ -219,6 +236,8 @@ export class CoasterScene { this.push( `${prefix}-base/view-${view}`, rideId, + 'support', + pieceId, x, y, ground * Z_STEP, @@ -240,6 +259,8 @@ export class CoasterScene { ? carSpriteKey(family, pose.heading, pose.pitch, pose.bank, rotation, pose.passengers) : transportCarSpriteKey(transport!, pose.heading, pose.pitch, rotation), pose.rideId, + 'car', + -1, x, y, cars.data[o + 2], @@ -274,6 +295,8 @@ export class CoasterScene { this.push( `people/rider-seated#${((car + k) & 7) * 4 + facing}`, pose.rideId, + 'rider', + -1, riderX, riderY, z + SEAT_HEIGHT, diff --git a/src/sim/rides/coaster.test.ts b/src/sim/rides/coaster.test.ts index 203476286..67a838bec 100644 --- a/src/sim/rides/coaster.test.ts +++ b/src/sim/rides/coaster.test.ts @@ -7,7 +7,7 @@ import { deserialize, serialize } from '../../save/save'; import { PieceId, pieceByName } from '../track/catalog'; import { circuitStatus } from '../track/construction'; import { GuestState } from '../guests/guest-store'; -import { PieceMode, TrackResult } from '../track/track-types'; +import { PieceMode, TrackNotice, TrackResult } from '../track/track-types'; import { VehicleState } from '../vehicles/vehicle-store'; import { StaffKind, spawnStaff } from '../staff/staff-store'; import { rideTrainSlots } from '../vehicles/ride-trains'; @@ -280,16 +280,20 @@ describe('opening a coaster', () => { expect(dispatched).toBeGreaterThan(0); }); - it('invalidates the test and closes the ride when the track is edited', () => { + it('invalidates the test and removes the trains when the track of a closed ride is edited', () => { const { sim, rideId } = testedCoaster(); connectStation(sim, rideId); sim.enqueue({ type: 'setRideStatus', rideId, status: 'open' }); sim.step(); + sim.enqueue({ type: 'setRideStatus', rideId, status: 'close' }); + run(sim, 3000); sim.enqueue({ type: 'removeTrack', rideId, pieceId: -1 }); sim.step(); const slot = sim.world.rides.idToSlot[rideId]; + expect(sim.world.feedback.code).toBe(TrackNotice.Removed); expect(sim.world.rides.cols.state[slot]).toBe(RideState.Closed); expect(isRideTested(sim.world, rideId)).toBe(false); + expect(sim.world.vehicles.count).toBe(0); }); it('round-trips a running coaster through save and load without diverging', () => { @@ -325,7 +329,7 @@ describe('coaster failure handling', () => { expect(sim.world.vehicles.cols.state[0]).toBe(VehicleState.Running); } - it('lets riders off and closes the ride when its track is edited mid-ride', () => { + it('keeps riders aboard and the ride running when its track is edited mid-ride', () => { const { sim, rideId, slot } = openWithRiders(); runUntilTrainIsOut(sim); run(sim, 5); @@ -339,10 +343,11 @@ describe('coaster failure handling', () => { expect(riding()).toBe(12); sim.enqueue({ type: 'removeTrack', rideId, pieceId: -1 }); run(sim, 10); - expect(riding()).toBe(0); - expect(sim.world.vehicles.count).toBe(0); - expect(sim.world.rides.cols.phase[slot]).toBe(RidePhase.Closed); - expect(sim.world.rides.cols.state[slot]).toBe(RideState.Closed); + expect(sim.world.feedback.code).toBe(TrackResult.RideBusy); + expect(riding()).toBe(12); + expect(sim.world.vehicles.count).toBe(1); + expect(sim.world.rides.cols.phase[slot]).toBe(RidePhase.Running); + expect(sim.world.rides.cols.state[slot]).toBe(RideState.Open); }); it('keeps a ride that is closed right after dispatch consistent and reopenable', () => { diff --git a/src/sim/rides/ride-boarding.ts b/src/sim/rides/ride-boarding.ts index abfd9a75a..65c91c640 100644 --- a/src/sim/rides/ride-boarding.ts +++ b/src/sim/rides/ride-boarding.ts @@ -78,3 +78,26 @@ export function faceBoardingAwayFromRide(world: World, slot: number): void { setBoardingFront(world, x, y, frontAwayFrom(tiles, x, y)); } } + +/** + * Takes an entrance or exit off a track ride once no station tile is beside it any more (after its + * station was removed). The path tile stays; the ride needs a new entrance or exit before it opens. + */ +export function detachStrandedGates(world: World, slot: number): void { + const ride = world.rides.cols; + const def = RIDE_CATALOG[ride.typeId[slot] as RideType]; + if (!def?.usesTrack) return; + const tiles = rideBoardingTiles(world, slot); + const beside = (x: number, y: number): boolean => + tiles.some(([bx, by]) => Math.abs(bx - x) + Math.abs(by - y) === 1); + if (ride.entrancePlaced[slot] && !beside(ride.entranceX[slot], ride.entranceY[slot])) { + setBoardingFront(world, ride.entranceX[slot], ride.entranceY[slot], -1); + ride.entrancePlaced[slot] = 0; + ride.queueConnected[slot] = 0; + ride.queueLineTiles[slot] = 0; + } + if (ride.exitPlaced[slot] && !beside(ride.exitX[slot], ride.exitY[slot])) { + setBoardingFront(world, ride.exitX[slot], ride.exitY[slot], -1); + ride.exitPlaced[slot] = 0; + } +} diff --git a/src/sim/rides/ride-commands.ts b/src/sim/rides/ride-commands.ts index 63231d7c7..d8083566e 100644 --- a/src/sim/rides/ride-commands.ts +++ b/src/sim/rides/ride-commands.ts @@ -53,7 +53,8 @@ function rideFootprintAt(world: World, x: number, y: number): boolean { return false; } -function isBusy(world: World, slot: number): boolean { +/** Open, testing, or mid-cycle (loading, running or unloading). */ +export function isBusy(world: World, slot: number): boolean { const ride = world.rides.cols; return ( ride.state[slot] === RideState.Open || diff --git a/src/sim/rides/track-edit-safety.test.ts b/src/sim/rides/track-edit-safety.test.ts new file mode 100644 index 000000000..86557b17e --- /dev/null +++ b/src/sim/rides/track-edit-safety.test.ts @@ -0,0 +1,169 @@ +import { describe, expect, it } from 'vitest'; +import { TRACK_STEPS_PER_LEVEL } from '../core/constants'; +import { FeedbackDomain } from '../core/feedback'; +import type { Simulation } from '../core/simulation'; +import type { Command } from '../core/commands'; +import { pieceByName } from '../track/catalog'; +import { circuitStatus, getConstructionCursor } from '../track/construction'; +import { TrackNotice, TrackResult } from '../track/track-types'; +import { VehicleState } from '../vehicles/vehicle-store'; +import { + GROUND, + SMALL_CIRCUIT, + STATION_X, + STATION_Y, + connectStation, + createCoaster, + flatOwnedSim, + queueGuests, + run, +} from './coaster-fixtures'; +import { isRideTested } from './ride-operations'; +import { RideResult } from './ride-results'; +import { RidePhase, RideState } from './ride-store'; + +const TEST_RUN_TICKS = 6000; + +type PlaceTrack = Extract; + +/** Builds SMALL_CIRCUIT one piece per tick and returns each piece's id and placement command. */ +function buildRecorded( + sim: Simulation, + rideId: number, +): Array<{ id: number; command: PlaceTrack }> { + const built: Array<{ id: number; command: PlaceTrack }> = []; + for (const [name, mode] of SMALL_CIRCUIT) { + const cursor = getConstructionCursor(sim.world, rideId); + const command: PlaceTrack = { + type: 'placeTrack', + rideId, + pieceType: pieceByName(name)!.id, + x: cursor.hasTrack ? cursor.x : STATION_X, + y: cursor.hasTrack ? cursor.y : STATION_Y, + z: cursor.hasTrack ? cursor.z : GROUND * TRACK_STEPS_PER_LEVEL, + dir: cursor.hasTrack ? cursor.dir : 0, + mode, + }; + sim.enqueue(command); + sim.step(); + built.push({ id: sim.world.track.lastPiece, command }); + } + return built; +} + +function testedCoaster() { + const sim = flatOwnedSim(1); + const rideId = createCoaster(sim); + const built = buildRecorded(sim, rideId); + connectStation(sim, rideId); + sim.enqueue({ type: 'setRideStatus', rideId, status: 'test' }); + run(sim, TEST_RUN_TICKS); + expect(isRideTested(sim.world, rideId)).toBe(true); + return { sim, rideId, built, slot: sim.world.rides.idToSlot[rideId] }; +} + +function command(sim: Simulation, c: Command): void { + sim.enqueue(c); + sim.step(); +} + +function trackFeedback(sim: Simulation): number { + expect(sim.world.feedback.domain).toBe(FeedbackDomain.Track); + return sim.world.feedback.code; +} + +describe('editing a built coaster from a chosen piece', () => { + it('rebuilds a removed middle piece, passes a new test and opens with riders', () => { + const { sim, rideId, built, slot } = testedCoaster(); + const turn = built[6]; + + command(sim, { type: 'removeTrack', rideId, pieceId: turn.id }); + expect(trackFeedback(sim)).toBe(TrackNotice.Removed); + expect(circuitStatus(sim.world, rideId)).toMatchObject({ closed: false, pieces: 13 }); + expect(isRideTested(sim.world, rideId)).toBe(false); + for (const piece of built) { + if (piece !== turn) expect(sim.world.track.pieces.isAlive(piece.id)).toBe(true); + } + + command(sim, { type: 'setRideStatus', rideId, status: 'test' }); + expect(sim.world.feedback.code).toBe(RideResult.TrackIncomplete); + + command(sim, turn.command); + expect(trackFeedback(sim)).toBe(TrackResult.Ok); + expect(circuitStatus(sim.world, rideId).complete).toBe(true); + + command(sim, { type: 'setRideStatus', rideId, status: 'test' }); + run(sim, TEST_RUN_TICKS); + expect(isRideTested(sim.world, rideId)).toBe(true); + command(sim, { type: 'setRideStatus', rideId, status: 'open' }); + expect(sim.world.feedback.code).toBe(RideResult.Ok); + queueGuests(sim, rideId, 8); + run(sim, 3000); + expect(sim.world.rides.cols.guestsServed[slot]).toBeGreaterThan(0); + }); + + it('refuses to change the track of an open ride and leaves it running', () => { + const { sim, rideId, built, slot } = testedCoaster(); + command(sim, { type: 'setRideStatus', rideId, status: 'open' }); + + command(sim, { type: 'removeTrack', rideId, pieceId: built[6].id }); + expect(trackFeedback(sim)).toBe(TrackResult.RideBusy); + command(sim, { type: 'removeTrack', rideId, pieceId: -1 }); + expect(trackFeedback(sim)).toBe(TrackResult.RideBusy); + + expect(sim.world.track.pieces.isAlive(built[6].id)).toBe(true); + expect(circuitStatus(sim.world, rideId).complete).toBe(true); + expect(sim.world.rides.cols.state[slot]).toBe(RideState.Open); + expect(isRideTested(sim.world, rideId)).toBe(true); + }); + + it('refuses edits while a closed ride still has a loaded train out, then allows them once it is back', () => { + const { sim, rideId, built, slot } = testedCoaster(); + command(sim, { type: 'setRideStatus', rideId, status: 'open' }); + queueGuests(sim, rideId, 12); + for (let i = 0; i < 2000 && sim.world.vehicles.cols.state[0] !== VehicleState.Running; i++) + sim.step(); + command(sim, { type: 'setRideStatus', rideId, status: 'close' }); + const riders = sim.world.vehicles.cols.passengers[0]; + const servedBefore = sim.world.rides.cols.guestsServed[slot]; + expect(riders).toBeGreaterThan(0); + + command(sim, { type: 'removeTrack', rideId, pieceId: built[6].id }); + expect(trackFeedback(sim)).toBe(TrackResult.RideBusy); + expect(sim.world.vehicles.cols.passengers[0]).toBe(riders); + + for (let i = 0; i < 4000 && sim.world.rides.cols.phase[slot] !== RidePhase.Closed; i++) + sim.step(); + command(sim, { type: 'removeTrack', rideId, pieceId: built[6].id }); + expect(trackFeedback(sim)).toBe(TrackNotice.Removed); + expect(sim.world.rides.cols.guestsServed[slot]).toBe(servedBefore + riders); + }); + + it('refuses edits during a test run', () => { + const { sim, rideId, built } = testedCoaster(); + command(sim, { type: 'setRideStatus', rideId, status: 'test' }); + command(sim, built[6].command); + expect(trackFeedback(sim)).toBe(TrackResult.RideBusy); + command(sim, { type: 'removeTrack', rideId, pieceId: built[6].id }); + expect(trackFeedback(sim)).toBe(TrackResult.RideBusy); + expect(circuitStatus(sim.world, rideId).complete).toBe(true); + }); + + it('takes the entrance off the ride when the station beside it is removed', () => { + const { sim, rideId, built } = testedCoaster(); + const station = built[0]; + + command(sim, { type: 'removeTrack', rideId, pieceId: station.id }); + command(sim, station.command); + expect(circuitStatus(sim.world, rideId).complete).toBe(true); + command(sim, { type: 'setRideStatus', rideId, status: 'test' }); + run(sim, TEST_RUN_TICKS); + expect(isRideTested(sim.world, rideId)).toBe(true); + command(sim, { type: 'setRideStatus', rideId, status: 'open' }); + expect(sim.world.feedback.code).toBe(RideResult.NoEntrance); + + connectStation(sim, rideId); + command(sim, { type: 'setRideStatus', rideId, status: 'open' }); + expect(sim.world.feedback.code).toBe(RideResult.Ok); + }); +}); diff --git a/src/sim/track/construction.test.ts b/src/sim/track/construction.test.ts index 67b5c5e9c..35f404258 100644 --- a/src/sim/track/construction.test.ts +++ b/src/sim/track/construction.test.ts @@ -281,7 +281,7 @@ describe('construction', () => { expect(getConstructionCursor(w, ride)).toMatchObject({ x: 12, y: 10 }); }); - it('removes from the ends, reopens a closed circuit, and rejects mid-chain removal', () => { + it('removes from the ends and reopens a closed circuit', () => { buildRing(w, ride); expect(removeTrack(w, ride, -1)).toBe(TrackResult.Ok); expect(circuitStatus(w, ride)).toMatchObject({ closed: false, pieces: 13 }); @@ -294,7 +294,6 @@ describe('construction', () => { app(w, r2, 'flat'); app(w, r2, 'flat'); const mid = w.track.pieces.slotToId[w.track.pieces.count - 2]; - expect(removeTrack(w, r2, mid)).toBe(TrackResult.NotAtEnd); expect(removeTrack(w, r2, w.track.head[r2])).toBe(TrackResult.Ok); expect(getConstructionCursor(w, r2)).toMatchObject({ x: 33, y: 30 }); expect(removeTrack(w, r2, mid + 9999)).toBe(TrackResult.NoSuchPiece); diff --git a/src/sim/track/construction.ts b/src/sim/track/construction.ts index ad2b4215f..9665d7067 100644 --- a/src/sim/track/construction.ts +++ b/src/sim/track/construction.ts @@ -132,39 +132,65 @@ export function connectablePieces(cursor: ConstructionCursor): number[] { return out; } -type Attach = 'first' | 'tail' | 'head'; +/** The open ends a new piece joins: the piece it follows and the piece it leads into (-1 = none). */ +export interface Attach { + after: number; + before: number; +} + +/** Whether the piece in `slot` ends exactly where `req` begins, in position, heading, slope and bank. */ +function endsAt(world: World, slot: number, req: PlaceRequest): boolean { + const c = world.track.pieces.cols; + const def = PIECES[c.pieceType[slot]]; + const next = PIECES[req.pieceType]; + const exit = pieceExit(def.id, c.x[slot], c.y[slot], c.z[slot], c.dir[slot]); + return ( + exit.x === req.x && + exit.y === req.y && + exit.z === req.z && + exit.dir === req.dir && + def.exitSlope === next.entrySlope && + def.exitBank === next.entryBank + ); +} -function attachPoint(world: World, req: PlaceRequest): Attach | TrackResult { +/** Whether the piece in `slot` begins exactly where `req` ends. */ +function beginsAt(world: World, slot: number, req: PlaceRequest): boolean { + const c = world.track.pieces.cols; + const def = PIECES[c.pieceType[slot]]; + const prev = PIECES[req.pieceType]; + const exit = pieceExit(prev.id, req.x, req.y, req.z, req.dir); + return ( + exit.x === c.x[slot] && + exit.y === c.y[slot] && + exit.z === c.z[slot] && + exit.dir === c.dir[slot] && + prev.exitSlope === def.entrySlope && + prev.exitBank === def.entryBank + ); +} + +/** + * The open ends of the ride's track that a placement meets. A ride's track is one or more + * sections; a new piece may continue any section's last piece and lead into any section's first + * piece, preferring the end of the section being built. + */ +export function attachPoint(world: World, req: PlaceRequest): Attach | TrackResult { const t = world.track; const r = req.rideId; - if (t.tail[r] < 0) return 'first'; - const def = PIECES[req.pieceType]; - const cur = getConstructionCursor(world, r); - if ( - cur.x === req.x && - cur.y === req.y && - cur.z === req.z && - cur.dir === req.dir && - cur.slope === def.entrySlope && - cur.bank === def.entryBank - ) { - return 'tail'; + if (t.tail[r] < 0) return { after: -1, before: -1 }; + const p = t.pieces; + const c = p.cols; + const activeTail = p.idToSlot[t.tail[r]]; + let after = c.next[activeTail] < 0 && endsAt(world, activeTail, req) ? t.tail[r] : -1; + let before = -1; + for (let slot = 0; slot < p.count; slot++) { + if (c.rideId[slot] !== r) continue; + if (after < 0 && c.next[slot] < 0 && endsAt(world, slot, req)) after = p.slotToId[slot]; + if (before < 0 && c.prev[slot] < 0 && beginsAt(world, slot, req)) before = p.slotToId[slot]; } - const hs = t.pieces.idToSlot[t.head[r]]; - const hdef = PIECES[t.pieces.cols.pieceType[hs]]; - const exit = pieceExit(def.id, req.x, req.y, req.z, req.dir); - const c = t.pieces.cols; - if ( - exit.x === c.x[hs] && - exit.y === c.y[hs] && - exit.z === c.z[hs] && - exit.dir === c.dir[hs] && - def.exitSlope === hdef.entrySlope && - def.exitBank === hdef.entryBank - ) { - return 'head'; - } - return TrackResult.NotConnected; + if (after < 0 && before < 0) return TrackResult.NotConnected; + return { after, before }; } /** Checks terrain, height and bounds, then clearance against all placed track. */ @@ -251,48 +277,81 @@ export function validatePlacement(world: World, req: PlaceRequest): TrackResult return checkSpace(world, req); } -/** Recomputes a ride's piece count, start arclengths and length, and invalidates its path. */ -export function relinkRide(world: World, rideId: number): void { +/** + * Makes the section holding `id` the one the construction cursor builds on: `head` and `tail` become + * its first and last piece. In a ring, `id` becomes the tail. + */ +function focusSection(world: World, rideId: number, id: number): void { const t = world.track; - const c = t.pieces.cols; - t.version[rideId]++; - t.paths[rideId] = null; - if (t.head[rideId] < 0) { - t.count[rideId] = 0; - t.closed[rideId] = 0; - t.length[rideId] = 0; + const p = t.pieces; + const c = p.cols; + let last = id; + for (let next = c.next[p.idToSlot[last]]; next >= 0 && next !== id;) { + last = next; + next = c.next[p.idToSlot[last]]; + } + if (c.next[p.idToSlot[last]] === id) { + t.head[rideId] = c.next[p.idToSlot[id]]; + t.tail[rideId] = id; return; } - let id = t.head[rideId]; + let first = id; + for (let prev = c.prev[p.idToSlot[first]]; prev >= 0; prev = c.prev[p.idToSlot[first]]) + first = prev; + t.head[rideId] = first; + t.tail[rideId] = last; +} + +/** Walks a section from `id`, numbering arclengths from 0. Returns its piece count and length. */ +function measureSection(world: World, id: number): [number, number] { + const p = world.track.pieces; + const c = p.cols; let s = 0; let n = 0; + let at = id; do { - const slot = t.pieces.idToSlot[id]; + const slot = p.idToSlot[at]; c.startS[slot] = s; s += PIECES[c.pieceType[slot]].length; n++; - id = c.next[slot]; - } while (id >= 0 && id !== t.head[rideId]); - t.count[rideId] = n; - t.length[rideId] = s; + at = c.next[slot]; + } while (at >= 0 && at !== id); + return [n, s]; } -function closesCircuit(world: World, rideId: number): boolean { +/** + * Recomputes a ride's piece count, length, start arclengths (from the first piece of each section) + * and whether its track is one closed circuit, and invalidates its path. + */ +export function relinkRide(world: World, rideId: number): void { const t = world.track; - const c = t.pieces.cols; - const ts = t.pieces.idToSlot[t.tail[rideId]]; - const hs = t.pieces.idToSlot[t.head[rideId]]; - const tdef = PIECES[c.pieceType[ts]]; - const hdef = PIECES[c.pieceType[hs]]; - const e = pieceExit(tdef.id, c.x[ts], c.y[ts], c.z[ts], c.dir[ts]); - return ( - e.x === c.x[hs] && - e.y === c.y[hs] && - e.z === c.z[hs] && - e.dir === c.dir[hs] && - tdef.exitSlope === hdef.entrySlope && - tdef.exitBank === hdef.entryBank - ); + const p = t.pieces; + const c = p.cols; + t.version[rideId]++; + t.paths[rideId] = null; + if (t.head[rideId] < 0) { + t.count[rideId] = 0; + t.closed[rideId] = 0; + t.length[rideId] = 0; + return; + } + for (let slot = 0; slot < p.count; slot++) if (c.rideId[slot] === rideId) c.startS[slot] = -1; + const [activeCount, activeLength] = measureSection(world, t.head[rideId]); + const ring = c.prev[p.idToSlot[t.head[rideId]]] === t.tail[rideId]; + let count = activeCount; + let length = activeLength; + for (let pass = 0; pass < 2; pass++) { + for (let slot = 0; slot < p.count; slot++) { + if (c.rideId[slot] !== rideId || c.startS[slot] >= 0) continue; + if (pass === 0 && c.prev[slot] >= 0) continue; + const [n, s] = measureSection(world, p.slotToId[slot]); + count += n; + length += s; + } + } + t.count[rideId] = count; + t.length[rideId] = length; + t.closed[rideId] = ring && activeCount === count ? 1 : 0; } /** Validates and applies a placement. Returns the result; the new piece id is `lastPiece`. */ @@ -314,36 +373,20 @@ export function placeTrack(world: World, req: PlaceRequest): TrackResult { c.z[slot] = req.z; c.dir[slot] = req.dir; c.mode[slot] = req.mode; - c.prev[slot] = -1; - c.next[slot] = -1; - const r = req.rideId; - if (attach === 'first') { - t.head[r] = id; - t.tail[r] = id; - } else if (attach === 'tail') { - const ts = t.pieces.idToSlot[t.tail[r]]; - c.next[ts] = id; - c.prev[slot] = t.tail[r]; - t.tail[r] = id; - } else { - const hs = t.pieces.idToSlot[t.head[r]]; - c.prev[hs] = id; - c.next[slot] = t.head[r]; - t.head[r] = id; - } - if (t.head[r] !== t.tail[r] && closesCircuit(world, r)) { - c.next[t.pieces.idToSlot[t.tail[r]]] = t.head[r]; - c.prev[t.pieces.idToSlot[t.head[r]]] = t.tail[r]; - t.closed[r] = 1; - } - relinkRide(world, r); + c.prev[slot] = attach.after; + c.next[slot] = attach.before; + if (attach.after >= 0) c.next[t.pieces.idToSlot[attach.after]] = id; + if (attach.before >= 0) c.prev[t.pieces.idToSlot[attach.before]] = id; + focusSection(world, req.rideId, id); + relinkRide(world, req.rideId); t.lastPiece = id; return TrackResult.Ok; } /** - * Removes a piece of the ride. `pieceId` -1 means the last-placed end. Open chains can only lose - * an end piece; any piece of a closed circuit can go, which reopens it. + * Removes a piece of the ride. `pieceId` -1 means the last piece of the section being built. The + * rest of the track stays: removing a middle piece splits its section in two (or opens a closed + * circuit there), and building continues from the piece before the gap. */ export function removeTrack(world: World, rideId: number, pieceId: number): TrackResult { const t = world.track; @@ -359,61 +402,40 @@ function removeInner(world: World, rideId: number, pieceId: number): TrackResult if (t.tail[rideId] < 0) return TrackResult.NoSuchPiece; const id = pieceId === -1 ? t.tail[rideId] : pieceId; if (!Number.isInteger(id) || id < 0 || !t.pieces.isAlive(id)) return TrackResult.NoSuchPiece; - const c = t.pieces.cols; - const slot = t.pieces.idToSlot[id]; + const p = t.pieces; + const c = p.cols; + const slot = p.idToSlot[id]; if (c.rideId[slot] !== rideId) return TrackResult.NoSuchPiece; - const closed = t.closed[rideId] === 1; - const isHead = id === t.head[rideId]; - const isTail = id === t.tail[rideId]; - if (!closed && !isHead && !isTail) return TrackResult.NotAtEnd; - if (t.count[rideId] === 1) { - t.pieces.despawnSlot(slot); - t.head[rideId] = -1; - t.tail[rideId] = -1; - relinkRide(world, rideId); - return TrackResult.Ok; - } const prevId = c.prev[slot]; const nextId = c.next[slot]; - if (closed) { - t.head[rideId] = nextId; - t.tail[rideId] = prevId; - t.closed[rideId] = 0; - c.next[t.pieces.idToSlot[prevId]] = -1; - c.prev[t.pieces.idToSlot[nextId]] = -1; - } else if (isTail) { - t.tail[rideId] = prevId; - c.next[t.pieces.idToSlot[prevId]] = -1; - } else { - t.head[rideId] = nextId; - c.prev[t.pieces.idToSlot[nextId]] = -1; - } - t.pieces.despawnSlot(slot); + if (prevId >= 0) c.next[p.idToSlot[prevId]] = -1; + if (nextId >= 0) c.prev[p.idToSlot[nextId]] = -1; + p.despawnSlot(slot); + t.head[rideId] = -1; + t.tail[rideId] = -1; + const focus = prevId >= 0 ? prevId : nextId >= 0 ? nextId : firstPieceOf(world, rideId); + if (focus >= 0) focusSection(world, rideId, focus); relinkRide(world, rideId); return TrackResult.Ok; } +function firstPieceOf(world: World, rideId: number): number { + const p = world.track.pieces; + for (let slot = 0; slot < p.count; slot++) + if (p.cols.rideId[slot] === rideId) return p.slotToId[slot]; + return -1; +} + /** Deletes every piece of a ride (called when the ride itself is demolished). */ export function removeRideTrack(world: World, rideId: number): void { const t = world.track; if (rideId < 0 || rideId >= MAX_TRACK_RIDES) return; - if (t.closed[rideId] === 1) { - t.pieces.cols.prev[t.pieces.idToSlot[t.head[rideId]]] = -1; - t.closed[rideId] = 0; - } - while (t.tail[rideId] >= 0) { - const slot = t.pieces.idToSlot[t.tail[rideId]]; - const prev = t.pieces.cols.prev[slot]; - t.pieces.despawnSlot(slot); - if (prev >= 0 && prev !== t.tail[rideId]) { - t.pieces.cols.next[t.pieces.idToSlot[prev]] = -1; - t.tail[rideId] = prev; - } else { - t.head[rideId] = -1; - t.tail[rideId] = -1; - } - } + const p = t.pieces; + for (let slot = p.count - 1; slot >= 0; slot--) + if (p.cols.rideId[slot] === rideId) p.despawnSlot(slot); + t.head[rideId] = -1; + t.tail[rideId] = -1; relinkRide(world, rideId); } @@ -421,14 +443,12 @@ export function circuitStatus(world: World, rideId: number): CircuitStatus { const t = world.track; const none = { pieces: 0, closed: false, stations: 0, complete: false, length: 0 }; if (rideId < 0 || rideId >= MAX_TRACK_RIDES || t.head[rideId] < 0) return none; - const c = t.pieces.cols; + const p = t.pieces; let stations = 0; - let id = t.head[rideId]; - do { - const slot = t.pieces.idToSlot[id]; - if (PIECES[c.pieceType[slot]].flags & PieceFlag.Station) stations++; - id = c.next[slot]; - } while (id >= 0 && id !== t.head[rideId]); + for (let slot = 0; slot < p.count; slot++) { + if (p.cols.rideId[slot] === rideId && PIECES[p.cols.pieceType[slot]].flags & PieceFlag.Station) + stations++; + } const closed = t.closed[rideId] === 1; return { pieces: t.count[rideId], diff --git a/src/sim/track/track-commands.ts b/src/sim/track/track-commands.ts index 8ddfd96f7..5c52d9f69 100644 --- a/src/sim/track/track-commands.ts +++ b/src/sim/track/track-commands.ts @@ -8,15 +8,23 @@ import { LedgerCategory } from '../economy/ledger'; import { ElementType, Surface } from '../map/tile-map'; import { rideCoversTile } from '../rides/ride-footprint'; import { badTunnelEntry, undergroundTiles } from './clearance'; -import { invalidateRideTest } from '../rides/coaster'; +import { invalidateRideTest, isTrackRide, loadedTrips } from '../rides/coaster'; +import { detachStrandedGates } from '../rides/ride-boarding'; +import { isBusy } from '../rides/ride-commands'; import { enableBlockSections } from '../rides/ride-operations'; import { RIDE_CATALOG } from '../rides/ride-types'; import type { RideType } from '../rides/ride-types'; import { PIECES } from './catalog'; -import { placeTrack, removeTrack, rotateTile, validatePlacement } from './construction'; +import { + attachPoint, + placeTrack, + removeTrack, + rotateTile, + validatePlacement, +} from './construction'; import type { PlaceRequest } from './construction'; import { MAX_TRACK_RIDES } from './track-store'; -import { PieceFlag, PieceMode, Slope, TrackResult, TrackWarning } from './track-types'; +import { PieceFlag, PieceMode, Slope, TrackNotice, TrackResult, TrackWarning } from './track-types'; import type { Direction } from './track-types'; export type TrackCommand = Extract; @@ -124,11 +132,13 @@ function placementWarning( c: Extract, ): TrackWarning | null { const t = world.track; - const tail = t.tail[c.rideId]; - if (tail < 0 || !(PIECES[c.pieceType].flags & PieceFlag.Inverted)) return null; - const cols = t.pieces.cols; - const previous = t.pieces.idToSlot[tail]; - return cols.mode[previous] === PieceMode.ChainLift ? TrackWarning.LiftIntoInversion : null; + if (!(PIECES[c.pieceType].flags & PieceFlag.Inverted)) return null; + const attach = attachPoint(world, { ...c, dir: c.dir as Direction, mode: c.mode as PieceMode }); + if (typeof attach === 'number' || attach.after < 0) return null; + const previous = t.pieces.idToSlot[attach.after]; + return t.pieces.cols.mode[previous] === PieceMode.ChainLift + ? TrackWarning.LiftIntoInversion + : null; } function applyPlace(world: World, c: Extract): TrackResult { @@ -155,18 +165,34 @@ function applyPlace(world: World, c: Extract 0; +} + /** Applies a track command; the outcome is recorded in `world.track.lastResult` and feedback. */ export function applyTrackCommand(world: World, c: TrackCommand): TrackResult { let result: TrackResult; let code: number; - if (c.type === 'placeTrack') { + if (rideInUse(world, c.rideId)) { + world.track.lastResult = TrackResult.RideBusy; + world.track.lastPiece = -1; + result = code = TrackResult.RideBusy; + } else if (c.type === 'placeTrack') { const warning = placementWarning(world, c); result = applyPlace(world, c); code = result === TrackResult.Ok && warning !== null ? warning : result; } else { result = removeTrack(world, c.rideId, c.pieceId); - if (result === TrackResult.Ok) invalidateRideTest(world, c.rideId); - code = result; + if (result === TrackResult.Ok) { + invalidateRideTest(world, c.rideId); + detachStrandedGates(world, world.rides.idToSlot[c.rideId]); + } + code = result === TrackResult.Ok ? TrackNotice.Removed : result; } reportFeedback(world.feedback, FeedbackDomain.Track, code, c.rideId, world.track.lastBlockerName); return result; diff --git a/src/sim/track/track-editing.test.ts b/src/sim/track/track-editing.test.ts new file mode 100644 index 000000000..5cc54206b --- /dev/null +++ b/src/sim/track/track-editing.test.ts @@ -0,0 +1,226 @@ +import { beforeEach, describe, expect, it } from 'vitest'; +import { World } from '../core/world'; +import { hashWorld } from '../core/hash'; +import { deserialize, serialize } from '../../save/save'; +import { pieceByName } from './catalog'; +import { + circuitStatus, + getConstructionCursor, + placeTrack, + removeRideTrack, + removeTrack, + validatePlacement, +} from './construction'; +import type { PlaceRequest } from './construction'; +import { PieceMode, TrackResult } from './track-types'; +import type { Direction } from './track-types'; + +const BASE_Z = 10; + +function newWorld(): World { + const w = new World({ seed: 1, width: 64, height: 64, maxGuests: 16 }); + w.map.heights.fill(2); + return w; +} + +function newRide(w: World): number { + return w.rides.slotToId[w.rides.spawn()]; +} + +/** Every placed piece: the request that built it and the id it was given. */ +interface Built { + id: number; + req: PlaceRequest; +} + +function place(w: World, req: PlaceRequest): Built { + expect(placeTrack(w, req)).toBe(TrackResult.Ok); + return { id: w.track.lastPiece, req }; +} + +/** Appends at the construction cursor (or starts the track at 10,10 heading +x). */ +function append(w: World, ride: number, name: string): Built { + const c = getConstructionCursor(w, ride); + return place(w, { + rideId: ride, + pieceType: pieceByName(name)!.id, + x: c.hasTrack ? c.x : 10, + y: c.hasTrack ? c.y : 10, + z: c.hasTrack ? c.z : BASE_Z, + dir: (c.hasTrack ? c.dir : 0) as Direction, + mode: PieceMode.Normal, + }); +} + +function chain(w: World, ride: number, names: readonly string[]): Built[] { + return names.map((name) => append(w, ride, name)); +} + +const RING = [ + 'station', + 'flat', + 'flat', + 'smallRight', + 'flat', + 'flat', + 'smallRight', + 'flat', + 'flat', + 'flat', + 'smallRight', + 'flat', + 'flat', + 'smallRight', +]; + +describe('editing track from a chosen piece', () => { + let w: World; + let ride: number; + beforeEach(() => { + w = newWorld(); + ride = newRide(w); + }); + + it('removes a middle piece of an unfinished track and keeps every piece after it', () => { + const built = chain(w, ride, ['station', 'flat', 'flat', 'flat', 'flat']); + const end = getConstructionCursor(w, ride); + + expect(removeTrack(w, ride, built[2].id)).toBe(TrackResult.Ok); + + expect(circuitStatus(w, ride).pieces).toBe(4); + for (const piece of [built[0], built[1], built[3], built[4]]) + expect(w.track.pieces.isAlive(piece.id)).toBe(true); + place(w, built[2].req); + expect(circuitStatus(w, ride).pieces).toBe(5); + expect(getConstructionCursor(w, ride)).toMatchObject({ x: end.x, y: end.y, dir: end.dir }); + }); + + it('reopens a closed circuit at a removed middle piece and closes it again when rebuilt', () => { + const built = chain(w, ride, RING); + expect(circuitStatus(w, ride).complete).toBe(true); + + expect(removeTrack(w, ride, built[6].id)).toBe(TrackResult.Ok); + expect(circuitStatus(w, ride)).toMatchObject({ closed: false, complete: false, pieces: 13 }); + expect(getConstructionCursor(w, ride)).toMatchObject({ + x: built[6].req.x, + y: built[6].req.y, + dir: built[6].req.dir, + }); + + place(w, built[6].req); + expect(circuitStatus(w, ride)).toMatchObject({ closed: true, complete: true, pieces: 14 }); + }); + + it('accepts a different shape in a gap but closes the circuit only where it meets the far side', () => { + const built = chain(w, ride, RING); + removeTrack(w, ride, built[9].id); + removeTrack(w, ride, built[4].id); + removeTrack(w, ride, built[5].id); + const rise = place(w, { ...built[4].req, pieceType: pieceByName('flatToUp25')!.id }); + const level = place(w, { + ...built[5].req, + pieceType: pieceByName('up25ToFlat')!.id, + z: getConstructionCursor(w, ride).z, + }); + place(w, built[9].req); + expect(circuitStatus(w, ride)).toMatchObject({ closed: false, pieces: 14 }); + + removeTrack(w, ride, level.id); + removeTrack(w, ride, rise.id); + place(w, built[4].req); + expect(circuitStatus(w, ride).closed).toBe(false); + place(w, built[5].req); + expect(circuitStatus(w, ride)).toMatchObject({ closed: true, complete: true, pieces: 14 }); + }); + + it('joins separate sections when the gaps between them are filled in any order', () => { + const built = chain(w, ride, ['station', 'flat', 'flat', 'flat', 'flat', 'flat', 'flat']); + const end = getConstructionCursor(w, ride); + removeTrack(w, ride, built[2].id); + removeTrack(w, ride, built[5].id); + expect(circuitStatus(w, ride).pieces).toBe(5); + + place(w, built[2].req); + place(w, built[5].req); + + expect(circuitStatus(w, ride).pieces).toBe(7); + expect(getConstructionCursor(w, ride)).toMatchObject({ x: end.x, y: end.y }); + expect(removeTrack(w, ride, -1)).toBe(TrackResult.Ok); + expect(w.track.pieces.isAlive(built[6].id)).toBe(false); + }); + + it('builds backward onto the start of the section after a gap', () => { + const built = chain(w, ride, ['station', 'flat', 'flat', 'flat', 'flat', 'flat']); + removeTrack(w, ride, built[2].id); + removeTrack(w, ride, built[3].id); + + place(w, built[3].req); + expect(circuitStatus(w, ride).pieces).toBe(5); + place(w, built[2].req); + expect(circuitStatus(w, ride).pieces).toBe(6); + expect(removeTrack(w, ride, built[4].id)).toBe(TrackResult.Ok); + expect(validatePlacement(w, built[4].req)).toBe(TrackResult.Ok); + }); + + it('only accepts new pieces that meet an open end', () => { + const built = chain(w, ride, ['station', 'flat', 'flat', 'flat']); + removeTrack(w, ride, built[1].id); + expect(validatePlacement(w, { ...built[1].req, y: 30 })).toBe(TrackResult.NotConnected); + expect(validatePlacement(w, { ...built[1].req, dir: 1 })).toBe(TrackResult.NotConnected); + expect(validatePlacement(w, built[1].req)).toBe(TrackResult.Ok); + }); + + it('keeps demolishing backward from the gap with the default end removal', () => { + const built = chain(w, ride, ['station', 'flat', 'flat', 'flat', 'flat']); + removeTrack(w, ride, built[3].id); + expect(removeTrack(w, ride, -1)).toBe(TrackResult.Ok); + expect(w.track.pieces.isAlive(built[2].id)).toBe(false); + expect(w.track.pieces.isAlive(built[4].id)).toBe(true); + expect(getConstructionCursor(w, ride)).toMatchObject({ x: built[2].req.x, y: built[2].req.y }); + }); + + it('removes the first and the last piece of a section', () => { + const built = chain(w, ride, ['station', 'flat', 'flat', 'flat', 'flat']); + removeTrack(w, ride, built[2].id); + expect(removeTrack(w, ride, built[3].id)).toBe(TrackResult.Ok); + expect(removeTrack(w, ride, built[4].id)).toBe(TrackResult.Ok); + expect(removeTrack(w, ride, built[0].id)).toBe(TrackResult.Ok); + expect(circuitStatus(w, ride).pieces).toBe(1); + expect(removeTrack(w, ride, built[1].id)).toBe(TrackResult.Ok); + expect(circuitStatus(w, ride).pieces).toBe(0); + expect(getConstructionCursor(w, ride).hasTrack).toBe(false); + }); + + it('refuses a piece that was already removed', () => { + const built = chain(w, ride, ['station', 'flat', 'flat']); + removeTrack(w, ride, built[1].id); + expect(removeTrack(w, ride, built[1].id)).toBe(TrackResult.NoSuchPiece); + expect(circuitStatus(w, ride).pieces).toBe(2); + }); + + it('counts the stations of every section', () => { + const built = chain(w, ride, ['flat', 'flat', 'station']); + expect(removeTrack(w, ride, built[1].id)).toBe(TrackResult.Ok); + expect(circuitStatus(w, ride)).toMatchObject({ pieces: 2, stations: 1 }); + }); + + it('clears every section when the ride is demolished', () => { + const built = chain(w, ride, ['station', 'flat', 'flat', 'flat', 'flat']); + expect(removeTrack(w, ride, built[1].id)).toBe(TrackResult.Ok); + expect(removeTrack(w, ride, built[3].id)).toBe(TrackResult.Ok); + removeRideTrack(w, ride); + expect(w.track.pieces.count).toBe(0); + expect(circuitStatus(w, ride).pieces).toBe(0); + }); + + it('saves and restores a track split into sections', () => { + const built = chain(w, ride, RING); + removeTrack(w, ride, built[3].id); + removeTrack(w, ride, built[9].id); + const copy = deserialize(serialize(w)); + expect(hashWorld(copy)).toBe(hashWorld(w)); + expect(placeTrack(copy, built[3].req)).toBe(TrackResult.Ok); + expect(placeTrack(copy, built[9].req)).toBe(TrackResult.Ok); + expect(circuitStatus(copy, ride).complete).toBe(true); + }); +}); diff --git a/src/sim/track/track-types.ts b/src/sim/track/track-types.ts index acd37b288..53d3d4dd7 100644 --- a/src/sim/track/track-types.ts +++ b/src/sim/track/track-types.ts @@ -53,7 +53,6 @@ export const enum TrackResult { BadMode = 8, TooManyPieces = 9, CircuitClosed = 10, - NotAtEnd = 11, StoreFull = 12, NotOwned = 13, InsufficientFunds = 14, @@ -65,6 +64,8 @@ export const enum TrackResult { TunnelEntry = 18, /** The piece would rise above the scenario's construction height cap. */ HeightLimit = 19, + /** The ride is open, testing, or still has a train out or riders aboard. */ + RideBusy = 20, } /** @@ -76,6 +77,12 @@ export const enum TrackWarning { LiftIntoInversion = 100, } +/** Successful track edits that are reported with their own wording, in the same code range. */ +export const enum TrackNotice { + /** A piece was demolished. */ + Removed = 101, +} + /** The horizontal shape of a piece in the vocabulary of the build controls. */ export type PieceShape = | 'station' diff --git a/src/ui/coaster-panel.ts b/src/ui/coaster-panel.ts index 57a1915dc..bade80f72 100644 --- a/src/ui/coaster-panel.ts +++ b/src/ui/coaster-panel.ts @@ -4,7 +4,6 @@ import { MAX_TRACK_LEVEL } from '../sim/track/track-store'; import { FeedbackDomain } from '../sim/core/feedback'; import { RIDE_CATALOG, RideType } from '../sim/rides/ride-types'; import type { RideTypeDef } from '../sim/rides/ride-types'; -import type { RideState } from '../sim/rides/ride-store'; import { RidePhase } from '../sim/rides/ride-store'; import { Bank, PieceMode, Slope } from '../sim/track/track-types'; import { TrackResult } from '../sim/track/track-types'; @@ -27,6 +26,18 @@ import { resolvePiece, } from './track-tool'; import type { PieceChoice, Placement, TurnKind } from './track-tool'; +import { PIECES } from '../sim/track/catalog'; +import { pieceExit } from '../sim/track/construction'; +import { RideState } from '../sim/rides/ride-store'; +import { + buildPointAt, + neighbourPiece, + openEnds, + resolveBuild, + sectionPosition, + snapshotPiece, +} from './track-selection'; +import type { BuildEnd, BuildPoint, SnapshotPiece } from './track-selection'; export interface CoasterPanelActions { command(command: Command): void; @@ -50,6 +61,29 @@ export interface TrackGhost { type BuildMode = 'track' | 'entrance' | 'exit'; +/** The piece picked in the construction window; `signature` catches a reused id. */ +interface Selection { + rideId: number; + pieceId: number; + signature: string; +} + +function signatureOf(piece: SnapshotPiece): string { + return `${piece.pieceType}:${piece.x}:${piece.y}:${piece.z}:${piece.dir}`; +} + +/** Short player-facing name of a placed piece: its shape, slope and drive mode. */ +export function pieceLabel(piece: SnapshotPiece): string { + const def = PIECES[piece.pieceType]; + const shape = TURN_LABELS.find(([turn]) => turn === def?.shape)?.[1] ?? def?.name ?? 'Track'; + const slope = + def && (def.entrySlope !== Slope.Flat || def.exitSlope !== Slope.Flat) + ? SLOPE_LABELS.find(([value]) => value === (def.exitSlope || def.entrySlope))?.[1] + : undefined; + const mode = piece.mode !== PieceMode.Normal ? MODE_LABELS[piece.mode as PieceMode] : undefined; + return [shape, slope, mode].filter(Boolean).join(' · '); +} + /** The parts of the map data the panel reads. */ export interface PanelMap { width: number; @@ -140,6 +174,12 @@ export class CoasterPanel { private readonly costLine: HTMLElement; private readonly rideInfo: HTMLElement; private readonly feedbackLine: HTMLElement; + private readonly selectionLine: HTMLElement; + private readonly previousButton: HTMLButtonElement; + private readonly nextButton: HTMLButtonElement; + private readonly trackEndButton: HTMLButtonElement; + private readonly buildBeforeButton: HTMLButtonElement; + private readonly removeButton: HTMLButtonElement; private tool: ToolMode = 'select'; private buildMode: BuildMode = 'track'; @@ -155,6 +195,12 @@ export class CoasterPanel { private lastFeedbackSeq = 0; private awaitingCreate = false; private rideCount = 0; + private selection: Selection | null = null; + private buildEnd: BuildEnd = 'after'; + /** A placement sent from the selection: select the new piece once it appears beside `from`. */ + private pendingFollow: { from: number; end: BuildEnd } | null = null; + /** A removal of the selected piece: select a neighbour once it is gone. */ + private pendingRemoval: { pieceId: number; prev: number; next: number } | null = null; constructor( private readonly windows: WindowManager, @@ -216,7 +262,19 @@ export class CoasterPanel { this.heightLine.className = 'coaster-height'; this.placeButton = this.button('Build piece', () => this.placeAtCursor()); this.placeButton.classList.add('primary'); - const removeButton = this.button('Demolish last piece', () => this.removeLast()); + this.removeButton = this.button('Demolish last piece', () => this.removeLast()); + this.selectionLine = el('div', 'coaster-selection-line'); + this.previousButton = this.button('Previous piece', () => this.step('previous')); + this.nextButton = this.button('Next piece', () => this.step('next')); + this.trackEndButton = this.button('Track end', () => this.clearSelection()); + this.trackEndButton.title = 'Build and demolish at the end of the track again'; + this.buildBeforeButton = this.button('Build before this piece', () => { + this.buildEnd = this.buildEnd === 'before' ? 'after' : 'before'; + }); + const selectionRow = el('div', 'coaster-row'); + selectionRow.append(this.previousButton, this.nextButton, this.trackEndButton); + const selection = el('div', 'coaster-selection'); + selection.append(this.selectionLine, selectionRow, this.buildBeforeButton); this.costLine = document.createElement('div'); this.costLine.className = 'coaster-cost'; @@ -246,8 +304,9 @@ export class CoasterPanel { this.trackControls.className = 'coaster-section'; const buildRow = document.createElement('div'); buildRow.className = 'coaster-row'; - buildRow.append(this.placeButton, removeButton); + buildRow.append(this.placeButton, this.removeButton); this.trackControls.append( + selection, turns, this.specialSelect, slopes, @@ -310,9 +369,144 @@ export class CoasterPanel { /** Makes a track ride the one the construction controls act on. */ setActiveRide(rideId: number): void { + if (rideId !== this.activeRideId) this.clearSelection(); this.activeRideId = rideId; } + /** + * Selects a placed piece to edit from. Selecting never changes the track: it only picks where + * Build piece and Demolish act. Returns the status line. + */ + selectPiece(rideId: number, pieceId: number): string { + const snapshot = this.actions.snapshot(); + if (snapshot) this.refreshRides(snapshot); + const piece = snapshot ? snapshotPiece(snapshot, pieceId) : null; + if (!snapshot || !piece || piece.rideId !== rideId) return 'That track piece no longer exists.'; + if (!this.rides.some((ride) => ride.id === rideId)) + return 'Only ride track can be edited here.'; + this.activeRideId = rideId; + this.rideSelect.value = String(rideId); + this.buildMode = 'track'; + this.focusPiece(piece); + const position = sectionPosition(snapshot, pieceId); + return `Selected ${pieceLabel(piece)}, piece ${position.index + 1} of ${position.count}.`; + } + + /** True while the construction controls build track (not an entrance or exit). */ + buildsTrack(): boolean { + return this.buildMode === 'track'; + } + + /** The selected piece, for highlighting, while the construction window is open. */ + selectedPiece(): { rideId: number; pieceId: number } | null { + return this.window && this.tool === 'track' && this.selection + ? { rideId: this.selection.rideId, pieceId: this.selection.pieceId } + : null; + } + + /** Goes back to building and demolishing at the end of the track. */ + clearSelection(): void { + this.selection = null; + this.buildEnd = 'after'; + this.pendingFollow = null; + this.pendingRemoval = null; + } + + private focusPiece(piece: SnapshotPiece): void { + this.selection = { rideId: piece.rideId, pieceId: piece.id, signature: signatureOf(piece) }; + this.pendingFollow = null; + this.pendingRemoval = null; + if (!openEnds(piece).includes(this.buildEnd)) this.buildEnd = 'after'; + } + + private selected(): SnapshotPiece | null { + const snapshot = this.actions.snapshot(); + if (!this.selection || !snapshot) return null; + const piece = snapshotPiece(snapshot, this.selection.pieceId); + return piece && piece.rideId === this.selection.rideId ? piece : null; + } + + /** Moves the selection one piece along the track; with nothing selected, picks the last piece. */ + private step(direction: 'previous' | 'next'): void { + const snapshot = this.actions.snapshot(); + const ride = this.activeRide(); + if (!snapshot || !ride) return; + const current = this.selected(); + const id = current + ? neighbourPiece(snapshot, current.id, direction) + : direction === 'previous' + ? this.lastPieceId(ride) + : -1; + const piece = id >= 0 ? snapshotPiece(snapshot, id) : null; + if (piece) this.actions.status(this.selectPiece(ride.id, piece.id)); + } + + /** The piece whose exit is the construction cursor: the end of the section being built. */ + private lastPieceId(ride: RideSummary): number { + const snapshot = this.actions.snapshot(); + const info = this.infoAt(ride); + if (!snapshot || !decodeCursor(info[RideInfo.Cursor]).hasTrack) return -1; + for (let row = 0; row < snapshot.tracks.count; row++) { + const piece = snapshotPiece(snapshot, snapshot.trackLinks[row * 3]); + if (!piece || piece.rideId !== ride.id) continue; + const exit = pieceExit(piece.pieceType, piece.x, piece.y, piece.z, piece.dir); + if ( + exit.x === info[RideInfo.CursorX] && + exit.y === info[RideInfo.CursorY] && + exit.z === info[RideInfo.CursorZ] + ) + return piece.id; + } + return -1; + } + + /** Where the selection builds: its chosen open end, or null when that end is already joined. */ + private selectionBuildPoint(): BuildPoint | null { + const piece = this.selected(); + if (!piece || !openEnds(piece).includes(this.buildEnd)) return null; + return buildPointAt(piece, this.buildEnd); + } + + /** Follows a placement or removal made from the selection, and drops a stale selection. */ + private reconcileSelection(snapshot: Snapshot): void { + const selection = this.selection; + if (!selection) return; + const piece = snapshotPiece(snapshot, selection.pieceId); + const alive = + piece && piece.rideId === selection.rideId && signatureOf(piece) === selection.signature; + const removal = this.pendingRemoval; + if (removal && !alive) { + const neighbour = [removal.prev, removal.next] + .map((id) => (id >= 0 ? snapshotPiece(snapshot, id) : null)) + .find((p) => p && p.rideId === selection.rideId); + if (neighbour) this.focusPiece(neighbour); + else this.clearSelection(); + return; + } + const follow = this.pendingFollow; + if (follow && piece && alive) { + const id = follow.end === 'after' ? piece.next : piece.prev; + const added = id >= 0 ? snapshotPiece(snapshot, id) : null; + if (added) { + const ride = this.activeRide(); + if (ride && this.infoAt(ride)[RideInfo.Flags] & RideFlag.CircuitClosed) { + this.clearSelection(); + return; + } + const end = follow.end; + this.focusPiece(added); + if (openEnds(added).includes(end)) this.buildEnd = end; + return; + } + } + if (!alive) { + this.clearSelection(); + this.feedbackLine.textContent = + 'The selected piece is gone; building from the end of the track.'; + this.feedbackLine.dataset.ok = 'false'; + } + } + setHover(tile: [number, number] | null): void { this.hover = tile; } @@ -362,9 +556,13 @@ export class CoasterPanel { if (ride && this.buildMode === 'track') this.place(ride); } + /** Demolishes the selected piece, or the last piece of the track when nothing is selected. */ removeLast(): void { const ride = this.activeRide(); - if (ride) this.actions.command({ type: 'removeTrack', rideId: ride.id, pieceId: -1 }); + if (!ride) return; + const piece = this.selected(); + if (piece) this.pendingRemoval = { pieceId: piece.id, prev: piece.prev, next: piece.next }; + this.actions.command({ type: 'removeTrack', rideId: ride.id, pieceId: piece ? piece.id : -1 }); } /** The piece the controls resolve to for the active ride, with its target placement. */ @@ -374,13 +572,22 @@ export class CoasterPanel { const map = this.actions.map(); if (!ride || !snap || !map || this.tool !== 'track' || this.buildMode !== 'track') return null; const info = this.infoAt(ride); - if (info[RideInfo.Flags] & RideFlag.CircuitClosed) return null; - const cursor = decodeCursor(info[RideInfo.Cursor]); - const piece = resolvePiece(cursor, this.choice, ride.type); - if (!piece) return null; let placement: Placement; let level: number; - if (cursor.hasTrack) { + let piece: TrackPieceDef | undefined; + const cursor = decodeCursor(info[RideInfo.Cursor]); + if (this.selection) { + const point = this.selectionBuildPoint(); + const build = point && resolveBuild(point, this.choice, ride.type); + if (!build) return null; + piece = build.piece; + placement = { x: build.placement.x, y: build.placement.y, dir: build.placement.dir }; + level = build.placement.z / TRACK_STEPS_PER_LEVEL; + } else if (info[RideInfo.Flags] & RideFlag.CircuitClosed) { + return null; + } else if (!(piece = resolvePiece(cursor, this.choice, ride.type))) { + return null; + } else if (cursor.hasTrack) { placement = { x: info[RideInfo.CursorX], y: info[RideInfo.CursorY], dir: cursor.dir }; level = info[RideInfo.CursorZ] / TRACK_STEPS_PER_LEVEL; } else if (this.hover) { @@ -392,7 +599,7 @@ export class CoasterPanel { const status = previewStatus( map, snap.buildable, - piece, + piece!, placement, snap.park.cash, level, @@ -400,7 +607,7 @@ export class CoasterPanel { ride.type, snap.scenario.restrictions.maxConstructionHeight, ); - return { rideType: ride.type, piece, placement, level, status }; + return { rideType: ride.type, piece: piece!, placement, level, status }; } update(): void { @@ -408,6 +615,7 @@ export class CoasterPanel { if (!snapshot) return; this.refreshRides(snapshot); this.consumeFeedback(snapshot); + this.reconcileSelection(snapshot); if (!this.window) return; const ride = this.activeRide(); this.refreshControls(ride, snapshot); @@ -429,6 +637,7 @@ export class CoasterPanel { } private place(ride: RideSummary): string { + if (this.selection) return this.placeAtSelection(ride); const map = this.actions.map(); const info = this.infoAt(ride); const cursor = decodeCursor(info[RideInfo.Cursor]); @@ -464,6 +673,24 @@ export class CoasterPanel { return `Placing ${piece.name} (${dollars(piece.cost)})…`; } + private placeAtSelection(ride: RideSummary): string { + const piece = this.selected(); + const point = this.selectionBuildPoint(); + if (!piece || !point) + return 'The selected piece is joined on both sides. Demolish it, or pick an open end with Previous piece or Next piece.'; + const build = resolveBuild(point, this.choice, ride.type); + if (!build) return 'No track piece matches those controls.'; + this.pendingFollow = { from: piece.id, end: point.end }; + this.actions.command({ + type: 'placeTrack', + rideId: ride.id, + pieceType: build.piece.id, + ...build.placement, + mode: this.mode, + }); + return `Placing ${build.piece.name} (${dollars(build.piece.cost)})…`; + } + private setStatus(status: 'open' | 'close' | 'test'): void { const ride = this.activeRide(); if (ride) this.actions.command({ type: 'setRideStatus', rideId: ride.id, status }); @@ -524,7 +751,11 @@ export class CoasterPanel { this.feedbackLine.textContent = line.text; this.feedbackLine.dataset.ok = String(line.ok); this.actions.status(line.text); - if (!line.ok) this.awaitingCreate = false; + if (!line.ok) { + this.awaitingCreate = false; + this.pendingFollow = null; + this.pendingRemoval = null; + } } private refreshControls(ride: RideSummary | undefined, snapshot: Snapshot): void { @@ -539,6 +770,7 @@ export class CoasterPanel { button.setAttribute('aria-pressed', String(bank === this.choice.bank)); this.specialSelect.value = MAIN_TURNS.includes(this.choice.turn) ? '' : this.choice.turn; this.directionButton.textContent = `Start direction: ${['+x', '+y', '-x', '-y'][this.startDir]}`; + this.refreshSelectionControls(ride, snapshot); if (!ride) { this.costLine.textContent = ''; this.placeButton.disabled = true; @@ -576,11 +808,17 @@ export class CoasterPanel { } this.startHeightLabel.textContent = this.startRaise === 0 ? 'Start on the ground' : `Start ${this.startRaise} above ground`; - this.heightLine.textContent = cursor.hasTrack - ? `Track end at height ${info[RideInfo.CursorZ] / TRACK_STEPS_PER_LEVEL}` - : ''; - const piece = resolvePiece(cursor, this.choice, ride.type); - this.placeButton.disabled = !piece || closed; + const point = this.selection ? this.selectionBuildPoint() : null; + const build = point ? resolveBuild(point, this.choice, ride.type) : undefined; + this.heightLine.textContent = point + ? `Building ${point.end} the selected piece at height ${point.z / TRACK_STEPS_PER_LEVEL}` + : this.selection + ? '' + : cursor.hasTrack + ? `Track end at height ${info[RideInfo.CursorZ] / TRACK_STEPS_PER_LEVEL}` + : ''; + const piece = this.selection ? build?.piece : resolvePiece(cursor, this.choice, ride.type); + this.placeButton.disabled = !piece || (closed && !this.selection); const modes = piece ? allowedModes(piece, ride.type) : [PieceMode.Normal]; const current = this.modeSelect.dataset.options; if (current !== modes.join(',')) { @@ -591,17 +829,50 @@ export class CoasterPanel { } if (!modes.includes(this.mode)) this.mode = PieceMode.Normal; this.modeSelect.value = String(this.mode); - this.costLine.textContent = closed - ? !hasEntrance - ? 'Circuit complete. Place an entrance next to the station.' - : !hasExit - ? 'Place an exit next to the station.' - : !tested - ? 'Test the ride before opening it.' - : 'Circuit complete. Remove a piece to change the layout.' - : piece - ? `${circuitLabel(flags)}. ${piece.name}: ${dollars(piece.cost)} of ${dollars(snapshot.park.cash)} cash` - : 'No piece fits those controls here.'; + const busy = + info[RideInfo.State] === RideState.Open || + info[RideInfo.State] === RideState.Testing || + info[RideInfo.Phase] === RidePhase.Loading || + info[RideInfo.Phase] === RidePhase.Running || + info[RideInfo.Phase] === RidePhase.Unloading; + const selected = this.selected(); + this.costLine.textContent = busy + ? 'Close the ride and wait for its train to return before changing the track.' + : selected && !point + ? openEnds(selected).length === 0 + ? 'This piece is joined on both sides: demolish it to rebuild this section.' + : 'Press Build before this piece to extend the track backward from here.' + : closed && !this.selection + ? !hasEntrance + ? 'Circuit complete. Place an entrance next to the station.' + : !hasExit + ? 'Place an exit next to the station.' + : !tested + ? 'Test the ride before opening it.' + : 'Circuit complete. Remove a piece to change the layout.' + : piece + ? `${circuitLabel(flags)}. ${piece.name}: ${dollars(piece.cost)} of ${dollars(snapshot.park.cash)} cash` + : 'No piece fits those controls here.'; + } + + private refreshSelectionControls(ride: RideSummary | undefined, snapshot: Snapshot): void { + const piece = this.selected(); + const hasTrack = + ride !== undefined && decodeCursor(this.infoAt(ride)[RideInfo.Cursor]).hasTrack; + if (piece) { + const position = sectionPosition(snapshot, piece.id); + this.selectionLine.textContent = `Selected piece ${position.index + 1} of ${position.count} · ${pieceLabel(piece)}`; + } else { + this.selectionLine.textContent = hasTrack + ? 'Building from the end of the track. Click a piece of track to edit from it.' + : 'Building from the end of the track.'; + } + this.previousButton.disabled = piece ? piece.prev < 0 : !hasTrack; + this.nextButton.disabled = !piece || piece.next < 0; + this.trackEndButton.disabled = !piece; + this.buildBeforeButton.hidden = !piece || !openEnds(piece).includes('before'); + this.buildBeforeButton.setAttribute('aria-pressed', String(this.buildEnd === 'before')); + this.removeButton.textContent = piece ? 'Demolish selected piece' : 'Demolish last piece'; } private describeRide(ride: RideSummary): string { diff --git a/src/ui/game-ui.ts b/src/ui/game-ui.ts index f44e364c9..2a1267456 100644 --- a/src/ui/game-ui.ts +++ b/src/ui/game-ui.ts @@ -136,6 +136,8 @@ export class GameUI { private tool: ToolMode = 'select'; private alternate = false; private patrolStaffId: number | null = null; + /** Track piece the player clicked to open each ride window, by ride id. */ + private readonly clickedPieces = new Map(); private selectedGuest: GuestSelection | null = null; /** The speed the player chose. The sim runs at `speed`, which building can cap lower. */ private requestedSpeed: GameSpeed = 1; @@ -166,7 +168,8 @@ export class GameUI { alternate: () => this.alternate, selectedGuest: () => this.selectedGuest, series: this.series, - openRide: (id) => this.openRide(id), + openRide: (id, pieceId) => this.openRide(id, pieceId), + clickedTrackPiece: (id) => this.clickedPieces.get(id), openGuest: (id) => this.openWindow(`guest-${id}`), openWorker: (id) => this.openWindow(`worker-${id}`), openWindow: (id) => this.openWindow(id), @@ -445,7 +448,9 @@ export class GameUI { } } - openRide(rideId: number): void { + openRide(rideId: number, pieceId?: number): void { + if (pieceId === undefined) this.clickedPieces.delete(rideId); + else this.clickedPieces.set(rideId, pieceId); const id = `ride-${rideId}`; if (this.windows.get(id)) { this.windows.focus(this.windows.get(id)!); diff --git a/src/ui/track-preview.ts b/src/ui/track-preview.ts index 3ced6a04e..30bfc285a 100644 --- a/src/ui/track-preview.ts +++ b/src/ui/track-preview.ts @@ -121,6 +121,8 @@ export class TrackPreviewOverlay { private readonly corner = new Float64Array(2); private atlas: CanvasAtlas | null = null; private hasContent = false; + /** Viewport corners of each footprint tile of the drawn track preview, four (x, y) pairs each. */ + private ghostTiles: number[][] = []; constructor(parent: HTMLElement) { this.canvas = document.createElement('canvas'); @@ -157,6 +159,7 @@ export class TrackPreviewOverlay { this.hasContent = active; canvas.hidden = !active; if (tileGhost) this.drawTileGhost(tileGhost, map, camera, viewport); + this.ghostTiles = []; if (!ghost) return; const fill = ghost.status === TrackResult.Ok ? VALID_FILL : INVALID_FILL; @@ -171,10 +174,14 @@ export class TrackPreviewOverlay { ctx.strokeStyle = ENTRY_MARK; ctx.lineWidth = 1.5; for (const [tx, ty] of tiles) { + const quad: number[] = []; + this.ghostTiles.push(quad); ctx.beginPath(); - this.corners(tx, ty, z, map, camera, viewport, (x, y, first) => - first ? ctx.moveTo(x, y) : ctx.lineTo(x, y), - ); + this.corners(tx, ty, z, map, camera, viewport, (x, y, first) => { + quad.push(x, y); + if (first) ctx.moveTo(x, y); + else ctx.lineTo(x, y); + }); ctx.closePath(); ctx.fill(); ctx.stroke(); @@ -225,6 +232,18 @@ export class TrackPreviewOverlay { ); } + /** Whether a viewport point lies on a tile of the track preview drawn last. */ + hits(x: number, y: number): boolean { + return this.ghostTiles.some((quad) => { + let inside = false; + for (let i = 0, j = quad.length - 2; i < quad.length; j = i, i += 2) { + const [xi, yi, xj, yj] = [quad[i], quad[i + 1], quad[j], quad[j + 1]]; + if (yi > y !== yj > y && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi) inside = !inside; + } + return inside; + }); + } + dispose(): void { this.canvas.remove(); this.atlas = null; diff --git a/src/ui/track-selection.test.ts b/src/ui/track-selection.test.ts new file mode 100644 index 000000000..bf3578986 --- /dev/null +++ b/src/ui/track-selection.test.ts @@ -0,0 +1,174 @@ +import { describe, expect, it } from 'vitest'; +import { World } from '../sim/core/world'; +import { pieceByName } from '../sim/track/catalog'; +import { + getConstructionCursor, + placeTrack, + removeTrack, + validatePlacement, +} from '../sim/track/construction'; +import type { PlaceRequest } from '../sim/track/construction'; +import { Bank, PieceMode, Slope, TrackResult } from '../sim/track/track-types'; +import type { Direction } from '../sim/track/track-types'; +import { RideType } from '../sim/rides/ride-types'; +import { createSnapshot, writeSnapshot } from '../worker/snapshot'; +import type { Snapshot } from '../worker/snapshot'; +import { + buildPointAt, + neighbourPiece, + openEnds, + resolveBuild, + sectionPosition, + snapshotPiece, +} from './track-selection'; + +function world(): { w: World; ride: number } { + const w = new World({ seed: 1, width: 64, height: 64, maxGuests: 16 }); + w.map.heights.fill(2); + return { w, ride: w.rides.slotToId[w.rides.spawn()] }; +} + +const placedIds = new Map(); + +/** Ids of the pieces `chain` placed in this world, in build order. */ +function ids(w: World): number[] { + return placedIds.get(w) ?? []; +} + +function chain(w: World, ride: number, names: readonly string[]): PlaceRequest[] { + const out: PlaceRequest[] = []; + if (!placedIds.has(w)) placedIds.set(w, []); + for (const name of names) { + const c = getConstructionCursor(w, ride); + const req: PlaceRequest = { + rideId: ride, + pieceType: pieceByName(name)!.id, + x: c.hasTrack ? c.x : 10, + y: c.hasTrack ? c.y : 10, + z: c.hasTrack ? c.z : 10, + dir: (c.hasTrack ? c.dir : 0) as Direction, + mode: PieceMode.Normal, + }; + expect(placeTrack(w, req)).toBe(TrackResult.Ok); + placedIds.get(w)!.push(w.track.lastPiece); + out.push(req); + } + return out; +} + +function snap(w: World): Snapshot { + const snapshot = createSnapshot({ guests: 16, staff: 0, vehicles: 0, litter: 0 }); + writeSnapshot(w, snapshot); + return snapshot; +} + +describe('construction from a selected piece', () => { + it('describes a published piece by its id with its position and neighbours', () => { + const { w, ride } = world(); + const reqs = chain(w, ride, ['station', 'smallRight', 'flat']); + const [first, turn, last] = ids(w); + const piece = snapshotPiece(snap(w), turn); + expect(piece).toMatchObject({ + id: turn, + rideId: ride, + pieceType: reqs[1].pieceType, + x: reqs[1].x, + y: reqs[1].y, + z: reqs[1].z, + dir: reqs[1].dir, + prev: first, + next: last, + }); + expect(snapshotPiece(snap(w), 9999)).toBeNull(); + }); + + it('steps to the previous and next piece, stopping at the ends of unfinished track', () => { + const { w, ride } = world(); + chain(w, ride, ['station', 'flat', 'flat']); + const [a, b, c] = ids(w); + const s = snap(w); + expect(neighbourPiece(s, b, 'previous')).toBe(a); + expect(neighbourPiece(s, b, 'next')).toBe(c); + expect(neighbourPiece(s, a, 'previous')).toBe(-1); + expect(neighbourPiece(s, c, 'next')).toBe(-1); + expect(sectionPosition(s, b)).toEqual({ index: 1, count: 3, ring: false }); + }); + + it('wraps around a closed circuit', () => { + const { w, ride } = world(); + chain(w, ride, [ + 'station', + 'flat', + 'smallRight', + 'flat', + 'smallRight', + 'flat', + 'flat', + 'smallRight', + 'flat', + 'smallRight', + ]); + const order = ids(w); + const s = snap(w); + expect(neighbourPiece(s, order[0], 'previous')).toBe(order[order.length - 1]); + expect(neighbourPiece(s, order[order.length - 1], 'next')).toBe(order[0]); + expect(sectionPosition(s, order[3])).toEqual({ index: 3, count: order.length, ring: true }); + expect(openEnds(snapshotPiece(s, order[3])!)).toEqual([]); + }); + + it('offers the open ends of the pieces either side of a gap', () => { + const { w, ride } = world(); + chain(w, ride, ['station', 'flat', 'flat', 'flat', 'flat']); + const [, before, gap, after, last] = ids(w); + removeTrack(w, ride, gap); + const s = snap(w); + expect(openEnds(snapshotPiece(s, before)!)).toEqual(['after']); + expect(openEnds(snapshotPiece(s, after)!)).toEqual(['before']); + expect(openEnds(snapshotPiece(s, last)!)).toEqual(['after']); + expect(sectionPosition(s, after)).toEqual({ index: 0, count: 2, ring: false }); + }); + + it.each(['flat', 'smallRight', 'smallLeft', 'flatToUp25', 'down25ToFlat', 'mediumRight'])( + 'resolves the piece the sim accepts when building a %s back onto the start of a section', + (name) => { + const { w, ride } = world(); + const before = name === 'down25ToFlat' ? ['flatToDown25', 'down25'] : []; + const after = name === 'flatToUp25' ? ['up25ToFlat', 'flat'] : ['flat', 'flat']; + const reqs = chain(w, ride, ['station', 'flat', ...before, name, ...after]); + const order = ids(w); + const target = 2 + before.length; + removeTrack(w, ride, order[target]); + removeTrack(w, ride, order[target - 1]); + const def = pieceByName(name)!; + const s = snap(w); + const head = snapshotPiece(s, order[target + 1])!; + const build = resolveBuild( + buildPointAt(head, 'before'), + { turn: def.shape, slope: def.entrySlope, bank: def.entryBank }, + RideType.WoodenCoaster, + ); + expect(build?.piece.id).toBe(def.id); + const req: PlaceRequest = { + ...reqs[target], + ...build!.placement, + dir: build!.placement.dir as Direction, + pieceType: build!.piece.id, + }; + expect(req).toEqual(reqs[target]); + expect(validatePlacement(w, req)).toBe(TrackResult.Ok); + }, + ); + + it('resolves the next piece forward from the end of a section', () => { + const { w, ride } = world(); + const reqs = chain(w, ride, ['station', 'flat', 'smallRight', 'flat']); + const order = ids(w); + removeTrack(w, ride, order[2]); + const build = resolveBuild( + buildPointAt(snapshotPiece(snap(w), order[1])!, 'after'), + { turn: 'smallRight', slope: Slope.Flat, bank: Bank.None }, + RideType.WoodenCoaster, + ); + expect({ ...reqs[2], ...build!.placement, pieceType: build!.piece.id }).toEqual(reqs[2]); + }); +}); diff --git a/src/ui/track-selection.ts b/src/ui/track-selection.ts new file mode 100644 index 000000000..acd2a993a --- /dev/null +++ b/src/ui/track-selection.ts @@ -0,0 +1,153 @@ +import { TILE_UNITS, TRACK_Z_STEP } from '../sim/core/constants'; +import { PIECES } from '../sim/track/catalog'; +import { pieceExit, rotateTile } from '../sim/track/construction'; +import type { Bank, Slope, TrackPieceDef } from '../sim/track/track-types'; +import type { RideType } from '../sim/rides/ride-types'; +import { SNAPSHOT_STRIDE, TRACK_LINK_STRIDE } from '../worker/snapshot'; +import type { Snapshot } from '../worker/snapshot'; +import { resolvePiece, resolvePieceBefore } from './track-tool'; +import type { PieceChoice } from './track-tool'; + +/** A placed track piece as published in a snapshot. Heights are in track steps. */ +export interface SnapshotPiece { + id: number; + rideId: number; + pieceType: number; + x: number; + y: number; + z: number; + dir: number; + mode: number; + /** Ids of the pieces before and after it (-1 at an open end). */ + prev: number; + next: number; +} + +/** Which side of a selected piece new track is built on. */ +export type BuildEnd = 'after' | 'before'; + +/** An open end of a section: where a new piece starts ('after') or ends ('before'). */ +export interface BuildPoint { + end: BuildEnd; + x: number; + y: number; + z: number; + dir: number; + slope: Slope; + bank: Bank; +} + +export interface BuildChoice { + piece: TrackPieceDef; + /** Origin tile, entry height in track steps and heading of the piece to place. */ + placement: { x: number; y: number; z: number; dir: number }; +} + +function rowOf(snapshot: Snapshot, pieceId: number): number { + if (pieceId < 0) return -1; + const links = snapshot.trackLinks; + for (let row = 0; row < snapshot.tracks.count; row++) + if (links[row * TRACK_LINK_STRIDE] === pieceId) return row; + return -1; +} + +/** The piece with this stable id in the snapshot, or null when it no longer exists. */ +export function snapshotPiece(snapshot: Snapshot, pieceId: number): SnapshotPiece | null { + const row = rowOf(snapshot, pieceId); + if (row < 0) return null; + const data = snapshot.tracks.data; + const o = row * SNAPSHOT_STRIDE; + const word = data[o + 3]; + const link = row * TRACK_LINK_STRIDE; + return { + id: pieceId, + rideId: word >>> 16, + pieceType: word & 0xff, + x: Math.floor(data[o] / TILE_UNITS), + y: Math.floor(data[o + 1] / TILE_UNITS), + z: data[o + 2] / TRACK_Z_STEP, + dir: (word >> 8) & 3, + mode: (word >> 10) & 7, + prev: snapshot.trackLinks[link + 1], + next: snapshot.trackLinks[link + 2], + }; +} + +/** The id of the piece before or after `pieceId` along the track, or -1 at an open end. */ +export function neighbourPiece( + snapshot: Snapshot, + pieceId: number, + step: 'previous' | 'next', +): number { + const piece = snapshotPiece(snapshot, pieceId); + if (!piece) return -1; + return step === 'previous' ? piece.prev : piece.next; +} + +/** Where the piece sits in its section (0-based from the section's first piece). */ +export function sectionPosition( + snapshot: Snapshot, + pieceId: number, +): { index: number; count: number; ring: boolean } { + const ahead: number[] = []; + for (let id = neighbourPiece(snapshot, pieceId, 'next'); id >= 0 && id !== pieceId;) + id = neighbourPiece(snapshot, ahead[ahead.push(id) - 1], 'next'); + const ring = + ahead.length > 0 && neighbourPiece(snapshot, ahead[ahead.length - 1], 'next') === pieceId; + if (ring) { + const loop = [pieceId, ...ahead]; + const isStation = (id: number): boolean => + PIECES[snapshotPiece(snapshot, id)!.pieceType]?.shape === 'station'; + const start = loop.findIndex( + (id, k) => isStation(id) && !isStation(loop[(k + loop.length - 1) % loop.length]), + ); + return { index: (loop.length - Math.max(0, start)) % loop.length, count: loop.length, ring }; + } + let index = 0; + for (let id = neighbourPiece(snapshot, pieceId, 'previous'); id >= 0; index++) + id = neighbourPiece(snapshot, id, 'previous'); + return { index, count: index + 1 + ahead.length, ring }; +} + +/** The open ends of a piece new track can be built on. */ +export function openEnds(piece: SnapshotPiece): BuildEnd[] { + const ends: BuildEnd[] = []; + if (piece.next < 0) ends.push('after'); + if (piece.prev < 0) ends.push('before'); + return ends; +} + +/** The connection a new piece must meet on `end` of `piece`. */ +export function buildPointAt(piece: SnapshotPiece, end: BuildEnd): BuildPoint { + const def = PIECES[piece.pieceType]; + if (end === 'before') + return { + end, + x: piece.x, + y: piece.y, + z: piece.z, + dir: piece.dir, + slope: def.entrySlope, + bank: def.entryBank, + }; + const exit = pieceExit(def.id, piece.x, piece.y, piece.z, piece.dir); + return { end, ...exit, slope: def.exitSlope, bank: def.exitBank }; +} + +/** The piece the controls select at an open end, and where it goes. */ +export function resolveBuild( + point: BuildPoint, + choice: PieceChoice, + rideType: RideType, +): BuildChoice | undefined { + const shape = { hasTrack: true, slope: point.slope, bank: point.bank }; + if (point.end === 'after') { + const piece = resolvePiece(shape, choice, rideType); + return piece && { piece, placement: { x: point.x, y: point.y, z: point.z, dir: point.dir } }; + } + const piece = resolvePieceBefore(shape, choice, rideType); + if (!piece) return undefined; + const dir = (point.dir - piece.headingDelta) & 3; + const [dx, dy] = rotateTile(piece.dx, piece.dy, dir); + return { piece, placement: { x: point.x - dx, y: point.y - dy, z: point.z - piece.dz, dir } }; +} diff --git a/src/ui/track-tool.ts b/src/ui/track-tool.ts index 6c66b0ed5..9a7ae3b66 100644 --- a/src/ui/track-tool.ts +++ b/src/ui/track-tool.ts @@ -18,6 +18,7 @@ import { PieceFlag, PieceMode, Slope, + TrackNotice, TrackResult, TrackWarning, } from '../sim/track/track-types'; @@ -56,23 +57,29 @@ export function classifyPiece(piece: TrackPieceDef): TurnKind { const PIECE_TURNS: readonly TurnKind[] = PIECES.map(classifyPiece); +/** Whether the ride type's track rules let it use the piece. */ +function rideTypeAllows(piece: TrackPieceDef, rideType?: RideType): boolean { + const rules = rideType === undefined ? undefined : RIDE_CATALOG[rideType]?.trackRules; + if (!rules) return true; + if (rules.allowedPieces && !rules.allowedPieces.includes(piece.id)) return false; + if ( + !rules.steepSlopes && + (Math.abs(piece.entrySlope) === Math.abs(Slope.Up60) || + Math.abs(piece.exitSlope) === Math.abs(Slope.Up60)) + ) + return false; + return rules.inversions || !(piece.flags & PieceFlag.Inverted); +} + /** The piece that matches the controls and attaches to the cursor, if the catalog has one. */ export function resolvePiece( cursor: CursorShape, choice: PieceChoice, rideType?: RideType, ): TrackPieceDef | undefined { - const allowedPieces = - rideType === undefined ? undefined : RIDE_CATALOG[rideType]?.trackRules?.allowedPieces; - const rules = rideType === undefined ? undefined : RIDE_CATALOG[rideType]?.trackRules; return PIECES.find( (piece, index) => - (!allowedPieces || allowedPieces.includes(piece.id)) && - (!rules || - rules.steepSlopes || - (Math.abs(piece.entrySlope) !== Math.abs(Slope.Up60) && - Math.abs(piece.exitSlope) !== Math.abs(Slope.Up60))) && - (!rules || rules.inversions || !(piece.flags & PieceFlag.Inverted)) && + rideTypeAllows(piece, rideType) && PIECE_TURNS[index] === choice.turn && piece.exitSlope === choice.slope && piece.exitBank === choice.bank && @@ -80,6 +87,27 @@ export function resolvePiece( ); } +/** + * The piece that matches the controls and leads into the start of a section whose first piece + * begins with `start`'s slope and bank. Building backward, the slope and bank controls set the + * new piece's far end: the slope and bank it starts with. + */ +export function resolvePieceBefore( + start: CursorShape, + choice: PieceChoice, + rideType?: RideType, +): TrackPieceDef | undefined { + return PIECES.find( + (piece, index) => + rideTypeAllows(piece, rideType) && + PIECE_TURNS[index] === choice.turn && + piece.entrySlope === choice.slope && + piece.entryBank === choice.bank && + piece.exitSlope === start.slope && + piece.exitBank === start.bank, + ); +} + /** Drive modes the piece supports on this ride type, in display order. */ export function allowedModes(piece: TrackPieceDef, rideType: RideType): PieceMode[] { const rules = RIDE_CATALOG[rideType]?.trackRules; @@ -230,14 +258,13 @@ const TRACK_MESSAGES: Record = { [TrackResult.NoSuchRide]: 'That ride no longer exists.', [TrackResult.NoSuchPiece]: 'There is no track piece to remove there.', [TrackResult.OutOfBounds]: 'The piece would leave the map.', - [TrackResult.NotConnected]: 'The piece does not connect to the end of the track.', + [TrackResult.NotConnected]: 'The piece does not connect to an open end of the track.', [TrackResult.Blocked]: 'Blocked by other track.', [TrackResult.BelowGround]: 'The piece would go below the ground.', [TrackResult.TooHigh]: 'The piece is too high for this ride.', [TrackResult.BadMode]: 'This piece cannot use that drive mode.', [TrackResult.TooManyPieces]: 'This ride has too many track pieces.', [TrackResult.CircuitClosed]: 'The circuit is complete; remove a piece to extend it.', - [TrackResult.NotAtEnd]: 'Only the end of an unfinished track can be removed.', [TrackResult.StoreFull]: 'The park cannot hold any more track.', [TrackResult.NotOwned]: 'You need to own the land or its construction rights.', [TrackResult.InsufficientFunds]: 'Not enough cash for that piece.', @@ -247,6 +274,8 @@ const TRACK_MESSAGES: Record = { 'Tunnels must enter through the side of the land, not a corner, and run straight until they are under cover.', [TrackResult.OverWater]: 'Track cannot be built over open water for this ride type.', [TrackResult.HeightLimit]: heightLimitRefusal(), + [TrackResult.RideBusy]: + 'Close the ride and wait for its train to return empty before changing the track.', }; const TRACK_WARNING_MESSAGES: Record = { @@ -302,6 +331,7 @@ export function feedbackMessage(domain: FeedbackDomain, code: number, detail = ' if (code === TrackWarning.LiftIntoInversion) { return { text: TRACK_WARNING_MESSAGES[code], ok: false }; } + if (code === TrackNotice.Removed) return { text: 'Track piece removed.', ok: true }; return { text: TRACK_MESSAGES[code as TrackResult] ?? `Track result ${code}`, ok: code === 0 }; } if (domain === FeedbackDomain.Ride) { diff --git a/src/ui/ui-types.ts b/src/ui/ui-types.ts index 35c721ca5..daffb3b5d 100644 --- a/src/ui/ui-types.ts +++ b/src/ui/ui-types.ts @@ -104,8 +104,8 @@ export interface GameUIActions { chooseRideType(type: RideType): void; /** Opens Footpaths with Queue line on and points at the ride's entrance, to build its queue. */ buildRideQueue(rideId: number): void; - /** Reopens a track ride in the construction window. */ - editTrack(rideId: number): void; + /** Reopens a track ride in the construction window, with `pieceId` selected when given. */ + editTrack(rideId: number, pieceId?: number): void; map(): MapData | null; camera(): Camera; audioSettings(): Pick; @@ -142,7 +142,10 @@ export interface UiContext { alternate(): boolean; selectedGuest(): GuestSelection | null; series: { cash: SampleSeries; value: SampleSeries; profit: SampleSeries; guests: SampleSeries }; - openRide(rideId: number): void; + /** Opens the ride's window; `pieceId` is the track piece the player clicked to open it. */ + openRide(rideId: number, pieceId?: number): void; + /** The track piece clicked to open the ride's window, if it was opened from one. */ + clickedTrackPiece(rideId: number): number | undefined; openGuest(guestId: number): void; openWorker(staffId: number): void; openWindow(id: string): void; diff --git a/src/ui/ui.css b/src/ui/ui.css index 1a6cfad8e..da9bcb186 100644 --- a/src/ui/ui.css +++ b/src/ui/ui.css @@ -2032,3 +2032,26 @@ .height-readout[hidden] { display: none; } + +.track-selection-outline { + position: fixed; + z-index: 3; + image-rendering: pixelated; + pointer-events: none; + animation: track-selection-pulse 0.9s ease-in-out infinite alternate; +} + +@keyframes track-selection-pulse { + from { + opacity: 1; + } + to { + opacity: 0.45; + } +} + +@media (prefers-reduced-motion: reduce) { + .track-selection-outline { + animation: none; + } +} diff --git a/src/ui/windows/ride-window.ts b/src/ui/windows/ride-window.ts index 1a644534d..66b817ee0 100644 --- a/src/ui/windows/ride-window.ts +++ b/src/ui/windows/ride-window.ts @@ -127,6 +127,12 @@ export function openRideWindow(ctx: UiContext, rideId: number): WindowController button('Place exit', () => ctx.actions.placeRidePart(rideId, 'exit'), 'ui-button'), ); const buildTrack = button('Edit track', () => ctx.actions.editTrack(rideId), 'ui-button'); + const editFromPiece = button( + 'Edit from this piece', + () => ctx.actions.editTrack(rideId, ctx.clickedTrackPiece(rideId)), + 'ui-button', + ); + editFromPiece.title = 'Open construction with the track piece you clicked selected'; const locate = button( 'Locate', () => { @@ -297,6 +303,7 @@ export function openRideWindow(ctx: UiContext, rideId: number): WindowController partButtons, turnStall, buildTrack, + editFromPiece, locate, ); p('vehicle').append( @@ -493,6 +500,7 @@ export function openRideWindow(ctx: UiContext, rideId: number): WindowController const missing = blockers.map((blocker) => blocker.label); setText(mainFacts.setup.value, missing.length ? missing.join(' · ') : 'Ride setup complete'); buildTrack.hidden = !def?.usesTrack; + editFromPiece.hidden = !def?.usesTrack || ctx.clickedTrackPiece(rideId) === undefined; trainsRow.hidden = !def?.usesTrack; partButtons.hidden = serviceRide; turnStall.hidden = !serviceRide; diff --git a/src/worker/snapshot.test.ts b/src/worker/snapshot.test.ts index 2b88c8aae..f88b76bbe 100644 --- a/src/worker/snapshot.test.ts +++ b/src/worker/snapshot.test.ts @@ -506,7 +506,7 @@ describe('staff and ground state in the snapshot', () => { expect(snapshot.grounds[sim.world.map.index(2, 2)]).toBe( sim.world.grounds[sim.world.map.index(2, 2)], ); - expect(snapshotBuffers(snapshot)).toHaveLength(17); + expect(snapshotBuffers(snapshot)).toHaveLength(18); }); }); diff --git a/src/worker/snapshot.ts b/src/worker/snapshot.ts index 74ad9f797..b3ddb503c 100644 --- a/src/worker/snapshot.ts +++ b/src/worker/snapshot.ts @@ -49,6 +49,8 @@ import { export const SNAPSHOT_STRIDE = 4; export const SNAPSHOT_RIDE_CAPACITY = 256; export const SNAPSHOT_TRACK_CAPACITY = MAX_TRACK_PIECES; +/** Ints per track row in `Snapshot.trackLinks`: piece id, previous piece id, next piece id (-1 = none). */ +export const TRACK_LINK_STRIDE = 3; /** Ints per ride in `Snapshot.rideInfo`; index with `RideInfo`. */ export const RIDE_INFO_STRIDE = 51; @@ -255,6 +257,8 @@ export interface Snapshot { litter: SnapshotLayer; rides: SnapshotLayer; tracks: SnapshotLayer; + /** `TRACK_LINK_STRIDE` ints per `tracks` row: the piece's stable id and its neighbours' ids. */ + trackLinks: Int32Array; /** Derived occupied intervals for track preview. */ occupancies: OccupancyVolume[]; /** `RIDE_INFO_STRIDE` ints per ride, in the same order as `rides`. */ @@ -370,6 +374,7 @@ export function createSnapshot(caps: SnapshotCapacities): Snapshot { litter: layer(caps.litter), rides: layer(caps.rides ?? SNAPSHOT_RIDE_CAPACITY), tracks: layer(caps.tracks ?? SNAPSHOT_TRACK_CAPACITY), + trackLinks: new Int32Array((caps.tracks ?? SNAPSHOT_TRACK_CAPACITY) * TRACK_LINK_STRIDE), occupancies: [], rideInfo: new Int32Array((caps.rides ?? SNAPSHOT_RIDE_CAPACITY) * RIDE_INFO_STRIDE), guestDetails: new Int32Array(caps.guests * GUEST_DETAIL_STRIDE), @@ -428,6 +433,7 @@ export function snapshotBuffers(s: Snapshot): ArrayBuffer[] { .map((l) => l.data.buffer as ArrayBuffer) .concat( s.rideInfo.buffer as ArrayBuffer, + s.trackLinks.buffer as ArrayBuffer, s.buildable.buffer as ArrayBuffer, s.grounds.buffer as ArrayBuffer, s.patrolAreas.buffer as ArrayBuffer, @@ -723,6 +729,10 @@ export function writeSnapshot(world: World, out: Snapshot): void { (trackPieces.cols.mode[i] << 10) | (trackPieces.cols.dir[i] << 8) | (trackPieces.cols.pieceType[i] & 0xff); + const link = i * TRACK_LINK_STRIDE; + out.trackLinks[link] = trackPieces.slotToId[i]; + out.trackLinks[link + 1] = trackPieces.cols.prev[i]; + out.trackLinks[link + 2] = trackPieces.cols.next[i]; } out.tracks.count = trackCount; const feedback = world.feedback; From 86d3eae08e01418917ea49345933334564c9eba0 Mon Sep 17 00:00:00 2001 From: "nori-sessions[bot]" <264258699+nori-sessions[bot]@users.noreply.github.com> Date: Mon, 2 Nov 2026 07:08:10 +0000 Subject: [PATCH 2/4] Document editing from a selected piece; proof crops include overlays MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 🤖 Generated with [Nori](https://noriagentic.com) Co-Authored-By: Nori --- docs/mechanics/track.md | 21 +++++++++++++++++++++ e2e/docs.md | 1 + 2 files changed, 22 insertions(+) diff --git a/docs/mechanics/track.md b/docs/mechanics/track.md index e5da8539b..7afe20c0a 100644 --- a/docs/mechanics/track.md +++ b/docs/mechanics/track.md @@ -147,6 +147,22 @@ Testing -> Closed if train crashes, stalls > N s, or exceeds time budget -> show Open: continue refining max values from real runs with slow decay of stale test data; recompute ratings every ~N ticks ``` +### 2.8 Editing from a selected piece + +What public sources describe: +- The construction window has next/previous track segment arrows that step the highlighted (selected) piece through the placed track, and right-clicking a placed segment selects it. The bulldozer removes the piece just built at the end, or the highlighted piece when one in the middle is selected. [S] (RCT2 manual p.38, https://archive.org/details/rct_2_manual) +- A ride must be closed before its track can be worked on. [S] (RCT2 manual pp.38-39) +- Deleting pieces from the middle leaves separate track sections that have to be joined up again before the ride can open; an incomplete circuit cannot be opened. [S, S] (https://forums.openrct2.org/topic/582-starting-a-new-track-section, https://forums.openrct2.org/topic/3504-forcing-a-ride-open-non-complete-circuit) +- After deleting pieces the construction arrow moves to a remaining open end rather than staying at the deleted spot. [S] (https://www.openrct2.io/download/changelog) +- Deleting a station in the middle of a platform can leave one platform that behaves as two stations. [S] (https://forums.openrct2.org/topic/5355-guests-never-leave-rollercoastersingle-station-seen-as-two-stations) + +What OpenCoaster does (our own design inspired by the above; **[I]**): +- A ride's track is one or more open sections or a single closed ring. Any piece can be demolished; removing a middle piece splits its section, or opens a closed circuit at that point. A placement may continue any section's last piece and lead into any section's first piece, joining sections. The ride only counts as a complete circuit when all of its track forms one ring with a station. +- The construction window keeps a selected piece (editor state only, never saved). Previous piece / Next piece step along the track, clicking rails in the build tool selects that piece, and the ride window offers Edit from this piece when it was opened from a rail. Build piece continues from the selection's open end; Build before this piece extends a section backward from its first piece. Demolish removes the selected piece, and the selection moves to its neighbour, preferring the previous one. +- Track can only change on a ride that is closed with its trains home and empty: not while open or testing, while a train is loading, running or unloading, or while riders are aboard. The edit is refused rather than force-closing the ride. +- After a demolition, an entrance or exit with no station tile beside it any more is detached from the ride; the ride needs a new one before it can open. +- Difference from the original: removing a piece gives no per-piece refund. Demolishing the whole ride refunds the pieces that remain. + --- ## 3. Data model proposal @@ -262,6 +278,11 @@ Sources: - https://rctv1.rctspace.com/test/info/tips2.html - https://tid.rctspace.com/TD4viewer.html - https://rct.fandom.com/wiki/Inverted_Hairpin_Coaster +- https://archive.org/details/rct_2_manual (pp.38-39, track editing) +- https://forums.openrct2.org/topic/582-starting-a-new-track-section +- https://forums.openrct2.org/topic/3504-forcing-a-ride-open-non-complete-circuit +- https://www.openrct2.io/download/changelog +- https://forums.openrct2.org/topic/5355-guests-never-leave-rollercoastersingle-station-seen-as-two-stations ### Tunnel portals: what the original game does and what we do diff --git a/e2e/docs.md b/e2e/docs.md index dd4e4b33b..93ac028ce 100644 --- a/e2e/docs.md +++ b/e2e/docs.md @@ -33,6 +33,7 @@ Path: @/e2e - [observation-tower-height.spec.ts](observation-tower-height.spec.ts) builds towers of chosen height through the placement controls (helpers in [support/tower.ts](support/tower.ts)), checks section prices, edits a closed tower's height from its window, and samples a test run for one climb, one descent and a steady cabin speed. [observation-tower-proof.spec.ts](observation-tower-proof.spec.ts) runs only when `TOWER_PROOF_DIR` is set and writes the PR proof (screenshots in every rotation for WebGL2 and Canvas2D, a phone check, a 1x video, timing JSON). - [flat-ride-footprints.spec.ts](flat-ride-footprints.spec.ts) builds all ride types through the UI on a flat street site and checks the placement ghost, allowed entrance ring, entrance and exit placement, open state, and footprint visibility in all four camera rotations. Swinging Ship, Ferris Wheel and Top Spin also exercise every ride orientation. Only the Merry-Go-Round waits for guests to ride and captures the served state; this keeps the full footprint matrix while avoiding repeated long guest simulations. Forced Canvas2D checks representative 3x3 square (Twist), elongated (Swinging Ship), and single-tile/tall-art (Observation Tower) footprints. The spec settles screenshots and guest-serving checks with simulation-tick polling and rendered-state assertions instead of fixed delays. A Pixel 8 case checks the Rotate ride button clears the HUD. Set `FOOTPRINT_SHOTS_DIR` to write the JPEG sheets (committed under docs/playtest/assets/footprints) instead of the test output folder. - [track-heights.spec.ts](track-heights.spec.ts) imports a flat owned park and, through the construction window only, builds a Steel Looping Coaster whose station end and far side sit one land level apart, checking the `Track end at height N` line through each half-level step of the climb and descent, and closes the circuit. Set `TRACK_HEIGHTS_PROOF_DIR` to write screenshots of the circuit in each rotation. +- [track-edit-selection.spec.ts](track-edit-selection.spec.ts) runs on desktop and emulated Pixel 8 under both WebGL2 and Canvas2D, importing a save from [support/track-edit-park.ts](support/track-edit-park.ts) (a closed tested circuit, plus an unfinished coaster crossed by another ride's overpass). It opens a ride window from a clicked rail and uses Edit from this piece, steps with Previous/Next piece, demolishes a middle piece and rebuilds it to close, test and reopen the circuit, checks an open ride refuses edits, selects stacked rails of two rides by click or tap, builds before a section's first piece, returns to Track end, and checks the selection outline sits over the clicked piece. - [art-review.spec.ts](art-review.spec.ts) compares default-zoom facility renders against the same scene without the facility, requiring a minimum visible-pixel area in both backends, and captures a populated context scene in all rotations. It also builds completed coaster and transport rides through the simulation's `createCoaster` and `placeTrack` command path, then renders their snapshots with the production Canvas2D and WebGL2 renderers. It verifies that each placed track piece resolves to generated art with opaque pixels and that the rendered canvas has no red fallback marker; optional capture output includes inventory sheets and per-ride images. The fixture imports [sprite-pages.ts](../src/render/sprite-pages.ts) by its canonical module URL so lazy page loads are visible to the renderer's shared sprite store. - [p1-ui-fidelity.spec.ts](p1-ui-fidelity.spec.ts) requires the desktop canvas to use WebGL2, checks populated ride windows avoid status bar and pointer overlap, validates compact coaster controls, builds while paused, checks the 2× construction cap and ride preview, verifies saved desktop window placement, and exercises ownership UI. The ride-access Pixel 8 scenario checks the construction controls fit the mobile viewport and uses touch to build. - [ride-breakdown-proof.spec.ts](ride-breakdown-proof.spec.ts) captures both a forced breakdown with a mechanic en route and a separate naturally rolled breakdown. The natural seeded scene in [support/breakdown-scene.ts](support/breakdown-scene.ts) advances until reliability has fallen and rolling downtime is nonzero; its Maintenance screenshot documents those live values. From 00fc393a3305e0c54d4af59f054f1320454d122d Mon Sep 17 00:00:00 2001 From: "nori-sessions[bot]" <264258699+nori-sessions[bot]@users.noreply.github.com> Date: Mon, 2 Nov 2026 07:08:12 +0000 Subject: [PATCH 3/4] Update module docs for editing from a selected piece MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 🤖 Generated with [Nori](https://noriagentic.com) Co-Authored-By: Nori --- src/app/bootstrap/docs.md | 1 + src/app/tools/docs.md | 4 +++- src/input/docs.md | 2 +- src/render/docs.md | 2 +- src/sim/rides/docs.md | 4 ++-- src/sim/track/docs.md | 10 +++++++--- src/ui/docs.md | 10 +++++++--- src/worker/docs.md | 3 ++- 8 files changed, 24 insertions(+), 12 deletions(-) diff --git a/src/app/bootstrap/docs.md b/src/app/bootstrap/docs.md index 3b0534a11..075c94237 100644 --- a/src/app/bootstrap/docs.md +++ b/src/app/bootstrap/docs.md @@ -19,6 +19,7 @@ Path: @/src/app/bootstrap - Keeps the optional wall-edge override for the current scenery placement. With a wall selected, the scenery preview and click use that edge or derive the nearest edge from the pointer and projected tile; the `t` key and rotate control cycle the override through the four world edges. Changing the selected scenery item clears the override. - Drives frame-time camera movement, scenario outcome observation, HUD/UI refresh, rendering and overlays from a single animation-frame callback. The loop synchronizes the UI's compass indicator with the camera's discrete rotation. Live viewport collection runs after layout on a throttled cadence, resolves stable entity IDs against the latest snapshot, and supplies a camera and canvas-relative rectangle to [src/render](../../render/docs.md). The refresh scheduler rotates through visible viewports, refreshing one WebGL2 target every three frames or one Canvas2D target every 100 ms. - Wires controller actions back into `SimClient` commands and pause/speed controls, including the tool controller's path and scenery removal callbacks used by canvas context menus. It creates the Land controller and one `AreaController` each for Clear scenery and Water, hands the same instances to camera input and the tool controller, routes the windows' `setLand` / `setClearScenery` / `setWater` settings to them, and calls each controller's `update` once per frame so previews, overlays and tooltips follow the latest worker answer. Pointer hover also supplies the renderer with the hovered tile and Shift/remove state; while Patrol is active, bootstrap sends the selected worker and preview state to the renderer before the world draw. +- Wires track editing from a selected piece: the `editTrack(rideId, pieceId?)` action makes the ride active in the [CoasterPanel](../../ui/coaster-panel.ts), selects the track tool and, when a piece is given, selects it and shows the selection status. It passes `trackGhostAt` (backed by `TrackPreviewOverlay.hits`) to the [tool controller](../tools/docs.md) so ghost clicks keep building, and creates the [TrackSelectionOutline](../tools/track-selection-outline.ts), updated every frame from `coasterPanel.selectedPiece()`, the renderer, the latest snapshot and the camera, and disposed with the other overlays. - On a new game, the map callback uses [opening-camera.ts](opening-camera.ts) to project the park gate and contiguous inward entrance path into the current camera rotation. It falls back to the map center when entrance coordinates are unavailable or negative; later map updates preserve the player's view. ### Things to Know diff --git a/src/app/tools/docs.md b/src/app/tools/docs.md index fd1fbe6db..6b05f512b 100644 --- a/src/app/tools/docs.md +++ b/src/app/tools/docs.md @@ -15,8 +15,10 @@ Path: @/src/app/tools ### Core Implementation -- `createToolController` converts CSS-pixel canvas positions to map tiles, dispatches the active tool, and updates selection/UI state. In Select mode, clicks use the topmost visible alpha-mask target first: flat ride sprites, tracked-ride track/support/car/rider sprites, and placed entrances/exits open their ride window; walking guests and staff open their detail windows; the park gate opens Park. Scenery and path additions open a small popup placed beside the clicked sprite (right side, flipping left when it does not fit, clamped to the screen) with the object's name and state and a Done control; scenery can be removed, while path additions can be removed and vandalised additions can be repaired. If no sprite target is hit, terrain picking falls back to ride footprints or track tiles, nearby people and the park entrance tile. +- `createToolController` converts CSS-pixel canvas positions to map tiles, dispatches the active tool, and updates selection/UI state. In Select mode, clicks use the topmost visible alpha-mask target first: flat ride sprites, tracked-ride track/support/car/rider sprites, and placed entrances/exits open their ride window; walking guests and staff open their detail windows; the park gate opens Park. Scenery and path additions open a small popup placed beside the clicked sprite (right side, flipping left when it does not fit, clamped to the screen) with the object's name and state and a Done control; scenery can be removed, while path additions can be removed and vandalised additions can be repaired. If no sprite target is hit, terrain picking falls back to ride footprints or track tiles, nearby people and the park entrance tile. A click on a coaster's rails passes the rail's `pieceId` to `GameUI.openRide`, which offers Edit from this piece in the [ride window](../../ui/docs.md); other coaster parts open the window without one. - Select-mode hover displays the target name in tool status and outlines the hovered object's sprite pixels (alpha mask, not a box) with a light tint; sliced flat-ride body cells are individual pick targets grouped with the ride's entrance and exit so hovering any visible slice outlines the whole ride. Coaster track pieces, stations, trains, stalls, scenery, path additions and people highlight individually ([object-overlay.ts](object-overlay.ts)); leaving Select mode clears that hover. Person pickup can begin from a guest or staff window action, a desktop drag that alpha-hit-tests the sprite under its start point, or a touch long-press gesture. Starting a pickup clears the hover outline so none is left at the vacated spot. While carried, the person is hidden from the park (`Renderer.setHeldPerson`) and their atlas sprite is redrawn at the pointer at the same zoomed height as its walking target, lifted a quarter tile (`heldLiftPixels`), with a dark pixel outline and zoom-scaled ground shadow. A green/red ring on the destination tile plus status text reports whether the drop is valid and why it is refused. A guest in queueing, waiting-to-board or riding state is refused. A drop resolves the terrain tile under the pointer and accepts a path or owned dry tile; invalid destinations report a reason without sending a command. Accepted drops enqueue `setPersonPosition`, and the worker applies it immediately while paused. The simulation remains authoritative and validates the same map constraints. +- Track tool clicks go through `trackToolClick`. While the construction window builds track (`CoasterPanel.buildsTrack()`) and the click is not on the build ghost (`trackGhostAt`, backed by `TrackPreviewOverlay.hits`), the controller runs `pickTrackPiece` from [object-picking](../../input/object-picking.ts) over the renderer's current targets. Rails select that piece through `CoasterPanel.selectPiece`, which also switches the active coaster when the rails belong to another ride; a train, rider or support only sets a hint to click the rails. Clicks on the ghost, on open ground, or in entrance/exit mode fall through to `handleTileClick` and build as before. +- [track-selection-outline.ts](track-selection-outline.ts) (`TrackSelectionOutline`) draws a pulsing outline of the construction window's selected piece on its own canvas. It filters the renderer's shared pick targets to that piece's rail sprites and draws them with `drawSpriteOutline` from [object-overlay.ts](object-overlay.ts), so the outline matches what both renderers drew and picked. The canvas ignores pointer events and sits on a low z-index, under windows. It redraws only when the piece's geometry, the camera or the viewport changes, and only repositions otherwise; with no selection or no visible rail it hides. The pulse is disabled under reduced motion. - [land-controller.ts](land-controller.ts) drives the Land window's tool: it picks the selection under the pointer ([land-selection.ts](land-selection.ts): square size, and for size 1 a corner, edge or whole tile from the position inside the tile), asks the worker to preview the edit, shows the overlay and a cursor tooltip with the price or refusal ([land-feedback.ts](land-feedback.ts)), sends the command on tap, and turns a vertical drag on a locked selection into one raise or lower step per terrain step of pointer travel. Flatten and smooth paint tile by tile while dragging; flatten keeps the first tile's height as its level. - [area-controller.ts](area-controller.ts) (`AreaController`) drives the Clear scenery and Water tools (vertical drags on Water repeat raise or lower steps like the Land tool); bootstrap creates one instance per tool. It reuses the Land tool's square picking (whole tiles only, no corner or edge picking), requests a worker preview whenever the edit under the pointer changes, draws [the area overlay](../../ui/area-overlay.ts), and shows a `.area-tip` cursor tooltip. A tap sends `clearScenery`, `raiseWater` or `lowerWater`; Shift or the alternate action inverts the Water window's Raise/Lower choice for that tap. Water has no drag-to-repeat, so repeated steps are repeated taps. A tap whose latest preview for the same edit was already refused flashes the reason instead of sending a command; worker refusals arriving in `Snapshot.feedback` under the tool's own domain (`Clear` or `Water`) are shown for 2.5 seconds with the blocking tile flagged. - [area-feedback.ts](area-feedback.ts) holds the tooltip text: the price of a step (for example a count of items to clear with their total, or "Raise water, N tiles" with its price) and tool-specific refusal wording, falling back to the Land tool's refusal text for shared `LandResult` codes. diff --git a/src/input/docs.md b/src/input/docs.md index 916baf67d..594384923 100644 --- a/src/input/docs.md +++ b/src/input/docs.md @@ -21,7 +21,7 @@ Path: @/src/input - Two active pointers establish a pinch baseline and midpoint. Distance changes report zoom scale around that midpoint; twist deltas accumulate until they cross 45 degrees, then request one quarter-turn per threshold crossing. - [camera-controls.ts](camera-controls.ts) snaps zoom to the supported scale set, preserves the world position under the zoom anchor, steps wheel zoom between levels, and caps device pixel ratio for rendering. Camera rotation is a quarter-turn around the world point at the viewport centre: the helper estimates a sloped terrain tile's centre elevation from its four corner heights, prefers a nearby raised path or coaster track, then converts the focus through the current projection and projects it into the next view before updating the camera. - [src/app/input](../app/input/docs.md) de-duplicates repeated paint commands within the same tile and routes touch holds through person pickup in Select mode, forced selection when no eligible person is picked up, and path removal in Footpaths mode. Desktop context clicks are routed per tool by [src/app/input](../app/input/docs.md). [src/app/tools](../app/tools/docs.md) uses renderer-picked targets for object selection and keeps tile-based ride lookup as the terrain fallback. -- [object-picking.ts](object-picking.ts) builds alpha masks from the shared sprite atlas and projects target bounds using the current camera, map and viewport. It sorts targets by painter depth and tests them in reverse order, ignoring transparent source pixels. Flat rides, stalls and facilities (keyed by their stored `RideInfo.Dir` facing, like the renderers), tracked-ride track cells, supports, cars and seated riders, placed entrances and exits, the park gate, walking guests and staff, scenery, and path additions produce targets; terrain tile picking and footprint/track lookup remain the fallback when no sprite target is hit. Both renderers expose the same target list through their `pickObject` interface. +- [object-picking.ts](object-picking.ts) builds alpha masks from the shared sprite atlas and projects target bounds using the current camera, map and viewport. It sorts targets by painter depth and tests them in reverse order, ignoring transparent source pixels. Flat rides, stalls and facilities (keyed by their stored `RideInfo.Dir` facing, like the renderers), tracked-ride track cells, supports, cars and seated riders, placed entrances and exits, the park gate, walking guests and staff, scenery, and path additions produce targets; terrain tile picking and footprint/track lookup remain the fallback when no sprite target is hit. Both renderers expose the same target list through their `pickObject` interface. Coaster targets carry the scene item's `coasterPart` and, for rails and supports, its `pieceId`. `pickTrackPiece` tests only coaster sprites, so scenery or guests drawn in front of the track never block it, and returns the topmost one as a rail piece (`rideId`, `pieceId`) or as a non-rail part (`'support'`, `'car'` or `'rider'`); trains, riders and supports are never mapped to a piece. The [build tool](../app/tools/docs.md) uses it to select pieces. - [wall-edge.ts](wall-edge.ts) chooses the closest projected terrain edge for wall scenery placement. It projects the four terrain corners with the current slope and camera rotation, then measures pointer distance to each edge segment; this keeps cursor selection aligned with the rendered diamond on raised and sloped tiles. ### Things to Know diff --git a/src/render/docs.md b/src/render/docs.md index a03a79e8c..b2a55528f 100644 --- a/src/render/docs.md +++ b/src/render/docs.md @@ -57,7 +57,7 @@ The projection maps a world point to `sy = 16 * (rx + ry) - 16 * z` (tiles, leve - [ground-anchor.ts](ground-anchor.ts) is the shared placement contract for both renderers: it supplies ground boxes for scenery, native-size flower-bed frames, and rain shelters, and the path walking surface `PATH_SURFACE_Z`, path-addition placement (`pathAdditionPlacements`: one copy per open, unconnected edge, offset 96 world units from the tile centre and so inside the tile; a crossroads gets none, except lamps, which stand as four corner posts), path-addition edge and ramp elevations, rotation-dependent tile-centre elevations for sloped scenery and flower beds, and the horizontal sprite-anchor shift used by WebGL2. Flowerbed ground elevation is the average height along the diagonal shared by the two terrain triangles for the camera rotation, plus the small ground-surface offset; it anchors placed and ambient beds and the placement preview. - [night-lighting.ts](night-lighting.ts) derives time of day from the simulation tick without adding saved state: one lighting cycle spans 36 in-game calendar days, about 7m56s at 1× (about 3m58s at 2× and 1m59s at 4×). Each cycle starts at 08:00; `darknessAt(tick)` eases through dusk from 18:00 to 20:00 and dawn from 05:00 to 07:00, giving about 39.6 real seconds for each transition at 1×. Path lamps turn on once darkness reaches `LAMP_ON_DARKNESS`; because darkness only rises through dusk and falls through dawn, lamps switch once each way. `collectLitLamps` lists intact lamp placements in view; vandalised lamps (`PATH_ADDITION_BROKEN`) are omitted. When `Camera.dayNight` is set, each renderer finishes its frame with a night pass after world drawing (skipped for object-ID captures): [night-pass-webgl.ts](night-pass-webgl.ts) multiplies the frame by a cool ambient tint that retains a readable floor at full night and adds lamp lights with instanced draws; [night-pass-canvas.ts](night-pass-canvas.ts) uses a `multiply` fill and one `lighter` `drawImage` per lamp of a small pool sprite built per zoom/device-pixel scale (hard-edged bands, smoothing off). The sprite canvas is CPU-backed (`willReadFrequently`) because compositing a large GPU-backed offscreen canvas into the scene canvas forces a per-frame readback that costs several times the rest of the frame. Overlapping pools add, as in the WebGL2 pass. `Camera.lampLights` independently enables lamp lighting. Each lamp uses a warm four-band ground ellipse plus a bright head core and halo; the pass overlays lights without depth testing, so they brighten guests and scenery in the pool. Game options > Display has "Day and night" and "Lamp lighting" switches, both on by default ([display-options.ts](../ui/display-options.ts)); [e2e/night-lamps.spec.ts](../../e2e/night-lamps.spec.ts) captures day, dusk and night in each renderer and camera rotation and measures frame time with about 200 lamps (`NIGHT_BENCH=1`; `NIGHT_SKIP_CATEGORIES` keeps WebGL2 within memory). - Weather shading is a separate DOM layer: [game-ui.ts](../ui/game-ui.ts) maps the weather kind from the worker snapshot to classes styled in [index.html](../../index.html). Rain and storm retain their moving streak patterns, while the cloudy/rain/storm color washes use low opacity so they do not compound the night pass into an unreadable dark scene. Weather changes presentation only here; gameplay effects stay in simulation systems. -- [coaster-art.ts](coaster-art.ts) maps tracked rides to coaster, water, or transport families and constructs track-cell and vehicle keys. [coaster-scene.ts](coaster-scene.ts) turns snapshot track and car layers into a reusable key-ordered list; track-piece cells follow piece direction and camera rotation, coaster supports stack to the ground beneath the in-cell track sample nearest the tile centre (`supportOffset`, so a column stands under the rails even where a turn hugs a tile edge), and cars or boats use per-car poses. Car draw keys use the continuous projected world position through `viewDepth`, rather than snapping each vehicle to a tile centre. Water boat keys include each car's packed passenger count to select empty or loaded sprites; the meshes show up to four passenger figures for Log Flume boats and seven for River Rapids boats. Log Flume and River Rapids therefore render track and boats through this scene; their older static ride dioramas remain generated art but are no longer the ride's runtime representation. +- [coaster-art.ts](coaster-art.ts) maps tracked rides to coaster, water, or transport families and constructs track-cell and vehicle keys. [coaster-scene.ts](coaster-scene.ts) turns snapshot track and car layers into a reusable key-ordered list; track-piece cells follow piece direction and camera rotation, coaster supports stack to the ground beneath the in-cell track sample nearest the tile centre (`supportOffset`, so a column stands under the rails even where a turn hugs a tile edge), and cars or boats use per-car poses. Each item carries `part` (`'track'`, `'support'`, `'car'` or `'rider'`) and `pieceId`, the stable track piece id read from the snapshot's `trackLinks` for rails and supports (-1 for cars and riders), so [object picking](../input/docs.md) can tell which piece a sprite belongs to. Car draw keys use the continuous projected world position through `viewDepth`, rather than snapping each vehicle to a tile centre. Water boat keys include each car's packed passenger count to select empty or loaded sprites; the meshes show up to four passenger figures for Log Flume boats and seven for River Rapids boats. Log Flume and River Rapids therefore render track and boats through this scene; their older static ride dioramas remain generated art but are no longer the ride's runtime representation. - Generated guest sprites use the `people/guest-walk#N` frames from [tools/sprites](../../tools/sprites/docs.md), indexed by guest tint, heading, and walking pose. Both renderers resolve them from the eager `people` atlas through the shared `guestSpriteName`, which switches to the `people/guest-sit` figure (indexed by tint and camera-rotated facing) when the snapshot row's seated bit is set (`guestRowSeated`); [GUEST_BOX](sprite-layout.ts) supplies the 20×24-pixel visibility and fallback bounds. Model-generated people frames render at native size. A seated guest is drawn at its seat position with the ordinary guest anchor and height-based occlusion, so it sorts against the bench by the shared per-pixel height model rather than any painter bias; its heading is the direction it faces (toward the path). Walking guests carrying a balloon or hat, or holding an umbrella in rain, get a `people/carried` overlay from the snapshot's drawn-item bits. Guests in the `Riding` state (`isRidingGuestRow`) are skipped by both renderers: they are drawn by their ride instead. [coaster-scene.ts](coaster-scene.ts) seats up to four `people/rider-seated` figures along each coaster, mouse, railway and monorail car from the car's packed passenger count; Log Flume and River Rapids boats and chairlift chairs already bake riders into their car art, and flat and enclosed rides show none, so a rider is never also a walking sprite. Riders reappear as walkers at the exit when the guest leaves `Riding`. Generated staff sprites encode uniform role and cardinal facing in their keys and provide four walking poses; the renderers combine staff heading with camera rotation and cycle all four poses from simulation ticks. Both renderers draw persisted tree elements, flower beds and other scenery through the shared scenery path, using the catalog boxes supplied by [sprite-layout.ts](sprite-layout.ts) and [ground-anchor.ts](ground-anchor.ts). - WebGL2 and [canvas2d-renderer.ts](canvas2d-renderer.ts) consume the generated art. Canvas2D resolves the same page store through [canvas-atlas.ts](canvas-atlas.ts), draws sprites at manifest frame size and anchor with image smoothing disabled, and keeps procedural terrain and fallback drawing. The affine Canvas2D cliff-texture path also disables smoothing while mapping atlas art onto terrain faces. Flowerbeds use their own tile's projected centre and terrain-derived elevation in both backends; native frame sizing and the manifest ground pivot keep their rendered footprint aligned with that tile. Their generated soil rests one pixel above the terrain, so the bed always wins against the ground under it. Litter uses a compact, flat generated sprite at its projected ground point; both backends use the shared 6×3-pixel target size in [world-art.ts](world-art.ts), keeping its footprint close to the path surface, with a small procedural fallback in Canvas2D. Both renderers use `pathAdditionGroundZ` (which includes the path walking surface) for flat and ramp path additions, with ramp props anchored at the path centre elevation; `pathAdditionBox` gives intact and vandalised variants of a prop the same rendered dimensions: 22×18 for benches, 8×11 for bins and 8×25 for lamps (the sprite bounds; the drawn size comes from the native sprite, sized against a guest in [path-additions.ts](../../tools/sprites/models/path-additions.ts): bench about 0.6, bin 0.45 and lamp 1.4 guest heights). Benches, bins, and lamps are derived from path connection flags and rendered at each unconnected edge, with the sim still storing one addition per tile; each faces the path, rotates with the edge and camera, and follows the ramp height at that edge. The same helper output drives the translucent path-addition preview, so preview and completed props share position and sizing without adding save data. `PATH_ADDITION_BROKEN` selects the vandalised furniture variants. [src/ui/track-preview.ts](../ui/track-preview.ts) uses generated ride keys for build-placement ghosts. - The [development art-coverage report](../../docs/art/coverage.md) exposes the sprite inventory and both backend paths; the Vite-only `/__art-coverage` endpoint renders it live. [tools/sprites/coverage.test.ts](../../tools/sprites/coverage.test.ts) verifies generated and prepared sprite-key availability for catalog entries, rejects ride rows with empty or missing keys, and checks fallback status when required art is missing. [canvas2d-renderer.test.ts](canvas2d-renderer.test.ts) also exercises the Canvas2D atlas path by drawing a rain shelter on a path tile. diff --git a/src/sim/rides/docs.md b/src/sim/rides/docs.md index 92677688c..d0e05d614 100644 --- a/src/sim/rides/docs.md +++ b/src/sim/rides/docs.md @@ -51,7 +51,7 @@ Path: @/src/sim/rides - `allowsWater` is ride-type capability metadata. Track command validation rejects each rotated piece footprint over open water for rides without that capability; Log Flume and River Rapids may place their track over open water. - Queue and service access are derived from the map; ordinary ride queues must reach at least one regular path tile. Stall access is re-derived from the stored facing after every map change and whenever boarding marks change, but losing it never closes the stall: guests simply stop choosing it until a footpath serves its front again. `closeInvalidOpenRides` (run on load) exempts shops for the same reason. - Flat rides and facilities publish one occupancy volume for each tile in the rotated footprint. Their current default clearance is three `Z_STEP`s above the base; track and other elevated elements can pass over them when the half-open vertical intervals leave clearance. Ride-type track clearances use authored RCT2 descriptor values converted to world units as described above; OpenRCT2's construction checks also account for track-sequence metadata. -- Consecutive station pieces are supported, and every station footprint contributes tiles where entrance and exit candidates can be placed. Any track edit invalidates the ride's tested state. +- Consecutive station pieces are supported, and every station footprint contributes tiles where entrance and exit candidates can be placed. Track can only be edited on a ride that is closed with no train out and nobody aboard: [track-commands.ts](../track/track-commands.ts) refuses edits with `RideBusy` when `isBusy` (exported from [ride-commands.ts](ride-commands.ts): open, testing, or loading/running/unloading) holds or `loadedTrips` from [coaster.ts](coaster.ts) is non-zero, so an edit never force-closes an open ride. A successful edit invalidates the ride's tested state. - Track rides dispatch and unload through the coaster system; flat rides use the regular ride phase system. A ride's phase and guest occupancy constrain when boarding points and operating settings can change. Created and maintained by Nori. @@ -59,7 +59,7 @@ Created and maintained by Nori. ### Queue lines - [queue-lines.ts](queue-lines.ts) keeps `World.queues` (derived, not saved or hashed): for every queue tile its owning ride slot and step distance from the ride entrance, and per ride the open-end tile, the ordinary path tile it joins, the queue tile count, and whether the entrance is on a queue at all. It also writes the entrance/exit marks into the map (see [map](../map/docs.md)). `refreshQueueIndex` runs at the start of every guests update and after ride commands; it rebuilds only when the marks or `pathVersion` change. A queue line belongs to the ride whose entrance it connects to by flood fill from that entrance; queue tiles reachable from no entrance are counted as orphans for the ride window warning. A ride whose entrance is an ordinary path tile (old saves) keeps the previous direct-entrance behaviour; stalls do not use the queue index at all, since guests walk to their serving path piece directly. -- [ride-boarding.ts](ride-boarding.ts) lists a ride's boarding tiles (footprint, or station tiles for track rides) and computes/stores the front edge of its entrance and exit (facing away from the ride). [boarding-front.ts](boarding-front.ts) infers fronts for placements made without one (fixtures, `placeRideEntranceExit`) and for saves before version 28, preferring the edge a queue already leaves by so existing parks stay connected. `refreshQueueIndex` fills in any gate front that is missing. A ride entered through an entrance with no queue line sends guests to the path tile in front of the entrance. +- [ride-boarding.ts](ride-boarding.ts) lists a ride's boarding tiles (footprint, or station tiles for track rides) and computes/stores the front edge of its entrance and exit (facing away from the ride). [boarding-front.ts](boarding-front.ts) infers fronts for placements made without one (fixtures, `placeRideEntranceExit`) and for saves before version 28, preferring the edge a queue already leaves by so existing parks stay connected. `refreshQueueIndex` fills in any gate front that is missing. A ride entered through an entrance with no queue line sends guests to the path tile in front of the entrance. `detachStrandedGates` runs after a track piece is removed: on a track ride, an entrance or exit with no station tile beside it any more is unplaced (its front mark cleared, the entrance's queue connection reset) while the path tile stays, so the ride needs a new one before it can open. - Line capacity (`rideQueueCapacity`): four guests per queue tile (`QUEUE_GUESTS_PER_TILE`), entrance tile included, or the operator's queue length limit (`setRideQueueLimit`, ride column `queueLimit`, 0 = none) when lower. `estimatedWaitTicks` divides the whole line (queuing plus waiting guests) into ride trips. - Line geometry: the line is the polyline through the queue tile centres from the open end to the entrance, continued one tile past the open end through the joining path tile. `queueLineCoord` gives a position's distance along it from the entrance centre (`QUEUE_SPACING` = 64 units, four to a tile); `queueLinePoint` steps a guest down it, so corners and ramps follow the chain. `rebuild` stores each tile's `down` (toward the entrance) and `up` (toward the open end) direction. `updateQueueLines` runs at the start of every guests update, orders every line's `Queuing` and `Waiting` guests by that coordinate and records per guest the coordinate of the guest ahead and its rank (`lineAhead`, `lineRank`), and per ride the last guest (`tail`); `queueEntryBlocked` holds back a joiner while the last guest is within one spacing of the join point. All of it is derived and neither saved nor hashed. - Boarding takes waiting guests in queue order: each guest's `queueSeq` is the ride's `queueSerial` counter when it joined the line, and `seatQueuedGuests` picks the lowest sequence first. diff --git a/src/sim/track/docs.md b/src/sim/track/docs.md index 3a487c3bf..d1c32e8e4 100644 --- a/src/sim/track/docs.md +++ b/src/sim/track/docs.md @@ -19,13 +19,16 @@ Path: @/src/sim/track - [catalog.ts](catalog.ts) builds immutable piece definitions and shared sampled geometry. Each piece defines entry and exit position, direction, slope and bank, height change, flags, cost, and footprint. Appended piece IDs preserve existing save references. - [geometry.ts](geometry.ts) creates integer-compatible centerline samples for straight, curved, sloped, banked, inverted, and water-drop shapes. The build controls select pieces by shape and compatible entry/exit state. -- [construction.ts](construction.ts) derives the current tail cursor, validates connection and map geometry, places/removes pieces, and detects circuit completion. For obstruction checks it turns each rotated piece-footprint cell, including its catalog support/base extent, into a world-height interval and checks it against the shared [map occupancy model](../map/docs.md). Consecutive station pieces are allowed. -- [track-commands.ts](track-commands.ts) applies ride-family and mode rules, generic geometry validation, rotated footprint water and ownership checks, and funds validation. Successful placement charges construction cost and invalidates the ride's test; removal also invalidates testing. Direct construction helpers do not apply command-only checks or charges. +- A ride's track layout is one or more sections (open chains linked by stable piece ids in `prev`/`next`) or a single closed ring. `head`/`tail` in [track-store.ts](track-store.ts) name the first and last piece of the active section, the one `getConstructionCursor` in [construction.ts](construction.ts) continues from the tail's exit. Placing a piece makes its section active; after a removal the active section is the one holding the piece before the gap, else the piece after it, else any remaining piece of the ride. +- [construction.ts](construction.ts) validates connection and map geometry and places/removes pieces. The exported `attachPoint` decides what a placement joins: the last piece of any section whose exit matches the request (preferring the active tail) and/or the first piece of any section the new piece's exit leads into. Joining both ends merges two sections, or closes a ring when they are the same section. `relinkRide` recomputes piece count and length over all sections, numbers `startS` from 0 at the start of each section (the active one first), and sets `closed` only when the active section is a ring holding every piece of the ride. +- For obstruction checks, [construction.ts](construction.ts) turns each rotated piece-footprint cell, including its catalog support/base extent, into a world-height interval and checks it against the shared [map occupancy model](../map/docs.md). Consecutive station pieces are allowed. +- `removeTrack` removes any piece of the ride; `pieceId` -1 means the last piece of the active section. Removing a middle piece splits its section in two, and removing any piece of a ring opens it there. `removeRideTrack` (ride demolition) scans every piece of the store rather than walking one chain, and `circuitStatus` counts stations over the whole ride, not just the active section. +- [track-commands.ts](track-commands.ts) applies ride-family and mode rules, generic geometry validation, rotated footprint water and ownership checks, and funds validation. Before any of that, `applyTrackCommand` refuses every place or remove with `TrackResult.RideBusy` while the ride is open or testing, mid-cycle (`isBusy` from [ride-commands.ts](../rides/ride-commands.ts)), or has loaded trains (`loadedTrips` from [coaster.ts](../rides/coaster.ts)), so an edit never force-closes a running ride. Successful placement charges construction cost and invalidates the ride's test. A successful removal invalidates the test, calls `detachStrandedGates` from [ride-boarding.ts](../rides/ride-boarding.ts) so an entrance or exit no longer beside a station is taken off the ride, and is reported as `TrackNotice.Removed` (101, in the warning code range) rather than `Ok`. The lift-into-inversion warning looks at the piece `attachPoint` would follow, not just the active tail. Direct construction helpers do not apply command-only checks or charges. - Transport rides share `TRANSPORT_PIECES` from [catalog.ts](catalog.ts): unbanked, noninverted pieces with slopes up to 25 degrees. Railway, monorail, and chairlift curves are buildable and have generated track art; banks, steep slopes, and inversions are filtered from the builder and rejected by simulation rules. - Track heights use RCT2's finer track grid: placed piece `z`, piece `dz` and `PlaceRequest.z` count track steps of `TRACK_Z_STEP` (half a land level, `TRACK_STEPS_PER_LEVEL` per level, from [core/constants.ts](../core/constants.ts)), while land, paths, water, `MAX_TRACK_LEVEL`, ride-type `maxLevel` and `CLEARANCE_UNITS` stay in whole land levels or world units. Height checks convert both sides to world units. - Piece rises in [catalog.ts](catalog.ts) are explicit RCT2 values taken from OpenRCT2's track coordinate table (`src/openrct2/ride/TrackData.cpp`), not derived from the curve: straights look up `STRAIGHT_RISE` by entry/exit slope class (flat to 25 degrees half a level, 25 degrees one level, 25 to 60 degrees two, 60 degrees four), sloped quarter turns use `SLOPED_TURN_RISE` by radius, helices climb two levels per full turn, and loops, S-bends and level corkscrews are level. `GRADE` (0.25 and 1 rise per run) only shapes the sampled profile. A straight slope pair with no RCT2 entry throws at catalog build. - Because flat-to-25-degree transitions rise half a level, any whole land-level difference between a circuit's ends is reachable by flat-to-flat track; flat pieces such as stations land on whole levels by chaining, as in RCT2. -- [track-path.ts](track-path.ts) assembles the connected piece samples into a world-space path for vehicle simulation. [track-system.ts](track-system.ts) removes track when its ride no longer exists, including after ride demolition. +- [track-path.ts](track-path.ts) assembles the active section's piece samples (head to tail) into a world-space path for vehicle simulation. Other sections are not on the path; that is harmless because trains only run on a complete circuit, where the active section is the whole ride. [track-system.ts](track-system.ts) removes track when its ride no longer exists, including after ride demolition. - [track-height-migration.ts](track-height-migration.ts) converts saves from before track steps (see [save](../../save/docs.md)): each chain's first station (or its head when it has none) keeps its world height, the rest of the chain is re-laid from it with the current rises, and `relinkRide` from [construction.ts](construction.ts) recomputes start arclengths and length. A ride with any sloped or rising piece goes through `invalidateRideTest` (closed, trains removed, must be tested again), since its stored test describes the old layout. A closed circuit whose last piece ends above or below the station after the re-lay is first healed: the last run of plain `flat` pieces long enough becomes a ramp (`flatToUp25`/`flatToDown25`, `up25`/`down25` middles, then the matching `...ToFlat`) of the missing even rise, which moves no track. A circuit that still does not meet (odd gap, no flat run) is reopened there. Reshaped closed circuits then go through [stall-repair.ts](stall-repair.ts). - [stall-repair.ts](stall-repair.ts) (`liftStalledClimbs`) runs an empty probe train round a migrated circuit using the vehicle system alone, with the same time limit as a ride test. Where the train stalls it puts a chain lift on the whole climb it died on, or, when it ran out of speed on level track, on the level run reaching that point (brakes there are replaced) and on to the next slope, then probes again, up to 24 lifts. Halving the rises costs momentum, so layouts built for the taller hills would otherwise fail their test run. @@ -37,6 +40,7 @@ Path: @/src/sim/track - Track over open water is allowed only when the ride type declares `allowsWater`; Log Flume and River Rapids are tracked water rides with that capability. Other coasters remain blocked from placing any part of a piece footprint over open water. - `WaterLift` is restricted to uphill pieces on water rides, and `ChainLift` is rejected on water rides. Ride-specific piece lists and slope, inversion, launch, and height limits are enforced at the command boundary. A scenario height cap refuses a piece with `TrackResult.HeightLimit` when any footprint cell's structure top (`zMax`, not train headroom) rises too far above that tile's ground; the cap is passed back as the blocker detail ([restrictions](../scenario/restrictions.ts)). - The generated [track coverage matrix](../../../docs/art/track-coverage.md) lists every catalog piece against each tracked ride type, including slope and bank transitions, builder restrictions, sprite availability, and the four direction-by-camera-view combinations. +- Piece ids are stable `EntityStore` ids while a piece is alive, but a freed id is reused by a later placement. Holders of a piece id across edits (the [UI selection](../../ui/docs.md)) guard it with a geometry signature rather than trusting the id alone. - Changing track invalidates `tested`, so track rides must pass another vehicle test before opening. A complete circuit also needs a station, and every station tile is considered for entrance/exit placement. - Tunnels: track may run below the terrain (`TunnelOk` pieces), but [clearance.ts](clearance.ts) finds every tile where the centre line dips under the interpolated ground (`undergroundTiles`) and the command path refuses (`TrackResult.TunnelBlocked`) a section that would pass under a ride footprint, a footpath or water. `pieceTunnelPortals` returns where a piece's centre line crosses the surface, snapped to the tile edge it crosses (within 0.4 tile), with the direction the portal faces and `valid`. A mouth is valid only on a tile edge whose two corners are level, in a tile whose opposite edge is also level and no lower and at most one level higher; corners, diagonal or sideways slopes, saddles and mid-tile crossings are invalid. `unsoundTrenchPiece` additionally refuses a piece that is not straight and lies partly below the ground without being roofed over along its whole length (a trench is cut straight). `badTunnelEntry` is true for either, and both `applyTrackCommand` and the builder's `previewStatus` refuse it as `TrackResult.TunnelEntry`. [trench.ts](trench.ts) derives, from placed pieces and terrain, the open cuts: `trenchTiles` returns a `TrenchTile` (axis, centre-line height and depth below the ground at each end, headwall flags) for every tile whose straight piece is below the ground by less than `ROOF_DEPTH` (one level less the clearance slack) at either end. A tile ends in a headwall at an end where the track is that deep; a dip that never gets that deep stays an open cutting. Nothing is stored: renderers derive it from the snapshot's track layer, so saves are unchanged. Rules use terrain levels (`Z_STEP`) and track steps (`TRACK_Z_STEP`) from [constants](../core/constants.ts), so they hold under the half-level track grid. Land edits already refuse to change ground within two levels of (or above) any track piece (`structureConflict`), which stops an edit from turning a tunnel entry into a corner entry. diff --git a/src/ui/docs.md b/src/ui/docs.md index 3b6d9264a..fe4e0df71 100644 --- a/src/ui/docs.md +++ b/src/ui/docs.md @@ -37,9 +37,12 @@ Path: @/src/ui - Ride, stall and facility pictures are drawn by [ride-preview.ts](ride-preview.ts), shared by the ride inspector and the thumbnails on the New attraction cards. A preview is a list of atlas sprites: flat rides use their whole-ride `preview/view-` sprite via [ridePreviewSpriteKey](../render/world-art.ts) (world renderers still draw them as per-tile slices so they interleave with paths, people and scenery by painter depth), stalls and toilets their `stalls/` shopfront (the facing is counter-rotated against the camera so the front always faces the viewer), and every track ride (coasters, water, transport) a short closed loop of its own track pieces with a six-car train, composed through the track art pipeline. The loop has a hill on one side whenever the ride's allowed pieces include the gentle slopes (`previewLoop`); cars are placed along the piece sample table at the simulation's car spacing and sprites are ordered by view depth. The canvas backing store is sized to its on-screen size, the art is centred on its visual bounds and drawn nearest-neighbour at a whole-number scale (capped at 3x, reduced only when the art would not otherwise fit), and CSS keeps the canvas at 2:1 so it is never stretched. Atlas pages are lazy: looking a sprite up starts its category loading, the draw reports `pending`, and the callers (the inspector every snapshot, the cards whenever `SpritePages.version` changes) redraw once the page arrives. The previews live in the DOM UI, so they are shared by WebGL2 and Canvas2D world rendering. [e2e/ride-previews.spec.ts](../../e2e/ride-previews.spec.ts) checks every card and ride window for enough opaque pixels, a clear edge band and the 2:1 ratio. - [guest-window.ts](windows/guest-window.ts) maps thought ids from guest snapshots to labels in individual guest details and the park-wide list, including needs, tired, out-of-money, and lost thoughts. Guest details also show the current happiness, hunger and thirst satisfaction, toilet need, nausea, energy, and cash values. The Carrying tab lists the balloon, hat, T-shirt, umbrella and park map the guest holds (`carriedItemsText`) above any voucher. The ride window's Financial data tab, for a stall, replaces the ticket price with one block per item ([stall-items.ts](windows/stall-items.ts): price control, worth to guests today, items sold, sales and profit). The Rides tab remains a placeholder because the simulation stores only a guest's last ride and total rides taken, not a full trip list. - [title-screen.ts](title-screen.ts) formats the selected scenario's objective summary for the preview. Dated objectives show their target and a deadline derived from the objective tick; Have Fun is explicitly open-ended and skips deadline calculation. Monthly-income goals use dedicated labels for monthly ride-ticket income and food/drink profit; other previews enumerate the selected ledger categories, such as admission, ride running and wages. The summary covers the current objective kinds, including ride-count, qualifying-coaster, complete-coaster and best-ride goals. `scenarioRulesText` adds a "Park rules: ..." line (`.scenario-rules`) built from `restrictionLines`; the Park window's Objectives tab lists the same rules under the objective. `scenarioTerrainLines` turns the scenario's optional `landscape` and `challenge` strings into "Terrain: ..." and "Challenge: ..." lines (`.scenario-terrain`); the selected-park preview shows both, while each scenario card shows only the first. -- [coaster-panel.ts](coaster-panel.ts) is the Ride construction window: shape, slope and bank icon buttons, a Special elements dropdown, drive select, start direction and Lower start / Raise start (shown only before the first piece; one land level per press, from the ground up to `MAX_START_RAISE`), a `Track end at height N` line once track exists, Build piece / Demolish last piece, Track / Entrance / Exit modes, Test / Open / Close, and the ride readout. Its compact control layout keeps Build piece visible at desktop and phone sizes. Once a circuit closes, it advances into entrance and exit placement before returning to track construction. It opens while the track tool is active; selecting 4× speed while that tool is active is capped to 2×. Snapshot cursor heights arrive in track steps; the panel divides by `TRACK_STEPS_PER_LEVEL`, so `TrackGhost.level` is in land levels and can be a half level (e.g. 4.5), which the `track at N` height readout and the construction marker label show as is. The first piece is placed at the hovered ground height plus the start raise, converted to track steps. +- [coaster-panel.ts](coaster-panel.ts) is the Ride construction window: shape, slope and bank icon buttons, a Special elements dropdown, drive select, start direction and Lower start / Raise start (shown only before the first piece; one land level per press, from the ground up to `MAX_START_RAISE`), a `Track end at height N` line once track exists, Build piece / Demolish last piece, the piece selection controls described below, Track / Entrance / Exit modes, Test / Open / Close, and the ride readout. Its compact control layout keeps Build piece visible at desktop and phone sizes. Once a circuit closes, it advances into entrance and exit placement before returning to track construction. It opens while the track tool is active; selecting 4× speed while that tool is active is capped to 2×. Snapshot cursor heights arrive in track steps; the panel divides by `TRACK_STEPS_PER_LEVEL`, so `TrackGhost.level` is in land levels and can be a half level (e.g. 4.5), which the `track at N` height readout and the construction marker label show as is. The first piece is placed at the hovered ground height plus the start raise, converted to track steps. +- The construction window keeps an optional selected piece (`selectPiece(rideId, pieceId)`, `selectedPiece()`, `clearSelection()`), held only in [coaster-panel.ts](coaster-panel.ts) as editor state and never saved. Selecting never changes track; it moves where Build piece and Demolish act. Selecting a piece of another coaster makes that ride active, and switching rides clears the selection. The selection row shows `Selected piece N of M · label` and offers Previous piece / Next piece (with nothing selected, Previous picks the piece at the construction cursor), Track end (back to building at the active section's end), and Build before this piece, a toggle shown only when the piece has no previous piece. Build piece then places at the selection's chosen open end; a piece joined on both sides can only be demolished. Demolish becomes `Demolish selected piece` and sends the piece's id. +- The selection follows the player's edits through pending markers reconciled on each snapshot: after a build from the selection, the new piece is selected (keeping the build direction) unless the circuit just closed, which clears it; after a demolition, the removed piece's previous neighbour, else its next, is selected. A selected piece that vanished for any other reason clears the selection with a notice. Because freed piece ids are reused ([track](../sim/track/docs.md)), the selection stores a geometry signature (type, position, direction) and treats a mismatch as gone. A refused command drops the pending markers. `buildsTrack()` reports whether the window is in Track mode (not entrance or exit placement), which the [build tool](../app/tools/docs.md) checks before treating a click as a selection. While the ride is open, testing or mid-cycle the cost line says to close it and wait for the train; the simulation refuses the edit with `RideBusy` either way. +- [track-selection.ts](track-selection.ts) holds the pure snapshot helpers behind the selection, read from `Snapshot.trackLinks` ([worker](../worker/docs.md)): `snapshotPiece` (a piece by stable id, or null), `neighbourPiece`, `sectionPosition` (1-based position for display; in a ring counted from the first station piece), `openEnds`, `buildPointAt` (the entry or exit a new piece must meet) and `resolveBuild`, which maps the controls to a piece and placement at an end. Building before a piece uses `resolvePieceBefore` from [track-tool.ts](track-tool.ts), where the slope and bank controls set the new piece's entry and its exit must match the section's first piece, and the placement is worked back from that piece's origin. - [shortcuts.ts](shortcuts.ts) maps the default keys: window closing, cancel, pause, game speed (number keys and +/-), zoom (Page Up/Down), camera rotation (Enter/Shift+Enter, Z/X), Q to dismiss a message, U for the underground view, T to rotate the ride, stall, wall or scenery being placed (`rotatePiece`, which ride setup handles first), and the window keys (F1-F5, F/D/R/P/G/S/M, Tab). Options > Controls describes the message-dismiss action and T, including that a stall serves only from its window side. While Footpaths is open in Piece by piece mode, U/L/D select Up/Level/Down before default shortcuts are dispatched. [zoom.ts](zoom.ts) holds the four-level discrete zoom ladder used by the toolbar, Page Up/Down, wheel steps and pinch gestures. -- [track-tool.ts](track-tool.ts) is pure logic (`resolvePiece`, `allowedModes`, `previewStatus`, `footprintTiles`, `feedbackMessage`, whose ride messages include the stall storefront reasons); `resolvePiece` applies ride allowlists and steep-slope/inversion rules when given a ride type. Without a ride type, it leaves the generic track palette unrestricted. Transport rides allow generated unbanked pieces, including the small turns used by normal circuits, and block pieces without atlas coverage. `previewStatus` takes the snapshot's height cap and reports `TrackResult.HeightLimit` with the same per-tile ground rule as the sim, and [placement-art.ts](../render/placement-art.ts) `ridePlacementValid` does the same for flat-ride ghosts, so a ghost shown as valid is accepted. [track-preview.ts](track-preview.ts) draws the flat-ride ghost over the whole rotated footprint (one outline per tile plus the ride's per-tile art slices, with T or the Rotate ride button turning it); it also draws the placement ghost. +- [track-tool.ts](track-tool.ts) is pure logic (`resolvePiece`, `allowedModes`, `previewStatus`, `footprintTiles`, `feedbackMessage`, whose ride messages include the stall storefront reasons); `resolvePiece` applies ride allowlists and steep-slope/inversion rules when given a ride type. Without a ride type, it leaves the generic track palette unrestricted. Transport rides allow generated unbanked pieces, including the small turns used by normal circuits, and block pieces without atlas coverage. `previewStatus` takes the snapshot's height cap and reports `TrackResult.HeightLimit` with the same per-tile ground rule as the sim, and [placement-art.ts](../render/placement-art.ts) `ridePlacementValid` does the same for flat-ride ghosts, so a ghost shown as valid is accepted. [track-preview.ts](track-preview.ts) draws the flat-ride ghost over the whole rotated footprint (one outline per tile plus the ride's per-tile art slices, with T or the Rotate ride button turning it); it also draws the placement ghost, remembers the screen quads of the ghost's tiles, and `TrackPreviewOverlay.hits(x, y)` reports whether a viewport point lies on them so clicks on the ghost still build. `feedbackMessage` words `TrackNotice.Removed` as a successful "Track piece removed." and `RideBusy` as a request to close the ride and wait for its train. - [icons.ts](icons.ts) maps all UI icon IDs to generated 16px or 24px pixel-art assets. [ui.css](ui.css) holds the interface styles, including pixelated scaling, pressed bevels and disabled grayscale states. ### Things to Know @@ -48,13 +51,14 @@ Path: @/src/ui - Staff windows list workers by role and open individual worker details, with role-specific task-order controls (handymen: sweep paths, empty bins, water gardens, mow grass) and a Statistics tab showing wage, the month hired and the role's activity totals (lawns mown, gardens watered, litter swept, bins emptied; rides inspected and fixed; vandals stopped; guests entertained). Each worker window opens that person's patrol editor and offers Pick up; the map overlay displays that worker's 4×4-tile patrol blocks while editing. The Staff window's Remove tiles toggle uses shared alternate-action state, and its pressed state is restored when the window is reopened. Guest detail windows also offer Pick up; guests on rides or in queues cannot be moved. - Footpath removal refunds the piece's cost. It works with the tool toggle, alternate click, context click, or a 900 ms touch hold. - Desktop windows can be resized. Mobile uses bottom sheets and keeps touch targets at least 44 px. Options are grouped into Game, Sound, Messages, Display, and Controls; sound and music volumes and mute are available, while view-filter effects and shortcut reassignment remain unimplemented. Message categories are award, ride, park and guest, matching the event types currently generated by [news.ts](news.ts); category filtering happens when messages are first observed, before they enter history or the ticker queue. Changing a category later does not remove messages already recorded in history or already queued. Ctrl+S downloads the canvas as a PNG. The UI specification leaves exact message colors unresolved; the six-second ticker lifetime is the current implementation and is not claimed as exact RCT2 behavior. -- Deferred from docs/fidelity/ui.md: view overlays (underground, see-through, and height marks; keys 1, 3-6, 8-0, H, V) remain unavailable; guest ride-summary details beyond four recent rides; worker uniform colors; shortcut reassignment; and exact ticker colors remain deferred. Ticker timing is currently six seconds, but is not claimed as exact RCT2 behavior. Enter rotates the view, so building a track piece uses the Build piece button; Delete demolishes the last piece. +- Deferred from docs/fidelity/ui.md: view overlays (underground, see-through, and height marks; keys 1, 3-6, 8-0, H, V) remain unavailable; guest ride-summary details beyond four recent rides; worker uniform colors; shortcut reassignment; and exact ticker colors remain deferred. Ticker timing is currently six seconds, but is not claimed as exact RCT2 behavior. Enter rotates the view, so building a track piece uses the Build piece button; Delete demolishes the selected piece, or the last piece when nothing is selected. - Tool status text reports that a placement was requested. The authoritative outcome arrives in `Snapshot.feedback`, which the panel shows via `feedbackMessage` when `seq` changes, including the research-required result when a locked ride type is submitted. Footpath, Land, Clear scenery and Water rejections also mark the refused tile and show the reason at the cursor (see [app tools](../app/tools/docs.md)); other map-command rejections remain silent. - The placement preview is a client-side approximation using the snapshot (bounds, ownership via `buildable`, funds); the simulation result is authoritative and may differ. - Ownership, ride-type rules and funds are enforced by the simulation's track command handler, not by the UI. - Staff roster identity is matched with stable staff IDs from snapshots; player names travel by ID, while role and position come from the current staff layer. Generated ride and staff labels display the internal zero-based IDs as one-based numbers, while the IDs themselves remain unchanged; a saved custom staff name takes precedence over its generated label. Ground and flower-bed state is carried in per-tile snapshot data, but is not currently drawn by the UI. - The ride window's main View tab presents a captioned bulldozer Demolish control for every ride, including stalls and coasters. Its tooltip names the action, and confirmation displays the ride name and exact current refund from `RideInfo.DemolitionRefund`. Ride controls request price, open/close, test, demolition, and entrance/exit placement commands; the simulation remains authoritative. Setup blockers offer direct actions to place a boarding point or build the queue; stalls and facilities show a "Turn stall" button in place of the entrance/exit buttons, which starts [ride setup](../app/ride-setup/docs.md)'s turn targets; a stall whose `RideInfo.StallFront` is not `Ok` shows the specific reason (no path, queue line, ride exit, wrong level, ramp across the window, unowned land, map edge) with a Build path action: an entrance with no queue or path, a queue line whose open end is not on a path, and (while a ride has no entrance) queue tiles linked to no ride entrance each get a row, and "Build queue" opens Footpaths with Queue line on and the entrance highlighted. The View tab shows the line as `guests of capacity`, the estimated wait, and a queue limit control. Queue connection is derived by the simulation from the queue line and refreshed when paths change. Turning Queue line on explains queue lines in the status line, and the Footpaths window keeps its Queue line toggle in step with the tool state. +- Track rides show Edit track in the ride window, plus Edit from this piece when the window was opened by clicking one of the ride's rails: `GameUI.openRide(rideId, pieceId)` remembers the clicked piece per ride (opening without one forgets it), `UiContext.clickedTrackPiece(rideId)` exposes it, and the button calls `editTrack(rideId, pieceId)` so the construction window opens with that piece selected. - `Snapshot` storage is owned by [SimClient](../worker/sim-client.ts) and may be transferred or recycled by the worker protocol. UI event handlers therefore use controller state refreshed from the current frame rather than retaining or exposing a cached snapshot; the ride window caches its locate coordinates from its latest update. - The ride list keeps row elements keyed by ride id and updates displayed values only when they change, preserving row identity and avoiding repeated DOM writes while simulation values are stable. - Game speed and pause controls affect the worker through [SimClient](../worker/sim-client.ts); rendering and panel refresh continue on the browser animation frame loop. While paused, construction commands apply immediately and publish updated map/snapshot data without advancing simulation time or running systems. This is an intentional departure from RCT2, whose [manual](https://cdn.akamai.steamstatic.com/steam/apps/285330/manuals/manual.pdf#page=7) says construction is unavailable while paused. diff --git a/src/worker/docs.md b/src/worker/docs.md index dccd6acdc..6db271308 100644 --- a/src/worker/docs.md +++ b/src/worker/docs.md @@ -33,12 +33,13 @@ Path: @/src/worker - `rideInfo` carries `RIDE_INFO_STRIDE` ints per ride in ride-layer order: stable ID, type/state/phase, ratings, queue length, placement/test flags, guests served, price, track piece count, construction cursor (`CursorX`/`CursorY` tile and `CursorZ` height in track steps, half a land level), entrance/exit tiles, reliability, lifetime income in cents, the ride's footprint anchor tile (`RideX`/`RideY`), its current demolition refund, its orientation in quarter turns (`Dir`) and, for flat rides, the floor height level (`BaseLevel`: the highest ground corner under the footprint), its queue tile count, estimated wait in ticks, line capacity and queue limit, then rolling downtime percent (`Downtime`), the inspection interval in minutes (`InspectionMinutes`, 0 = never), minutes since the last inspection (`MinutesSinceInspection`) and the derived `MechanicStatus` (see the [rides module](../sim/rides/docs.md)). `PhaseProgress` is the permille of the Running phase already elapsed (0 in other phases); renderers spread long ride animation profiles, such as the Swinging Ship pose sequence, across it. `TrainsSet`, `CarsSet`, `MaxTrains`, `MaxCars`, and `Capacity` report the configured train layout, its track/station limits, and the resulting guests per dispatch. `StallFront` is the `RideResult` explaining why guests cannot buy from a stall's or facility's window (`Ok` when they can, and for every other ride), computed with the simulation's own `stallSlotProblem`; for stalls `Dir` is the service-window direction and `EntrancePlaced` means the front serves guests (see [rides](../sim/rides/docs.md#stall-storefronts)). `RideFlag.HasQueue` marks a ride entered through a built queue; `park.orphanQueueTiles` counts queue tiles no ride owns. Guest rows carry an idle bit for standing guests. Refund calculation is shared with the simulation's demolition command through [ride-refund.ts](../sim/rides/ride-refund.ts). Cursor direction, slope, bank, and track presence are packed with `encodeCursor` / `decodeCursor`. - The ride row also carries kiosk/stall second price and per-item sales counters. Guest metadata bits 11–13 select balloon, hat, and rain-umbrella overlays; the final `guestDetails` word carries the full set of items visible in the guest window. - `TowerHeight` and `TowerCabinLevel` ride-info values carry Observation Tower height (land levels) and cabin height in thousandths of a level, computed in the worker by `observationTowerCabinMilli` from elapsed ticks, including stranded and returning cabins; renderers and previews read the value rather than recomputing the motion. +- `trackLinks` is an `Int32Array` with `TRACK_LINK_STRIDE` (3) ints per `tracks` row, in the same row order: the piece's stable id, then its previous and next piece ids (-1 = none). It lets the main thread name, step through and outline individual pieces (coaster rendering, picking and the [construction window selection](../ui/docs.md)) without reaching into the world. - `feedback` copies `world.feedback` (`seq`, `domain`, `code`, `subject`) so the UI can show the outcome of its latest command. - Successful build and demolition commands append monotonically identified events to the world's transient audio-event queue. Snapshot publication copies and clears that queue; event ids let the audio consumer ignore cues already observed when snapshots are repeated or recycled. ### Things to Know -- Snapshot buffers, including patrol masks, staff patrol IDs, the track-piece layer, and per-tile `buildable` array, are transferred rather than copied. The map message's ownership and terrain arrays are also transferred. After transfer, the sender's typed-array backing buffers are detached until the client returns snapshot buffers in a recycle message; map data is independently re-extracted when the map revision changes. +- Snapshot buffers, including patrol masks, staff patrol IDs, the track-piece layer and its `trackLinks`, and per-tile `buildable` array, are transferred rather than copied. The map message's ownership and terrain arrays are also transferred. After transfer, the sender's typed-array backing buffers are detached until the client returns snapshot buffers in a recycle message; map data is independently re-extracted when the map revision changes. - Three snapshots are pooled. The pool is sized for the largest map seen so far and grows only when a larger map arrives; recycled buffers smaller than the current pool are dropped. If none is free after simulation ticks advance, publication is skipped so the simulation can continue while the main thread catches up. - A new game or a load replaces the running `Simulation` in the same worker. The pool and the scheduler's speed and pause state carry over, so the player's settings survive a new game. - Ride rendering entries expose stable IDs rather than ride state or type. The UI uses these IDs to associate track pieces with a ride; ride type and operating state remain in the simulation state. From a70d354af08609a4f128e0f7b331a00f8445592b Mon Sep 17 00:00:00 2001 From: "nori-sessions[bot]" <264258699+nori-sessions[bot]@users.noreply.github.com> Date: Mon, 2 Nov 2026 08:11:30 +0000 Subject: [PATCH 4/4] Keep the selection after warned placements; cheaper selection lookups; first piece of a new coaster may go beside other track MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 🤖 Generated with [Nori](https://noriagentic.com) Co-Authored-By: Nori --- src/app/tools/index.ts | 2 +- src/app/tools/track-selection-outline.ts | 13 +++++---- src/input/object-picking.test.ts | 10 +++++-- src/sim/rides/track-edit-safety.test.ts | 6 ++-- src/sim/track/track-editing.test.ts | 35 ++++++++++++++---------- src/ui/coaster-panel.ts | 33 ++++++++++++++++------ src/ui/track-selection.test.ts | 12 ++++++++ src/ui/track-selection.ts | 21 ++++++++++---- src/ui/track-tool.test.ts | 20 +++++++++++++- src/ui/track-tool.ts | 11 ++++++++ 10 files changed, 122 insertions(+), 41 deletions(-) diff --git a/src/app/tools/index.ts b/src/app/tools/index.ts index 18a6e3134..537fbe397 100644 --- a/src/app/tools/index.ts +++ b/src/app/tools/index.ts @@ -678,7 +678,7 @@ export function createToolController(deps: ToolControllerDependencies) { rect: DOMRect, ): void { const snapshot = deps.sim.latest; - if (snapshot && deps.coasterPanel.buildsTrack() && !deps.trackGhostAt(localX, localY)) { + if (snapshot && deps.coasterPanel.picksPieces() && !deps.trackGhostAt(localX, localY)) { const targets = deps.renderer.objectTargets(snapshot, deps.camera, { width: rect.width, height: rect.height, diff --git a/src/app/tools/track-selection-outline.ts b/src/app/tools/track-selection-outline.ts index 51033b3d4..1ba3899ae 100644 --- a/src/app/tools/track-selection-outline.ts +++ b/src/app/tools/track-selection-outline.ts @@ -12,6 +12,8 @@ export class TrackSelectionOutline { private readonly canvas: HTMLCanvasElement; private key = ''; private origin = { x: 0, y: 0 }; + /** Whether the selected piece had any rail sprite in view when the outline was last drawn. */ + private visible = false; constructor(parent: HTMLElement) { this.canvas = document.createElement('canvas'); @@ -53,12 +55,13 @@ export class TrackSelectionOutline { const targets = renderer .objectTargets(snapshot, camera, viewport) .filter((target) => target.coasterPart === 'track' && target.pieceId === piece.id); - if (targets.length === 0) { - this.canvas.hidden = true; - return; - } - this.origin = drawSpriteOutline(this.canvas, targets); this.key = key; + this.visible = targets.length > 0; + if (this.visible) this.origin = drawSpriteOutline(this.canvas, targets); + } + if (!this.visible) { + this.canvas.hidden = true; + return; } this.canvas.style.left = `${rect.left + this.origin.x}px`; this.canvas.style.top = `${rect.top + this.origin.y}px`; diff --git a/src/input/object-picking.test.ts b/src/input/object-picking.test.ts index 624e26f0a..0ea00b510 100644 --- a/src/input/object-picking.test.ts +++ b/src/input/object-picking.test.ts @@ -133,12 +133,18 @@ describe('track piece picking', () => { const upper = sprite({ coasterPart: 'track', pieceId: 9, - sortDepth: 1, + sortDepth: 2, alpha: Uint8Array.of(0, 255, 0, 0), }); const tree = sprite({ id: 'scenery:1', kind: 'scenery', rideId: undefined, sortDepth: 5 }); - expect(pickTrackPiece([lower, upper, tree], 11.5, 10.5)).toEqual({ rideId: 3, pieceId: 9 }); + expect( + pickTrackPiece( + [upper, lower, tree].sort((a, b) => a.sortDepth - b.sortDepth), + 11.5, + 10.5, + ), + ).toEqual({ rideId: 3, pieceId: 9 }); expect(pickTrackPiece([lower, upper, tree], 10.5, 10.5)).toEqual({ rideId: 3, pieceId: 4 }); expect(pickTrackPiece([tree], 10.5, 10.5)).toBeNull(); }); diff --git a/src/sim/rides/track-edit-safety.test.ts b/src/sim/rides/track-edit-safety.test.ts index 86557b17e..3438b7dc9 100644 --- a/src/sim/rides/track-edit-safety.test.ts +++ b/src/sim/rides/track-edit-safety.test.ts @@ -123,6 +123,7 @@ describe('editing a built coaster from a chosen piece', () => { queueGuests(sim, rideId, 12); for (let i = 0; i < 2000 && sim.world.vehicles.cols.state[0] !== VehicleState.Running; i++) sim.step(); + expect(sim.world.vehicles.cols.state[0]).toBe(VehicleState.Running); command(sim, { type: 'setRideStatus', rideId, status: 'close' }); const riders = sim.world.vehicles.cols.passengers[0]; const servedBefore = sim.world.rides.cols.guestsServed[slot]; @@ -134,6 +135,7 @@ describe('editing a built coaster from a chosen piece', () => { for (let i = 0; i < 4000 && sim.world.rides.cols.phase[slot] !== RidePhase.Closed; i++) sim.step(); + expect(sim.world.rides.cols.phase[slot]).toBe(RidePhase.Closed); command(sim, { type: 'removeTrack', rideId, pieceId: built[6].id }); expect(trackFeedback(sim)).toBe(TrackNotice.Removed); expect(sim.world.rides.cols.guestsServed[slot]).toBe(servedBefore + riders); @@ -141,9 +143,9 @@ describe('editing a built coaster from a chosen piece', () => { it('refuses edits during a test run', () => { const { sim, rideId, built } = testedCoaster(); - command(sim, { type: 'setRideStatus', rideId, status: 'test' }); + command(sim, { type: 'removeTrack', rideId, pieceId: built[6].id }); command(sim, built[6].command); - expect(trackFeedback(sim)).toBe(TrackResult.RideBusy); + command(sim, { type: 'setRideStatus', rideId, status: 'test' }); command(sim, { type: 'removeTrack', rideId, pieceId: built[6].id }); expect(trackFeedback(sim)).toBe(TrackResult.RideBusy); expect(circuitStatus(sim.world, rideId).complete).toBe(true); diff --git a/src/sim/track/track-editing.test.ts b/src/sim/track/track-editing.test.ts index 5cc54206b..00777d804 100644 --- a/src/sim/track/track-editing.test.ts +++ b/src/sim/track/track-editing.test.ts @@ -52,6 +52,11 @@ function append(w: World, ride: number, name: string): Built { }); } +/** Removes a piece, expecting the removal to succeed. */ +function remove(w: World, ride: number, id: number): void { + expect(removeTrack(w, ride, id)).toBe(TrackResult.Ok); +} + function chain(w: World, ride: number, names: readonly string[]): Built[] { return names.map((name) => append(w, ride, name)); } @@ -113,9 +118,9 @@ describe('editing track from a chosen piece', () => { it('accepts a different shape in a gap but closes the circuit only where it meets the far side', () => { const built = chain(w, ride, RING); - removeTrack(w, ride, built[9].id); - removeTrack(w, ride, built[4].id); - removeTrack(w, ride, built[5].id); + remove(w, ride, built[9].id); + remove(w, ride, built[4].id); + remove(w, ride, built[5].id); const rise = place(w, { ...built[4].req, pieceType: pieceByName('flatToUp25')!.id }); const level = place(w, { ...built[5].req, @@ -125,8 +130,8 @@ describe('editing track from a chosen piece', () => { place(w, built[9].req); expect(circuitStatus(w, ride)).toMatchObject({ closed: false, pieces: 14 }); - removeTrack(w, ride, level.id); - removeTrack(w, ride, rise.id); + remove(w, ride, level.id); + remove(w, ride, rise.id); place(w, built[4].req); expect(circuitStatus(w, ride).closed).toBe(false); place(w, built[5].req); @@ -136,8 +141,8 @@ describe('editing track from a chosen piece', () => { it('joins separate sections when the gaps between them are filled in any order', () => { const built = chain(w, ride, ['station', 'flat', 'flat', 'flat', 'flat', 'flat', 'flat']); const end = getConstructionCursor(w, ride); - removeTrack(w, ride, built[2].id); - removeTrack(w, ride, built[5].id); + remove(w, ride, built[2].id); + remove(w, ride, built[5].id); expect(circuitStatus(w, ride).pieces).toBe(5); place(w, built[2].req); @@ -151,8 +156,8 @@ describe('editing track from a chosen piece', () => { it('builds backward onto the start of the section after a gap', () => { const built = chain(w, ride, ['station', 'flat', 'flat', 'flat', 'flat', 'flat']); - removeTrack(w, ride, built[2].id); - removeTrack(w, ride, built[3].id); + remove(w, ride, built[2].id); + remove(w, ride, built[3].id); place(w, built[3].req); expect(circuitStatus(w, ride).pieces).toBe(5); @@ -164,7 +169,7 @@ describe('editing track from a chosen piece', () => { it('only accepts new pieces that meet an open end', () => { const built = chain(w, ride, ['station', 'flat', 'flat', 'flat']); - removeTrack(w, ride, built[1].id); + remove(w, ride, built[1].id); expect(validatePlacement(w, { ...built[1].req, y: 30 })).toBe(TrackResult.NotConnected); expect(validatePlacement(w, { ...built[1].req, dir: 1 })).toBe(TrackResult.NotConnected); expect(validatePlacement(w, built[1].req)).toBe(TrackResult.Ok); @@ -172,7 +177,7 @@ describe('editing track from a chosen piece', () => { it('keeps demolishing backward from the gap with the default end removal', () => { const built = chain(w, ride, ['station', 'flat', 'flat', 'flat', 'flat']); - removeTrack(w, ride, built[3].id); + remove(w, ride, built[3].id); expect(removeTrack(w, ride, -1)).toBe(TrackResult.Ok); expect(w.track.pieces.isAlive(built[2].id)).toBe(false); expect(w.track.pieces.isAlive(built[4].id)).toBe(true); @@ -181,7 +186,7 @@ describe('editing track from a chosen piece', () => { it('removes the first and the last piece of a section', () => { const built = chain(w, ride, ['station', 'flat', 'flat', 'flat', 'flat']); - removeTrack(w, ride, built[2].id); + remove(w, ride, built[2].id); expect(removeTrack(w, ride, built[3].id)).toBe(TrackResult.Ok); expect(removeTrack(w, ride, built[4].id)).toBe(TrackResult.Ok); expect(removeTrack(w, ride, built[0].id)).toBe(TrackResult.Ok); @@ -193,7 +198,7 @@ describe('editing track from a chosen piece', () => { it('refuses a piece that was already removed', () => { const built = chain(w, ride, ['station', 'flat', 'flat']); - removeTrack(w, ride, built[1].id); + remove(w, ride, built[1].id); expect(removeTrack(w, ride, built[1].id)).toBe(TrackResult.NoSuchPiece); expect(circuitStatus(w, ride).pieces).toBe(2); }); @@ -215,8 +220,8 @@ describe('editing track from a chosen piece', () => { it('saves and restores a track split into sections', () => { const built = chain(w, ride, RING); - removeTrack(w, ride, built[3].id); - removeTrack(w, ride, built[9].id); + remove(w, ride, built[3].id); + remove(w, ride, built[9].id); const copy = deserialize(serialize(w)); expect(hashWorld(copy)).toBe(hashWorld(w)); expect(placeTrack(copy, built[3].req)).toBe(TrackResult.Ok); diff --git a/src/ui/coaster-panel.ts b/src/ui/coaster-panel.ts index bade80f72..b83fe9b04 100644 --- a/src/ui/coaster-panel.ts +++ b/src/ui/coaster-panel.ts @@ -8,7 +8,13 @@ import { RidePhase } from '../sim/rides/ride-store'; import { Bank, PieceMode, Slope } from '../sim/track/track-types'; import { TrackResult } from '../sim/track/track-types'; import type { TrackPieceDef } from '../sim/track/track-types'; -import { RideFlag, RideInfo, RIDE_INFO_STRIDE, decodeCursor } from '../worker/snapshot'; +import { + RideFlag, + RideInfo, + RIDE_INFO_STRIDE, + TRACK_LINK_STRIDE, + decodeCursor, +} from '../worker/snapshot'; import type { Snapshot } from '../worker/snapshot'; import type { ToolMode } from './ui-types'; import { element as el } from './dom'; @@ -21,6 +27,7 @@ import { SLOPE_LABELS, TURN_LABELS, allowedModes, + editRefused, feedbackMessage, previewStatus, resolvePiece, @@ -392,9 +399,16 @@ export class CoasterPanel { return `Selected ${pieceLabel(piece)}, piece ${position.index + 1} of ${position.count}.`; } - /** True while the construction controls build track (not an entrance or exit). */ - buildsTrack(): boolean { - return this.buildMode === 'track'; + /** + * Whether a click on placed track should select a piece: while building track (not an entrance + * or exit), except for a coaster with no track yet, whose first piece may go beside other rides. + */ + picksPieces(): boolean { + const ride = this.activeRide(); + return ( + this.buildMode === 'track' && + (!ride || decodeCursor(this.infoAt(ride)[RideInfo.Cursor]).hasTrack) + ); } /** The selected piece, for highlighting, while the construction window is open. */ @@ -447,13 +461,14 @@ export class CoasterPanel { const info = this.infoAt(ride); if (!snapshot || !decodeCursor(info[RideInfo.Cursor]).hasTrack) return -1; for (let row = 0; row < snapshot.tracks.count; row++) { - const piece = snapshotPiece(snapshot, snapshot.trackLinks[row * 3]); - if (!piece || piece.rideId !== ride.id) continue; + const piece = snapshotPiece(snapshot, snapshot.trackLinks[row * TRACK_LINK_STRIDE]); + if (!piece || piece.rideId !== ride.id || piece.next >= 0) continue; const exit = pieceExit(piece.pieceType, piece.x, piece.y, piece.z, piece.dir); if ( exit.x === info[RideInfo.CursorX] && exit.y === info[RideInfo.CursorY] && - exit.z === info[RideInfo.CursorZ] + exit.z === info[RideInfo.CursorZ] && + exit.dir === decodeCursor(info[RideInfo.Cursor]).dir ) return piece.id; } @@ -751,8 +766,8 @@ export class CoasterPanel { this.feedbackLine.textContent = line.text; this.feedbackLine.dataset.ok = String(line.ok); this.actions.status(line.text); - if (!line.ok) { - this.awaitingCreate = false; + if (!line.ok) this.awaitingCreate = false; + if (editRefused(feedback.domain, feedback.code)) { this.pendingFollow = null; this.pendingRemoval = null; } diff --git a/src/ui/track-selection.test.ts b/src/ui/track-selection.test.ts index bf3578986..b7757cd9a 100644 --- a/src/ui/track-selection.test.ts +++ b/src/ui/track-selection.test.ts @@ -116,6 +116,18 @@ describe('construction from a selected piece', () => { expect(openEnds(snapshotPiece(s, order[3])!)).toEqual([]); }); + it('numbers the pieces of a ring without a station from a fixed piece', () => { + const { w, ride } = world(); + chain(w, ride, ['flat', 'smallRight', 'smallRight', 'flat', 'smallRight', 'smallRight']); + const order = ids(w); + const s = snap(w); + const positions = order.map((id) => sectionPosition(s, id).index); + expect(new Set(positions).size).toBe(order.length); + expect(sectionPosition(s, order[2]).index).toBe( + (sectionPosition(s, order[1]).index + 1) % order.length, + ); + }); + it('offers the open ends of the pieces either side of a gap', () => { const { w, ride } = world(); chain(w, ride, ['station', 'flat', 'flat', 'flat', 'flat']); diff --git a/src/ui/track-selection.ts b/src/ui/track-selection.ts index acd2a993a..990f188f0 100644 --- a/src/ui/track-selection.ts +++ b/src/ui/track-selection.ts @@ -43,12 +43,20 @@ export interface BuildChoice { placement: { x: number; y: number; z: number; dir: number }; } +/** Track row of each piece id, rebuilt once per published snapshot revision. */ +const rowIndex = new WeakMap }>(); + function rowOf(snapshot: Snapshot, pieceId: number): number { if (pieceId < 0) return -1; - const links = snapshot.trackLinks; - for (let row = 0; row < snapshot.tracks.count; row++) - if (links[row * TRACK_LINK_STRIDE] === pieceId) return row; - return -1; + let index = rowIndex.get(snapshot); + if (!index || index.revision !== snapshot.revision) { + const rows = new Map(); + for (let row = 0; row < snapshot.tracks.count; row++) + rows.set(snapshot.trackLinks[row * TRACK_LINK_STRIDE], row); + index = { revision: snapshot.revision, rows }; + rowIndex.set(snapshot, index); + } + return index.rows.get(pieceId) ?? -1; } /** The piece with this stable id in the snapshot, or null when it no longer exists. */ @@ -98,10 +106,11 @@ export function sectionPosition( const loop = [pieceId, ...ahead]; const isStation = (id: number): boolean => PIECES[snapshotPiece(snapshot, id)!.pieceType]?.shape === 'station'; - const start = loop.findIndex( + let start = loop.findIndex( (id, k) => isStation(id) && !isStation(loop[(k + loop.length - 1) % loop.length]), ); - return { index: (loop.length - Math.max(0, start)) % loop.length, count: loop.length, ring }; + if (start < 0) start = loop.indexOf(Math.min(...loop)); + return { index: (loop.length - start) % loop.length, count: loop.length, ring }; } let index = 0; for (let id = neighbourPiece(snapshot, pieceId, 'previous'); id >= 0; index++) diff --git a/src/ui/track-tool.test.ts b/src/ui/track-tool.test.ts index e32a34f21..821efc6ff 100644 --- a/src/ui/track-tool.test.ts +++ b/src/ui/track-tool.test.ts @@ -1,11 +1,19 @@ import { describe, expect, it } from 'vitest'; import { PIECES, PieceId } from '../sim/track/catalog'; -import { Bank, PieceMode, Slope, TrackResult } from '../sim/track/track-types'; +import { + Bank, + PieceMode, + Slope, + TrackNotice, + TrackResult, + TrackWarning, +} from '../sim/track/track-types'; import { RIDE_CATALOG, RideType } from '../sim/rides/ride-types'; import { TURN_LABELS, allowedModes, classifyPiece, + editRefused, feedbackMessage, footprintTiles, MODE_LABELS, @@ -301,3 +309,13 @@ describe('previewStatus under a scenario height cap', () => { expect(at(17)).toBe(TrackResult.Ok); }); }); + +describe('track edit refusals', () => { + it('treats a placement that came with a warning as built, and refusals as not built', () => { + expect(editRefused(FeedbackDomain.Track, TrackWarning.LiftIntoInversion)).toBe(false); + expect(editRefused(FeedbackDomain.Track, TrackNotice.Removed)).toBe(false); + expect(editRefused(FeedbackDomain.Track, TrackResult.Ok)).toBe(false); + expect(editRefused(FeedbackDomain.Track, TrackResult.RideBusy)).toBe(true); + expect(editRefused(FeedbackDomain.Track, TrackResult.Blocked)).toBe(true); + }); +}); diff --git a/src/ui/track-tool.ts b/src/ui/track-tool.ts index 9a7ae3b66..7faef0591 100644 --- a/src/ui/track-tool.ts +++ b/src/ui/track-tool.ts @@ -322,6 +322,17 @@ const RIDE_MESSAGES: Record = { [RideResult.RideTypeForbidden]: RESTRICTION_REFUSALS.rideType, }; +/** Whether a command outcome means the edit did not happen (warnings and notices did happen). */ +export function editRefused(domain: FeedbackDomain, code: number): boolean { + if (domain === FeedbackDomain.Track) + return ( + code !== TrackResult.Ok && + code !== TrackWarning.LiftIntoInversion && + code !== TrackNotice.Removed + ); + return !feedbackMessage(domain, code).ok; +} + /** Player-facing text for a command outcome from the simulation. */ export function feedbackMessage(domain: FeedbackDomain, code: number, detail = ''): FeedbackLine { const ok = code === 0 || code === RideResult.TestPassed;