diff --git a/docs/mechanics/track.md b/docs/mechanics/track.md index 7afe20c0..b0d6ce50 100644 --- a/docs/mechanics/track.md +++ b/docs/mechanics/track.md @@ -158,7 +158,7 @@ What public sources describe: 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. +- 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. Selecting a piece pans the camera only when windows or the screen edge hide it. - 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. diff --git a/e2e/docs.md b/e2e/docs.md index 93ac028c..9b16195b 100644 --- a/e2e/docs.md +++ b/e2e/docs.md @@ -33,7 +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. +- [track-edit-selection.spec.ts](track-edit-selection.spec.ts) runs on desktop and emulated Pixel 8 under both WebGL2 and Canvas2D (plus a Pixel 8 landscape, 915x412 touch, variant of the closed-circuit flow), 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. `expectPieceUncovered` requires at least 99% of the selected piece's rail pixels to hit the canvas rather than a sheet or bar, with the outline matching the piece's bounds. Phones also check Previous/Next/Demolish/Build sit in the viewport without scrolling; desktop checks Edit from this piece leaves the camera still; a manual pan survives running the game until the next selection reveals the piece again. `ridePieces` reads the snapshot in one evaluation to avoid detached buffers. - [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. diff --git a/e2e/track-edit-selection.spec.ts b/e2e/track-edit-selection.spec.ts index d00d0a8e..ac04c798 100644 --- a/e2e/track-edit-selection.spec.ts +++ b/e2e/track-edit-selection.spec.ts @@ -5,6 +5,7 @@ import { openPage, toolbarAction } from './support/park'; import { UNFINISHED_PIECES, trackEditPark } from './support/track-edit-park'; type Backend = 'WebGL2' | 'Canvas2D'; +type Device = 'desktop' | 'Pixel 8' | 'Pixel 8 landscape'; interface Piece { id: number; @@ -51,32 +52,32 @@ async function loadPark(page: Page, testInfo: TestInfo): Promise { /** 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 }; + // A snapshot handed back to the worker for reuse has detached buffers; read a live one. + const read = () => + page.evaluate((rideId) => { + const snapshot = ( + window as unknown as { + __snapshot?: { tracks: { count: number; data: Int32Array }; trackLinks: Int32Array }; + } + ).__snapshot; + if (!snapshot || snapshot.tracks.data.length === 0 || snapshot.trackLinks.length === 0) + return null; + 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, + }); } - ).__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); + return out; + }, rideId); + let rows = await read(); + await expect.poll(async () => (rows = await read()) !== null).toBe(true); + if (!rows) throw new Error('No live snapshot'); 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[] = []; @@ -162,8 +163,89 @@ async function expectHighlightAt(page: Page, point: { x: number; y: number }): P expect(point.y).toBeLessThanOrEqual(box.y + box.height + 2); } -async function shot(page: Page, testInfo: TestInfo, name: string, point: { x: number; y: number }) { +/** + * Expects the piece to be on screen with its rails uncovered by any window, sheet or bar, and the + * selection outline drawn over it. + */ +async function expectPieceUncovered(page: Page, pieceId: number): Promise { + const check = () => + page.locator('#game').evaluate(async (canvas, pieceId) => { + const [{ buildObjectPickTargets }, { spritePages }] = await Promise.all([ + import('/src/input/object-picking.ts'), + import('/src/render/sprite-pages.ts'), + ]); + const state = window as unknown as { + __camera: Parameters[2]; + __map: Parameters[1]; + __snapshot: Parameters[0]; + }; + const rect = canvas.getBoundingClientRect(); + const targets = buildObjectPickTargets( + state.__snapshot, + state.__map, + state.__camera, + { width: rect.width, height: rect.height }, + spritePages, + ).filter((t) => t.coasterPart === 'track' && t.pieceId === pieceId); + if (!targets.length) return 'not on screen'; + let rails = 0; + let uncovered = 0; + for (const target of targets) { + for (let i = 0; i < target.alpha.length; i += 2) { + if (target.alpha[i] === 0) continue; + rails++; + const x = + rect.left + + target.x + + (((i % target.alphaWidth) + 0.5) / target.alphaWidth) * target.width; + const y = + rect.top + + target.y + + ((Math.floor(i / target.alphaWidth) + 0.5) / target.alphaHeight) * target.height; + if (document.elementFromPoint(x, y) === canvas) uncovered++; + } + } + if (rails === 0 || uncovered / rails < 0.99) + return `${rails - uncovered} of ${rails} rail pixels covered`; + const outline = document.querySelector('.track-selection-outline'); + if (!outline || outline.hidden) return 'no outline'; + const box = outline.getBoundingClientRect(); + const left = rect.left + Math.min(...targets.map((t) => t.x)); + const top = rect.top + Math.min(...targets.map((t) => t.y)); + const right = rect.left + Math.max(...targets.map((t) => t.x + t.width)); + const bottom = rect.top + Math.max(...targets.map((t) => t.y + t.height)); + const near = (a: number, b: number) => Math.abs(a - b) <= 8; + if ( + !near(box.left, left) || + !near(box.top, top) || + !near(box.right, right) || + !near(box.bottom, bottom) + ) + return 'outline elsewhere'; + return 'ok'; + }, pieceId); + await expect.poll(check, { timeout: 20_000 }).toBe('ok'); +} + +/** The selection, Build and Demolish controls are on screen without scrolling the window. */ +async function expectEditControlsInView(page: Page): Promise { + const panel = construction(page); + for (const name of [/^Previous piece$/, /^Next piece$/, /^Demolish/, /^Build piece$/]) + await expect(panel.getByRole('button', { name })).toBeInViewport({ ratio: 1 }); +} + +async function cameraPosition(page: Page): Promise<{ x: number; y: number }> { + return page.evaluate(() => { + const { x, y } = (window as unknown as { __camera: { x: number; y: number } }).__camera; + return { x, y }; + }); +} + +async function shot(page: Page, testInfo: TestInfo, name: string, at: { x: number; y: number }) { const viewport = page.viewportSize()!; + const outline = page.locator('.track-selection-outline'); + const box = (await outline.isVisible()) ? await outline.boundingBox() : null; + const point = box ? { x: box.x + box.width / 2, y: box.y + box.height / 2 } : at; 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)); @@ -180,7 +262,8 @@ 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 { +async function editClosedCircuit(page: Page, device: Device, testInfo: TestInfo): Promise { + const mobile = device !== 'desktop'; await toolbarAction(page, 'Pause'); const circuit = await ridePieces(page, 0); expect(circuit).toHaveLength(14); @@ -190,14 +273,40 @@ async function editClosedCircuit(page: Page, mobile: boolean, testInfo: TestInfo await tapOrClick(page, mobile, point); const rideWindow = page.locator('[data-panel^="ride-"]:visible'); await expect(rideWindow).toHaveCount(1); + const before = await cameraPosition(page); 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); + // The desktop camera stays put; a phone frames the piece above its construction sheet. + await expectPieceUncovered(page, middle.id); + if (!mobile) { + await expectHighlightAt(page, point); + expect(await cameraPosition(page)).toEqual(before); + } + if (mobile) await expectEditControlsInView(page); 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 expectPieceUncovered(page, circuit[7].id); + await page.getByRole('button', { name: 'Previous piece' }).click(); + await expect(selectionLine(page)).toContainText('Selected piece 7 of 14'); + await expectPieceUncovered(page, middle.id); + + // The camera follows the selection, not the clock: a pan away holds until the next selection. + const panned = await page.evaluate(() => { + const camera = (window as unknown as { __camera: { x: number; y: number } }).__camera; + camera.x += 300; + camera.y += 200; + return { x: camera.x, y: camera.y }; + }); + await toolbarAction(page, 'Resume'); + await page.waitForTimeout(1_500); + await toolbarAction(page, 'Pause'); + expect(await cameraPosition(page)).toEqual(panned); + await page.getByRole('button', { name: 'Next piece' }).click(); + await expect(selectionLine(page)).toContainText('Selected piece 8 of 14'); + await expectPieceUncovered(page, circuit[7].id); await page.getByRole('button', { name: 'Previous piece' }).click(); await expect(selectionLine(page)).toContainText('Selected piece 7 of 14'); @@ -207,6 +316,8 @@ async function editClosedCircuit(page: Page, mobile: boolean, testInfo: TestInfo 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 expectPieceUncovered(page, circuit[5].id); + if (mobile) await expectEditControlsInView(page); await shot(page, testInfo, 'circuit-gap', point); await page.getByRole('button', { name: 'Right small' }).click(); @@ -216,10 +327,11 @@ async function editClosedCircuit(page: Page, mobile: boolean, testInfo: TestInfo 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); // With nothing selected, Previous picks the last piece built: here the one that closed the gap. await page.getByRole('button', { name: 'Previous piece' }).click(); await expect(selectionLine(page)).toContainText('Selected piece 7 of 14'); + await expectPieceUncovered(page, (await ridePieces(page, 0))[6].id); + await shot(page, testInfo, 'circuit-rebuilt', point); await page.getByRole('button', { name: 'Track end' }).click(); await expect(selectionLine(page)).toContainText('Building from the end of the track'); @@ -241,7 +353,8 @@ async function editClosedCircuit(page: Page, mobile: boolean, testInfo: TestInfo await expect(rideInfo(page)).toContainText('Track 14 pieces'); } -async function editUnfinished(page: Page, mobile: boolean, testInfo: TestInfo): Promise { +async function editUnfinished(page: Page, device: Device, testInfo: TestInfo): Promise { + const mobile = device !== 'desktop'; await toolbarAction(page, 'Pause'); const unfinished = await ridePieces(page, 1); const overpass = await ridePieces(page, 2); @@ -251,7 +364,8 @@ async function editUnfinished(page: Page, mobile: boolean, testInfo: TestInfo): 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); + if (!mobile) await expectHighlightAt(page, upper); + await expectPieceUncovered(page, overpass[3].id); const lower = await pointOnPiece(page, unfinished[3].id); await tapOrClick(page, mobile, lower); @@ -298,23 +412,33 @@ async function editUnfinished(page: Page, mobile: boolean, testInfo: TestInfo): expect(last.map((piece) => piece.id)).not.toContain(unfinished[6].id); } +const FLOWS = [ + ['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; + 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) { + for (const device of [ + 'desktop', + 'Pixel 8', + 'Pixel 8 landscape', + ] as const satisfies readonly Device[]) { + test.describe(`editing track from a chosen piece in ${backend} on ${device}`, () => { + // The short landscape phone covers the circuit flow: select, step, rebuild, retest, reopen. + for (const [name, run] of device === 'Pixel 8 landscape' + ? FLOWS.filter(([, run]) => run === editClosedCircuit) + : FLOWS) { test(name, async ({ browser }, testInfo) => { test.setTimeout(480_000); - const page = await openPage(browser, mobile); + const page = await openPage(browser, device !== 'desktop'); try { - if (!mobile) await page.setViewportSize({ width: 1280, height: 800 }); + if (device === 'desktop') await page.setViewportSize({ width: 1280, height: 800 }); + if (device === 'Pixel 8 landscape') + await page.setViewportSize({ width: 915, height: 412 }); if (backend === 'Canvas2D') await forceCanvas2D(page); await loadPark(page, testInfo); await expect(page.locator('.hud')).toContainText(backend); - await run(page, mobile, testInfo); + await run(page, device, testInfo); } finally { await page.context().close(); } diff --git a/src/app/bootstrap/docs.md b/src/app/bootstrap/docs.md index 075c9423..69705914 100644 --- a/src/app/bootstrap/docs.md +++ b/src/app/bootstrap/docs.md @@ -19,7 +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. +- Wires track editing from a selected piece: the `editTrack(rideId, pieceId?)` action closes the ride window first on compact screens (`COMPACT_QUERY` from [window-layout.ts](../../ui/window-layout.ts): narrow or short screens, where the construction window replaces it instead of stacking on it), 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. The panel's `reveal` action feeds a [SelectionReveal](../tools/selection-reveal.ts), whose `update` runs each frame just before the outline so a camera pan it makes is drawn in the same frame. - 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/bootstrap/index.ts b/src/app/bootstrap/index.ts index 9f21e80e..1d52493f 100644 --- a/src/app/bootstrap/index.ts +++ b/src/app/bootstrap/index.ts @@ -7,6 +7,7 @@ import { Hud } from '../../ui/hud'; import { GameUI } from '../../ui/game-ui'; import type { GuestSelection, ToolMode } from '../../ui/game-ui'; import { WindowManager } from '../../ui/window-manager'; +import { COMPACT_QUERY } from '../../ui/window-layout'; import { DEFAULT_ZOOM, stepZoom } from '../../ui/zoom'; import '../../ui/ui.css'; import { TitleScreen } from '../../ui/title-screen'; @@ -18,6 +19,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 { SelectionReveal } from '../tools/selection-reveal'; import { TrackSelectionOutline } from '../tools/track-selection-outline'; import { displayOptionEnabled } from '../../ui/display-options'; import { TerrainAidOverlay } from '../terrain-aids'; @@ -108,12 +110,14 @@ export async function bootstrap(): Promise { const landHolder: { controller?: LandController } = {}; const areaHolder: { clear?: AreaController; water?: AreaController } = {}; const windows = new WindowManager(root); + const selectionReveal = new SelectionReveal(); const coasterPanel = new CoasterPanel(windows, { command: (command) => sim.command(command), selectTool: (tool) => gameUi.selectTool(tool), snapshot: () => sim.latest, map: () => sim.map, status: (text) => gameUi.setToolStatus(text), + reveal: (pieceId) => selectionReveal.request(pieceId), }); const trackPreview = new TrackPreviewOverlay(root); const trackSelectionOutline = new TrackSelectionOutline(root); @@ -210,6 +214,8 @@ export async function bootstrap(): Promise { rideSetupState.current.chooseRideType(type); }, editTrack(rideId, pieceId) { + // On a phone the construction window replaces the ride window rather than stacking on it. + if (window.matchMedia(COMPACT_QUERY).matches) windows.close(`ride-${rideId}`); coasterPanel.setActiveRide(rideId); gameUi.selectTool('track'); if (pieceId !== undefined) gameUi.setToolStatus(coasterPanel.selectPiece(rideId, pieceId)); @@ -539,6 +545,14 @@ export async function bootstrap(): Promise { } } syncPause(); + selectionReveal.update( + coasterPanel.selectedPiece(), + renderer, + latest, + sim.map, + camera, + canvas.getBoundingClientRect(), + ); const viewKey = `${camera.x}:${camera.y}:${camera.zoom}:${camera.rotation}`; if (viewKey !== hoverViewKey || sim.map !== hoverMap) { hoverViewKey = viewKey; diff --git a/src/app/tools/docs.md b/src/app/tools/docs.md index 6b05f512..f8c5ecb3 100644 --- a/src/app/tools/docs.md +++ b/src/app/tools/docs.md @@ -19,6 +19,7 @@ Path: @/src/app/tools - 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. +- [selection-reveal.ts](selection-reveal.ts) (`SelectionReveal`) frames a newly selected piece when windows, sheets, bars or the screen edge hide it, which on phones is otherwise the norm because the bottom sheets cover most of the map. Every selection path (Edit from this piece, rail taps, Previous/Next piece, follow-ups after Build or Demolish) goes through the panel's `focusPiece`, which calls the optional `CoasterPanelActions.reveal(pieceId)`. A request first waits until window rectangles are unchanged for two consecutive frames (capped at ten) so opening and self-placing windows settle, then pans at most twice: onto the projected tile when the piece's sprites are off screen, then onto its drawn rails, then ends. `revealShift` returns null when every opaque rail pixel (from the pick-target alpha masks) is on screen and clear of every cover, otherwise the shift centring the piece in `largestFreeRect`, the largest viewport rectangle no cover overlaps. Covers come from `coverRects` (visible, non-transparent toolbar, tool status, objective strip, status bar, HUD and windows). Any camera change since the request (pan, zoom, rotate) drops it, and nothing recentres on later ticks, so a desktop click on a visible piece never moves the camera. - [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/app/tools/selection-reveal.test.ts b/src/app/tools/selection-reveal.test.ts new file mode 100644 index 00000000..8bfea8d5 --- /dev/null +++ b/src/app/tools/selection-reveal.test.ts @@ -0,0 +1,138 @@ +import { describe, expect, it } from 'vitest'; +import { largestFreeRect, revealShift, type Rect } from './selection-reveal'; + +const overlaps = (a: Rect, b: Rect): boolean => + a.x < b.x + b.width && b.x < a.x + a.width && a.y < b.y + b.height && b.y < a.y + a.height; +const inside = (a: Rect, b: Rect): boolean => + a.x >= b.x && a.y >= b.y && a.x + a.width <= b.x + b.width && a.y + a.height <= b.y + b.height; +const shifted = (piece: Rect, viewport: Rect, covers: Rect[]): Rect => { + const shift = revealShift(piece, viewport, covers); + expect(shift).not.toBeNull(); + return { ...piece, x: piece.x + shift!.dx, y: piece.y + shift!.dy }; +}; +const expectCentredIn = (piece: Rect, area: Rect): void => { + expect(piece.x + piece.width / 2).toBeCloseTo(area.x + area.width / 2); + expect(piece.y + piece.height / 2).toBeCloseTo(area.y + area.height / 2); +}; + +/** Pixel 8 portrait: toolbar, tool status line, bottom sheets and status bar. */ +const portrait: Rect = { x: 0, y: 0, width: 412, height: 839 }; +const portraitCovers: Rect[] = [ + { x: 0, y: 0, width: 412, height: 52 }, + { x: 6, y: 58, width: 400, height: 28 }, + { x: 0, y: 420, width: 412, height: 319 }, + { x: 0, y: 739, width: 412, height: 100 }, +]; + +/** Landscape phone: floating construction window on the right. */ +const landscape: Rect = { x: 0, y: 0, width: 915, height: 412 }; +const landscapeCovers: Rect[] = [ + { x: 0, y: 0, width: 915, height: 44 }, + { x: 591, y: 48, width: 320, height: 290 }, + { x: 0, y: 344, width: 915, height: 68 }, +]; + +describe('largestFreeRect', () => { + it('is the whole viewport when nothing covers it', () => { + expect(largestFreeRect(portrait, [])).toEqual(portrait); + }); + + it('is the strip between the top bars and the bottom sheets on a portrait phone', () => { + expect(largestFreeRect(portrait, portraitCovers)).toEqual({ + x: 0, + y: 86, + width: 412, + height: 334, + }); + }); + + it('is the area beside a floating window on a landscape phone', () => { + expect(largestFreeRect(landscape, landscapeCovers)).toEqual({ + x: 0, + y: 44, + width: 591, + height: 300, + }); + }); + + it('ignores the parts of covers that lie outside the viewport', () => { + expect(largestFreeRect(portrait, [{ x: -50, y: 700, width: 600, height: 400 }])).toEqual({ + x: 0, + y: 0, + width: 412, + height: 700, + }); + }); +}); + +describe('revealShift', () => { + it('leaves a piece that is already in view where it is', () => { + const piece = { x: 150, y: 200, width: 80, height: 50 }; + expect(revealShift(piece, portrait, portraitCovers)).toBeNull(); + }); + + it('leaves a visible piece alone even when it is outside the largest free area', () => { + const piece = { x: 620, y: 360, width: 60, height: 30 }; + const covers = [...landscapeCovers.slice(0, 2), { x: 0, y: 400, width: 915, height: 12 }]; + expect(revealShift(piece, landscape, covers)).toBeNull(); + }); + + it('brings a piece hidden under a bottom sheet into the free area', () => { + const piece = { x: 150, y: 520, width: 80, height: 50 }; + const after = shifted(piece, portrait, portraitCovers); + expectCentredIn(after, largestFreeRect(portrait, portraitCovers)); + for (const cover of portraitCovers) expect(overlaps(after, cover)).toBe(false); + }); + + it('brings a piece partly under a floating window beside it', () => { + const piece = { x: 560, y: 150, width: 90, height: 60 }; + const after = shifted(piece, landscape, landscapeCovers); + expectCentredIn(after, largestFreeRect(landscape, landscapeCovers)); + for (const cover of landscapeCovers) expect(overlaps(after, cover)).toBe(false); + }); + + it('brings a piece partly past the edge of an uncovered screen fully into view', () => { + const piece = { x: -20, y: 300, width: 80, height: 50 }; + expect(inside(shifted(piece, portrait, []), portrait)).toBe(true); + }); + + it('brings an off-screen piece back into view', () => { + const piece = { x: -400, y: -900, width: 70, height: 40 }; + const after = shifted(piece, landscape, landscapeCovers); + expect(inside(after, largestFreeRect(landscape, landscapeCovers))).toBe(true); + }); + + it('centres a piece larger than the free area on it', () => { + const piece = { x: 0, y: 300, width: 412, height: 500 }; + expectCentredIn( + shifted(piece, portrait, portraitCovers), + largestFreeRect(portrait, portraitCovers), + ); + }); + + describe('with the rails drawn in the piece', () => { + /** A 4x2 sprite drawn 80x40 at (150,60): only its bottom row of pixels is rail. */ + const rails = { + x: 150, + y: 60, + width: 80, + height: 40, + alphaWidth: 4, + alphaHeight: 2, + alpha: Uint8Array.from([0, 0, 0, 0, 255, 255, 255, 255]), + }; + const piece = { x: 150, y: 60, width: 80, height: 40 }; + + it('leaves a piece alone when only its transparent margin is under a bar', () => { + expect(revealShift(piece, portrait, portraitCovers, [rails])).toBeNull(); + }); + + it('moves a piece whose rails are under a bar', () => { + const covers = [{ x: 0, y: 0, width: 412, height: 95 }]; + const shift = revealShift(piece, portrait, covers, [rails]); + expect(shift).not.toBeNull(); + const moved = { ...rails, x: rails.x + shift!.dx, y: rails.y + shift!.dy }; + expect(revealShift(moved, portrait, covers, [moved])).toBeNull(); + }); + }); +}); diff --git a/src/app/tools/selection-reveal.ts b/src/app/tools/selection-reveal.ts new file mode 100644 index 00000000..5e464e4d --- /dev/null +++ b/src/app/tools/selection-reveal.ts @@ -0,0 +1,235 @@ +import type { Camera, Renderer } from '../../render/renderer'; +import { TILE_H, TILE_W, project } from '../../render/projection'; +import { TILE_UNITS, TRACK_Z_STEP } from '../../sim/core/constants'; +import type { Snapshot } from '../../worker/snapshot'; +import { snapshotPiece } from '../../ui/track-selection'; + +/** An axis-aligned screen rectangle in CSS pixels. */ +export interface Rect { + x: number; + y: number; + width: number; + height: number; +} + +/** Elements drawn over the game canvas that can hide the map beneath them. */ +const COVER_SELECTOR = + '.game-toolbar, .tool-status, .objective-strip, .status-bar, .hud, .ui-window'; +/** The covers that move while a selection settles: windows opening, closing and placing themselves. */ +const WINDOW_SELECTOR = '.ui-window'; + +const overlaps = (a: Rect, b: Rect): boolean => + a.x < b.x + b.width && b.x < a.x + a.width && a.y < b.y + b.height && b.y < a.y + a.height; + +const clip = (r: Rect, to: Rect): Rect | null => { + const x = Math.max(r.x, to.x); + const y = Math.max(r.y, to.y); + const width = Math.min(r.x + r.width, to.x + to.width) - x; + const height = Math.min(r.y + r.height, to.y + to.height) - y; + return width > 0 && height > 0 ? { x, y, width, height } : null; +}; + +/** The largest rectangle of the viewport that no cover overlaps. */ +export function largestFreeRect(viewport: Rect, covers: readonly Rect[]): Rect { + const clipped = covers.flatMap((cover) => clip(cover, viewport) ?? []); + const xs = [ + ...new Set([ + viewport.x, + viewport.x + viewport.width, + ...clipped.flatMap((c) => [c.x, c.x + c.width]), + ]), + ].sort((a, b) => a - b); + const ys = [ + ...new Set([ + viewport.y, + viewport.y + viewport.height, + ...clipped.flatMap((c) => [c.y, c.y + c.height]), + ]), + ].sort((a, b) => a - b); + let best: Rect = { x: viewport.x, y: viewport.y, width: 0, height: 0 }; + for (let left = 0; left < xs.length; left++) { + for (let right = left + 1; right < xs.length; right++) { + for (let top = 0; top < ys.length; top++) { + for (let bottom = top + 1; bottom < ys.length; bottom++) { + const candidate = { + x: xs[left], + y: ys[top], + width: xs[right] - xs[left], + height: ys[bottom] - ys[top], + }; + if (candidate.width * candidate.height <= best.width * best.height) continue; + if (clipped.some((cover) => overlaps(candidate, cover))) break; + best = candidate; + } + } + } + } + return best; +} + +/** A sprite's screen rectangle and the alpha mask drawn into it. */ +export interface RailMask extends Rect { + alphaWidth: number; + alphaHeight: number; + alpha: ArrayLike; +} + +const containsPoint = (r: Rect, x: number, y: number): boolean => + x >= r.x && x <= r.x + r.width && y >= r.y && y <= r.y + r.height; + +/** Whether every opaque pixel of the masks is on screen and clear of every cover. */ +function railsClear(masks: readonly RailMask[], viewport: Rect, covers: readonly Rect[]): boolean { + for (const mask of masks) { + for (let i = 0; i < mask.alpha.length; i++) { + if (mask.alpha[i] === 0) continue; + const x = mask.x + (((i % mask.alphaWidth) + 0.5) / mask.alphaWidth) * mask.width; + const y = mask.y + ((Math.floor(i / mask.alphaWidth) + 0.5) / mask.alphaHeight) * mask.height; + if (!containsPoint(viewport, x, y) || covers.some((cover) => containsPoint(cover, x, y))) + return false; + } + } + return true; +} + +/** + * The screen shift that brings a piece into the largest free area, centred there, or null when the + * piece is already in view: its rails (or, without masks, its whole rectangle) are on screen and + * clear of every cover. + */ +export function revealShift( + piece: Rect, + viewport: Rect, + covers: readonly Rect[], + masks?: readonly RailMask[], +): { dx: number; dy: number } | null { + const clear = masks + ? railsClear(masks, viewport, covers) + : piece.x >= viewport.x && + piece.y >= viewport.y && + piece.x + piece.width <= viewport.x + viewport.width && + piece.y + piece.height <= viewport.y + viewport.height && + !covers.some((cover) => overlaps(piece, cover)); + if (clear) return null; + const free = largestFreeRect(viewport, covers); + return { + dx: free.x + free.width / 2 - (piece.x + piece.width / 2), + dy: free.y + free.height / 2 - (piece.y + piece.height / 2), + }; +} + +/** Screen rectangles of the visible bars, sheets and windows over the canvas. */ +export function coverRects(root: ParentNode = document, selector = COVER_SELECTOR): Rect[] { + const rects: Rect[] = []; + for (const element of root.querySelectorAll(selector)) { + const r = element.getBoundingClientRect(); + if (r.width > 0 && r.height > 0 && Number(getComputedStyle(element).opacity) > 0) + rects.push({ x: r.left, y: r.top, width: r.width, height: r.height }); + } + return rects; +} + +/** Frames the layout may keep changing (windows opening and placing themselves) before revealing. */ +const MAX_SETTLE_FRAMES = 10; +/** Pans per request: one onto the piece's position, one onto its drawn rails once they are in view. */ +const MAX_PANS = 2; + +/** + * Pans the camera once to a newly selected track piece when windows, sheets or the screen edge hide + * it. A request waits for the window layout to settle; otherwise the camera is left to the player. + */ +export class SelectionReveal { + private pieceId: number | null = null; + private coversKey = ''; + private frames = 0; + private pans = 0; + /** The camera as this left it; a different camera means the player moved it, which wins. */ + private cameraKey: string | null = null; + private readonly out = new Float64Array(2); + + request(pieceId: number): void { + this.pieceId = pieceId; + this.coversKey = ''; + this.frames = 0; + this.pans = 0; + this.cameraKey = null; + } + + update( + selected: { pieceId: number } | null, + renderer: Renderer, + snapshot: Snapshot | null, + map: { width: number; height: number } | null, + camera: Camera, + canvas: DOMRect, + ): void { + if (this.pieceId === null || !snapshot || !map) return; + if (selected?.pieceId !== this.pieceId) { + this.pieceId = null; + return; + } + const cameraKey = `${camera.x}:${camera.y}:${camera.zoom}:${camera.rotation}`; + if (this.cameraKey === null) this.cameraKey = cameraKey; + else if (cameraKey !== this.cameraKey) { + this.pieceId = null; + return; + } + const key = coverRects(document, WINDOW_SELECTOR) + .map((r) => `${r.x},${r.y},${r.width},${r.height}`) + .join(';'); + if (key !== this.coversKey && ++this.frames < MAX_SETTLE_FRAMES) { + this.coversKey = key; + return; + } + const covers = coverRects(); + const piece = snapshotPiece(snapshot, this.pieceId); + if (!piece) { + this.pieceId = null; + return; + } + const viewport = { width: canvas.width, height: canvas.height }; + const targets = renderer + .objectTargets(snapshot, camera, viewport) + .filter((target) => target.coasterPart === 'track' && target.pieceId === piece.id); + let bounds: Rect; + if (targets.length) { + const left = Math.min(...targets.map((t) => t.x)); + const top = Math.min(...targets.map((t) => t.y)); + bounds = { + x: canvas.left + left, + y: canvas.top + top, + width: Math.max(...targets.map((t) => t.x + t.width)) - left, + height: Math.max(...targets.map((t) => t.y + t.height)) - top, + }; + } else { + project( + (piece.x + 0.5) * TILE_UNITS, + (piece.y + 0.5) * TILE_UNITS, + piece.z * TRACK_Z_STEP, + map.width, + map.height, + camera.rotation, + this.out, + ); + const width = TILE_W * camera.zoom; + const height = TILE_H * camera.zoom; + bounds = { + x: canvas.left + viewport.width / 2 + (this.out[0] - camera.x) * camera.zoom - width / 2, + y: canvas.top + viewport.height / 2 + (this.out[1] - camera.y) * camera.zoom - height / 2, + width, + height, + }; + } + const visible = { x: canvas.left, y: canvas.top, ...viewport }; + const masks = targets.map((t) => ({ ...t, x: canvas.left + t.x, y: canvas.top + t.y })); + const shift = revealShift(bounds, visible, covers, targets.length ? masks : undefined); + if (!shift || this.pans >= MAX_PANS) { + this.pieceId = null; + return; + } + camera.x -= shift.dx / camera.zoom; + camera.y -= shift.dy / camera.zoom; + this.cameraKey = `${camera.x}:${camera.y}:${camera.zoom}:${camera.rotation}`; + this.pans++; + if (targets.length) this.pieceId = null; + } +} diff --git a/src/ui/coaster-panel.ts b/src/ui/coaster-panel.ts index 05685b87..c494a25c 100644 --- a/src/ui/coaster-panel.ts +++ b/src/ui/coaster-panel.ts @@ -54,6 +54,8 @@ export interface CoasterPanelActions { map(): PanelMap | null; /** Shows a line in the tool status area. */ status(text: string): void; + /** Brings a newly selected piece into view when windows or the screen edge hide it. */ + reveal?(pieceId: number): void; } /** What the track tool would place right now, for the hover preview. */ @@ -310,7 +312,7 @@ export class CoasterPanel { this.trackControls = document.createElement('div'); this.trackControls.className = 'coaster-section'; const buildRow = document.createElement('div'); - buildRow.className = 'coaster-row'; + buildRow.className = 'coaster-row coaster-build-row'; buildRow.append(this.placeButton, this.removeButton); this.trackControls.append( selection, @@ -431,6 +433,7 @@ export class CoasterPanel { this.pendingFollow = null; this.pendingRemoval = null; if (!openEnds(piece).includes(this.buildEnd)) this.buildEnd = 'after'; + this.actions.reveal?.(piece.id); } private selected(): SnapshotPiece | null { diff --git a/src/ui/docs.md b/src/ui/docs.md index fe4e0df7..1370bcc9 100644 --- a/src/ui/docs.md +++ b/src/ui/docs.md @@ -6,7 +6,7 @@ Path: @/src/ui - Builds the RCT2-style park interface from DOM elements: a top toolbar, floating bevelled windows with per-kind title-bar colours, a lower-left status box (cash, guests, rating bar), a lower-right date/weather box and a news ticker. Layout and behaviour follow [docs/fidelity/ui.md](../../docs/fidelity/ui.md) where implemented; deferred items are listed under Things to Know. - Displays worker snapshots and timing statistics; authoritative game state remains in the simulation worker. -- Below 700 px width windows become stacked bottom sheets (only the front sheet is expanded; tapping a title collapses/expands), while toolbar actions move under a labeled Actions menu. The mobile menu includes separate clockwise and anticlockwise rotation buttons alongside pause, footpaths, rides, finance, staff, park, and save/load, with touch targets of at least 44 px. Pointer focus preserves a collapsed sheet so its title-bar controls, including close, remain tappable. +- Below 700 px width windows become stacked bottom sheets (only the front sheet is expanded; tapping a title collapses/expands; the construction sheet is capped at 44dvh and its body scrolls), while toolbar actions move under a labeled Actions menu. The mobile menu includes separate clockwise and anticlockwise rotation buttons alongside pause, footpaths, rides, finance, staff, park, and save/load, with touch targets of at least 44 px. Pointer focus preserves a collapsed sheet so its title-bar controls, including close, remain tappable. Landscape phones (height 500 px or less) keep desktop floating windows but still count as compact (`COMPACT_QUERY` in [window-layout.ts](window-layout.ts)) for ride construction; on coarse pointers there the coaster panel's buttons are at least 40 px tall. - Hosts the game shell: a title screen, an in-game menu (reached from Game options), and a one-time scenario outcome dialog. - Title and scenario selection use the same bevelled window chrome as the in-game interface. Each category tab shows how many of its scenarios have been won (`Beginner Parks (1/4)`), won scenarios carry a Completed badge in the list, and the preview states the completion date or `Not completed`; the title screen takes a progress callback so it stays independent of storage. New Game shows a map-specific top-down image on each scenario card and for the selected park, with objective/deadline, category difficulty and map dimensions alongside it. The images are generated from prepared scenario maps before development or production builds; the UI selects native or 2× assets using `srcset`. Scenario JSON defaults to Beginner Parks unless `category` is set. - The title screen's main menu ends with a footer of three right-aligned links: a Nori call to action (`NORI_URL`), the article on why and how agents on Nori built OpenCoaster (`BUILD_STORY_URL`), and the "Open source, MIT licensed" GitHub repository link (`SOURCE_REPOSITORY_URL`), all in [title-screen.ts](title-screen.ts). One helper opens each in a new tab with `noopener noreferrer` and a visually hidden "opens in a new tab" hint. Below 700 px width or on coarse pointers (touch, including landscape phones) each link has a 44 px minimum touch target ([ui.css](ui.css)). The menu is rebuilt on every return from New game or Load game, so the footer reappears there; the scenario and save sub-views do not show it. An empty title message element is hidden so it takes no space above the footer. Footer copy deliberately avoids naming RollerCoaster Tycoon, per the clean-room rule in [CONTRIBUTING.md](../../CONTRIBUTING.md). @@ -37,7 +37,7 @@ 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, 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. +- [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; on compact screens CSS reorders the track controls to put the selection block and then the Build piece / Demolish row (`coaster-build-row`) above the piece palettes. 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. @@ -58,7 +58,7 @@ Path: @/src/ui - 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. +- 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. On compact screens the ride window closes first, since it duplicates the construction controls and covers the map. Selecting a piece asks bootstrap to bring it into view ([selection-reveal.ts](../app/tools/selection-reveal.ts)). - `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/ui/ui.css b/src/ui/ui.css index da9bcb18..d635d840 100644 --- a/src/ui/ui.css +++ b/src/ui/ui.css @@ -2055,3 +2055,26 @@ animation: none; } } + +/* Ride construction on phones: keep the selected piece's map visible above or beside the window, + and put the selection, Build and Demolish controls first. */ +@media (max-width: 699px), (max-height: 500px) and (pointer: coarse) { + .coaster-section > .coaster-selection { + order: -2; + } + .coaster-section > .coaster-cost, + .coaster-section > .coaster-build-row { + order: -1; + } +} +@media (max-width: 699px) { + .ui-window[data-panel='construction'] { + max-height: 44dvh; + } +} +@media (max-height: 500px) and (pointer: coarse) { + .coaster-panel button, + .coaster-panel select { + min-height: 40px; + } +} diff --git a/src/ui/window-layout.ts b/src/ui/window-layout.ts index da3de4fc..f2812b40 100644 --- a/src/ui/window-layout.ts +++ b/src/ui/window-layout.ts @@ -2,6 +2,8 @@ export const MOBILE_MAX_WIDTH = 699; export const MOBILE_QUERY = `(max-width: ${MOBILE_MAX_WIDTH}px)`; +/** Phones in either orientation: narrow screens, and short touch screens (landscape phones). */ +export const COMPACT_QUERY = `${MOBILE_QUERY}, (max-height: 500px) and (pointer: coarse)`; /** Space reserved above (toolbar) and below (status bar) the windows on desktop. */ export const TOP_INSET = 40;