#!/usr/bin/env bash
# mp_launch.sh -- launch a 2-node local multiplayer test (FOGDAY.EGG) with the two
# game nodes PINNED TO DISJOINT CPU CORES + the console relay.
#
# WHY THE AFFINITY MATTERS (task #50, 2026-07-15): two Debug btl4 nodes on one box
# fight for the same cores, and Windows punishes the contention by BATCHING their
# TCP packet delivery -- update records that should arrive every ~17ms instead
# arrive in bursts (measured gaps up to 226ms, burstiness 3-7x, BT_RXJIT).  A peer
# dead-reckons across those gaps and then snaps when a record finally lands -> the
# "random" shaky peer motion.  Pinning each node to its own core set restores even
# ~17ms delivery (burstiness ~1.0) and the shakiness vanishes.  This is a SINGLE-BOX
# TEST-RIG artifact -- real pods are dedicated machines and never see it; do NOT
# "fix" it in the game with an interpolation buffer.
#
# Usage:  tools/mp_launch.sh [extra env for BOTH nodes...]
#   e.g.  tools/mp_launch.sh BT_SLIDE=1
# Run from the repo root; content/ must hold FOGDAY.EGG and the build in build/Debug.
set -u
cd "$(dirname "$0")/../content" || exit 1
EXE=../build/Debug/btl4.exe
EXTRA="$*"

powershell -NoProfile -Command "Get-Process btl4,python -ErrorAction SilentlyContinue | Stop-Process -Force" 2>/dev/null
sleep 2
rm -f fa.log fb.log console.log

env $EXTRA BT_DEV_GAUGES=1 BT_LOG=fb.log BT_START_INSIDE=1 BT_SPAWN_AT="40 -150"  "$EXE" -egg FOGDAY.EGG -net 1601 &
sleep 2
env $EXTRA BT_DEV_GAUGES=1 BT_LOG=fa.log BT_START_INSIDE=1 BT_SPAWN_AT="-40 -150" "$EXE" -egg FOGDAY.EGG -net 1501 &
sleep 3

# Pin the two nodes to disjoint core sets (0x00F = cores 0-3, 0x3C0 = cores 6-9).
powershell -NoProfile -Command "\$ps=@(Get-Process btl4 | Sort-Object Id); if(\$ps.Count -ge 2){ \$ps[0].ProcessorAffinity=[IntPtr]0x00F; \$ps[1].ProcessorAffinity=[IntPtr]0x3C0; Write-Output ('PINNED '+\$ps[0].Id+'->cores0-3, '+\$ps[1].Id+'->cores6-9') } else { Write-Output ('WARN only '+\$ps.Count+' btl4 up') }"

sleep 6
python -u ../tools/btconsole.py FOGDAY.EGG 127.0.0.1:1501 127.0.0.1:1601 > console.log 2>&1 &
echo "console streaming; nodes on 1501/1601. Logs: content/fa.log content/fb.log"
wait
