## gun_knowledge.nim — GUNK: a learned additive ANGULAR RESIDUAL on top of the ## SELF-CONSISTENT LEAD FORECAST. It answers exactly ONE question: ## ## "given a tracked enemy, which ABSOLUTE GUN DIRECTION should I aim at?" ## ## It does NOT decide whether firing is possible, does NOT pick fire power and ## does NOT move. Those live in `movement_harness/fire_tracker`, ## `gun_harness/virtual_bullets` (PowerBins = [1.0, 1.5, 2.0, 3.0]) and the ## movement modules. The caller picks the power, then hands it back to us as ## `GkFeatures.power`. ## ## ── WHY THE BASE IS `lead_forecast.forecastLinear`, NOT A CLOSED FORM ───────── ## The base aim is a 5-iteration FIXED POINT on the flight time ## (`t = |predictedPos(t) - self| / bulletSpeed`, the same fixed point ## `circular.nim` uses), taken verbatim from `guns/lead_forecast`: ## ## let d0 = hypot(enemyX - selfX, enemyY - selfY) ## var t = d0 / bulletSpeed ## for _ in 0..4: ## ex = enemyX + cos(hr) * enemySpeed * t ## ey = enemyY + sin(hr) * enemySpeed * t ## t = hypot(ex - selfX, ey - selfY) / bulletSpeed ## ## The single-step closed form this module USED to ship — one `dist / bulletSpeed` ## evaluated with the CURRENT enemy position — was MEASURED TO FAIL, and ## `lead_forecast`'s header records how: the virtual-bullet metric resolves a ## bullet when its travel distance reaches the distance to its aim point, so an ## aim point placed at the FIRE-time distance resolves at the wrong radius ## whenever the target moved radially during the flight and misses even with a ## perfect angle. Measured: the whole GuessFactor family scored ~0% on the ## circular / wall-bounce / random-walk fixtures while the self-consistent ## forecast scored 40-100%, and the Linear gun scored 87% (p3.0 = 63/100) on ## the constant-velocity fixture where the fixed point scores 100%. ## ## `closedFormLead` is KEPT ONLY as a cross-check / teaching artefact for the ## failure above (`testClosedFormCrossCheck` in the test file labels it as ## such). It is NOT the production path and MUST NOT be wired back in. ## ## The base is an ABSOLUTE world-frame bearing, straight out of the forecast: ## `aim = radToDeg(forecastLinear(...).bearing)`. It is NOT re-referenced to the ## gun, and the caller's own heading is never mixed in: the caller turns the ## turret by `aimAngle(self, pred) - getGunDirection()` from an ABSOLUTE ## prediction point (`ModularBot.nim:1501-1503`), so the module must answer in ## the same absolute frame. Adding an absolute heading to a relative lead term ## (the old `gunHeading + (baseBearing - los)`) induced an error of ## `gunHeading - los` and aimed ~180 deg backwards whenever the bot faced away. ## The frame invariant is pinned by `testAimFrameInvariant`. ## ## ── THE RADIUS OF THE ANSWER IS THE FORECAST DISTANCE ─────────────────────── ## `aim` returns a BEARING and `predict` returns a POINT: `self + dist * ## (cos, sin)(aim)`, where `dist` is `forecastLinear(...).dist` -- the distance ## from the shooter to the PREDICTED enemy position, NOT the current line-of- ## sight distance. The two are the same only for a stationary target. The ## forecast is a self-consistent fixed point precisely so that the radius the ## bullet is resolved at is the radius it actually flies, and resolving it at ## the fire-time distance instead is the failure `lead_forecast`'s header ## records for the single-step closed form. `GkAim.dist` carries it, pinned by ## `testForecastDistance`. ## ## ── WHY A RESIDUAL ─────────────────────────────────────────────────────────── ## The forecast assumes the enemy holds speed AND heading for the whole flight. ## That is false exactly when the enemy turns, accelerates, hugs a wall or ## ranges rather than orbits. What is left over is a small signed angle, so that ## is the only thing we learn: `aim = base + residual`. Every key feature below ## (turn / speed-trend / space / heat / radial fraction) expresses UNCERTAINTY ## about the constant-velocity assumption, not geometry, which is why none of ## them appear in the base — they only partition the table. ## ## AND THE TABLE HAS TO BE ALLOWED TO BE WRONG ONCE. A residual that is never ## tried is never measured, and a row whose every shot was filed at the null can ## only ever answer 0 deg. So an under-sampled row explores (see EXPLORATION in ## the constants) and a sampled one does not. ## ## ── THE 15-BIT KEY (6 features, 3840 rows) ────────────────────────────────── ## The key was 19 bits over 8 features (524288 rows, 35 MiB) and was sparse by ## construction: the truth is a product of small bin counts, so most of the table ## could never be reached. It is now 6 features / 15 bits / **3840 rows** ## (5*3*4*4*4*4 = 3840, well inside 2^15 = 32768), packed MIXED-RADIX so the ## table is dense: see `keyOf`. Feature sources are all pre-existing: ## distance band from `lead_gain.lgBandOf` (the ruler's 5 bands), enemy space ## from `spaceOf` below, turning and speed trend from this module's own scan ## track, gun heat from the caller, and the radial fraction from ## `lead_forecast.radialFrac` (VelWindow 16, RadialWindow 32). ## ## Turn and speed-trend each carry a FOURTH value, `gkUnknown`. Scans are not ## every tick (the radar arc is 36 deg wide, MAX_EVENTS_AGE = 2 drops stale ## events, radar_lock makes the interval irregular). A gap over GK_GAP_MAX ## means "no observation"; folding that into straight/constant would make ONE ## row blend two populations (genuinely-straight vs nothing-observed) into an ## unweighted mixture with nothing reporting it. `unknownCount` / ## `unknownRate` make the frequency measurable instead of guessed. ## ## MEASURED, NOT GUESSED. Across 184 recorded round-battles: 118,253 alive ## ticks and 24,883 radar scans, i.e. a mean inter-scan gap of 4.75 ticks. The ## limit was originally GK_GAP_MAX = 2, which put at least 57.9% of every ## observation into `gkUnknown` (per-round median bound: only 33.8% known), ## killed two of the six key features and left 25% of the 3840 rows ## unreachable. GK_GAP_MAX is therefore 6, which covers the measured mean of ## 4.75. ## ## HONEST CONSEQUENCE OF 6. When the gap is greater than 1 tick the derived turn ## rate and speed trend are GAP-AVERAGES over the interval, not instantaneous ## rates: `normalize180(dir[0] - dir[1]) / gap` is the mean turn rate over ## those `gap` ticks, and it cannot tell "turned 30 deg in one tick" from ## "turned 5 deg in each of six". That is a legitimate average of a real ## quantity, but it is an average, and the dead bands (GK_TURN_DEAD 2 deg/tick, ## GK_TREND_DEAD 0.05 px/tick) are applied to the AVERAGE. The fraction of ## derivations that actually used a gap over 1 tick is measured at runtime by ## `longGapCount` / `longGapRate`, next to `unknownRate`, so the amount of ## averaging is never silent. ## ## Coordinate/angle convention: 0° = East, CCW positive (Tank Royale ## standard), matching `gun_harness/gun_interface` and `guns/lead_forecast`. ## `GkFeatures` is in the WORLD frame (it is built from the same `WorldState` ## every gun receives); the answer is an absolute world bearing in the caller's ## own frame. It reuses `bulletSpeed` ## (20 - 3*power) from `gun_harness/gun_interface` rather than repeating the ## server formula. ## ## Run: nim c -r --path:common_libs common_libs/tests/test_gun_knowledge.nim import std/[algorithm, math, os, strutils, tables] import gun_harness/gun_interface # WorldState, bulletSpeed() == 20 - 3*power import gun_harness/virtual_bullets # PowerBins: one pending aim per power bin import guns/lead_forecast # forecastLinear, radialFrac, RadialWindow import guns/lead_gain # lgBandOf / LG_BAND_LO / LG_BAND_HI export lgBandOf, LG_BAND_LO, LG_BAND_HI # the key's distance band, re-exported const # ── the 13-bit situation key (6 features) ─────────────────────────────────── GK_DIST_BITS* = 3 ## distance band, 5 bands (lead_gain.lgBandOf) GK_SPACE_BITS* = 2 ## near one wall / in a corner / free GK_TURN_BITS* = 3 ## straight / right / left / UNKNOWN GK_TREND_BITS* = 3 ## accelerating / constant / decelerating / UNKNOWN GK_HEAT_BITS* = 2 ## gun heat, 4 quarters of [0,1] GK_RADIAL_BITS* = 2 ## radialFrac, 4 quarters of [0,1] GK_KEY_BITS* = 15 ## informational: 2^15 = 32768 > GK_NKEYS GK_NKEYS* = 3840 ## 5*3*4*4*4*4 — the DENSE, reachable row count # ── residual bins ─────────────────────────────────────────────────────────── # THE NULL RESIDUAL IS BIN 0 AND IT IS THE CENTRE OF THE TABLE. A row that # has learned nothing must answer "no correction" (0.0 deg), so the bin a # no-correction observation is filed under HAS to be the 0.0 deg bin. It used # not to be: with the uniform [-30,+30] tiling, bin 0 sat at -29.06 deg, so # every below-threshold shot was filed (via clamp(-1, 0, 31) = 0) into a # 29 deg correction, and `bestResidual`'s argmax then returned that bin # forever. MEASURED, FAITHFUL regime, fresh table, 450+ band: aim rms 36.46 # deg / hit rate 3.46% against a bare forecastLinear's 21.46 deg / 6.97%. # # The layout (32 centres, exact inverses both ways, GK_RES_WIDTH = 60/32): # bin 0 0.000 <- the NULL residual # bins 1..16 -GK_RES_WIDTH * b -> -1.875 .. -30.000 # bins 17..31 +GK_RES_POS_WIDTH * (b - 16) -> +2.000 .. +30.000 # 32 is EVEN, so with one bin on 0 there cannot be 15 pairs around it: 16 bins # below the null and 15 above. A single step cannot then put BOTH extremes at # exactly ±30, so the two sides are stepped differently (1.875 below, # GK_RES_POS_WIDTH = 2.0 above) and the coverage is exactly [-30, +30]. The # price is a slightly coarser positive side; the price of NOT paying it is a # table that can never be centred on the null. Anything past ±30 is clamped # into the ±30 bin, because the module never applies more than ±30. GK_NBINS* = 32 GK_NULL_BIN* = 0 ## the 0.0 deg bin: "no correction" GK_RES_LO* = -30.0 ## binCentre(16), the most negative GK_RES_HI* = 30.0 ## binCentre(31), the most positive GK_RES_WIDTH* = 60.0 / 32.0 ## 1.875 deg, the step BELOW the null GK_RES_POS_WIDTH* = 2.0 ## 2.000 deg, the step ABOVE the null # ── trust thresholds ──────────────────────────────────────────────────────── GK_GLOBAL_MIN_ATTEMPTS* = 5 ## global row must have this many to be used GK_OPP_MIN_ATTEMPTS* = 20 ## per-opponent row needs more before it wins GK_MIN_BIN_HITS* = 3 ## Per-bin minimum before a bin may be returned. The row layout stores only ## a row-level `attempts`, so the per-bin attempt count is not directly ## available; `hits[b] >= n` is a LOWER BOUND on bin b's attempts (you ## cannot have n hits from fewer than n tries), which is the property the ## "never trust a bin tried once" rule actually needs. # ── exploration ───────────────────────────────────────────────────────────── # WHY THIS EXISTS. `update` files whatever bin the shot actually used, and a # shot taken with no correction is filed at GK_NULL_BIN. If the module NEVER # proposes anything else then EVERY shot in the whole table is bin 0, the # argmax can never move off the null, and no non-zero correction can ever be # discovered -- the table is a machine for recording that the base was right. # It is not a safe default, because the correction is the whole point: on the # recorded corpus a LEARNED residual beats the bare forecast (+0.54 pp hit, # t = 5.99 over 70 battles) when it is measured, and the constant-velocity # forecast is exactly the assumption that fails when the enemy turns, hugs a # wall or ranges. So a row that has NOT been sampled enough explores; a row # that has is trusted. GK_EPSILON of the shots on a fresh row try a UNIFORM # bin out of all 32 (which includes the null, so the null stays the majority), # and `aim` reports the bin it tried in `residualBin`, so the resolution # credits the bin that was really applied. The FIRST shot on a row is never # a probe. GK_EXPLORE_MIN* = 20 ## row attempts below this => exploration is allowed GK_EPSILON* = 0.25 ## chance an under-sampled shot takes a random bin GK_RNG_SEED* = 0xE377CB49'u32 ## fixed seed of the module's OWN LCG # ── space derivation ──────────────────────────────────────────────────────── GK_WALL_MARGIN* = 60.0 ## px from a wall that counts as "at" that wall # ── scan track (features 3 and 4) ─────────────────────────────────────────── GK_TRACK_N* = 5 ## samples kept per scannedBotId (PPO's tracker: 5) GK_GAP_MAX* = 6 ## scan gap > 6 ticks => the signal is UNKNOWN. ## MEASURED over 184 recorded round-battles: ## 118,253 alive ticks / 24,883 scans = a mean ## inter-scan gap of 4.75 ticks, so 6 covers the ## measured mean. The previous limit of 2 threw ## at least 57.9% of all observations into ## gkUnknown. Above 1 tick the rate is a ## GAP-AVERAGE, counted by longGapCount. GK_TURN_DEAD* = 2.0 ## deg/turn below this the enemy counts as straight GK_TREND_DEAD* = 0.05 ## px/turn change below this counts as constant # ── on-disk format ────────────────────────────────────────────────────────── # HEADER, GK_HEADER_LEN = 32 bytes, all integers little-endian: # 0 : 8 bytes magic, exact compare against "SIRGUNKN" # 8 : u32 version, must equal GK_VERSION # 12 : u32 nGlobal — number of non-empty global rows # 16 : u32 nOpp — number of opponent rows # 20 : u32 nNames — number of interned opponent names # 24 : u32 nUnknown — feature derivations that produced gkUnknown # 28 : u32 nFeature — total feature derivations # `longGapCount` is deliberately NOT persisted: like the scan tracks and the # arena constants it is per-episode runtime telemetry, and a 7th u32 would # change this header's size for no learning value. It resets on `load`. # PAYLOAD, in exactly this order and nothing else: # nGlobal * ( key u32 | attempts u16 | hits 32*u16 ) # nOpp * ( oppId u32 | key u32 | attempts u16 | hits 32*u16 ) # nNames * ( len u32 | bytes ) # The parser is STRICT: bad magic, bad version, an out-of-range key/oppId, a # short read, or a cursor that does not land exactly on the end of the file # all mean REJECT — empty table, false. `save` is ATOMIC: it writes a sibling # temp file and renames it over the target, so a crash mid-write leaves the # previous good table intact. GK_MAGIC* = "SIRGUNKN" GK_VERSION* = 1'u32 GK_HEADER_LEN* = GK_MAGIC.len + 6 * 4 type GkTurn* = enum gkStraight, gkRight, gkLeft, gkUnknown GkTrend* = enum gkAccelerating, gkConstant, gkDecelerating, gkUnknown GkSpace* = enum gkNearWall, gkCorner, gkFree GkSource* = enum gkSourceNone, gkSourceGlobal, gkSourceOpponent GkRow* = object ## One 15-bit-keyed row. 2 + 64 bytes (the spec's `isOpponent` flag is not ## stored per row: opponent and global rows live in SEPARATE stores, which ## is the same information with no wasted byte). attempts*: uint16 hits*: array[GK_NBINS, uint16] GkSample* = object ## One radar scan: where the enemy was and what it was doing. x*, y*: float dir*: float ## deg speed*: float ## px/tick turn*: int ## the scan's turnNumber, for the gap rule below GkTrack* = object ## A short per-scannedBotId scan history. Index 0 is the NEWEST scan, each ## older one shifted up, so the two most recent are `samples[0]` and ## `samples[1]`. samples*: array[GK_TRACK_N, GkSample] n*: int GkFeatures* = object ## World-frame snapshot of the situation, in the same units as the ## `WorldState` every other gun gets. Built by `featuresFor`; the accessors ## below (gkDist / gkBearing / gkGamma) derive the geometry so there is one ## source of truth. enemyX*, enemyY*: float ## enemy's current position enemyHeading*, enemySpeed*: float ## deg, px/tick selfX*, selfY*: float turning*: GkTurn ## from the scan track, see turnOf speedTrend*: GkTrend ## from the scan track, see trendOf space*: GkSpace ## from spaceOf (needs the arena constant) gunHeat*: float ## 0..1, the caller's gun heat power*: float ## fire power, chosen by the caller's power module radialFrac*: float ## lead_forecast.radialFrac over RadialWindow hasTarget*: bool ## false => query returns the no-target sentinel GkAim* = object ## The answer. `hasTarget == false` => nothing else here is meaningful and ## NO table was touched. hasTarget*: bool base*: float ## deg, the forecast base alone dist*: float ## px, the FORECAST distance (to the predicted enemy ## position), NOT the current LOS distance. `predict` ## places the aim point at THIS radius, which is the ## radius the virtual bullet is resolved at. residual*: float ## deg, what the knowledge added aim*: float ## deg, clamp(base + residual, -180, 180) residualBin*: int ## -1 when residual came from an all-zero row source*: GkSource key*: int opponentId*: int GunKnowledge* = object globalRows*: seq[GkRow] ## GK_NKEYS rows oppRows*: Table[(int, int), GkRow] ## (opponentId, key) tracks*: Table[int, GkTrack] ## scannedBotId -> track interner*: OpponentInterner arenaW*, arenaH*: float ## per-episode constant unknownCount*: uint32 ## derivations that produced gkUnknown featureCount*: uint32 ## total derivations (the denominator) longGapCount*: uint32 ## derivations whose rate was GAP-AVERAGED (gap > 1) rng*: uint32 ## the module's OWN LCG state (exploration only). ## NEVER `rand`/`randomize`: the selector's stream ## must stay reproducible (see `exploreUnit`). OpponentInterner* = object ## Persistent cross-battle identity: a name -> small int. Names are never ## stored in a key. Within a battle `scannedBotId` (or the caller's own ## id space) can be used directly; the interner is what survives a restart. ids*: Table[string, int] names*: seq[string] # ── angle helpers ───────────────────────────────────────────────────────────── proc normalize180*(a: float): float {.inline.} = ## Wrap to [-180, 180). var r = a + 180.0 r -= 360.0 * floor(r / 360.0) # fmod without pulling in fmod's float32/float64 split r - 180.0 proc gammaOf*(enemyHeading, selfX, selfY, enemyX, enemyY: float): float {.inline.} = ## Enemy heading minus the bearing of the LOS to it, wrapped to [-180,180). ## +90 = the enemy moves perpendicular to our line of sight. let los = radToDeg(arctan2(enemyY - selfY, enemyX - selfX)) normalize180(enemyHeading - los) proc gkDist*(f: GkFeatures): float {.inline.} = ## px, self -> enemy. hypot(f.enemyX - f.selfX, f.enemyY - f.selfY) proc gkBearing*(f: GkFeatures): float {.inline.} = ## deg, world bearing of the LOS to the enemy, in [-180, 180). radToDeg(arctan2(f.enemyY - f.selfY, f.enemyX - f.selfX)) proc gkGamma*(f: GkFeatures): float {.inline.} = ## deg, the enemy's heading relative to the LOS to it. gammaOf(f.enemyHeading, f.selfX, f.selfY, f.enemyX, f.enemyY) # ── residual bins ───────────────────────────────────────────────────────────── proc residualBin*(residualDeg: float): int {.inline.} = ## EXACT INVERSE of `binCentre`: `residualBin(binCentre(b)) == b` for every ## one of the 32 bins (pinned in the tests). Anything below -GK_RES_WIDTH ## folds toward the null and anything past +30 clamps into bin 31. if residualDeg >= 0.0: if residualDeg < GK_RES_POS_WIDTH: GK_NULL_BIN else: clamp(16 + int(floor(residualDeg / GK_RES_POS_WIDTH)), 17, GK_NBINS - 1) else: clamp(int(floor(-residualDeg / GK_RES_WIDTH)), 0, 16) proc binCentre*(bin: int): float {.inline.} = ## Centre angle of a bin, degrees. Bin GK_NULL_BIN is 0.0 -- the NULL ## residual -- and it is the centre of the table; clamps out-of-range ## indices. See the GK_NBINS block for the full 32-centre layout. let b = clamp(bin, 0, GK_NBINS - 1) if b == GK_NULL_BIN: 0.0 elif b <= 16: -GK_RES_WIDTH * b.float else: GK_RES_POS_WIDTH * (b - 16).float # ── the base: the self-consistent forecast ──────────────────────────────────── proc forecastFor*(f: GkFeatures): BaseForecast = ## THE PRODUCTION FORECAST: `guns/lead_forecast.forecastLinear`, the ## 5-iteration flight-time fixed point, called with `f.power` so the power ## that produced the key also produces the flight time. A power with no ## bullet speed degenerates to "the enemy, right now". let v = bulletSpeed(clamp(f.power, 0.1, 3.0)) # reused from gun_harness if v <= 0.0: return BaseForecast(x: f.enemyX, y: f.enemyY, dist: gkDist(f), bearing: degToRad(gkBearing(f))) forecastLinear( WorldState(enemyX: f.enemyX, enemyY: f.enemyY, enemyHeading: f.enemyHeading, enemySpeed: f.enemySpeed, selfX: f.selfX, selfY: f.selfY), v) proc forecastBase*(f: GkFeatures, gunHeading: float): float = ## THE PRODUCTION BASE, in degrees: ## baseBearing = bearing from us to the forecast's predicted point (rad) ## answer = radToDeg(baseBearing) (degrees) ## Returns an ABSOLUTE world direction, wrapped to [-180, 180). ## ## `gunHeading` is KEPT ONLY for call-site compatibility and is NOT used: the ## forecast bearing is already absolute, and the caller turns the turret ## relative to `getGunDirection()` on its own. Adding an absolute heading to a ## relative lead (the previous `gunHeading + lead`) is the bug pinned by ## `testAimFrameInvariant`. discard gunHeading normalize180(radToDeg(forecastFor(f).bearing)) # ── the closed form: CROSS-CHECK ONLY, NOT THE PRODUCTION PATH ──────────────── proc closedFormLead*(dist, power, enemySpeed, bearingFromGun, gamma: float): float {.inline.} = ## NOT USED BY `aim`. Kept as the documented cross-check for why the fixed ## point exists: the single-step `dist / bulletSpeed` below places the aim ## point at the FIRE-time distance, and the virtual-bullet metric resolves the ## bullet against the distance it actually flies, so any radial motion during ## the flight makes the shot miss with a perfect angle. Measured failure is ## recorded in `guns/lead_forecast`'s header (~0% for the whole GF family on ## the circular / wall-bounce fixtures, 87% for Linear where the fixed point ## gets 100%). See `testClosedFormCrossCheck`. ## ## v = 20 - 3*power (bullet speed; power clamped to ## MIN_FIRE_POWER 0.1 .. MAX_FIRE_POWER 3.0) ## t = dist / v ## lato = enemySpeed * t * sin(gamma) ## lungo = dist + enemySpeed * t * cos(gamma) ## base = bearingFromGun + atan2(lato, lungo) let p = clamp(power, 0.1, 3.0) let v = bulletSpeed(p) # reused from gun_harness if v <= 0.0: return normalize180(bearingFromGun) let t = dist / v let g = degToRad(gamma) let lato = enemySpeed * t * sin(g) let lung = dist + enemySpeed * t * cos(g) normalize180(bearingFromGun + radToDeg(arctan2(lato, lung))) # ── feature binning ─────────────────────────────────────────────────────────── proc binHeat*(gunHeat: float): int {.inline.} = ## Feature 5: the gun's heat in quarters of [0,1] — 0 = cool, 3 = hot. if gunHeat < 0.25: 0 elif gunHeat < 0.5: 1 elif gunHeat < 0.75: 2 else: 3 proc binRadial*(radialFrac: float): int {.inline.} = ## Feature 6: `lead_forecast.radialFrac(vt, RadialWindow)` in quarters of ## [0,1] — 0 = purely tangential (range-holding surfer), 3 = purely radial. ## Out-of-range input is clamped, so a bad tracker can only be wrong, never ## out of the table. if radialFrac < 0.25: 0 elif radialFrac < 0.5: 1 elif radialFrac < 0.75: 2 else: 3 proc spaceOf*(ex, ey, selfX, selfY, arenaW, arenaH: float): GkSpace {.inline.} = ## DERIVED feature 2, exact rule as implemented: ## ## For each of the four walls compute the gap from the ENEMY and the gap from ## US. A wall counts as "the wall behind the enemy, away from us" when ## gapE <= GK_WALL_MARGIN AND gapE < gapS ## i.e. the enemy is within 60 px of it AND it is the side we came from ## (the enemy is closer to that wall than we are). ## ## 0 such walls -> gkFree ## 1 such wall -> gkNearWall ## >= 2, spanning both axes (one vertical + one horizontal) -> gkCorner ## >= 2 on the SAME axis (opposite walls, only possible in a tiny arena) ## -> gkNearWall let gL = ex let gR = arenaW - ex let gB = ey let gT = arenaH - ey let sL = selfX let sR = arenaW - selfX let sB = selfY let sT = arenaH - selfY var vert = false var horz = false var n = 0 template consider(gE, gS: float, isVert: bool) = if gE <= GK_WALL_MARGIN and gE < gS: inc n if isVert: vert = true else: horz = true consider(gL, sL, true) consider(gR, sR, true) consider(gB, sB, false) consider(gT, sT, false) if n == 0: gkFree elif n == 1: gkNearWall elif vert and horz: gkCorner else: gkNearWall # ── the scan track: features 3 (turn) and 4 (speed trend) ──────────────────── # # RULE AS IMPLEMENTED. A track is the last GK_TRACK_N radar scans of ONE # scannedBotId (`GunKnowledge.observe`, one entry per ScannedBotEvent). The # signal uses the TWO MOST RECENT scans, samples[0] and samples[1]: # # gap = turns[0] - turns[1] # turnDegPerTurn = normalize180(dir[0] - dir[1]) / gap # speedChange = (speed[0] - speed[1]) / gap # # WHY THE DIVISION AND WHY `GK_GAP_MAX`: scans are gated by the radar sweep and # by MAX_EVENTS_AGE, so two consecutive entries are not necessarily one turn # apart. Dividing by the REAL gap is what keeps the per-turn rate honest # instead of making a 3-turn-old turn look like a 3x turn rate. A gap larger # than GK_GAP_MAX (6, measured -- see the constants block) is not evidence at # all -- the enemy has very likely turned several times since we last saw it -- # so the signal is reported as `gkUnknown`, its OWN key value, NOT a degrade to # straight/constant. There is no "unknown" row in the old design, so # straight+constant silently absorbed no-observation-at-all and the one row for # it blended two populations; `trackKnown` told you, but nothing learned from # the row could. # # HONESTLY: for a gap over 1 tick the rate is a GAP-AVERAGE over the interval, # not an instantaneous rate. `longGapCount` / `longGapRate` measure how often # that happened, so the averaging is never silent. # # Sign convention: headings are CCW-positive (0 = East), so a POSITIVE # `turnDegPerTurn` is the enemy turning LEFT and a negative one is RIGHT. # `GK_TURN_DEAD` / `GK_TREND_DEAD` are the dead-bands inside which we claim # nothing. proc observe*(gk: var GunKnowledge, botId: int, x, y, dir, speed: float, turn: int) = ## Append one radar scan to this bot's track. Call ONCE PER ScannedBotEvent, ## with the event's turnNumber as `turn`. Repeated calls with the same turn ## number are ignored, so a double-enqueue cannot invent motion. if botId < 0: return var tr = if botId in gk.tracks: gk.tracks[botId] else: GkTrack() if tr.n > 0 and tr.samples[0].turn == turn: return for i in countdown(min(tr.n, GK_TRACK_N - 1), 1): tr.samples[i] = tr.samples[i - 1] tr.samples[0] = GkSample(x: x, y: y, dir: dir, speed: speed, turn: turn) if tr.n < GK_TRACK_N: inc tr.n gk.tracks[botId] = tr proc trackGap*(tr: GkTrack): int {.inline.} = ## Ticks between the two newest scans, or -1 when there is no pair yet. This ## is the interval the turn rate and the speed trend are AVERAGED over (see ## `turnOf` / `trendOf`), exposed so the averaging is observable. if tr.n < 2: -1 else: tr.samples[0].turn - tr.samples[1].turn proc trackKnown*(tr: GkTrack): bool {.inline.} = ## False when there is no usable pair of scans: fewer than two samples, or a ## gap of more than GK_GAP_MAX ticks (see the rule above). if tr.n < 2: return false (tr.samples[0].turn - tr.samples[1].turn) <= GK_GAP_MAX proc turnOf*(tr: GkTrack): GkTurn {.inline.} = ## Feature 3. A gap over GK_GAP_MAX (or fewer than two scans) yields ## `gkUnknown` — a real key value, never `gkStraight`. Positive rate = ## turning left (CCW). For a gap over 1 tick this is the MEAN rate over the ## interval, not an instantaneous one. if not tr.trackKnown: return gkUnknown let gap = (tr.samples[0].turn - tr.samples[1].turn).float let rate = normalize180(tr.samples[0].dir - tr.samples[1].dir) / gap if rate > GK_TURN_DEAD: gkLeft elif rate < -GK_TURN_DEAD: gkRight else: gkStraight proc trendOf*(tr: GkTrack): GkTrend {.inline.} = ## Feature 4. A gap over GK_GAP_MAX (or fewer than two scans) yields ## `gkUnknown` — a real key value, never `gkConstant`. For a gap over 1 tick ## this is the MEAN change per tick over the interval. if not tr.trackKnown: return gkUnknown let gap = (tr.samples[0].turn - tr.samples[1].turn).float let dv = (tr.samples[0].speed - tr.samples[1].speed) / gap if dv > GK_TREND_DEAD: gkAccelerating elif dv < -GK_TREND_DEAD: gkDecelerating else: gkConstant proc trackFor*(gk: GunKnowledge, botId: int): GkTrack {.inline.} = if botId in gk.tracks: gk.tracks[botId] else: GkTrack() # ── the 13-bit key (mixed radix, so the table is DENSE) ────────────────────── proc keyOf*(f: GkFeatures): int {.inline.} = ## Row index in [0, GK_NKEYS). Mixed-radix (not bit-shifted) packing, because ## 5*3*4*4*4*4 = 3840 < 2^15 = 32768: bit-shifting would leave most of the ## table unreachable. Digits, outermost (highest weight) first: ## dist band 5 x space 3 x turning 4 x trend 4 x heat 4 x radial 4 ## i.e. weights 768 / 256 / 64 / 16 / 4 / 1. `turning` and `speedTrend` ## have 4 values each, `gkUnknown` included (ord 3). let k = lgBandOf(gkDist(f)) result = ((k * 3 + ord(f.space)) * 4 + ord(f.turning)) * 4 + ord(f.speedTrend) result = (result * 4 + binHeat(f.gunHeat)) * 4 + binRadial(f.radialFrac) # ── opponent interning ──────────────────────────────────────────────────────── proc opponentName*(gk: GunKnowledge, id: int): string {.inline.} = if id >= 0 and id < gk.interner.names.len: gk.interner.names[id] else: "" proc opponentId*(oi: var OpponentInterner, name: string): int = ## Stable small id for a name, interning on first sight. Id 0 is the first ## name interned; callers pass -1 (or omit the override) for "no identity". if name.len == 0: return -1 if name in oi.ids: return oi.ids[name] let id = oi.names.len oi.ids[name] = id oi.names.add name id proc opponentName*(oi: OpponentInterner, id: int): string = if id >= 0 and id < oi.names.len: oi.names[id] else: "" # ── lifecycle ───────────────────────────────────────────────────────────────── proc initGunKnowledge*(arenaW = 0.0, arenaH = 0.0): GunKnowledge = result.arenaW = arenaW result.arenaH = arenaH result.rng = GK_RNG_SEED result.globalRows = newSeq[GkRow](GK_NKEYS) result.oppRows = initTable[(int, int), GkRow]() result.tracks = initTable[int, GkTrack]() proc setArena*(gk: var GunKnowledge, w, h: float) {.inline.} = ## Per-episode constant. Only the space feature depends on it. gk.arenaW = w gk.arenaH = h proc spaceFor*(gk: GunKnowledge, ex, ey, selfX, selfY: float): GkSpace {.inline.} = ## The space feature derived with the module's current arena constant. Sets ## it with `setArena` once per battle; before that it degrades to `gkFree`. if gk.arenaW <= 0.0 or gk.arenaH <= 0.0: gkFree else: spaceOf(ex, ey, selfX, selfY, gk.arenaW, gk.arenaH) proc opponentId*(gk: var GunKnowledge, name: string): int {.inline.} = opponentId(gk.interner, name) # ── featuresFor: build the world-frame snapshot ─────────────────────────────── proc featuresFor*(gk: var GunKnowledge, state: WorldState, botId: int, power, gunHeat, radialFrac: float): GkFeatures = ## THE constructor. `state` is the same `WorldState` every gun gets this tick ## (so the forecast and the residuals are all on one frame), `botId` is the ## `scannedBotId` whose track supplies features 3 and 4, `power` is the ## caller's chosen fire power, `gunHeat` its gun heat, and `radialFrac` comes ## from `lead_forecast.radialFrac(velTracker, RadialWindow)`. ## ## `var` only so the gkUnknown counter is measured where the features are ## actually produced (one derivation = one counter tick). let tr = gk.trackFor(botId) let turn = tr.turnOf let trend = tr.trendOf inc gk.featureCount if turn == gkUnknown or trend == gkUnknown: inc gk.unknownCount # the rate was an AVERAGE over more than one tick, not an instantaneous one if tr.trackGap > 1: inc gk.longGapCount GkFeatures(enemyX: state.enemyX, enemyY: state.enemyY, enemyHeading: state.enemyHeading, enemySpeed: state.enemySpeed, selfX: state.selfX, selfY: state.selfY, turning: turn, speedTrend: trend, space: gk.spaceFor(state.enemyX, state.enemyY, state.selfX, state.selfY), gunHeat: gunHeat, power: power, radialFrac: radialFrac, hasTarget: true) proc unknownRate*(gk: GunKnowledge): float = ## Fraction of feature derivations that produced `gkUnknown` on either the ## turn or the trend feature. 0.0 before anything has been derived, so a ## bot that never sees a gap never looks like one that always does. if gk.featureCount == 0: 0.0 else: gk.unknownCount.float / gk.featureCount.float proc longGapRate*(gk: GunKnowledge): float = ## Fraction of feature derivations whose turn rate / speed trend was ## GAP-AVERAGED over more than one tick, i.e. how often the answer is an ## average over an interval rather than an instantaneous rate. Reported next ## to `unknownRate` so the price of GK_GAP_MAX = 6 is measurable at runtime ## and not just claimed in a comment. 0.0 before anything is derived. if gk.featureCount == 0: 0.0 else: gk.longGapCount.float / gk.featureCount.float # ── residual selection ──────────────────────────────────────────────────────── proc bestResidual(row: GkRow): tuple[deg: float, bin: int] = ## argmax(hits[b]) over bins that clear GK_MIN_BIN_HITS, tie-broken toward ## GK_NULL_BIN (least aggressive correction, the one that is exactly 0 deg) ## so an empty/ambiguous row degrades to "no correction" rather than to ## noise. An all-zero row (or one with no bin past the threshold) returns ## 0.0 deg, bin -1, i.e. the NULL residual. ## ## A shot filed under the null (`update` with a below-threshold usedBin, see ## below) can only ever raise hits[GK_NULL_BIN], so it can only ever pull the ## argmax TOWARD 0 deg. There is no way for thin evidence about a ## no-correction shot to buy a large correction. var bestB = -1 var bestHits = 0 for b in 0 ..< GK_NBINS: let h = int(row.hits[b]) if h < GK_MIN_BIN_HITS: continue if h > bestHits or (h == bestHits and bestB >= 0 and abs(b - GK_NULL_BIN) < abs(bestB - GK_NULL_BIN)): bestHits = h bestB = b if bestB < 0: (0.0, -1) else: (binCentre(bestB), bestB) # ── exploration: the module's OWN RNG ───────────────────────────────────────── proc exploreUnit(gk: var GunKnowledge): float {.inline.} = ## ONE draw in [0,1) from a 32-bit LCG held IN `gk.rng`. ## ## WHY NOT `rand`: the global RNG belongs to the harness' selector. A rack gun ## that drew from it would silently reshuffle the whole bot's behaviour ## (`test_knowledge_registration` pins `rand` parity across the module's ## `aim`/`update` path, and the parity survives precisely because the state ## here is a plain field). The seed is a CONSTANT, so a run is reproducible. gk.rng = gk.rng * 1664525'u32 + 1013904223'u32 (gk.rng shr 8).float / 16777216.0 # 24 bits, [0,1) proc exploreBin(gk: var GunKnowledge): int {.inline.} = ## A UNIFORM bin over ALL 32, the null included. A SECOND draw, not the same ## one the epsilon used: reusing it would make "explore" mean "the low bins", ## which is not uniform and never tries a large correction. clamp(int(gk.exploreUnit() * GK_NBINS.float), 0, GK_NBINS - 1) # ── query ───────────────────────────────────────────────────────────────────── proc aim*(gk: var GunKnowledge, f: GkFeatures, gunHeading = 0.0, oppId = -1): GkAim = ## The whole module. Touches at most ONE table row (the global one, and only ## when nothing has reached threshold yet). `gunHeading` is accepted for ## call-site compatibility and IGNORED: `aim` is an ABSOLUTE world bearing ## (`base` from the forecast + the learned residual), which is the frame ## `ModularBot.nim` consumes it in. `oppId` is an already-interned id (from ## `GunKnowledge.opponentId(name)`, or a battle-local `scannedBotId`); -1 ## means "global only". discard gunHeading if not f.hasTarget: return GkAim(hasTarget: false, base: 0.0, residual: 0.0, aim: 0.0, residualBin: -1, source: gkSourceNone, key: -1, opponentId: -1) let key = keyOf(f) result.hasTarget = true result.key = key let fc = forecastFor(f) result.base = normalize180(radToDeg(fc.bearing)) result.dist = fc.dist let oid = if oppId >= 0 and oppId < gk.interner.names.len: oppId else: -1 result.opponentId = oid var chosen = 0.0 var binIdx = -1 var src = gkSourceNone # 1. per-opponent override if oid >= 0 and (oid, key) in gk.oppRows: let row = gk.oppRows[(oid, key)] if row.attempts >= GK_OPP_MIN_ATTEMPTS: let (d, b) = bestResidual(row) chosen = d binIdx = b src = gkSourceOpponent if src == gkSourceNone: # 2. global if gk.globalRows[key].attempts >= GK_GLOBAL_MIN_ATTEMPTS: let (d, b) = bestResidual(gk.globalRows[key]) chosen = d binIdx = b src = gkSourceGlobal else: # 3. nothing learned yet: the NULL residual, 0 deg, and start counting # the situation on the GLOBAL row so it can eventually reach # threshold. inc gk.globalRows[key].attempts # EXPLORATION, on the one answer that is a DEFAULT rather than a measurement: # either the row has not reached threshold (step 3), or it has but no bin # cleared GK_MIN_BIN_HITS, so `bestResidual` degraded to the null. Those are # exactly the shots that would otherwise all be filed at bin 0, which is how # a table ends up unable to discover anything at all. A row with fewer than # GK_EXPLORE_MIN attempts spends GK_EPSILON of them on a UNIFORM bin out of # all 32 (the null included, so it stays the majority), and the bin is REPORTED # in `residualBin`, so the caller files it as `usedBin` and the resolution # credits the bin that was really applied. At or above the threshold, or with # a real measurement in hand, there is no exploration: the row answers. # # The FIRST shot on a row is never a probe (`attempts >= 1`): the base gets one # honest observation before the module starts guessing, and it costs nothing # because the row has 20 shots to spend. if (src == gkSourceNone or binIdx == -1) and int(gk.globalRows[key].attempts) in 1 ..< GK_EXPLORE_MIN and gk.exploreUnit() < GK_EPSILON: let b = gk.exploreBin() chosen = binCentre(b) binIdx = b result.residual = chosen result.residualBin = binIdx result.source = src result.aim = clamp(result.base + chosen, -180.0, 180.0) # ── learning ────────────────────────────────────────────────────────────────── proc update*(gk: var GunKnowledge, f: GkFeatures, usedBin: int, hit: bool, oppId = -1) = ## A shot resolved. `f` must be the SAME situation the shot was taken in and ## `usedBin` the residual bin actually applied. `hit` marks a successful hit. ## Touches the opponent row when `oppId` is valid, else the global row. ## ## `usedBin < 0` MEANS THE MODULE APPLIED NO CORRECTION (the row was below ## threshold, or nothing cleared GK_MIN_BIN_HITS) and such a shot is filed ## under GK_NULL_BIN, whose centre is exactly 0.0 deg. It is NOT clamped into ## a residual the module never applied: `clamp(-1, 0, 31) = 0` used to file ## every no-correction shot into the lowest bin, and with the old layout that ## bin sat at -29.06 deg, so the argmax returned a 29 deg correction ## forever. Filing it at the null instead is safe by construction: it can ## only raise hits[GK_NULL_BIN], i.e. only pull the argmax toward 0 deg, so ## a shot the module barely corrected can never buy a large correction on ## thin evidence. if not f.hasTarget: return let b = if usedBin < 0: GK_NULL_BIN else: clamp(usedBin, 0, GK_NBINS - 1) let key = keyOf(f) if oppId >= 0 and oppId < gk.interner.names.len: let okey = (oppId, key) if okey notin gk.oppRows: gk.oppRows[okey] = GkRow() inc gk.oppRows[okey].attempts if hit: inc gk.oppRows[okey].hits[b] else: inc gk.globalRows[key].attempts if hit: inc gk.globalRows[key].hits[b] proc rowAttempts*(gk: GunKnowledge, f: GkFeatures, oppId = -1): int {.inline.} = let key = keyOf(f) if oppId >= 0 and (oppId, key) in gk.oppRows: int(gk.oppRows[(oppId, key)].attempts) else: int(gk.globalRows[key].attempts) proc rowHitCount*(gk: GunKnowledge, f: GkFeatures, bin: int, oppId = -1): int {.inline.} = let key = keyOf(f) let b = clamp(bin, 0, GK_NBINS - 1) if oppId >= 0 and (oppId, key) in gk.oppRows: int(gk.oppRows[(oppId, key)].hits[b]) else: int(gk.globalRows[key].hits[b]) # ── maintenance ─────────────────────────────────────────────────────────────── proc prune*(gk: var GunKnowledge): int = ## Drop every row that is still BELOW its global threshold — such a row has ## never produced a residual and only costs memory. Rows that HAVE reached ## threshold (global >= GK_GLOBAL_MIN_ATTEMPTS, opponent >= ## GK_OPP_MIN_ATTEMPTS) are NEVER touched. Returns the number of rows dropped. var dropped = 0 for i in 0 ..< GK_NKEYS: if int(gk.globalRows[i].attempts) in 1 ..< GK_GLOBAL_MIN_ATTEMPTS: gk.globalRows[i] = GkRow() inc dropped var okeys: seq[(int, int)] = @[] for ok in gk.oppRows.keys: okeys.add ok for ok in okeys: if int(gk.oppRows[ok].attempts) < GK_OPP_MIN_ATTEMPTS: gk.oppRows.del ok inc dropped dropped # ── persistence ─────────────────────────────────────────────────────────────── proc putU16(s: var string, v: uint16) = s.add char(v and 0xFF'u16) s.add char((v shr 8) and 0xFF'u16) proc putU32(s: var string, v: uint32) = for i in 0 ..< 4: s.add char((v shr (8 * i)) and 0xFF'u32) proc getU16(s: string, i: var int): uint16 = if i + 2 > s.len: raise newException(ValueError, "gk: truncated u16") result = uint16(ord(s[i])) or (uint16(ord(s[i + 1])) shl 8) i += 2 proc getU32(s: string, i: var int): uint32 = if i + 4 > s.len: raise newException(ValueError, "gk: truncated u32") result = 0'u32 for k in 0 ..< 4: result = result or (uint32(ord(s[i + k])) shl (8 * k)) i += 4 proc putRow(s: var string, r: GkRow) = s.putU16 r.attempts for b in 0 ..< GK_NBINS: s.putU16 r.hits[b] proc getRow(s: string, i: var int): GkRow = result.attempts = getU16(s, i) for b in 0 ..< GK_NBINS: result.hits[b] = getU16(s, i) proc encode*(gk: GunKnowledge): string = ## Only NON-EMPTY rows are written, which is what keeps the in-memory table ## (3840 rows) at a few kB on disk. Layout: see the GK_HEADER_LEN block in ## the constants above for the byte-exact header and payload. var keys: seq[int] for i in 0 ..< GK_NKEYS: if gk.globalRows[i].attempts > 0: keys.add i result = GK_MAGIC result.putU32 GK_VERSION result.putU32 uint32(keys.len) result.putU32 uint32(gk.oppRows.len) result.putU32 uint32(gk.interner.names.len) result.putU32 gk.unknownCount result.putU32 gk.featureCount for k in keys: result.putU32 uint32(k) result.putRow gk.globalRows[k] var okeys: seq[(int, int)] = @[] for ok in gk.oppRows.keys: okeys.add ok okeys.sort for ok in okeys: result.putU32 uint32(ok[0]) result.putU32 uint32(ok[1]) result.putRow gk.oppRows[ok] for nm in gk.interner.names: result.putU32 uint32(nm.len) result.add nm proc tempPathFor(path: string): string = ## Sibling temp file, in the SAME directory (a rename is only atomic inside ## one filesystem). A bare filename has no directory part, so don't prepend ## an empty one. let dir = parentDir(path) let base = extractFilename(path) & ".tmp" if dir.len == 0: base else: dir / base proc gkReport(what, path, reason: string) = ## THE FAILURE CONVENTION for this module, the same one the load-rejection ## path and `lead_gain` / `gun_harness` use: a one-line `[gun_knowledge]` ## diagnostic on stderr naming the path attempted and the reason. Never ## raised: a persistence problem must not take the bot down mid-battle, and ## learning keeps going in memory either way. stderr.writeLine("[gun_knowledge] cannot " & what & " " & path & ": " & reason) proc discardTemp(tmp: string) = ## Best-effort cleanup of the sibling temp file; cleanup must never be the ## thing that throws. try: if fileExists(tmp): removeFile(tmp) except CatchableError: discard proc save*(gk: GunKnowledge, path: string): bool = ## ATOMIC. Encodes into a sibling temp file and `moveFile`s (rename) it over ## the target, so a crash or a full disk mid-write leaves the PREVIOUS good ## table intact and never a half-written one. ## ## The parent directory of `path` is CREATED when it is missing, so a nested ## `TR_KNOWLEDGE_MEM` works on the very first save with no manual `mkdir`. ## A path that is itself a directory, or a parent that is not a directory, ## is REPORTED and rejected before a single byte is written. ## ## Every failure is reported on stderr naming the path and the reason, and ## the three failure kinds are told apart: (1) the directory could not be ## created, (2) the temp file could not be written (unwritable dir, disk ## full, wrong type), (3) the rename onto the target was refused. In all ## three the temp file is removed and `false` is returned; nothing raises. let dir = parentDir(path) if dir.len > 0 and not dirExists(dir): try: createDir(dir) except CatchableError as e: gkReport("create directory", path, e.msg) return false if dirExists(path): gkReport("write the knowledge table to", path, "it is a directory, not a file") return false let tmp = tempPathFor(path) try: writeFile(tmp, gk.encode()) except CatchableError as e: gkReport("write the knowledge table to", path, e.msg) discardTemp(tmp) return false try: # rename(2) / MoveFileEx(REPLACE_EXISTING) REPLACES the target in one step; # never unlink it first, that would open the same data-loss window. moveFile(tmp, path) true except CatchableError as e: gkReport("replace the knowledge table at", path, e.msg) discardTemp(tmp) false proc emptyTable(): GunKnowledge = result.rng = GK_RNG_SEED result.globalRows = newSeq[GkRow](GK_NKEYS) result.oppRows = initTable[(int, int), GkRow]() result.tracks = initTable[int, GkTrack]() result.interner = OpponentInterner(ids: initTable[string, int](), names: @[]) proc load*(gk: var GunKnowledge, path: string): bool = ## STRICT. A missing, empty, short, long, wrong-magic or wrong-version file ## leaves the table EMPTY and returns false — it is never parsed anyway and ## never half-loaded. A file is accepted only when magic, version, every ## key/oppId range, every read bound AND the final cursor position are all ## exactly right. The arena constants are per-episode and are NOT persisted, ## and neither is `longGapCount` (the gap-averaging telemetry is per-episode ## too). let keepW = gk.arenaW # captured BEFORE the reset below let keepH = gk.arenaH gk = emptyTable() var s: string try: if not fileExists(path): return false s = readFile(path) if s.len < GK_HEADER_LEN: return false if s[0 ..< GK_MAGIC.len] != GK_MAGIC: return false var i = GK_MAGIC.len if getU32(s, i) != GK_VERSION: return false let nG = int(getU32(s, i)) let nO = int(getU32(s, i)) let nN = int(getU32(s, i)) let nU = getU32(s, i) let nF = getU32(s, i) if nG < 0 or nG > GK_NKEYS or nO < 0 or nN < 0: return false var t = emptyTable() for _ in 0 ..< nG: let key = int(getU32(s, i)) if key < 0 or key >= GK_NKEYS: return false t.globalRows[key] = getRow(s, i) for _ in 0 ..< nO: let oid = int(getU32(s, i)) let key = int(getU32(s, i)) if key < 0 or key >= GK_NKEYS: return false t.oppRows[(oid, key)] = getRow(s, i) for _ in 0 ..< nN: let n = int(getU32(s, i)) if n < 0 or i + n > s.len: return false discard t.opponentId(s[i ..< i + n]) i += n # LONGER than the header declared => trailing garbage => reject if i != s.len: return false t.unknownCount = nU t.featureCount = nF t.arenaW = keepW # per-episode, not persisted t.arenaH = keepH gk = t true except CatchableError: gk = emptyTable() false # ── introspection (tests / boot report) ─────────────────────────────────────── proc usedGlobalRows*(gk: GunKnowledge): int = for i in 0 ..< GK_NKEYS: if gk.globalRows[i].attempts > 0: inc result proc memoryBytes*(gk: GunKnowledge): int {.inline.} = ## sizeof(GkRow) * rows, for the boot report. 3840 rows x 66 B = 253440 B. gk.globalRows.len * sizeof(GkRow) + gk.oppRows.len * sizeof(GkRow) # ── THE RACK GUN: `KnowledgeGun`, the `Gun` concept this module is mounted as ─ # # Everything above is the LEARNER (pure: features, key, aim, update, persist). # This block is the thin rack adapter, and it is deliberately thin: the gun # answers ONE question — at what ABSOLUTE angle should the turret point — and # nothing else. It does not choose fire power (`predict` is HANDED `bulletSpeed`, # which is the proof that power was decided elsewhere: `PowerBins` in # `virtual_bullets` plus the energy-aware `applyPowerPolicy`), it does not decide # whether to fire (`selector.shouldFire`), and it does not pick a target # (`targeting/enemy_tracker` + `targeting/target_selector` own that; the gun is # told which opponent it is aiming at through `KnowledgeGun.targetId`). # # WHAT THE ADAPTER ADDS, and why each piece is needed: # * `ensureInit` / `networkBytes` — the 3840-row table is only allocated on # FIRST USE, so a rack that never admits this gun never pays for it. Same # lazy shape as `lead_gain.initLeadGainGun`. # * `vt` (a `lead_forecast.VelocityTracker`) and the per-tick `gk.observe` — # the Gun concept hands a gun a `WorldState` and nothing else, so the scan # track (features 3 and 4) and the radial fraction (feature 6) have to be # fed from the per-tick pose the caller already has. Both are one-per-tick # and both ignore same-tick repeats, so being called once per power bin is # harmless. # * `pending` — ONE record per power bin, written by `predict` and consumed by # `onResult`. This is what makes the label land on the EXACT row that # produced the angle: the harness resolves the bullet for the gun that # spawned it (even when the rack's SELECTED gun, and therefore the real # shot, was a different one) and hands back the real hit/miss plus the fire # tick, so the update is on the truth, not on what we hoped. # * `onRoundBoundary` — persistence wiring. Called on the tick regression that # starts a new round, which is the same round boundary `lead_gain` uses: load # once, then save (atomically, via the learner's own `save`) at EVERY # boundary after a `prune`. Nothing here resets the counts, so the table # accumulates ACROSS rounds; that is this gun's own capability, not a # comparison between two arms. # * `confidence = 1 - unknownRate` — the Gun concept's only per-prediction # telemetry, used here to carry the `gkUnknown` frequency out of a live # battle: 1.0 = every feature derivation was fully observed, 0.0 = every one # hit a scan gap. # # NO GLOBAL RNG. `initKnowledgeGun` only reads the environment and fills # integers; the 3840-row table is `newSeq`/`initTable`, never a random draw, so # constructing the gun cannot perturb the selector's `rand` stream # (`common_libs/tests/test_knowledge_registration.nim` pins that with a seeded # parity check). EXPLORATION does draw, but from the module's OWN LCG state # (`GunKnowledge.rng`, seeded from a constant): neither `aim` nor `update` can # reach the global `rand` at all, and the parity check is kept over the whole # aim+update path, not just the constructor. const GK_MEM_ENV* = "TR_KNOWLEDGE_MEM" ## path of the learned table; "" = memory only type GkPending* = object ## The aim ONE power bin produced on ONE tick, kept so the resolving ## virtual bullet updates that exact situation. valid*: bool fireTick*: int f*: GkFeatures usedBin*: int ## the residual bin actually applied (-1 = no residual) oppId*: int ## the interned opponent id used for the aim KnowledgeGun* = object ## The rack gun. `Gun` concept: `predict` + `onResult` (see ## `gun_harness/gun_interface`). Public state the caller sets/reads: targetId*: int ## the opponent the caller is aiming at; -1 = global only gunHeat*: float ## 0..1 gun heat; the caller sets it each tick memPath*: string ## TR_KNOWLEDGE_MEM; "" = memory only (no disk at all) unknownRate*: float ## gkUnknown fraction, telemetry for the boot/log path longGapRate*: float ## fraction of derivations whose rate was gap-averaged gk*: GunKnowledge vt*: VelocityTracker initialized*: bool loaded*: bool lastTick*: int trackId*: int ## last targetId the scan track was interned for interned*: int ## interned id of `trackId` (the opponent partition key) pending*: array[len(PowerBins), GkPending] proc powerBinSlot*(power: float): int = ## Slot in `KnowledgeGun.pending` for `power`: the exact `PowerBins` index, else ## the highest bin not above it (0 when there is none). Same rule as ## `virtual_bullets.binIndexForPower`, written over the imported table so the ## slot and the feedback's `powerBin` are the same index. result = 0 for i in 0.. 0: memPath else: getEnv(GK_MEM_ENV, "").strip() result.unknownRate = 0.0 result.longGapRate = 0.0 proc ensureInit*(g: var KnowledgeGun) = ## Build the 3840-row table on FIRST USE. `networkBytes` is 0 until here. if g.initialized: return g.initialized = true g.gk = initGunKnowledge() g.trackId = -1 g.interned = -1 g.lastTick = -1 proc networkBytes*(g: KnowledgeGun): int = ## 0 before the first `predict` (the lazy guarantee the registration test ## pins), the real table size after it. if not g.initialized: 0 else: g.gk.memoryBytes proc isWarmedUp*(g: KnowledgeGun): bool {.inline.} = true proc powerOfBulletSpeed*(bulletSpeed: float): float {.inline.} = ## Inverse of `gun_interface.bulletSpeed` (= 20 - 3p), so the caller can hand ## `predict` a speed and the key still carries the power that produced it. (20.0 - bulletSpeed) / 3.0 proc onRoundBoundary*(g: var KnowledgeGun) = ## ROUND BOUNDARY, wired from `predict` on the tick regression that starts a ## new round (bots teleport between rounds, so every in-round quantity is ## dropped: scan tracks, the velocity ring, the per-tick cache, the pending ## aims). The LEARNED COUNTS AND THE OPPONENT PARTITION ARE KEPT — they are ## battle/bot-scale, not round-scale. g.gk.tracks.clear() g.vt = VelocityTracker() for i in 0.., state: WorldState, bulletSpeed: float): GunPrediction ## Only the AIM is produced. With no power (`bulletSpeed <= 0`) the forecast ## has no flight time to solve, so the aim point is the enemy itself. g.ensureInit() if g.lastTick >= 0 and state.tick < g.lastTick: g.onRoundBoundary() if state.tick != g.lastTick: g.lastTick = state.tick g.gk.setArena(state.arenaWidth, state.arenaHeight) # The scan track: one entry per tick for the opponent we are aiming at. The # SAME turn number twice in a row (predict runs once per power bin) is # ignored by `observe`, so a gap in the record IS a real gap. if g.targetId != g.trackId: g.trackId = g.targetId g.interned = if g.targetId >= 0: g.gk.opponentId($g.targetId) else: -1 if g.targetId >= 0: g.gk.observe(g.targetId, state.enemyX, state.enemyY, state.enemyHeading, state.enemySpeed, state.tick) lead_forecast.observe(g.vt, state) g.unknownRate = g.gk.unknownRate g.longGapRate = g.gk.longGapRate if bulletSpeed <= 0.0: return GunPrediction(x: state.enemyX, y: state.enemyY, confidence: 1.0 - g.unknownRate) let power = powerOfBulletSpeed(bulletSpeed) let f = g.gk.featuresFor(state, g.trackId, power, g.gunHeat, lead_forecast.radialFrac(g.vt, lead_forecast.RadialWindow)) # The aim is already an ABSOLUTE world bearing, so the aim point is placed on # that RAY. The RADIUS is the FORECAST distance (`GkAim.dist`, the distance # from us to the predicted enemy position) and NOT the current LOS distance: # the forecast is a self-consistent fixed point precisely so that the bullet's # travel distance and the radius it is resolved at agree, and the caller # turns the turret against the point itself (`aimAngle(self, pred)`). let a = g.gk.aim(f, 0.0, g.interned) var px = state.enemyX var py = state.enemyY if a.hasTarget: let d = a.dist let r = degToRad(a.aim) px = state.selfX + cos(r) * d py = state.selfY + sin(r) * d # A pending aim belongs to the VIRTUAL bullet of one power bin, and only # the per-bin loop (`ModularBot.nim:1380`, powers are exact # `PowerBins[i]`) spawns those. The REAL shot (`ModularBot.nim:1484`) is # aimed with the policy-capped power, which is usually NOT a bin (a # `powerToKill` or energy-slope 0.7, say), and `powerBinSlot` would FLOOR # it onto a real bin's slot: the bin's own virtual bullet would then train # on THIS shot's features and residual -- a different power's row, at the # same fireTick, so the resolution guard cannot tell. The exactness of the # power IS the discriminator between the two paths (no interface change). let slot = powerBinSlot(power) if abs(PowerBins[slot] - power) < 1e-9: g.pending[slot] = GkPending( valid: true, fireTick: state.tick, f: f, usedBin: a.residualBin, oppId: g.interned) GunPrediction(x: px, y: py, confidence: 1.0 - g.unknownRate) proc onResult*(g: var KnowledgeGun, e: FeedbackEvent) = ## THE RACK SIGNATURE (identical to every other gun in the rack): ## onResult*(g: var , e: FeedbackEvent) ## A shot resolved: update the EXACT row that produced the angle, with the ## bin that angle used and the real outcome. `FeedbackEvent` carries the spawn ## `powerBin` (the pending slot) and the spawn `fireTick`, so a stale pending ## record — from a round that ended, or a power bin that never predicted — is ## dropped instead of learning on a situation that did not happen. if not g.initialized: return if e.powerBin < 0 or e.powerBin >= len(g.pending): return let p = g.pending[e.powerBin] if not p.valid or p.fireTick != e.fireTick: return g.gk.update(p.f, p.usedBin, e.hit, p.oppId) when isMainModule: echo sizeof(GkRow), " bytes/row; ", GK_NKEYS, " rows = ", GK_NKEYS * sizeof(GkRow), " B global table"