From e2d1968a77adc036572ef73908f7013807b4cf56 Mon Sep 17 00:00:00 2001 From: Davide Cappellini Date: Mon, 5 Oct 2026 22:43:30 +0200 Subject: [PATCH] Bots: env reporting, TFIL movement, gun selector and docs refresh DevControlBot DevControlBot.sh env-file handling and defines, tfil.nim survival-movement rework, README ModularBot .env.example, ModularBot.nim, env_report.nim, vbullet_draw.nim PPO_Bot enemy_tracker.nim common_libs gun_harness/selector.nim tests env_report, lead_gain_legacy, rack_membership, rack_stat_width, tm_pattern_registration adjustments docs env_reference.md, goto-controller-algorithm.md --- .../DevControlBot/DevControlBot.sh | 50 ++++- .../DevControlBot/modules/tfil.nim | 184 +++++++++--------- DevControlBot_garage/README.md | 9 +- ModularBot_garage/.env.example | 36 +++- ModularBot_garage/src/ModularBot.nim | 56 +++++- ModularBot_garage/src/env_report.nim | 10 + ModularBot_garage/src/vbullet_draw.nim | 2 + PPO_Bot_garage/src/PPO_Bot/enemy_tracker.nim | 13 +- common_libs/gun_harness/selector.nim | 18 +- common_libs/tests/test_env_report.nim | 2 +- common_libs/tests/test_lead_gain_legacy.nim | 4 +- common_libs/tests/test_rack_membership.nim | 13 +- common_libs/tests/test_rack_stat_width.nim | 23 ++- .../tests/test_tm_pattern_registration.nim | 3 +- docs/env_reference.md | 12 +- docs/research/goto-controller-algorithm.md | 16 +- 16 files changed, 309 insertions(+), 142 deletions(-) diff --git a/DevControlBot_garage/DevControlBot/DevControlBot.sh b/DevControlBot_garage/DevControlBot/DevControlBot.sh index a715abc..f829e04 100755 --- a/DevControlBot_garage/DevControlBot/DevControlBot.sh +++ b/DevControlBot_garage/DevControlBot/DevControlBot.sh @@ -7,11 +7,15 @@ # propagates the real exit code. Signals are forwarded to Nimble so the task's # own EXIT/INT/TERM cleanup always runs. # -# Usage: DevControlBot.sh [--debug] [] [extra args for the bot] +# Usage: DevControlBot.sh [--debug] [-d:[=]]... [] [extra args] # # (no args) RELEASE build + run with the bundled DevControlBot.json # (no flag) RELEASE build (nim c -d:release), quiet output # --debug classic DEBUG build (plain nim c): compiler hints + diagnostics +# -d:foo compile-time Nim define. ANY number, in any position, in EITHER +# build mode: --debug only changes optimisation/hints, defines are +# independent of it, so `-d:tfilDebug` debug graphics work in a +# release build too. Accepted forms: -d:foo and -d:foo=bar. # # --debug is a build-mode flag for this wrapper only: it is stripped here and # never reaches the bot binary or nimble's task arguments. It travels to the @@ -19,6 +23,14 @@ # confused with a bot argument, cannot collide with the status file mechanism # and keeps the task's argument parsing untouched. Repeated --debug is harmless. # +# -d: args travel the same way, as $DEVCONTROLBOT_DEFINES. They MUST be stripped +# here: the runBot task forwards its own argv to the BOT BINARY, so a -d: arg +# would otherwise become the bot's argv and never reach the compiler. Matching is +# the anchored glob `-d:*` (whole-argument, starts with -d:), so a value that +# merely contains "-d:" inside another word ("x-d:y", "--debug-d:x") is NOT a +# define and is forwarded verbatim. Anything that is neither --debug, -h/--help +# nor a -d: arg still reaches the bot binary exactly as before. +# # Configuration (SERVER_URL, SERVER_SECRET, ...) is NOT handled here at all: the # API's start() reads those from the environment, and the optional .env file is # loaded by the runBot task, so it also works with a direct `nimble runBot`. @@ -30,11 +42,16 @@ cd "$SCRIPT_DIR" usage() { cat <] [extra args for the bot] +Usage: $(basename "$0") [--debug] [-d:[=]]... [] [extra args for the bot] - --debug classic debug build: shows compiler hints and diagnostics - (default is a quiet RELEASE build, nim c -d:release) - -h,--help show this help + --debug classic debug build: shows compiler hints and diagnostics + (default is a quiet RELEASE build, nim c -d:release) + -d:foo, -d:foo=bar Nim compile-time define, passed to `nim c`. Repeatable. + Independent of --debug: defines apply in BOTH build modes, + so `-d:tfilDebug` debug graphics also work in a release + build. Only whole args starting with -d: are treated as + defines; everything else is forwarded to the bot binary. + -h,--help show this help Examples: $(basename "$0") # release build + run, bundled DevControlBot.json @@ -42,15 +59,33 @@ Examples: $(basename "$0") -h # this help $(basename "$0") --debug # debug build $(basename "$0") --debug my.json # debug build with custom metadata + $(basename "$0") -d:tfilDebug # release build with TFIL debug graphics + $(basename "$0") --debug -d:tfilDebug # debug build, also with debug graphics + $(basename "$0") -d:danger -d:logLevel=2 my.json EOF } -# Split caller args: everything except --debug is forwarded verbatim. +# Split caller args: --debug and -d: defines are consumed here, everything else +# is forwarded verbatim. The defines end up in a single space-separated string +# because the compiler line is `eval`ed (like $DEPS) to survive paths with spaces. BUILD_MODE=release +DEFINES="" FORWARDED=() for a in "$@"; do case "$a" in --debug) BUILD_MODE=debug ;; + -d:*) + # TRUST BOUNDARY: the string is eval'ed by the runBot task, so a define + # carrying whitespace, quotes, $, ` or ; could inject shell. Reject it + # loudly instead of passing it on. Legal Nim defines (-d:foo, -d:foo=bar) + # contain none of these. + case "$a" in + *[[:space:]\"\'\$\;\`\\]*) + echo "$(basename "$0"): invalid define '$a'" >&2 + echo " expected -d:name or -d:name=value with no spaces or shell characters" >&2 + exit 1 ;; + esac + DEFINES="$DEFINES $a" ;; *) FORWARDED+=("$a") ;; esac done @@ -63,6 +98,9 @@ case "${1:-}" in esac export DEVCONTROLBOT_DEBUG="$BUILD_MODE" +# Leading space trimmed: empty when the caller passed no -d: arg, and the runBot +# task's compile lines are then byte-identical to a run without this feature. +export DEVCONTROLBOT_DEFINES="${DEFINES# }" # The runBot task's shell always exits 0 (otherwise Nimble raises a NimScript # exception with a stack trace and a dump of the whole script) and writes the diff --git a/DevControlBot_garage/DevControlBot/modules/tfil.nim b/DevControlBot_garage/DevControlBot/modules/tfil.nim index 5e28324..94c7c06 100644 --- a/DevControlBot_garage/DevControlBot/modules/tfil.nim +++ b/DevControlBot_garage/DevControlBot/modules/tfil.nim @@ -20,7 +20,7 @@ ## exactly the flat one), corridors run to the wall, the virtual centre pillar ## is absent (0/0), the pick is a UNIFORM draw (no turn / no-rev / geometry ## tilt), no arrival bound, no bounded hold, no commit diagnostics. -## * debug graphics — restored below, but behind `-d:tfilDebug` (off by default, +## * debug graphics — restored below, but behind ` ` (off by default, ## since the SVG payload costs time every tick). ## * the pure bookkeeping fields (loss histogram, lastPick*, log-only vars). ## @@ -28,8 +28,7 @@ import std/[math, random] import robocode_tankroyale_botapi -import robocode_tankroyale_botapi/graphics -import robocode_tankroyale_botapi/color +import robocode_tankroyale_botapi/color # graphics comes re-exported by the import above ## ── Debug graphics ────────────────────────────────────────────────────────── ## OFF by default: the drawing is a real per-tick cost (an SVG buffer sent to @@ -534,107 +533,108 @@ proc collectCoolestTiles(m: var TfilModule): seq[tuple[col, row: int]] = result.add t break -proc drawHeatField(m: TfilModule, ws: WorldState) = - ## The lava field per tile (colour ramp + value text), the tracked bullets' - ## core/aura circles, their danger corridors and the enemies' core/aura. +when defined(tfilDebug): + proc drawHeatField(m: TfilModule, ws: WorldState) = + ## The lava field per tile (colour ramp + value text), the tracked bullets' + ## core/aura circles, their danger corridors and the enemies' core/aura. - var maxLava = 0.0 - for v in m.lava: - if v > maxLava: maxLava = v + var maxLava = 0.0 + for v in m.lava: + if v > maxLava: maxLava = v - setFont("Arial", 10.0) - for row in 0.. 0.0: val / maxLava else: 0.0 - let heatColor = fromRgb(255'u8, uint8(255.0 * (1.0 - t)), 0'u8) - let x0 = m.marginX + col.float * GridSize - let y0 = m.marginY + row.float * GridSize - setStrokeColor(heatColor) + setFont("Arial", 10.0) + for row in 0.. 0.0: val / maxLava else: 0.0 + let heatColor = fromRgb(255'u8, uint8(255.0 * (1.0 - t)), 0'u8) + let x0 = m.marginX + col.float * GridSize + let y0 = m.marginY + row.float * GridSize + setStrokeColor(heatColor) + setStrokeWidth(1.0) + drawRectangle(x0, y0, GridSize, GridSize) + setFillColor(heatColor) + drawText($int(val), x0 + 12.0, y0 + 22.0) + + # Tracked bullets: red core outline + filled centre, orange aura ring. + for b in m.bullets: + let (coreR, auraR) = bulletRadii(b.power) + setStrokeColor(RED) setStrokeWidth(1.0) - drawRectangle(x0, y0, GridSize, GridSize) - setFillColor(heatColor) - drawText($int(val), x0 + 12.0, y0 + 22.0) + setFillColor(RED) + drawCircle(b.x, b.y, coreR) + fillCircle(b.x, b.y, 3.0) + setStrokeColor(fromHex("#FF8800")) + drawCircle(b.x, b.y, auraR) - # Tracked bullets: red core outline + filled centre, orange aura ring. - for b in m.bullets: - let (coreR, auraR) = bulletRadii(b.power) - setStrokeColor(RED) + # Danger corridor: the rotated rectangle from each bullet to the arena wall. + setStrokeColor(fromHex("#AAAAAA")) setStrokeWidth(1.0) - setFillColor(RED) - drawCircle(b.x, b.y, coreR) - fillCircle(b.x, b.y, 3.0) - setStrokeColor(fromHex("#FF8800")) - drawCircle(b.x, b.y, auraR) + for b in m.bullets: + let (_, auraR) = bulletRadii(b.power) + let cg = corridorGeom(b, m.arenaWidth, m.arenaHeight) + if cg.tMin == 0.0: continue + let wx = cg.bx + cg.dx * cg.tMin + let wy = cg.by + cg.dy * cg.tMin + drawPolygon(@[ + (cg.bx + cg.px * auraR, cg.by + cg.py * auraR), + (cg.bx - cg.px * auraR, cg.by - cg.py * auraR), + (wx - cg.px * auraR, wy - cg.py * auraR), + (wx + cg.px * auraR, wy + cg.py * auraR), + ]) - # Danger corridor: the rotated rectangle from each bullet to the arena wall. - setStrokeColor(fromHex("#AAAAAA")) - setStrokeWidth(1.0) - for b in m.bullets: - let (_, auraR) = bulletRadii(b.power) - let cg = corridorGeom(b, m.arenaWidth, m.arenaHeight) - if cg.tMin == 0.0: continue - let wx = cg.bx + cg.dx * cg.tMin - let wy = cg.by + cg.dy * cg.tMin - drawPolygon(@[ - (cg.bx + cg.px * auraR, cg.by + cg.py * auraR), - (cg.bx - cg.px * auraR, cg.by - cg.py * auraR), - (wx - cg.px * auraR, wy - cg.py * auraR), - (wx + cg.px * auraR, wy + cg.py * auraR), - ]) - - # Enemies: cyan body core, green aura ring. - setStrokeColor(fromHex("#00FFFF")) - setStrokeWidth(1.5) - for ei in ws.enemies: drawCircle(ei.x, ei.y, EnemyCoreRadius) - setStrokeColor(fromHex("#00CC00")) - setStrokeWidth(1.0) - for ei in ws.enemies: drawCircle(ei.x, ei.y, EnemyAuraRadius) - -proc drawDecision(m: TfilModule, ws: WorldState, - scoredTiles, safeTiles: seq[ScoredTile]) = - ## What the planner actually did: reachable hull, the tiles whose path is - ## blocked, the safe set, the tile it committed to, its own tile, and the - ## committed-target line. - if m.cachedHull.len >= 3: - let hullPts = block: - var s: seq[(float, float)] - for p in m.cachedHull: s.add (p.x, p.y) - s - setStrokeColor(fromHex("#336699")) + # Enemies: cyan body core, green aura ring. + setStrokeColor(fromHex("#00FFFF")) + setStrokeWidth(1.5) + for ei in ws.enemies: drawCircle(ei.x, ei.y, EnemyCoreRadius) + setStrokeColor(fromHex("#00CC00")) setStrokeWidth(1.0) - drawPolygon(hullPts) + for ei in ws.enemies: drawCircle(ei.x, ei.y, EnemyAuraRadius) - setStrokeColor(fromHex("#006666")) - setStrokeWidth(1.0) - for t in scoredTiles: - if t.pathMaxHeat <= PathDangerThreshold: continue - if t in safeTiles: continue ## promoted into the safe set: drawn cyan below - drawRectangle(m.marginX + t.col.float * GridSize, - m.marginY + t.row.float * GridSize, GridSize, GridSize) + proc drawDecision(m: TfilModule, ws: WorldState, + scoredTiles, safeTiles: seq[ScoredTile]) = + ## What the planner actually did: reachable hull, the tiles whose path is + ## blocked, the safe set, the tile it committed to, its own tile, and the + ## committed-target line. + if m.cachedHull.len >= 3: + let hullPts = block: + var s: seq[(float, float)] + for p in m.cachedHull: s.add (p.x, p.y) + s + setStrokeColor(fromHex("#336699")) + setStrokeWidth(1.0) + drawPolygon(hullPts) - setStrokeColor(fromHex("#00FFFF")) - setStrokeWidth(2.0) - for t in safeTiles: - drawRectangle(m.marginX + t.col.float * GridSize, - m.marginY + t.row.float * GridSize, GridSize, GridSize) + setStrokeColor(fromHex("#006666")) + setStrokeWidth(1.0) + for t in scoredTiles: + if t.pathMaxHeat <= PathDangerThreshold: continue + if t in safeTiles: continue ## promoted into the safe set: drawn cyan below + drawRectangle(m.marginX + t.col.float * GridSize, + m.marginY + t.row.float * GridSize, GridSize, GridSize) - let (chosenCol, chosenRow) = m.tileAt(m.commitTarget.x, m.commitTarget.y) - setStrokeColor(fromHex("#00FF00")) - setStrokeWidth(2.5) - drawRectangle(m.marginX + chosenCol.float * GridSize, - m.marginY + chosenRow.float * GridSize, GridSize, GridSize) + setStrokeColor(fromHex("#00FFFF")) + setStrokeWidth(2.0) + for t in safeTiles: + drawRectangle(m.marginX + t.col.float * GridSize, + m.marginY + t.row.float * GridSize, GridSize, GridSize) - let (botCol, botRow) = m.tileAt(ws.selfX, ws.selfY) - setStrokeColor(fromHex("#0088FF")) - setStrokeWidth(2.5) - drawRectangle(m.marginX + botCol.float * GridSize, - m.marginY + botRow.float * GridSize, GridSize, GridSize) + let (chosenCol, chosenRow) = m.tileAt(m.commitTarget.x, m.commitTarget.y) + setStrokeColor(fromHex("#00FF00")) + setStrokeWidth(2.5) + drawRectangle(m.marginX + chosenCol.float * GridSize, + m.marginY + chosenRow.float * GridSize, GridSize, GridSize) - setStrokeColor(fromHex("#00FF00")) - setStrokeWidth(1.5) - drawLine(ws.selfX, ws.selfY, m.commitTarget.x, m.commitTarget.y) + let (botCol, botRow) = m.tileAt(ws.selfX, ws.selfY) + setStrokeColor(fromHex("#0088FF")) + setStrokeWidth(2.5) + drawRectangle(m.marginX + botCol.float * GridSize, + m.marginY + botRow.float * GridSize, GridSize, GridSize) + + setStrokeColor(fromHex("#00FF00")) + setStrokeWidth(1.5) + drawLine(ws.selfX, ws.selfY, m.commitTarget.x, m.commitTarget.y) proc computeMove*(m: var TfilModule, ws: WorldState): MoveCommand = if m.cols == 0: diff --git a/DevControlBot_garage/README.md b/DevControlBot_garage/README.md index 37c846b..44bf3aa 100644 --- a/DevControlBot_garage/README.md +++ b/DevControlBot_garage/README.md @@ -175,7 +175,10 @@ in the bot's environment for local runs. ## Optional `.env` (a convenience for local runs only) -`DevControlBot/.env` is **optional**. If it is absent nothing happens: no error, +`DevControlBot/.env` is **optional**, and in this checkout it is empty (0 bytes): +it sets no `SERVER_URL` and no port at all. So no `.env` disabling or editing is +needed to run against the Tank Royale GUI, whose default port is 7654 — the same +as the API default below. If it is absent nothing happens: no error, no warning beyond one informational line, the run behaves exactly as before and the API defaults apply. It is not required, not generated, and not committed. @@ -276,9 +279,9 @@ not masked. Each mode prints its own short line, e.g. ``` -[start] Cannot connect to ws://localhost:4567: Connection refused +[start] Cannot connect to ws://localhost:7654: Connection refused [devcontrolbot] bot exited with code 1. -[devcontrolbot] No game server on ws://localhost:4567 (SERVER_URL). +[devcontrolbot] No game server on ws://localhost:7654 (SERVER_URL). [devcontrolbot] Start the Tank Royale server, or point SERVER_URL at a running one. ``` diff --git a/ModularBot_garage/.env.example b/ModularBot_garage/.env.example index 5dfd4bf..5749e2e 100644 --- a/ModularBot_garage/.env.example +++ b/ModularBot_garage/.env.example @@ -226,6 +226,8 @@ TR_RACK_TMSELECT=off # Tsetlin machine used as the shot selector TR_RACK_TMPATTERN=off # Tsetlin machine used as a pattern matcher TR_RACK_TMHORIZON=off # horizon Tsetlin automata gun TR_RACK_LEADGAIN=off # per-range-band learned lead-gain corrector +TR_RACK_KNOWLEDGE=off # learned angular-residual corrector on the lead forecast +TR_RACK_WAVEELM=off # online-ELM learned (x,y) offset on the analytic intercept # Give every named gun a fixed share of the turns instead of ranking them. # e.g. TR_RACK_SHARE=PATTERN:60%,HEADON:40% (GUN:weight, comma separated, # the % sign is optional). Empty = the ranking selector. GOTCHA: every gun you @@ -236,8 +238,9 @@ TR_RACK_SHARE= # Drop whole guns by rack id (comma separated, e.g. 16). Empty = keep them all. # Ids: 0 HEADON 1 LINEAR 2 TSETLIN 3 CIRCULAR 4 GUESSFACTOR 5 PATTERN # 6 WALLBOUNCE 7 ACCEL 8 STOPSHOT 9 DISPLACE 10 AVGLEAD 11 DECAYGF 12 KNN -# 13 TMSELECT 14 TMPATTERN 15 TMHORIZON 16 LEADGAIN. A disabled gun never even -# spawns a virtual bullet, so its fitness stays empty and it cannot be picked. +# 13 TMSELECT 14 TMPATTERN 15 TMHORIZON 16 LEADGAIN 17 KNOWLEDGE 18 WAVEELM. +# A disabled gun never even spawns a virtual bullet, so its fitness stays empty +# and it cannot be picked. GUN_RACK_DISABLE= # ── gun selector (which admitted gun fires this tick) ─────────────────────── @@ -667,6 +670,35 @@ TR_LEADGAIN_ADAPT=32 # NO-OP: the old adapt interval, no longer used TR_LEADGAIN_CALIB=512 # NO-OP: the old calibration interval, no longer used TR_LEADGAIN_SEED=20240921 # NO-OP: the old seed, no longer used +# KNOWLEDGE (rack id 17) — the learned additive angular residual on top of the +# self-consistent lead forecast. It answers only the aim angle: no power, no +# fire decision, no target picking. +TR_KNOWLEDGE_MEM= # path of the learned table; EMPTY = memory only + # (nothing is ever written to disk). Set to e.g. + # /tmp/gun_knowledge.bin to persist across battles. + +# WAVEELM (rack id 18) — the online-ELM gun. Analytic bullet/target intercept +# (self-consistent flight time) plus a learned (x, y) offset from a recursive +# least-squares ELM trained on the real-shot feedback. Admitted by the rack line +# above only; this gun has NO env knobs of its own — see below. +# +# OFF BY DEFAULT (shipped, like every gun except PATTERN). To enable: +# TR_RACK_WAVEELM=both (also: 1v1 | melee; aliases any/empty->both, +# single/lock->1v1, only1v1->1v1, +# multi/onlymelee->melee, none/disabled/disable->off) +# UNRECOGNISED value warns on stderr and falls back to `both` (GOTCHA: a typo +# ADDS the gun to the rack, it never turns it off). +# FORCED SHARE: TR_RACK_SHARE=WAVEELM:50,PATTERN:50 works, but only if +# WAVEELM is admitted above — a share naming an `off` gun is refused. +# NOTHING TO TUNE FROM HERE: WaveLambda (0.1 ridge), WaveRho (1.02 forgetting), +# WaveIters (20 intercept iterations), WaveMaxResidual, WaveMaxOffset, +# WaveTraceSlots and the ELM seed (42) are `const`s in +# common_libs/guns/waveelm.nim — changing them needs a REBUILD, not an env var. +# No TR_WAVEELME_* variable exists; there is no persisted memory path either +# (the ELM is rebuilt from scratch every battle, unlike KNOWLEDGE). +# Per-shot behaviour for every admitted gun is logged by the shared stats writer +# (GUN_STATS_PATH below). + # PATTERN — the shipped gun, the only one the rack admits. TR_PATTERN_LEN=10 # ticks of movement history used as the search key TR_PATTERN_DEPTH=500 # how far back the history scan may reach diff --git a/ModularBot_garage/src/ModularBot.nim b/ModularBot_garage/src/ModularBot.nim index 47c06cb..7922d7b 100644 --- a/ModularBot_garage/src/ModularBot.nim +++ b/ModularBot_garage/src/ModularBot.nim @@ -1,5 +1,5 @@ ## ModularBot — plugin gun architecture tracer bullet. -## Guns: HeadOnGun (0), LinearGun (1), TsetlinGun (2), CircularGun (3), GFGun (4), PatternMatcherGun (5), WallBounceGun (6), AccelGun (7), StopShotGun (8), DisplacementGun (9), AveragedLeadGun (10), DecayGFGun (11), KNNGun (12), TmSelectorGun (13), TmPatternGun (14), TmHorizonGun (15), LeadGainGun (16), BitbrainNetGun (17) via GunHarness. +## Guns: HeadOnGun (0), LinearGun (1), TsetlinGun (2), CircularGun (3), GFGun (4), PatternMatcherGun (5), WallBounceGun (6), AccelGun (7), StopShotGun (8), DisplacementGun (9), AveragedLeadGun (10), DecayGFGun (11), KNNGun (12), TmSelectorGun (13), TmPatternGun (14), TmHorizonGun (15), LeadGainGun (16), KnowledgeGun (17), WaveElmGun (18) via GunHarness. ## Radar: RadarLockModule (1v1) / AdaptiveMeleeRadarModule (2+ enemies), auto-switched per tick. ## Movement: OscillatorModule (perpendicular strafing). @@ -31,6 +31,8 @@ import guns/tm_selector import guns/tm_pattern import guns/tm_horizon import guns/lead_gain +import guns/gun_knowledge +import guns/waveelm import movements/phantom_meteor import movements/rammer import movements/ram_decision @@ -158,7 +160,7 @@ let ResultLog* = block: let v = getEnv("TR_RESULT_LOG", "1").strip().toLowerAscii() not (v == "0" or v == "false" or v == "no" or v == "off") -const GunNames = ["HeadOn", "Linear", "Tsetlin", "Circular", "GuessFactor", "Pattern", "WallBounce", "Accel", "StopShot", "Displace", "AvgLead", "DecayGF", "KNN", "TMSelect", "TMPattern", "TMHorizon", "LeadGain"] +const GunNames = ["HeadOn", "Linear", "Tsetlin", "Circular", "GuessFactor", "Pattern", "WallBounce", "Accel", "StopShot", "Displace", "AvgLead", "DecayGF", "KNN", "TMSelect", "TMPattern", "TMHorizon", "LeadGain", "Knowledge", "WaveElm"] ## Rack id of the new TM pattern gun. It defaults to `TR_RACK_TMPATTERN=off`; ## unlike the other guns, its virtual-bullet spawn is gated on rack admission @@ -182,6 +184,25 @@ const TmHorizonId = 15 ## (backward compatibility; see `gun_harness/selector`). const LeadGainId = 16 +## Rack id of KNOWLEDGE, the learned additive angular residual on top of the +## self-consistent lead forecast (`common_libs/guns/gun_knowledge.nim`). It is +## APPENDED at the end of the rack, so no existing id moved and every +## `tools/ab/arms_*.txt` config still addresses the gun it was written for. It +## ships `TR_RACK_KNOWLEDGE=off`, like every gun except Pattern, and its +## virtual-bullet spawn is gated on rack admission (`vBulletAdmitted`), so the +## shipped default never spawns it and the shared tracker ring head — hence every +## other gun's learning order — is byte-for-byte unchanged. Unlike the rest of +## the rack it may also touch disk (`TR_KNOWLEDGE_MEM`), which is another reason +## it stays out of the default rack. +const KnowledgeId = 17 + +## Rack id of WAVEELM, the online-ELM gun (`common_libs/guns/waveelm.nim`): an +## analytic intercept plus a learned per-tick (x, y) offset trained by an +## online sequential ELM on its OWN virtual-bullet feedback. APPENDED at the end +## of the rack, so no existing id moved. Ships `TR_RACK_WAVEELM=off`, like every +## gun except Pattern, and its virtual-bullet spawn is gated on rack admission. +const WaveElmId = 18 + ## ── virtual-bullet debug overlay (TR_VBULLET_DEBUG*) ─────────────────────── ## OFF by default: the shipped bot draws nothing. When on, the tracker's ## virtual bullets are overlaid so the training signal the selector learns @@ -254,6 +275,8 @@ type tmPattern: TmPatternGun tmHorizon: TmHorizonGun leadGain: LeadGainGun + knowledge: KnowledgeGun + waveElm: WaveElmGun mover: TFILModule ringMover: TFILRingModule strafeMover: StrafeModule @@ -1316,6 +1339,8 @@ method run*(bot: ModularBot) = var tmpPreds: array[len(PowerBins), GunPrediction] var tmhPreds: array[len(PowerBins), GunPrediction] var lgPreds: array[len(PowerBins), GunPrediction] + var gkPreds: array[len(PowerBins), GunPrediction] + var wePreds: array[len(PowerBins), GunPrediction] # ── TR_VBULLET_ADMIT_ONLY gate ────────────────────────────────────── # Rack membership used to filter only SELECTION, so every unselected gun # still ran predict()+spawnBullets() each tick to feed a fitness table the @@ -1332,7 +1357,8 @@ method run*(bot: ModularBot) = admit[gi] = ModuleVBullets and vBulletAdmitted(gi, bot.rackMode, ActiveRackMembership, VBulletAdmitOnly or gi == TmPatternId or - gi == TmHorizonId or gi == LeadGainId) + gi == TmHorizonId or gi == LeadGainId or + gi == KnowledgeId or gi == WaveElmId) for i in 0.. 0: emit("legacy TR_BITBRAIN_* aliases honoured", "yes", "legacy") else: emit("legacy TR_BITBRAIN_* aliases honoured", "no", "default") + # ── KNOWLEDGE, the learned residual gun (rack id 17) ────────────────────── + # One knob: where its learned table lives. Unset = memory only, i.e. nothing + # is ever written to disk. The table is allocated on FIRST USE, so this line + # reports the configured path, not a live table. + let gkMem = getEnv(GK_MEM_ENV, "").strip() + emit("TR_KNOWLEDGE_MEM", if gkMem.len > 0: gkMem else: "(unset -> memory only)", + sourceOf(GK_MEM_ENV)) + # ── Pattern match-shape + radial knobs ──────────────────────────────────── # These are resolved lazily inside `predict` (which has not run at boot), so # unless something already forced them we report the raw env value and say so. @@ -629,6 +638,7 @@ proc knownEnvNames*(): seq[string] = TMH_SHIFT_ENV, TMH_BIG_MULT_ENV, TMH_LOG_ENV, TMH_RESET_ON_TARGET_ENV, TMH_WINDOW_ENV, TMH_RESET_DROP_ENV, TMH_NSTATES_ENV, TMH_ACCURVE_ENV, TMH_RETRAIN_EVERY_ENV, TMH_EPOCHS_ENV, + GK_MEM_ENV, LG_MEM_ENV, LG_GAINS_ENV, LG_N_ENV, LG_NADE_ENV, LG_RANGE_ENV, LG_LOG_ENV, LG_MIN_OBS_ENV, LG_WARMUP_ENV, LG_ADAPT_ENV, LG_CALIB_ENV, LG_DECAY_ENV, LG_DECAY_FRAC_ENV, LG_SEED_ENV, LG_RESET_ON_TARGET_ENV, diff --git a/ModularBot_garage/src/vbullet_draw.nim b/ModularBot_garage/src/vbullet_draw.nim index 32ccc6e..cf988ad 100644 --- a/ModularBot_garage/src/vbullet_draw.nim +++ b/ModularBot_garage/src/vbullet_draw.nim @@ -100,6 +100,8 @@ proc gunColors*(gunId: int): tuple[turret, bullet: string] = of 14: ("#AAFF00", "#CCFF66") # TMPattern — lime of 15: ("#00AAFF", "#66CCFF") # TMHorizon — sky of 16: ("#FF1493", "#FF69B4") # LEADGAIN — deep pink + of 17: ("#8B4513", "#D2691E") # KNOWLEDGE — saddle brown + of 18: ("#7B68EE", "#9370DB") # WAVEELM — medium slate blue else: ("#FFFFFF", "#FFFFFF") proc gunTurretColor*(gunId: int): string = gunColors(gunId).turret diff --git a/PPO_Bot_garage/src/PPO_Bot/enemy_tracker.nim b/PPO_Bot_garage/src/PPO_Bot/enemy_tracker.nim index 0380625..da55b04 100644 --- a/PPO_Bot_garage/src/PPO_Bot/enemy_tracker.nim +++ b/PPO_Bot_garage/src/PPO_Bot/enemy_tracker.nim @@ -1,7 +1,8 @@ ## Enemy tracker — deterministic radar lock + dead reckoning for PPO_Bot. -## No bot API imports; takes plain floats. +## Takes plain floats; only the SDK radar constants are used. import std/math +import tankroyale_botapi/constants type EnemyState* = object @@ -75,14 +76,14 @@ proc normalizeRelative(angle: float64): float64 {.inline.} = proc getRadarTurnRate*(tracker: var EnemyTracker; botX, botY, botDirection, radarDirection: float64): float64 = ## Returns radar turn rate (degrees/tick, positive = right). - ## Before contact: full 45° sweep. + ## Before contact: full-speed sweep. ## After contact: lock with overshoot; widen if stale. if not tracker.hasContact: - return 45.0 + return MAX_RADAR_TURN_RATE if tracker.current.ticksSinceLastScan >= 8: # Lost lock — widen sweep - return 45.0 + return MAX_RADAR_TURN_RATE # Bearing from radar to enemy. # Tank Royale radar directions use standard math convention (0=east, CCW+). @@ -94,7 +95,7 @@ proc getRadarTurnRate*(tracker: var EnemyTracker; # Width Lock: overshoot proportional to arctan(36 / distance) let distance = sqrt(dx * dx + dy * dy) - let extraTurn = min(arctan(36.0 / distance) * 180.0 / PI, 45.0) + let extraTurn = min(arctan(36.0 / distance) * 180.0 / PI, MAX_RADAR_TURN_RATE) if radarTurn < 0.0: radarTurn -= extraTurn else: radarTurn += extraTurn - result = radarTurn.clamp(-45.0, 45.0) + result = radarTurn.clamp(-MAX_RADAR_TURN_RATE, MAX_RADAR_TURN_RATE) diff --git a/common_libs/gun_harness/selector.nim b/common_libs/gun_harness/selector.nim index 77025ec..efdff55 100644 --- a/common_libs/gun_harness/selector.nim +++ b/common_libs/gun_harness/selector.nim @@ -22,6 +22,10 @@ import virtual_bullets # TR_RACK_KNN=off -> removed from both racks # TR_RACK_TMPATTERN=off (shipped default for the new TM pattern gun) # TR_RACK_LEADGAIN=both -> the per-range-band lead-gain corrector (id 16) +# TR_RACK_KNOWLEDGE=both -> the learned residual gun (id 17); it is a +# persistence-carrying gun, so the shipped default +# is `off` and it only ever touches disk when a +# caller admits it # # SHIPPED DEFAULT IS `onlyPattern`: Pattern (id 5) is admitted in both racks and # every other gun is `off`. This is a deliberate, measured decision, not a @@ -45,10 +49,11 @@ import virtual_bullets # transition the radar uses. const - RackGunNames*: array[17, string] = [ + RackGunNames*: array[19, string] = [ "HEADON", "LINEAR", "TSETLIN", "CIRCULAR", "GUESSFACTOR", "PATTERN", "WALLBOUNCE", "ACCEL", "STOPSHOT", "DISPLACE", "AVGLEAD", "DECAYGF", - "KNN", "TMSELECT", "TMPATTERN", "TMHORIZON", "LEADGAIN"] + "KNN", "TMSELECT", "TMPATTERN", "TMHORIZON", "LEADGAIN", "KNOWLEDGE", + "WAVEELM"] RackEnvPrefix* = "TR_RACK_" ## THE rack size, derived from `RackGunNames`. Every per-gun-indexed array and ## loop in the bot and in the harness MUST be sized with this, never with a @@ -74,7 +79,7 @@ const ## it never spawns a virtual bullet unless explicitly enabled, so the shared ## VirtualTracker ring head — and every other gun's learning order — is ## unchanged. - DefaultRackMembership*: array[17, RackMembership] = [ + DefaultRackMembership*: array[19, RackMembership] = [ rmOff, # 0 HEADON — off (measured: worst over-selected gun) rmOff, # 1 LINEAR — off rmOff, # 2 TSETLIN — off @@ -91,7 +96,12 @@ const rmOff, # 13 TMSELECT — off rmOff, # 14 TMPATTERN — off (already shipped off; TM pattern gun) rmOff, # 15 TMHORIZON — off (horizon-based TM corrector; expected to lose) - rmOff] # 16 LEADGAIN — off (per-range-band lead-gain corrector) + rmOff, # 16 LEADGAIN — off (per-range-band lead-gain corrector) + rmOff, # 17 KNOWLEDGE — off (learned additive angular residual on top of + # the self-consistent lead forecast; see + # `guns/gun_knowledge.nim`) + rmOff] # 18 WAVEELM — off (online-ELM learned offset on the analytic + # intercept; see `guns/waveelm.nim`) ## NOTE: the table is registered in the SAME commit as the gun id and the live ## wiring, so `TR_RACK_LEADGAIN=both` (or the legacy `TR_RACK_BITBRAIN=both`) ## are the ONLY things that admit that gun, and an unset environment is diff --git a/common_libs/tests/test_env_report.nim b/common_libs/tests/test_env_report.nim index 9f75837..3ceac1e 100644 --- a/common_libs/tests/test_env_report.nim +++ b/common_libs/tests/test_env_report.nim @@ -73,7 +73,7 @@ proc testKnownNames() = check "known set has no duplicates", known.len == s.len check "known set only holds TR_*/GUN_* names", known.allIt(it.startsWith("TR_") or it.startsWith("GUN_")) - check "known set covers all 17 rack names", + check "known set covers every rack name (width derived, not a literal)", RackGunNames.allIt((RackEnvPrefix & it) in s) for name in ["TR_MOVEMENT", "TR_POWER_ENERGY_MIN", "TR_TMHORIZON_NSTATES", "GUN_VBULLET_METRIC", "TR_ENV_REPORT", "GUN_SELECTOR_SEED", diff --git a/common_libs/tests/test_lead_gain_legacy.nim b/common_libs/tests/test_lead_gain_legacy.nim index ca998bf..50d7df5 100644 --- a/common_libs/tests/test_lead_gain_legacy.nim +++ b/common_libs/tests/test_lead_gain_legacy.nim @@ -164,8 +164,8 @@ proc testDefaultParity() = let want = if i == 5: rmBoth else: rmOff if m[i] != want: onlyPattern = false check "parity: a clean env still loads the shipped onlyPattern rack", onlyPattern - check "parity: the rack is still 17 guns at id 16 = LEADGAIN", - RackGunNames.len == 17 and RackGunNames[LeadGainId] == "LEADGAIN" + check "parity: the rack is still one entry per gun and id 16 = LEADGAIN", + RackGunNames.len == NumRackGuns and RackGunNames[LeadGainId] == "LEADGAIN" var g = initLeadGainGun() check "parity: a clean env resolves the shipped candidate set", g.cands == @[0.0, 0.25, 0.5, 0.75, 1.0] and g.memMode == lgPerRound diff --git a/common_libs/tests/test_rack_membership.nim b/common_libs/tests/test_rack_membership.nim index 036e63e..54bbbe0 100644 --- a/common_libs/tests/test_rack_membership.nim +++ b/common_libs/tests/test_rack_membership.nim @@ -158,14 +158,14 @@ proc testDefaultsOnlyPattern() = DefaultRackMembership[12] == rmOff and DefaultRackMembership[13] == rmOff and DefaultRackMembership[14] == rmOff check "defaults: the default rack admits ONLY Pattern in 1v1", - admittedGuns(17, rm1v1, DefaultRackMembership) == @[PatternId] + admittedGuns(NumRackGuns, rm1v1, DefaultRackMembership) == @[PatternId] check "defaults: the default rack admits ONLY Pattern in melee", - admittedGuns(17, rmMelee, DefaultRackMembership) == @[PatternId] + admittedGuns(NumRackGuns, rmMelee, DefaultRackMembership) == @[PatternId] let loaded = loadRackMembership() check "defaults: with a clean environment loadRackMembership() == shipped table", loaded == DefaultRackMembership - check "defaults: RackGunNames covers the shipped 17-gun rack", - RackGunNames.len == 17 and DefaultRackMembership.len == 17 + check "defaults: RackGunNames covers the shipped rack (width derived, not a literal)", + RackGunNames.len == NumRackGuns and DefaultRackMembership.len == NumRackGuns proc testFloorRespectsAdmission() = ## The FLOOR path (`bestRate <= 0` or below the floor rate) historically fell @@ -213,14 +213,15 @@ proc testRevertOverrideRestoresFullRack() = if m[i] != want: full = false check "revert: the documented one-liner restores the all-`both` full rack", full check "revert: 1v1 rack admits every gun again (TMPATTERN excluded)", - admittedGuns(17, rm1v1, m) == @[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16] + admittedGuns(NumRackGuns, rm1v1, m) == + @[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17, 18] clearRackEnv() # The ADE+SBC gun (old rack id 17) is RETIRED, so `TR_RACK_BITBRAIN` is now # unambiguously LEADGAIN's old name: alone, it admits LEADGAIN and nothing else. putEnv("TR_RACK_BITBRAIN", "both") let mLegacy = loadRackMembership() check "revert: the legacy TR_RACK_BITBRAIN alone selects LEADGAIN (16) only", - mLegacy[16] == rmBoth and admittedGuns(17, rm1v1, mLegacy) == @[5, 16] + mLegacy[16] == rmBoth and admittedGuns(NumRackGuns, rm1v1, mLegacy) == @[5, 16] clearRackEnv() proc testEnvOverrides() = diff --git a/common_libs/tests/test_rack_stat_width.nim b/common_libs/tests/test_rack_stat_width.nim index ad7cd52..37fdeed 100644 --- a/common_libs/tests/test_rack_stat_width.nim +++ b/common_libs/tests/test_rack_stat_width.nim @@ -14,8 +14,9 @@ ## The fix derives every gun-indexed width from `NumRackGuns` (== `len(RackGunNames)`). ## This test is the guard that would have caught it: ## -## A. rack table — `NumRackGuns` is 17, 17 DISTINCT names, and the -## membership table and the legacy alias target are in range; +## A. rack table — `NumRackGuns` is one entry per gun, DISTINCT names, and +## the membership table and the legacy alias target are in +## range; ## B. source shape — `ModularBot.nim` contains NO literal width/loop bound ## narrower than `NumRackGuns` for the gun-indexed ## accounting, and sizes them with `NumRackGuns`; @@ -26,10 +27,12 @@ ## D. live (opt-in) — with a rack that admits ONLY the newest id, the bot ## selects it, fires and lands hits (skipped without JARs). ## -## The ADE+SBC gun (rack id 17) was later RETIRED, so the rack is back to 17 and -## the newest id is LEADGAIN (16). The guard is unchanged in shape and in -## strength: C3 now proves the fix survives a rack that grows again, which is -## the general form of the bug that shipped. +## The ADE+SBC gun (rack id 17) was later RETIRED, so the rack went back to 17 +## with LEADGAIN (16) as the newest id. KNOWLEDGE now occupies id 17 again, so +## the newest id is asserted as a DERIVED value (`NumRackGuns - 1`), never a +## literal: the guard is unchanged in shape and in strength, and C3 still proves +## the fix survives a rack that grows again, which is the general form of the bug +## that shipped. ## ## Run: nim c -r common_libs/tests/test_rack_stat_width.nim ## Live: TR_SERVER_JAR=... TR_BATTLE_RUNNER=... nim c -r common_libs/tests/test_rack_stat_width.nim @@ -47,7 +50,7 @@ const adversaryDir = repoRoot / "common_libs" / "test_framework" / "adversaries" / "SittingDuck" statsPath = "/tmp/rack_stat_width_stats.jsonl" PatternId = 5 - NewestId = NumRackGuns - 1 ## 16 (LEADGAIN), the newest rack id + NewestId = NumRackGuns - 1 ## the newest rack id (KNOWLEDGE) LegacyLeadGainId = 16 var failures = 0 @@ -59,7 +62,7 @@ proc check(name: string, ok: bool) = proc testRackTable() = check "A1: NumRackGuns is derived from RackGunNames", - NumRackGuns == RackGunNames.len and NumRackGuns == 17 + NumRackGuns == RackGunNames.len and NumRackGuns > 0 check "A2: rack membership table has one entry per gun", DefaultRackMembership.len == NumRackGuns var seen = initTable[string, bool]() @@ -176,9 +179,9 @@ proc testAccounting() = check "C3: a rack one gun WIDER is still fully covered by the NumRackGuns width", grownOk and grown[NumRackGuns] == 1 - # The legacy namespace: TR_RACK_BITBRAIN is now unambiguously LEADGAIN's old + # The legacy namespace: TR_RACK_BITBRAIN is unambiguously LEADGAIN's old # name (the ADE+SBC gun that briefly owned it was retired), so it always - # admits LEADGAIN (16) — the newest id — and nothing else. + # admits LEADGAIN (16) — and nothing else, not the gun that reused id 17. for n in RackGunNames: delEnv("TR_RACK_" & n) delEnv("TR_BITBRAIN_NET") putEnv("TR_RACK_BITBRAIN", "both") diff --git a/common_libs/tests/test_tm_pattern_registration.nim b/common_libs/tests/test_tm_pattern_registration.nim index c351c1b..958f9f4 100644 --- a/common_libs/tests/test_tm_pattern_registration.nim +++ b/common_libs/tests/test_tm_pattern_registration.nim @@ -62,7 +62,8 @@ proc seedOldRack(t: var VirtualTracker, targetId: int) = # ── registration table ──────────────────────────────────────────────────────── proc testTable() = - check "rack: RackGunNames has 17 entries", RackGunNames.len == 17 + check "rack: RackGunNames has one entry per rack gun (width derived)", + RackGunNames.len == NumRackGuns check "rack: the new gun is named TMPATTERN at id 14", RackGunNames[TmPatternId] == "TMPATTERN" check "rack: the new gun defaults to `off`", diff --git a/docs/env_reference.md b/docs/env_reference.md index c4090e2..26cebfa 100644 --- a/docs/env_reference.md +++ b/docs/env_reference.md @@ -399,14 +399,14 @@ tank. | variable | default | what it does | |---|---|---| -| `TR_RACK_` | `PATTERN=both`, all other 15 guns `off` | membership: `both` \| `1v1` \| `melee` \| `off` | +| `TR_RACK_` | `PATTERN=both`, all other 17 guns `off` | membership: `both` \| `1v1` \| `melee` \| `off` | | `GUN_RACK_DISABLE` | empty | comma-separated gun **ids** to remove entirely (older mechanism; the gun never even spawns virtual bullets) | | `GUN_STATS_PATH` | `/tmp/gun_stats.jsonl` | where the per-round per-gun stats are written | | `GUN_SHOTLOG_PATH` | `/tmp/shot_log.jsonl` | where the per-shot JSONL is written | -`` names (ids 0-15, `selector.nim:52`): +`` names (ids 0-17, `selector.nim:RackGunNames`): `HEADON LINEAR TSETLIN CIRCULAR GUESSFACTOR PATTERN WALLBOUNCE ACCEL STOPSHOT -DISPLACE AVGLEAD DECAYGF KNN TMSELECT TMPATTERN TMHORIZON`. +DISPLACE AVGLEAD DECAYGF KNN TMSELECT TMPATTERN TMHORIZON LEADGAIN KNOWLEDGE`. Shipped default membership (`selector.nim:DefaultRackMembership`): @@ -420,6 +420,8 @@ Shipped default membership (`selector.nim:DefaultRackMembership`): | **PATTERN** | **both** | TMSELECT | off | | WALLBOUNCE | off | TMPATTERN | off | | ACCEL | off | TMHORIZON | off | +| STOPSHOT | off | LEADGAIN | off | +| KNOWLEDGE | off | | | `TR_RACK_` accepts aliases: `both`/`any`/empty → both; `1v1`/`single`/`lock` → 1v1; `melee`/`multi` → melee; @@ -429,6 +431,10 @@ to `both`** (`selector.nim:parseRackMembership`). The `1v1`/`melee` split is driven by **server truth**, `getEnemyCount()`: `== 1` → 1v1 rack, `> 1` → melee rack (`virtual_bullets.rackMode`). +| variable | default | what it does | +|---|---|---| +| `TR_KNOWLEDGE_MEM` | empty (memory only) | path of the learned table `KNOWLEDGE` (id 17) loads at the first round boundary and re-saves (atomically, after a prune) at every boundary. Unset = nothing is ever written to disk. | + **Empty-set fallback:** if every gun is filtered out for a mode, the *selector* falls back to the **full rack** so it can never end up with no gun (`admittedGuns`, `virtual_bullets.nim`). Note this fallback is on *selection*; diff --git a/docs/research/goto-controller-algorithm.md b/docs/research/goto-controller-algorithm.md index 8ff8de0..f00c4d1 100644 --- a/docs/research/goto-controller-algorithm.md +++ b/docs/research/goto-controller-algorithm.md @@ -48,8 +48,20 @@ is smooth but limited to 4°/tick at top speed. ### Coordinate system -North = 0°, clockwise. `directionTo` in `utils.nim` returns a bearing in -`[0, 360)`. `bearingTo` returns a signed relative bearing in `(-180, 180]`. +East = 0°, North = 90°, positive angles increase counter-clockwise (Y increases +upward, so the arena's bottom edge is Y = 0). `directionTo` in `utils.nim` +returns a bearing in `[0, 360)`. `bearingTo` returns a signed relative bearing in +`(-180, 180]`. + +> **Note — the SDK's own doc comments are wrong here.** `bot.nim:183/187/191`, +> `utils.nim:68` and the examples at `utils.nim:159-161` and `~197` all claim +> "0 = North, 90 = East". The **implementation is authoritative**, not the +> comments: `utils.nim:162` computes +> `normalizeAbsoluteAngle(180.0 * arctan2(toY - fromY, toX - fromX) / PI)`, i.e. +> plain `arctan2(dy, dx)`, and `bot.nim:178` puts the arena's bottom edge at +> `Y = 0`. Running the SDK's own `directionTo` (robocode_tankroyale_botapi +> 1.0.7) returns `0.0` for East and `90.0` for North, and `bearingTo` agrees. +> Do not "fix" this section back to the commented convention. ---