mirror of
https://github.com/openfrontio/OpenFrontIO.git
synced 2026-06-30 21:23:27 +00:00
23e05f0115346b01e9b4160189a8d39443b5de55
3470 Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
23e05f0115 |
Fix nations always attacking nuked territory instead of waiting for the correct strategy 🤖 (#4422)
## Description: Nations always rushed nuked (fallout) TerraNullius instead of retaliating or attacking enemies. The bug needed two commits to compose: **#3786** introduced `PlayerImpl.nearby()` (renamed from `neighbors()`) and wired it into the early expansion gate in `AiAttackBehavior.maybeAttack()` via a second disjunct: ```ts const hasNonNukedTerraNullius = border.some((t) => !hasOwner(t) && !hasFallout(t)) || // already filtered playerNeighbors.some((n) => !n.isPlayer()); // via nearby() ``` The first disjunct correctly excludes fallout, but the second one went through `nearby()`, whose direct-neighbor loop never filtered fallout (unlike the `shoreReachableNeighbors()` sibling introduced in the same commit). So a nation bordering directly-adjacent nuked TN reported it as plain TerraNullius and set the gate true. The bug stayed **dormant** because #3786 also introduced `hasLandBorderWithTerraNullius()` *with* a fallout filter, so `sendAttack(terraNullius())` still rejected nuked TN and the early `return` never fired. **#3814** removed the fallout filter from `hasLandBorderWithTerraNullius()` so the `nuked` strategy could capture fallout tiles. That unblocked the land path of `sendAttack`: now the early gate fired on nuked-only borders *and* `sendAttack` succeeded, pre-empting every attack strategy (retaliate, bots, assist, ...) on every difficulty. Fix: filter nuked (fallout) unowned tiles in `nearby()`'s direct-neighbor loop, making it consistent with `shoreReachableNeighbors()`. The early gate now only fires for non-nuked TerraNullius, and the `nuked` strategy still fires (and captures territory) when the nation has nothing better to do, preserving the behaviour #3814 intended. Added `tests/AiAttackBehaviorNukedTerritory.test.ts` covering: - `nearby()` excludes directly-adjacent nuked TerraNullius - `maybeAttack` retaliates against an incoming attacker instead of nuked TN - the early gate is bypassed when only nuked TN borders the nation - the `nuked` strategy still captures tiles when the nation is idle (Impossible and Easy difficulties) - `isUnitDisabled(MissileSilo)` short-circuits the `nuked` strategy ## Please complete the following: - [X] I have added screenshots for all UI updates - [X] I process any text displayed to the user through translateText() and I've added it to the en.json file - [X] I have added relevant tests to the test directory ## Please put your Discord username so you can be contacted if a bug or regression is found: FloPinguin |
||
|
|
f83e768631 |
Adds map of the Caspian Sea (With Team Spawns) (#4408)
> **Before opening a PR:** discuss new features on [Discord](https://discord.gg/K9zernJB5z) first, and file bugs or small improvements as [issues](https://github.com/openfrontio/OpenFrontIO/issues/new/choose). You must be assigned to an `approved` issue — unsolicited PRs will be auto-closed. **Add approved & assigned issue number here:** Resolves #4389 ## Description: It is basically a vertical version of Black Sea. This one is slighyly smaller. It would be the first Central Asian map and it will also complete all of the collection of caucasian maps that we will ever need. There are 12 nations. (No additional nations, yet, possibly in a future update i will add them for many maps.) The map is split in half for team spawns. https://www.youtube.com/watch?v=XSKXD6Qm6IQ <img width="1008" height="1728" alt="image" src="https://github.com/user-attachments/assets/0cbf6a29-6805-4089-9d42-ecdf265d23ab" /> <img width="334" height="463" alt="Screenshot 2026-06-24 174215" src="https://github.com/user-attachments/assets/3549aa22-c828-45ea-a3f4-146f07e4a72d" /> ## Please complete the following: - [x] I have added screenshots for all UI updates - [x] I process any text displayed to the user through translateText() and I've added it to the en.json file - [x] I have added relevant tests to the test directory ## Please put your Discord username so you can be contacted if a bug or regression is found: DISCORD_USERNAME crunchybbbbb |
||
|
|
2436eebaa7 |
fix: don't re-challenge Turnstile on lobby reconnect (#4420)
## Problem
A player who joins a **private** lobby and waits for the start timer can
get an alert — `connection refused: Unauthorized: Turnstile token
rejected` — the moment the game starts. Turnstile is only supposed to
gate the *first* join, so this looks wrong.
## Root cause
A websocket **reconnect during the lobby phase** re-sends the original
Turnstile token via `joinGame()` (`ClientGameRunner.ts` lobby
`onconnect` → `Transport.joinGame()`, line 417). Cloudflare Turnstile
tokens are **single-use** and `lobbyConfig.turnstileToken` is never
refreshed, so re-verifying the already-redeemed token returns `rejected`
→ `ws.close(1002, ...)` (`Worker.ts`).
Normally the server skips Turnstile for reconnects: a `join` first tries
`rejoinClient` and returns early if the player is a known member
(`Worker.ts:359-366`). But on a **lobby-phase disconnect**, the close
handler **deletes** the `persistentId → clientId` mapping to free the
slot (`GameServer.ts`, `if (!this._hasStarted) {
persistentIdToClientId.delete(...) }`). With the mapping gone,
`rejoinClient` fails and the reconnect falls through to a full join + a
doomed Turnstile re-check.
**Why at game start:** `GameManager.tick()` calls `prestart()`
immediately but schedules `start()` 2s later, so `_hasStarted` is still
`false` for ~2s — exactly while the client runs its heavy terrain-decode
+ WebGL init, which stalls the ping loop and makes a socket drop (`1006`
→ `reconnect()`) likely. A reconnect in that window re-sends the spent
token and gets rejected.
## Fix
Decouple **"was admitted"** from the slot-mapping:
- `GameServer` tracks `admittedPersistentIds` (populated on a successful
`joinClient`) that **survives** lobby-phase disconnects, plus a
`wasAdmitted()` accessor.
- `GameManager.wasAdmitted(gameID, persistentID)` exposes it.
- `Worker` skips the Turnstile check for an already-admitted player: `if
(env !== Dev && !gm.wasAdmitted(gameID, persistentId))`.
A reconnecting admitted player now proceeds through `joinClient`
normally instead of failing on the spent token.
### Safety
Only the Turnstile check is skipped. Every other gate still runs on
every join: token-signature, ban, flares, clan tag, cosmetics,
allowlist, maxPlayers, and **kick**. Genuine first joins are still
challenged (no admission record yet). The set is per-game and excludes
kicked players, and `persistentId` comes from the verified token so it
can't be spoofed.
## Testing
- New `tests/server/TurnstileReadmit.test.ts` (4 tests), incl. a
regression that fires the real `ws.on("close")` handler and asserts
`getClientIdForPersistentId` goes null **but `wasAdmitted` stays true**.
- Full server suite: 126/126 pass · `tsc --noEmit` clean · eslint clean.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
|
||
|
|
2bd203968f |
Add terrain colors settings (#4391)
## Description: Add terrain color settings for all terrain types <img width="977" height="485" alt="image" src="https://github.com/user-attachments/assets/ac1cef11-4b1a-45f2-8cf6-94f557ba8f6e" /> ## Please complete the following: - [x] I have added screenshots for all UI updates - [x] I process any text displayed to the user through translateText() and I've added it to the en.json file - [ ] I have added relevant tests to the test directory ## Please put your Discord username so you can be contacted if a bug or regression is found: MR. Box |
||
|
|
06c5a4ef35 |
fix:name reveal works by publicid during game config (#4415)
## Description: Adds nameRevealPublicIds to GameConfig — the same per-player reveal as nameReveals but keyed by stable account publicId instead of per-game clientID. Lets an automated host (the admin bot / OFM) grant casters and observers real-name vision at create_game, where it only knows publicIds and never learns a client's per-game clientID. viewerSeesAllNames resolves the viewer's clientID to its publicId via allClients and checks membership; nameReveals (clientID) is unchanged. ## Please complete the following: - [x] I have added screenshots for all UI updates - [x] I process any text displayed to the user through translateText() and I've added it to the en.json file - [x] I have added relevant tests to the test directory ## Please put your Discord username so you can be contacted if a bug or regression is found: zixer._ |
||
|
|
f025f89b96 |
feat: speed up spawn-phase ring pulse for better visibility
Bump spawnOverlay animSpeed 0.005 -> 0.008 so the breathing pulse on spawn-phase highlight rings cycles faster, making own and teammate spawn locations easier to spot. Addresses reports that players had trouble finding their teammates during the spawn phase in team games. |
||
|
|
61236879b7 |
fix: kick_player can target a disconnected account by publicId (#4409)
## Description: kick_player resolved a targetPublicID only against activeClients, but a client is dropped from activeClients on socket close (so players technically can disconnect right before getting kicked, then reconnect at a later point and continue playing), aka a disconnected account cannot not be kicked. Fall back to allClients (which persists) so the kick lands and bans the persistentID, blocking rejoin and reconnect. ## Please complete the following: - [x] I have added screenshots for all UI updates - [x] I process any text displayed to the user through translateText() and I've added it to the en.json file - [x] I have added relevant tests to the test directory ## Please put your Discord username so you can be contacted if a bug or regression is found: zixer._ |
||
|
|
4c55f82e87 |
Adds map of the USA (made for new impassable terrain feature) (#4405)
## Description: Adds map of the continental USA. This map was made for the brand new impassable terrain feature: https://github.com/openfrontio/OpenFrontIO/pull/4340 Only the territory of the US is playable, with canada and mexico being impassable terrain. Also, adds a new category called "countries" for Country maps like this map, that use Impassable Terrain. 49 default nations (Lower 48 + D.C.) , with additional nations (native nations and proposed states) for a total of 62, for private games and Human Vs Nations gamemode. Also standarizes many of the flags of the US states, since they did not have the black border like the other flags in the game <img width="857" height="567" alt="Captura de pantalla 2026-06-24 165158" src="https://github.com/user-attachments/assets/70a8d760-851f-40ed-ad79-d3e210dadb90" /> <img width="872" height="510" alt="Captura de pantalla 2026-06-24 165510" src="https://github.com/user-attachments/assets/c998cc10-ee89-41a7-b5e9-091be5e90da0" /> ## Please complete the following: - [x] I have added screenshots for all UI updates - [x] I process any text displayed to the user through translateText() and I've added it to the en.json file - [x] I have added relevant tests to the test directory ## Please put your Discord username so you can be contacted if a bug or regression is found: tri.star1011 |
||
|
|
904a407a35 |
Fixed rail network path length limit and readded tests for it (#4406)
> **Before opening a PR:** discuss new features on [Discord](https://discord.gg/K9zernJB5z) first, and file bugs or small improvements as [issues](https://github.com/openfrontio/OpenFrontIO/issues/new/choose). You must be assigned to an `approved` issue — unsolicited PRs will be auto-closed. **Add approved & assigned issue number here:** Resolves #4396 ## Description: Makes the max rail length 1.4142 * the max station radius to be minimum amount outside of the factory effect radius. Bug: <img width="1921" height="1078" alt="image" src="https://github.com/user-attachments/assets/91b3b3fa-037a-4d9a-b06b-afe2fe2c8ea8" /> Fixed: <img width="1922" height="1079" alt="image" src="https://github.com/user-attachments/assets/3719cf73-bc41-494f-9d86-548f308f5896" /> ## Please complete the following: - [x] I have added screenshots for all UI updates - [x] I process any text displayed to the user through translateText() and I've added it to the en.json file - [x] I have added relevant tests to the test directory ## Please put your Discord username so you can be contacted if a bug or regression is found: tktk1234567 |
||
|
|
c8a42d4c33 |
feat: include publicID in admin-bot live stats players (#4404)
## Description: The live stats endpoint enriches each player with username/connected but not publicId, so an account-keyed caller (e.g. an admin bot, which knows players by account, not per-session clientID) can't map a stats row back to a player directly. Add publicId from the same activeClients source — mirrors the kick_player targetPublicID path. ## Please complete the following: - [x] I have added screenshots for all UI updates - [x] I process any text displayed to the user through translateText() and I've added it to the en.json file - [x] I have added relevant tests to the test directory ## Please put your Discord username so you can be contacted if a bug or regression is found: zixer._ |
||
|
|
181368f962 |
Add live game stats endpoint to the admin bot API (#4399)
## Summary The game simulation runs **client-side**, so the server can't directly see what's happening in a running game. This adds a way for the admin bot to observe a live game: clients report a live stats snapshot every ~10s, the server reaches consensus on it (reusing the winner's vote mechanism), and a new admin-bot endpoint serves it. ## How it works 1. **`LiveStatsController`** (client) emits a snapshot every **100 turns** (~10s at 100ms/turn) — only deterministic sim values, with players sorted by clientID, so in-sync clients produce an identical payload. 2. The snapshot is sent as a new **`live_stats`** wire message wrapping a `LiveStats` object (`turn` + per-human-player `tilesOwned`/`troops`/`gold`/`isAlive`/`team`). 3. **`GameServer.handleLiveStats`** tallies a per-turn **IP-weighted majority vote** — the same consensus the winner uses — and keeps the latest agreed snapshot. 4. **`GET /api/adminbot/game/:id/stats`** returns it, enriched with usernames the server already holds. `liveStats` is `null` until the first consensus. The winner's vote tally was extracted into a small reusable **`VoteRound`** (`src/server/VoteTally.ts`) and is now used for both winner and live-stats consensus. Names are deliberately **excluded** from the voted payload (they vary per client under name anonymization, which would break exact-match consensus); the server joins `clientID → username` instead. ## Changes - `src/server/VoteTally.ts` *(new)* — reusable IP-weighted `VoteRound` - `src/core/Schemas.ts` — `PlayerLiveStatsSchema`, `LiveStatsSchema`, `ClientSendLiveStatsSchema` + unions - `src/client/controllers/LiveStatsController.ts` *(new)* — per-100-turn snapshot reporter - `src/client/Transport.ts` — `SendLiveStatsEvent` + sender - `src/client/hud/GameRenderer.ts` — register the controller - `src/server/GameServer.ts` — refactor winner onto `VoteRound`; add live-stats consensus + `liveStats()` accessor - `src/server/AdminBotRoutes.ts` — `GET …/stats` endpoint ## Testing - **Unit:** `tests/server/VoteTally.test.ts` (majority/dedup/ties), `tests/server/LiveStats.test.ts` (consensus, disagreement, per-client dedup, stale-turn rejection, turn advance, out-of-sync exclusion, + endpoint 200/404/400). Full suite green (`npm test`), typecheck + lint clean. - **Manual e2e** against the dev server: created an admin-bot game, joined it in a browser, force-started via `toggle_game_start_timer`, and confirmed `GET …/stats` returned the consensus snapshot with username enrichment and an advancing `turn`. Also verified wrong-worker → 400 and missing-key → 401. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com> |
||
|
|
8ffb19d938 |
Discord (#4367)
Resolves #(issue number) ## Description: continuation of https://github.com/openfrontio/infra/pull/359 adds ability to put discord URL into a dedicated slot pc: <img width="1917" height="921" alt="image" src="https://github.com/user-attachments/assets/100a25d5-e998-4744-904e-df40b74ccd76" /> mobile: <img width="385" height="826" alt="image" src="https://github.com/user-attachments/assets/de904f83-c88f-41e7-9c98-81c2296ec9a2" /> ## Please complete the following: - [x] I have added screenshots for all UI updates - [x] I process any text displayed to the user through translateText() and I've added it to the en.json file - [x] I have added relevant tests to the test directory ## Please put your Discord username so you can be contacted if a bug or regression is found: w.o.n --------- Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com> |
||
|
|
8ce5f3439c |
feat: kick_player can target a publicId (admin bot) (#4403)
## Description: Add an optional `targetPublicId` to KickPlayerIntent; the server resolves it against the connected clients to the live clientID, then kicks as before. Existing clientID targeting (lobby / in-game kick) is unchanged. That way you can kick player with both the clientID and playerID ## Please complete the following: - [x] I have added screenshots for all UI updates - [x] I process any text displayed to the user through translateText() and I've added it to the en.json file - [x] I have added relevant tests to the test directory ## Please put your Discord username so you can be contacted if a bug or regression is found: zixer._ |
||
|
|
3b84a6f569 |
Feat/anonymize names (#4318)
**Add approved & assigned issue number here:** Resolves #4296 ## Description: Adds an "Anonymous players" option to private lobbies (host toggle, off by default). When it is on, the server sends each client anonymized usernames for everyone except themselves. The lobby creator and admins still see real names so they can moderate. Names are hidden on every player-facing surface: the game start message, lobby info, /api/game/:id, and the link preview. It is enforced server-side, so a client extension cannot read real names off the wire. Initially added as part of our overhaul of OpenFront masters, but this feature can very well be useful for content creators, and other tournament hosts. Anonymized names reuse the existing tribe word lists (no emoji), so they pass UsernameSchema, and they are seeded per user, so a player looks different to different users but stays consistent from the lobby into the game. The saved game record keeps real names (anonymization is a per-send transform, gameStartInfo is never mutated), so replays and stats are unaffected. Nothing changes for normal games. New option selection: <img width="990" height="918" alt="image" src="https://github.com/user-attachments/assets/31df0b0b-7757-4b2b-9bff-84310faee8d9" /> The host, when enabling the option, gets a little eye icon next to the players(including himself to enable/disable the anon names for himself, and/or other player) By default(the names everyone will see are random and unique): <img width="979" height="188" alt="image" src="https://github.com/user-attachments/assets/f0caa4a4-9f14-41d3-89c6-9a38e8c2e6f0" /> Toggling the eye ON for yourself (the host, or any given player, will allow them to see the real names of everyone, in the lobby and in game): <img width="969" height="138" alt="image" src="https://github.com/user-attachments/assets/89abf0e0-1433-43ea-9870-49d96ca46d30" /> ## Please complete the following: - [x] I have added screenshots for all UI updates - [x] I process any text displayed to the user through translateText() and I've added it to the en.json file - [x] I have added relevant tests to the test directory ## Please put your Discord username so you can be contacted if a bug or regression is found: zixer._ |
||
|
|
67f7d09fe5 |
Add admin bot HTTP API for managing private games (#4388)
## What A trusted, server-side HTTP API so a bot authenticated with a shared secret can **create private games, change their settings, start them, kick players, and pause/resume** — without opening a WebSocket or joining as a player. Two endpoints under `/api/adminbot/`, reaching the owning worker via the existing `/wN/` nginx routing. They reuse the existing Zod schemas and `GameServer` methods, mirroring the WebSocket intent flow rather than inventing a new wire protocol. | Endpoint | Purpose | | --- | --- | | `POST /api/adminbot/create_game` | Create a private game; the worker mints a self-owned id and returns it (body: `GameConfigSchema.partial()`) | | `POST /api/adminbot/game/:id/intent` | Send a lobby-management intent (body: base `IntentSchema`) | ## How it works - **Auth:** `ADMIN_BOT_API_KEY` env var via the `x-admin-bot-key` header (timing-safe compare). The whole API is **disabled — 404 — when the var is unset**, so non-configured environments expose nothing. It's distinct from the per-instance `ADMIN_TOKEN`, which an external bot can't know. - **`GameServer.handleIntent`** is the unified intent dispatch for both the WebSocket `case "intent"` path and the admin-bot HTTP API. An `IntentActor` carries identity + authority (per-connection lobby-creator/role checks for the WS path; admin authority for the bot). It honors `update_game_config`, `toggle_game_start_timer`, `kick_player`, and `toggle_pause` — **on private games only** (`isPublic()` → 403). Gameplay intents and `mark_disconnected` are rejected (400). - **Private games only.** `create_game` rejects any `gameType` other than `Private` (Public *and* Singleplayer → 400); an omitted `gameType` defaults to `Private`. - **The bot is never a player.** It sends no `clientID`; the server stamps a placeholder `ADMIN_BOT_CLIENT_ID = "ADMINBOT"` (collision-proof — contains `I`/`O`, which `generateID()` never emits). A gameplay intent stamped with it would resolve to no player, so puppeteering is structurally impossible on top of the explicit 400. - **Determinism unchanged:** the only intent that reaches the sim is `toggle_pause`, via the same `addIntent` → turn queue → `ServerTurnMessage` path the WS uses. ## Notable details for review - **`hostCheats` is assigned unconditionally — on purpose.** `updateGameConfig` sets `this.gameConfig.hostCheats = gameConfig.hostCheats` unconditionally, unlike its sibling fields (which are guarded on `!== undefined`). The WS host clears cheats by re-sending the *full* config with `hostCheats: undefined`, so here `undefined` must mean "clear", not "leave unchanged". **Caveat for the admin bot**, which is a *partial*-update client: a partial `update_game_config` that omits `hostCheats` will clear it — the bot should send `hostCheats` explicitly (or a full config) when it wants to keep a previously-set value. - **Deploy wiring:** `ADMIN_BOT_API_KEY` is piped through the deploy steps' `env:` in `deploy.yml`/`release.yml` → `deploy.sh` heredoc → container via `update.sh`'s `--env-file`. The remaining manual step is creating the GitHub secret itself. ## Tests 19 new tests: - `GameServer.handleIntent` admin-bot behavior (per-intent, private-only, post-start guards, placeholder clientID, rejected gameplay/`mark_disconnected` intents). - `create_game` gameType guard (Public and Singleplayer both rejected). - `requireAdminBotKey` middleware (404 disabled / 401 missing / 401 wrong / pass). tsc + eslint clean. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com> |
||
|
|
d01be405c7 |
Cache maxTroops during leaderboard update (#4379)
**Add approved & assigned issue number here:** Resolves #4316 ## Description: At the beginning of the leaderboard update cycle, evaluates `maxTroops` once for each `PlayerView` and uses the cached value for the rest of the `maxTroops` lookups in the function. Measured a reduction in `updateLeaderboard` processing time from 6ms/sec down to 2ms/sec (measured over the first minute of a singleplayer game on world map and default settings). ## Please complete the following: - [ ] I have added screenshots for all UI updates - [ ] I process any text displayed to the user through translateText() and I've added it to the en.json file - [ ] I have added relevant tests to the test directory ## Please put your Discord username so you can be contacted if a bug or regression is found: Demonessica |
||
|
|
06cc01668b |
Fix non-structures being deleteable (#4385)
Resolves #4307 ## Description: Adds a check for the "delete" element of the raidial menu, to make sure the unit attemped to be removed is a structure. Previously, non-structure units such as trains could be deleted using the menu. ## Please complete the following: - [ ] I have added screenshots for all UI updates (No UI updates) - [ ] I process any text displayed to the user through translateText() and I've added it to the en.json file (No text added) - [ ] I have added relevant tests to the test directory (Not sure how this works or if it's needed) ## Please put your Discord username so you can be contacted if a bug or regression is found: unne27 --------- Co-authored-by: unne27 <uno.gunnar.johansson@gmail.com> |
||
|
|
c55ea6bb5a |
Mint game ids on the server, randomly route create-game across workers (#4393)
## What Game creation no longer requires the caller to pick the `gameID` or compute its owning worker. The client POSTs to a prefix-less `/api/create_game`; **nginx (prod) and the vite dev proxy randomly route it to a worker**, which **mints an id that hashes back to itself** and returns it along with its `workerIndex`. ## Why it stays correct The minted id still hashes to the creating worker (via the existing `generateGameIdForWorker`), so everything downstream that derives the worker from the gameID — websocket connect, share URL, join flow — keeps working unchanged. The only thing that moved is *who picks the id and worker*. ## Changes - **`src/server/Worker.ts`** — factor create into a shared `createGameForId`; add `POST /api/create_game` (no id) that mints a self-owned id and returns `gameInfo` + `workerIndex`/`workerPath`. The existing `POST /api/create_game/:id` stays. - **`nginx.conf`** — `location = /api/create_game` proxies to a `random` worker upstream. - **`generate-nginx-upstream.sh` + `Dockerfile`** — the entrypoint generates that upstream from `NUM_WORKERS` at container **start** time. `NUM_WORKERS` isn't known at image build time (the image is built once and deployed with different env), so it can't be baked into `nginx.conf` — hence runtime generation of exactly the live worker ports (no dead-server padding). - **`vite.config.ts`** — dev-only middleware forwards `POST /api/create_game` to a random worker. Vite's `http-proxy` can't pick a per-request random target, so this is a small middleware plugin (same pattern as the existing `serveProprietaryDir`), registered before the `/api` proxy. - **`src/client/HostLobbyModal.ts`** — stop generating the id client-side; use the server's. ## Behavior change to note The host's share link used to be copied **instantly** from a client-generated id. Now the id comes from the server, so the copy waits one create round-trip — I moved the URL build/copy into the create `.then` (and kept the failure path that clears the clipboard). Brief empty-link state in the modal until create resolves. ## Verification - tsc + eslint clean; full suite green (1543 tests). - nginx additions validated with `nginx -t` in isolation (the full file references container-only paths like `/etc/nginx/mime.types`); upstream + `proxy_pass` resolve. - `generate-nginx-upstream.sh` tested with `NUM_WORKERS` set and unset (defaults to 1). Not yet exercised live end-to-end (needs a dev-server restart — `vite.config.ts` + `Worker.ts` changes aren't hot-reloaded). 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com> |
||
|
|
170f506200 |
Fix transport ship's troop count to update when a hydro hits the player. (#4381)
**Add approved & assigned issue number here:** Resolves #4308 ## Description: When nuclear damage reduces a player's troop count, it also affects any transports ships in the water. This works well and is useful to avoid exploiting tranports to avoid hydro damages. `UnitImpl.setTroops()` changes the transports troop count without queuing a unit update. the core value changes, but the client never receives a fresh UnitUpdate unless something else touches the ship. - UnitImpl.ts now emits a UnitUpdate when a unit troop count actually changes. - NukeExecution.ts batches transport ship nuke losses, then applies one final troop update per ship. - Attack.test.ts now asserts the nuke tick includes a transport UnitUpdate with the reduced troop count. ## Please complete the following: - [N/A] I have added screenshots for all UI updates - [N/A] I process any text displayed to the user through translateText() and I've added it to the en.json file - [X] I have added relevant tests to the test directory ## Please put your Discord username so you can be contacted if a bug or regression is found: elliotlepley |
||
|
|
5a097317cb |
fix(render): make train tracks visible from farther out
Lower railroad railMinZoom from 4 to 3 so train tracks start rendering at a more zoomed-out level. |
||
|
|
97b689f2d1 |
Add structure dots toggle to graphics settings (#4356)
## What Adds an on/off **Structure dots** toggle to the graphics settings modal (Structure Icons section), controlling whether structures collapse into small dots when zoomed out. ## How The renderer already gates the dots LOD on `structure.dotsZoomThreshold` (structures become dots when `zoom <= threshold`). The debug GUI exposes that threshold as a slider; this surfaces a simple player-facing toggle: - `GraphicsOverrides.ts` — adds `structure.showDots` (boolean) to the override schema. - `RenderOverrides.ts` — when `showDots === false`, `applyGraphicsOverrides` sets `dotsZoomThreshold = 0`. Since zoom is always > 0, the dots LOD never triggers, so structures keep their full icon at every zoom. When enabled (default), the threshold is left untouched. - `GraphicsSettingsModal.ts` — toggle button mirroring the existing Classic icons / Classic level numbers toggles; defaults to On. - `en.json` — `structure_dots_label` / `structure_dots_desc`. The change applies live: a `settings.graphics` change re-runs `applyGraphicsOverrides` onto the live settings object the passes read each frame, and `dotsZoomThreshold` is a per-frame uniform. ## Testing - `tsc --noEmit` clean. - Verified in a headless solo game: the toggle renders (default On), flipping it persists `structure.showDots = false`, and `applyGraphicsOverrides` yields `dotsZoomThreshold` 1.2 when on / 0 when off. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
8536f1bc10 |
fix(events): make donation received events blue instead of green
Donation events were split into DONATION_SENT/DONATION_RECEIVED, and DONATION_RECEIVED was grouped with the green "success" colors. In v31 all player donations (sent and received) were blue. Move DONATION_RECEIVED back to the blue group so both directions render blue again. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> |
||
|
|
cbf1e5c513 |
Make host lobby start button yellow during countdown
Add a `warning` variant to o-button that reuses the existing `--color-cyber-yellow` brand token, and apply it to the host lobby's start button while the "Starting in Xs" countdown is active. The button stays primary blue in the Waiting/Start states. |
||
|
|
17ee294d5b |
Surface alliance renewal & rejection events in important-events panel (#4354)
## Problem The important-events notification panel splits events into a prominent **tier-1** list and a dim, auto-expiring **tier-2** list (capped at the 4 newest entries). Two alliance notifications were landing in tier-2, making them easy to miss: - **"X wants to renew your alliance"** (`RENEW_ALLIANCE`) — the core simulation still sends this when another player requests a renewal, but it was buried in tier-2, so you couldn't reliably tell whether someone had asked to renew. - **"X rejected your alliance"** (`ALLIANCE_REJECTED`) — also tier-2, so the outcome of a sent request was inconsistent (accepted was prominent, rejected was not). ## Fix Add `MessageType.RENEW_ALLIANCE` and `MessageType.ALLIANCE_REJECTED` to `TIER_1_TYPES` in `EventsDisplay.ts`, so they show prominently alongside the already-tier-1 `ALLIANCE_ACCEPTED` event. No core/simulation changes — the messages were already being emitted; only the client presentation needed fixing. Display styling for both message types already exists in `Utils.ts`. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
91cd4214a5 |
Reduce compact map chance in 1v1 from 50% to 20% 🗺️ (#4374)
## Description: Changes the probability of getting a compact map in 1v1 games from 50% (Math.random() < 0.5) to 20% (Math.random() < 0.2) in `MapPlaylist.ts`. Reasoning is feedback on discord. This suggestion thread: https://discord.com/channels/1284581928254701718/1514204284173025301 And this, for example: <img width="634" height="225" alt="image" src="https://github.com/user-attachments/assets/0b4d53de-582c-4e6a-8d18-0007433c12ee" /> Pro players seemingly want to get rid of compact maps completely, but in the thread you can also see people liking them. So lets do 20% for now? ## Please complete the following: - [X] I have added screenshots for all UI updates - [X] I process any text displayed to the user through translateText() and I've added it to the en.json file - [X] I have added relevant tests to the test directory ## Please put your Discord username so you can be contacted if a bug or regression is found: FloPinguin |
||
|
|
1ec1f0c5bd |
fix(render): update coastline color dynamically when ocean color changes (#4377)
fix(render): update coastline color dynamically when ocean color changes Resolves #4329 ## Description: Previously, the shoreline water color (`isShoreline && !isLand`) was hardcoded to a static bright blue (`rgb(100, 143, 255)`) in `encodeTerrainTile`. When a user customized the ocean/water color in Settings, the deep ocean changed colors but the shoreline water remained bright blue, causing a jarred, visually mismatched appearance. This PR updates `encodeTerrainTile` in `ColorUtils.ts` to dynamically calculate the shoreline water color by scaling the configured `oceanColor` channels: - Red and Blue channels scale by `1.4` (clamped to `255`). - Green channel scales by `1.08` (clamped to `255`). This scales the coastline water color harmoniously alongside any custom water color settings (e.g. green, red, or dark ocean tones). ## Please complete the following: - [x] I have added screenshots for all UI/rendering updates (Attached `coastline_screenshot.png` showing dynamic color integration) - [ ] I process any text displayed to the user through translateText() and I've added it to the en.json file (N/A — No user-facing text additions) - [ ] I have added relevant tests to the test directory (N/A — WebGL rendering code has no automated test harness) ## Please put your Discord username so you can be contacted if a bug or regression is found: barfires |
||
|
|
b46476384d |
Take off the v32 maps from the "New" category to make room for v33 maps (#4378)
Resolves #4375 ## Description: Remove V32 maps from "new" to make way for v33 maps. This will allow map makers to add their new maps for v33 into "new", with the v32 maps only remaining in the continental and other categories like the rest of the maps. This is a process we will make every update ## Please complete the following: - [x] I have added screenshots for all UI updates - [x] I process any text displayed to the user through translateText() and I've added it to the en.json file - [x] I have added relevant tests to the test directory ## Please put your Discord username so you can be contacted if a bug or regression is found: tri.star1011 |
||
|
|
d8395fab46 |
If player is localplayer, set structure border to territory color (#4366)
Resolves #4365 ## Description: Currently the border of icons are using borderColor which is grey for local player <img width="227" height="281" alt="image" src="https://github.com/user-attachments/assets/9e334e19-c5b2-49ca-a85d-4576a5bbc1a9" /> This set it to territory color <img width="187" height="102" alt="image" src="https://github.com/user-attachments/assets/9b9f27f9-69e2-4ae7-9f35-a789b56b45de" /> ## Please complete the following: - [x] I have added screenshots for all UI updates - [x] I process any text displayed to the user through translateText() and I've added it to the en.json file - [ ] I have added relevant tests to the test directory ## Please put your Discord username so you can be contacted if a bug or regression is found: Mr. Box |
||
|
|
758063651d |
Add allowlist for private lobbies (OFM) (#4351)
**Add approved & assigned issue number here:** Resolves #4349 ## Description: 1. **Private-lobby allowlist.** `create_game` accepts an optional `allowedPublicIds`. It's set by whoever creates the lobby (admin-token gated, no client UI), the game server pulls it out of the config so it's never broadcast to clients or written to the game record, and it rejects any joiner whose OF publicId isn't on the list before they take a slot (stickily, so they can't retry on reconnect). Lobbies created without it behave exactly as before. It is off by default Previews: <img width="241" height="140" alt="image" src="https://github.com/user-attachments/assets/30c4e47b-399d-4720-b25b-a04c63668577" /> <img width="982" height="456" alt="image" src="https://github.com/user-attachments/assets/1b5c68b7-9b99-4ccc-b987-e70c8ec25dce" /> <img width="547" height="369" alt="image" src="https://github.com/user-attachments/assets/1623090b-ea2b-4657-9cd8-903fbabca51b" /> I am not able to manually test all of it since it needs to also run the auth API (infra) and actually be connected to disc and whatnot (but still tested the refused flow).. Also, we would need to place some guards and visual error feedback, but since this only would affect casual of players and is more of a improvement to the feature, I will consider it out of scope for now. ## Please complete the following: - [x] I have added screenshots for all UI updates (no UI changes in this PR) - [x] I process any text displayed to the user through translateText() and I've added it to the en.json file (no new user-facing text) - [x] I have added relevant tests to the test directory ## Please put your Discord username so you can be contacted if a bug or regression is found: zixer._ |
||
|
|
93614b274c |
Change css to preview the graphics settings live (#4372)
<img width="1152" height="866" alt="settings" src="https://github.com/user-attachments/assets/dff00f2e-775d-4b7e-8590-855813dcff7d" /> ## Description: Small qol change to be able to preview graphics settings changes ## Please complete the following: - [x] I have added screenshots for all UI updates - [x] I process any text displayed to the user through translateText() and I've added it to the en.json file - [x] I have added relevant tests to the test directory ## Please put your Discord username so you can be contacted if a bug or regression is found: Mr. Box |
||
|
|
af1e0c7415 |
fix(account): show "Linked to Google" once a Google account is linked (#4371)
**Add approved & assigned issue number here:** N/A — bug fix for the recently-merged Google OAuth login (#4028), paired with infra PR #378. ## Description: Two bugs were reported after Google login merged. Both stem from the API (`/users/@me`) only reporting the identity used to sign in — fixed in infra PR #378, which must deploy first. This PR is the client half. - **Still says "Link":** a Discord user who linked Google saw the account page still offer "Link Google" (the response never reported `google`). Now that the API reports all linked identities, the account page shows a positive **"Linked to Google (<email>)"** confirmation instead of just hiding the button — so the link visibly succeeds and the user won't re-link (which would replace the prior Google account). - **Avatar replaced by email badge:** signing in via Google dropped the linked Discord profile, so the top bar lost the Discord avatar. This is fixed entirely by the API change (the existing Discord-first logic in `Main.ts`/`hasLinkedAccount` restores the avatar) — no client change needed beyond this PR's linked-state display. ## Please complete the following: - [x] I have added screenshots for all UI updates - [x] I process any text displayed to the user through translateText() and I've added it to the en.json file - [x] I have added relevant tests to the test directory ## Please put your Discord username so you can be contacted if a bug or regression is found: jish |
||
|
|
89297bbe9e |
Add nuke fallout color graphics option (#4355)
## What Adds a **Nuke fallout color** option to the in-game graphics settings modal (Effects section), letting players recolor the fallout tint left on territory after a nuke.  ## How Mirrors the existing **Ocean color** override pattern: - `GraphicsOverrides.ts` — adds `staleNukeColor` (hex string) to the `mapOverlay` override schema. - `RenderOverrides.ts` — `applyGraphicsOverrides` parses the hex and writes the renderer's `staleNukeR/G/B` 0–1 float channels (`hexToRgb` yields 0–255, so it divides by 255). - `GraphicsSettingsModal.ts` — new hex-text + native color-picker row, default computed from `render-settings.json`. - `en.json` — `nuke_color_label` / `nuke_color_desc`. The value persists via `UserSettings.graphicsOverrides()` and is cleared by the modal's existing "Reset to defaults". The render debug GUI already exposes the same setting as **Stale Nuke Color** (Map Overlay), so no change was needed there. ## Testing - `tsc --noEmit` clean. - Verified in a headless solo game: the row renders with the green default (`#0d8c12`), changing it persists `mapOverlay.staleNukeColor`, and `applyGraphicsOverrides("#ff0000")` produces `staleNukeR=1, G=0, B=0`. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
08b8715667 |
Add black outline to alliance icon for terrain contrast (#4353)
## Problem The green alliance icon above player names blends into similarly-colored terrain — most notably irradiated land, which is the same green — making it hard to spot allied players. ## Fix Add a configurable dark outline to the alliance status icon, rendered in the status-icon shader (the icons come from a pre-baked atlas with no regeneration script, so this is done in-shader rather than by editing the PNG). - **Outline**: an alpha dilation gated to the alliance icon (slot 3). 8-direction sampling of the icon's alpha builds a black halo around its silhouette; interior pixels and all other status icons are untouched. - **No clipping**: the alliance icon's quad is grown outward into the atlas cell's existing transparent padding so the halo isn't clipped at the quad edge. The icon's on-screen size and position are unchanged; 8px of the cell's 16px mipmap-safety padding is preserved. - **Drain stays aligned**: the alliance-expiry drain effect's cut line and faded-icon UVs are remapped into the expanded quad space so the animation still lines up. - **Tunable**: width is driven by `name.statusOutlineWidth` in `render-settings.json` (default 6 texels; 0 disables), with a matching "Status Outline Width" slider in the debug GUI. ## Testing `tsc` and `eslint` pass. Verified in-game: the handshake now reads clearly against irradiated terrain, with the outline rendering fully (no edge clipping) and the drain animation still aligned. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
2f594ebc26 |
Make the important events panel scrollable (#4346)
## What Cap the height of the **Tier 1 (important) events panel** and make it scroll when many events stack up, instead of letting it grow unbounded up the screen. ## Why The less-important (Tier 2) events panel was already height-capped and scrollable, but the important panel had no limit — a burst of important events (chat, nukes inbound, alliance changes, etc.) could push the panel arbitrarily tall. ## Changes (`src/client/hud/layers/EventsDisplay.ts`) - Added `max-h-[30vh] lg:max-h-[40vh] overflow-y-auto` to the important-events container. - Mirrored the existing Tier 2 auto-scroll-to-bottom behavior for the important panel (new `.important-events-container` query + scroll tracking), so the newest important events stay in view rather than being hidden below the fold. If the player scrolls up, auto-scroll pauses (same as Tier 2). ## Testing Verified in the live game by injecting 15 important events: - Panel is height-capped and scrollable (`scrollHeight 540 > clientHeight 400`). - Auto-scrolls to the newest (`scrollTop` pinned to bottom); events 5–15 visible, older ones reachable by scrolling up. lint clean. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
08af8470fa |
Fixed factory ghost radius (#4337)
> **Before opening a PR:** discuss new features on [Discord](https://discord.gg/K9zernJB5z) first, and file bugs or small improvements as [issues](https://github.com/openfrontio/OpenFrontIO/issues/new/choose). You must be assigned to an `approved` issue — unsolicited PRs will be auto-closed. **Add approved & assigned issue number here:** Resolves #4323 ## Description: Made stations use euclidean distance for radius for checking if other stations are close enough, removed redundant if check and unneeded config <img width="1920" height="1080" alt="Screenshot from 2026-06-18 14-19-48" src="https://github.com/user-attachments/assets/a84f29f8-0cc1-46ea-9b96-3d70d6b0b20a" /> ## Please complete the following: - [x] I have added screenshots for all UI updates - [x] I process any text displayed to the user through translateText() and I've added it to the en.json file - [x] I have added relevant tests to the test directory ## Please put your Discord username so you can be contacted if a bug or regression is found: tktk1234567 |
||
|
|
805f0968b1 |
Add impassable terrain 🗺️ (#4340)
## Description: Relates to #3725 Adds a new **Impassable** terrain type that enables non-rectangular maps and creates impassable barriers on the map. Painted with pure black (`#000`) in the map editor's `image.png`. **Encoding:** Impassable terrain is encoded in the binary format as `isLand=1, magnitude=31` (previously unused). The Go map generator detects `#000` pixels and produces this encoding. The map generator's minimap downscaling gives impassable highest priority (Impassable > Water > Land). Thumbnails render impassable as transparent so the map picker background shows through. **Rendering:** Impassable tiles render as the map background colour (`rgb(60, 60, 60)`, matching `gl.clearColor` in `Renderer.ts`), making them visually indistinguishable from the area outside the map quad. This enables maps to appear non-rectangular. **Gameplay restrictions:** Impassable terrain cannot be: - Owned (`conquer()` throws) - Attacked (`AttackExecution` skips impassable tiles in both `tick()` and `addNeighbors()`) - Nuked (targeting rejected in `nukeSpawn()`, blast radius filtered in `tilesToDestroy()`) - Spawned on (nations, human players, and structures all reject impassable tiles) - Converted to water (guarded in `WaterManager` and `setWater()`) **Nuke trajectories:** Nuke trajectories cannot cross impassable terrain, matching the existing map-border enforcement. This is checked at launch time in `NukeExecution.tick()`. The client-side trajectory preview turns red with a red X where the arc crosses impassable terrain (reusing the existing SAM-intercept visual pipeline in `NukeTrajectory.ts`). The nuke ghost preview is completely hidden when hovering over impassable terrain (same as hovering outside the map). https://github.com/user-attachments/assets/ff131146-9749-41e0-892a-617e5cd16c54 Impassable terrain is transparent on the thumbnail: <img width="213" height="152" alt="Screenshot 2026-06-18 211640" src="https://github.com/user-attachments/assets/ede16f8c-9239-4ab1-be5d-0ba81cce5e9e" /> Tested with water nukes, made sure there is no water depth gradient near the impassable terrain, just like at the world border: <img width="774" height="771" alt="Screenshot 2026-06-18 212348" src="https://github.com/user-attachments/assets/4429069d-911b-48e8-91e3-7307d42c9397" /> Models used: GLM 5.2 and MiMo 2.5 Pro 😄 ## Please complete the following: - [X] I have added screenshots for all UI updates - [X] I process any text displayed to the user through translateText() and I've added it to the en.json file - [X] I have added relevant tests to the test directory ## Please put your Discord username so you can be contacted if a bug or regression is found: FloPinguin |
||
|
|
6e892839e8 |
Ofm tournament - Log Final standings and Per-Kill eliminations (#4350)
**Add approved & assigned issue number here:** Resolves #4349 ## Description: The infra related PR is linked to this one and would need to be pushed first (376) Two changes for organized/tournament matches: 1. **Final standings.** `setWinner` snapshots each player's tiles owned at game end into `PlayerStats` (`finalTiles`). It's a deterministic integer captured in the sim, so it's replay-safe and rides into the existing game record. This lets standings be derived directly (winner, then surviving players by territory, then eliminated players by when they died) without re-simulating, which matters because a domination win ends with many players still alive. 2. **Per-kill log**. Records, per player, which humans they eliminated and at what tick (kills on PlayerStats). This lets standings attribute each kill to the victim's final placement, and gives a deterministic kill graph for integrity review. Hooked once in conquerPlayer (the single elimination funnel), humans only. Additive optional field that rides the existing game record, no archive or wire changes. These are off by default with no effect on normal play. ## Please complete the following: - [x] I have added screenshots for all UI updates (no UI changes in this PR) - [x] I process any text displayed to the user through translateText() and I've added it to the en.json file (no new user-facing text) - [x] I have added relevant tests to the test directory ## Please put your Discord username so you can be contacted if a bug or regression is found: zixer._ |
||
|
|
ff5eb78689 |
Login with Google — client UI (#4028) (#4279)
Resolves #4028 (client half — backend is openfrontio/infra#368, which must be deployed first). ## Description: Adds "Login with Google" to the client, alongside the existing Discord login. Companion to the backend PR (openfrontio/infra#368). - `Auth.ts` — `googleLogin()` (full-page redirect to `/auth/login/google?redirect_uri=…`, mirrors `discordLogin()`). - `ApiSchemas.ts` — `GoogleUserSchema` + optional `user.google` on `UserMeResponseSchema`. - `AccountModal.ts` — a "Login with Google" button (Google brand guidelines: white surface, dark text, the multicolor "G" mark) in the login options, and the logged-in view now renders a Google-authenticated user's email (also added `google` to `isLinkedAccount()`). - `en.json` — `main.login_google`. - `resources/images/GoogleLogo.svg` — the Google "G" mark. > **Draft.** Depends on infra#368 being deployed (the button hits the live `/auth/login/google`). ## Please complete the following: - [x] I have added screenshots for all UI updates <!-- TODO: add screenshot of the Google button --> - [x] I process any text displayed to the user through translateText() and I've added it to the en.json file - [x] I have added relevant tests to the test directory <!-- no client tests exist for AccountModal/Auth; verified via tsc --noEmit + eslint. Backend behaviour is covered in infra#368 --> ## Please put your Discord username so you can be contacted if a bug or regression is found: jish |
||
|
|
21291b9fa3 |
Add trade ship captured event with toggle setting (#4344)
## What Notify a player when one of their trade ships is captured. The alert appears in the **less-important (top) events tier** and is gated behind a new in-game setting (on by default). ## Why Previously there was no notification to the player who *lost* a trade ship — only the capturer got a transient +gold pip on the ship's arrival. This surfaces the loss to the victim, while letting players opt out if they find it noisy. ## Changes - **`src/core/execution/TradeShipExecution.ts`** — On capture detection, emit a display message (`events_display.trade_ship_captured`, type `UNIT_DESTROYED`) to the original owner. Fires once, guarded by the existing `wasCaptured` flag. `UNIT_DESTROYED` is not a Tier-1 type, so it lands in the top/less-important tier. - **`src/client/hud/layers/EventsDisplay.ts`** — Suppress the message when the setting is off, following the existing key-based filter pattern. - **`src/core/game/UserSettings.ts`** — New `tradeShipCapturedEvents()` getter (default `true`) + `toggleTradeShipCapturedEvents()`. - **`src/client/hud/layers/SettingsModal.ts`** — New toggle in the in-game settings modal. - **`resources/lang/en.json`** — New `events_display.trade_ship_captured` and `user_setting.trade_ship_captured_label`/`_desc` keys. - **`tests/core/executions/TradeShipExecution.test.ts`** — Tests that the notification is sent to the original owner with the right args and only once across ticks. ## Notes - The setting is gated client-side (in `EventsDisplay`), keeping `src/core` free of client-local localStorage settings — consistent with how display events are already filtered there. - Reused `MessageType.UNIT_DESTROYED` (red/"loss" styling) rather than adding a new message type, to keep the change minimal. Happy to add a dedicated type/color if preferred. ## Testing - `npx vitest tests/core/executions/TradeShipExecution.test.ts --run` — 7 passed - lint clean, no type errors 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
9881b118e4 |
Fix anonymous-names setting not hiding names on the map (#4345)
## Problem Enabling the **hidden names** (anonymous names) setting hid names in the leaderboard/HUD but **not on the map**. The GL name renderer (`NamePass`) drew `slot.static.displayName` — always the real name — and never consulted `userSettings.anonymousNames()`. The HUD works because it calls `PlayerView.displayName()` (which honors the setting) on each render, but the names baked into the GPU texture bypassed that path entirely. ## Fix Push the *resolved* name into the renderer instead of the raw static name: - **`WebGLFrameBuilder.syncPlayers`** registers each player with `displayName: p.displayName()` (honors the setting) instead of `static.displayName`. Covers enabling the setting before a game and players who join after a toggle. - **`WebGLFrameBuilder.refreshNames` → `MapRenderer` → `Renderer` → `NamePass.refreshNames`** is a new path that re-resolves cached names and forces a re-upload (resets `slot.nameLen = 0`, which also recomputes the name half-width so it stays centered). - **`ClientGameRunner`** listens for the `settings.anonymousNames` change event and calls `refreshNames`, mirroring the existing territory-patterns live toggle. ## Behavior - Enabled before a game → players register with anonymous names. - Toggled mid-game → map names flip to/from anonymous on the next sim tick (~100ms), matching the leaderboard. - Your own name is unaffected (unchanged — `PlayerView` maps the local player's anonymous name to their real name). ## Testing `tsc --noEmit` passes for all edited files. This is a WebGL rendering change with no straightforward unit test; verified by tracing the data flow (resolved name → cached `slot.static.displayName` → re-upload on dirty). 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com> |
||
|
|
58e8a5fabd |
Fix ocean color change reverting nuke-created water to land (#4343)
## Problem Changing the ocean/water color in **Graphics settings** repaints the terrain — and any water tiles created by water nukes (land → water) snap back to their original land appearance. ## Root cause `TerrainPass` captures the `terrainBytes` buffer at construction and reuses it in two places: - `setOceanColor()` does a **full** terrain texture re-upload from `terrainBytes` when the ocean color changes. - `applyTerrainDelta()` applies live land→water nuke conversions, but only wrote to the **GPU texture** — never back into `terrainBytes`. So the CPU buffer stayed frozen at the map's original terrain. Changing the ocean color rebuilt the whole texture from that stale buffer, reverting every nuke crater to land. ## Fix Write each delta byte back into `terrainBytes` inside `applyTerrainDelta()`, so the buffer stays the live source of truth and full re-uploads reflect conversions. ```ts this.terrainBytes[ref] = bytes[i]; ``` The indexing already lines up — `terrainBytes` is indexed by linear ref (`y * mapW + x`), the same `ref` the delta loop iterates. The buffer is only otherwise read once at construction by `RailroadPass`/`TerrainPass` to seed GPU textures (which copy), so mutating it has no side effects elsewhere. ## Testing The WebGL passes have no unit-test harness (they need a live GL context), so this isn't covered by an automated test. Verified by reasoning through the data flow; can confirm in-game by nuking land into water and then changing the ocean color. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com> |
||
|
|
117fa43947 |
Fix nuke preview showing teammate SAMs as threats (#4342)
## Problem In the nuke trajectory preview, the SAM-intercept **"X"** marker was drawn over **teammates'** SAMs — implying their SAM would shoot down your missile. It shouldn't: like allies, a teammate's SAM never engages your nuke. The bug only affected teammates; allies already worked. ## Cause The preview built its threat set from `myPlayer.allies()` only — formal alliances — and never considered teammates. That diverged from the sim ([`SAMLauncherExecution.ts`](src/core/execution/SAMLauncherExecution.ts#L118-L134)), which skips any nuke whose owner it's `isFriendly()` with (**same team OR allied**). ## Fix `samThreatensNukePreview` now takes a teammate set and excludes teammates **unconditionally**. The subtlety: allies keep the existing *betrayal* exception — a strike close enough to break the alliance makes that ally's SAM engage at launch (`listNukeBreakAlliance`, the same function the sim uses). Teammates get **no** such exception, because a strike can break an alliance but never a team relationship. So even a player who is both a teammate *and* a betrayed ally is correctly left off the threat set. ## Notes - The sim has an "aftergame fun" exception where teammate SAMs *do* target teammate nukes once there's a winner. The preview only appears while aiming a buildable mid-game (no winner yet), so that case doesn't apply here. ## Tests Updated `samThreatensNukePreview` unit tests for the new signature and added coverage for: teammate excluded, and teammate stays excluded even when listed as betrayed. All 11 tests pass. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com> |
||
|
|
16996d489c |
Hide clan tag input on CrazyGames (#4341)
## Summary Clans aren't supported on CrazyGames, so don't let players set a clan tag there. - Tag the clan tag input wrapper with the existing `no-crazygames` class so Main.ts's hiding logic removes it on CrazyGames, matching how other CrazyGames-hidden elements work. - Guard loading the stored clan tag (`loadStoredUsername`) so a tag saved on the main site isn't silently submitted in the handshake while on CrazyGames — CSS hiding alone wouldn't prevent that. - Guard storing the tag (`validateAndStore`) so a returning user's saved tag isn't clobbered with an empty value during a CrazyGames session. ## Testing - `npx tsc --noEmit` — clean (no UsernameInput errors) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
0e7c33a594 |
Cap renderer device-pixel-ratio at 2 (#4339)
## What
Routes every renderer call site that read `window.devicePixelRatio`
through a single `renderDpr()` helper that caps the value at **2**.
```ts
export function renderDpr(): number {
return Math.min(window.devicePixelRatio || 2, 2);
}
```
## Why
On very high-DPI displays (DPR 3, common on phones) the WebGL backing
store was sized at 3× CSS pixels — ~9× the fragment work of 1× — for a
marginal visual gain over 2×. Capping at 2 keeps retina (DPR 2)
pixel-perfect while clamping the 3× case.
## How it stays correct
DPR isn't just the canvas size — it's one coordinate system shared by:
- the canvas backing-store size (`Renderer.resize`)
- the camera's screen↔world math (`Camera.resize` / `screenToWorld` /
`worldToScreen`)
- the camera zoom scale (`ClientGameRunner.syncCamera`)
- the constant-CSS-pixel-size world text (`WorldTextPass`)
These must all use the same DPR value or pointer hit-testing and text
sizing drift. Routing them through one helper guarantees that. The
diagnostics reporter (`Diagnostic.ts`) is intentionally left reading the
real hardware DPR, since its job is to report the actual device.
## Test
- `tsc --noEmit` clean for all touched files (one pre-existing unrelated
`marked` types error remains on `main`).
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
|
||
|
|
ca5342d6bf |
Render spawn overlay with instancing to support large lobbies (#4322)
## Problem The spawn-phase overlay stored every human's spawn center in GLSL **uniform arrays** (capped at `MAX_SPAWNS = 32`) and looped over all of them **per screen pixel** in a fullscreen pass. In lobbies with more than 32 humans, centers past the cap were silently dropped in join order — so a few seconds into the spawn phase the **local player's own ring could disappear while the phase was still active**. Team modes make this worse: `playerTeams` can be a raw team count, so a single team can have far more than 32 members, all of which need rings. The two walls that blocked simply raising the constant: - **Uniform arrays cap out ~96** against WebGL2's 224-vec4 fragment floor — 1024 would never link. - The **fullscreen per-pixel loop** over every spawn is `O(pixels × spawns)` — raising the cap makes it a GPU hazard during the spawn phase. ## Fix Rewrite `SpawnOverlayPass` to draw **one instanced quad per spawn center**, sized to that center's influence radius (mirroring `SAMRadiusPass`). This removes the uniform-array limit and the per-pixel loop, so cost scales with the number of spawns rather than screen area, and the overlay supports the renderer's full ~1024-player ceiling. Instances are ordered **enemies → teammates → self** so the local player's ring composites on top under normal alpha blending. Self/teammate render as breathing rings; enemies render as tile-fill highlights on unowned tiles — identical visuals and render-settings to before. ## Changes - `gl/passes/SpawnOverlayPass.ts` — instanced rendering via `DynamicInstanceBuffer` + `drawArraysInstanced`; no `MAX_SPAWNS` cap. - `shaders/spawn-overlay/spawn-overlay.frag.glsl` — per-instance (kind-dispatched) instead of a uniform-array loop; self white→color pulse moved into the shader. - `shaders/spawn-overlay/spawn-overlay.vert.glsl` — new instanced vertex shader. ## Testing - `tsc` (full project) + `eslint` clean. - Headless WebGL run: shaders **compile and link** (game starts normally with 123 players), and the genuine `updateSpawnOverlay → update() → drawArraysInstanced()` path renders self/teammate rings and enemy tile highlights with **no GL errors**. - ⚠️ Not yet verified end-to-end in a real 30+ human FFA lobby (the original repro) — that needs multiple real clients. The instanced draw path and rendering were confirmed in singleplayer with the overlay force-activated. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
661d96ba28 |
Fix structure cost double-counting units under construction (#4320)
## Problem
The ghost/build-menu price of a structure can show the wrong (inflated)
cost. Concretely: a player who owns a **captured** city and then starts
building their **first** city sees the 3rd-city price (**500k**) for
that build instead of the 2nd-city price (**250k**).
## Root cause
Structure cost scales as `2^(units built) × base` (city: 125k / 250k /
500k …), counted via:
```ts
Math.min(player.unitsOwned(type), player.unitsConstructed(type))
```
The `Math.min` is deliberate — it caps the count at how many you've
actually **built**, so **captured** units (owned but not built) don't
inflate the price.
`unitsConstructed()` defeated that by double-counting in-progress
builds:
```ts
const built = this.numUnitsConstructed[type] ?? 0; // already includes the building unit
let constructing = 0;
for (const unit of this._units) {
if (unit.type() !== type) continue;
if (!unit.isUnderConstruction()) continue;
constructing++; // counts the SAME unit again
}
return constructing + built; // doubled
```
`recordUnitConstructed()` is called in `buildUnit()` the moment the unit
is created — while it is still under construction — so
`numUnitsConstructed` already accounts for in-progress builds. The extra
loop counted them a second time.
With one captured city + one city under construction: `unitsOwned = 2`,
double-counted `unitsConstructed = 2`, so `Math.min(2, 2) = 2` → 500k.
Without the double-count it's `Math.min(2, 1) = 1` → 250k. ✅
The redundant loop is a leftover from #2378, which removed the separate
`UnitType.Construction` unit. Back then in-progress builds were a
distinct unit type **not** recorded in `numUnitsConstructed`, so the
loop was needed; afterward it became a pure double-count. This is a
long-standing latent bug — present identically on `v31` — not a recent
regression.
## Fix
`unitsConstructed()` now just returns `numUnitsConstructed[type]`, which
already includes under-construction builds.
## Tests
`tests/economy/ConstructionCost.test.ts` covers both:
- pure case (first city under construction) → still 250k
- captured city + first city under construction → was 500k, now 250k
(fails without the fix with `expected 2 to be 1`)
All related suites (economy, PlayerImpl, nation structure behavior,
upgrades, MIRV pricing, stats) — 144 tests — pass.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
|
||
|
|
305534cc65 |
Dispose WebGL renderer when a game stops 🧹 (#4295)
## Problem `ClientGameRunner.stop()` tore down the worker, network, and sound, but left the `MapRenderer` (and its WebGL context), the WebGL canvas, the input overlay, and the self-driving RAF loop in place. When you exit a game via the **Exit button** or browser **back**, the page navigates to `/`, so the browser reclaims everything — that path is fine. But you can start a new game **without** a reload: matchmaking and joining another lobby go through `handleJoinLobby`, which calls `lobbyHandle.stop(true)` then `joinLobby()` on the same document. The old WebGL context stayed alive (the never-cancelled RAF kept it referenced, so it wasn't even GC'd), and each new game stacked another context. After a few games, mobile browsers hit their WebGL context limit — matching the repro in #4267. ## Fix `stop()` now disposes the renderer: - cancels the self-driving RAF loop and disconnects the frame-loop resize observer - disposes the `MapRenderer` (frees all GPU resources) - removes the WebGL canvas and the input overlay from the DOM `GPURenderer.dispose()` additionally calls `WEBGL_lose_context.loseContext()` so the context is released promptly instead of waiting on unreliable GC. The territory-patterns settings listener is wired to the existing graphics `AbortController` so it no longer outlives the disposed view. The cleanup runs unconditionally in `stop()` (a superseded join can stop before the game becomes active) and is idempotent against repeated `stop()` calls. Fixes #4267 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
64409cae4d |
Animate HUD troop/population bars with transform instead of width (#4319)
## Problem The troop and population ratio bars in `ControlPanel` and `PlayerInfoOverlay` update their inline `width` on every game tick, with a `transition-[width] duration-200` to smooth the change. But `width` is a layout property — animating it forces the browser to **recalculate layout for the surrounding HUD components every animation frame**. Since the width changes every tick, this kept the whole HUD in a near-constant relayout loop and showed up as jank. ## Fix Keep the smooth animation, but drive it with `transform` (GPU-composited, no layout) instead of `width`: - Replace the two flex `width: %` segments with absolutely-positioned, full-width bars. - Segment 1: `transform: scaleX(green/100)` anchored to the left edge (`origin-left`). - Segment 2: `transform: translateX(green%) scaleX(orange/100)` so it stays flush against the first segment. - Animate with `transition-transform duration-200 ease-out`. Because `transform` is composited rather than laid out, the bars animate smoothly **without** triggering the per-frame HUD relayout. The segments are now always mounted (`scaleX(0)` when empty) instead of conditionally rendered, which also prevents the transition from resetting as values cross zero. Files: - `src/client/hud/layers/ControlPanel.ts` (mobile + desktop troop bars: malibu-blue / aquarius) - `src/client/hud/layers/PlayerInfoOverlay.ts` (sky-700 / malibu-blue) A grep confirmed these were the only `transition-[width]` usages in the client. ## Testing - `eslint --fix` / prettier ran clean via the pre-commit hook. - CSS-only change; no sim/behavioral logic touched. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com> |
||
|
|
83cd864018 |
Show rail ghost for initial factory 🚂 (#4294)
## Problem Fixes #4284. When you build a factory in an area with **no pre-existing factory** (e.g. just a city nearby), no rail ghost preview appeared — even though building the factory *would* lay rail lines connecting it to that city. ## Root cause `computeGhostRailPaths` in `RailNetworkImpl.ts` had two factory-hostile assumptions: 1. It bailed out early unless a `Factory` was already in range (`hasUnitNearby(..., UnitType.Factory)`). 2. It only matched neighbors that were *already* train stations (`findStation(...)` → skipped if null). But a **Factory** always becomes a station itself and *promotes* nearby City/Port/Factory into the rail network (see `FactoryExecution`). So it needs no pre-existing factory, and its neighbors won't be stations yet on first build. A **City/Port** only joins the network when a factory already exists (`CityExecution`/`PortExecution`) — so their behavior is correctly left unchanged. ## Fix - Skip the "factory must be nearby" gate when the placed unit is itself a `Factory`. - For a factory build, pathfind to nearby City/Port/Factory even if they aren't stations yet. City/Port keep connecting only to existing stations. ## Tests Added two cases to `RailNetwork.test.ts` (factory connects with no pre-existing factory; city still doesn't without one). All 25 tests pass. ## Note on scope As @Katokoda noted on the issue, a fully build-exact preview (neighboring structures also connecting to *each other*, merging existing networks, etc.) is larger and order-dependent. This PR resolves the reported bug — the initial factory now shows its rail ghost — and leaves the exact-match cascade as a separate follow-up. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
678112492c |
Fix per-frame layout jank when focusing a toggle-input-card field (#4314)
## Problem
Focusing the number field of a `toggle-input-card` (Game Timer / Gold
Multiplier / Starting Gold, in both the single-player and host-lobby
modals) cost several ms of layout/paint **every tick** for as long as
the field stayed focused.
## Root cause
The input was rendered **conditionally** — `${this.checked ?
html`…<input>…` : nothing}`. Enabling a toggle therefore **freshly
inserts** the `<input>` into the DOM, and **focusing a just-inserted
input** is what forced the per-frame layout/paint. An input that was
already present in the DOM doesn't do this.
## Fix
Keep the input **permanently mounted** and toggle a `hidden` class when
unchecked, instead of conditionally rendering it. Focusing it is then
always focusing an element that was already there. Because both modals
share `<toggle-input-card>`, this single change fixes both.
Also restores the **autofocus + select** of the field on enable (it had
been removed earlier while chasing this bug) — safe now that the input
isn't freshly inserted.
No other UX change: the toggle behavior, checkmark, styling, and all
three cards behave identically.
## Testing
Hard-reload, then in both the Solo and Host-lobby modals, enable each of
Game Timer / Gold Multiplier / Starting Gold, type a value, and keep the
field focused — smooth, no per-frame jank, and the field autofocuses on
enable.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
|