diff --git a/README.md b/README.md index 66210a44e..42a5cbd51 100644 --- a/README.md +++ b/README.md @@ -1,19 +1,78 @@ # OpenCoaster -An open-source, browser-based, clean-room theme-park management game inspired by the gameplay of 1999–2004 era roller-coaster tycoon games. +**Build roller coasters, run a theme park, and keep your guests happy, right in your browser.** -Status: playable end-to-end prototype (private until a maintainer approves going public). Original generated world art, UI icons, and animated ride sprites, with procedural fallbacks. This clean-room project is not affiliated with or endorsed by the publishers of any commercial game and contains none of their assets or code. +OpenCoaster is an open-source, clean-room theme-park management game inspired by the gameplay of 1999–2004 era roller-coaster tycoon games. Lay out paths, build coasters with lift hills, loops and corkscrews, hire staff, set prices and watch thousands of simulated guests decide whether your park is worth the ticket. -## Quick start +### [▶ Play now at opencoaster.noriagentic.com](https://opencoaster.noriagentic.com/) + +No install, no account. It runs on desktop and on phones, and works offline once loaded. + +![A busy daytime park in OpenCoaster: crowds of guests walk stall-lined avenues between merry-go-rounds, Ferris wheels, a spiral slide, an observation tower and other flat rides.](docs/screenshots/readme/park-overview.png) + +| | | +| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| ![A blue-and-white steel looping coaster with a tall lift hill, a vertical loop and a corkscrew rising over an autumn forest beside a busy midway.](docs/screenshots/readme/steel-coaster.png) | ![A riverside fairground at nightfall, with glowing path lamps along the river, a merry-go-round, a Ferris wheel and guests out for the evening.](docs/screenshots/readme/riverside-night.png) | +| A steel looping coaster: lift hill, drop, vertical loop and corkscrew. | Riverside Fairground at dusk, with the path lamps lit. | + +## What you can do + +- **Design coasters piece by piece.** Stations, flat track, 25° and 60° slopes, small to large curves (flat, banked and sloped), vertical loops, corkscrews, S-bends, helices, tunnels, chain lifts, brakes, block brakes and launch sections. Each finished circuit gets a test run that measures speed, G-forces, drops, inversions and airtime to produce excitement, intensity and nausea ratings. +- **Run 19 rides and 13 stalls and facilities.** Wooden, Steel Looping, Junior and Wild Mouse coasters; a log flume and river rapids; a miniature railway, monorail and chairlift; flat rides from the Merry-Go-Round and Ferris Wheel to the Top Spin and Enterprise; food, drink, souvenir and balloon stalls, information kiosks and toilets. Stalls rotate to face the path and sell items guests carry around the park. +- **Watch guests think for themselves.** Every guest tracks hunger, thirst, toilet needs, energy, nausea and happiness, has a thrill preference and a budget, judges ride and ticket prices, queues single file, sits on benches, drops litter and tells you what they think. +- **Hire and manage staff.** Handymen sweep, mow, water and empty bins; mechanics inspect and repair rides as they wear down and break; security guards deter vandals; entertainers cheer guests up. Assign patrol areas and work orders. +- **Shape the land.** Raise, lower, flatten and smooth terrain, raise and lower water, buy land and construction rights, lay footpaths, queues, ramps and raised bridges, and decorate with trees, flower beds, fountains, statues, fences, benches, bins and lamps. +- **Balance the books.** Choose an entry fee or pay-per-ride, take and repay loans, fund research to unlock new ride types, and run marketing campaigns. Finance windows chart cash, park value and weekly profit, and your park can win (or lose) awards. +- **Play scenarios or a sandbox.** Eleven original scenarios from beginner to expert, each with its own map and climate. Most set a deadline goal (guests and park rating, park value, repaying the loan, ride income, food profit, or a set of excellent coasters); one is just for fun. There is also an unrestricted sandbox. +- **Live with the weather.** Sun, cloud, rain and storms change what guests want to do, and the park shifts from day to night with lamps that light up after dusk. +- **Save anywhere.** Save to in-browser slots, or export and import `.ocsave` files. + +Everything runs locally: the simulation is deterministic and runs in a Web Worker, the world draws with WebGL2 (with a Canvas2D fallback), and all art, music and sound effects are original or procedurally generated. + +### What's not there yet + +OpenCoaster is a playable game, not a finished remake. The ride catalog is smaller than the games that inspired it, research unlocks rides but not scenery, there are four weather types rather than a full forecast system, and some rating and guest-behaviour formulas are still being tuned. Open gaps are tracked in [docs/mechanics/gap-audit.md](docs/mechanics/gap-audit.md) and [docs/fidelity/](docs/fidelity/). + +## Built with Nori Projects + +OpenCoaster was built by AI coding agents running on [Nori](https://noriagentic.com), working as one Nori Project with people steering along the way. + +- **It started as a goal.** The owner gave the project one goal: an efficient, open-source browser game in the spirit of the classic coaster tycoon games, built by researching how each game mechanic works, parallelizing aggressively, and alternating between Anthropic and OpenAI models. +- **A coordinator broke it up.** A persistent project coordinator kept the goal and shared context, split the work into mechanics research and implementation tasks, and handed each one to its own cloud subworker. +- **Many agents worked in parallel.** Subworkers ran side by side on separate branches, mixing Anthropic Claude and OpenAI Codex models. Mechanics research was written up with public sources in [docs/mechanics/](docs/mechanics/) before code was written against it. +- **Work was checked, not just merged.** Each change came in as a pull request with tests, and UI and art changes carried browser screenshots that were reviewed before merging. Proof captures live on the repository's `nori/pr-proofs` branch. +- **Playtests fed back into the work.** Agents played the live build through a real browser and wrote up what broke (see [docs/playtest/](docs/playtest/)). The owner played builds too and sent feedback, such as lamps that turn on after dark, queue lines that stay single file, and harder scenarios with awkward terrain, and the coordinator turned that feedback into new tasks. + +The commit history, pull requests and [docs/DECISIONS.md](docs/DECISIONS.md) record how the game came together. + +## Run it locally + +You need Node.js 20.19+ or 22.12+ and pnpm 10 (`corepack enable` provides the pinned version). ```sh +git clone https://github.com/tilework-tech/opencoaster.git +cd opencoaster pnpm install -pnpm dev # http://localhost:5173 -pnpm check # lint, format, typecheck, test, build -pnpm bench # sim ms/tick with 5000 guests -pnpm e2e # headless Chromium playtest; screenshots go to .local/playwright-results/ +pnpm dev # Vite dev server at http://localhost:5173 ``` -Docs: [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md), [CONTRIBUTING.md](CONTRIBUTING.md) (clean-room rules), [AGENTS.md](AGENTS.md). Mechanics research lives in `docs/mechanics/`. +The first `pnpm dev` or `pnpm build` generates the sprite pages from the art sources, which takes a few minutes. + +Checks: + +```sh +pnpm check # lint, format, typecheck, unit tests and production build (what CI runs) +pnpm e2e:quick # desktop Playwright subset for UI changes +pnpm e2e # full Playwright suite, desktop and Pixel 8 +pnpm bench # simulation benchmark +``` + +Pushes to `main` deploy to GitHub Pages at [opencoaster.noriagentic.com](https://opencoaster.noriagentic.com/) ([docs/deploy/README.md](docs/deploy/README.md)). + +## Contributing + +Contributions are welcome. Please read [CONTRIBUTING.md](CONTRIBUTING.md) first: the clean-room rules are mandatory, so never use original game assets, decompiled code or code from incompatibly licensed projects. Then see [AGENTS.md](AGENTS.md) for commands and conventions and [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) for how the simulation, worker and renderers fit together. + +## License -License: MIT. +[MIT](LICENSE). This clean-room project is not affiliated with or endorsed by the publishers of any commercial game, and contains none of their assets or code. All art and audio are original or procedurally generated. diff --git a/docs/deploy/README.md b/docs/deploy/README.md index 691a787cf..b4b8468cd 100644 --- a/docs/deploy/README.md +++ b/docs/deploy/README.md @@ -1,18 +1,17 @@ # GitHub Pages deploy -The game is served from a project-site subpath: https://tilework-tech.github.io/opencoaster/ +The game is served at https://opencoaster.noriagentic.com/ over HTTPS. `public/CNAME` names that domain, and GitHub Pages redirects both https://tilework-tech.github.io/opencoaster/ and plain HTTP to it. -## What is ready +## Workflow -- `docs/deploy/pages.yml` is a ready-to-install workflow. It runs `pnpm build` and deploys `dist/` with `actions/upload-pages-artifact@v3` and `actions/deploy-pages@v4` on every push to `main`. -- Production builds use a relative Vite base (`./`) by default, so `dist/` works at the site root or under `/opencoaster/`. Set `OC_BASE` (e.g. `OC_BASE=/opencoaster/ pnpm build`) to pin an absolute base instead. -- `pnpm smoke:subpath` builds `dist/`, serves it under `/opencoaster/` with no cross-origin isolation headers (`tools/serve-subpath.mjs`), and runs the smoke suite against it. GitHub Pages sends no COOP/COEP headers, so this is the production configuration. +- [.github/workflows/pages.yml](../../.github/workflows/pages.yml) is installed and deploys on every push to `main` and on manual `workflow_dispatch`. It runs `pnpm build`, uploads `dist/` with `actions/upload-pages-artifact`, and publishes it with `actions/deploy-pages`. +- After deploying, an "Ensure custom domain" step sets the Pages custom domain back to `opencoaster.noriagentic.com` if it has been cleared. The step is allowed to fail without failing the deploy. +- Pages Source in the repository settings is "GitHub Actions". +- [pages.yml](pages.yml) in this folder is a historical copy from before the workflow was installed and has drifted from it. Edit the installed workflow, not this copy. -## Installing the workflow +## Base path -The GitHub session token cannot push `.github/workflows/` files, so the workflow lives here until an admin installs it: - -1. Copy `docs/deploy/pages.yml` to `.github/workflows/pages.yml` and merge it. -2. In the repository settings, open Pages and set Source to "GitHub Actions". +- Production builds use a relative Vite base (`./`) by default, so `dist/` works at the domain root and under a subpath such as `/opencoaster/`. Set `OC_BASE` (e.g. `OC_BASE=/opencoaster/ pnpm build`) to pin an absolute base instead. +- `pnpm smoke:subpath` builds `dist/`, serves it under `/opencoaster/` with no cross-origin isolation headers (`tools/serve-subpath.mjs`), and runs the smoke suite against it. GitHub Pages sends no COOP/COEP headers, so this matches production. Dev and preview builds keep the root base and the COOP/COEP headers the Vite dev server sends. diff --git a/docs/screenshots/readme/park-overview.png b/docs/screenshots/readme/park-overview.png new file mode 100644 index 000000000..a655a6a8f Binary files /dev/null and b/docs/screenshots/readme/park-overview.png differ diff --git a/docs/screenshots/readme/riverside-night.png b/docs/screenshots/readme/riverside-night.png new file mode 100644 index 000000000..c6e603e1f Binary files /dev/null and b/docs/screenshots/readme/riverside-night.png differ diff --git a/docs/screenshots/readme/steel-coaster.png b/docs/screenshots/readme/steel-coaster.png new file mode 100644 index 000000000..5b1c0d808 Binary files /dev/null and b/docs/screenshots/readme/steel-coaster.png differ diff --git a/e2e/docs.md b/e2e/docs.md index f2251442b..7a6076f00 100644 --- a/e2e/docs.md +++ b/e2e/docs.md @@ -37,6 +37,8 @@ Path: @/e2e - [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. - [scenario-selection.spec.ts](scenario-selection.spec.ts) checks scenario tabs and previews, plus persistence of completed-park status across reloads. +- [title-source-link.spec.ts](title-source-link.spec.ts) checks the title screen's "Source on GitHub" link on desktop and Pixel 8: it is inside the viewport, opens the repository in a new tab with `noopener noreferrer`, is reachable with Tab, does not overlap the menu buttons, and returns after Back from a sub-view. +- [readme-screenshots.spec.ts](readme-screenshots.spec.ts) captures the README images in [docs/screenshots/readme](../docs/screenshots/readme) and runs only when `README_SHOT_DIR` is set (`README_SHOTS` limits it to named parks). [support/readme-parks.ts](support/readme-parks.ts) builds developed parks in Node with the real simulation and integration fixtures, serializes them, and the spec imports each through Import save file, lets it run briefly, then frames and captures each view with WebGL2. Regenerate with `README_SHOT_DIR=docs/screenshots/readme pnpm exec playwright test --config=playwright.e2e.config.ts e2e/readme-screenshots.spec.ts`. - [footpath-tool.spec.ts](footpath-tool.spec.ts) drives the Footpaths window through the UI: a dragged run previews its tiles and cost and lays them on release, a refused run shows red tiles with the reason, right-click and long-press remove a footpath with a refund, piece mode builds and removes at the cursor, and the hint shows once. Shared helpers are in [footpath-helpers.ts](footpath-helpers.ts). - [scenery-catalog.spec.ts](scenery-catalog.spec.ts) browses the grouped Scenery menu on desktop and Pixel 8, checks tooltips, places, refuses and shift-removes new decorations. [scenery-proof.spec.ts](scenery-proof.spec.ts) (`@art-review`, set `SCENERY_PROOF_DIR`) photographs every decoration at four rotations and facings, its ghost, the menu and a decorated park in both renderers. - [wall-edge-placement.spec.ts](wall-edge-placement.spec.ts) exercises wall scenery through the browser tool in WebGL2 and forced Canvas2D: it places edge walls, rotates the camera, and drag-places a continuous fence run. It complements simulation tests for per-edge occupancy and wall-blocked path links. @@ -64,6 +66,7 @@ Path: @/e2e - `pnpm e2e` runs against the Vite development server and does not build the app. The Starter Park save round-trip completes without advancing a full year; set `E2E_RUN_YEAR=1` to opt into the longer year-one objective outcome run. - Manual browser contexts must use `createTestContext`; the shared auto fixture closes registered contexts between tests. This prevents contexts and their WebGL resources from accumulating across the single-worker suite. - Repository screenshots captured by the UI flow are stored in [docs/screenshots](../docs/screenshots). The Starter Park ride-access runs attach their screenshots to the Playwright report; those attachment files are test artifacts rather than committed repository assets. P1 construction and ride-window before/after images are committed in [docs/playtest/assets](../docs/playtest/assets). +- The README screenshot spec launches Chromium with `--disable-accelerated-2d-canvas` and `--disable-gpu-rasterization`: a developed park loads every flat-ride sprite page, which otherwise exhausts browser memory. - Mobile profiles and SwiftShader are browser emulation; their screenshots and FPS samples verify the browser integration path but do not characterize physical phone GPU performance. - [queue-lines.spec.ts](queue-lines.spec.ts) runs on desktop and emulated Pixel 8 against Open Grounds, building everything through the controls (a walkway, a Merry-Go-Round with its entrance and exit, the queue line dragged out from the highlighted entrance, and an exit path). It reads the live sim through the dev-only `window.__sim` hook, spawns a crowd from the Game options menu, and checks that the prompt opens Footpaths with Queue line on, that the ghost says the line links to the entrance and the path, that guests queue one per tile in joining order, that wanderers never stand on a queue tile, and that a queue length limit of 3 caps the line and turns guests away with the "queue is too long" thought. Phones place paths with CDP touch drags. - [icon-names.spec.ts](icon-names.spec.ts) opens every tabbed window from the toolbar and asserts each toolbar button and tab has a non-empty accessible name and tooltip. diff --git a/e2e/readme-screenshots.spec.ts b/e2e/readme-screenshots.spec.ts new file mode 100644 index 000000000..42c63472d --- /dev/null +++ b/e2e/readme-screenshots.spec.ts @@ -0,0 +1,171 @@ +import { mkdirSync } from 'node:fs'; +import { expect, test } from '@playwright/test'; +import type { Page, Request } from '@playwright/test'; +import sharp from 'sharp'; +import { project } from '../src/render/projection'; +import type { Rotation } from '../src/render/projection'; +import { TILE_UNITS, Z_STEP } from '../src/sim/core/constants'; +import { README_PARKS } from './support/readme-parks'; +import type { ReadmeView } from './support/readme-parks'; + +/** + * Captures the README screenshots: each developed park is built in Node with the real + * simulation, imported through the title screen's Import save file control, run briefly so rides + * and guests animate, then framed and captured at 1280x800 with the WebGL2 renderer. + * + * Runs only when README_SHOT_DIR names the output directory. Regenerate with + * + * README_SHOT_DIR=docs/screenshots/readme pnpm exec playwright test \ + * --config=playwright.e2e.config.ts e2e/readme-screenshots.spec.ts + * + * README_SHOTS=midway or README_SHOTS=riverside limits the run to one park. Needs the dev server + * on port 4173 (the Playwright config starts or reuses it); takes about 90 seconds. + */ +const shotDir = process.env.README_SHOT_DIR; +const only = process.env.README_SHOTS?.split(','); + +interface SimWindow { + __sim: { + latest: { cars: { data: Int32Array; count: number } }; + map: { width: number; height: number }; + setSpeed(multiplier: number): void; + setPaused(paused: boolean): void; + }; + __camera: { x: number; y: number; zoom: number; rotation: number }; +} + +/** Resolves once every sprite page the renderer asked for has arrived and nothing new is pending. */ +function spriteIdleTracker(page: Page): () => Promise { + let pending = 0; + let lastActivity = Date.now(); + const isSprite = (request: Request) => /\/sprites\//.test(request.url()); + page.on('request', (request) => { + if (!isSprite(request)) return; + pending++; + lastActivity = Date.now(); + }); + const done = (request: Request) => { + if (!isSprite(request)) return; + pending--; + lastActivity = Date.now(); + }; + page.on('requestfinished', done); + page.on('requestfailed', done); + return async () => { + const deadline = Date.now() + 90_000; + while (pending > 0 || Date.now() - lastActivity < 2_000) { + if (Date.now() > deadline) throw new Error('sprite pages did not finish loading'); + await page.waitForTimeout(200); + } + }; +} + +/** True when a car of `rideId` is inside the tile box. */ +async function trainIn(page: Page, train: NonNullable): Promise { + return page.evaluate(({ rideId, box, minLevel }) => { + const { cars } = (window as unknown as SimWindow).__sim.latest; + for (let i = 0; i < cars.count; i++) { + if (cars.data[i * 4 + 3]! >>> 16 !== rideId) continue; + const x = cars.data[i * 4]! / 256; + const y = cars.data[i * 4 + 1]! / 256; + const level = cars.data[i * 4 + 2]! / 64; + if (x >= box[0] && x <= box[2] && y >= box[1] && y <= box[3] && level >= (minLevel ?? 0)) + return true; + } + return false; + }, train); +} + +async function aim(page: Page, view: ReadmeView): Promise { + const { width, height, rotation } = await page.evaluate(() => { + const w = window as unknown as SimWindow; + return { width: w.__sim.map.width, height: w.__sim.map.height, rotation: w.__camera.rotation }; + }); + const at = new Float64Array(2); + const [x, y, level] = view.focus; + project( + x * TILE_UNITS + TILE_UNITS / 2, + y * TILE_UNITS + TILE_UNITS / 2, + level * Z_STEP, + width, + height, + rotation as Rotation, + at, + ); + await page.evaluate( + ([cx, cy, zoom]) => { + const camera = (window as unknown as SimWindow).__camera; + camera.x = cx!; + camera.y = cy!; + camera.zoom = zoom!; + }, + [at[0], at[1], view.zoom], + ); +} + +test.use({ + viewport: { width: 1280, height: 800 }, + launchOptions: { + args: [ + '--use-gl=angle', + '--use-angle=swiftshader', + '--enable-unsafe-swiftshader', + '--disable-dev-shm-usage', + // Software 2D canvases free the scratch canvases the WebGL2 renderer uploads each sprite + // page through; GPU-backed ones linger and push a software-GL browser past 4 GB. + '--disable-accelerated-2d-canvas', + '--disable-gpu-rasterization', + ], + }, +}); + +for (const [name, build] of Object.entries(README_PARKS)) { + test(`README screenshot: ${name} @art-review`, async ({ page }) => { + test.skip(!shotDir, 'set README_SHOT_DIR to capture the README screenshots'); + test.skip(only !== undefined && !only.includes(name), `${name} not in README_SHOTS`); + test.setTimeout(600_000); + mkdirSync(shotDir!, { recursive: true }); + const park = build(); + const spritesIdle = spriteIdleTracker(page); + + await page.goto('/'); + const chooser = page.waitForEvent('filechooser'); + await page.getByRole('button', { name: 'Import save file' }).click(); + await ( + await chooser + ).setFiles({ + name: `${name}.ocsave`, + mimeType: 'application/octet-stream', + buffer: Buffer.from(park.save), + }); + await expect(page.locator('.game-toolbar')).toBeVisible({ timeout: 60_000 }); + await expect(page.locator('.hud')).toContainText('WebGL2', { timeout: 60_000 }); + const closeButtons = page.locator('.ui-window button[aria-label^="Close"]'); + while (await closeButtons.count()) await closeButtons.first().click(); + + await page.evaluate(() => (window as unknown as SimWindow).__sim.setSpeed(1)); + await aim(page, park.views[0]!); + await page.mouse.move(640, 790); + await page.waitForTimeout(4_000); + + for (const view of park.views) { + const sim = (paused: boolean) => + page.evaluate((p) => (window as unknown as SimWindow).__sim.setPaused(p), paused); + await sim(false); + await aim(page, view); + if (view.train) + await expect + .poll(() => trainIn(page, view.train!), { timeout: 120_000, intervals: [50] }) + .toBe(true); + await sim(true); + await page.waitForTimeout(1_500); + await spritesIdle(); + await page.waitForTimeout(1_500); + const png = await page.screenshot({ timeout: 300_000 }); + const out = `${shotDir}/${view.name}.png`; + await sharp(png).png({ compressionLevel: 9, effort: 10 }).toFile(out); + const stats = await sharp(png).stats(); + expect(stats.channels[0]!.stdev, `${view.name} is not blank`).toBeGreaterThan(10); + } + }); +} diff --git a/e2e/renderer-depth.spec.ts b/e2e/renderer-depth.spec.ts index 195218a78..82144c0f2 100644 --- a/e2e/renderer-depth.spec.ts +++ b/e2e/renderer-depth.spec.ts @@ -1,7 +1,6 @@ import { expect, test } from './support/test'; -// Superseded by the universal occlusion work in run 473f4a2a: -// https://demo.norisessions.com/chat/01a16c13-c814-7295-9955-b11ff875ed14 +// Superseded by the universal occlusion oracle in e2e/occlusion-oracle.spec.ts. test.fixme('the foreground tree wins its pixel overlap with a guest in every renderer orientation', async ({ page, }) => { diff --git a/e2e/support/readme-parks.ts b/e2e/support/readme-parks.ts new file mode 100644 index 000000000..b2e4ce4a8 --- /dev/null +++ b/e2e/support/readme-parks.ts @@ -0,0 +1,678 @@ +import { readFileSync } from 'node:fs'; +import { TILE_UNITS, TRACK_STEPS_PER_LEVEL } from '../../src/sim/core/constants'; +import { Simulation } from '../../src/sim/core/simulation'; +import { World } from '../../src/sim/core/world'; +import { spawnGuest } from '../../src/sim/guests/guest-store'; +import { setParkEntrance } from '../../src/sim/guests/park'; +import { layPath, openRide } from '../../src/sim/integration/fixtures'; +import { worldOccupancies } from '../../src/sim/map/occupancy'; +import { PathAddition, setPathAddition } from '../../src/sim/map/paths'; +import { placeScenery, SceneryItem } from '../../src/sim/map/scenery'; +import { OWNED } from '../../src/sim/map/tile-map'; +import { connectRideQueue } from '../../src/sim/rides/ride-operations'; +import { RideType } from '../../src/sim/rides/ride-types'; +import { parseScenarioFile } from '../../src/sim/scenario/scenario-file'; +import { prepareScenario } from '../../src/sim/scenario/scenario-layout'; +import { pieceByName } from '../../src/sim/track/catalog'; +import { getConstructionCursor } from '../../src/sim/track/construction'; +import { PieceMode } from '../../src/sim/track/track-types'; +import { WeatherKind } from '../../src/sim/weather/weather'; +import { TICKS_PER_NIGHT_CYCLE } from '../../src/render/night-lighting'; +import { serialize } from '../../src/save/save'; + +export type Tile = readonly [x: number, y: number]; + +/** Where to point the camera for one README screenshot. */ +export interface ReadmeView { + /** File name without extension. */ + name: string; + /** Tile the camera centres on, and the height level it is projected at. */ + focus: readonly [x: number, y: number, level: number]; + zoom: number; + /** Wait until a car of this ride is inside the tile box [x0, y0, x1, y1] before capturing. */ + train?: { rideId: number; box: readonly [number, number, number, number]; minLevel?: number }; +} + +export interface ReadmePark { + save: Uint8Array; + views: ReadmeView[]; +} + +function scenarioWorld(id: string): World { + const scenario = parseScenarioFile( + JSON.parse( + readFileSync(new URL(`../../src/sim/scenario/scenarios/${id}.json`, import.meta.url), 'utf8'), + ), + ); + const world = new World({ + seed: scenario.seed, + width: scenario.mapWidth, + height: scenario.mapHeight, + }); + prepareScenario(world, scenario); + return world; +} + +/** Levels the tiles x0..x1, y0..y1 to `level`, clears them and buys them. */ +function clearFlat(world: World, x0: number, y0: number, x1: number, y1: number, level: number) { + const m = world.map; + for (let vy = y0; vy <= y1 + 1; vy++) + for (let vx = x0; vx <= x1 + 1; vx++) m.vertexHeights[m.vertexIndex(vx, vy)] = level; + for (let y = y0; y <= y1; y++) + for (let x = x0; x <= x1; x++) { + const i = m.index(x, y); + m.waterLevel[i] = 0; + m.ownership[i] |= OWNED; + for (let e = m.firstElement(i); e >= 0; e = m.firstElement(i)) m.removeElement(i, e); + } + for (let y = Math.max(0, y0 - 1); y <= Math.min(m.height - 1, y1 + 1); y++) + for (let x = Math.max(0, x0 - 1); x <= Math.min(m.width - 1, x1 + 1); x++) + m.refreshTile(m.index(x, y)); +} + +function line(from: Tile, to: Tile): Tile[] { + const out: Tile[] = []; + const dx = Math.sign(to[0] - from[0]); + const dy = Math.sign(to[1] - from[1]); + for (let [x, y] = from; ; x += dx, y += dy) { + out.push([x, y]); + if (x === to[0] && y === to[1]) return out; + } +} + +/** Tiles any ride, track, path or entrance stands on, so planting can leave them clear. */ +function builtTiles(world: World): Set { + const out = new Set(); + for (const volume of worldOccupancies(world)) + if (volume.kind !== 'scenery' && volume.kind !== 'terrain') + out.add(`${volume.tileX},${volume.tileY}`); + return out; +} + +/** Plants `item` on each tile that nothing else stands on. */ +function plant(world: World, built: Set, tiles: readonly Tile[], item: SceneryItem) { + for (const [x, y] of tiles) if (!built.has(`${x},${y}`)) placeScenery(world.map, x, y, item); +} + +function furnish(world: World, tiles: readonly Tile[], every: number, kinds: PathAddition[]) { + tiles.forEach(([x, y], k) => { + if (k % every === 0) setPathAddition(world.map, x, y, kinds[(k / every) % kinds.length]!); + }); +} + +interface FlatRide { + type: RideType; + /** Largest-x, largest-y corner of the unrotated footprint. */ + corner: Tile; + entrance: Tile; + /** Queue tiles from the entrance outwards. */ + queue: Tile[]; + /** Footpath tile the far end of the queue opens onto. */ + joins: Tile; + exit: Tile; + /** Footpath from the exit towards the rest of the network. */ + exitPath: Tile[]; +} + +function flatRide(world: World, ride: FlatRide): void { + layPath(world, [ride.entrance, ...ride.queue], true); + layPath(world, [ride.exit, ...ride.exitPath]); + world.research.unlocked.add(ride.type); + openRide(world, ride.type, ride.corner, ride.entrance, ride.exit, [...ride.queue, ride.joins]); +} + +function stall(world: World, type: RideType, at: Tile, front: Tile): void { + world.research.unlocked.add(type); + openRide(world, type, at, front, at); +} + +interface TrackRide { + type: RideType; + /** First station tile, its level and heading. */ + start: readonly [x: number, y: number, level: number, dir: number]; + layout: ReadonlyArray; + entrance: Tile; + queue: Tile[]; + joins: Tile; + exit: Tile; + exitPath: Tile[]; +} + +/** Builds, tests and opens a tracked ride; returns its id. */ +function trackRide(sim: Simulation, ride: TrackRide): number { + const world = sim.world; + world.research.unlocked.add(ride.type); + sim.enqueue({ type: 'createRide', rideType: ride.type, x: ride.start[0], y: ride.start[1] }); + sim.step(); + const rideId = world.rides.slotToId[world.rides.count - 1]!; + buildTrack(sim, rideId, ride.start, ride.layout); + if (!getConstructionCursor(world, rideId).closed) throw new Error('circuit is not closed'); + layPath(world, ride.queue, true); + layPath(world, ride.exitPath); + sim.enqueue({ type: 'placeRideEntrance', rideId, x: ride.entrance[0], y: ride.entrance[1] }); + sim.enqueue({ type: 'placeRideExit', rideId, x: ride.exit[0], y: ride.exit[1] }); + sim.enqueue({ type: 'setRideStatus', rideId, status: 'test' }); + sim.step(); + const slot = world.rides.idToSlot[rideId]!; + for (let tick = 0; world.rides.cols.tested[slot] === 0; tick++) { + if (tick > 40_000) throw new Error('ride test did not finish'); + sim.step(); + } + const chain = [ride.entrance, ...ride.queue, ride.joins].map(([x, y]) => ({ x, y })); + if (!connectRideQueue(world, rideId, chain)) throw new Error('queue'); + sim.enqueue({ type: 'setRideStatus', rideId, status: 'open' }); + sim.step(); + return rideId; +} + +/** Places each piece at the construction cursor, starting at (x, y, level) heading `dir`. */ +function buildTrack( + sim: Simulation, + rideId: number, + start: readonly [x: number, y: number, level: number, dir: number], + layout: ReadonlyArray, +): void { + for (const [name, mode] of layout) { + const cursor = getConstructionCursor(sim.world, rideId); + const piece = pieceByName(name); + if (!piece) throw new Error(`piece ${name}`); + sim.enqueue({ + type: 'placeTrack', + rideId, + pieceType: piece.id, + x: cursor.hasTrack ? cursor.x : start[0], + y: cursor.hasTrack ? cursor.y : start[1], + z: cursor.hasTrack ? cursor.z : start[2] * TRACK_STEPS_PER_LEVEL, + dir: cursor.hasTrack ? cursor.dir : start[3], + mode, + }); + sim.step(); + } +} + +/** Puts `count` guests on random footpath tiles from `tiles`. */ +function populate(world: World, tiles: readonly Tile[], count: number): void { + const g = world.guests.cols; + for (let n = 0; n < count; n++) { + if (!spawnGuest(world)) throw new Error('spawnGuest'); + const slot = world.guests.count - 1; + const [x, y] = tiles[world.rng.int(tiles.length)]!; + g.x[slot] = x * TILE_UNITS + 40 + world.rng.int(TILE_UNITS - 80); + g.y[slot] = y * TILE_UNITS + 40 + world.rng.int(TILE_UNITS - 80); + g.z[slot] = world.map.heightAt(g.x[slot], g.y[slot]); + g.cash[slot] = 8_000; + g.ridesTaken[slot] = 1; + } +} + +/** Runs the sim, keeping guests cheerful, rested and in funds so they stay and keep riding. */ +function runHappy(sim: Simulation, ticks: number): void { + const world = sim.world; + for (let tick = 0; tick < ticks; tick++) { + sim.step(); + if (world.tick % 100 !== 0) continue; + const g = world.guests.cols; + for (let slot = 0; slot < world.guests.count; slot++) { + g.energy[slot] = Math.max(g.energy[slot], 140); + g.happiness[slot] = Math.max(g.happiness[slot], 220); + g.happinessTarget[slot] = Math.max(g.happinessTarget[slot], 220); + g.cash[slot] = Math.max(g.cash[slot], 5_000); + g.patience[slot] = Math.max(g.patience[slot], 600); + g.nausea[slot] = Math.min(g.nausea[slot], 40); + g.toilet[slot] = Math.min(g.toilet[slot], 60); + } + } +} + +/** Runs until the clock of the day-night lighting reads `hour`. */ +function runUntilHour(sim: Simulation, hour: number): void { + const want = Math.floor((((hour - 8 + 24) % 24) / 24) * TICKS_PER_NIGHT_CYCLE); + while (Math.floor(sim.world.tick % TICKS_PER_NIGHT_CYCLE) !== want) runHappy(sim, 1); +} + +function fineWeather(world: World): void { + world.weather.kind = WeatherKind.Sunny; + world.weather.temperature = 24; + world.weather.ticksUntilChange = 1_000_000; +} + +const N = PieceMode.Normal; +const LIFT = PieceMode.ChainLift; +const rep = (n: number, name: string, mode = N): Array<[string, PieceMode]> => + Array.from({ length: n }, () => [name, mode]); + +/** + * A steel looping coaster that completes its circuit: a three-tile station, a six-step chain lift, + * a banked turnaround, a drop into a vertical loop and a corkscrew, then an S-bend and two flat + * turns back to the station. + */ +const LOOPING_COASTER: ReadonlyArray = [ + ['station', N], + ['flatToUp25', LIFT], + ...rep(6, 'up25', LIFT), + ['up25ToFlat', LIFT], + ['flat', N], + ['flatToRightBank', N], + ['mediumRightBanked', N], + ['mediumRightBanked', N], + ['rightBankToFlat', N], + ['flatToDown25', N], + ...rep(6, 'down25'), + ['down25ToFlat', N], + ['verticalLoopRight', N], + ['corkscrewRight', N], + ['sBendLeft', N], + ['smallRight', N], + ['largeRight', N], + ...rep(5, 'flat'), + ['station', N], + ['station', N], +]; + +/** Deterministic generator of numbers in [0, 1) for natural-looking planting. */ +function pseudoRandom(seed: number): () => number { + let state = seed >>> 0; + return () => { + state = (state + 0x6d2b79f5) >>> 0; + let t = state; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296; + }; +} + +const TREES = [SceneryItem.OakTree, SceneryItem.BlossomTree, SceneryItem.BirchTree]; +const GROUND = 7; + +/** + * Open Grounds grown into a busy park: a steel looping coaster at the back, two rows of flat + * rides either side of a stall-lined avenue, a gate walk with flower beds and fountains, lamps and + * benches, and a crowd of guests riding, queueing and shopping. + */ +export function midwayPark(): ReadmePark { + const world = scenarioWorld('open-grounds'); + world.economy.cash = 100_000_000; + fineWeather(world); + clearFlat(world, 20, 28, 70, 74, GROUND); + + const avenue = line([30, 58], [64, 58]); + const promenade = line([30, 51], [64, 51]); + const southAvenue = line([30, 66], [64, 66]); + const gateWalk = line([47, 59], [47, 74]); + const northWalk = line([47, 52], [47, 57]); + const walks = [...avenue, ...promenade, ...southAvenue, ...gateWalk, ...northWalk]; + layPath(world, walks); + + const north = (x: number): Pick => ({ + entrance: [x, 56], + queue: [[x, 57]], + joins: [x, 58], + }); + const south = (x: number): Pick => ({ + entrance: [x, 68], + queue: [[x, 67]], + joins: [x, 66], + }); + const rides: FlatRide[] = [ + { + type: RideType.MerryGoRound, + corner: [34, 55], + ...north(32), + exit: [34, 56], + exitPath: [[34, 57]], + }, + { type: RideType.Twist, corner: [40, 55], ...north(38), exit: [40, 56], exitPath: [[40, 57]] }, + { + type: RideType.FerrisWheel, + corner: [44, 55], + ...north(44), + exit: [45, 55], + exitPath: [ + [45, 56], + [45, 57], + ], + }, + { + type: RideType.SpiralSlide, + corner: [51, 55], + ...north(50), + exit: [51, 56], + exitPath: [[51, 57]], + }, + { + type: RideType.TopSpin, + corner: [56, 55], + ...north(54), + exit: [56, 56], + exitPath: [[56, 57]], + }, + { + type: RideType.Enterprise, + corner: [63, 55], + ...north(61), + exit: [63, 56], + exitPath: [[63, 57]], + }, + { + type: RideType.SwingingShip, + corner: [33, 73], + ...south(33), + exit: [34, 69], + exitPath: [ + [34, 68], + [34, 67], + ], + }, + { + type: RideType.HauntedHouse, + corner: [39, 71], + ...south(37), + exit: [39, 68], + exitPath: [[39, 67]], + }, + { + type: RideType.ObservationTower, + corner: [43, 69], + ...south(43), + exit: [44, 69], + exitPath: [ + [44, 68], + [44, 67], + ], + }, + { + type: RideType.MerryGoRound, + corner: [53, 71], + ...south(51), + exit: [53, 68], + exitPath: [[53, 67]], + }, + { type: RideType.Twist, corner: [58, 71], ...south(56), exit: [58, 68], exitPath: [[58, 67]] }, + { + type: RideType.FerrisWheel, + corner: [62, 72], + ...south(62), + exit: [63, 69], + exitPath: [ + [63, 68], + [63, 67], + ], + }, + ]; + for (const ride of rides) flatRide(world, ride); + + const stalls: RideType[] = [ + RideType.BurgerStall, + RideType.DrinkStall, + RideType.IceCreamStall, + RideType.BalloonStall, + RideType.CandyflossStall, + RideType.PizzaStall, + RideType.Toilets, + RideType.InformationKiosk, + RideType.PopcornStall, + RideType.HatStall, + RideType.ChipsStall, + RideType.SouvenirStall, + RideType.FoodStall, + RideType.DrinkStall, + RideType.IceCreamStall, + RideType.BalloonStall, + ]; + stalls.forEach((type, k) => { + const x = 31 + 2 * k + (k >= 8 ? 2 : 0); + stall(world, type, [x, 59], [x, 58]); + }); + + const sim = new Simulation(world); + const coaster = trackRide(sim, { + type: RideType.SteelLoopingCoaster, + start: [41, 48, GROUND, 2], + layout: LOOPING_COASTER, + entrance: [43, 49], + queue: [ + [43, 50], + [44, 50], + [45, 50], + [46, 50], + ], + joins: [46, 51], + exit: [41, 49], + exitPath: [[41, 50]], + }); + + furnish(world, avenue, 3, [PathAddition.Lamp, PathAddition.Bench, PathAddition.Bin]); + furnish(world, promenade, 3, [PathAddition.Lamp, PathAddition.Bench]); + furnish(world, southAvenue, 3, [PathAddition.Lamp, PathAddition.Bench, PathAddition.Bin]); + furnish(world, gateWalk, 2, [PathAddition.Lamp, PathAddition.Bench]); + + const built = builtTiles(world); + for (let x = 30; x <= 64; x++) { + plant(world, built, [[x, 60]], x % 2 ? SceneryItem.FlowerBed : SceneryItem.Shrub); + plant(world, built, [[x, 65]], x % 2 ? SceneryItem.Shrub : SceneryItem.FlowerBed); + } + for (let y = 59; y <= 74; y++) { + plant(world, built, [[46, y]], y % 2 ? SceneryItem.FlowerBed : SceneryItem.LavenderRows); + plant(world, built, [[48, y]], y % 2 ? SceneryItem.FlowerBed : SceneryItem.LavenderRows); + } + for (const x of [36, 58]) plant(world, built, [[x, 62]], SceneryItem.TieredFountain); + for (const x of [42, 52]) plant(world, built, [[x, 63]], SceneryItem.JetFountain); + const scatter = pseudoRandom(7); + const sow = ( + x0: number, + y0: number, + x1: number, + y1: number, + density: number, + items: SceneryItem[], + ) => { + for (let y = y0; y <= y1; y++) + for (let x = x0; x <= x1; x++) + if (scatter() < density) + plant(world, built, [[x, y]], items[Math.floor(scatter() * items.length)]!); + }; + sow(30, 61, 64, 64, 0.45, [...TREES, SceneryItem.Shrub, SceneryItem.FlowerBed]); + sow(26, 44, 51, 47, 0.3, [SceneryItem.FlowerBed, SceneryItem.LavenderRows, SceneryItem.Shrub]); + sow(20, 28, 70, 42, 0.55, [ + SceneryItem.Conifer, + SceneryItem.Conifer, + SceneryItem.OakTree, + SceneryItem.BirchTree, + SceneryItem.AutumnTree, + ]); + sow(20, 43, 28, 74, 0.5, [...TREES, SceneryItem.Conifer]); + sow(66, 43, 70, 74, 0.5, [...TREES, SceneryItem.Conifer]); + sow(30, 52, 64, 52, 0.6, [SceneryItem.FlowerBed, SceneryItem.Shrub]); + sow(30, 73, 64, 74, 0.5, TREES); + + populate(world, walks, 360); + runHappy(sim, 8_000); + runUntilHour(sim, 13); + world.economy.cash = 4_825_000; + return { + save: serialize(world), + views: [ + { name: 'park-overview', focus: [47, 58, GROUND], zoom: 1 }, + { + name: 'steel-coaster', + focus: [38, 47, GROUND + 2], + zoom: 1, + train: { rideId: coaster, box: [34, 43, 39, 44], minLevel: 8 }, + }, + ], + }; +} + +const W = PieceMode.WaterLift; + +/** A log flume: a station, a two-step water lift, a long run, a splash drop and the way home. */ +const LOG_FLUME: ReadonlyArray = [ + ...rep(3, 'station'), + ['flatToUp25', W], + ...rep(2, 'up25', W), + ['up25ToFlat', W], + ...rep(2, 'flat'), + ['smallRight', N], + ...rep(3, 'flat'), + ['smallRight', N], + ['flat', N], + ['waterSplashDrop', N], + ['down25', N], + ['down25', N], + ['down25ToFlat', N], + ...rep(4, 'flat'), + ['smallRight', N], + ...rep(3, 'flat'), + ['smallRight', N], +]; + +const RIVERBANK = 5; + +/** + * Riverside Fairground at dusk: a lamp-lit promenade along the river, a log flume and a row of + * stalls with the evening crowd still out. + */ +export function riversidePark(): ReadmePark { + const world = scenarioWorld('riverside-fairground'); + world.economy.cash = 100_000_000; + fineWeather(world); + clearFlat(world, 17, 24, 46, 54, RIVERBANK); + const promenade = line([19, 24], [19, 54]); + const crossWalk = line([20, 38], [44, 38]); + const southWalk = line([20, 45], [40, 45]); + const walks = [...promenade, ...crossWalk, ...southWalk]; + layPath(world, walks); + if (!setParkEntrance(world, 19, 54)) throw new Error('setParkEntrance'); + const sim = new Simulation(world); + trackRide(sim, { + type: RideType.LogFlume, + start: [24, 30, RIVERBANK, 0], + layout: LOG_FLUME, + entrance: [25, 29], + queue: [ + [25, 28], + [24, 28], + [23, 28], + [22, 28], + [21, 28], + [20, 28], + ], + joins: [19, 28], + exit: [24, 29], + exitPath: [[24, 28]], + }); + const rides: FlatRide[] = [ + { + type: RideType.MerryGoRound, + corner: [24, 42], + entrance: [23, 39], + queue: [], + joins: [23, 38], + exit: [24, 39], + exitPath: [], + }, + { + type: RideType.FerrisWheel, + corner: [28, 43], + entrance: [28, 39], + queue: [], + joins: [28, 38], + exit: [29, 40], + exitPath: [[29, 39]], + }, + { + type: RideType.Twist, + corner: [33, 42], + entrance: [32, 39], + queue: [], + joins: [32, 38], + exit: [33, 39], + exitPath: [], + }, + { + type: RideType.TopSpin, + corner: [24, 49], + entrance: [23, 46], + queue: [], + joins: [23, 45], + exit: [24, 46], + exitPath: [], + }, + { + type: RideType.SpiralSlide, + corner: [28, 48], + entrance: [27, 46], + queue: [], + joins: [27, 45], + exit: [28, 46], + exitPath: [], + }, + { + type: RideType.Enterprise, + corner: [34, 50], + entrance: [32, 46], + queue: [], + joins: [32, 45], + exit: [34, 46], + exitPath: [], + }, + ]; + for (const ride of rides) flatRide(world, ride); + const crossStalls = [ + RideType.BurgerStall, + RideType.DrinkStall, + RideType.IceCreamStall, + RideType.CandyflossStall, + ]; + crossStalls.forEach((type, k) => stall(world, type, [37 + 2 * k, 37], [37 + 2 * k, 38])); + const promenadeStalls = [ + RideType.PopcornStall, + RideType.BalloonStall, + RideType.Toilets, + RideType.HatStall, + ]; + promenadeStalls.forEach((type, k) => stall(world, type, [20, 47 + 2 * k], [19, 47 + 2 * k])); + const southStalls = [RideType.PizzaStall, RideType.ChipsStall, RideType.SouvenirStall]; + southStalls.forEach((type, k) => stall(world, type, [26 + 4 * k, 44], [26 + 4 * k, 45])); + furnish(world, promenade, 2, [PathAddition.Lamp]); + furnish(world, promenade.slice(1), 4, [PathAddition.Bench]); + furnish(world, crossWalk, 2, [PathAddition.Lamp, PathAddition.Lamp, PathAddition.Bin]); + furnish(world, southWalk, 2, [PathAddition.Lamp, PathAddition.Bench]); + + const built = builtTiles(world); + const scatter = pseudoRandom(11); + const sow = ( + x0: number, + y0: number, + x1: number, + y1: number, + density: number, + items: SceneryItem[], + ) => { + for (let y = y0; y <= y1; y++) + for (let x = x0; x <= x1; x++) + if (scatter() < density) + plant(world, built, [[x, y]], items[Math.floor(scatter() * items.length)]!); + }; + sow(17, 24, 18, 54, 0.45, [SceneryItem.OakTree, SceneryItem.BirchTree]); + sow(20, 24, 46, 27, 0.5, [...TREES, SceneryItem.Conifer]); + sow(36, 28, 46, 36, 0.45, [...TREES, SceneryItem.FlowerBed]); + sow(23, 31, 33, 35, 0.3, [SceneryItem.FlowerBed, SceneryItem.Shrub]); + sow(21, 44, 46, 54, 0.4, [...TREES, SceneryItem.FlowerBed, SceneryItem.Shrub]); + sow(35, 39, 46, 43, 0.4, [...TREES, SceneryItem.FlowerBed]); + + runUntilHour(sim, 18.1); + populate(world, walks, 220); + runUntilHour(sim, 19.9); + world.economy.cash = 2_316_000; + return { + save: serialize(world), + views: [{ name: 'riverside-night', focus: [23, 38, RIVERBANK], zoom: 2 }], + }; +} + +/** README screenshot parks by shot name. */ +export const README_PARKS: Record ReadmePark> = { + midway: midwayPark, + riverside: riversidePark, +}; diff --git a/e2e/title-source-link.spec.ts b/e2e/title-source-link.spec.ts new file mode 100644 index 000000000..2c01f0ad2 --- /dev/null +++ b/e2e/title-source-link.spec.ts @@ -0,0 +1,58 @@ +import { devices, expect, test } from './support/test'; +import type { Page } from '@playwright/test'; +import { createTestContext } from './support/test-contexts'; + +const REPO_URL = 'https://github.com/tilework-tech/opencoaster'; + +async function expectSourceLinkBesideMenu(page: Page): Promise { + await expect(page.getByRole('heading', { name: 'OpenCoaster' })).toBeVisible(); + const link = page.getByRole('link', { name: /Source on GitHub/ }); + await expect(link).toBeVisible(); + await expect(link).toHaveAttribute('href', REPO_URL); + await expect(link).toHaveAttribute('target', '_blank'); + const rel = (await link.getAttribute('rel')) ?? ''; + expect(rel.split(/\s+/)).toEqual(expect.arrayContaining(['noopener', 'noreferrer'])); + + await expect(link).toBeInViewport({ ratio: 1 }); + const linkBox = await link.boundingBox(); + expect(linkBox).not.toBeNull(); + for (const name of ['New game', 'Sandbox', 'Continue', 'Load game', 'Import save file']) { + const box = await page.getByRole('button', { name, exact: true }).boundingBox(); + expect(box).not.toBeNull(); + const overlaps = + linkBox!.x < box!.x + box!.width && + box!.x < linkBox!.x + linkBox!.width && + linkBox!.y < box!.y + box!.height && + box!.y < linkBox!.y + linkBox!.height; + expect(overlaps, `link overlaps ${name}`).toBe(false); + } +} + +test('the title screen links to the source on GitHub in a new tab on desktop', async ({ page }) => { + await page.setViewportSize({ width: 1280, height: 800 }); + await page.goto('/'); + await expectSourceLinkBesideMenu(page); + + const link = page.getByRole('link', { name: /Source on GitHub/ }); + for (let i = 0; i < 12 && !(await link.evaluate((el) => el === document.activeElement)); i++) { + await page.keyboard.press('Tab'); + } + await expect(link).toBeFocused(); + + await page.getByRole('button', { name: 'New game', exact: true }).click(); + await page.getByRole('button', { name: 'Back', exact: true }).click(); + await expectSourceLinkBesideMenu(page); + + await page.getByRole('button', { name: 'Load game', exact: true }).click(); + await page.getByRole('button', { name: 'Back', exact: true }).click(); + await expectSourceLinkBesideMenu(page); +}); + +test('the title screen source link fits beside the menu on a Pixel 8', async ({ browser }) => { + const { defaultBrowserType: _browserType, ...options } = devices['Pixel 8']; + void _browserType; + const context = await createTestContext(browser, options); + const page = await context.newPage(); + await page.goto('/'); + await expectSourceLinkBesideMenu(page); +}); diff --git a/src/ui/docs.md b/src/ui/docs.md index b105432c4..b305e1f10 100644 --- a/src/ui/docs.md +++ b/src/ui/docs.md @@ -9,6 +9,7 @@ Path: @/src/ui - 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. - 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 an "Open source, MIT licensed" footer linking to the GitHub repository (`SOURCE_REPOSITORY_URL` in [title-screen.ts](title-screen.ts)) in a new tab, with a visually hidden "opens in a new tab" hint for screen readers. 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. ### How it fits into the larger codebase diff --git a/src/ui/title-screen.ts b/src/ui/title-screen.ts index 30a24de35..8f8403078 100644 --- a/src/ui/title-screen.ts +++ b/src/ui/title-screen.ts @@ -10,6 +10,8 @@ import { deadlineLabel } from './objective'; import { formatMoney } from './format'; import { slotRow } from './slot-list'; +export const SOURCE_REPOSITORY_URL = 'https://github.com/tilework-tech/opencoaster'; + const SCENARIO_CATEGORIES: ReadonlyArray<{ id: ScenarioCategory; label: string }> = [ { id: 'beginner', label: 'Beginner Parks' }, { id: 'challenging', label: 'Challenging Parks' }, @@ -81,6 +83,7 @@ export class TitleScreen { button('Load game', () => this.showSaves(saves.slice())), button('Import save file', () => this.chooser.click()), this.message, + sourceFooter(), ); } @@ -324,3 +327,16 @@ export function scenarioRulesText(def: ScenarioDef): string { const lines = restrictionLines(def.restrictions ?? {}); return lines.length === 0 ? 'Park rules: no restrictions.' : `Park rules: ${lines.join(' ')}`; } + +function sourceFooter(): HTMLElement { + const link = element('a', 'title-source-link', 'Source on GitHub'); + link.href = SOURCE_REPOSITORY_URL; + link.target = '_blank'; + link.rel = 'noopener noreferrer'; + link.append(element('span', 'title-source-hint', ' (opens in a new tab)')); + const separator = element('span', undefined, ' · '); + separator.setAttribute('aria-hidden', 'true'); + const footer = element('p', 'title-footer', 'Open source, MIT licensed'); + footer.append(separator, link); + return footer; +} diff --git a/src/ui/ui.css b/src/ui/ui.css index 46a7443fd..a14f3f349 100644 --- a/src/ui/ui.css +++ b/src/ui/ui.css @@ -1209,6 +1209,56 @@ #app .title-message { color: #8a321e; } +#app .title-message:empty { + display: none; +} +#app .title-footer { + margin: 10px -10px -10px; + padding: 6px 10px; + border-top: 1px solid var(--bevel-dark); + background: #bdb9a7; + color: #403c32; + font-size: 12px; + text-align: right; +} +#app .title-source-link { + display: inline-block; + padding: 6px 4px; + color: #23466e; + font-weight: 600; + text-decoration: underline; +} +@media (max-width: 699px) { + #app .title-footer { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: flex-end; + column-gap: 0.3em; + padding: 0 10px; + } + #app .title-source-link { + display: inline-flex; + align-items: center; + min-height: 44px; + padding: 0 4px; + } +} +#app .title-source-link:hover { + color: #13304f; +} +#app .title-source-link:focus-visible { + outline: 2px solid #23466e; + outline-offset: 1px; +} +#app .title-source-hint { + position: absolute; + width: 1px; + height: 1px; + overflow: hidden; + clip-path: inset(50%); + white-space: nowrap; +} #app .title-panel > .menu-button { align-self: stretch; min-height: 42px;