Files
SirRoboGarage/common_libs/guns/guess_factor.nim
T
SirStone 2cc2a3bd87 fix(ModularBot): ram loop prevention, dead-target guards, cleaner logging
- 30-tick cooldown after ghost-stuck/timeout ram exit prevents re-entry loop
- enemy_tracker.update() skips dead bots to prevent same-tick scan resurrection
- TFIL graphics cleared when ramming is active movement
- [config] logs: white base with green-highlighted changes only
- [ram:enter] logs trigger reason and key values on false→true transition
- [death] and [target-invalid] logs retained for diagnostics
2026-09-20 20:44:45 +02:00

124 lines
4.3 KiB
Nim

## Guess-factor gun: statistical targeting via GF histogram.
## Bins: 31, ranging GF -1 (max CW escape) to +1 (max CCW escape).
## Learns from virtual bullet outcomes; caches wave state per-tick.
import std/[math, strformat]
import gun_harness/gun_interface
const
GFBins = 31
GFPrior = 0.1
DebugGF* = false
type
Wave = object
fireX, fireY: float
fireBearing: float # atan2(enemyY-selfY, enemyX-selfX) at fire tick (rad)
# mea not stored — recomputed from FeedbackEvent.bulletPower at resolution time
GFGun* = object
bins: array[GFBins, float]
waves: seq[Wave] # pending unresolved waves
# per-tick cache: store wave only once across multiple power-bin calls
cachedTick: int
cachedWaveStored: bool
debugGraphics*: bool
proc initGFGun*(): GFGun =
result.cachedTick = -1
result.debugGraphics = false
# Seed with a head-on prior: triangular bump at bin 15 (GF=0).
# Prevents the cold-start tie-break to GF=-1 (bin 0) that poisons early fitness.
let center = (GFBins - 1) div 2 # = 15
for i in 0..<GFBins:
let d = abs(i - center)
result.bins[i] = GFPrior + 0.5 / float(1 + d)
proc gfToIndex(gf: float): int {.inline.} =
clamp(int(round((gf + 1.0) * 0.5 * float(GFBins - 1))), 0, GFBins - 1)
proc indexToGF(idx: int): float {.inline.} =
float(idx) / float(GFBins - 1) * 2.0 - 1.0
proc peakBin(g: GFGun): int =
var best = 0
for i in 1..<GFBins:
if g.bins[i] > g.bins[best]:
best = i
best
proc predict*(g: var GFGun, state: WorldState, bulletSpeed: float): GunPrediction =
if bulletSpeed <= 0.0:
return GunPrediction(x: state.enemyX, y: state.enemyY)
let dx = state.enemyX - state.selfX
let dy = state.enemyY - state.selfY
let dist = sqrt(dx*dx + dy*dy)
let bearing = arctan2(dy, dx)
let mea = arcsin(clamp(8.0 / bulletSpeed, -1.0, 1.0))
# Store one wave per tick regardless of how many power bins call us
if state.tick != g.cachedTick:
g.cachedTick = state.tick
g.cachedWaveStored = false
if not g.cachedWaveStored:
g.waves.add Wave(
fireX: state.selfX,
fireY: state.selfY,
fireBearing: bearing,
)
g.cachedWaveStored = true
let peak = g.peakBin()
let peakGF = indexToGF(peak)
let gfAngle = bearing + peakGF * mea
# Aim from self at gfAngle, at current dist (angular targeting)
let px = state.selfX + cos(gfAngle) * dist
let py = state.selfY + sin(gfAngle) * dist
when DebugGF:
echo fmt"[gf-dbg] predict: peakGF={peakGF:.2f} peakBin={peak} mea={radToDeg(mea):.1f}° aimAngle={radToDeg(gfAngle):.1f}° waves={g.waves.len}"
GunPrediction(
x: clamp(px, BotRadius, state.arenaWidth - BotRadius),
y: clamp(py, BotRadius, state.arenaHeight - BotRadius),
)
proc onResult*(g: var GFGun, e: FeedbackEvent) =
## Called when a virtual bullet resolves. Match the wave by predicted point,
## compute actual GF, and increment the histogram with a smoothing kernel.
## We don't have the original wave tick here, so we use the prediction coords
## to identify and remove the matching wave.
## ponytail: O(n) scan over waves; waves list stays tiny (< a dozen at a time)
if g.waves.len == 0:
return
# Pop the oldest wave (FIFO matches bullet resolution order)
let w = g.waves[0]
g.waves.delete(0)
# Recompute mea from the actual bullet power (correct per-bin, not the cached first-bin mea)
let speed = bulletSpeed(e.bulletPower)
let mea = arcsin(clamp(8.0 / speed, -1.0, 1.0))
# Compute actual bearing from fire position to where the enemy actually was
let actualDx = e.actualX - w.fireX
let actualDy = e.actualY - w.fireY
let actualBearing = arctan2(actualDy, actualDx)
var bearingDelta = actualBearing - w.fireBearing
# Normalize to [-PI, PI]
while bearingDelta > PI: bearingDelta -= 2.0*PI
while bearingDelta < -PI: bearingDelta += 2.0*PI
let gf = if mea > 1e-10: clamp(bearingDelta / mea, -1.0, 1.0) else: 0.0
let centerIdx = gfToIndex(gf)
when DebugGF:
echo fmt"[gf-dbg] onResult: fireBearing={radToDeg(w.fireBearing):.1f}° actualBearing={radToDeg(actualBearing):.1f}° delta={radToDeg(bearingDelta):.1f}° MEA={radToDeg(mea):.1f}° GF={gf:.2f} peakBin={centerIdx}"
# Triangular smoothing kernel over adjacent bins
for i in 0..<GFBins:
let dist = abs(i - centerIdx)
g.bins[i] += 1.0 / float(1 + dist)