diff --git a/services/flysim/crates/flybrain-gb/README.md b/services/flysim/crates/flybrain-gb/README.md index 07b8555..22e83b7 100644 --- a/services/flysim/crates/flybrain-gb/README.md +++ b/services/flysim/crates/flybrain-gb/README.md @@ -17,7 +17,7 @@ ROM bytes -> Emulator::run_frame -> RGBA frame + PCM + WRAM | `emulator` | Safe wrapper over binjgb: frames, framebuffer, buttons, WRAM, audio, save states, ROM hash | | `image` | The boundary memory image (`read_memory_image`), the `Cartridge` and `ImageReader`, which runs the macros and adapters over an image instead of a live emulator (MEM-01) | | `adapter` | `GameAdapter`, `RewardEvent`, `ProgressSnapshot`, `MemoryReader`, `adapter_for` | -| `pokemon_red` | The `pokered-unique8-v7` reward adapter, its catalog and its generated symbol table | +| `pokemon_red` | The `pokered-unique8-v8` reward adapter, its catalog and its generated symbol table | | `platformer` | The `sml-progress-v1` Super Mario Land adapter, its catalog and its RAM map | | `ratchet` | The progress ratchet, generic over the adapter's rank and its `RecoveryPolicy` | | `recovery` | Rolling the game back to the ratchet's best safe snapshot | diff --git a/services/flysim/crates/flybrain-gb/src/adapter.rs b/services/flysim/crates/flybrain-gb/src/adapter.rs index ef83db6..d1d75f8 100644 --- a/services/flysim/crates/flybrain-gb/src/adapter.rs +++ b/services/flysim/crates/flybrain-gb/src/adapter.rs @@ -57,7 +57,7 @@ impl MemoryReader for &mut dyn MemoryReader { /// /// `kind` is an adapter-owned interned name (Pokémon: `milestone`, /// `exploration`, `map`, `species`, `trainer`, `battle`, `badge`, `boundary`, `catch`, -/// `talk`, `item`); it is the key the statistics counters and the on-screen ticker group +/// `talk`, `item`, `damage`); it is the key the statistics counters and the on-screen ticker group /// by. Field names serialize exactly as the prototype's `RewardEvent` did, so a /// checkpoint written by either implementation reads in the other. #[derive(Debug, Clone, PartialEq, Serialize)] @@ -241,7 +241,7 @@ impl std::error::Error for AdapterError {} /// A game, as the sim loop sees it. pub trait GameAdapter: Send { /// Adapter version string, pinned into the checkpoint compatibility string. - /// Pokémon: `pokered-unique8-v7`. + /// Pokémon: `pokered-unique8-v8`. fn id(&self) -> &'static str; /// Earlier [`GameAdapter::id`]s whose checkpoints this build can read, by a migration diff --git a/services/flysim/crates/flybrain-gb/src/compatibility.rs b/services/flysim/crates/flybrain-gb/src/compatibility.rs index 3b01985..cef747b 100644 --- a/services/flysim/crates/flybrain-gb/src/compatibility.rs +++ b/services/flysim/crates/flybrain-gb/src/compatibility.rs @@ -30,7 +30,7 @@ pub const PROTOTYPE_PLASTICITY_VERSION: &str = "fly-kc-mbon-rstdp-v2"; pub struct Compatibility<'a> { /// `kernelVersion(config)` from the neural library. pub neural_kernel_version: &'a str, - /// The adapter's version string, e.g. `pokered-unique8-v7`. + /// The adapter's version string, e.g. `pokered-unique8-v8`. pub adapter: &'a str, /// The dataset's seven SHA-256 digests joined with `:`. pub dataset_fingerprint: &'a str, @@ -78,7 +78,7 @@ const ADAPTER_SEGMENT: usize = 1; /// The environment variable that opts a deploy into the adapter migration. /// /// Read by flysim at restore and by `infra/05-deploy.sh`'s compatibility gate. Comma- or -/// whitespace-separated adapter ids, e.g. `FLY_ACCEPT_ADAPTERS=pokered-unique8-v6`. +/// whitespace-separated adapter ids, e.g. `FLY_ACCEPT_ADAPTERS=pokered-unique8-v7`. pub const ACCEPT_ADAPTERS_ENV: &str = "FLY_ACCEPT_ADAPTERS"; /// What a build may do with a checkpoint whose compatibility string is not its own. @@ -180,7 +180,7 @@ mod tests { assert_eq!( fixture().prototype_string(), concat!( - "lif-1ms-f64-v2/pokered-unique8-v7/aa:bb:cc:dd:ee:ff:00/", + "lif-1ms-f64-v2/pokered-unique8-v8/aa:bb:cc:dd:ee:ff:00/", "fly-kc-mbon-rstdp-v2/", "binjgb:c60e138da5a795ebb55e56b11b7e90024e41112c/", "pokered:0cd19d3b877b7dc66d12c7050bed9a7f38154d4b", @@ -194,10 +194,43 @@ mod tests { #[test] fn an_identical_string_restores_without_any_opt_in() { - let current = with_adapter("pokered-unique8-v7"); + let current = with_adapter("pokered-unique8-v8"); assert_eq!(decide(¤t, ¤t, &[], &[]), RestoreDecision::Exact); } + #[test] + fn a_v7_checkpoint_restores_under_v8_only_with_the_opt_in_and_v6_still_does() { + let new = with_adapter("pokered-unique8-v8"); + let migrates = crate::pokemon_red::MIGRATES_FROM; + for from in ["pokered-unique8-v7", "pokered-unique8-v6"] { + let old = with_adapter(from); + assert!(matches!(decide(&old, &new, migrates, &[]), RestoreDecision::Refuse(_))); + assert_eq!( + decide(&old, &new, migrates, &accepted_adapters(Some(from))), + RestoreDecision::MigrateAdapter { from: from.to_string() } + ); + } + // Naming v7 does not wave a v6 checkpoint through, nor v5 at all. + assert!(matches!( + decide( + &with_adapter("pokered-unique8-v6"), + &new, + migrates, + &accepted_adapters(Some("pokered-unique8-v7")) + ), + RestoreDecision::Refuse(_) + )); + assert!(matches!( + decide( + &with_adapter("pokered-unique8-v5"), + &new, + migrates, + &accepted_adapters(Some("pokered-unique8-v5")) + ), + RestoreDecision::Refuse(_) + )); + } + #[test] fn a_v6_checkpoint_restores_under_v7_only_with_the_opt_in() { let old = with_adapter("pokered-unique8-v6"); diff --git a/services/flysim/crates/flybrain-gb/src/pokemon_red/catalog.rs b/services/flysim/crates/flybrain-gb/src/pokemon_red/catalog.rs index b009c4c..34efd7d 100644 --- a/services/flysim/crates/flybrain-gb/src/pokemon_red/catalog.rs +++ b/services/flysim/crates/flybrain-gb/src/pokemon_red/catalog.rs @@ -1,4 +1,4 @@ -//! The `pokered-unique8-v7` reward catalog. +//! The `pokered-unique8-v8` reward catalog. //! //! A direct port of the prototype's `src/reward/catalog.ts`, including the //! declaration order, which is the order `counts` and `last` serialize in. @@ -23,6 +23,7 @@ pub mod kind { pub const CATCH: &str = "catch"; pub const TALK: &str = "talk"; pub const ITEM: &str = "item"; + pub const DAMAGE: &str = "damage"; } /// What a `catch` of a species this run has already caught pays. @@ -46,7 +47,7 @@ pub struct RewardRule { pub stimulation_ms: u32, } -pub const REWARDS: [RewardRule; 11] = [ +pub const REWARDS: [RewardRule; 12] = [ RewardRule { kind: kind::MILESTONE, label: "Story", @@ -151,6 +152,22 @@ pub const REWARDS: [RewardRule; 11] = [ value: 0.15, stimulation_ms: 120, }, + // The operator's decision of 2026-09-29: pay the fly for the HP its own attack removes from + // the Pokémon it is fighting, so the move that deals damage is worth more than the one that + // does not (row 67: TAIL WHIP 155, BUBBLE 23, TACKLE 0, 29 battles lost). Appended for the + // same reason as every rule since `boundary`. + // + // The value is what one whole enemy Pokémon's max HP pays, paid in proportion as it goes; + // `damage::KO_BONUS` adds 0.05 when the fly's hit knocks out a trainer's Pokémon, and + // `damage::BATTLE_CAP` holds a battle to the 0.50 the `trainer` rule pays for winning one. + // A wild battle is scaled 1, 1/2, 1/3 per (map, species, level) like the wild-KO rule. + RewardRule { + kind: kind::DAMAGE, + label: "Damage", + trigger: "HP the fly's own attack removed in battle, 0.20 per whole Pokémon; +0.05 a trainer's Pokémon knocked out; max 0.50 a battle; wild 1, 1/2, 1/3 per map/species/level", + value: 0.20, + stimulation_ms: 80, + }, ]; /// Position of `kind` in [`REWARDS`], or `None` for an unknown kind. This is @@ -260,6 +277,9 @@ mod tests { assert_eq!(rule(kind::TALK).unwrap().stimulation_ms, 100); assert_eq!(rule(kind::ITEM).unwrap().value, 0.15); assert_eq!(rule(kind::ITEM).unwrap().stimulation_ms, 120); + // Nor this: the operator's damage rule, `pokered-unique8-v8`. + assert_eq!(rule(kind::DAMAGE).unwrap().value, 0.20); + assert_eq!(rule(kind::DAMAGE).unwrap().stimulation_ms, 80); assert!(rule("blackout").is_none(), "the catalog has no penalties"); assert!(REWARDS.iter().all(|rule| rule.value > 0.0)); } @@ -281,9 +301,10 @@ mod tests { kind::CATCH, kind::TALK, kind::ITEM, + kind::DAMAGE, ] ); - assert_eq!(index(kind::ITEM), Some(REWARDS.len() - 1)); + assert_eq!(index(kind::DAMAGE), Some(REWARDS.len() - 1)); } #[test] diff --git a/services/flysim/crates/flybrain-gb/src/pokemon_red/damage.rs b/services/flysim/crates/flybrain-gb/src/pokemon_red/damage.rs new file mode 100644 index 0000000..0a092f5 --- /dev/null +++ b/services/flysim/crates/flybrain-gb/src/pokemon_red/damage.rs @@ -0,0 +1,447 @@ +//! What the damage rule of `pokered-unique8-v8` reads: HP the fly's own attack removed from the +//! Pokémon it is fighting. +//! +//! The operator's decision of 2026-09-29 (`docs/rewards-learning.md`, "Damage rewards"), chosen +//! over a pad rule that would have withheld a stat move once it had been used. Row 67 +//! (`infra/docs/macros-traps.md`) is the reason: the live fly lost the Pewter Gym's Jr. Trainer 29 +//! times running with TAIL WHIP 155, BUBBLE 23, TACKLE 0, and nothing in the catalog paid for +//! anything that happened inside a battle it did not win. This rule pays for the attack that lands, +//! so the move that deals damage is worth more than the one that does not, in the battle where the +//! choice is made. +//! +//! Everything here is a read of game memory after a frame. Nothing chooses, biases or presses a +//! button: which moves are on the pad is still the scene's (`docs/design/macros.md`), and which one +//! is pressed is still the fly's. +//! +//! ## What counts as the fly's attack +//! +//! A drop in `wEnemyMonHP` on a sample where `hWhoseTurn` reads 0 (the player's side is acting) +//! and `wPlayerMoveNum` is not `STRUGGLE`. At the pinned commit (`engine/battle/core.asm`): +//! +//! - `ApplyDamageToEnemyPokemon` subtracts `wDamage` from `wEnemyMonHP` inside +//! `ExecutePlayerMove`, with `hWhoseTurn` 0. Multi-hit moves subtract once per hit. +//! - the enemy's poison and burn ticks and a Leech Seed on the enemy are +//! `HandlePoisonBurnLeechSeed`, which picks the enemy's HP *because* `hWhoseTurn` is 1; +//! the enemy's recoil, its confusion self-hit, its own Explosion and a Substitute it makes +//! all happen in `ExecuteEnemyMove`, with `hWhoseTurn` 1. None of them pays. +//! - a Leech Seed on the *player* heals the enemy on the player's turn: HP goes up, which never +//! pays (below). Damage into an enemy Substitute is `AttackSubstitute`, which never touches +//! `wEnemyMonHP`. +//! - `STRUGGLE` is the move the cartridge executes for a Pokémon with no PP. The fly chose FIGHT, +//! not the move, so it is not paid for; winning still pays what winning pays. +//! +//! ## What cannot be farmed +//! +//! - **Heal.** Each target keeps its lowest HP this battle; only HP below that pays. A Potion, +//! Recover, Rest or a drain lifts the HP and the same HP is not paid twice. +//! - **Switch.** A target is `(wEnemyMonPartyPos, species, level)`, so a trainer's Pokémon that +//! goes out and comes back keeps its mark, and two Weedles of one level are two targets. A +//! target is marked the first time it reads full HP, which is how every enemy Pokémon enters a +//! battle in this game, so a stale `wEnemyMon` left over from the last battle neither pays nor +//! hides the real Pokémon's first hit. +//! - **The battle.** At most [`BATTLE_CAP`] a battle, whatever the party size. +//! - **Wild Pokémon.** A wild battle pays at the scale the wild-KO rule uses -- 1, 1/2, 1/3 -- +//! for its first three battles per `(map, species, level)` that paid any damage, and nothing +//! after, and a rollback blocks every key that has paid. Trainer battles have no such ledger: +//! a trainer is only fought again after losing to it (or a rollback), and the per-battle cap +//! bounds each of those. + +use serde_json::{Value, json}; + +use crate::adapter::MemoryReader; + +use super::state::poke; +use super::symbols::ram; + +/// What a trainer's Pokémon knocked out by the fly's own hit adds to that hit. +/// +/// The damage share of the knockout hit is already paid; this is the step "one of the trainer's +/// Pokémon is down", on the frame it happens. Trainer battles only: a wild knockout is the +/// `battle` rule's, paid on the way out of the battle. +pub const KO_BONUS: f64 = 0.05; + +/// The most damage pays in one battle: the `trainer` rule's own 0.50, so that a battle's worth +/// of damage is worth what winning it is. The Pewter Gym's Jr. Trainer (two Pokémon) reaches it +/// exactly: 2 x (0.20 + 0.05). +pub const BATTLE_CAP: f64 = 0.50; + +/// Wild battles per `(map, species, level)` that may pay damage, for the lifetime of the ledger: +/// the wild-KO rule's three, for the same reason. +pub const MAX_WILD_BATTLES: u64 = 3; + +/// The sanity bound the adapter already applies to an enemy's max HP (`sample`'s wild-KO read): +/// the largest in the game is under 1000, so anything else is a byte read out of a battle that +/// is not set up yet. +const MAX_HP_BOUND: u16 = 1000; + +/// One enemy Pokémon, as far as a battle can tell them apart. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Target { + /// `wEnemyMonPartyPos`: the enemy party slot (`$ff` before a trainer's first send-out). + pub slot: u8, + pub species: u8, + pub level: u8, +} + +/// The bytes one sample reads for the rule. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Reading { + pub target: Target, + pub hp: u16, + pub max_hp: u16, + /// `hWhoseTurn` reads 0. + pub fly_turn: bool, + /// `wPlayerMoveNum`. + pub move_id: u8, +} + +impl Reading { + /// Read one sample, or `None` when the enemy's HP is not a readable HP: a max of 0 or past + /// [`MAX_HP_BOUND`], or a current HP above the max -- which is also what the one torn read + /// possible here looks like, `ApplyDamageToEnemyPokemon`'s `sbc` having wrapped below zero + /// before it clamps. + pub fn read(memory: &mut impl MemoryReader) -> Option { + let hp = word(memory, ram::wEnemyMonHP); + let max_hp = word(memory, ram::wEnemyMonMaxHP); + if max_hp == 0 || max_hp >= MAX_HP_BOUND || hp > max_hp { + return None; + } + Some(Self { + target: Target { + slot: memory.read8(ram::wEnemyMonPartyPos), + species: memory.read8(ram::wEnemyMonSpecies), + level: memory.read8(ram::wEnemyMonLevel), + }, + hp, + max_hp, + fly_turn: memory.read8(poke::H_WHOSE_TURN) == 0, + move_id: memory.read8(ram::wPlayerMoveNum), + }) + } +} + +fn word(memory: &mut impl MemoryReader, address: u16) -> u16 { + u16::from(memory.read8(address)) << 8 | u16::from(memory.read8(address + 1)) +} + +/// HP the fly's own attack removed on one sample. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Hit { + pub target: Target, + pub removed: u16, + pub max_hp: u16, + pub knocked_out: bool, +} + +/// One target's mark: its max HP when first seen and the lowest HP it has shown. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +struct Mark { + target: Target, + max_hp: u16, + low: u16, +} + +/// The rule's state for one battle. Carried in the adapter's `battle` (and so in a checkpoint +/// taken mid-battle); a new battle starts with a new one. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct BattleDamage { + marks: Vec, + /// Paid so far this battle, after the wild scale. + paid: f64, + /// The wild scale, decided at the battle's first hit; always 1 in a trainer battle. + scale: Option, + /// A battle restored from a state written before this rule: a target first seen is marked + /// at the HP it has *now*, since what it had lost before the restore is unknown. + restored: bool, +} + +impl BattleDamage { + /// The state for a battle a `v7` checkpoint was taken in. + pub fn restored() -> Self { + Self { restored: true, ..Self::default() } + } + + pub fn paid(&self) -> f64 { + self.paid + } + + pub fn scale(&self) -> Option { + self.scale + } + + /// Update the marks with one sample and say what the fly is owed for, if anything. + /// + /// Every drop moves the mark, whoever caused it, so a poison tick is never paid later as + /// part of the fly's next hit. Only a drop on the fly's own turn, by a move it chose, is a + /// [`Hit`]. + pub fn observe(&mut self, reading: Reading) -> Option { + let index = match self.marks.iter().position(|mark| mark.target == reading.target) { + Some(index) if self.marks[index].max_hp == reading.max_hp => index, + found => { + // Every enemy Pokémon enters a battle at its max HP -- a wild one is generated + // full, a trainer's party is built full -- so a target not yet marked is only + // real once it reads full. Anything else is `wEnemyMon` still holding the last + // battle's Pokémon: `InitBattleVariables` does not clear it, and a trainer + // battle sets `wIsInBattle` a whole transition before `LoadEnemyMonData` runs. + // In the row 67 ring that stale Pokémon is the same trainer's, in the same + // slot, at the HP it beat the fly with. A battle restored from a state without + // this rule cannot know, and marks what it reads. + if !self.restored && reading.hp != reading.max_hp { + return None; + } + let mark = + Mark { target: reading.target, max_hp: reading.max_hp, low: reading.hp }; + match found { + // The same slot, species and level with another max HP is another Pokémon + // (a wild one with other DVs): its mark starts again. + Some(index) => { + self.marks[index] = mark; + index + } + None => { + self.marks.push(mark); + self.marks.len() - 1 + } + } + } + }; + let mark = &mut self.marks[index]; + if reading.hp >= mark.low { + return None; + } + let removed = mark.low - reading.hp; + mark.low = reading.hp; + if !reading.fly_turn || reading.move_id == poke::moves::STRUGGLE { + return None; + } + Some(Hit { + target: reading.target, + removed, + max_hp: reading.max_hp, + knocked_out: reading.hp == 0, + }) + } + + /// Decide the wild scale once per battle. `ledger` is `(battles already paid for this key, + /// whether a rollback blocked it)`; the caller counts the battle when this returns a + /// non-zero scale for the first time. + pub fn decide_scale(&mut self, trainer: bool, ledger: (u64, bool)) -> (f64, bool) { + if let Some(scale) = self.scale { + return (scale, false); + } + let (count, blocked) = ledger; + let scale = if trainer { + 1.0 + } else if blocked || count >= MAX_WILD_BATTLES { + 0.0 + } else { + 1.0 / (count as f64 + 1.0) + }; + self.scale = Some(scale); + (scale, !trainer && scale > 0.0) + } + + /// What `hit` pays: `value` per whole Pokémon's max HP, plus [`KO_BONUS`] for a trainer's + /// Pokémon knocked out, at the battle's scale, within what is left of [`BATTLE_CAP`]. + pub fn pay(&mut self, hit: Hit, value: f64, trainer: bool) -> f64 { + let scale = self.scale.unwrap_or(0.0); + let mut amount = value * f64::from(hit.removed) / f64::from(hit.max_hp); + if trainer && hit.knocked_out { + amount += KO_BONUS; + } + let amount = (amount * scale).min((BATTLE_CAP - self.paid).max(0.0)); + self.paid += amount; + amount + } + + pub fn to_json(&self) -> Value { + json!({ + "paid": self.paid, + "scale": self.scale, + "restored": self.restored, + "marks": self.marks.iter().map(|mark| json!([ + mark.target.slot, mark.target.species, mark.target.level, mark.max_hp, mark.low, + ])).collect::>(), + }) + } + + /// The inverse of [`BattleDamage::to_json`]; `None` for anything malformed. + pub fn from_json(value: &Value) -> Option { + let paid = value.get("paid")?.as_f64().filter(|paid| paid.is_finite() && *paid >= 0.0)?; + let scale = match value.get("scale") { + None | Some(Value::Null) => None, + Some(scale) => Some(scale.as_f64().filter(|scale| (0.0..=1.0).contains(scale))?), + }; + let restored = value.get("restored")?.as_bool()?; + let byte = |value: &Value| value.as_u64().and_then(|v| u8::try_from(v).ok()); + let hp = |value: &Value| value.as_u64().and_then(|v| u16::try_from(v).ok()); + let marks = value + .get("marks")? + .as_array()? + .iter() + .map(|mark| { + let mark = mark.as_array().filter(|mark| mark.len() == 5)?; + Some(Mark { + target: Target { + slot: byte(&mark[0])?, + species: byte(&mark[1])?, + level: byte(&mark[2])?, + }, + max_hp: hp(&mark[3])?, + low: hp(&mark[4])?, + }) + }) + .collect::>>()?; + Some(Self { marks, paid, scale, restored }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const DIGLETT: Target = Target { slot: 0, species: 0x3b, level: 11 }; + const SANDSHREW: Target = Target { slot: 1, species: 0x60, level: 11 }; + const BUBBLE: u8 = 145; + const TACKLE: u8 = 33; + + fn fly(target: Target, hp: u16, max_hp: u16, move_id: u8) -> Reading { + Reading { target, hp, max_hp, fly_turn: true, move_id } + } + + fn enemy(target: Target, hp: u16, max_hp: u16) -> Reading { + Reading { target, hp, max_hp, fly_turn: false, move_id: BUBBLE } + } + + #[test] + fn a_drop_on_the_flys_turn_is_a_hit_and_one_on_the_enemys_is_not() { + let mut battle = BattleDamage::default(); + assert_eq!(battle.observe(fly(DIGLETT, 31, 31, BUBBLE)), None, "full HP is the mark"); + let hit = battle.observe(fly(DIGLETT, 20, 31, BUBBLE)).unwrap(); + assert_eq!((hit.removed, hit.knocked_out), (11, false)); + // The enemy's own poison tick: the mark moves, nothing is owed. + assert_eq!(battle.observe(enemy(DIGLETT, 18, 31)), None); + // ... so the next hit is paid from 18, not from 20. + assert_eq!(battle.observe(fly(DIGLETT, 12, 31, TACKLE)).unwrap().removed, 6); + // The same HP on the next sample is not a second hit. + assert_eq!(battle.observe(fly(DIGLETT, 12, 31, TACKLE)), None); + } + + #[test] + fn struggle_is_not_the_flys_choice_and_pays_nothing() { + let mut battle = BattleDamage::default(); + battle.observe(fly(DIGLETT, 31, 31, BUBBLE)); + assert_eq!(battle.observe(fly(DIGLETT, 25, 31, poke::moves::STRUGGLE)), None); + assert_eq!(battle.observe(fly(DIGLETT, 20, 31, BUBBLE)).unwrap().removed, 5); + } + + #[test] + fn healed_hp_is_not_paid_twice() { + let mut battle = BattleDamage::default(); + battle.observe(fly(DIGLETT, 31, 31, BUBBLE)); + assert_eq!(battle.observe(fly(DIGLETT, 10, 31, BUBBLE)).unwrap().removed, 21); + // A Super Potion on the trainer's turn, or a drain on the fly's: up is never paid. + assert_eq!(battle.observe(enemy(DIGLETT, 31, 31)), None); + assert_eq!(battle.observe(fly(DIGLETT, 31, 31, BUBBLE)), None); + // Down to 15 again is ground already paid for; 15 to 4 is new. + assert_eq!(battle.observe(fly(DIGLETT, 15, 31, BUBBLE)), None); + let hit = battle.observe(fly(DIGLETT, 0, 31, BUBBLE)).unwrap(); + assert_eq!((hit.removed, hit.knocked_out), (10, true)); + } + + #[test] + fn a_switch_keeps_each_targets_mark() { + let mut battle = BattleDamage::default(); + battle.observe(fly(DIGLETT, 31, 31, BUBBLE)); + battle.observe(fly(DIGLETT, 16, 31, BUBBLE)); + // Sandshrew comes out: a new target, marked at its max. + assert_eq!(battle.observe(enemy(SANDSHREW, 33, 33)), None); + assert_eq!(battle.observe(fly(SANDSHREW, 30, 33, TACKLE)).unwrap().removed, 3); + // Diglett comes back at the 16 it left with: nothing new until it goes below. + assert_eq!(battle.observe(enemy(DIGLETT, 16, 31)), None); + assert_eq!(battle.observe(fly(DIGLETT, 10, 31, BUBBLE)).unwrap().removed, 6); + // Two Pokémon of one species and level in different slots are two targets. + let twin = Target { slot: 2, ..DIGLETT }; + assert_eq!(battle.observe(enemy(twin, 31, 31)), None); + assert_eq!(battle.observe(fly(twin, 21, 31, BUBBLE)).unwrap().removed, 10); + } + + #[test] + fn a_stale_enemy_from_the_last_battle_cannot_pay_or_hide_the_real_one() { + // The first in-battle samples can still hold the last battle's Pokémon at the HP it + // finished on -- in the row 67 ring, the same trainer's Diglett in the same slot. It is + // not marked until it reads full, so neither it nor the real Diglett's first hit is lost. + let mut battle = BattleDamage::default(); + assert_eq!(battle.observe(enemy(DIGLETT, 7, 31)), None); + assert_eq!(battle.observe(fly(DIGLETT, 3, 31, BUBBLE)), None, "not marked: not paid"); + assert_eq!(battle.observe(enemy(DIGLETT, 31, 31)), None, "the real one loads full"); + assert_eq!(battle.observe(fly(DIGLETT, 20, 31, BUBBLE)).unwrap().removed, 11); + // The same identity with another max HP is another Pokémon: its mark starts again. + assert_eq!(battle.observe(fly(DIGLETT, 29, 29, BUBBLE)), None); + assert_eq!(battle.observe(fly(DIGLETT, 19, 29, BUBBLE)).unwrap().removed, 10); + } + + #[test] + fn a_battle_restored_without_the_rule_marks_targets_where_they_stand() { + let mut battle = BattleDamage::restored(); + assert_eq!(battle.observe(fly(DIGLETT, 12, 31, BUBBLE)), None, "12/31 is the mark"); + assert_eq!(battle.observe(fly(DIGLETT, 5, 31, BUBBLE)).unwrap().removed, 7); + } + + #[test] + fn a_trainer_battle_pays_the_share_plus_the_knockout_and_stops_at_the_cap() { + let mut battle = BattleDamage::default(); + assert_eq!(battle.decide_scale(true, (99, true)), (1.0, false), "no ledger for trainers"); + let value = 0.20; + battle.observe(fly(DIGLETT, 31, 31, BUBBLE)); + let hit = battle.observe(fly(DIGLETT, 0, 31, BUBBLE)).unwrap(); + assert!((battle.pay(hit, value, true) - 0.25).abs() < 1e-12, "0.20 + the 0.05 knockout"); + battle.observe(fly(SANDSHREW, 33, 33, BUBBLE)); + let hit = battle.observe(fly(SANDSHREW, 0, 33, BUBBLE)).unwrap(); + assert!((battle.pay(hit, value, true) - 0.25).abs() < 1e-12); + assert!((battle.paid() - BATTLE_CAP).abs() < 1e-12, "two Pokémon reach the cap"); + let third = Target { slot: 2, ..SANDSHREW }; + battle.observe(fly(third, 33, 33, BUBBLE)); + let hit = battle.observe(fly(third, 0, 33, BUBBLE)).unwrap(); + assert_eq!(battle.pay(hit, value, true), 0.0, "a third pays nothing"); + } + + #[test] + fn a_wild_battle_pays_one_half_one_third_then_nothing() { + let value = 0.20; + let mut paid = Vec::new(); + for count in 0..4 { + let mut battle = BattleDamage::default(); + let (scale, counted) = battle.decide_scale(false, (count, false)); + assert_eq!(counted, count < MAX_WILD_BATTLES); + battle.observe(fly(DIGLETT, 31, 31, TACKLE)); + let hit = battle.observe(fly(DIGLETT, 0, 31, TACKLE)).unwrap(); + paid.push(battle.pay(hit, value, false)); + assert_eq!(battle.decide_scale(false, (0, false)).0, scale, "decided once a battle"); + } + assert!((paid[0] - 0.20).abs() < 1e-12, "no knockout bonus in the wild: {paid:?}"); + assert!((paid[1] - 0.10).abs() < 1e-12); + assert!((paid[2] - 0.20 / 3.0).abs() < 1e-12); + assert_eq!(paid[3], 0.0); + let mut blocked = BattleDamage::default(); + assert_eq!(blocked.decide_scale(false, (0, true)), (0.0, false), "a rollback blocks it"); + } + + #[test] + fn the_battle_state_round_trips() { + let mut battle = BattleDamage::default(); + battle.decide_scale(false, (1, false)); + battle.observe(fly(DIGLETT, 31, 31, BUBBLE)); + let hit = battle.observe(fly(DIGLETT, 20, 31, BUBBLE)).unwrap(); + battle.pay(hit, 0.2, false); + let back = BattleDamage::from_json(&battle.to_json()).unwrap(); + assert_eq!(back, battle); + assert!(BattleDamage::from_json(&json!({ "paid": -1.0 })).is_none()); + assert!( + BattleDamage::from_json(&json!({ + "paid": 0.0, "scale": null, "restored": false, "marks": [[0, 1, 2, 3]] + })) + .is_none() + ); + } +} diff --git a/services/flysim/crates/flybrain-gb/src/pokemon_red/mod.rs b/services/flysim/crates/flybrain-gb/src/pokemon_red/mod.rs index 2d6b390..b8f533f 100644 --- a/services/flysim/crates/flybrain-gb/src/pokemon_red/mod.rs +++ b/services/flysim/crates/flybrain-gb/src/pokemon_red/mod.rs @@ -1,4 +1,4 @@ -//! The Pokémon Red reward adapter, `pokered-unique8-v7`. +//! The Pokémon Red reward adapter, `pokered-unique8-v8`. //! //! A port of the prototype's `src/reward/pokemon-red.ts`. The gates and budgets //! are unchanged; `docs/rewards-learning.md` holds the live rule table and the @@ -8,9 +8,11 @@ //! next to and the first step onto each of a map's exits; v6 adds `catch`, the //! operator's decision of 2026-09-22, which pays for keeping a wild Pokémon; v7 adds //! `talk` and `item` and stops `boundary` paying indoors, the operator's decision of -//! 2026-09-23 to pay for engaging with a building rather than for leaving it. +//! 2026-09-23 to pay for engaging with a building rather than for leaving it; v8 adds `damage`, +//! the operator's decision of 2026-09-29 to pay for the HP the fly's own attack removes. pub mod catalog; +pub mod damage; pub mod engage; #[cfg(test)] pub(crate) mod fake_wram; @@ -36,7 +38,15 @@ use symbols::ram; /// Adapter version, pinned into the checkpoint compatibility string. /// -/// `v7` is the engagement rules: `talk` and `item` pay, and `boundary` stops paying on an +/// `v8` is the damage rule (the operator, 2026-09-29): HP the fly's own attack removes from the +/// Pokémon it is fighting pays, in proportion, within a per-battle cap ([`damage`]). A `v7` +/// checkpoint is refused by default and resumed only when the operator names it in +/// `FLY_ACCEPT_ADAPTERS`, like every migration before it. `v7`'s state is a `v8` state with no +/// `damageCounts` (no wild key has paid damage) and, for a battle in flight, no per-battle damage +/// state: that battle marks each enemy Pokémon at the HP it has when first read, so nothing lost +/// before the restore is paid ([`damage::BattleDamage::restored`]). +/// +/// `v7` was the engagement rules: `talk` and `item` pay, and `boundary` stops paying on an /// indoor map (the operator, 2026-09-23). Bumping it is what makes a `v6` checkpoint a /// decision rather than an accident: the compatibility string is compared whole before a /// restore is attempted, so a `v6` run is refused by default and resumed only when the @@ -53,11 +63,17 @@ use symbols::ram; /// that meant "4 badges" on the old ladder is not a rung on the new one. Neither of /// those is a migration; the last two are, because nothing an older ledger holds means /// something different under the newer rules.) -pub const REWARD_ADAPTER: &str = "pokered-unique8-v7"; +pub const REWARD_ADAPTER: &str = "pokered-unique8-v8"; -/// Adapter ids whose checkpoints `v7` can read. +/// Adapter ids whose checkpoints `v8` can read. /// -/// Exactly one, and it is one because the engagement rules add ledger keys and change nothing +/// `v7`, the live run's, by the migration [`REWARD_ADAPTER`] describes. And still `v6`: the +/// chain composes, because nothing in `v8` reads a key `v7` wrote that a `v6` state lacks other +/// than the ones `v7`'s own migration already handles in this build -- the item seed runs on the +/// first sample that finds `items:seeded` absent, and the damage state starts empty either way. +/// `compat_migration.rs` restores a `v6` envelope and a `v7` envelope under this build. +/// +/// (For `v7` the list was `v6` alone, and the reason it was one:) the engagement rules add ledger keys and change nothing /// else a `v6` state holds: every field keeps its name, shape and meaning, the `talk:` keys start /// empty (no conversation was ever paid), and the `item:`/`hidden:` keys are seeded from the /// game's own flags on the first sample, so no pickup made under `v6` pays when a rollback @@ -68,7 +84,7 @@ pub const REWARD_ADAPTER: &str = "pokered-unique8-v7"; /// /// Listing an id here is necessary but not sufficient: `FLY_ACCEPT_ADAPTERS` must name it too /// (`crate::compatibility::decide`, `docs/design/flysim.md`). -pub const MIGRATES_FROM: &[&str] = &["pokered-unique8-v6"]; +pub const MIGRATES_FROM: &[&str] = &["pokered-unique8-v7", "pokered-unique8-v6"]; /// The only cartridge semantic rewards are enabled for. Even the canonical /// pret build stays disabled until reviewed; see `docs/rewards-learning.md`. @@ -102,6 +118,11 @@ pub const SUPPORTED_ROM: &str = /// *Not* bumped for the engagement rules either. `talk` and `item` key their payouts into the /// existing `seen` array, the way `boundary` did, and the item seed is marked there too /// ([`ITEMS_SEEDED`]); a `v6` state is structurally a `v7` state with none of those keys. +/// +/// *Not* bumped for the damage rule. It adds one optional counter, `damageCounts`, and one +/// optional object inside a battle in flight, `battle.damage`; a `v7` state without them restores +/// with the counter empty and the battle marked where it stands, which is the truth about a run +/// that was never paid for damage. pub const STATE_VERSION: u64 = 4; /// The `seen` key that says the item keys have been seeded from the cartridge's flags. @@ -374,7 +395,7 @@ fn rung_place(seen: &OrderedSet, rung: usize) -> Option { } } -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq)] struct Battle { key: String, wild: bool, @@ -400,6 +421,8 @@ struct Battle { /// Whether that catch was a species this run had never owned, decided on the frame /// the capture was observed. captured_new: bool, + /// The damage rule's marks and what this battle has paid ([`damage::BattleDamage`]). + damage: damage::BattleDamage, } /// Immutable per-sample byte cache. Each address requested during one sample @@ -449,6 +472,9 @@ pub struct PokemonRedReward { /// string. The one field `v6` adds to the checkpoint; absent in a `v5` state, which /// reads as every species at zero. catch_counts: BTreeMap, + /// Wild battles that paid damage, per wild key (`map:species:level`, the wild-KO rule's). The + /// one field `v8` adds to the checkpoint; absent in a `v7` state, which reads as none. + damage_counts: BTreeMap, replay_blocked: OrderedSet, counts: Counts, total: f64, @@ -507,6 +533,7 @@ impl PokemonRedReward { tile_counts: BTreeMap::new(), wild_wins: BTreeMap::new(), catch_counts: BTreeMap::new(), + damage_counts: BTreeMap::new(), replay_blocked: OrderedSet::new(), counts: Counts::default(), total: 0.0, @@ -676,6 +703,10 @@ impl PokemonRedReward { for species in caught { self.replay_blocked.insert(&format!("catch:{species}")); } + let damaged: Vec = self.damage_counts.keys().cloned().collect(); + for key in damaged { + self.replay_blocked.insert(&format!("damage:{key}")); + } } /// Sample WRAM after one completed frame and return this frame's payouts. @@ -800,6 +831,7 @@ impl PokemonRedReward { species_at_start: Some(species_paid), captured: None, captured_new: false, + damage: damage::BattleDamage::default(), }); } // The cartridge's own answer to "was one caught": `ram/wram.asm`'s comment on @@ -831,6 +863,9 @@ impl PokemonRedReward { battle.species_at_start.is_some_and(|before| species_paid > before); } } + if in_battle != 255 { + self.damage(&mut emitted, memory, in_battle == 2, brain_ms); + } } else if in_battle == 0 { self.mode = "OVERWORLD".to_string(); if let Some(battle) = self.battle.take() { @@ -985,6 +1020,39 @@ impl PokemonRedReward { emitted } + /// The damage rule (`docs/rewards-learning.md`, the operator 2026-09-29): pay for the HP the + /// fly's own attack removed from the enemy on this sample. [`damage`] says what counts. + fn damage( + &mut self, + emitted: &mut Vec, + memory: &mut impl MemoryReader, + trainer: bool, + brain_ms: f64, + ) { + let Some(reading) = damage::Reading::read(memory) else { return }; + let Some(battle) = self.battle.as_mut() else { return }; + let Some(hit) = battle.damage.observe(reading) else { return }; + let key = battle.key.clone(); + let count = self.damage_counts.get(&key).copied().unwrap_or(0); + let blocked = self.replay_blocked.contains(&format!("damage:{key}")); + let (_, counted) = battle.damage.decide_scale(trainer, (count, blocked)); + let value = catalog::rule(kind::DAMAGE).expect("the damage rule is in the catalog").value; + let amount = battle.damage.pay(hit, value, trainer); + if counted { + self.damage_counts.insert(key, (count + 1).min(damage::MAX_WILD_BATTLES)); + } + if amount > 0.0 { + let knocked_out = if hit.knocked_out { " KO" } else { "" }; + self.emit_amount( + emitted, + kind::DAMAGE, + format!("HIT #{} FOR {} HP{knocked_out}", hit.target.species, hit.removed), + amount, + brain_ms, + ); + } + } + fn emit( &mut self, emitted: &mut Vec, @@ -1220,6 +1288,8 @@ impl PokemonRedReward { // empty, which is the documented v5 -> v6 migration and the truth about a run // that was never paid for a catch. "catchCounts": self.catch_counts, + // The one field v8 adds, absent in a v7 state for the same reason. + "damageCounts": self.damage_counts, "replayBlocked": self.replay_blocked.as_slice(), "counts": self.counts, "total": self.total, @@ -1243,6 +1313,7 @@ impl PokemonRedReward { "speciesAtStart": battle.species_at_start, "captured": battle.captured, "capturedNew": battle.captured_new, + "damage": battle.damage.to_json(), })), "mode": self.mode, }) @@ -1295,6 +1366,11 @@ impl PokemonRedReward { None | Some(Value::Null) => BTreeMap::new(), Some(value) => counted_record(Some(value)).ok_or(BAD_CHECKPOINT)?, }; + // Absent in every v7 state: no wild key has paid damage, because the rule did not exist. + let damage_counts = match input.get("damageCounts") { + None | Some(Value::Null) => BTreeMap::new(), + Some(value) => counted_record(Some(value)).ok_or(BAD_CHECKPOINT)?, + }; let recent = recent_raw .iter() @@ -1330,6 +1406,12 @@ impl PokemonRedReward { .get("capturedNew") .and_then(Value::as_bool) .unwrap_or(false), + // v8's. A v7 battle has none, and marks each enemy Pokémon at the HP it reads + // next rather than paying for HP lost before the restore. + damage: match value.get("damage") { + None | Some(Value::Null) => damage::BattleDamage::restored(), + Some(state) => damage::BattleDamage::from_json(state).ok_or(BAD_HISTORY)?, + }, }), }; let replay_blocked = match input.get("replayBlocked") { @@ -1356,6 +1438,7 @@ impl PokemonRedReward { self.tile_counts = tile_counts; self.wild_wins = wild_wins_raw; self.catch_counts = catch_counts; + self.damage_counts = damage_counts; self.replay_blocked = replay_blocked.iter().map(String::as_str).collect(); self.counts = Counts::default(); for (key, count) in &counts_raw { diff --git a/services/flysim/crates/flybrain-gb/src/pokemon_red/state.rs b/services/flysim/crates/flybrain-gb/src/pokemon_red/state.rs index b9bcb5f..c39eb72 100644 --- a/services/flysim/crates/flybrain-gb/src/pokemon_red/state.rs +++ b/services/flysim/crates/flybrain-gb/src/pokemon_red/state.rs @@ -50,6 +50,17 @@ pub mod poke { /// reads it back from there (row 63, `docs/design/macros.md` 12.27). pub const H_JOY_LAST: u16 = 0xffb1; + /// `ram/hram.asm`: `hWhoseTurn`, "0 on player's turn, 1 on enemy's turn". Counted from the + /// `hJoyLast` anchor above through the declarations that follow it (each `UNION` at its + /// largest member) to `$FFF3`; the section's remaining nine bytes then end at `$FFFE`, the + /// last byte of HRAM, which is the check that the count is right. It is the classic + /// `H_WHOSETURN`. The battle engine writes it before each side acts (`MainInBattleLoop`, + /// `ExecutePlayerMove`), and `HandlePoisonBurnLeechSeed` reads it to pick whose HP to cut, so + /// the enemy's poison, burn and Leech Seed ticks all land while it reads 1. Read by the damage + /// reward (`docs/rewards-learning.md`) and pinned on the cartridge by + /// `tests/rom_damage.rs`, which reads 0 on the frame BUBBLE lands. + pub const H_WHOSE_TURN: u16 = 0xfff3; + pub mod pad { pub const A: u8 = 1 << 0; pub const B: u8 = 1 << 1; @@ -285,6 +296,10 @@ pub mod poke { pub const ROW_BYTES: u16 = 6; /// `constants/move_constants.asm`: `NUM_ATTACKS`, `STRUGGLE` (`$a5`) the last. pub const LAST_MOVE: u8 = 0xa5; + /// The same constant under its own name: the move the cartridge executes for a + /// Pokémon whose moves have no PP left (`ExecutePlayerMove`'s caller, `MoveSelectionMenu`'s + /// "has no moves left!"). The damage reward does not pay for it: the fly did not choose it. + pub const STRUGGLE: u8 = 0xa5; /// `constants/move_effect_constants.asm`: the stat-stage effects, each run in stage /// order ATTACK, DEFENSE, SPEED, SPECIAL, ACCURACY, EVASION. diff --git a/services/flysim/crates/flybrain-gb/src/pokemon_red/tests.rs b/services/flysim/crates/flybrain-gb/src/pokemon_red/tests.rs index dd43822..8f4e17b 100644 --- a/services/flysim/crates/flybrain-gb/src/pokemon_red/tests.rs +++ b/services/flysim/crates/flybrain-gb/src/pokemon_red/tests.rs @@ -865,8 +865,8 @@ fn the_recent_ticker_keeps_the_newest_eight_events_newest_first() { #[test] fn the_adapter_reports_its_identity_and_pinned_rom() { let reward = PokemonRedReward::new(); - assert_eq!(reward.id(), "pokered-unique8-v7"); - assert_eq!(reward.migrates_from(), ["pokered-unique8-v6"]); + assert_eq!(reward.id(), "pokered-unique8-v8"); + assert_eq!(reward.migrates_from(), ["pokered-unique8-v7", "pokered-unique8-v6"]); assert!(reward.rom_allowed(SUPPORTED_ROM)); assert!(!reward.rom_allowed( "5ca7ba01642a3b27b0cc0b5349b52792795b62d3ed977e98a09390659af96b7b" @@ -1894,3 +1894,272 @@ fn a_warp_is_classified_by_the_header_still_loaded_while_the_map_id_has_moved_on f.memory.set(ram::wCurMap, maps::PEWTER_CITY); assert!(boundary_values(&f.visit(10, 7)).is_empty()); } + +// -- the damage rule (`pokered-unique8-v8`, the operator 2026-09-29) -------------------------- + +/// Move ids from `constants/move_constants.asm`, the three row 67's Squirtle knows. +const TACKLE: u8 = 0x21; +const TAIL_WHIP: u8 = 0x27; +const BUBBLE: u8 = 0x91; +/// `wTrainerClass`-independent: `wIsInBattle` is 2 in a trainer battle, 1 in a wild one. +const TRAINER_BATTLE: u8 = 2; +const WILD_BATTLE: u8 = 1; + +impl Fixture { + /// The enemy battle struct as `LoadEnemyMonData` leaves it: party slot, species, level, HP + /// and max HP (both big-endian words). + fn enemy(&mut self, slot: u8, species: u8, level: u8, hp: u16, max_hp: u16) { + self.memory.set(ram::wEnemyMonPartyPos, slot); + self.memory.set(ram::wEnemyMonSpecies, species); + self.memory.set(ram::wEnemyMonLevel, level); + self.enemy_hp(hp, max_hp); + } + + fn enemy_hp(&mut self, hp: u16, max_hp: u16) { + self.memory.set(ram::wEnemyMonHP, (hp >> 8) as u8); + self.memory.set(ram::wEnemyMonHP + 1, hp as u8); + self.memory.set(ram::wEnemyMonMaxHP, (max_hp >> 8) as u8); + self.memory.set(ram::wEnemyMonMaxHP + 1, max_hp as u8); + } + + /// `hWhoseTurn` and `wPlayerMoveNum` for the side acting, as `ExecutePlayerMove` and + /// `MainInBattleLoop` write them. + fn turn(&mut self, fly: bool, move_id: u8) { + self.memory.set(state::poke::H_WHOSE_TURN, u8::from(!fly)); + self.memory.set(ram::wPlayerMoveNum, move_id); + } + + fn damage_events(&mut self) -> Vec { + self.sample().into_iter().filter(|event| event.kind == kind::DAMAGE).collect() + } +} + +fn values(events: &[RewardEvent]) -> Vec { + events.iter().map(|event| event.value).collect() +} + +fn close(a: f64, b: f64) -> bool { + (a - b).abs() < 1e-12 +} + +/// Row 67's battle: the Jr. Trainer's Diglett (slot 0, $3b, L11, 31 HP) and Sandshrew (slot 1, +/// $60, L11, 33 HP), entered with the *last* battle's Diglett still in `wEnemyMon` at 7 HP. +fn row67_battle() -> Fixture { + let mut f = Fixture::booted(); + f.enemy(0, 0x3b, 11, 7, 31); + f.turn(true, BUBBLE); + f.memory.set(ram::wIsInBattle, TRAINER_BATTLE); + assert!(f.damage_events().is_empty(), "the stale Diglett is not the battle's"); + f.enemy_hp(3, 31); + assert!(f.damage_events().is_empty(), "and nothing it does pays"); + f.enemy(0, 0x3b, 11, 31, 31); + assert!(f.damage_events().is_empty(), "the real Diglett loads full"); + f +} + +#[test] +fn the_flys_own_attack_pays_in_proportion_and_tail_whip_pays_nothing() { + let mut f = row67_battle(); + // TAIL WHIP: no HP moves, whatever the turn. + f.turn(true, TAIL_WHIP); + assert!(f.damage_events().is_empty()); + // BUBBLE lands for 12 of 31. + f.turn(true, BUBBLE); + f.enemy_hp(19, 31); + let hit = f.damage_events(); + assert_eq!(labels(&hit), ["HIT #59 FOR 12 HP"]); + assert!(close(hit[0].value, 0.20 * 12.0 / 31.0)); + assert_eq!(hit[0].stimulation_ms, 80); + // The HP bar animates for a while; the same HP is not paid again. + assert!(f.damage_events().is_empty()); + // TACKLE for 5. + f.turn(true, TACKLE); + f.enemy_hp(14, 31); + assert_eq!(values(&f.damage_events()).len(), 1); + assert_eq!(f.reward.statistics().counts[kind::DAMAGE], 2); +} + +#[test] +fn hp_the_enemy_loses_on_its_own_turn_and_struggle_pay_nothing() { + let mut f = row67_battle(); + // Poison, burn, Leech Seed, recoil, a confusion self-hit, its own Explosion: all with + // `hWhoseTurn` 1. + f.turn(false, BUBBLE); + f.enemy_hp(27, 31); + assert!(f.damage_events().is_empty()); + // Struggle is the cartridge's move, not the fly's. + f.turn(true, state::poke::moves::STRUGGLE); + f.enemy_hp(24, 31); + assert!(f.damage_events().is_empty()); + // The fly's next hit is paid from 24, not from 31. + f.turn(true, BUBBLE); + f.enemy_hp(20, 31); + let hit = f.damage_events(); + assert_eq!(labels(&hit), ["HIT #59 FOR 4 HP"]); +} + +#[test] +fn a_healed_enemy_is_not_paid_for_twice_and_a_switch_keeps_the_marks() { + let mut f = row67_battle(); + f.turn(true, BUBBLE); + f.enemy_hp(11, 31); + assert_eq!(f.damage_events().len(), 1); + // A Potion on the trainer's turn. + f.turn(false, BUBBLE); + f.enemy_hp(31, 31); + assert!(f.damage_events().is_empty()); + f.turn(true, BUBBLE); + f.enemy_hp(19, 31); + assert!(f.damage_events().is_empty(), "31 to 19 was paid before the Potion"); + // The trainer switches to Sandshrew, which is hit, and back. + f.turn(false, BUBBLE); + f.enemy(1, 0x60, 11, 33, 33); + assert!(f.damage_events().is_empty()); + f.turn(true, TACKLE); + f.enemy_hp(28, 33); + assert_eq!(labels(&f.damage_events()), ["HIT #96 FOR 5 HP"]); + f.turn(false, BUBBLE); + f.enemy(0, 0x3b, 11, 19, 31); + assert!(f.damage_events().is_empty()); + f.turn(true, BUBBLE); + f.enemy_hp(8, 31); + assert_eq!(labels(&f.damage_events()), ["HIT #59 FOR 3 HP"], "only below its low of 11"); +} + +#[test] +fn a_trainer_battle_pays_the_knockouts_and_stops_at_the_cap() { + let mut f = row67_battle(); + f.turn(true, BUBBLE); + f.enemy_hp(0, 31); + let ko = f.damage_events(); + assert_eq!(labels(&ko), ["HIT #59 FOR 31 HP KO"]); + assert!(close(ko[0].value, 0.25)); + f.enemy(1, 0x60, 11, 33, 33); + f.sample(); + f.enemy_hp(0, 33); + assert!(close(values(&f.damage_events())[0], 0.25)); + // A third Pokémon: the cap is spent. + f.enemy(2, 0x60, 11, 33, 33); + f.sample(); + f.enemy_hp(0, 33); + assert!(f.damage_events().is_empty()); + f.memory.set(ram::wIsInBattle, 0); + f.sample(); + assert!(close(f.reward.statistics().total, 0.50), "the battle's damage is the trainer's 0.50"); +} + +#[test] +fn a_new_trainer_battle_starts_a_new_budget() { + // Row 67's ring: lose, black out, walk back, fight again. Each battle pays its own damage. + let mut f = row67_battle(); + f.turn(true, BUBBLE); + f.enemy_hp(19, 31); + assert_eq!(f.damage_events().len(), 1); + f.memory.set(ram::wIsInBattle, 0xff); + f.sample(); + f.memory.set(ram::wIsInBattle, 0); + f.sample(); + f.memory.set(ram::wIsInBattle, TRAINER_BATTLE); + f.sample(); + f.enemy(0, 0x3b, 11, 31, 31); + f.sample(); + f.enemy_hp(19, 31); + assert_eq!(f.damage_events().len(), 1, "the second battle's first hit pays"); +} + +#[test] +fn a_wild_battle_pays_damage_on_the_wild_ko_scale_and_a_rollback_blocks_the_key() { + let mut f = Fixture::booted(); + let mut paid = Vec::new(); + for _ in 0..4 { + f.enemy(0, 0xa5, 3, 12, 12); + f.turn(true, TACKLE); + f.memory.set(ram::wIsInBattle, WILD_BATTLE); + f.sample(); + f.enemy_hp(6, 12); + paid.extend(values(&f.damage_events())); + f.memory.set(ram::wIsInBattle, 0); + f.memory.set(ram::wBattleResult, 1); + f.sample(); + } + assert_eq!(paid.len(), 3, "three wild battles per map/species/level: {paid:?}"); + assert!(close(paid[0], 0.10) && close(paid[1], 0.05) && close(paid[2], 0.10 / 3.0)); + assert_eq!(f.reward.export_state()["damageCounts"], json!({ "38:165:3": 3 })); + + // Another species on the same map is another key, and a rollback blocks it once paid. + f.enemy(0, 0x24, 3, 12, 12); + f.memory.set(ram::wIsInBattle, WILD_BATTLE); + f.sample(); + f.enemy_hp(0, 12); + let events = f.damage_events(); + assert_eq!(labels(&events), ["HIT #36 FOR 12 HP KO"]); + assert!(close(events[0].value, 0.20), "no knockout bonus in the wild"); + f.memory.set(ram::wIsInBattle, 0); + f.memory.set(ram::wBattleResult, 0); + assert_eq!(kinds(&f.sample()), ["battle"], "the wild KO still pays as it did"); + f.reward.clear_transient(); + f.enemy(0, 0x24, 3, 12, 12); + f.memory.set(ram::wIsInBattle, WILD_BATTLE); + f.sample(); + f.enemy_hp(0, 12); + assert!(f.damage_events().is_empty(), "a rollback cannot replay the damage"); +} + +#[test] +fn a_battle_sample_still_reads_each_address_once() { + let mut f = row67_battle(); + f.turn(true, BUBBLE); + f.enemy_hp(19, 31); + f.damage_events(); + assert!( + f.memory.reads.values().all(|count| *count == 1), + "{:?}", + f.memory.reads.iter().filter(|(_, count)| **count != 1).collect::>() + ); +} + +#[test] +fn a_battle_in_flight_round_trips_through_a_checkpoint() { + let mut f = row67_battle(); + f.turn(true, BUBBLE); + f.enemy_hp(19, 31); + f.damage_events(); + let state = f.reward.export_state(); + let mut restored = PokemonRedReward::new(); + restored.import_state(&state).unwrap(); + assert_eq!(restored.export_state(), state); + f.reward = restored; + f.enemy_hp(15, 31); + assert_eq!(labels(&f.damage_events()), ["HIT #59 FOR 4 HP"], "the mark came back with it"); +} + +#[test] +fn a_v7_state_restores_under_v8_with_no_damage_ledger_and_its_battle_marked_where_it_stands() { + // A v7 export mid-battle: v8's export without `damageCounts`, `counts.damage` or + // `battle.damage`. + let mut f = row67_battle(); + f.turn(true, BUBBLE); + f.enemy_hp(19, 31); + f.damage_events(); + let mut v7 = f.reward.export_state(); + v7.as_object_mut().unwrap().remove("damageCounts"); + v7["counts"].as_object_mut().unwrap().remove("damage"); + v7["battle"].as_object_mut().unwrap().remove("damage"); + assert_eq!(v7["version"], json!(STATE_VERSION), "v7 and v8 share a schema version"); + + let mut restored = PokemonRedReward::new(); + restored.import_state(&v7).unwrap(); + assert_eq!(restored.statistics().counts[kind::DAMAGE], 0); + assert_eq!(restored.export_state()["damageCounts"], json!({})); + f.reward = restored; + // Diglett stands at 19 of 31: that is its mark, and the 12 lost before the restore is not + // paid. The next hit is. + assert!(f.damage_events().is_empty()); + f.enemy_hp(10, 31); + assert_eq!(labels(&f.damage_events()), ["HIT #59 FOR 9 HP"]); + // Sandshrew, which the restore never saw, is marked where it first reads too. + f.enemy(1, 0x60, 11, 33, 33); + f.sample(); + f.enemy_hp(30, 33); + assert_eq!(labels(&f.damage_events()), ["HIT #96 FOR 3 HP"]); +} diff --git a/services/flysim/crates/flysim/src/reset.rs b/services/flysim/crates/flysim/src/reset.rs index b535256..42b6e66 100644 --- a/services/flysim/crates/flysim/src/reset.rs +++ b/services/flysim/crates/flysim/src/reset.rs @@ -337,7 +337,7 @@ mod tests { wall_ms: 1_700_000_000_000, rom_sha256: "ab".repeat(32), emulator_frame: 12_345, - compatibility: "kernel/pokered-unique8-v7/fingerprint".to_string(), + compatibility: "kernel/pokered-unique8-v8/fingerprint".to_string(), speed: 1.0, buttons: 0, rank_since_ms: 4_242.0, diff --git a/services/flysim/crates/flysim/src/snapshot.rs b/services/flysim/crates/flysim/src/snapshot.rs index 02b4f62..4084566 100644 --- a/services/flysim/crates/flysim/src/snapshot.rs +++ b/services/flysim/crates/flysim/src/snapshot.rs @@ -242,7 +242,7 @@ pub struct FeedMacroOutcome { /// Reward categories the feed reports counts for. The adapter's own interned kinds /// (`milestone`, `exploration`, `map`, `species`, `trainer`, `battle`, `badge`, `boundary`, -/// `catch`, `talk`, `item`) map onto these. +/// `catch`, `talk`, `item`) map onto these; `damage` has no counter (`from_adapter`). #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum RewardKind { @@ -300,6 +300,15 @@ impl RewardKind { // "new place" for all four, the operator's call (`apps/stage/src/games/pokemon-red.ts`). "talk" => Self::Explore, "item" => Self::Explore, + // `damage` (the operator, 2026-09-29) has no counter, deliberately. It pays for a hit, + // several times a battle, in trainer battles as well as wild ones: on `wildwin` the + // stage would fold every hit into "N wild wins", which is false of a trainer battle + // and of a battle the fly goes on to lose, and on any other counter it would be as + // wrong. Unmapped, a hit still reaches the page as a reward event with its own label + // (`HIT # FOR HP`), the event log, `/status` and the checkpoint; it is + // only left out of `game.rewardCounts` and the ticker's per-kind copy, the way the + // platformer's `started` and `clear` are. The feed's closed kind set does not move. + "damage" => return None, // The platformer. "band" => Self::Explore, "coin" => Self::Wildwin, @@ -753,13 +762,16 @@ mod tests { GameMode::Unknown ); for rule in flybrain_gb::pokemon_red::catalog::REWARDS { - assert!(RewardKind::from_adapter(rule.kind).is_some(), "{}", rule.kind); + // Every Pokémon kind shares a counter but `damage`, which has none on purpose. + let mapped = RewardKind::from_adapter(rule.kind).is_some(); + assert_eq!(mapped, rule.kind != "damage", "{}", rule.kind); } assert_eq!(RewardKind::from_adapter("nonsense"), None); assert_eq!(RewardKind::from_adapter("boundary"), Some(RewardKind::Explore)); assert_eq!(RewardKind::from_adapter("catch"), Some(RewardKind::Wildwin)); assert_eq!(RewardKind::from_adapter("talk"), Some(RewardKind::Explore)); assert_eq!(RewardKind::from_adapter("item"), Some(RewardKind::Explore)); + assert_eq!(RewardKind::from_adapter("damage"), None, "a hit is not a wild win"); } #[test] diff --git a/services/flysim/crates/flysim/tests/compat_migration.rs b/services/flysim/crates/flysim/tests/compat_migration.rs index cf70694..8e8b410 100644 --- a/services/flysim/crates/flysim/tests/compat_migration.rs +++ b/services/flysim/crates/flysim/tests/compat_migration.rs @@ -1,17 +1,19 @@ -//! A `v6` checkpoint restored under `v7`: accepted with the opt-in, refused without it. +//! A `v7` (and a `v6`) checkpoint restored under `v8`: accepted with the opt-in, refused without +//! it. //! //! The unit tests in `flybrain-gb` cover the decision function and the adapter's own state //! migration separately. This is the two of them against one artefact: a real `FLYSIM01` -//! envelope carrying a `pokered-unique8-v6` compatibility string and a `v6` reward ledger — -//! written, encoded, decoded, and then put through exactly what `Sim::try_restore` puts a -//! candidate through, and then one sample of a game in which items were already taken. +//! envelope carrying a `pokered-unique8-v7` (or `-v6`) compatibility string and that version's +//! reward ledger — written, encoded, decoded, and then put through exactly what +//! `Sim::try_restore` puts a candidate through, and then samples of a game: one in which items +//! were already taken (`v6`), one in the middle of the row 67 battle (`v7`). //! //! No ROM and no dataset, deliberately. Building a `Sim` would need both, and neither is part of //! the question: what decides a restore is the compatibility string and `import_state`, and what //! decides the seed is the first sample's read of the cartridge's own item bits. //! -//! (`v5` -> `v6`, the catch rule's migration, was this same file; `v6` no longer migrates from -//! anything, so that pair is refused now like any other.) +//! (`v5` -> `v6`, the catch rule's migration, was this same file, and `v6` -> `v7` the engagement +//! rules'. `v8` reads both `v7` and `v6`: the chain composes, and `v5` stays refused.) use flybrain_gb::GameAdapter; use flybrain_gb::MemoryReader; @@ -67,7 +69,34 @@ fn v6_reward() -> serde_json::Value { }) } +/// A `v7` reward ledger: the `v6` one after the engagement rules' first sample (the item seed and +/// a conversation), with a battle in flight -- the row 67 Jr. Trainer's Diglett at 19 of 31 -- +/// and **no** `damageCounts`, `counts.damage` or `battle.damage`. +fn v7_reward() -> serde_json::Value { + let mut reward = v6_reward(); + let seen = reward["seen"].as_array_mut().unwrap(); + for key in ["items:seeded", "item:42", "talk:54:sprite:1"] { + seen.push(serde_json::json!(key)); + } + reward["counts"]["talk"] = serde_json::json!(1); + reward["counts"]["item"] = serde_json::json!(0); + reward["mode"] = serde_json::json!("BATTLE"); + reward["battle"] = serde_json::json!({ + "key": "54:59:11", "wild": false, "sawLiving": true, "ko": false, + "speciesAtStart": 1, "captured": null, "capturedNew": false + }); + reward +} + fn v6_checkpoint() -> Vec { + checkpoint_of("pokered-unique8-v6", v6_reward()) +} + +fn v7_checkpoint() -> Vec { + checkpoint_of("pokered-unique8-v7", v7_reward()) +} + +fn checkpoint_of(adapter: &str, reward: serde_json::Value) -> Vec { use flybrain_core::decoder::DecoderState; use flybrain_core::lif::LifState; use flybrain_core::ordered::NumberMap; @@ -118,12 +147,12 @@ fn v6_checkpoint() -> Vec { wall_ms: 1_790_000_000_000, rom_sha256: flybrain_gb::pokemon_red::SUPPORTED_ROM.to_string(), emulator_frame: 1_000_000, - compatibility: compatibility("pokered-unique8-v6"), + compatibility: compatibility(adapter), speed: 1.0, buttons: 0, rank_since_ms: 1_000.0, last_event_id: 4_242, - reward: v6_reward(), + reward, ratchet: flybrain_gb::RatchetState { best: 3, attempts: 1, recoveries: 4, ..Default::default() }, emulator: vec![3; 64], framebuffer: vec![0; 32], @@ -134,25 +163,31 @@ fn v6_checkpoint() -> Vec { } #[test] -fn a_v6_checkpoint_is_refused_under_v7_without_the_opt_in() { - let checkpoint = store::decode(&v6_checkpoint()).expect("the fixture decodes"); +fn a_v7_or_v6_checkpoint_is_refused_under_v8_without_its_own_opt_in() { let adapter = PokemonRedReward::new(); let current = compatibility(adapter.id()); - assert_ne!(checkpoint.runtime.compatibility, current, "v7 is not v6"); - - for opt_in in [None, Some(""), Some("pokered-unique8-v5"), Some("some-other-adapter")] { - assert!( - matches!( - decide( - &checkpoint.runtime.compatibility, - ¤t, - adapter.migrates_from(), - &accepted_adapters(opt_in), + for (bytes, own) in + [(v7_checkpoint(), "pokered-unique8-v7"), (v6_checkpoint(), "pokered-unique8-v6")] + { + let checkpoint = store::decode(&bytes).expect("the fixture decodes"); + assert_ne!(checkpoint.runtime.compatibility, current, "v8 is not {own}"); + let other = if own.ends_with("v7") { "pokered-unique8-v6" } else { "pokered-unique8-v7" }; + for opt_in in + [None, Some(""), Some("pokered-unique8-v5"), Some("some-other-adapter"), Some(other)] + { + assert!( + matches!( + decide( + &checkpoint.runtime.compatibility, + ¤t, + adapter.migrates_from(), + &accepted_adapters(opt_in), + ), + RestoreDecision::Refuse(_) ), - RestoreDecision::Refuse(_) - ), - "FLY_ACCEPT_ADAPTERS={opt_in:?} must not migrate anything" - ); + "{own} with FLY_ACCEPT_ADAPTERS={opt_in:?} must not migrate" + ); + } } } @@ -166,7 +201,7 @@ impl MemoryReader for Wram { } #[test] -fn a_v6_checkpoint_restores_under_v7_with_the_new_ledgers_empty_and_the_items_seeded() { +fn a_v6_checkpoint_restores_under_v8_with_the_new_ledgers_empty_and_the_items_seeded() { let checkpoint = store::decode(&v6_checkpoint()).expect("the fixture decodes"); let mut adapter = PokemonRedReward::new(); let current = compatibility(adapter.id()); @@ -182,18 +217,20 @@ fn a_v6_checkpoint_restores_under_v7_with_the_new_ledgers_empty_and_the_items_se ); // The migration itself: `import_state`, exactly as `Sim::try_restore` calls it. - adapter.import_state(&checkpoint.runtime.reward).expect("a v6 ledger is a valid v7 ledger"); + adapter.import_state(&checkpoint.runtime.reward).expect("a v6 ledger is a valid v8 ledger"); let after = adapter.export_state(); assert_eq!(after["counts"]["talk"], serde_json::json!(0), "no conversation was ever paid"); assert_eq!(after["counts"]["item"], serde_json::json!(0), "nor any item"); + assert_eq!(after["counts"]["damage"], serde_json::json!(0), "nor any damage"); + assert_eq!(after["damageCounts"], serde_json::json!({})); - // And nothing else moved: every field the v6 state carried round-trips to the same value, - // and v7 adds no field at all -- its ledgers are keys in `seen`. + // And nothing else moved: every field the v6 state carried round-trips to the same value; + // v7 added no field (its ledgers are keys in `seen`) and v8 adds one, `damageCounts`. // // `counts` is the one field that is not byte-identical, and it is not a change of meaning: - // it serializes every kind in the catalog, so a v7 state lists `talk` and `item` where a v6 - // state had nothing to list. Every kind the v6 state did carry keeps its number. + // it serializes every kind in the catalog, so a v8 state lists `talk`, `item` and `damage` + // where a v6 state had nothing to list. Every kind the v6 state did carry keeps its number. let before = v6_reward(); for (key, value) in before.as_object().unwrap() { if key == "counts" { @@ -206,7 +243,7 @@ fn a_v6_checkpoint_restores_under_v7_with_the_new_ledgers_empty_and_the_items_se .keys() .filter(|kind| !value.as_object().unwrap().contains_key(*kind)) .collect(); - assert_eq!(added, vec!["talk", "item"], "v7 counts two more kinds and no others"); + assert_eq!(added, vec!["talk", "item", "damage"], "three more kinds and no others"); continue; } assert_eq!(&after[key], value, "{key} must survive the migration byte for byte"); @@ -217,7 +254,7 @@ fn a_v6_checkpoint_restores_under_v7_with_the_new_ledgers_empty_and_the_items_se .keys() .filter(|key| !before.as_object().unwrap().contains_key(*key)) .collect(); - assert!(added.is_empty(), "v7 adds no field: {added:?}"); + assert_eq!(added, vec!["damageCounts"], "v8 adds one field"); // The first sample of the restored game. Under v6 the fly took an item ball (global // toggleable index 0x2a) and a hidden item (index 9); v6 paid for neither. The sample seeds @@ -250,11 +287,11 @@ fn a_v6_checkpoint_restores_under_v7_with_the_new_ledgers_empty_and_the_items_se #[test] fn nothing_but_the_adapter_segment_may_differ_for_the_migration_to_apply() { let adapter = PokemonRedReward::new(); - let accepted = accepted_adapters(Some("pokered-unique8-v6")); + let accepted = accepted_adapters(Some("pokered-unique8-v7")); let current = compatibility(adapter.id()); - // A v6 string whose state format also moved: a different build, not a rule change. - let other_abi = compatibility("pokered-unique8-v6").replace("199616", "199617"); + // A v7 string whose state format also moved: a different build, not a rule change. + let other_abi = compatibility("pokered-unique8-v7").replace("199616", "199617"); assert!(matches!( decide(&other_abi, ¤t, adapter.migrates_from(), &accepted), RestoreDecision::Refuse(_) @@ -266,14 +303,85 @@ fn nothing_but_the_adapter_segment_may_differ_for_the_migration_to_apply() { RestoreDecision::Exact ); - // And v5 -> v7 is not a migration this adapter wrote, whatever the operator names. + // And v5 -> v8 is not a migration this adapter wrote, whatever the operator names. assert!(matches!( decide( &compatibility("pokered-unique8-v5"), ¤t, adapter.migrates_from(), - &accepted_adapters(Some("pokered-unique8-v5,pokered-unique8-v6")), + &accepted_adapters(Some("pokered-unique8-v5,pokered-unique8-v6,pokered-unique8-v7")), ), RestoreDecision::Refuse(_) )); } + +/// The enemy battle struct and the turn, as `LoadEnemyMonData` and `ExecutePlayerMove` leave them. +fn battle_wram(hp: u8, fly_turn: bool) -> Wram { + let mut wram = Wram(vec![0; 0x10000]); + wram.0[ram::wStatusFlags6 as usize] = 1; + wram.0[ram::wPartyCount as usize] = 1; + wram.0[ram::wCurMap as usize] = 54; + wram.0[ram::wCurMapWidth as usize] = 5; + wram.0[ram::wCurMapHeight as usize] = 7; + wram.0[ram::wXCoord as usize] = 4; + wram.0[ram::wYCoord as usize] = 10; + wram.0[ram::wIsInBattle as usize] = 2; + wram.0[ram::wEnemyMonPartyPos as usize] = 0; + wram.0[ram::wEnemyMonSpecies as usize] = 59; + wram.0[ram::wEnemyMonLevel as usize] = 11; + wram.0[(ram::wEnemyMonHP + 1) as usize] = hp; + wram.0[(ram::wEnemyMonMaxHP + 1) as usize] = 31; + wram.0[flybrain_gb::pokemon_red::state::poke::H_WHOSE_TURN as usize] = u8::from(!fly_turn); + wram.0[ram::wPlayerMoveNum as usize] = 0x91; + wram +} + +#[test] +fn a_v7_checkpoint_taken_mid_battle_restores_under_v8_and_pays_only_what_follows() { + let checkpoint = store::decode(&v7_checkpoint()).expect("the fixture decodes"); + let mut adapter = PokemonRedReward::new(); + let current = compatibility(adapter.id()); + assert_eq!( + decide( + &checkpoint.runtime.compatibility, + ¤t, + adapter.migrates_from(), + &accepted_adapters(Some("pokered-unique8-v7")), + ), + RestoreDecision::MigrateAdapter { from: "pokered-unique8-v7".to_string() } + ); + adapter.import_state(&checkpoint.runtime.reward).expect("a v7 ledger is a valid v8 ledger"); + + // Every field v7 carried survives, and v8 adds `damageCounts` and the battle's `damage`. + let before = v7_reward(); + let after = adapter.export_state(); + for (key, value) in before.as_object().unwrap() { + match key.as_str() { + "counts" => { + for (kind, count) in value.as_object().unwrap() { + assert_eq!(&after["counts"][kind], count, "counts.{kind}"); + } + assert_eq!(after["counts"]["damage"], serde_json::json!(0)); + } + "battle" => { + for (field, v) in value.as_object().unwrap() { + assert_eq!(&after["battle"][field], v, "battle.{field}"); + } + assert_eq!(after["battle"]["damage"]["restored"], serde_json::json!(true)); + } + _ => assert_eq!(&after[key], value, "{key} must survive the migration byte for byte"), + } + } + assert_eq!(after["damageCounts"], serde_json::json!({})); + + // The restored battle: Diglett stands at 19 of 31. The 12 HP it lost under v7 are not paid; + // its own turn's poison tick is not paid; BUBBLE's next hit is. + assert!(adapter.sample(&mut battle_wram(19, true), 2_000.0).is_empty(), "no back pay"); + assert!(adapter.sample(&mut battle_wram(17, false), 2_017.0).is_empty(), "not its turn"); + let hit = adapter.sample(&mut battle_wram(8, true), 2_034.0); + assert_eq!(hit.len(), 1); + assert_eq!(hit[0].kind, "damage"); + assert_eq!(hit[0].label, "HIT #59 FOR 9 HP"); + assert!((hit[0].value - 0.20 * 9.0 / 31.0).abs() < 1e-12); + assert_eq!(adapter.progress().rank, 3, "the rank is untouched"); +} diff --git a/services/flysim/crates/flysim/tests/integration.rs b/services/flysim/crates/flysim/tests/integration.rs index 78dd541..bfeb8a2 100644 --- a/services/flysim/crates/flysim/tests/integration.rs +++ b/services/flysim/crates/flysim/tests/integration.rs @@ -278,7 +278,7 @@ async fn the_service_streams_takes_sugar_checkpoints_and_resumes_after_being_kil }; assert_eq!(status, 200); assert_eq!(versions["version"]["kernel"], json!("lif-1ms-f64-v2")); - assert_eq!(versions["version"]["adapter"], json!("pokered-unique8-v7")); + assert_eq!(versions["version"]["adapter"], json!("pokered-unique8-v8")); assert!( versions["version"]["dataset"].as_str().unwrap_or_default().len() > 32, "the dataset fingerprint is in /status: {}", diff --git a/services/flysim/crates/flysim/tests/rom_damage.rs b/services/flysim/crates/flysim/tests/rom_damage.rs new file mode 100644 index 0000000..e09478c --- /dev/null +++ b/services/flysim/crates/flysim/tests/rom_damage.rs @@ -0,0 +1,273 @@ +//! The damage reward against the real cartridge, from the live row 67 checkpoint. +//! +//! Gated on `FLY_ROM` *and* on the checkpoint, the way every ROM test in this workspace is, and +//! skips cleanly without either: +//! +//! ```sh +//! FLY_ROM="$HOME/roms/pokemon-red.gb" \ +//! FLY_ROW67_CHECKPOINT=.local/checkpoints/ \ +//! cargo test --release -p flysim --test rom_damage -- --nocapture +//! ``` +//! +//! ## What only the cartridge can answer +//! +//! The synthetic traces in `pokemon_red/tests.rs` and `pokemon_red/damage.rs` write +//! `wEnemyMonHP`, `hWhoseTurn` and `wPlayerMoveNum` from the disassembly. They cannot say that +//! `hWhoseTurn` is at `$FFF3` on this cartridge, that it reads 0 on the frame the fly's BUBBLE +//! lands and 1 on the frame the enemy's attack does, or that the enemy's HP drops on a frame the +//! adapter samples with the move that did it still in `wPlayerMoveNum`. This test does, with the +//! shipping adapter sampling once a frame -- and it restores the checkpoint's own `v7` reward +//! ledger, so it is also the `v7` -> `v8` migration on the live run's state. +//! +//! ## How the fly is moved +//! +//! Not by a brain: the shipping palette (`PokemonPalette`) deals the pad, and a harness picks. Out +//! of battle the pick is uniform over what the pad deals, which is what `row67_the_gym_trainer_is_ +//! beaten_from_what_the_pad_deals` (`rom_macros_mode.rs`) showed reaches the gym's Jr. Trainer. +//! In battle it rotates the three moves -- TAIL WHIP, BUBBLE, TACKLE -- so each is used, and the +//! test asserts what each one was paid. + +use std::collections::BTreeMap; + +use flybrain_gb::adapter::RewardEvent; +use flybrain_gb::compatibility::{RestoreDecision, accepted_adapters, decide}; +use flybrain_gb::pokemon_red::macros::PokemonPalette; +use flybrain_gb::pokemon_red::symbols::ram; +use flybrain_gb::pokemon_red::{MIGRATES_FROM, PokemonRedReward, REWARD_ADAPTER, state}; +use flybrain_gb::{ + AdapterLedger, DEFAULT_AUDIO_FRAMES, DEFAULT_AUDIO_FREQUENCY, Emulator, GameAdapter, + MacroPalette, MemoryReader, Started, +}; + +const MS_PER_FRAME: f64 = 1000.0 / 59.7275; +const SEED: u32 = 20_260_929; +/// `constants/move_constants.asm`. +const TACKLE: u8 = 0x21; +const TAIL_WHIP: u8 = 0x27; +const BUBBLE: u8 = 0x91; + +fn rom() -> Option> { + let path = std::env::var_os("FLY_ROM")?; + match std::fs::read(&path) { + Ok(bytes) => Some(bytes), + Err(error) => panic!("FLY_ROM is set to {path:?} but could not be read: {error}"), + } +} + +fn checkpoint() -> Option { + let path = std::env::var_os("FLY_ROW67_CHECKPOINT")?; + Some( + flysim::store::load(std::path::Path::new(&path)) + .expect("the checkpoint should be a FLYSIM01 envelope"), + ) +} + +fn hp(gb: &mut Emulator, address: u16) -> u16 { + u16::from(gb.read8(address)) << 8 | u16::from(gb.read8(address + 1)) +} + +/// The live `v7` checkpoint is refused by this build without the opt-in and restored with it, by +/// the same decision `Sim::try_restore` makes, and its reward ledger imports. +#[test] +fn the_live_v7_checkpoint_migrates_to_v8() { + let Some(checkpoint) = checkpoint() else { + eprintln!("skipped: no FLY_ROW67_CHECKPOINT"); + return; + }; + let live = checkpoint.runtime.compatibility.clone(); + let segments: Vec<&str> = live.split('/').collect(); + assert_eq!(segments[1], "pokered-unique8-v7", "the live run is v7: {live}"); + // This build's string is the live one with the adapter segment moved and nothing else: the + // dataset, kernel, plasticity, emulator, symbols and state format are the same build inputs. + let mut ours = segments.clone(); + ours[1] = REWARD_ADAPTER; + let current = ours.join("/"); + assert!(matches!(decide(&live, ¤t, MIGRATES_FROM, &[]), RestoreDecision::Refuse(_))); + assert_eq!( + decide(&live, ¤t, MIGRATES_FROM, &accepted_adapters(Some("pokered-unique8-v7"))), + RestoreDecision::MigrateAdapter { from: "pokered-unique8-v7".to_string() } + ); + let mut adapter = PokemonRedReward::new(); + adapter.import_state(&checkpoint.runtime.reward).expect("a v7 ledger is a v8 ledger"); + let state = adapter.export_state(); + assert_eq!(state["damageCounts"], serde_json::json!({})); + assert_eq!(state["counts"]["damage"], serde_json::json!(0)); + for kind in ["milestone", "map", "trainer", "battle", "talk", "item", "catch"] { + assert_eq!( + state["counts"][kind], checkpoint.runtime.reward["counts"][kind], + "counts.{kind} survives" + ); + } + assert_eq!(state["seen"], checkpoint.runtime.reward["seen"], "the ledger survives"); + assert_eq!(adapter.progress().rank, 10, "PEWTER CITY"); +} + +/// BUBBLE and TACKLE are paid when they land, TAIL WHIP never is, and the enemy's own hits land +/// while `hWhoseTurn` reads 1. +#[test] +fn damage_pays_on_bubble_and_tackle_and_not_on_tail_whip() { + let (Some(rom), Some(checkpoint)) = (rom(), checkpoint()) else { + eprintln!("skipped: needs FLY_ROM and FLY_ROW67_CHECKPOINT"); + return; + }; + let mut gb = Emulator::new(&rom, DEFAULT_AUDIO_FREQUENCY, DEFAULT_AUDIO_FRAMES) + .expect("binjgb should accept the cartridge"); + gb.import_state(&checkpoint.runtime.emulator).expect("the checkpoint's emulator state"); + let mut adapter = PokemonRedReward::new(); + adapter.import_state(&checkpoint.runtime.reward).expect("a v7 ledger is a v8 ledger"); + + let mut palette = PokemonPalette::new(SEED); + let rotation = ["MOVE 2", "MOVE 3", "MOVE 1"]; + let mut next_move = 0usize; + let hold_frames = 48u32; + let mut since_decision = hold_frames; + let mut running = false; + let mut rng = 7u32; + let mut ms = 0.0; + + // Per move id: moves started, enemy HP drops seen, damage events paid, HP paid for. + let mut chosen: BTreeMap = BTreeMap::new(); + let mut drops: BTreeMap = BTreeMap::new(); + let mut paid: BTreeMap> = BTreeMap::new(); + let mut enemy_drop_turns: BTreeMap = BTreeMap::new(); + let mut own_drop_turns: BTreeMap = BTreeMap::new(); + let mut last_enemy: Option<(u8, u8, u16)> = None; + let mut last_own: Option = None; + let mut trainer_battles = 0u32; + let mut fighting = gb.read8(ram::wIsInBattle); + + for _frame in 0..90_000u32 { + palette.clock(ms); + let observed = { + let ledger = AdapterLedger(&adapter); + palette.observe(&mut gb, &ledger) + }; + let mut mask = 0u8; + { + let ledger = AdapterLedger(&adapter); + if running { + match palette.step(&mut gb, &ledger) { + Some(held) => mask = held, + None => running = false, + } + } else if since_decision >= hold_frames && !observed.bindings.is_empty() { + since_decision = 0; + let moves: Vec<_> = + observed.bindings.iter().filter(|b| b.name.starts_with("MOVE ")).collect(); + let binding = if moves.is_empty() { + rng ^= rng << 13; + rng ^= rng >> 17; + rng ^= rng << 5; + &observed.bindings[(rng >> 8) as usize % observed.bindings.len()] + } else { + let want = rotation[next_move % rotation.len()]; + let pick = moves.iter().find(|b| b.name == want).unwrap_or(&moves[0]); + next_move += 1; + pick + }; + if let Some(n) = binding.name.strip_prefix("MOVE ").and_then(|n| n.parse::().ok()) + { + let id = gb.read8(ram::wBattleMonMoves + n - 1); + *chosen.entry(id).or_default() += 1; + } + if let Started::Running(_) = palette.start(binding.slot, &mut gb, &ledger) { + running = true; + match palette.step(&mut gb, &ledger) { + Some(held) => mask = held, + None => running = false, + } + } + } + } + since_decision += 1; + gb.set_buttons(mask); + gb.run_frame().expect("a frame should complete"); + ms += MS_PER_FRAME; + let events = adapter.sample(&mut gb, ms); + + let in_battle = gb.read8(ram::wIsInBattle); + if fighting == 0 && in_battle == 2 { + trainer_battles += 1; + } + fighting = in_battle; + let whose = gb.read8(state::poke::H_WHOSE_TURN); + let move_id = gb.read8(ram::wPlayerMoveNum); + if in_battle == 2 { + let enemy = ( + gb.read8(ram::wEnemyMonPartyPos), + gb.read8(ram::wEnemyMonSpecies), + hp(&mut gb, ram::wEnemyMonHP), + ); + if let Some(before) = last_enemy + && (before.0, before.1) == (enemy.0, enemy.1) + && enemy.2 < before.2 + { + *enemy_drop_turns.entry(whose).or_default() += 1; + if whose == 0 { + *drops.entry(move_id).or_default() += 1; + } + } + last_enemy = Some(enemy); + let own = hp(&mut gb, ram::wBattleMonHP); + if let Some(before) = last_own + && own < before + { + *own_drop_turns.entry(whose).or_default() += 1; + } + last_own = Some(own); + } else { + last_enemy = None; + last_own = None; + } + for event in events.into_iter().filter(|event| event.kind == "damage") { + assert_eq!(whose, 0, "a damage payout on the enemy's turn: {event:?}"); + assert_eq!(in_battle, 2, "the walk to the gym has no grass: {event:?}"); + paid.entry(move_id).or_default().push(event); + } + let hits = |id: u8| paid.get(&id).map_or(0, Vec::len); + if hits(BUBBLE) >= 2 + && hits(TACKLE) >= 2 + && chosen.get(&TAIL_WHIP).copied().unwrap_or(0) >= 3 + && own_drop_turns.values().sum::() >= 2 + { + break; + } + } + + let summary: BTreeMap> = paid + .iter() + .map(|(id, events)| { + (*id, events.iter().map(|event| (event.label.clone(), event.value)).collect()) + }) + .collect(); + eprintln!( + "{:.1} brain minutes, {trainer_battles} trainer battle(s). moves chosen {chosen:?}; \ + enemy HP drops on the fly's turn by move {drops:?}; enemy drops by hWhoseTurn \ + {enemy_drop_turns:?}; own drops by hWhoseTurn {own_drop_turns:?}; damage paid by move \ + {summary:?}", + ms / 60_000.0 + ); + assert!(trainer_battles > 0, "the run never reached the trainer's battle"); + assert!(chosen.get(&TAIL_WHIP).copied().unwrap_or(0) >= 3, "TAIL WHIP was not used"); + assert!(!paid.contains_key(&TAIL_WHIP), "TAIL WHIP was paid: {summary:?}"); + for id in [BUBBLE, TACKLE] { + let events = paid.get(&id).map(Vec::as_slice).unwrap_or_default(); + assert!(events.len() >= 2, "move {id:#04x} was not paid twice: {summary:?}"); + for event in events { + assert!(event.value > 0.0 && event.value <= 0.25 + 1e-12, "{event:?}"); + assert_eq!(event.stimulation_ms, 80); + } + } + // The address, pinned on the cartridge: the fly's hits land on 0, the enemy's on 1. + assert_eq!(enemy_drop_turns.get(&1), None, "the enemy lost HP on its own turn"); + assert!(own_drop_turns.get(&1).copied().unwrap_or(0) >= 2, "{own_drop_turns:?}"); + assert_eq!(own_drop_turns.get(&0), None, "the fly lost HP on its own turn: {own_drop_turns:?}"); + // Every drop on the fly's turn was paid, and only those. + for (id, count) in &drops { + assert_eq!( + paid.get(id).map_or(0, Vec::len) as u32, + *count, + "move {id:#04x}: every drop it caused is one payout" + ); + } +} diff --git a/services/flysim/crates/flysim/tests/schema.rs b/services/flysim/crates/flysim/tests/schema.rs index e0115c8..81c14e2 100644 --- a/services/flysim/crates/flysim/tests/schema.rs +++ b/services/flysim/crates/flysim/tests/schema.rs @@ -202,6 +202,11 @@ fn every_status_mode_reward_kind_and_attachment_the_service_can_emit_is_in_the_s assert_valid(&validator, &serde_json::to_value(&snapshot.header).unwrap()); } for rule in flybrain_gb::pokemon_red::catalog::REWARDS { + // `damage` publishes no counter (`RewardKind::from_adapter`): its events carry their own + // label and no `rewardKind`, which the schema already allows. + if rule.kind == flybrain_gb::pokemon_red::catalog::kind::DAMAGE { + continue; + } let kind = flysim::snapshot::RewardKind::from_adapter(rule.kind).expect(rule.kind); snapshot.header.events[0].reward_kind = Some(kind); assert_valid(&validator, &serde_json::to_value(&snapshot.header).unwrap());