From 214ab7aac76497c29222cababf2e0e81576a185d Mon Sep 17 00:00:00 2001 From: Hadrian Burkhardt Date: Sat, 24 Oct 2026 20:08:34 +0200 Subject: [PATCH] feat(m1): add replay v1 with verification, determinism gate and status docs --- CHANGELOG.md | 7 + crates/sim/src/lib.rs | 2 + crates/sim/src/replay.rs | 242 ++++++++++++++++++++++++++++++++++ crates/sim/src/state.rs | 20 +++ docs/roadmap.md | 1 + docs/status/autonomous-log.md | 63 +++++++++ docs/status/blocked.md | 36 +++++ 7 files changed, 371 insertions(+) create mode 100644 crates/sim/src/replay.rs create mode 100644 docs/status/autonomous-log.md create mode 100644 docs/status/blocked.md diff --git a/CHANGELOG.md b/CHANGELOG.md index f8af4a6..16e4e40 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,13 @@ Alle nennenswerten Änderungen an diesem Projekt. Format nach ## [Unreleased] ### Added +- (m0) Cargo-Workspace mit `sim`, `content`, `ffi`, `server`, `balance`; `tools/ci.sh` +- (m0) Flutter-App mit `targetSdk 36`, `minSdk 24`, NDK 28.2; `tools/build_rust_android.sh` inkl. 16-KB-Check +- (sim) Q16.16-Fixed-Point, eingecheckte Sinus-LUT, PCG32 mit gepinnter Referenzsequenz +- (sim) Heightmap-Terrain mit Kratern, Materialien und beidseitigem Sand-Kollaps +- (sim) Match-State mit Zuegen, Timer, Ballistik, Schaden, Lava und Sudden Death +- (sim) FNV-1a-State-Hash und Replay v1 inkl. Verifikation durch Re-Simulation + - Projektkonventionen: `.gitignore`, `.gitattributes`, `.editorconfig` - `README.md` mit Stack (R1 + R3), Repo-Map, Doku-Index und offenen Entscheidungen - `docs/GDD.md`: Game Design Document (14 Kapitel, MVP-1/2/3-Scope) diff --git a/crates/sim/src/lib.rs b/crates/sim/src/lib.rs index e422c7b..657c669 100644 --- a/crates/sim/src/lib.rs +++ b/crates/sim/src/lib.rs @@ -13,6 +13,8 @@ extern crate alloc; pub mod fixed; pub mod hash; +#[cfg(feature = "serde")] +pub mod replay; pub mod rng; pub mod state; pub mod terrain; diff --git a/crates/sim/src/replay.rs b/crates/sim/src/replay.rs new file mode 100644 index 0000000..9322b29 --- /dev/null +++ b/crates/sim/src/replay.rs @@ -0,0 +1,242 @@ +//! Replay format v1 (see docs/protocol.md). +//! +//! A replay is the complete proof of a match: seed, loadouts, timestamped +//! commands and the resulting state hash. + +use alloc::format; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; + +use serde::{Deserialize, Serialize}; + +use crate::state::{Command, Sim, TankSpec}; +use crate::terrain::WORLD_W; +use crate::SIM_VERSION; + +/// Loadout of one player. +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] +pub struct PlayerLoadout { + /// Tank identifier (content id). + pub tank: String, + /// Weapon ids in slot order. + pub loadout: [u8; 3], +} + +/// Serialisable command representation. +#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum CommandDto { + /// Fire a weapon. + Fire { angle: u32, power: i32, w: u8 }, + /// Raise the shield. + Shield, + /// End the turn. + EndTurn, +} + +impl CommandDto { + /// Converts a simulation command into its wire form. + pub fn from_command(cmd: Command) -> Self { + match cmd { + Command::Fire { + angle_mdeg, + power, + weapon, + } => CommandDto::Fire { + angle: angle_mdeg, + power, + w: weapon, + }, + Command::Shield => CommandDto::Shield, + Command::EndTurn => CommandDto::EndTurn, + } + } + + /// Converts the wire form back into a simulation command. + pub fn to_command(self) -> Command { + match self { + CommandDto::Fire { angle, power, w } => Command::Fire { + angle_mdeg: angle, + power, + weapon: w, + }, + CommandDto::Shield => Command::Shield, + CommandDto::EndTurn => Command::EndTurn, + } + } +} + +/// One recorded command. +#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)] +pub struct CommandRecord { + /// Tick at which the command was submitted. + pub t: u32, + /// Player index. + pub p: u8, + /// The command itself. + pub c: CommandDto, +} + +/// Replay of a complete match. +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] +pub struct ReplayV1 { + /// Format version. + pub v: u8, + /// Simulation version that produced the replay. + pub sim_version: String, + /// Content hash of the ruleset. + pub content_hash: String, + /// Match seed. + pub seed: u64, + /// Game mode (`ranked`, `async`, `daily`, `hotseat`, `campaign`). + pub mode: String, + /// Player loadouts. + pub players: Vec, + /// Timestamped commands. + pub commands: Vec, + /// Resulting state hash. + pub final_hash: u64, + /// Match length in ticks. + pub duration_ticks: u32, +} + +impl ReplayV1 { + /// Builds a replay from a finished (or in-flight) simulation. + pub fn capture(sim: &Sim, content_hash: &str, mode: &str, duration_ticks: u32) -> Self { + let commands = sim + .recorded_commands() + .iter() + .enumerate() + .map(|(i, (tick, cmd))| CommandRecord { + t: *tick, + p: if i % 2 == 0 { 0 } else { 1 }, + c: CommandDto::from_command(*cmd), + }) + .collect(); + + let players = [ + PlayerLoadout { + tank: "vanguard".to_string(), + loadout: sim.tanks[0].loadout, + }, + PlayerLoadout { + tank: "longshot".to_string(), + loadout: sim.tanks[1].loadout, + }, + ] + .to_vec(); + + Self { + v: 1, + sim_version: SIM_VERSION.to_string(), + content_hash: content_hash.to_string(), + seed: sim.seed, + mode: mode.to_string(), + players, + commands, + final_hash: sim.state_hash(), + duration_ticks, + } + } + + /// Re-simulates the replay and returns the resulting state hash. + pub fn verify(&self) -> Result { + if self.v != 1 { + return Err(format!("unsupported replay version {}", self.v)); + } + if self.sim_version != SIM_VERSION { + return Err(format!( + "sim_version mismatch: replay {} vs server {}", + self.sim_version, SIM_VERSION + )); + } + if self.players.len() != 2 { + return Err(format!("expected 2 players, got {}", self.players.len())); + } + if self.commands.len() > 50_000 { + return Err(format!("too many commands: {}", self.commands.len())); + } + + let specs = [ + TankSpec { + x: 220, + loadout: self.players[0].loadout, + }, + TankSpec { + x: WORLD_W - 220, + loadout: self.players[1].loadout, + }, + ]; + let mut sim = Sim::new(self.seed, specs); + + let mut projected = 0u8; + for (i, rec) in self.commands.iter().enumerate() { + if rec.p != projected { + return Err(format!( + "command {i} by player {} while {} is to move", + rec.p, projected + )); + } + while sim.tick < rec.t { + sim.tick(); + } + sim.submit(rec.c.to_command()) + .map_err(|e| format!("illegal command {i}: {e:?}"))?; + projected = 1 - projected; + } + + while sim.tick < self.duration_ticks { + sim.tick(); + } + Ok(sim.state_hash()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::fixed::from_int; + + fn sample_replay() -> ReplayV1 { + let mut sim = Sim::default_match(4242); + sim.submit(Command::Fire { + angle_mdeg: 45_000, + power: from_int(1), + weapon: 1, + }) + .unwrap(); + for _ in 0..300 { + sim.tick(); + } + ReplayV1::capture(&sim, "b3:test", "hotseat", sim.tick) + } + + #[test] + fn replay_verifies_and_matches_hash() { + let replay = sample_replay(); + assert_eq!(replay.verify().unwrap(), replay.final_hash); + } + + #[test] + fn json_roundtrip_is_stable() { + let replay = sample_replay(); + let json = serde_json::to_string(&replay).unwrap(); + let back: ReplayV1 = serde_json::from_str(&json).unwrap(); + assert_eq!(replay, back); + assert_eq!(serde_json::to_string(&back).unwrap(), json); + } + + #[test] + fn tampering_is_detected() { + let mut replay = sample_replay(); + replay.seed = replay.seed.wrapping_add(1); + assert_ne!(replay.verify().unwrap(), replay.final_hash); + } + + #[test] + fn version_mismatch_is_rejected() { + let mut replay = sample_replay(); + replay.sim_version = "0.0.9".to_string(); + assert!(replay.verify().is_err()); + } +} diff --git a/crates/sim/src/state.rs b/crates/sim/src/state.rs index b00e313..e2286fd 100644 --- a/crates/sim/src/state.rs +++ b/crates/sim/src/state.rs @@ -626,4 +626,24 @@ mod tests { assert_eq!(sim.phase, Phase::Finished); assert!(sim.turn > MAX_TURNS, "turn={}", sim.turn); } + #[test] + fn thousand_seeds_are_reproducible() { + for seed in 0..1000u64 { + let mut a = Sim::default_match(seed); + let mut b = Sim::default_match(seed); + let angle = 30_000 + (seed % 20_000) as u32; + let power = from_ratio(50 + (seed % 50) as i32, 100); + for sim in [&mut a, &mut b] { + sim.submit(Command::Fire { + angle_mdeg: angle, + power, + weapon: 1, + }) + .unwrap(); + } + run(&mut a, 120); + run(&mut b, 120); + assert_eq!(a.state_hash(), b.state_hash(), "seed {seed} diverged"); + } + } } diff --git a/docs/roadmap.md b/docs/roadmap.md index b0a4950..6abff61 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -5,6 +5,7 @@ | Stand | 2026-10-24 | | Aufwand | ~6–7 Wochen (solo, mit KI-Unterstützung) | | Gerätebedarf | ab M3 (Performance), Pflicht in M6 (Abnahme) | +| Status | **M0 ✅ (2026-10-24) · M1 ✅ (2026-10-24)** · M2 als Nächstes | Jeder Meilenstein hat ein **objektiv prüfbares Gate**. Kein Gate, kein Weiter. diff --git a/docs/status/autonomous-log.md b/docs/status/autonomous-log.md new file mode 100644 index 0000000..df7ef4a --- /dev/null +++ b/docs/status/autonomous-log.md @@ -0,0 +1,63 @@ +# Autonomer Arbeitsbericht + +| Feld | Wert | +|---|---| +| Datum | 2026-10-24 | +| Modus | Act Mode, ohne Rückfragen (Nutzer abwesend) | +| Ergebnis | **M0 und M1 vollständig, Gates bestanden** | + +--- + +## Umgebungshinweise (wichtig für die nächste Session) + +- Die **Shell-Integration des Terminals ist defekt**: Befehle werden ausgeführt, aber die Fertigstellung wird nicht erkannt. Workaround: Ausgaben nach `/tmp/*.txt` umleiten und mit dem Datei-Reader prüfen. Ein Neustart des Terminals/der Session behebt das. +- Mehrere Kommandos in *einem* Aufruf werden parallel ausgeführt und können sich bei Heredocs gegenseitig stören. **Regel: ein Schreibvorgang pro Befehl(skette).** +- `flutter config --jdk-dir=/usr/lib/jvm/java-21-openjdk-amd64` ist gesetzt (JDK 25 meiden). +- `PATH` muss `~/Android/Sdk/platform-tools` zuerst enthalten (zwei adb-Binaries vorhanden). + +## M0 — Skeleton & Toolchain (erledigt) + +| Ergebnis | Beleg | +|---|---| +| Cargo-Workspace mit 5 Crates (`sim`, `content`, `ffi`, `server`, `balance`) | `cargo build --workspace` grün (11,5 s) | +| `rust-toolchain.toml` inkl. Android-Targets | Targets installiert | +| Flutter-App (`app/`, `com.ironarc.iron_arc`) | `flutter create`, 27 getrackte Dateien | +| `compileSdk/targetSdk 36`, `minSdk 24`, NDK 28.2 gepinnt | `android/app/build.gradle.kts` | +| Debug-APK baut | `flutter build apk --debug` (100,6 s) | +| Rust-CDylib für 3 ABIs im APK | `lib/arm64-v8a/libffi.so`, `armeabi-v7a`, `x86_64` | +| **16-KB-Page-Size** | alle LOAD-Segmente `0x4000` | +| Build-Skript mit Alignment-Check | `tools/build_rust_android.sh` | +| CI-Gate | `tools/ci.sh` (fmt, clippy -D warnings, Float-Grep, Tests) | + +## M1 — Sim-Kern (erledigt) + +| Modul | Inhalt | +|---|---| +| `fixed.rs` | Q16.16, `mul/div/sqrt/dist`, Trigonometrie über LUT, Floor-Rundung | +| `trig_table.rs` | 1 025 Stützstellen, **eingecheckt** (nicht zur Build-Zeit erzeugt → plattformunabhängig) | +| `rng.rs` | eigener PCG32, gepinnte Referenzsequenz | +| `terrain.rs` | Heightmap (1 024 Samples), 3 Materialien, Krater, beidseitiger Sand-Kollaps | +| `weapons.rs` | 6 Waffen als Datentabelle | +| `state.rs` | Tanks, Züge, Timer, Ballistik, Schaden, Lava, Sudden Death, State-Hash | +| `hash.rs` | FNV-1a-Kette, Testvektoren | +| `replay.rs` | Replay v1 (serde), **Verifikation durch Re-Simulation**, Tamper-Erkennung | + +**Gates** +- 32 Tests grün, davon `thousand_seeds_are_reproducible` (1 000 Seeds, identischer Hash) +- Replay: `verify()` reproduziert `final_hash`; manipulierter Seed ⇒ abweichender Hash +- Clippy `-D warnings` clean, `cargo fmt` angewendet +- Kein `f32`/`f64` in `crates/sim` (per Lint und CI-Grep) + +**Bewusste Vereinfachungen (dokumentiert, nicht vergessen)** +- MIRV teilt sich noch nicht auf (Einzelprojektil). +- Panzer-Ultimates und Panzer-Passivwerte noch nicht implementiert. +- Roller rollt noch nicht bergab; Digger nutzt denselben Krater-Pfad. +- Schaden fällt linear statt quadratisch ab (Balancing-Entscheidung offen). +- Spawn-Positionen fest (220 / WORLD_W-220); Karten-Presets folgen in M2. + +## Nächste Schritte (M2 zuerst) + +1. `crates/content`: serde-Modelle + `content_hash` (blake3), JSON für 2 Panzer und 6 Waffen. +2. Waffen aus `weapons.rs` in Content verschieben (Sim bleibt datengetrieben). +3. `tools/balance`: KI-Heuristik + 100k-Matches-CSV. +4. Danach M3 (Flame-Client) — dafür wird die frb-Integration und das Gerät gebraucht. diff --git a/docs/status/blocked.md b/docs/status/blocked.md new file mode 100644 index 0000000..6a5d804 --- /dev/null +++ b/docs/status/blocked.md @@ -0,0 +1,36 @@ +# Blockiert — was ich ohne dich nicht erledigen kann + +## 1. Gerät (blockiert M3-Abnahme und M6) + +**Was ich brauche:** ein Android-Gerät, das von dieser Umgebung per `adb` erreichbar ist. + +**Vorgehen (Weg A, empfohlen):** +1. Handy/Tablet per USB an deinen PC, USB-Debugging aktivieren. +2. Am PC: `adb devices` → Gerät sichtbar, dann `adb tcpip 5555`. +3. In `~/.ssh/config` beim bestehenden Host: `RemoteForward 5555 :5555`. +4. Bei mir: `adb connect 127.0.0.1:5555` (Port 5037 ist hier bereits belegt!). + +**Damit möglich:** echte Screenshots, `gfxinfo`-Framestats (p50/p90/p99, Jank), Insets/Notch, Rotation, Reconnect, Soak-Tests, arm64-Determinismus-Beweis. + +## 2. Konten (blockiert M6/M7) + +| Konto | Wofür | +|---|---| +| Google Play Console | 12-Tester-Closed-Test (14 Tage), Upload-Key, Data Safety, IARC | +| AdMob | App-ID + Test-Unit-IDs, Mediation | +| Firebase | Projekt, `google-services.json` (nicht im Repo!), Crashlytics/GA4 | + +## 3. Entscheidungen + +| Thema | Auswirkung | Aktueller Default | +|---|---|---| +| Finaler Markenname | `applicationId`, Store-Listing, Icon | IRON ARC / `com.ironarc.iron_arc` | +| Lizenz | `LICENSE`, OSS-Fähigkeit | proprietär (keine Datei) | +| Art-Pipeline | M3-Renderer, Asset-Format | Vektor → PNG-Atlas (Vorschlag) | +| Ads ab MVP-1? | UMP-Consent-Skeleton in M3 | nein (erst M7) | + +## 4. Balancing-Freigaben (kein Blocker, aber Review nötig) + +- Schadensfalloff linear vs. quadratisch. +- MIRV-Aufteilung (3 Sprengkörper) — Designfrage, keine Technik. +- Panzer-Passivwerte (Vanguard +10 % Schild etc.) sind noch nicht implementiert.