diff --git a/CHANGELOG.md b/CHANGELOG.md index 37997eaa..f96c8314 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Added +- Bots with character (#64): every bot is a named rider of a made-up cast ("Gus Tailwind", "Penny Farthing") (and, rarely, Goldie Lemon in lemon yellow) with a riding type (rouleur, climber, sprinter, attacker, tourer) and a team kit, the same everywhere. Bots now race you: they take turns on the front of a group and swing off, attack near the top of a climb, take up the chase when you come past and sprint for the line, as long as their energy (W′) lasts. They ride in groups that spawn out of sight around every rider (mostly a group ahead to chase, sometimes one coming up from behind),; the number of riders per route is still `OPENRADLR_TARGET_RIDERS`. The 3D view shows bots in their team's kit, the rider list names their type, and the ticker calls out moves near you. - Golden lemons: a few lemons float over the road, each in one lane, and move to new places every day (the same for every rider). Ride through one in its lane to collect it; they grow back every lap. A pickup shows in the ticker with your all-time count, and the finish screen lists the ride's lemons. No counter on the HUD: it's an easter egg. - Ghost lap: your best lap on a loop route is kept in the browser, and a see-through rider labelled "Best lap" rides it again from the line, lane changes and all. The HUD shows the live gap ("Best lap +4.2 s", red behind, green ahead), and a faster lap becomes the new ghost at once. Hidden in races and events. - Crowds along the route: spectators line the last 600 m of every climb in loose groups, thicker towards the top, and every sprint line gets a crowd behind barriers. They turn towards a rider coming by and cheer harder (penguins clap faster), and some wave flags. The more riders are online, the more of them come out; bots don't count. diff --git a/client/public/js/i18n/de.js b/client/public/js/i18n/de.js index 36cb45bf..9624561d 100644 --- a/client/public/js/i18n/de.js +++ b/client/public/js/i18n/de.js @@ -274,6 +274,15 @@ export default { "panels.remote.other": "{n} aus anderen Apps", "panels.botSuffix": "(Bot)", "panels.bot": "Bot", + "panels.botStyle.rouleur": "Rouleur-Bot", + "panels.botStyle.climber": "Kletterer-Bot", + "panels.botStyle.sprinter": "Sprinter-Bot", + "panels.botStyle.attacker": "Angreifer-Bot", + "panels.botStyle.tourer": "Tourenfahrer-Bot", + "bots.attack": "{name} greift an!", + "bots.sprint": "{name} geht in den Sprint!", + "bots.answer": "{name} nimmt die Verfolgung auf!", + "bots.pull": "{name} geht nach vorn und übernimmt die Führung.", "panels.joined": "{who} ist beigetreten", "panels.race.countdown": "Rennen über {laps} startet in {s} s", "panels.race.started": "Rennen gestartet — los!", diff --git a/client/public/js/i18n/en.js b/client/public/js/i18n/en.js index 146ecdd5..8c1bef2a 100644 --- a/client/public/js/i18n/en.js +++ b/client/public/js/i18n/en.js @@ -274,6 +274,15 @@ export default { "panels.remote.other": "{n} from other apps", "panels.botSuffix": "(bot)", "panels.bot": "bot", + "panels.botStyle.rouleur": "rouleur bot", + "panels.botStyle.climber": "climber bot", + "panels.botStyle.sprinter": "sprinter bot", + "panels.botStyle.attacker": "attacker bot", + "panels.botStyle.tourer": "tourer bot", + "bots.attack": "{name} attacks!", + "bots.sprint": "{name} goes for the sprint!", + "bots.answer": "{name} takes up the chase!", + "bots.pull": "{name} comes through for a turn on the front.", "panels.joined": "{who} joined", "panels.race.countdown": "Race over {laps} starts in {s} s", "panels.race.started": "Race started — go!", diff --git a/client/public/js/main.js b/client/public/js/main.js index 11dd46c0..3a7525c9 100644 --- a/client/public/js/main.js +++ b/client/public/js/main.js @@ -39,6 +39,7 @@ import { JUNCTION_WINDOW_M, OFF_ROUTE_ID, junctionAhead, offRouteRoad, stepOptio import { RideAutosave, continueAllowed, indexedDbStore, unfinishedLabel } from "./ride/rideAutosave.js"; import { backToMenuWarning, createFinishController } from "./ride/finishController.js"; import { LemonHunt, lemonDay, lemonsFor } from "./ride/lemons.js"; +import { BotCalls } from "./ride/botCalls.js"; import { GhostStore, LapRun, formatLapGap, ghostAt, timeAt } from "./ride/ghostLap.js"; import { MilestoneWatch, lifetimeTotals } from "./ride/milestones.js"; import { RideHistory, rideRecord } from "./ride/rideHistory.js"; @@ -331,6 +332,8 @@ const app = { splits: [], shownSplits: 0, splitToastTimer: null, + /** Bots' moves near me, called out in the ticker (#64). */ + botCalls: new BotCalls(), /** Golden lemons on my route (null off the routes, in the studio and workouts), and how many this ride collected. */ lemonHunt: null, lemonsThisRide: 0, @@ -1440,6 +1443,13 @@ function runAction(action) { } /** A message for the rider: kept in the feed drawer and shown briefly on the HUD. */ +const BOT_CALL_TEXT = Object.freeze({ attack: "bots.attack", sprint: "bots.sprint", answer: "bots.answer", pull: "bots.pull" }); + +/** A line in the ticker when a bot near me starts a move (#64). */ +function callBotMoves(riders, me) { + for (const call of app.botCalls.update({ riders, me, route: app.route, nowS: now() })) notify(t(BOT_CALL_TEXT[call.move], { name: call.name })); +} + function notify(text, kind = "event") { appendFeed($("feed"), text, kind); if (!$("hud-ticker")) return; @@ -1787,6 +1797,7 @@ function endRide() { splits: [], shownSplits: 0, splitToastTimer: (clearTimeout(app.splitToastTimer), ($("split-toast").hidden = true), null), + botCalls: new BotCalls(), lemonHunt: null, lemonsThisRide: 0, lemonTotal: 0, @@ -1873,6 +1884,7 @@ function wireConnection(connection) { app.state = { ...message, riders: riders.filter(onMyRoute), elsewhere }; // The workout screen has none of the ride panels. if (!app.workout) updatePanels(); + if (!app.workout && app.route) callBotMoves(riders, me); }); on("studio_state", (message) => { app.state = message; diff --git a/client/public/js/ride/botCalls.js b/client/public/js/ride/botCalls.js new file mode 100644 index 00000000..27711a59 --- /dev/null +++ b/client/public/js/ride/botCalls.js @@ -0,0 +1,49 @@ +/** + * Calls out bots' moves near me in the ticker (#64): an attack, a sprint, a + * chase after me, a turn on the front. Only the start of a move counts, by a + * bot on my route within `BOT_CALLS.reachM`; a chase only when the bot is + * behind me. At most one line every `everyS`, and the same bot and move at + * most once every `repeatS`. Pure: the caller posts the lines. + */ +export const BOT_CALLS = Object.freeze({ reachM: 120, everyS: 15, repeatS: 90 }); + +const CALLED = new Set(["attack", "sprint", "answer", "pull"]); + +export class BotCalls { + /** Each bot's move when last seen (null while it just rides). */ + #moves = new Map(); + /** When each "bot:move" was last called out. */ + #said = new Map(); + #lastS = -Infinity; + + /** + * @param {{riders: object[], me: ?{route: ?string, distance: number}, route: {signedGap(a: number, b: number): number}, nowS: number}} frame + * @returns {{id: number, name: string, move: string}[]} the line to post, if any + */ + update({ riders, me, route, nowS }) { + const started = []; + const seen = new Set(); + for (const rider of riders) { + if (!rider.is_bot) continue; + seen.add(rider.id); + const known = this.#moves.has(rider.id); + const before = this.#moves.get(rider.id); + const move = rider.move ?? null; + this.#moves.set(rider.id, move); + // A bot first seen mid-move didn't start it in front of me. + if (!known || !move || move === before || !CALLED.has(move)) continue; + if (!me?.route || rider.route !== me.route) continue; + const gap = route.signedGap(me.distance, rider.distance); + if (Math.abs(gap) > BOT_CALLS.reachM) continue; + if (move === "answer" && gap >= 0) continue; + started.push({ id: rider.id, name: rider.name, move }); + } + for (const id of this.#moves.keys()) if (!seen.has(id)) this.#moves.delete(id); + if (nowS - this.#lastS < BOT_CALLS.everyS) return []; + const call = started.find((c) => nowS - (this.#said.get(`${c.id}:${c.move}`) ?? -Infinity) >= BOT_CALLS.repeatS); + if (!call) return []; + this.#lastS = nowS; + this.#said.set(`${call.id}:${call.move}`, nowS); + return [call]; + } +} diff --git a/client/public/js/view/botKits.js b/client/public/js/view/botKits.js new file mode 100644 index 00000000..35ec4ace --- /dev/null +++ b/client/public/js/view/botKits.js @@ -0,0 +1,20 @@ +/** + * Bot teams' kit colours (#64). The server sends each bot's `team`; its jersey + * takes the team's colour in the 3D view. None is orange (me) or sky blue + * (humans), so bots still read as bots. Unknown teams keep the bot grey. + */ +export const TEAM_KITS = Object.freeze({ + zitrone: "#f2cf2a", + moos: "#4f8f3a", + kirsche: "#b3263a", + lavendel: "#8c6bc8", + kreide: "#ecebe4", + schiefer: "#2f3339", + petrol: "#1f7f7a", + rose: "#e58fb2", +}); + +/** A bot's kit colour (`#rrggbb`), or null for humans and unknown teams. */ +export function botKit(rider) { + return (rider?.is_bot && Object.hasOwn(TEAM_KITS, rider.team) && TEAM_KITS[rider.team]) || null; +} diff --git a/client/public/js/view/panels.js b/client/public/js/view/panels.js index a0261b0d..7429cf89 100644 --- a/client/public/js/view/panels.js +++ b/client/public/js/view/panels.js @@ -149,12 +149,27 @@ export function riderName(rider) { return isPaddler(rider) ? `${rider.name} ${PADDLE_BADGE}` : rider.name; } +const BOT_STYLES = Object.freeze({ + rouleur: "panels.botStyle.rouleur", + climber: "panels.botStyle.climber", + sprinter: "panels.botStyle.sprinter", + attacker: "panels.botStyle.attacker", + tourer: "panels.botStyle.tourer", +}); + +/** A bot's badge: its riding type ("climber bot"), or plain "bot" (#64). */ +export function botBadgeText(rider) { + return Object.hasOwn(BOT_STYLES, rider.style) ? t(BOT_STYLES[rider.style]) : t("panels.bot"); +} + export function renderRiderList(list, entries, myId) { list.replaceChildren( ...entries.map(({ rider, gap, routeName }) => { const item = element("li", rider.id === myId ? "rider me" : "rider"); - const name = element("span", "rider-name", rider.name); - if (rider.is_bot) name.append(element("span", "badge", t("panels.bot"))); + // The name gives way to the badges: a bot is always marked, however long its name. + const name = element("span", "rider-name split"); + name.append(element("span", "rider-name-text", rider.name)); + if (rider.is_bot) name.append(element("span", "badge", botBadgeText(rider))); if (isRemote(rider)) name.append(element("span", "badge badge-remote", rider.app)); if (isPaddler(rider)) name.append(paddleBadge()); item.append(name, element("span", "rider-power", `${Math.round(rider.power)} W`), element("span", "rider-gap", rider.id === myId ? "" : gap === null ? routeName : formatGap(gap))); diff --git a/client/public/js/view3d/view3d.js b/client/public/js/view3d/view3d.js index b9f14e05..d4a07b18 100644 --- a/client/public/js/view3d/view3d.js +++ b/client/public/js/view3d/view3d.js @@ -3,6 +3,7 @@ * floating name labels. Same inputs as the 2D views (smoothed riders), so it * needs no protocol changes. */ +import { TEAM_KITS, botKit } from "../view/botKits.js"; import { CAMERA_MODES, ChaseCamera } from "./chaseCamera.js"; import { clipFor, mirrorPlant, mirrorPose, settle } from "./clips.js"; import { chunkNear, chunkVisible } from "./chunks.js"; @@ -69,6 +70,14 @@ export function hexToRgb(hex) { return [((n >> 16) & 255) / 255, ((n >> 8) & 255) / 255, (n & 255) / 255]; } +/** Bot teams' kit colours as tints (#64). */ +const KIT_TINTS = new Map(Object.entries(TEAM_KITS).map(([team, hex]) => [team, hexToRgb(hex)])); + +/** A bot's jersey: its team's kit, else the bot grey. */ +function botTint(rider, tints) { + return (botKit(rider) && KIT_TINTS.get(rider.team)) || tints.bot; +} + /** * Projects a world point to CSS pixels. Returns null when it is behind the camera. * @returns {{x: number, y: number, depth: number} | null} @@ -656,7 +665,7 @@ export class View3D { const seatModel = multiply(base, placement(seat.hip, seat.yaw)); // The hip stays put when the rider is scaled: scale about it, then bring the solo hip to the origin. const legsModel = multiply(seatModel, multiply(scaling(look.scale), placement([0, -hy, -hz]))); - const tint = rider.id === myId ? tints.me : isRemote(rider) ? tints.remote : rider.is_bot ? tints.bot : tints.human; + const tint = rider.id === myId ? tints.me : isRemote(rider) ? tints.remote : rider.is_bot ? botTint(rider, tints) : tints.human; bodies.push({ variant: look.variant, model: multiply(seatModel, scaling(look.scale)), tint }); limbs.push(...this.#legs(legsModel, look, this.#pedal(rider.id, seatCadence(rider), dt))); heads.set(rider.id, transformPoint(seatModel, [0, 0.62 * look.scale + 0.55, 0]).slice(0, 3)); @@ -718,7 +727,7 @@ export class View3D { // Far riders are invisible anyway; riders right at the camera would block the view. if (fromCamera > 600 || (fromCamera < SCENE.nearCameraHide && rider.id !== myId)) continue; const cadence = rider.id === myId ? (myCadence ?? 0) : rider.power > 0 ? 85 : 0; - const tint = rider.ghost ? SCENE.ghost.tint : rider.id === myId ? tints.me : isRemote(rider) ? tints.remote : rider.is_bot ? tints.bot : tints.human; + const tint = rider.ghost ? SCENE.ghost.tint : rider.id === myId ? tints.me : isRemote(rider) ? tints.remote : rider.is_bot ? botTint(rider, tints) : tints.human; const parts = gym ? this.#workoutParts(rider, gym, timeS) : this.#riderParts(rider, position, forward, cadence, dt); visible.push({ rider, position, forward, fromCamera, tint, ghost: Boolean(rider.ghost), ...parts }); } diff --git a/client/public/styles.css b/client/public/styles.css index 67e66569..4d3cd854 100644 --- a/client/public/styles.css +++ b/client/public/styles.css @@ -2990,6 +2990,23 @@ body.riding { white-space: nowrap; } +.rider-name.split { + display: flex; + align-items: baseline; + min-width: 0; +} + +.rider-name-text { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + min-width: 0; +} + +.rider-name.split .badge { + flex: none; +} + .rider-gap, .rider-power { text-align: right; diff --git a/client/test/bots.test.js b/client/test/bots.test.js new file mode 100644 index 00000000..95a9c015 --- /dev/null +++ b/client/test/bots.test.js @@ -0,0 +1,113 @@ +import { test, afterEach } from "node:test"; +import assert from "node:assert/strict"; +import { BOT_CALLS, BotCalls } from "../public/js/ride/botCalls.js"; +import { TEAM_KITS, botKit } from "../public/js/view/botKits.js"; +import { botBadgeText } from "../public/js/view/panels.js"; +import { setLocale } from "../public/js/i18n/i18n.js"; + +afterEach(() => setLocale("en")); + +// --- kits -------------------------------------------------------------------------- + +const rgb = (hex) => [1, 3, 5].map((i) => Number.parseInt(hex.slice(i, i + 2), 16)); +const hue = ([r, g, b]) => { + const max = Math.max(r, g, b); + const min = Math.min(r, g, b); + if (max === min) return null; + const d = max - min; + const h = max === r ? ((g - b) / d) % 6 : max === g ? (b - r) / d + 2 : (r - g) / d + 4; + return (h * 60 + 360) % 360; +}; + +test("no team rides in my orange or the humans' sky blue", () => { + const me = hue(rgb("#ff7a1a")); + const human = hue(rgb("#4cc3ff")); + for (const [team, hex] of Object.entries(TEAM_KITS)) { + const h = hue(rgb(hex)); + if (h === null) continue; + const apart = (a, b) => Math.min(Math.abs(a - b), 360 - Math.abs(a - b)); + assert.ok(apart(h, me) > 15, `${team} is too close to orange`); + assert.ok(apart(h, human) > 15, `${team} is too close to sky blue`); + } +}); + +test("a bot wears its team's kit; humans and unknown teams none", () => { + assert.equal(botKit({ is_bot: true, team: "moos" }), TEAM_KITS.moos); + assert.equal(botKit({ is_bot: true, team: "nowhere" }), null); + assert.equal(botKit({ is_bot: true, team: "toString" }), null); + assert.equal(botKit({ is_bot: true }), null); + assert.equal(botKit({ is_bot: false, team: "moos" }), null); +}); + +// --- the badge -------------------------------------------------------------------- + +test("the bot badge names the riding type, in the rider's language", () => { + assert.equal(botBadgeText({ is_bot: true, style: "climber" }), "climber bot"); + assert.equal(botBadgeText({ is_bot: true }), "bot"); + assert.equal(botBadgeText({ is_bot: true, style: "unicyclist" }), "bot"); + setLocale("de"); + assert.equal(botBadgeText({ is_bot: true, style: "climber" }), "Kletterer-Bot"); +}); + +// --- ticker calls ----------------------------------------------------------------- + +const route = { signedGap: (from, to) => to - from }; +const me = { id: 1, route: "r", distance: 1000 }; +const bot = (move, distance = 1050, extra = {}) => ({ id: 7, name: "Gus Tailwind", is_bot: true, route: "r", distance, move, ...extra }); + +function calls(frames) { + const watch = new BotCalls(); + return frames.map(({ riders, nowS }) => watch.update({ riders, me, route, nowS })); +} + +test("a bot near me starting an attack is called out once", () => { + const out = calls([ + { riders: [bot(undefined)], nowS: 0 }, + { riders: [bot("attack")], nowS: 1 }, + { riders: [bot("attack")], nowS: 2 }, + ]); + assert.deepEqual(out, [[], [{ id: 7, name: "Gus Tailwind", move: "attack" }], []]); +}); + +test("a bot first seen mid-move, far away, on another route or a human is not called out", () => { + for (const [first, second] of [ + [null, bot("attack")], + [bot(undefined, 1000 + BOT_CALLS.reachM + 50), bot("attack", 1000 + BOT_CALLS.reachM + 50)], + [bot(undefined, 1050, { route: "other" }), bot("attack", 1050, { route: "other" })], + [bot(undefined, 1050, { is_bot: false }), bot("attack", 1050, { is_bot: false })], + ]) { + const out = calls([ + { riders: first ? [first] : [], nowS: 0 }, + { riders: [second], nowS: 1 }, + ]); + assert.deepEqual(out[1], [], JSON.stringify(second)); + } +}); + +test("a chase is only called out when the bot comes after me", () => { + const ahead = calls([ + { riders: [bot(undefined, 1030)], nowS: 0 }, + { riders: [bot("answer", 1030)], nowS: 1 }, + ]); + assert.deepEqual(ahead[1], []); + const behind = calls([ + { riders: [bot(undefined, 970)], nowS: 0 }, + { riders: [bot("answer", 970)], nowS: 1 }, + ]); + assert.equal(behind[1][0].move, "answer"); +}); + +test("calls are spaced out and the same bot's move isn't repeated soon", () => { + const other = (move) => ({ ...bot(move), id: 8, name: "Sally Sprocket" }); + const out = calls([ + { riders: [bot(undefined), other(undefined)], nowS: 0 }, + { riders: [bot("attack"), other("pull")], nowS: 1 }, + { riders: [bot(undefined), other(undefined)], nowS: 5 }, + { riders: [bot("attack"), other("pull")], nowS: 10 }, + { riders: [bot(undefined), other(undefined)], nowS: 30 }, + { riders: [bot("attack"), other("pull")], nowS: 40 }, + ]); + assert.equal(out[1].length, 1, "one line at a time"); + assert.deepEqual(out[3], [], `within ${BOT_CALLS.everyS} s of the last line`); + assert.deepEqual(out[5], [{ id: 8, name: "Sally Sprocket", move: "pull" }], "Gus's attack was called less than 90 s ago"); +}); diff --git a/client/test/remoteRiders.test.js b/client/test/remoteRiders.test.js index 40b8f997..8df0f5af 100644 --- a/client/test/remoteRiders.test.js +++ b/client/test/remoteRiders.test.js @@ -79,3 +79,13 @@ test("a remote name with markup stays text in the 3D label", () => assert.ok(nodes.some((node) => node.textContent === "")); assert.ok(nodes.some((node) => node.className.includes("badge") && node.textContent === "incyclist")); })); + +test("a bot's name and its type badge are apart in the row, so only the name is cut short (#64)", () => + withFakeDocument(() => { + const list = new FakeElement("ul"); + const bot = { id: 9, name: "Valentina Draftsworth", is_bot: true, style: "attacker", power: 150 }; + renderRiderList(list, [{ rider: bot, gap: 5, routeName: "" }], 1); + const nodes = list.all(); + assert.ok(nodes.some((node) => node.className === "rider-name-text" && node.textContent === "Valentina Draftsworth")); + assert.ok(nodes.some((node) => node.className === "badge" && node.textContent === "attacker bot")); + })); diff --git a/client/test/view3d.test.js b/client/test/view3d.test.js index c2170e8b..d62bac22 100644 --- a/client/test/view3d.test.js +++ b/client/test/view3d.test.js @@ -938,3 +938,22 @@ test("a penguin holds its flag lower, in its flipper", () => { const flag = renderer.draws.find((d) => d.handle === view.flagMesh); assert.ok(flag.model[13] < 101.2, `at ${flag.model[13]}`); }); + +// --- bot kits (#64) ------------------------------------------------------------------ + +test("a bot rides in its team's kit; one without a known team in the bot colour", () => { + const { view, renderer } = gymView([], "temperate", null, new RecordingRenderer()); + const me = { id: 1, name: "Me", distance: 100, lane: 1, speed: 8, power: 200 }; + // Past label range, so no DOM is needed. + const teamed = { id: 41, name: "Gus Tailwind", is_bot: true, team: "moos", distance: 200, lane: 0, speed: 8, power: 150 }; + const plain = { id: 42, name: "Sally Sprocket", is_bot: true, distance: 205, lane: 3, speed: 8, power: 150 }; + view.render({ riders: [me, teamed, plain], myId: 1, timeS: 3, colors }); + const tintAt = (rider) => { + const road = riderPosition(squareRoute(), rider.distance, rider.lane).position; + const body = view.bodies[riderLook(rider.id).variant]; + const draw = renderer.draws.find((d) => d.handle === body && Math.abs(d.model[12] - road[0]) < 0.01 && Math.abs(d.model[14] - road[2]) < 0.01); + return draw.tint.map((c) => Math.round(c * 255)); + }; + assert.deepEqual(tintAt(teamed), [0x4f, 0x8f, 0x3a]); + assert.deepEqual(tintAt(plain), [0, 0, 255]); +}); diff --git a/docs/adr/0022-bots-as-characters-with-tactics.md b/docs/adr/0022-bots-as-characters-with-tactics.md new file mode 100644 index 00000000..c16280df --- /dev/null +++ b/docs/adr/0022-bots-as-characters-with-tactics.md @@ -0,0 +1,36 @@ +# 22. Bots as characters with tactics, spawned around the riders + +Date: 2026-11-10 · Status: accepted + +## Context + +Bots kept every route at a fixed twelve riders. Each one: + +- got a random "Adjective Animal" name and riding style; +- rode a fixed share of its FTP; +- spawned wherever its route was emptiest. + +They never reacted to humans. On longer routes a rider was mostly alone, and meeting a bot changed nothing (#64). + +## Decision + +- **A cast, not random bots.** A bot's name is made up from fixed lists: a first name and a cycling pun for a surname ("Gus Tailwind"), so no real person or film character is borrowed. Its riding type (rouleur, climber, sprinter, attacker, tourer) and its team follow from a stable hash of the name, so the same name rides the same way everywhere. Fitness is still matched to the humans online. +- **Moves within an energy budget.** Each bot does one move at a time: ride, pull, swing off, attack, answer, sprint or recover. + - Moves start from what the bot sees: a line ahead, a rider coming past, a wheel behind, a human close by. + - They end on time or on energy. Energy is the W′ balance of the critical power model, with Skiba's recovery time constant, and FTP serves as critical power. + - Attacks and answers need a human close by (or a race), so bots alone on the map ride quietly. + - Moves only change power and lane choice. The physics, drafting and races are untouched. +- **Spawning follows the humans.** + - A route still keeps `OPENRADLR_TARGET_RIDERS` riders (`target_riders`), humans plus bots, and `0` still means no bots. Company comes out of that count; it adds none. + - Every human riding freely keeps `bots_near_human` bots within a window: 1.5 km ahead, 400 m behind. + - Missing company spawns in groups, out of sight. Mostly the groups are ahead and a bit slower (to chase), sometimes behind and a bit faster (to come by). + - On a full route, bots far from everyone make room. +- **The wire stays additive.** Bots' rider entries gain `team`, `style` and `move`. No version bump: older clients ignore them. + +## Consequences + +- **Every ride has company and something happens.** In a simulated hour on Col de la Forge, the rider was alone (no bot within 300 m) for 29 s instead of half the hour, with about one move nearby every four minutes. +- **The bot count and the server's load don't change.** `OPENRADLR_TARGET_RIDERS` stays the one setting. With a small target and many humans on one route, the company is thinner. +- **Bots now spawn in groups,** so the old test "bots start apart" became "groups start apart". +- **Bot tuning lives in `bot.rs` (`tactics`) and `SimConfig`.** Further characters (rivalries, a bot remembering you) can build on the stable cast. +- **Overlap with #17:** the spacing and passing PR (#17) touches the same files. The two combine (moves set power and a lane wish; spacing caps speed and steers past), but whichever merges second needs a rebase. diff --git a/docs/architecture.md b/docs/architecture.md index f302991f..9dda2bae 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -68,7 +68,7 @@ that died after its rider was taken over by a new one can't touch the rider. captain's road, then copies speed, position and lane to every seat. 5. Lanes move towards their target lane (one lane per second). 6. Finishers are recorded; the race completes when every participant finished. -7. Bots are spawned or removed to keep the target rider count. +7. Bots are spawned or removed to keep `OPENRADLR_TARGET_RIDERS` riders on every route. Each human keeps a few of them around: far bots make room, and groups spawn out of sight, ahead to chase or behind to come by (#64, ADR 0022). 8. The game core sends events to their route, every fifth tick each client the state of the riders around them, and new resistance whenever a rider's grade changed by at least 0.1 %. @@ -126,7 +126,7 @@ dependencies (see [ADR 0005](adr/0005-own-webgl-renderer.md)): | `island.js` | The map as an island: coast a seeded margin beyond the outermost roads, beaches, cliffs, sea floor | | `menuCamera.js`, `highlight.js` | Start menu: drone orbit over the island, glide down to the picked route and follow it (cuts with reduced motion); glowing band on the picked route with climbs, sprints and a start beacon | | `worldScene.js`, `worldWorker.js` | Build the world in a module worker and hand the meshes over without copying (falls back to building in place) | -| `riderModel.js` | Low-poly cyclist; jersey parts are tinted (me orange, humans blue, bots grey); skin, helmet, bike and size vary per rider (deterministic from the id); cranks turn, legs follow the pedals by two-bone IK (`legPose`), spoked wheels spin | +| `riderModel.js` | Low-poly cyclist; jersey parts are tinted (me orange, humans blue, bots in their team's kit, see `view/botKits.js`, else grey); skin, helmet, bike and size vary per rider (deterministic from the id); cranks turn, legs follow the pedals by two-bone IK (`legPose`), spoked wheels spin | | `zones.js` | Scenery zones from the route file, or seeded defaults (village, river, forest) | | `features.js` | River carving and water, stone bridge, village (houses, church, pavements, lamps, signs), farms with animals, wind turbines, spectators (at the finish, climbs and sprints, lining the last 600 m of each climb), guard rails, warning signs, flamme rouge | | `lemonModel.js` | The golden lemon floating over the road (lemons are placed by `ride/lemons.js`) | diff --git a/docs/protocol.md b/docs/protocol.md index c7f3a0eb..1e0ccd98 100644 --- a/docs/protocol.md +++ b/docs/protocol.md @@ -89,7 +89,7 @@ entered it, `next` the road they take at the next junction: their pick, else their route's, straight on off every route), `lap` (in a race, else `null`), `lane` (continuous, 0 = leftmost in riding direction), `speed`, `power`, and `device` (`sim`, `paddle` or `workout`; left out for -trainers and bots, so clients can mark phone paddlers and workouts), `vehicle`? (`id`, `kind`, `seat`, `seats`, `captain`: true for the current captain's seat) and `cadence` (only for seated riders, so each seat pedals at its own rate) and `parked` (true while pulled over for a pause, left out otherwise; always true for a workout rider) and `exercise` (the exercise a workout rider does now, left out at rest) and `side` (`right` or `left`, only for a sided pose, so the view can mirror the left side) and `app` (the id of the other app, for example `incyclist`, on a rider shared through OpenBikeNet; left out for riders of this server). Such a remote rider has `is_bot: false`, an `id` from `0xF000_0000` upwards (never reused while the server runs), no physics, no drafting and no `vehicle`; clients show the name as text and mark the app. They appear only on a shared route (see ADR 0020). Riders of different routes draft each other +trainers and bots, so clients can mark phone paddlers and workouts), `vehicle`? (`id`, `kind`, `seat`, `seats`, `captain`: true for the current captain's seat) and `cadence` (only for seated riders, so each seat pedals at its own rate) and `parked` (true while pulled over for a pause, left out otherwise; always true for a workout rider) and `exercise` (the exercise a workout rider does now, left out at rest) and `side` (`right` or `left`, only for a sided pose, so the view can mirror the left side) and `app` (the id of the other app, for example `incyclist`, on a rider shared through OpenBikeNet; left out for riders of this server). Bots also carry `team` (their kit: `zitrone`, `moos`, `kirsche`, `lavendel`, `kreide`, `schiefer`, `petrol` or `rose`), `style` (their riding type: `rouleur`, `climber`, `sprinter`, `attacker` or `tourer`) and `move` (what they are doing: `pull`, `attack`, `answer` or `sprint`; left out while they just ride), see [bots](superpowers/specs/2026-11-10-bots-design.md) (#64); humans never have these fields. Such a remote rider has `is_bot: false`, an `id` from `0xF000_0000` upwards (never reused while the server runs), no physics, no drafting and no `vehicle`; clients show the name as text and mark the app. They appear only on a shared route (see ADR 0020). Riders of different routes draft each other where they ride the same road the same way. Studio `riders[]` entries: `id`, `name`, `is_bot`, `seat` (0–7 front row, diff --git a/docs/superpowers/plans/2026-11-10-bots.md b/docs/superpowers/plans/2026-11-10-bots.md new file mode 100644 index 00000000..fb138590 --- /dev/null +++ b/docs/superpowers/plans/2026-11-10-bots.md @@ -0,0 +1,49 @@ +# Bots With Character: Implementation Plan + +**Goal:** Bots are characters who ride with and against the humans: a cast with riding types and team kits, moves within a W′ energy budget, and groups that spawn around every rider (#64). + +**Architecture:** Mostly the sim crate. +- `names.rs` holds the cast. +- `bot.rs` holds the types, teams, energy and moves. +- `world.rs` works out what each bot sees each step and decides where groups spawn. + +The server adds three optional fields to bots' rider entries. The client tints bots' jerseys, names their type in the rider list and calls out moves in the ticker. Design: `docs/superpowers/specs/2026-11-10-bots-design.md`. Decision: ADR 0022. + +## Steps + +1. **Cast (`sim/names.rs`):** made-up names, a first name and a cycling-pun surname ("Gus Tailwind"). Keep `generate_unique`, add `name_hash` (FNV-1a). Easter egg: one new bot in 200 is "Goldie Lemon", always in Team Zitrone. Tests: names are a first name and a pun surname, the cast holds at least 1,000 names, uniqueness and the numbered fallback, a stable hash. +2. **Types and teams (`sim/bot.rs`):** + - `RidingStyle::{Rouleur, Climber, Sprinter, Attacker, Tourer}` and `Team`, both from the name hash. + - `BotProfile::character` and `BotProfile::matched` take the name. + - Tests: a name is stable; the shares are roughly as planned; weights suit the type. +3. **Energy (`Energy`):** spend above CP, recover below with Skiba's τ. Tests: spend, clamp at empty, faster recovery when riding easier, the exact value for one case. +4. **Moves (`Move`, `BotBrain::decide`, `choose_lane`):** one move at a time, started from `BotSituation` and ended on time or energy; lane wishes for answer and swing off; escaping a blocked lane while attacking. Tests: + - a climber attacks near the top only with a human close, then recovers; + - each line once per pass; + - a sprinter goes for the line only with an audience; + - a tired bot lets the line go; + - an attacker answers a human, not a bot; + - a pull, then a swing off, then back once passed; + - no moves in a vehicle or a group ride; + - only pull, attack, answer and sprint go on the wire. +5. **What bots see (`World::bot_surroundings`):** the next line, a rider coming past, a wheel behind, the gap ahead, the nearest human, waiting for or leaving the group. Tests on a route with a climb and a sprint, and on a spawned group. +6. **Spawning (`keep_company`, `make_room`, `spawn_group`), within `target_riders`:** groups in rows, company ahead or behind out of sight, far bots make room. Tests: + - the route keeps its target however many humans want company; + - no bots with a target of 0; + - company out of sight; + - company levels ahead and behind; + - a full route brings its bots to a lonely human; + - racers bring no company; + - groups in rows at about one level. + + Adjust the old tests: base population without company, and "groups start apart". +7. **Tuning:** a simulated hour per route with one rider at 75% of a 3.0 W/kg FTP. Bring spawns closer (350–800 m ahead), and stop counting bots more than 400 m behind as company. The numbers are in the spec. +8. **Protocol (`server/protocol.rs`):** `team`, `style` and `move` on bots, none on humans. Test it, and update `docs/protocol.md`. +9. **Client:** + - `view/botKits.js`: kits avoiding orange and sky blue; the 3D view tints bots' jerseys. + - `panels.botStyle.*`: the type in the rider list badge. The name and its badges sit apart in the row, so only the name is cut short. + - `ride/botCalls.js`: calls the start of a move near me, rate limited; wired into the `state` handler. + - i18n in English and German. + - Tests for kits, the badge, the calls and the 3D tint. +10. **Docs:** the spec, this plan, ADR 0022, `architecture.md`, CHANGELOG. Screenshots for the PR from a local server. +11. **After review:** drop the growth with humans and its fixed cap (48). `OPENRADLR_TARGET_RIDERS` stays the one setting, and company is drawn from the route's own bots. diff --git a/docs/superpowers/specs/2026-11-10-bots-design.md b/docs/superpowers/specs/2026-11-10-bots-design.md new file mode 100644 index 00000000..8be3b12d --- /dev/null +++ b/docs/superpowers/specs/2026-11-10-bots-design.md @@ -0,0 +1,205 @@ +# Bots with character: design + +## Why + +Bots today are interchangeable. Each one: + +- is called "Adjective Animal"; +- rides a fixed share of its FTP with some noise; +- changes lanes only to catch a draft; +- spawns wherever the route is emptiest. + +A rider meets a bot, overtakes it and never sees it again. Nothing happens between them. On a long route the twelve bots per route are kilometres apart, so you mostly ride alone. + +The rethink has four parts: + +- **who the bots are:** names, a riding type, a team kit; +- **how they ride:** moves, limited by how much energy they have left; +- **where they appear:** around the riders who are online, in groups; +- **how many there are:** unchanged, `OPENRADLR_TARGET_RIDERS` per route; company comes out of it. + +The aim is that every ride has someone to chase, someone to ride with and now and then someone who attacks you. + +## Who the bots are: a cast + +- **Names:** each bot is a made-up character: a first name and a cycling pun for a surname ("Gus Tailwind", "Penny Farthing", "Sally Sprocket"). There are 40 first names and 40 surnames, 1,600 names in all, enough for any server (a route holds at most 200 riders). Invented names borrow no real person and no film or TV character, so there are no rights or trademark questions. +- **Easter egg:** about one new bot in 200 is "Goldie Lemon", who always rides in Team Zitrone's lemon yellow, after the golden lemons on the road. +- **Fixed per name:** a character's **riding type** and **team** come from a hash of their name. So "Gus Tailwind" is always the same climber in the same kit, on every server and in every session, and riders get to know them. Fitness is not fixed: it is still matched to the humans online. +- **Always marked:** bots stay marked as bots everywhere (`is_bot`, the "bot" badge). Only the name changes. +- **Same source everywhere:** studio and seat bots take their names from the cast too, so they look the same everywhere. + +### Riding types (archetypes) + +| type | share | weight | W′ | base pace | uphill | what it does | +|---|---|---|---|---|---|---| +| rouleur | 30% | 68–82 kg | 15 kJ | 0.72 FTP | +0.10 | rides on the front of a group (Pull), then moves aside (Swing off) | +| climber | 20% | 52–64 kg | 14 kJ | 0.66 FTP | +0.22 | attacks near climb tops | +| sprinter | 20% | 72–88 kg | 22 kJ | 0.68 FTP | +0.06 | sits in, goes for sprint lines and finishes | +| attacker | 15% | 60–74 kg | 18 kJ | 0.70 FTP | +0.12 | attacks riders near it, answers riders who pass | +| tourer | 15% | 60–95 kg | 10 kJ | 0.58 FTP | +0.06 | easy company, never races anybody | + +Rules that apply to every type: + +- Descents stay at 0.35 FTP. +- Races ride at 0.95 FTP. +- Group rides ride at 0.75 FTP and make no moves. +- The race-finish kick stays as it is today. + +### Teams + +There are eight fictional teams, each with a kit colour: + +- Zitrone (yellow) +- Moos (green) +- Kirsche (red) +- Lavendel (purple) +- Kreide (chalk white) +- Schiefer (slate black) +- Petrol (teal) +- Rosé (pink) + +None of the colours is orange (me) or sky blue (humans). In the 3D view, a bot's jersey has its team's colour instead of the grey all bots shared before. The 2D view keeps the grey dots: it is being redone in #38. + +## How bots ride: moves within an energy budget + +### Energy (W′) + +Every bot carries a **W′ balance** from the critical power model: + +- **Critical power:** the bot's FTP. +- **Riding above it** spends W′: (P − CP)·dt joules. +- **Riding below it** recovers the deficit exponentially, with Skiba's time constant τ = 546·e^(−0.01·(CP − P)) + 316 s. + +A bot with an empty tank cracks and has to recover. A strong human can therefore wear down an attacker by following it, the way it works in real racing. + +### Moves + +A bot is always doing exactly one move. **Ride** is the default. The other moves end after a while or when the bot's energy runs low, and then the bot goes back to Ride or into Recover. + +| move | power | how it starts | how it ends | +|---|---|---|---| +| Ride | base pace (types above); 0.55 while waiting for its group | default | — | +| Pull | ≥ 0.85 FTP | a rouleur (or, now and then, another type) with a wheel behind it for 10 s and clear road ahead | after 30–60 s, then Swing off | +| Swing off | 0.60 FTP, one lane over | after a pull | when the rider behind has come past, or after 20 s | +| Attack | 1.30–1.60 FTP by type | a climber within 600 m of a climb's top (an attacker within 300 m); an attacker near a human on the flat (about once in 4 min) | after 20–45 s, or when W′ drops below 15% | +| Answer | 1.25 FTP | someone (a human, or anyone in a race) passes within 8 m at least 0.8 m/s faster; the chance depends on the type | once on the passer's wheel (gap < 5 m), after 25 s, or when W′ drops below 30% | +| Sprint | 1.9 FTP (sprinter), 1.5 (others) | within 200 m of a sprint line (sprinters 250 m) with a human within 150 m, or in a race | after the line, or when W′ runs out | +| Recover | 0.55 FTP | after Attack, Answer or Sprint | after 30–60 s, or when W′ is back above 70% | + +Limits on starting a move: + +- Each line (sprint or summit) is contested at most once per pass. +- A move starts only from Ride with enough W′: more than 50% for an answer, 40% otherwise. +- Bots in a vehicle and bots in a group ride never make moves. +- Attacks and answers happen only near humans (within 80 m), or in races. Bots alone on the map don't spend their energy where nobody is watching, and the world stays calm. + +### Lanes during moves + +- **Attack, Answer and Sprint:** the bot moves into a neighbouring lane that is clear for 10 m ahead, if its own lane is blocked. +- **Swing off:** the bot moves to a neighbouring lane. +- **Otherwise:** the existing draft-seeking lane choice applies. + +## Where bots appear: company and groups + +### Groups + +Bots spawn in groups of 2–5 (a single bot now and then): + +- **Levels:** within ±3% of each other. +- **Line-up:** in rows across the lanes, 2.5 m apart. +- **Waiting:** a group member that gets more than 25 m ahead of the rest of its group, with none of them close behind, eases off (Ride at 0.55). Moves ignore this. A group therefore stays together until somebody attacks. +- **Breaking up:** a member more than 300 m from the rest rides solo from then on. + +### Company + +Every human riding a route keeps company. "Riding" means on the route: not in a workout, a race, an event or a vehicle. + +- **The goal:** at least 6 bots (`bots_near_human`) around them: up to 1,500 m ahead (`company_radius_m`) or up to 400 m behind (`company_behind_m`). Bots further back have been passed and no longer count, so a new group takes their place ahead. +- **Topping up:** when a human has fewer, groups spawn for them, at least 350 m from every human (`spawn_clear_m`: out of sight, so nothing appears in view). +- **Ahead (70%):** 350–800 m ahead, at 0.85–0.95 × the human's level. The human catches them within a few minutes: a group to chase. +- **Behind (30%):** 350–600 m behind, at 1.05–1.15 × the human's level. They catch the human, which gives a wheel to jump on. + +These numbers come from a simulated hour per route, with one rider at 75% of a 3.0 W/kg FTP: + +| route | no bot within 300 m | bots within 150 m (mean) | moves called near the rider | +|---|---|---|---| +| Col de la Forge | 29 s | 3.4 | 14 | +| Riverside Flats | 330 s | 2.0 | 18 | +| Island Tour | 29 s | 3.0 | 13 | + +A first try had the spawns 350–1,200 m ahead and counted bots up to 1,500 m behind. On Col de la Forge that left the rider alone for 1,696 s of the hour, with one move nearby. + +### Making room + +When the route is already at its target: + +- a bot more than `bot_despawn_distance_m` from every human, and not keeping anyone company, is removed to make room; +- surplus bots leave as before: the one farthest from humans first, and only out of sight. + +## How many: unchanged, `OPENRADLR_TARGET_RIDERS` + +A route keeps `target_riders` riders, humans plus bots, as before. That's the existing `OPENRADLR_TARGET_RIDERS`: 12 by default, 75 in production. Company doesn't add bots. It moves the route's own bots: far ones make room, and groups take their place around the humans. + +- With `target_riders = 0`, a route has no bots at all: the OpenBikeNet velodrome and the tests. +- With no humans online nothing changes but the groups. +- With many humans and a small target, the company is thinner: each human gets what is left, and the humans are company for each other. + +A first draft grew the target with the humans (`humans × 7`, capped at a new, fixed 48). That left two settings for one thing, and with production's 75 the cap did nothing. So `OPENRADLR_TARGET_RIDERS` stays the one setting. + +Simulated hours on Col de la Forge (one rider at 75% of a 3.0 W/kg FTP; the other riders started with them): + +| target | humans | riders | bots within 150 m (mean) | no bot within 300 m | +|---|---|---|---|---| +| 12 | 1 | 12 | 2.7 | 64 s | +| 75 | 1 | 75 | 3.4 | 75 s | +| 12 | 3 | 12 | 2.9 | 322 s | + +## Protocol (additive, no version bump) + +Bots' `riders[]` entries gain three fields: + +- `team`: the team id, for example `"moos"`. +- `style`: `rouleur` | `climber` | `sprinter` | `attacker` | `tourer`. +- `move`: `pull` | `attack` | `answer` | `sprint`. It is left out while riding or recovering. + +Humans and remote riders never have these fields. Older clients ignore them. + +## Client + +- **3D jerseys:** a bot's jersey has its team's kit colour; an unknown team keeps the bot grey. +- **Rider list:** the bot badge names the riding type ("climber bot" / "Kletterer-Bot"). +- **Ticker:** a pure `ride/botMoves.js` watches the riders around me and posts a line when a bot near me (same route, within 120 m) starts a move: + - "Gus Tailwind attacks!" + - "… goes for the sprint!" + - "… takes up the chase!" (only when it was behind me) + - "… comes through for a turn on the front." + + Only the start of a move counts. There is at most one line every 15 s, and each bot gets at most one line per move in 90 s. + +## Not in scope + +- Bots riding the network off their route, or turning at junctions. +- Bots reacting to chat. +- Persistent rivalries: a bot remembering that you dropped it yesterday. The fixed cast makes that possible later. +- Spacing and passing physics: #17 handles those. This design changes only the bots' power and lane choices, so the two combine. Whichever merges second needs a rebase in `world.rs` and `bot.rs`. + +## Testing + +All of these tests are deterministic and use the injected RNG: + +- **Sim:** + - the W′ model (spend, then recover with Skiba's τ); + - each move's start and end; + - lines contested once per pass; + - no moves in a vehicle or a group ride; + - a cast character's type and team are stable; + - names are unique; + - groups spawn together, wait for each other and split up; + - company spawns out of sight, ahead or behind, at the right levels; + - the route keeps its target however many humans want company; + - `target_riders = 0` means no bots. +- **Server:** the new fields on bots, and their absence on humans. +- **Client:** + - kit colours (none orange or sky blue); + - the bot badge text; + - the ticker's start-only rule, its rate limits and its distance. diff --git a/server/crates/server/src/protocol.rs b/server/crates/server/src/protocol.rs index f5ba24f9..a83d40ba 100644 --- a/server/crates/server/src/protocol.rs +++ b/server/crates/server/src/protocol.rs @@ -12,8 +12,8 @@ use openradlr_sim::sharing::Flow; use openradlr_sim::studio::{Studio, StudioEvent}; use openradlr_sim::vehicle::Vehicle; use openradlr_sim::vehicle::{shares, VehicleId}; -use openradlr_sim::world::Rider; use openradlr_sim::world::VehicleChange; +use openradlr_sim::world::{Controller, Rider}; use openradlr_sim::{RiderId, RouteIndex, World, WorldEvent}; use serde::{Deserialize, Serialize}; use std::collections::HashMap; @@ -483,6 +483,15 @@ pub struct RiderState { /// The side of a sided pose; left out for any other. #[serde(skip_serializing_if = "Option::is_none")] pub side: Option, + /// A bot's team (its kit colour); left out for humans. + #[serde(skip_serializing_if = "Option::is_none")] + pub team: Option<&'static str>, + /// A bot's riding type; left out for humans. + #[serde(skip_serializing_if = "Option::is_none")] + pub style: Option<&'static str>, + /// What a bot is doing (`pull`, `attack`, `answer`, `sprint`); left out while it just rides. + #[serde(rename = "move", skip_serializing_if = "Option::is_none")] + pub bot_move: Option<&'static str>, } impl RiderState { @@ -506,6 +515,9 @@ impl RiderState { exercise: None, app: Some(r.app.clone()), side: None, + team: None, + style: None, + bot_move: None, } } } @@ -834,6 +846,10 @@ fn rider_state(world: &World, r: &Rider, tags: RiderTags) -> RiderState { let seat = v.seats.iter().position(|s| *s == Some(r.id))?; Some((v, seat)) }); + let bot = match &r.controller { + Controller::Bot(brain) => Some(brain), + Controller::Human { .. } => None, + }; RiderState { id: r.id, name: r.name.clone(), @@ -867,6 +883,9 @@ fn rider_state(world: &World, r: &Rider, tags: RiderTags) -> RiderState { exercise: tags.exercise, app: None, side: tags.side, + team: bot.map(|b| b.profile().team.id()), + style: bot.map(|b| b.profile().style.id()), + bot_move: bot.and_then(|b| b.current_move().id()), } } @@ -1239,6 +1258,9 @@ mod tests { exercise: None, app: None, side: None, + team: None, + style: None, + bot_move: None, } } @@ -1511,4 +1533,46 @@ mod tests { .to_json(); assert!(!json.contains("event")); } + + #[test] + fn bots_carry_their_team_style_and_move_and_humans_none() { + use openradlr_sim::bot::{RidingStyle, Team}; + use openradlr_sim::rng::SplitMix64; + use openradlr_sim::route::{Point, Route, RouteSpec}; + use openradlr_sim::SimConfig; + let route = Route::new(RouteSpec { + id: "r".into(), + name: "R".into(), + lanes: 4, + seed: 1, + points: vec![Point::new(0.0, 0.0, 0.0), Point::new(2000.0, 0.0, 0.0)], + markers: vec![], + walk: vec![], + }) + .unwrap(); + let config = SimConfig { + target_riders: 3, + ..SimConfig::default() + }; + let mut world = World::new(route, config, Box::new(SplitMix64::new(1))); + let me = world.join_human("Anna", 70.0); + let Some(ServerMessage::State { riders, .. }) = + state_message(&world, 1, me, 50, None, &|_| RiderTags::default()) + else { + panic!("no state"); + }; + let human = serde_json::to_string(riders.iter().find(|r| r.id == me).unwrap()).unwrap(); + for key in ["\"team\"", "\"style\"", "\"move\""] { + assert!(!human.contains(key), "{human}"); + } + let bot = riders.iter().find(|r| r.is_bot).unwrap(); + assert_eq!(bot.team, Some(Team::of_name(&bot.name).id())); + assert_eq!(bot.style, Some(RidingStyle::of_name(&bot.name).id())); + assert_eq!(bot.bot_move, None, "just riding"); + let json = serde_json::to_string(bot).unwrap(); + assert!( + json.contains(&format!("\"team\":\"{}\"", Team::of_name(&bot.name).id())), + "{json}" + ); + } } diff --git a/server/crates/sim/src/bot.rs b/server/crates/sim/src/bot.rs index 372fcaea..0f4682ff 100644 --- a/server/crates/sim/src/bot.rs +++ b/server/crates/sim/src/bot.rs @@ -1,22 +1,151 @@ //! Bots: server-side riders that feed generated power into the same physics //! as humans. They make the world feel alive and are always flagged as bots. +//! +//! Each bot is a character of the cast (see `names`): its name fixes its +//! riding type and team. It rides with a W′ energy budget (the critical power +//! model) and makes moves — pulling on the front, attacking near a climb's +//! top, answering a rider who passes, sprinting for a line — that end when the +//! time is up or the tank runs low. See docs/superpowers/specs/2026-11-10-bots-design.md. +use crate::names::name_hash; use crate::rng::RandomSource; +/// A bot's riding type (archetype). Fixed by its name. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum RidingStyle { - Steady, + /// Steady; takes turns on the front of a group. + Rouleur, + /// Light; attacks near the top of a climb. Climber, + /// Heavy; sits in and goes for sprint lines and finishes. Sprinter, + /// Attacks riders near it and answers riders who pass. + Attacker, + /// Easy company; never races anybody. + Tourer, +} + +impl RidingStyle { + pub const ALL: [RidingStyle; 5] = [ + Self::Rouleur, + Self::Climber, + Self::Sprinter, + Self::Attacker, + Self::Tourer, + ]; + + /// The riding type of the cast member `name`: rouleurs 30%, climbers and + /// sprinters 20% each, attackers and tourers 15% each. + pub fn of_name(name: &str) -> Self { + match name_hash(name) % 100 { + 0..30 => Self::Rouleur, + 30..50 => Self::Climber, + 50..70 => Self::Sprinter, + 70..85 => Self::Attacker, + _ => Self::Tourer, + } + } + + /// Its id on the wire. + pub fn id(self) -> &'static str { + match self { + Self::Rouleur => "rouleur", + Self::Climber => "climber", + Self::Sprinter => "sprinter", + Self::Attacker => "attacker", + Self::Tourer => "tourer", + } + } + + fn weight_kg(self) -> (f64, f64) { + match self { + Self::Rouleur => (68.0, 82.0), + Self::Climber => (52.0, 64.0), + Self::Sprinter => (72.0, 88.0), + Self::Attacker => (60.0, 74.0), + Self::Tourer => (60.0, 95.0), + } + } + + /// W′: the work above critical power the bot can do on a full tank. + fn w_prime_j(self) -> f64 { + match self { + Self::Rouleur => 15_000.0, + Self::Climber => 14_000.0, + Self::Sprinter => 22_000.0, + Self::Attacker => 18_000.0, + Self::Tourer => 10_000.0, + } + } + + /// Share of FTP on the flat when free riding, and what it adds uphill. + fn pace(self) -> (f64, f64) { + match self { + Self::Rouleur => (0.72, 0.10), + Self::Climber => (0.66, 0.22), + Self::Sprinter => (0.68, 0.06), + Self::Attacker => (0.70, 0.12), + Self::Tourer => (0.58, 0.06), + } + } +} + +/// A bot's team: its kit colour on the clients. Fixed by its name. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Team { + Zitrone, + Moos, + Kirsche, + Lavendel, + Kreide, + Schiefer, + Petrol, + Rose, +} + +impl Team { + pub const ALL: [Team; 8] = [ + Self::Zitrone, + Self::Moos, + Self::Kirsche, + Self::Lavendel, + Self::Kreide, + Self::Schiefer, + Self::Petrol, + Self::Rose, + ]; + + /// The team of the cast member `name` (Goldie Lemon rides in lemon yellow). + pub fn of_name(name: &str) -> Self { + if name == crate::names::LEMON_NAME { + return Self::Zitrone; + } + Self::ALL[((name_hash(name) >> 32) % Self::ALL.len() as u64) as usize] + } + + /// Its id on the wire. + pub fn id(self) -> &'static str { + match self { + Self::Zitrone => "zitrone", + Self::Moos => "moos", + Self::Kirsche => "kirsche", + Self::Lavendel => "lavendel", + Self::Kreide => "kreide", + Self::Schiefer => "schiefer", + Self::Petrol => "petrol", + Self::Rose => "rose", + } + } } /// Fitness profile of a bot. #[derive(Debug, Clone, PartialEq)] pub struct BotProfile { - /// Sustainable power per kg (functional threshold power). + /// Sustainable power per kg (functional threshold power, used as critical power). pub ftp_wkg: f64, pub weight_kg: f64, pub style: RidingStyle, + pub team: Team, /// Relative standard deviation of the power noise, e.g. `0.05`. pub variance: f64, } @@ -29,15 +158,15 @@ impl BotProfile { /// Share of matched bots that ride near a human's level (the rest are field bots). const PACK_SHARE: f64 = 0.70; - /// Draws a profile to ride with humans of the given levels: mostly - /// pack bots at 0.95-1.10 x one human's level, the rest field bots - /// spanning at least 2.0..4.5 W/kg, widened to the humans' extremes. - /// Without levels this is [`BotProfile::random`]. - pub fn matched(levels_wkg: &[f64], rng: &mut dyn RandomSource) -> Self { + /// The profile of cast member `name` to ride with humans of the given + /// levels: mostly pack bots at 0.95-1.10 x one human's level, the rest + /// field bots spanning at least 2.0..4.5 W/kg, widened to the humans' + /// extremes. Without levels this is [`BotProfile::character`]. + pub fn matched(name: &str, levels_wkg: &[f64], rng: &mut dyn RandomSource) -> Self { + let mut profile = Self::character(name, rng); if levels_wkg.is_empty() { - return Self::random(rng); + return profile; } - let mut profile = Self::random(rng); profile.ftp_wkg = if rng.next_f64() < Self::PACK_SHARE { levels_wkg[rng.index(levels_wkg.len())] * rng.range_f64(0.95, 1.10) } else { @@ -48,17 +177,16 @@ impl BotProfile { profile } - /// Draws a plausible amateur profile. - pub fn random(rng: &mut dyn RandomSource) -> Self { - let style = match rng.index(3) { - 0 => RidingStyle::Steady, - 1 => RidingStyle::Climber, - _ => RidingStyle::Sprinter, - }; + /// The profile of cast member `name` at a plausible amateur level: its + /// type and team from the name, a weight that suits the type. + pub fn character(name: &str, rng: &mut dyn RandomSource) -> Self { + let style = RidingStyle::of_name(name); + let (light, heavy) = style.weight_kg(); Self { ftp_wkg: rng.range_f64(2.0, 4.5), - weight_kg: rng.range_f64(55.0, 95.0), + weight_kg: rng.range_f64(light, heavy), style, + team: Team::of_name(name), variance: rng.range_f64(0.03, 0.10), } } @@ -101,8 +229,65 @@ pub fn pack_levels(levels_wkg: &[f64]) -> Vec { .collect() } -/// What a bot knows about its situation when choosing its power. +/// W′ balance (Skiba): riding above critical power spends it, riding below +/// recovers the deficit exponentially, faster the further below. #[derive(Debug, Clone, Copy, PartialEq)] +pub struct Energy { + capacity_j: f64, + deficit_j: f64, +} + +impl Energy { + pub fn full(capacity_j: f64) -> Self { + Self { + capacity_j, + deficit_j: 0.0, + } + } + + /// Accounts `dt` seconds at `power` watts against critical power `cp`. + pub fn ride(&mut self, power: f64, cp: f64, dt: f64) { + if power > cp { + self.deficit_j = (self.deficit_j + (power - cp) * dt).min(self.capacity_j); + } else { + let tau = 546.0 * (-0.01 * (cp - power)).exp() + 316.0; + self.deficit_j *= (-dt / tau).exp(); + } + } + + /// What is left of W′, from 0 (empty) to 1 (full). + pub fn fraction(&self) -> f64 { + 1.0 - self.deficit_j / self.capacity_j + } +} + +/// A line a bot can ride for: the end of a sprint, or a climb's top. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum LineKind { + Sprint, + Summit, +} + +/// The next line ahead on the bot's route. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct LineAhead { + pub kind: LineKind, + /// Which marker of the route, so each line is contested once per pass. + pub index: usize, + pub distance_m: f64, +} + +/// A rider coming past: just ahead (within a few metres) and faster. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Passer { + pub human: bool, + /// How much faster than the bot, in m/s. + pub speed_gain: f64, + pub lane: u8, +} + +/// What a bot knows about its situation when choosing its power. +#[derive(Debug, Clone, Copy, PartialEq, Default)] pub struct BotSituation { pub grade_percent: f64, pub racing: bool, @@ -110,6 +295,18 @@ pub struct BotSituation { pub group_ride: bool, /// Remaining race distance in metres, `None` outside a race. pub distance_to_finish: Option, + /// May make moves: on its route, not seated in a vehicle. + pub free: bool, + pub line_ahead: Option, + pub passer: Option, + /// A rider sits on this bot's wheel (in its lane, a few metres behind). + pub wheel_behind: bool, + /// Gap to the rider ahead in this bot's lane, `None` if the road is clear. + pub gap_ahead_m: Option, + /// Distance to the nearest human along the route, either way. + pub human_m: Option, + /// Ahead of the rest of its group: eases off for them. + pub waiting_for_group: bool, } /// Gap to the nearest rider ahead in each lane, as seen by one bot. @@ -143,29 +340,153 @@ impl Default for BotTuning { } } +/// What a bot is doing now. +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum Move { + Ride, + /// On the front of a group, pulling the others along. + Pull, + /// Moved aside after a pull, letting the group come past. + SwingOff, + /// An attack at `intensity` × FTP. + Attack { + intensity: f64, + }, + /// Chasing a rider who just came past. + Answer, + /// Going for a line at `intensity` × FTP. + Sprint { + intensity: f64, + }, + /// Easing off after an effort. + Recover, +} + +impl Move { + /// The move's id on the wire; `None` while riding, swinging off or recovering. + pub fn id(self) -> Option<&'static str> { + match self { + Move::Pull => Some("pull"), + Move::Attack { .. } => Some("attack"), + Move::Answer => Some("answer"), + Move::Sprint { .. } => Some("sprint"), + Move::Ride | Move::SwingOff | Move::Recover => None, + } + } +} + +/// When moves start and end. +mod tactics { + /// A move starts only with more of W′ left than this… + pub const MIN_ENERGY: f64 = 0.40; + /// …and an answer with more than this. + pub const MIN_ENERGY_ANSWER: f64 = 0.50; + /// Attacks and answers only happen with a human this close (or in a race). + pub const HUMAN_NEAR_M: f64 = 80.0; + /// A sprint only starts with a human this close (or in a race). + pub const SPRINT_AUDIENCE_M: f64 = 150.0; + /// A rider at least this much faster, just ahead, is coming past. + pub const PASS_GAIN_MPS: f64 = 0.8; + /// Seconds a wheel has to sit behind before a pull. + pub const WHEEL_BEFORE_PULL_S: f64 = 10.0; + /// Pulls start only with the road ahead clear for this long. + pub const CLEAR_TO_PULL_M: f64 = 15.0; + /// An answer ends on the passer's wheel. + pub const ON_THE_WHEEL_M: f64 = 5.0; + /// Attacks, answers and sprints look for a lane clear for this long. + pub const CLEAR_LANE_M: f64 = 10.0; + /// Once rolled, the next pass is ignored for this long. + pub const ANSWER_COOLDOWN_S: f64 = 20.0; + /// An attacker near a human attacks on average once in this many seconds. + pub const ATTACK_EVERY_S: f64 = 240.0; + /// A line already contested is forgotten once it is this far ahead again. + pub const FORGET_LINE_M: f64 = 1500.0; + pub const RIDE_WAITING: f64 = 0.55; + pub const PULL: f64 = 0.85; + pub const SWING_OFF: f64 = 0.60; + pub const ANSWER: f64 = 1.25; + pub const RECOVER: f64 = 0.55; + pub const SWING_OFF_S: f64 = 20.0; + pub const ANSWER_S: f64 = 25.0; +} + +/// A lane the bot wants to be in, decided by a move. +#[derive(Debug, Clone, Copy, PartialEq)] +enum LaneWish { + /// One lane over, the left one first. + Aside, + Lane(u8), +} + #[derive(Debug, Clone)] pub struct BotBrain { profile: BotProfile, tuning: BotTuning, noise: f64, lane_cooldown_s: f64, + energy: Energy, + current: Move, + /// Seconds left of the current move. + left_s: f64, + /// Seconds a wheel has sat behind with the road ahead clear. + wheel_s: f64, + answer_cooldown_s: f64, + /// The line last contested (or let go), so each is ridden for once per pass. + contested: Option, + lane_wish: Option, + /// The group it was spawned with, while it still rides with them. + group: Option, } impl BotBrain { pub fn new(profile: BotProfile, tuning: BotTuning) -> Self { + let energy = Energy::full(profile.style.w_prime_j()); Self { profile, tuning, noise: 0.0, lane_cooldown_s: 0.0, + energy, + current: Move::Ride, + left_s: 0.0, + wheel_s: 0.0, + answer_cooldown_s: 0.0, + contested: None, + lane_wish: None, + group: None, } } + /// The same bot, riding with group `group`. + pub fn in_group(mut self, group: Option) -> Self { + self.group = group; + self + } + + pub fn group(&self) -> Option { + self.group + } + + /// Rides on alone: too far from the rest of its group. + pub fn leave_group(&mut self) { + self.group = None; + } + pub fn profile(&self) -> &BotProfile { &self.profile } - /// Fraction of FTP the bot aims for in the given situation (no noise). + /// What the bot is doing now. + pub fn current_move(&self) -> Move { + self.current + } + + /// What is left of its W′, from 0 to 1. + pub fn energy(&self) -> f64 { + self.energy.fraction() + } + + /// Fraction of FTP the bot aims for while riding (no move, no noise). pub fn target_intensity(&self, situation: &BotSituation) -> f64 { let style = self.profile.style; let grade = situation.grade_percent; @@ -174,23 +495,17 @@ impl BotBrain { return 0.35; } + let (flat, uphill) = style.pace(); let mut intensity: f64 = if situation.racing { 0.95 } else if situation.group_ride { 0.75 } else { - match style { - RidingStyle::Steady => 0.70, - RidingStyle::Climber => 0.68, - RidingStyle::Sprinter => 0.70, - } + flat }; if grade > 2.0 { - intensity += match style { - RidingStyle::Climber => 0.20, - _ => 0.10, - }; + intensity += uphill; } if let Some(remaining) = situation.distance_to_finish { @@ -206,25 +521,223 @@ impl BotBrain { intensity.clamp(0.3, 1.8) } + /// Fraction of FTP for the current move in `situation`. + fn intensity(&self, situation: &BotSituation) -> f64 { + let riding = self.target_intensity(situation); + if situation.distance_to_finish.is_some_and(|d| d <= 1000.0) { + // The race finale rides by its own rules. + return riding; + } + match self.current { + Move::Ride if situation.waiting_for_group => riding.min(tactics::RIDE_WAITING), + Move::Ride => riding, + Move::Pull => riding.max(tactics::PULL), + Move::SwingOff => tactics::SWING_OFF, + Move::Attack { intensity } | Move::Sprint { intensity } => intensity, + Move::Answer => tactics::ANSWER, + Move::Recover => riding.min(tactics::RECOVER), + } + } + /// Power in watts for the next `dt` seconds. The noise is a slowly /// drifting (AR(1)) process so bots do not ride like clockwork. pub fn power(&mut self, situation: &BotSituation, rng: &mut dyn RandomSource, dt: f64) -> f64 { + self.decide(situation, rng, dt); let decay = (-dt / self.tuning.noise_time_constant_s).exp(); self.noise = self.noise * decay + (1.0 - decay * decay).sqrt() * rng.standard_normal(); let factor = 1.0 + self.profile.variance * self.noise; - (self.profile.ftp_watts() * self.target_intensity(situation) * factor).max(0.0) + let power = (self.profile.ftp_watts() * self.intensity(situation) * factor).max(0.0); + self.energy.ride(power, self.profile.ftp_watts(), dt); + power + } + + fn start(&mut self, next: Move, seconds: f64) { + self.current = next; + self.left_s = seconds; } - /// Decides whether to move into a neighbouring lane to catch a draft. + /// Starts and ends moves. + fn decide(&mut self, s: &BotSituation, rng: &mut dyn RandomSource, dt: f64) { + use tactics::*; + self.left_s -= dt; + self.answer_cooldown_s = (self.answer_cooldown_s - dt).max(0.0); + let energy = self.energy.fraction(); + let style = self.profile.style; + if self.contested.is_some_and(|i| { + s.line_ahead + .is_none_or(|l| l.index != i || l.distance_m > FORGET_LINE_M) + }) { + self.contested = None; + } + if !s.free || s.group_ride { + self.current = Move::Ride; + self.wheel_s = 0.0; + return; + } + match self.current { + Move::Ride => {} + Move::Pull => { + if s.gap_ahead_m.is_some_and(|g| g < CLEAR_TO_PULL_M) { + self.current = Move::Ride; + } else if self.left_s <= 0.0 { + self.start(Move::SwingOff, SWING_OFF_S); + self.lane_wish = Some(LaneWish::Aside); + } + return; + } + Move::SwingOff => { + if self.left_s <= 0.0 || s.passer.is_some() { + self.current = Move::Ride; + } + return; + } + Move::Attack { .. } => { + if self.left_s <= 0.0 || energy < 0.15 { + self.start(Move::Recover, rng.range_f64(30.0, 60.0)); + } + return; + } + Move::Answer => { + if s.gap_ahead_m.is_some_and(|g| g <= ON_THE_WHEEL_M) { + self.current = Move::Ride; + } else if self.left_s <= 0.0 || energy < 0.30 { + self.start(Move::Recover, rng.range_f64(30.0, 60.0)); + } + return; + } + Move::Sprint { .. } => { + if self.left_s <= 0.0 || energy <= 0.02 { + self.start(Move::Recover, rng.range_f64(30.0, 60.0)); + } + return; + } + Move::Recover => { + if self.left_s <= 0.0 || energy > 0.70 { + self.current = Move::Ride; + } + return; + } + } + + // Riding: is there a reason to start something? + let clear_ahead = s.gap_ahead_m.is_none_or(|g| g > CLEAR_TO_PULL_M); + self.wheel_s = if s.wheel_behind && clear_ahead { + self.wheel_s + dt + } else { + 0.0 + }; + if style == RidingStyle::Tourer { + return; + } + let human_near = s.racing || s.human_m.is_some_and(|d| d <= HUMAN_NEAR_M); + + if let Some(line) = s.line_ahead.filter(|l| self.contested != Some(l.index)) { + match line.kind { + LineKind::Sprint => { + let reach = if style == RidingStyle::Sprinter { 250.0 } else { 200.0 }; + let audience = s.racing || s.human_m.is_some_and(|d| d <= SPRINT_AUDIENCE_M); + if line.distance_m <= reach && audience { + self.contested = Some(line.index); + if energy > MIN_ENERGY { + let intensity = if style == RidingStyle::Sprinter { 1.9 } else { 1.5 }; + self.start(Move::Sprint { intensity }, line.distance_m / 10.0 + 3.0); + return; + } + } + } + LineKind::Summit => { + let (reach, chance, intensity) = match style { + RidingStyle::Climber => (600.0, 0.8, 1.30), + RidingStyle::Attacker => (300.0, 0.5, 1.45), + RidingStyle::Rouleur => (200.0, 0.1, 1.30), + _ => (200.0, 0.05, 1.30), + }; + if line.distance_m <= reach && human_near { + self.contested = Some(line.index); + if energy > MIN_ENERGY && rng.next_f64() < chance { + self.start(Move::Attack { intensity }, rng.range_f64(20.0, 45.0)); + return; + } + } + } + } + } + + if let Some(passer) = s + .passer + .filter(|p| p.speed_gain >= PASS_GAIN_MPS && (p.human || s.racing)) + { + if self.answer_cooldown_s <= 0.0 && energy > MIN_ENERGY_ANSWER { + self.answer_cooldown_s = ANSWER_COOLDOWN_S; + let chance = match style { + RidingStyle::Attacker => 0.7, + RidingStyle::Climber if s.grade_percent > 2.0 => 0.6, + RidingStyle::Sprinter if s.grade_percent.abs() <= 2.0 => 0.3, + _ => 0.3, + }; + if rng.next_f64() < chance { + self.start(Move::Answer, ANSWER_S); + self.lane_wish = Some(LaneWish::Lane(passer.lane)); + return; + } + } + } + + if style == RidingStyle::Attacker && human_near && energy > 0.6 && rng.next_f64() < dt / ATTACK_EVERY_S { + self.start(Move::Attack { intensity: 1.5 }, rng.range_f64(20.0, 45.0)); + return; + } + + if self.wheel_s >= WHEEL_BEFORE_PULL_S { + self.wheel_s = 0.0; + if style == RidingStyle::Rouleur || rng.next_f64() < 0.3 { + self.start(Move::Pull, rng.range_f64(30.0, 60.0)); + } + } + } + + /// Decides whether to move into another lane: where a move wants to be, + /// out of a blocked lane while attacking, or over to catch a draft. pub fn choose_lane(&mut self, view: &LaneView, dt: f64) -> Option { self.lane_cooldown_s = (self.lane_cooldown_s - dt).max(0.0); + let lanes = view.gap_ahead.len(); + let current = view.current_lane as usize; + if let Some(wish) = self.lane_wish.take() { + let lane = match wish { + LaneWish::Aside if current > 0 => current - 1, + LaneWish::Aside => current + 1, + LaneWish::Lane(lane) => usize::from(lane), + }; + if lane < lanes && lane != current { + self.lane_cooldown_s = self.tuning.lane_change_cooldown_s; + return Some(lane as u8); + } + return None; + } if self.lane_cooldown_s > 0.0 { return None; } + let gap = |lane: usize| view.gap_ahead.get(lane).copied().flatten(); + + // An answer wants the wheel ahead, not a way past it. + if matches!(self.current, Move::Attack { .. } | Move::Sprint { .. }) { + let blocked = |lane: usize| gap(lane).is_some_and(|g| g < tactics::CLEAR_LANE_M); + if !blocked(current) { + return None; + } + let escape = [current.checked_sub(1), Some(current + 1)] + .into_iter() + .flatten() + .filter(|&lane| lane < lanes && !blocked(lane)) + .max_by(|&a, &b| gap(a).unwrap_or(f64::MAX).total_cmp(&gap(b).unwrap_or(f64::MAX))); + return escape.map(|lane| { + self.lane_cooldown_s = self.tuning.lane_change_cooldown_s; + lane as u8 + }); + } let in_window = |gap: Option, (lo, hi): (f64, f64)| gap.is_some_and(|g| (lo..=hi).contains(&g)); - let current = view.current_lane as usize; - if in_window(view.gap_ahead.get(current).copied().flatten(), self.tuning.draft_window) { + if in_window(gap(current), self.tuning.draft_window) { return None; } @@ -232,8 +745,8 @@ impl BotBrain { let best = neighbours .into_iter() .flatten() - .filter(|&lane| lane < view.gap_ahead.len()) - .filter_map(|lane| view.gap_ahead[lane].map(|gap| (lane, gap))) + .filter(|&lane| lane < lanes) + .filter_map(|lane| gap(lane).map(|gap| (lane, gap))) .filter(|&(_, gap)| in_window(Some(gap), self.tuning.join_window)) .min_by(|a, b| a.1.total_cmp(&b.1)); @@ -249,16 +762,18 @@ mod tests { use super::*; use crate::rng::SplitMix64; + fn profile(style: RidingStyle) -> BotProfile { + BotProfile { + ftp_wkg: 3.0, + weight_kg: 70.0, + style, + team: Team::Moos, + variance: 0.05, + } + } + fn brain(style: RidingStyle) -> BotBrain { - BotBrain::new( - BotProfile { - ftp_wkg: 3.0, - weight_kg: 70.0, - style, - variance: 0.05, - }, - BotTuning::default(), - ) + BotBrain::new(profile(style), BotTuning::default()) } const FREE_RIDE_FLAT: BotSituation = BotSituation { @@ -266,25 +781,106 @@ mod tests { racing: false, group_ride: false, distance_to_finish: None, + free: true, + line_ahead: None, + passer: None, + wheel_behind: false, + gap_ahead_m: None, + human_m: None, + waiting_for_group: false, }; + /// Rides `seconds` in `situation`, returning the moves seen. + fn ride(bot: &mut BotBrain, situation: &BotSituation, seconds: f64, rng: &mut SplitMix64) -> Vec { + let mut seen = Vec::new(); + for _ in 0..(seconds / 0.05).round() as usize { + bot.power(situation, rng, 0.05); + let m = bot.current_move(); + if seen + .last() + .is_none_or(|last: &Move| std::mem::discriminant(last) != std::mem::discriminant(&m)) + { + seen.push(m); + } + } + seen + } + + fn is_attack(m: &Move) -> bool { + matches!(m, Move::Attack { .. }) + } + + // --- the cast ------------------------------------------------------------------ + + #[test] + fn a_name_always_rides_the_same_type_in_the_same_kit() { + assert_eq!( + RidingStyle::of_name("Gus Tailwind"), + RidingStyle::of_name("Gus Tailwind") + ); + assert_eq!(Team::of_name("Gus Tailwind"), Team::of_name("Gus Tailwind")); + let a = BotProfile::character("Gus Tailwind", &mut SplitMix64::new(1)); + let b = BotProfile::character("Gus Tailwind", &mut SplitMix64::new(2)); + assert_eq!((a.style, a.team), (b.style, b.team)); + } + + #[test] + fn the_cast_has_every_type_and_team_in_about_the_planned_shares() { + let names = crate::names::all_names(); + let share = + |style| names.iter().filter(|n| RidingStyle::of_name(n) == style).count() as f64 / names.len() as f64; + for (style, planned) in [ + (RidingStyle::Rouleur, 0.30), + (RidingStyle::Climber, 0.20), + (RidingStyle::Sprinter, 0.20), + (RidingStyle::Attacker, 0.15), + (RidingStyle::Tourer, 0.15), + ] { + assert!((share(style) - planned).abs() < 0.05, "{style:?}: {}", share(style)); + } + for team in Team::ALL { + assert!(names.iter().any(|n| Team::of_name(n) == team), "{team:?}"); + } + } + #[test] - fn random_profiles_stay_in_documented_ranges() { + fn character_profiles_stay_in_documented_ranges() { let mut rng = SplitMix64::new(9); - for _ in 0..1000 { - let p = BotProfile::random(&mut rng); + for name in crate::names::all_names().iter().take(500) { + let p = BotProfile::character(name, &mut rng); + let (light, heavy) = p.style.weight_kg(); assert!((2.0..4.5).contains(&p.ftp_wkg)); - assert!((55.0..95.0).contains(&p.weight_kg)); + assert!((light..heavy).contains(&p.weight_kg)); assert!((0.03..0.10).contains(&p.variance)); } } + #[test] + fn goldie_lemon_rides_for_team_zitrone() { + assert_eq!(Team::of_name(crate::names::LEMON_NAME), Team::Zitrone); + } + + #[test] + fn climbers_are_lighter_than_sprinters() { + assert!(RidingStyle::Climber.weight_kg().1 < RidingStyle::Sprinter.weight_kg().0); + } + + // --- pace -------------------------------------------------------------------------- + #[test] fn free_ride_is_endurance_pace() { - let i = brain(RidingStyle::Steady).target_intensity(&FREE_RIDE_FLAT); + let i = brain(RidingStyle::Rouleur).target_intensity(&FREE_RIDE_FLAT); assert!((0.65..=0.75).contains(&i)); } + #[test] + fn tourers_ride_easier_than_everyone() { + let tourer = brain(RidingStyle::Tourer).target_intensity(&FREE_RIDE_FLAT); + for style in RidingStyle::ALL.into_iter().filter(|s| *s != RidingStyle::Tourer) { + assert!(tourer < brain(style).target_intensity(&FREE_RIDE_FLAT), "{style:?}"); + } + } + #[test] fn climbers_push_harder_uphill_than_others() { let uphill = BotSituation { @@ -292,9 +888,9 @@ mod tests { ..FREE_RIDE_FLAT }; let climber = brain(RidingStyle::Climber).target_intensity(&uphill); - let steady = brain(RidingStyle::Steady).target_intensity(&uphill); - assert!(climber > steady); - assert!(steady > brain(RidingStyle::Steady).target_intensity(&FREE_RIDE_FLAT)); + let rouleur = brain(RidingStyle::Rouleur).target_intensity(&uphill); + assert!(climber > rouleur); + assert!(rouleur > brain(RidingStyle::Rouleur).target_intensity(&FREE_RIDE_FLAT)); } #[test] @@ -309,10 +905,9 @@ mod tests { #[test] fn races_are_harder_and_sprinters_kick_at_the_end() { let race = BotSituation { - grade_percent: 0.0, racing: true, - group_ride: false, distance_to_finish: Some(5000.0), + ..FREE_RIDE_FLAT }; let sprint = BotSituation { distance_to_finish: Some(200.0), @@ -323,22 +918,397 @@ mod tests { assert!(sprinter.target_intensity(&sprint) >= 1.5); } + #[test] + fn group_ride_intensity() { + let group = BotSituation { + group_ride: true, + ..FREE_RIDE_FLAT + }; + assert_eq!(brain(RidingStyle::Rouleur).target_intensity(&group), 0.75); + let racing = BotSituation { racing: true, ..group }; + assert_eq!(brain(RidingStyle::Rouleur).target_intensity(&racing), 0.95); + } + #[test] fn power_varies_around_the_target() { - let mut bot = brain(RidingStyle::Steady); + let mut bot = brain(RidingStyle::Rouleur); let mut rng = SplitMix64::new(4); let samples: Vec = (0..2000).map(|_| bot.power(&FREE_RIDE_FLAT, &mut rng, 0.05)).collect(); let mean = samples.iter().sum::() / samples.len() as f64; - let target = 210.0 * 0.70; + let target = 210.0 * 0.72; assert!((mean - target).abs() < target * 0.1, "mean {mean}"); let min = samples.iter().cloned().fold(f64::MAX, f64::min); let max = samples.iter().cloned().fold(f64::MIN, f64::max); assert!(max > min, "power should not be constant"); } + #[test] + fn a_bot_ahead_of_its_group_waits_for_it() { + let mut bot = brain(RidingStyle::Rouleur); + let waiting = BotSituation { + waiting_for_group: true, + ..FREE_RIDE_FLAT + }; + assert!(bot.intensity(&waiting) <= 0.55); + bot.current = Move::Attack { intensity: 1.5 }; + assert_eq!(bot.intensity(&waiting), 1.5, "an attack doesn't wait"); + } + + // --- energy -------------------------------------------------------------------------- + + #[test] + fn riding_above_critical_power_spends_w_prime() { + let mut e = Energy::full(20_000.0); + e.ride(300.0, 200.0, 50.0); + assert!((e.fraction() - 0.75).abs() < 1e-9); + e.ride(1000.0, 200.0, 1000.0); + assert_eq!(e.fraction(), 0.0, "never below empty"); + } + + #[test] + fn w_prime_comes_back_faster_the_easier_the_ride() { + let drained = || { + let mut e = Energy::full(20_000.0); + e.ride(400.0, 200.0, 50.0); + e + }; + let (mut easy, mut tempo) = (drained(), drained()); + easy.ride(100.0, 200.0, 120.0); + tempo.ride(190.0, 200.0, 120.0); + assert!(easy.fraction() > tempo.fraction()); + assert!(tempo.fraction() > drained().fraction()); + // Skiba's τ at 100 W under CP: 546·e^-1 + 316 ≈ 517 s. + let tau: f64 = 546.0 * (-1.0f64).exp() + 316.0; + let expected = 1.0 - 0.5 * (-120.0 / tau).exp(); + assert!((easy.fraction() - expected).abs() < 1e-9); + } + + // --- moves --------------------------------------------------------------------------- + + fn summit(distance_m: f64) -> Option { + Some(LineAhead { + kind: LineKind::Summit, + index: 1, + distance_m, + }) + } + + fn sprint_line(distance_m: f64) -> Option { + Some(LineAhead { + kind: LineKind::Sprint, + index: 2, + distance_m, + }) + } + + #[test] + fn a_climber_attacks_near_the_top_with_a_human_close_then_recovers() { + let near_top = BotSituation { + grade_percent: 6.0, + line_ahead: summit(500.0), + human_m: Some(30.0), + ..FREE_RIDE_FLAT + }; + let mut attacks = 0; + for seed in 0..20 { + let mut bot = brain(RidingStyle::Climber); + let moves = ride(&mut bot, &near_top, 120.0, &mut SplitMix64::new(seed)); + if moves.iter().any(is_attack) { + attacks += 1; + let attack = moves.iter().position(is_attack).unwrap(); + assert_eq!(moves.get(attack + 1), Some(&Move::Recover), "{moves:?}"); + } + } + assert!((12..=19).contains(&attacks), "{attacks} of 20 climbers attacked"); + } + + #[test] + fn an_attack_pushes_well_over_ftp_and_drains_the_tank() { + let mut bot = brain(RidingStyle::Climber); + let mut rng = SplitMix64::new(3); + bot.start(Move::Attack { intensity: 1.3 }, 30.0); + let watts: f64 = (0..200) + .map(|_| bot.power(&FREE_RIDE_FLAT, &mut rng, 0.05)) + .sum::() + / 200.0; + assert!(watts > 1.2 * 210.0, "{watts} W"); + assert!(bot.energy() < 1.0); + } + + #[test] + fn nobody_attacks_far_from_the_top_or_with_nobody_watching() { + for situation in [ + BotSituation { + line_ahead: summit(900.0), + human_m: Some(30.0), + ..FREE_RIDE_FLAT + }, + BotSituation { + line_ahead: summit(300.0), + human_m: Some(500.0), + ..FREE_RIDE_FLAT + }, + ] { + let mut bot = brain(RidingStyle::Climber); + let moves = ride(&mut bot, &situation, 60.0, &mut SplitMix64::new(1)); + assert_eq!(moves, vec![Move::Ride], "{situation:?}"); + } + } + + #[test] + fn a_line_is_contested_once_per_pass() { + let mut bot = brain(RidingStyle::Climber); + bot.contested = Some(1); + let near_top = BotSituation { + line_ahead: summit(400.0), + human_m: Some(10.0), + ..FREE_RIDE_FLAT + }; + assert_eq!( + ride(&mut bot, &near_top, 30.0, &mut SplitMix64::new(1)), + vec![Move::Ride] + ); + // Next lap: the line is far ahead again and may be ridden for once more. + let next_lap = BotSituation { + line_ahead: summit(5000.0), + ..near_top + }; + ride(&mut bot, &next_lap, 0.05, &mut SplitMix64::new(1)); + assert_eq!(bot.contested, None); + } + + #[test] + fn tourers_never_race_anybody() { + let everything = BotSituation { + line_ahead: sprint_line(100.0), + human_m: Some(5.0), + passer: Some(Passer { + human: true, + speed_gain: 3.0, + lane: 1, + }), + ..FREE_RIDE_FLAT + }; + let mut bot = brain(RidingStyle::Tourer); + assert_eq!( + ride(&mut bot, &everything, 60.0, &mut SplitMix64::new(2)), + vec![Move::Ride] + ); + } + + #[test] + fn a_sprinter_goes_for_the_line_with_a_human_close() { + let mut bot = brain(RidingStyle::Sprinter); + let line = BotSituation { + line_ahead: sprint_line(240.0), + human_m: Some(120.0), + ..FREE_RIDE_FLAT + }; + let moves = ride(&mut bot, &line, 40.0, &mut SplitMix64::new(1)); + assert_eq!(moves[0], Move::Sprint { intensity: 1.9 }); + assert!(moves.contains(&Move::Recover)); + let alone = BotSituation { human_m: None, ..line }; + assert_eq!( + ride(&mut brain(RidingStyle::Sprinter), &alone, 40.0, &mut SplitMix64::new(1)), + vec![Move::Ride] + ); + } + + #[test] + fn a_tired_bot_lets_the_line_go() { + let mut bot = brain(RidingStyle::Sprinter); + bot.energy = Energy { + capacity_j: 22_000.0, + deficit_j: 20_000.0, + }; + let line = BotSituation { + line_ahead: sprint_line(100.0), + racing: true, + ..FREE_RIDE_FLAT + }; + assert_eq!(ride(&mut bot, &line, 5.0, &mut SplitMix64::new(1)), vec![Move::Ride]); + } + + #[test] + fn an_attacker_answers_a_human_who_comes_past_and_moves_into_their_lane() { + let passed = BotSituation { + human_m: Some(3.0), + gap_ahead_m: None, + passer: Some(Passer { + human: true, + speed_gain: 2.0, + lane: 2, + }), + ..FREE_RIDE_FLAT + }; + let mut answered = 0; + for seed in 0..40 { + let mut bot = brain(RidingStyle::Attacker); + bot.power(&passed, &mut SplitMix64::new(seed), 0.05); + if bot.current_move() == Move::Answer { + answered += 1; + let view = LaneView { + current_lane: 1, + gap_ahead: vec![None, None, Some(3.0), None], + }; + assert_eq!(bot.choose_lane(&view, 0.05), Some(2)); + } + } + assert!((20..=36).contains(&answered), "{answered} of 40 answered"); + } + + #[test] + fn an_answering_bot_stays_behind_the_wheel_it_chases() { + let mut bot = brain(RidingStyle::Attacker); + bot.current = Move::Answer; + let view = LaneView { + current_lane: 1, + gap_ahead: vec![None, Some(7.0), None, None], + }; + assert_eq!(bot.choose_lane(&view, 0.05), None); + } + + #[test] + fn an_answer_ends_on_the_wheel() { + let mut bot = brain(RidingStyle::Attacker); + bot.start(Move::Answer, 25.0); + let on_wheel = BotSituation { + gap_ahead_m: Some(3.0), + ..FREE_RIDE_FLAT + }; + bot.power(&on_wheel, &mut SplitMix64::new(1), 0.05); + assert_eq!(bot.current_move(), Move::Ride); + } + + #[test] + fn bots_only_answer_humans_outside_races() { + let bot_passes = BotSituation { + human_m: Some(3.0), + passer: Some(Passer { + human: false, + speed_gain: 2.0, + lane: 1, + }), + ..FREE_RIDE_FLAT + }; + for seed in 0..20 { + let mut bot = brain(RidingStyle::Attacker); + bot.power(&bot_passes, &mut SplitMix64::new(seed), 0.05); + assert_ne!(bot.current_move(), Move::Answer); + } + } + + #[test] + fn a_rouleur_with_a_wheel_behind_pulls_then_swings_off_and_lets_them_by() { + let mut bot = brain(RidingStyle::Rouleur); + let mut rng = SplitMix64::new(1); + let leading = BotSituation { + wheel_behind: true, + ..FREE_RIDE_FLAT + }; + let mut moves = vec![bot.current_move()]; + for _ in 0..(90.0 / 0.05) as usize { + bot.power(&leading, &mut rng, 0.05); + if moves.last() != Some(&bot.current_move()) { + moves.push(bot.current_move()); + } + if bot.current_move() == Move::SwingOff { + break; + } + } + assert_eq!(moves, [Move::Ride, Move::Pull, Move::SwingOff]); + let view = LaneView { + current_lane: 1, + gap_ahead: vec![None, None, None, None], + }; + assert_eq!(bot.choose_lane(&view, 0.05), Some(0), "aside to the left"); + let passing = BotSituation { + passer: Some(Passer { + human: true, + speed_gain: 1.0, + lane: 1, + }), + ..FREE_RIDE_FLAT + }; + bot.power(&passing, &mut rng, 0.05); + assert_eq!(bot.current_move(), Move::Ride, "back to riding once they come past"); + } + + #[test] + fn a_pull_ends_when_someone_is_ahead_again() { + let mut bot = brain(RidingStyle::Rouleur); + bot.start(Move::Pull, 40.0); + let caught = BotSituation { + gap_ahead_m: Some(4.0), + ..FREE_RIDE_FLAT + }; + bot.power(&caught, &mut SplitMix64::new(1), 0.05); + assert_eq!(bot.current_move(), Move::Ride); + } + + #[test] + fn an_attacker_near_a_human_attacks_now_and_then() { + let mut bot = brain(RidingStyle::Attacker); + let company = BotSituation { + human_m: Some(20.0), + ..FREE_RIDE_FLAT + }; + let moves = ride(&mut bot, &company, 1800.0, &mut SplitMix64::new(5)); + let attacks = moves.iter().filter(|m| is_attack(m)).count(); + assert!((2..=14).contains(&attacks), "{attacks} attacks in 30 min: {moves:?}"); + } + + #[test] + fn no_moves_in_a_vehicle_or_a_group_ride() { + let line = BotSituation { + line_ahead: sprint_line(100.0), + human_m: Some(5.0), + wheel_behind: true, + ..FREE_RIDE_FLAT + }; + for situation in [ + BotSituation { free: false, ..line }, + BotSituation { + group_ride: true, + ..line + }, + ] { + let mut bot = brain(RidingStyle::Sprinter); + bot.start(Move::Attack { intensity: 1.5 }, 30.0); + assert_eq!( + ride(&mut bot, &situation, 60.0, &mut SplitMix64::new(1)), + vec![Move::Ride] + ); + } + } + + #[test] + fn an_attacking_bot_leaves_a_blocked_lane() { + let mut bot = brain(RidingStyle::Attacker); + bot.current = Move::Attack { intensity: 1.5 }; + let view = LaneView { + current_lane: 1, + gap_ahead: vec![Some(4.0), Some(3.0), None, None], + }; + assert_eq!(bot.choose_lane(&view, 0.05), Some(2)); + } + + #[test] + fn only_some_moves_go_on_the_wire() { + assert_eq!(Move::Ride.id(), None); + assert_eq!(Move::Recover.id(), None); + assert_eq!(Move::SwingOff.id(), None); + assert_eq!(Move::Pull.id(), Some("pull")); + assert_eq!(Move::Attack { intensity: 1.4 }.id(), Some("attack")); + assert_eq!(Move::Answer.id(), Some("answer")); + assert_eq!(Move::Sprint { intensity: 1.9 }.id(), Some("sprint")); + } + + // --- lanes and levels (unchanged) ------------------------------------------------ + #[test] fn bot_stays_in_a_good_draft() { - let mut bot = brain(RidingStyle::Steady); + let mut bot = brain(RidingStyle::Rouleur); let view = LaneView { current_lane: 1, gap_ahead: vec![Some(3.0), Some(2.0), None, None], @@ -348,7 +1318,7 @@ mod tests { #[test] fn bot_moves_over_to_catch_a_wheel_and_then_waits() { - let mut bot = brain(RidingStyle::Steady); + let mut bot = brain(RidingStyle::Rouleur); let view = LaneView { current_lane: 1, gap_ahead: vec![None, None, Some(8.0), None], @@ -359,7 +1329,7 @@ mod tests { #[test] fn bot_ignores_far_away_riders() { - let mut bot = brain(RidingStyle::Steady); + let mut bot = brain(RidingStyle::Rouleur); let view = LaneView { current_lane: 0, gap_ahead: vec![None, Some(80.0)], @@ -388,7 +1358,7 @@ mod tests { fn matched_mixes_pack_and_field() { let mut rng = SplitMix64::new(7); let draws: Vec = (0..2000) - .map(|_| BotProfile::matched(&[2.5], &mut rng).ftp_wkg) + .map(|_| BotProfile::matched("Gus Tailwind", &[2.5], &mut rng).ftp_wkg) .collect(); let pack = draws.iter().filter(|w| (2.375..=2.75).contains(*w)).count() as f64 / 2000.0; assert!((0.68..=0.80).contains(&pack), "pack share {pack}"); @@ -399,20 +1369,9 @@ mod tests { fn matched_field_widens_to_the_humans() { let mut rng = SplitMix64::new(7); let draws: Vec = (0..2000) - .map(|_| BotProfile::matched(&[5.5], &mut rng).ftp_wkg) + .map(|_| BotProfile::matched("Gus Tailwind", &[5.5], &mut rng).ftp_wkg) .collect(); assert!(draws.iter().all(|w| *w <= 6.05)); assert!(draws.iter().cloned().fold(f64::MIN, f64::max) > 4.5); } - - #[test] - fn group_ride_intensity() { - let group = BotSituation { - group_ride: true, - ..FREE_RIDE_FLAT - }; - assert_eq!(brain(RidingStyle::Steady).target_intensity(&group), 0.75); - let racing = BotSituation { racing: true, ..group }; - assert_eq!(brain(RidingStyle::Steady).target_intensity(&racing), 0.95); - } } diff --git a/server/crates/sim/src/names.rs b/server/crates/sim/src/names.rs index 296604c0..3b16ea39 100644 --- a/server/crates/sim/src/names.rs +++ b/server/crates/sim/src/names.rs @@ -1,22 +1,112 @@ -//! Generated bot names in the form "Adjective Animal". +//! Bot names: a cast of made-up characters, a first name and a cycling pun +//! for a surname ("Gus Tailwind", "Penny Farthing", "Sally Sprocket"). All +//! invented, so no real person or film character is borrowed. A name also +//! fixes the character's riding type and team (see `bot::RidingStyle::of_name` +//! and `bot::Team::of_name`), so the same name rides the same way everywhere. use crate::rng::RandomSource; -const ADJECTIVES: &[&str] = &[ - "Swift", "Brave", "Steady", "Lucky", "Sunny", "Rapid", "Quiet", "Bold", "Clever", "Gentle", "Mighty", "Nimble", - "Jolly", "Calm", "Fierce", "Merry", "Rusty", "Silver", "Golden", "Breezy", +const FIRST_NAMES: &[&str] = &[ + "Lena", + "Jonas", + "Tomás", + "Lucía", + "Sofie", + "Mads", + "Giulia", + "Marco", + "Camille", + "Hugo", + "Femke", + "Daan", + "Kasia", + "Piotr", + "Ella", + "Oliver", + "Valentina", + "Andrés", + "Rita", + "Gus", + "Dolly", + "Barry", + "Penny", + "Hank", + "Patty", + "Freddie", + "Wendy", + "Clint", + "Sally", + "Bonnie", + "Kurt", + "Molly", + "Doug", + "Gerry", + "Ruby", + "Otto", + "Ingrid", + "Rosa", + "Nils", + "Mila", ]; -const ANIMALS: &[&str] = &[ - "Badger", "Falcon", "Otter", "Fox", "Heron", "Lynx", "Marmot", "Hare", "Ibex", "Kestrel", "Wolf", "Beaver", - "Stoat", "Swallow", "Bison", "Puffin", "Gecko", "Moose", "Raven", "Panda", +const SURNAMES: &[&str] = &[ + "Tailwind", + "Freewheel", + "Sprocket", + "Derailleur", + "Handlebar", + "Spokes", + "Cadence", + "Crankshaw", + "Chainring", + "Bidon", + "Musette", + "Puncture", + "Pannier", + "Headwind", + "Crosswind", + "Switchback", + "Hairpin", + "Breakaway", + "Slipstream", + "Draftsworth", + "Domestique", + "Bonk", + "Lowgear", + "Bigring", + "Cleats", + "Bottlecage", + "Toeclip", + "Brakewell", + "Tubeless", + "Flatwhite", + "Chamois", + "Saddlesore", + "Wheelie", + "Bunnyhop", + "Climbsworth", + "Watts", + "Sprintwell", + "Cobbles", + "Gravelly", + "Farthing", ]; -/// Returns a name such as "Swift Badger". +/// The easter egg of the cast: a rare rider in Team Zitrone's lemon yellow, +/// after the golden lemons on the road. +pub const LEMON_NAME: &str = "Goldie Lemon"; + +/// One new bot in this many is Goldie Lemon (while nobody else has the name). +const LEMON_ODDS: usize = 200; + +/// Returns a cast name such as "Gus Tailwind" (now and then "Goldie Lemon"). pub fn generate(rng: &mut dyn RandomSource) -> String { - let adjective = ADJECTIVES[rng.index(ADJECTIVES.len())]; - let animal = ANIMALS[rng.index(ANIMALS.len())]; - format!("{adjective} {animal}") + if rng.index(LEMON_ODDS) == 0 { + return LEMON_NAME.to_owned(); + } + let first = FIRST_NAMES[rng.index(FIRST_NAMES.len())]; + let last = SURNAMES[rng.index(SURNAMES.len())]; + format!("{first} {last}") } /// Returns a generated name that is not contained in `taken`. @@ -35,16 +125,43 @@ pub fn generate_unique(rng: &mut dyn RandomSource, taken: &[&str]) -> String { .expect("an unbounded range always yields a free name") } +/// A stable 64-bit hash of a name (FNV-1a), the same on every server. +pub fn name_hash(name: &str) -> u64 { + name.bytes().fold(0xcbf2_9ce4_8422_2325, |h, b| { + (h ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3) + }) +} + +#[cfg(test)] +pub(crate) fn all_names() -> Vec { + FIRST_NAMES + .iter() + .flat_map(|f| SURNAMES.iter().map(move |l| format!("{f} {l}"))) + .chain([LEMON_NAME.to_owned()]) + .collect() +} + #[cfg(test)] mod tests { use super::*; use crate::rng::SplitMix64; #[test] - fn names_have_two_words() { + fn names_are_a_first_name_and_a_cycling_surname() { let mut rng = SplitMix64::new(1); - let name = generate(&mut rng); - assert_eq!(name.split(' ').count(), 2); + for _ in 0..200 { + let name = generate(&mut rng); + let (first, last) = name.split_once(' ').expect("two words"); + assert!(FIRST_NAMES.contains(&first) && SURNAMES.contains(&last), "{name}"); + } + } + + #[test] + fn the_cast_is_large_enough_for_a_full_server() { + let mut all = all_names(); + all.sort(); + all.dedup(); + assert!(all.len() >= 1000, "{} names", all.len()); } #[test] @@ -57,12 +174,23 @@ mod tests { #[test] fn unique_names_fall_back_to_numbers_when_everything_is_taken() { - let all: Vec = ADJECTIVES - .iter() - .flat_map(|a| ANIMALS.iter().map(move |b| format!("{a} {b}"))) - .collect(); + let all = all_names(); let taken: Vec<&str> = all.iter().map(String::as_str).collect(); let name = generate_unique(&mut SplitMix64::new(5), &taken); assert!(name.ends_with(" 2"), "got {name}"); } + + #[test] + fn goldie_lemon_turns_up_now_and_then() { + let mut rng = SplitMix64::new(3); + let lemons = (0..20_000).filter(|_| generate(&mut rng) == LEMON_NAME).count(); + assert!((50..=150).contains(&lemons), "{lemons} in 20,000"); + } + + #[test] + fn the_name_hash_is_stable() { + assert_eq!(name_hash(""), 0xcbf2_9ce4_8422_2325); + assert_eq!(name_hash("Gus Tailwind"), name_hash("Gus Tailwind")); + assert_ne!(name_hash("Gus Tailwind"), name_hash("Gus Sprocket")); + } } diff --git a/server/crates/sim/src/world.rs b/server/crates/sim/src/world.rs index 7ea2b647..3fb8fb3a 100644 --- a/server/crates/sim/src/world.rs +++ b/server/crates/sim/src/world.rs @@ -14,14 +14,17 @@ //! onto any other road they ride off-route, road by road, straight on unless //! they pick another way. -use crate::bot::{pack_levels, BotBrain, BotProfile, BotSituation, BotTuning, LaneView}; +use crate::bot::{ + pack_levels, BotBrain, BotProfile, BotSituation, BotTuning, LaneView, LineAhead, LineKind, Passer, + DEFAULT_LEVEL_WKG, +}; use crate::drafting::DraftParams; use crate::names; use crate::network::{Network, RoadKey}; use crate::physics::{self, Body, PhysicsParams, RiderPhysics, StepInput}; use crate::race::{Race, RaceError, RaceEvent, RacePhase}; use crate::rng::{RandomSource, SplitMix64}; -use crate::route::Route; +use crate::route::{MarkerKind, Route}; use crate::sharing::SharingTuning; use crate::vehicle::{Vehicle, VehicleId, VehicleKind, VehicleParams}; use std::collections::{BTreeMap, BTreeSet}; @@ -37,8 +40,20 @@ pub type RouteIndex = usize; /// Tunables of the simulation. Everything has a sensible default. #[derive(Debug, Clone, PartialEq)] pub struct SimConfig { - /// Humans plus bots the world tries to keep riding on every route. + /// Humans plus bots the world keeps riding on every route + /// (`OPENRADLR_TARGET_RIDERS`; 0: no bots at all). pub target_riders: usize, + /// Bots every human riding a route keeps around them: up to + /// `company_radius_m` ahead or `company_behind_m` behind. They come out + /// of the route's `target_riders`: far bots make room, the count stays. + pub bots_near_human: usize, + /// How far ahead along the route a bot keeps a human company. + pub company_radius_m: f64, + /// How far behind a bot still keeps a human company: those further back + /// are passed and gone, and a new group takes their place ahead. + pub company_behind_m: f64, + /// New bots appear at least this far from every human (out of sight). + pub spawn_clear_m: f64, pub physics: PhysicsParams, pub draft: DraftParams, pub bot_tuning: BotTuning, @@ -69,6 +84,10 @@ impl Default for SimConfig { fn default() -> Self { Self { target_riders: 12, + bots_near_human: 6, + company_radius_m: 1500.0, + company_behind_m: 400.0, + spawn_clear_m: 350.0, physics: PhysicsParams::default(), draft: DraftParams::default(), bot_tuning: BotTuning::default(), @@ -274,6 +293,20 @@ struct Slot { draft: DraftParams, /// The road under the rider, how far along it, and the road after it. road: Option<(Step, f64, RoadKey)>, + speed: f64, + human: bool, +} + +/// What a bot sees around it in one step (see `World::bot_surroundings`). +#[derive(Debug, Clone, Copy, Default)] +struct Surroundings { + line_ahead: Option, + passer: Option, + wheel_behind: bool, + gap_ahead_m: Option, + human_m: Option, + waiting_for_group: bool, + leave_group: bool, } /// The race of one route and who is entered in it. @@ -306,6 +339,7 @@ pub struct World { /// The vehicle each seated rider (captain and bots included) sits in. seat_of: BTreeMap, next_vehicle_id: VehicleId, + next_group: u32, } impl World { @@ -384,6 +418,7 @@ impl World { vehicles: BTreeMap::new(), seat_of: BTreeMap::new(), next_vehicle_id: 1, + next_group: 1, }; world.balance_population(); world @@ -814,6 +849,8 @@ impl World { slots: &slots, }; + let around = self.bot_surroundings(&field, &own_slots); + // The draft each vehicle gets from the gap ahead of its captain. let vehicle_drafts: Vec<(VehicleId, f64)> = self .vehicles @@ -851,11 +888,22 @@ impl World { } _ => None, }; + let near = around.get(&rider.id).copied().unwrap_or_default(); + if near.leave_group { + brain.leave_group(); + } let situation = BotSituation { grade_percent: grade, racing: distance_to_finish.is_some(), group_ride: rider.in_group_ride, distance_to_finish, + free: !seated && rider.off_route.is_none(), + line_ahead: near.line_ahead, + passer: near.passer, + wheel_behind: near.wheel_behind, + gap_ahead_m: near.gap_ahead_m, + human_m: near.human_m, + waiting_for_group: near.waiting_for_group, }; rider.power = brain.power(&situation, self.rng.as_mut(), dt); rider.cadence = Some(85.0); @@ -954,6 +1002,8 @@ impl World { wide, draft, road, + speed: rider.speed, + human: !rider.is_bot(), } } @@ -1152,22 +1202,56 @@ impl World { } } - /// Keeps humans + bots at the target on every route: spawns bots where - /// there are too few riders, removes surplus bots once no human is nearby. + /// Riders of `route` that count towards its population: everyone but seated riders. + fn population(&self, route: RouteIndex) -> usize { + self.riders + .values() + .filter(|r| r.route == route && !self.seat_of.contains_key(&r.id)) + .count() + } + + /// Humans riding `route` freely, who keep bots around them: on the route, + /// not in a workout, a vehicle, a race or an event. Their position and level. + fn company_humans(&self, route: RouteIndex) -> Vec<(f64, f64)> { + let entrants = &self.races[route].entrants; + self.riders + .values() + .filter(|r| { + r.route == route + && !r.is_bot() + && r.off_route.is_none() + && !r.workout + && !r.in_group_ride + && !r.turns_locked + && !entrants.contains(&r.id) + && !self.seat_of.contains_key(&r.id) + }) + .map(|r| (r.position, r.level_wkg.unwrap_or(DEFAULT_LEVEL_WKG))) + .collect() + } + + /// A bot that may leave: not seated, racing or in a group ride. + fn free_bot(&self, r: &Rider) -> bool { + r.is_bot() + && !r.in_group_ride + && !self.races[r.route].entrants.contains(&r.id) + && !self.seat_of.contains_key(&r.id) + } + + /// Keeps every route at `target_riders`: company for its humans first + /// (far bots making room), then groups where the route is emptiest; + /// surplus bots leave once no human is nearby. fn balance_population(&mut self) { + let target = self.config.target_riders; for route in 0..self.routes.len() { - // Seated riders (a vehicle's captain, humans and bots) are not population. - let population = |world: &Self| { - world - .riders - .values() - .filter(|r| r.route == route && !world.seat_of.contains_key(&r.id)) - .count() - }; - while population(self) < self.config.target_riders { - self.spawn_bot(route); + self.keep_company(route, target); + while self.population(route) < target { + let room = target - self.population(route); + if self.spawn_group(route, None, room) == 0 { + break; + } } - while population(self) > self.config.target_riders { + while self.population(route) > target { // Humans anywhere on the map: a bot on a shared road can be in someone's view. let humans: Vec<(f64, f64)> = self .riders @@ -1175,17 +1259,10 @@ impl World { .filter(|r| !r.is_bot()) .map(|r| self.rider_xy(r)) .collect(); - let entrants = &self.races[route].entrants; let candidate = self .riders .values() - .filter(|r| { - r.route == route - && r.is_bot() - && !r.in_group_ride - && !entrants.contains(&r.id) - && !self.seat_of.contains_key(&r.id) - }) + .filter(|r| r.route == route && self.free_bot(r)) .map(|bot| { let at = self.rider_xy(bot); let nearest = humans.iter().map(|&h| distance(h, at)).fold(f64::INFINITY, f64::min); @@ -1203,6 +1280,87 @@ impl World { } } + /// Whether a rider at route position `bot` keeps a human at `at` company. + fn keeps_company(&self, route: RouteIndex, at: f64, bot: f64) -> bool { + let line = &self.routes[route]; + let ahead = line.forward_gap(at, bot); + ahead <= self.config.company_radius_m.min(line.length() / 2.0) + || line.length() - ahead <= self.config.company_behind_m + } + + /// Bots of `route` keeping the human at route position `at` company. + fn bots_near(&self, route: RouteIndex, at: f64) -> usize { + self.riders + .values() + .filter(|r| { + r.route == route + && r.is_bot() + && r.off_route.is_none() + && !self.seat_of.contains_key(&r.id) + && self.keeps_company(route, at, r.position) + }) + .count() + } + + /// Spawns a group for every human of `route` with too few bots around, + /// making room first where the route is full. + fn keep_company(&mut self, route: RouteIndex, target: usize) { + if self.config.bots_near_human == 0 || target == 0 { + return; + } + for (at, level) in self.company_humans(route) { + loop { + let near = self.bots_near(route, at); + let Some(missing) = self.config.bots_near_human.checked_sub(near).filter(|&m| m > 0) else { + break; + }; + while self.population(route) >= target && self.make_room(route) {} + let room = target.saturating_sub(self.population(route)); + if room == 0 || self.spawn_group(route, Some((at, level)), missing.min(room)) == 0 { + break; + } + } + } + } + + /// Removes the bot of `route` furthest from every human, if it is out of + /// sight and keeps nobody company. Returns whether one left. + fn make_room(&mut self, route: RouteIndex) -> bool { + let humans: Vec<(f64, f64)> = self + .riders + .values() + .filter(|r| !r.is_bot()) + .map(|r| self.rider_xy(r)) + .collect(); + let company = self.company_humans(route); + let candidate = self + .riders + .values() + .filter(|r| r.route == route && self.free_bot(r)) + .filter(|r| { + r.off_route.is_some() + || company + .iter() + .all(|&(at, _)| !self.keeps_company(route, at, r.position)) + }) + .map(|bot| { + let at = self.rider_xy(bot); + ( + bot.id, + humans.iter().map(|&h| distance(h, at)).fold(f64::INFINITY, f64::min), + ) + }) + .filter(|&(_, nearest)| nearest >= self.config.bot_despawn_distance_m) + .max_by(|a, b| a.1.total_cmp(&b.1)); + match candidate { + Some((id, _)) => { + self.leave_without_rebalance(id); + true + } + None => false, + } + } + fn leave_without_rebalance(&mut self, id: RiderId) { if let Some(rider) = self.riders.remove(&id) { self.events.push(WorldEvent::RiderLeft { @@ -1213,23 +1371,15 @@ impl World { } } - /// Candidate start points a new bot picks from: the one furthest from + /// Candidate start points a new group picks from: the one furthest from /// everybody, so bots spread over the map instead of piling up where /// routes share a road. const SPAWN_CANDIDATES: usize = 6; + /// Rows of a group, one bike length and a bit apart. + const GROUP_ROW_M: f64 = 2.5; - fn spawn_bot(&mut self, route: RouteIndex) { - let levels = pack_levels(&self.human_levels()); - self.spawn_bot_matched(route, &levels); - } - - fn spawn_bot_matched(&mut self, route: RouteIndex, levels: &[f64]) -> RiderId { - let id = self.allocate_id(); - let taken: Vec<&str> = self.riders.values().map(|r| r.name.as_str()).collect(); - let name = names::generate_unique(self.rng.as_mut(), &taken); - let profile = BotProfile::matched(levels, self.rng.as_mut()); - let lanes = self.routes[route].lanes(); - let lane = self.rng.index(usize::from(lanes)) as u8; + /// The emptiest of a few random points of `route`. + fn emptiest_position(&mut self, route: RouteIndex) -> f64 { let length = self.routes[route].length(); let others: Vec<(f64, f64)> = self.riders.values().map(|r| self.rider_xy(r)).collect(); let mut position = self.rng.range_f64(0.0, length); @@ -1243,15 +1393,121 @@ impl World { position = candidate; } } + position + } + + /// Where a group for a human at route position `at` of level `level` + /// starts and at what level: 70% ahead and a bit slower (a group to + /// chase), else behind and a bit faster (a wheel coming by). Out of sight + /// of every human, or `None`. + fn company_spot(&mut self, route: RouteIndex, at: f64, level: f64) -> Option<(f64, f64)> { + let humans: Vec<(f64, f64)> = self + .riders + .values() + .filter(|r| !r.is_bot()) + .map(|r| self.rider_xy(r)) + .collect(); + let ahead = self.rng.next_f64() < 0.7; + let factor = if ahead { + self.rng.range_f64(0.85, 0.95) + } else { + self.rng.range_f64(1.05, 1.15) + }; + for _ in 0..Self::SPAWN_CANDIDATES { + let offset = if ahead { + self.rng.range_f64(350.0, 800.0) + } else { + -self.rng.range_f64(350.0, 600.0) + }; + let position = self.routes[route].wrap(at + offset); + let xy = self.routes[route].position_at(position); + if humans.iter().all(|&h| distance(h, xy) >= self.config.spawn_clear_m) { + return Some((position, level * factor)); + } + } + None + } + + /// Spawns a group of up to `max` bots on `route` (2–5, now and then one): + /// for a human (`company`: their route position and level) or where the + /// route is emptiest, matched to the humans online. Returns how many. + fn spawn_group(&mut self, route: RouteIndex, company: Option<(f64, f64)>, max: usize) -> usize { + let size = if self.rng.next_f64() < 0.2 { + 1 + } else { + 2 + self.rng.index(4) + } + .min(max); + if size == 0 { + return 0; + } + let (lead, level) = match company { + Some((at, level)) => match self.company_spot(route, at, level) { + Some((position, level)) => (position, Some(level)), + None => return 0, + }, + None => (self.emptiest_position(route), None), + }; + let group = (size > 1).then(|| { + let id = self.next_group; + self.next_group = self.next_group.wrapping_add(1).max(1); + id + }); + let levels = pack_levels(&self.human_levels()); + let lanes = usize::from(self.routes[route].lanes()); + let first_lane = self.rng.index(lanes); + let mut base = level; + for k in 0..size { + let name = self.unique_name(); + let mut profile = BotProfile::matched(&name, &levels, self.rng.as_mut()); + match base { + Some(level) if k == 0 && company.is_some() => profile.ftp_wkg = level, + Some(level) => profile.ftp_wkg = level * self.rng.range_f64(0.97, 1.03), + None => {} + } + base.get_or_insert(profile.ftp_wkg); + let row = (k / lanes) as f64; + let position = self.routes[route].wrap(lead - row * Self::GROUP_ROW_M); + let lane = ((first_lane + k) % lanes) as u8; + self.spawn_bot_at(route, &name, profile, position, lane, group); + } + size + } + + fn unique_name(&mut self) -> String { + let taken: Vec<&str> = self.riders.values().map(|r| r.name.as_str()).collect(); + names::generate_unique(self.rng.as_mut(), &taken) + } + + fn spawn_bot_matched(&mut self, route: RouteIndex, levels: &[f64]) -> RiderId { + let name = self.unique_name(); + let profile = BotProfile::matched(&name, levels, self.rng.as_mut()); + let lanes = self.routes[route].lanes(); + let lane = self.rng.index(usize::from(lanes)) as u8; + let position = self.emptiest_position(route); + self.spawn_bot_at(route, &name, profile, position, lane, None) + } + + fn spawn_bot_at( + &mut self, + route: RouteIndex, + name: &str, + profile: BotProfile, + position: f64, + lane: u8, + group: Option, + ) -> RiderId { + let id = self.allocate_id(); let mass_kg = profile.weight_kg; let cruising_speed = 8.0; + let brain = BotBrain::new(profile, self.config.bot_tuning).in_group(group); self.riders.insert( id, Rider { id, - name: name.clone(), - controller: Controller::Bot(Box::new(BotBrain::new(profile, self.config.bot_tuning))), + name: name.to_owned(), + controller: Controller::Bot(Box::new(brain)), mass_kg, route, position, @@ -1275,13 +1531,110 @@ impl World { ); self.events.push(WorldEvent::RiderJoined { rider_id: id, - name, + name: name.to_owned(), is_bot: true, route, }); id } + /// What every bot on its route sees around it this step. + fn bot_surroundings(&self, field: &Field<'_>, slots: &[Slot]) -> BTreeMap { + const WHEEL_M: f64 = 4.0; + const PASSING_M: f64 = 8.0; + const GROUP_WAIT_M: f64 = 25.0; + const GROUP_SPLIT_M: f64 = 300.0; + let groups: Vec<(RiderId, u32, RouteIndex, f64)> = self + .riders + .values() + .filter(|r| r.off_route.is_none()) + .filter_map(|r| match &r.controller { + Controller::Bot(brain) => brain.group().map(|g| (r.id, g, r.route, r.position)), + Controller::Human { .. } => None, + }) + .collect(); + let mut around = BTreeMap::new(); + for (rider, me) in self.riders.values().zip(slots) { + if !rider.is_bot() || rider.off_route.is_some() || self.seat_of.contains_key(&rider.id) { + continue; + } + let route = &self.routes[rider.route]; + let line_ahead = route + .markers() + .iter() + .enumerate() + .filter_map(|(index, marker)| { + let (kind, length) = match marker.kind { + MarkerKind::Sprint { length } => (LineKind::Sprint, length), + MarkerKind::Climb { length } => (LineKind::Summit, length), + MarkerKind::StartFinish => return None, + }; + let line = route.wrap(marker.distance + length); + Some(LineAhead { + kind, + index, + distance_m: route.forward_gap(rider.position, line), + }) + }) + .min_by(|a, b| a.distance_m.total_cmp(&b.distance_m)); + let same_road = |s: &&Slot| s.id != me.id && s.route == me.route && s.on_route; + let passer = slots + .iter() + .filter(same_road) + .filter(|s| { + let gap = route.forward_gap(me.position, s.position); + gap > 0.0 && gap <= PASSING_M && s.speed > me.speed + }) + .map(|s| Passer { + human: s.human, + speed_gain: s.speed - me.speed, + lane: s.lane.round().max(0.0) as u8, + }) + .max_by(|a, b| a.speed_gain.total_cmp(&b.speed_gain)); + let wheel_behind = field.gap_behind(me, me.lane).is_some_and(|gap| gap <= WHEEL_M); + let human_m = slots + .iter() + .filter(same_road) + .filter(|s| s.human) + .map(|s| route.loop_distance(me.position, s.position)) + .min_by(f64::total_cmp); + let mut waiting_for_group = false; + let mut leave_group = false; + if let Some(group) = groups.iter().find(|g| g.0 == rider.id).map(|g| g.1) { + let mates: Vec = groups + .iter() + .filter(|g| g.0 != rider.id && g.1 == group && g.2 == rider.route) + .map(|g| g.3) + .collect(); + let nearest = mates + .iter() + .map(|&p| route.loop_distance(rider.position, p)) + .fold(f64::INFINITY, f64::min); + if nearest > GROUP_SPLIT_M { + leave_group = true; + } else { + let all_behind = mates + .iter() + .all(|&p| route.forward_gap(p, rider.position) < route.length() / 2.0); + waiting_for_group = all_behind && nearest > GROUP_WAIT_M; + } + } + around.insert( + rider.id, + Surroundings { + line_ahead, + passer, + wheel_behind, + gap_ahead_m: field.gap_ahead(me, me.lane), + human_m, + waiting_for_group, + leave_group, + }, + ); + } + around + } + fn allocate_id(&mut self) -> RiderId { let id = self.next_id; self.next_id = self.next_id.wrapping_add(1).max(1); @@ -1451,6 +1804,18 @@ impl Field<'_> { .min_by(|a, b| a.0.total_cmp(&b.0)) } + /// Gap to the closest rider behind `me` in `lane` on its route, if any. + fn gap_behind(&self, me: &Slot, lane: f64) -> Option { + let route = &self.routes[me.route]; + self.slots + .iter() + .filter(|s| s.id != me.id && s.route == me.route && s.on_route && me.on_route) + .filter(|s| (s.lane - lane).abs() < s.half_width.max(me.half_width)) + .map(|s| route.forward_gap(s.position, me.position)) + .filter(|&gap| gap > 0.0 && gap < route.length() / 2.0) + .min_by(f64::total_cmp) + } + fn lane_view(&self, me: &Slot) -> LaneView { let lanes = self.routes[me.route].lanes(); LaneView { @@ -1465,7 +1830,7 @@ mod tests { use super::*; use crate::rng::SplitMix64; use crate::route::tests::{flat_loop, square_loop, step}; - use crate::route::{Point, RouteSpec, WalkStep}; + use crate::route::{Marker, Point, RouteSpec, WalkStep}; pub(super) const DT: f64 = 0.05; @@ -1581,6 +1946,7 @@ mod tests { let config = SimConfig { target_riders: 3, bot_despawn_distance_m: 0.0, + bots_near_human: 0, ..SimConfig::default() }; let mut world = world_with(square_loop(), config); @@ -1595,6 +1961,7 @@ mod tests { let config = SimConfig { target_riders: 1, bot_despawn_distance_m: 10_000.0, + bots_near_human: 0, ..SimConfig::default() }; let mut world = world_with(square_loop(), config); @@ -2154,16 +2521,26 @@ mod tests { } #[test] - fn bots_spread_out_instead_of_piling_up() { + fn bot_groups_spread_out_instead_of_piling_up() { let world = map_world(10); - let at: Vec<(f64, f64)> = world.riders().map(|r| world.rider_xy(r)).collect(); + // One rider of each group (a bot riding alone is a group of its own). + let mut seen = BTreeSet::new(); + let at: Vec<(f64, f64)> = world + .riders() + .filter(|r| match &r.controller { + Controller::Bot(brain) => brain.group().is_none_or(|g| seen.insert(g)), + Controller::Human { .. } => true, + }) + .map(|r| world.rider_xy(r)) + .collect(); let closest = at .iter() .enumerate() .flat_map(|(i, &a)| at[i + 1..].iter().map(move |&b| distance(a, b))) .fold(f64::INFINITY, f64::min); - // 30 bots on 7.6 km of road: random starts would put some within a few metres. - assert!(closest > 25.0, "two bots start {closest:.1} m apart"); + // 30 bots in groups on 7.6 km of road: random starts would put some within a few metres. + assert!(at.len() >= 6, "{} groups", at.len()); + assert!(closest > 25.0, "two groups start {closest:.1} m apart"); } #[test] @@ -2545,4 +2922,317 @@ mod tests { let world = empty_world(flat_loop(1000.0)); assert_eq!(world.rider_physics(9_999), None); } + + // --- bots: population, company, groups and what they see ------------------------- + + fn company_world(config: SimConfig, seed: u64) -> World { + World::new(flat_loop(20_000.0), config, Box::new(SplitMix64::new(seed))) + } + + fn bot_level(rider: &Rider) -> f64 { + match &rider.controller { + Controller::Bot(brain) => brain.profile().ftp_wkg, + Controller::Human { .. } => panic!("{} is no bot", rider.name), + } + } + + fn group_of(rider: &Rider) -> Option { + match &rider.controller { + Controller::Bot(brain) => brain.group(), + Controller::Human { .. } => None, + } + } + + fn joined_bots(world: &mut World) -> Vec { + world + .drain_events() + .into_iter() + .filter_map(|e| match e { + WorldEvent::RiderJoined { + rider_id, is_bot: true, .. + } => Some(rider_id), + _ => None, + }) + .filter(|id| world.rider(*id).is_some()) + .collect() + } + + fn surroundings_of(world: &World, id: RiderId) -> Surroundings { + let slots: Vec = world.riders().map(|r| world.slot(r)).collect(); + let field = Field { + routes: &world.routes, + slots: &slots, + }; + world.bot_surroundings(&field, &slots)[&id] + } + + #[test] + fn a_route_keeps_its_target_however_many_humans_want_company() { + let config = SimConfig { + target_riders: 12, + bot_despawn_distance_m: 0.0, + ..SimConfig::default() + }; + let mut world = company_world(config, 1); + for name in ["Anna", "Ben", "Cleo", "Dan", "Eva"] { + world.join_human(name, 70.0); + world.tick(DT); + assert_eq!(world.riders().count(), 12, "after {name} joined"); + } + } + + #[test] + fn a_world_without_bots_stays_without_bots() { + let mut world = company_world( + SimConfig { + target_riders: 0, + ..SimConfig::default() + }, + 1, + ); + world.join_human("Anna", 70.0); + world.tick(DT); + assert_eq!(world.bot_count(), 0); + } + + #[test] + fn every_human_gets_company_that_appears_out_of_sight() { + for seed in 0..8 { + let mut world = company_world( + SimConfig { + target_riders: 7, + ..SimConfig::default() + }, + seed, + ); + world.drain_events(); + let anna = world.join_human("Anna", 70.0); + for _ in 0..20 { + world.tick(DT); + } + let me = world.rider(anna).unwrap(); + let (at, xy) = (me.position, world.rider_xy(me)); + let route = world.route(0); + let near = world + .riders() + .filter(|r| r.is_bot() && route.loop_distance(at, r.position) <= 1500.0) + .count(); + assert!(near >= 6, "seed {seed}: {near} bots near"); + for id in joined_bots(&mut world) { + let bot = world.rider(id).unwrap(); + // Spawned at least 350 m away; a second of riding since. + assert!( + distance(world.rider_xy(bot), xy) >= 330.0, + "seed {seed}: {} appeared in sight", + bot.name + ); + } + } + } + + #[test] + fn company_ahead_is_a_bit_slower_and_company_behind_a_bit_faster() { + let (mut ahead, mut behind) = (0, 0); + for seed in 0..16 { + // One human and their company fill the route: every new bot is company. + let mut world = company_world( + SimConfig { + target_riders: 7, + ..SimConfig::default() + }, + seed, + ); + world.drain_events(); + world.join_human("Anna", 70.0); + let level = DEFAULT_LEVEL_WKG; + for id in joined_bots(&mut world) { + let bot = world.rider(id).unwrap(); + let wkg = bot_level(bot); + if world.route(0).forward_gap(0.0, bot.position) < 10_000.0 { + ahead += 1; + assert!( + (level * 0.85 * 0.97..=level * 0.95 * 1.03).contains(&wkg), + "ahead at {wkg}" + ); + } else { + behind += 1; + assert!( + (level * 1.05 * 0.97..=level * 1.15 * 1.03).contains(&wkg), + "behind at {wkg}" + ); + } + } + } + assert!(ahead > behind && behind > 0, "{ahead} ahead, {behind} behind"); + } + + #[test] + fn a_full_route_brings_its_far_bots_to_a_lonely_human() { + let config = SimConfig { + target_riders: 6, + ..SimConfig::default() + }; + let mut world = company_world(config, 3); + let bots: Vec = world.riders().map(|r| r.id).collect(); + for (k, id) in bots.iter().enumerate() { + place(&mut world, *id, 9000.0 + 10.0 * k as f64, 8.0); + } + let anna = world.join_human("Anna", 70.0); + for _ in 0..40 { + world.tick(DT); + } + assert_eq!(world.riders().count(), 6); + let at = world.rider(anna).unwrap().position; + let near = world + .riders() + .filter(|r| r.is_bot() && world.route(0).loop_distance(at, r.position) <= 1500.0) + .count(); + assert_eq!(near, 5, "every bot moved to Anna"); + } + + #[test] + fn humans_in_a_race_bring_no_company() { + let mut world = company_world( + SimConfig { + target_riders: 1, + race_countdown_s: 30.0, + ..SimConfig::default() + }, + 1, + ); + let anna = world.join_human("Anna", 70.0); + assert_eq!(world.company_humans(0).len(), 1); + world.start_race(1, Some(anna)).unwrap(); + assert!(world.company_humans(0).is_empty()); + } + + fn spawn_a_group(world: &mut World, at_least: usize) -> Vec { + loop { + world.drain_events(); + let n = world.spawn_group(0, None, 5); + let ids = joined_bots(world); + assert_eq!(ids.len(), n); + if n >= at_least { + return ids; + } + } + } + + #[test] + fn a_group_starts_together_in_rows_at_about_one_level() { + let mut world = empty_world(flat_loop(10_000.0)); + let ids = spawn_a_group(&mut world, 5); + let members: Vec<&Rider> = ids.iter().map(|id| world.rider(*id).unwrap()).collect(); + let group = group_of(members[0]); + assert!(group.is_some()); + assert!(members.iter().all(|r| group_of(r) == group)); + let route = world.route(0); + for r in &members { + assert!( + route.loop_distance(members[0].position, r.position) <= 2.5 + 1e-9, + "rows 2.5 m apart" + ); + } + let lanes: BTreeSet = members[..4].iter().map(|r| r.target_lane).collect(); + assert_eq!(lanes.len(), 4, "the first row spans the lanes"); + let levels: Vec = members.iter().map(|r| bot_level(r)).collect(); + let (low, high) = levels + .iter() + .fold((f64::MAX, f64::MIN), |(l, h), &w| (l.min(w), h.max(w))); + assert!(high / low <= 1.03 / 0.97 + 1e-9, "levels {levels:?}"); + } + + #[test] + fn a_bot_ahead_of_its_group_waits_and_one_far_away_rides_alone() { + // No bots of its own, and the group's bots never leave. + let config = SimConfig { + target_riders: 0, + bot_despawn_distance_m: f64::INFINITY, + ..SimConfig::default() + }; + let mut world = world_with(flat_loop(10_000.0), config); + world.join_human("Anna", 70.0); + let ids = spawn_a_group(&mut world, 3); + let (a, b, c) = (ids[0], ids[1], ids[2]); + place(&mut world, a, 1000.0, 8.0); + place(&mut world, b, 970.0, 8.0); + place(&mut world, c, 965.0, 8.0); + for &id in &ids[3..] { + place(&mut world, id, 960.0, 8.0); + } + assert!(surroundings_of(&world, a).waiting_for_group); + assert!(!surroundings_of(&world, b).waiting_for_group); + place(&mut world, a, 980.0, 8.0); + assert!(!surroundings_of(&world, a).waiting_for_group, "close enough"); + place(&mut world, a, 1500.0, 8.0); + assert!(surroundings_of(&world, a).leave_group); + world.tick(DT); + assert_eq!(group_of(world.rider(a).unwrap()), None); + } + + fn marked_loop() -> Route { + Route::new(RouteSpec { + id: "marked".into(), + name: "Marked".into(), + lanes: 4, + seed: 1, + points: vec![Point::new(0.0, 0.0, 0.0), Point::new(5000.0, 0.0, 0.0)], + markers: vec![ + Marker { + kind: MarkerKind::StartFinish, + distance: 0.0, + }, + Marker { + kind: MarkerKind::Climb { length: 1000.0 }, + distance: 500.0, + }, + Marker { + kind: MarkerKind::Sprint { length: 300.0 }, + distance: 2000.0, + }, + ], + walk: vec![], + }) + .expect("valid route") + } + + #[test] + fn a_bot_sees_the_next_line_the_human_and_who_comes_past() { + let mut world = empty_world(marked_loop()); + let anna = world.join_human("Anna", 70.0); + let bot = world.spawn_bot_matched(0, &[]); + place(&mut world, bot, 1200.0, 8.0); + place(&mut world, anna, 1205.0, 10.0); + let seen = surroundings_of(&world, bot); + assert_eq!( + seen.line_ahead, + Some(LineAhead { + kind: LineKind::Summit, + index: 1, + distance_m: 300.0 + }) + ); + assert_eq!( + seen.passer, + Some(Passer { + human: true, + speed_gain: 2.0, + lane: 1 + }) + ); + assert_eq!(seen.human_m, Some(5.0)); + assert_eq!(seen.gap_ahead_m, Some(5.0)); + assert!(!seen.wheel_behind); + + place(&mut world, anna, 1197.0, 8.0); + let seen = surroundings_of(&world, bot); + assert!(seen.wheel_behind); + assert_eq!(seen.passer, None); + + place(&mut world, bot, 1600.0, 8.0); + assert_eq!( + surroundings_of(&world, bot).line_ahead.map(|l| (l.kind, l.distance_m)), + Some((LineKind::Sprint, 700.0)) + ); + } } diff --git a/server/crates/sim/src/world/vehicles.rs b/server/crates/sim/src/world/vehicles.rs index d2400e58..1213ff67 100644 --- a/server/crates/sim/src/world/vehicles.rs +++ b/server/crates/sim/src/world/vehicles.rs @@ -378,7 +378,7 @@ impl World { let id = self.allocate_id(); let taken: Vec<&str> = self.riders.values().map(|r| r.name.as_str()).collect(); let name = names::generate_unique(self.rng.as_mut(), &taken); - let mut profile = BotProfile::random(self.rng.as_mut()); + let mut profile = BotProfile::character(&name, self.rng.as_mut()); profile.ftp_wkg = level_wkg; let lane = self.routes[route].lanes() / 2; let mass_kg = profile.weight_kg;