From 2c410a4c328eddf1aab1fea7e3dc99ae166eec6d Mon Sep 17 00:00:00 2001 From: stsiakal Date: Thu, 22 Oct 2026 03:40:17 +0300 Subject: [PATCH 01/14] fix(data): add the Old Memoria Lake Tree spawns for Low on Lumber Co-Authored-By: Claude Opus 5.5 --- rust/crates/aaemu-game/PORTING.md | 11 +++ .../Data/Worlds/main_world/doodad_spawns.json | 77 +++++++++++++++++++ .../src/systems/npcs/spawn_tests.rs | 50 ++++++++++++ 3 files changed, 138 insertions(+) diff --git a/rust/crates/aaemu-game/PORTING.md b/rust/crates/aaemu-game/PORTING.md index 0ed21abd60..876ab68bd0 100644 --- a/rust/crates/aaemu-game/PORTING.md +++ b/rust/crates/aaemu-game/PORTING.md @@ -2485,3 +2485,14 @@ running in place). Four mirrored C# bugs and one missing safeguard: `flow_tests::follow_path_command_set_walks_every_route_point` runs the real command-set shape over three routes with an elevated point and checks every point is targeted in order, the set finishes and the NPC settles in HoldPosition without further movement. + +## Old Memoria Lake Tree spawns for "Low on Lumber" (C# PR #1793, 2026-10-22) + +Ported C# `develop` 9549c76b (PR #1793): seven `UnitId` 3848 (`Old Memoria Lake Tree`) +placements in `app/Data/Worlds/main_world/doodad_spawns.json` at the Old Memoria lake +(X ~9049-9098, Y ~9060-9121, Z ~192-197), next to the one placement the file already had. They +make quest "Low on Lumber" (context 2094, level 38) satisfiable: `QuestActObjItemGather` id 890 +gathers item 16035 x 5 with `highlight_doodad_id` 3848. Data only: `DoodadSpawnerDef` +(`systems/npcs/doodad/spawner.rs`) already reads `UnitId` / `Position`. Regression test +`spawn_tests::real_data_old_memoria_lake_trees_for_low_on_lumber` loads the shipped file through +the real `parse_list` and checks the eight placements. diff --git a/rust/crates/aaemu-game/app/Data/Worlds/main_world/doodad_spawns.json b/rust/crates/aaemu-game/app/Data/Worlds/main_world/doodad_spawns.json index b3b3f12071..ea780869fb 100644 --- a/rust/crates/aaemu-game/app/Data/Worlds/main_world/doodad_spawns.json +++ b/rust/crates/aaemu-game/app/Data/Worlds/main_world/doodad_spawns.json @@ -385636,6 +385636,83 @@ "Yaw": 106.9 } }, + { + "UnitId": 3848, // Old Memoria Lake Tree + "Position": { + "X": 9097.6, + "Y": 9063.8, + "Z": 193.6, + "Roll": 0.0, + "Pitch": 0.0, + "Yaw": 126.6 + } + }, + { + "UnitId": 3848, // Old Memoria Lake Tree + "Position": { + "X": 9088.3, + "Y": 9059.7, + "Z": 194.7, + "Roll": 0.0, + "Pitch": 0.0, + "Yaw": 90.0 + } + }, + { + "UnitId": 3848, // Old Memoria Lake Tree + "Position": { + "X": 9063.3, + "Y": 9087.7, + "Z": 196.5, + "Roll": 0.0, + "Pitch": 0.0, + "Yaw": -53.4 + } + }, + { + "UnitId": 3848, // Old Memoria Lake Tree + "Position": { + "X": 9087.8, + "Y": 9070.8, + "Z": 192.2, + "Roll": 0.0, + "Pitch": 0.0, + "Yaw": 61.9 + } + }, + { + "UnitId": 3848, // Old Memoria Lake Tree + "Position": { + "X": 9064.6, + "Y": 9098.9, + "Z": 194.1, + "Roll": 0.0, + "Pitch": 0.0, + "Yaw": 42.2 + } + }, + { + "UnitId": 3848, // Old Memoria Lake Tree + "Position": { + "X": 9062.2, + "Y": 9114.8, + "Z": 193.9, + "Roll": 0.0, + "Pitch": 0.0, + "Yaw": -16.9 + } + }, + { + "UnitId": 3848, // Old Memoria Lake Tree + "Position": { + "X": 9048.9, + "Y": 9120.5, + "Z": 196.3, + "Roll": 0.0, + "Pitch": 0.0, + "Yaw": 30.9 + } + }, { "UnitId": 3848, // Old Memoria Lake Tree "Position": { diff --git a/rust/crates/aaemu-game/src/systems/npcs/spawn_tests.rs b/rust/crates/aaemu-game/src/systems/npcs/spawn_tests.rs index a5b4a6f92d..af873a1c62 100644 --- a/rust/crates/aaemu-game/src/systems/npcs/spawn_tests.rs +++ b/rust/crates/aaemu-game/src/systems/npcs/spawn_tests.rs @@ -3252,3 +3252,53 @@ fn real_data_ronbann_mine_npcs_are_on_the_mine_floor() { "Ronbann middle-cave placements found: {middle}" ); } + +/// The Old Memoria Lake Tree placements of the level 38 quest "Low on Lumber" (context 2094: +/// `QuestActObjItemGather` item 16035 x 5 with `highlight_doodad_id` 3848). The C# PR #1793 +/// (upstream 9549c76b) added seven trees at the lake; the shipped file already had one east of +/// it. The doodad spawn loader must accept every entry (template id, position) and the seven +/// lake positions must be present exactly once each. +#[test] +fn real_data_old_memoria_lake_trees_for_low_on_lumber() { + use crate::systems::npcs::doodad::spawner::{parse_list, DoodadSpawnerDef}; + + let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("app/Data/Worlds/main_world/doodad_spawns.json"); + let Ok(text) = std::fs::read_to_string(path) else { + return; + }; + let defs = parse_list(&text, DoodadSpawnerDef::from_json).expect("doodad_spawns.json"); + + let mut all: Vec<(f32, f32, f32, f32)> = defs + .iter() + .filter(|d| d.base.unit_id == 3848) + .map(|d| { + let p = &d.base.position; + (p.x, p.y, p.z, p.yaw) + }) + .collect(); + assert_eq!(all.len(), 8, "Old Memoria Lake Tree placements: {all:?}"); + all.sort_by(|a, b| a.partial_cmp(b).unwrap()); + all.dedup(); + assert_eq!(all.len(), 8, "duplicate Old Memoria Lake Tree placement"); + + // The seven PR #1793 placements around the lake (X ~9049-9098, Y ~9060-9121), plus the + // pre-existing one at (9078.5, 9125.3, 190.2, yaw 0) just north-east of them. + let mut lake: Vec<(f32, f32, f32, f32)> = all + .into_iter() + .filter(|&(x, y, _, _)| (9040.0..=9100.0).contains(&x) && (9050.0..=9130.0).contains(&y)) + .collect(); + let mut expected = vec![ + (9097.6, 9063.8, 193.6, 126.6), + (9088.3, 9059.7, 194.7, 90.0), + (9063.3, 9087.7, 196.5, -53.4), + (9087.8, 9070.8, 192.2, 61.9), + (9064.6, 9098.9, 194.1, 42.2), + (9062.2, 9114.8, 193.9, -16.9), + (9048.9, 9120.5, 196.3, 30.9), + (9078.5, 9125.3, 190.2, 0.0), + ]; + expected.sort_by(|a, b| a.partial_cmp(b).unwrap()); + lake.sort_by(|a, b| a.partial_cmp(b).unwrap()); + assert_eq!(lake, expected); +} From b3f461b8289ea1c76d56b35e404eba17cdd0ca0a Mon Sep 17 00:00:00 2001 From: stsiakal Date: Thu, 22 Oct 2026 03:41:23 +0300 Subject: [PATCH 02/14] fix(doodads): ore, rock mining and shearing funcs DoodadFuncOreMine / RockMine / Shear were log-only stubs, so the phase never advanced and the authored loot / depletion / regrow groups never ran. They now set ToNextPhase like DoodadFuncCutdown; labor stays the gathering skill's consume_lp and the 1.2 server (C# and Rust) does not validate mainhand_tool_id. Co-Authored-By: Claude Opus 5.5 --- rust/crates/aaemu-game/PORTING.md | 16 + .../src/systems/npcs/doodad/funcs/mod.rs | 26 +- .../src/systems/npcs/doodad/funcs/tests.rs | 7 + .../src/systems/npcs/doodad/gather_tests.rs | 405 ++++++++++++++++++ .../aaemu-game/src/systems/npcs/doodad/mod.rs | 4 + 5 files changed, 455 insertions(+), 3 deletions(-) create mode 100644 rust/crates/aaemu-game/src/systems/npcs/doodad/gather_tests.rs diff --git a/rust/crates/aaemu-game/PORTING.md b/rust/crates/aaemu-game/PORTING.md index 1ca30539d6..53a8564dbf 100644 --- a/rust/crates/aaemu-game/PORTING.md +++ b/rust/crates/aaemu-game/PORTING.md @@ -1430,6 +1430,22 @@ is no longer mirrored (see "Known deviations", dead NPC returned and healed). which the time-of-day watcher fires on crossing. The C# has no such suppression (its chain recursed). Boards respawned by their own Final, and every other spawn, keep the catch-up. +* systems::npcs (2026-10-22): `DoodadFuncOreMine`, `DoodadFuncRockMine` and `DoodadFuncShear` + were log-only stubs in the C#, so their phases never advanced and ore / rock veins and the + shearing doodads could not be gathered. The 1.2 compact tables carry no loot, labor or tool + columns either (`doodad_func_ore_mines` / `doodad_func_rock_mines`: `id` only; + `doodad_func_shears`: `shear_type_id`, `shear_term`), so the Rust funcs now do what the + authored phase graph describes, like `DoodadFuncCutdown`: set `ToNextPhase` and let the + engine enter the func's `NextPhase` group. That group holds the `DoodadFuncLootItem` rows + (e.g. vein 326: 255 OreMine -> 425 three loot rolls -> 426 `Final` / `RatioRespawn`; + green ore 1532: 2371 -> 2372 -> `RatioChange` branches) and, for shearing, the regrow + `Timer` (56 Shear -> 57 loot + 30 s timer). Loot keeps its C# task type + (`RecoverDoodadItem`), so a full bag still sends `BagInvalidItem` and leaves the phase + unlocked. Labor is the gathering skill's `consume_lp`, enforced by the skill cast. The + tool is data only: the C# server never validated `SkillTemplate.MainhandToolId` (the 1.2 + mining / shear ids 2654 and 15607 do not even resolve to `items` rows) and neither does + Rust, so there is no server-side tool refusal at 1.2 parity. + * systems::ai (2026-10-15): the optional compact patch `SQL/patches/compact/2026-10-14-fix-npc-ai-param-syntax.sql` repairs malformed Lua syntax in `npc_ai_params` 443, 835 and 1975 only when the original bytes match. It preserves authored diff --git a/rust/crates/aaemu-game/src/systems/npcs/doodad/funcs/mod.rs b/rust/crates/aaemu-game/src/systems/npcs/doodad/funcs/mod.rs index 6c341e1bfc..8b98213302 100644 --- a/rust/crates/aaemu-game/src/systems/npcs/doodad/funcs/mod.rs +++ b/rust/crates/aaemu-game/src/systems/npcs/doodad/funcs/mod.rs @@ -130,6 +130,29 @@ pub fn use_func( tracing::trace!("DoodadFuncHarvest"); set_to_next_phase(ctx, true); } + // Gathering phase funcs: the 1.2 tables only carry the func id + // (`doodad_func_ore_mines` / `doodad_func_rock_mines`) or the shear type / term + // (`doodad_func_shears`); loot, depletion and regrowth live in the next func group + // (e.g. ore 255 -> 425 LootItem -> 426 Final / RatioRespawn, sheared 56 -> 57 LootItem + // + Timer). The C# bodies only logged, so the phase never advanced; advancing is what + // makes the authored loot / respawn chain run. The gathering skill covers labor + // (`consume_lp`) and the 1.2 server never validated `mainhand_tool_id`. + F::OreMine(_) => { + tracing::trace!("DoodadFuncOreMine"); + set_to_next_phase(ctx, true); + } + F::RockMine(_) => { + tracing::trace!("DoodadFuncRockMine"); + set_to_next_phase(ctx, true); + } + F::Shear(f) => { + tracing::trace!( + "DoodadFuncShear: ShearTypeId {}, ShearTerm {}", + f.shear_type_id, + f.shear_term + ); + set_to_next_phase(ctx, true); + } F::OpenFarmInfo(f) => { // 1.2 commonfarm/info.alb opens on OPEN_COMMON_FARM_INFO. The packet's // count describes the position array, not the farm's planting capacity @@ -200,13 +223,10 @@ pub fn use_func( | F::NaviOpenMailbox(_) | F::NaviRemove(_) | F::OpenPaper(_) - | F::OreMine(_) | F::ParentInfo(_) | F::PlantCollect(_) | F::RenewItem(_) - | F::RockMine(_) | F::SeedCollect(_) - | F::Shear(_) | F::SkinOff(_) | F::SoilCollect(_) | F::SpiceCollect(_) diff --git a/rust/crates/aaemu-game/src/systems/npcs/doodad/funcs/tests.rs b/rust/crates/aaemu-game/src/systems/npcs/doodad/funcs/tests.rs index ebb8111846..b5ddd87f92 100644 --- a/rust/crates/aaemu-game/src/systems/npcs/doodad/funcs/tests.rs +++ b/rust/crates/aaemu-game/src/systems/npcs/doodad/funcs/tests.rs @@ -210,6 +210,13 @@ async fn to_next_phase_funcs_and_stubs() { FuncTemplate::Harvest(DoodadFuncHarvest { id: 1 }), FuncTemplate::OpenFarmInfo(DoodadFuncOpenFarmInfo { id: 1, farm_id: 0 }), FuncTemplate::PuzzleRoll(DoodadFuncPuzzleRoll::default()), + FuncTemplate::OreMine(DoodadFuncOreMine { id: 1 }), + FuncTemplate::RockMine(DoodadFuncRockMine { id: 1 }), + FuncTemplate::Shear(DoodadFuncShear { + id: 1, + shear_type_id: 1, + shear_term: 60_000, + }), ] { fx.doodad.data().phase.to_next_phase = false; fx.run(t, 0, 0); diff --git a/rust/crates/aaemu-game/src/systems/npcs/doodad/gather_tests.rs b/rust/crates/aaemu-game/src/systems/npcs/doodad/gather_tests.rs new file mode 100644 index 0000000000..7ed404dffe --- /dev/null +++ b/rust/crates/aaemu-game/src/systems/npcs/doodad/gather_tests.rs @@ -0,0 +1,405 @@ +//! Mining / shearing gathering flows: `DoodadFuncOreMine` / `RockMine` / `Shear` advance to the +//! authored loot group, and the gathering skill pays the labor and grants the loot through the +//! real phase machine and economy. +//! +//! The compact tables only carry the func id (`doodad_func_ore_mines` / `..._rock_mines`) or +//! the shear type / term (`doodad_func_shears`); the items, depletion and regrowth are in the +//! next func groups (ore 255 -> 425 LootItem -> 426 Final / RatioRespawn, sheared 56 -> 57 +//! LootItem + Timer). The 1.2 server never validated `SkillTemplate.MainhandToolId`, so only +//! the labor requirement is enforced server-side. + +use aaemu_commons::{Marshal, PacketStream}; + +use crate::data::items::{GradeTemplate, ItemTemplate}; +use crate::data::GameData; +use crate::opcodes::sc; +use crate::server::GameServer; +use crate::systems::economy::inventory::Inv; +use crate::systems::npcs::doodad::data::DoodadData; +use crate::systems::npcs::doodad::manager; +use crate::systems::npcs::doodad::templates::*; +use crate::systems::skills::data::effects::EffectTemplate; +use crate::systems::skills::data::EffectKind; +use crate::systems::skills::handlers::{start_skill, CSStartSkillPacket}; +use crate::systems::skills::types::{ + skill_result, SkillCastTarget, SkillCaster, SkillObject, SkillTargetType, +}; +use crate::test_support::*; +use crate::world::{DoodadRef, PlayerRef}; + +const ORE: u32 = 8022; +const WOOL: u32 = 8053; +const LABOR_BASE: i32 = 100; +const MINING_LABOR: i32 = 5; +const SHEAR_LABOR: i32 = 1; +const REGROW_MS: i32 = 60_000; + +const VEIN: u32 = 101; +const VEIN_START: u32 = 10; +const VEIN_LOOT: u32 = 11; +const VEIN_DEPLETED: u32 = 12; + +const ROCK: u32 = 103; +const ROCK_START: u32 = 30; +const ROCK_LOOT: u32 = 31; +const ROCK_DEPLETED: u32 = 32; + +const SHEEP: u32 = 102; +const SHEEP_START: u32 = 20; +const SHEEP_LOOT: u32 = 21; +const SHEEP_SHEARED: u32 = 22; + +const ORE_MINE_SKILL: u32 = 9100; +const SHEAR_SKILL: u32 = 9101; +/// `mainhand_tool_id` of the 1.2 mining skills (data only: no server-side check). +const PICKAXE: u32 = 2654; + +const ORE_MINE_EFFECT: u32 = 900_001; +const SHEAR_EFFECT: u32 = 900_002; + +/// Synthetic `DoodadData` builder (templates, funcs and phase funcs). +#[derive(Default)] +struct DoodadBuilder { + data: DoodadData, +} + +impl DoodadBuilder { + fn template(mut self, id: u32, groups: &[(u32, u32)]) -> Self { + let mut t = DoodadTemplate { + id, + ..DoodadTemplate::default() + }; + for &(gid, kind) in groups { + let g = DoodadFuncGroups { + id: gid, + almighty: id, + group_kind_id: kind, + ..DoodadFuncGroups::default() + }; + t.func_groups.push(g.clone()); + self.data + .all_func_groups_index + .insert(gid, self.data.all_func_groups.len()); + self.data.all_func_groups.push(g); + } + self.data.template_order.push(id); + self.data.templates.insert(id, t); + self + } + + fn func(mut self, group: u32, t: FuncTemplate, next_phase: i32) -> Self { + let (class, id) = (t.func_type(), t.id()); + self.data + .func_templates + .entry(class) + .or_default() + .insert(id, t); + let key = self.data.funcs_by_id.len() as u32 + 1; + let f = DoodadFunc { + group_id: group, + func_id: id, + func_key: key, + func_type: class.into(), + next_phase, + ..DoodadFunc::default() + }; + self.data.funcs_by_id.insert(key, f.clone()); + self.data.funcs_by_groups.entry(group).or_default().push(f); + self + } + + fn phase_func(mut self, group: u32, t: FuncTemplate) -> Self { + let (class, id) = (t.func_type(), t.id()); + self.data + .phase_func_templates + .entry(class) + .or_default() + .insert(id, t); + self.data + .phase_funcs + .entry(group) + .or_default() + .push(DoodadPhaseFunc { + group_id: group, + func_id: id, + func_type: class.into(), + }); + self + } +} + +fn loot(id: u32, item_id: u32) -> FuncTemplate { + FuncTemplate::LootItem(DoodadFuncLootItem { + id, + item_id, + count_min: 1, + count_max: 1, + percent: 10_000, + ..DoodadFuncLootItem::default() + }) +} + +fn regrow_timer(id: u32, start_phase: i32) -> FuncTemplate { + FuncTemplate::Timer(DoodadFuncTimer { + id, + delay: REGROW_MS, + next_phase: start_phase, + ..DoodadFuncTimer::default() + }) +} + +fn game_data() -> GameData { + let mut d = GameData::empty(); + d.items.grades.insert( + 0, + GradeTemplate { + grade: 0, + grade_order: 0, + durability: 1.0, + }, + ); + d.items.config.durability_const = 1.0; + d.items.templates.insert(ORE, ItemTemplate::plain(ORE, 100)); + d.items + .templates + .insert(WOOL, ItemTemplate::plain(WOOL, 100)); + + let s = &mut d.systems.skills; + s.add_effect( + EffectKind::InteractionEffect, + EffectTemplate::Interaction { + id: ORE_MINE_EFFECT, + world_interaction: 73, // WorldInteractionType.OreMine + doodad_id: 0, + }, + ORE_MINE_EFFECT, + ); + s.add_effect( + EffectKind::InteractionEffect, + EffectTemplate::Interaction { + id: SHEAR_EFFECT, + world_interaction: 19, // WorldInteractionType.Use + doodad_id: 0, + }, + SHEAR_EFFECT, + ); + let mut mining = crate::systems::skills::tests::skill_template(ORE_MINE_SKILL); + mining.consume_labor_power = MINING_LABOR; + mining.mainhand_tool_id = PICKAXE; + mining.target_type = SkillTargetType::Doodad as i32; + mining + .effects + .push(crate::systems::skills::tests::skill_effect( + ORE_MINE_EFFECT, + EffectKind::InteractionEffect, + ORE_MINE_EFFECT, + )); + s.add_skill(mining); + let mut shear = crate::systems::skills::tests::skill_template(SHEAR_SKILL); + shear.consume_labor_power = SHEAR_LABOR; + shear.target_type = SkillTargetType::Doodad as i32; + shear + .effects + .push(crate::systems::skills::tests::skill_effect( + SHEAR_EFFECT, + EffectKind::InteractionEffect, + SHEAR_EFFECT, + )); + s.add_skill(shear); + + d.systems.npcs.doodad = DoodadBuilder::default() + .template(VEIN, &[(VEIN_START, 1), (VEIN_LOOT, 2), (VEIN_DEPLETED, 2)]) + .func( + VEIN_START, + FuncTemplate::OreMine(DoodadFuncOreMine { id: 1 }), + VEIN_LOOT as i32, + ) + .func(VEIN_LOOT, loot(2, ORE), VEIN_DEPLETED as i32) + .phase_func(VEIN_DEPLETED, regrow_timer(3, VEIN_START as i32)) + .template(ROCK, &[(ROCK_START, 1), (ROCK_LOOT, 2), (ROCK_DEPLETED, 2)]) + .func( + ROCK_START, + FuncTemplate::RockMine(DoodadFuncRockMine { id: 7 }), + ROCK_LOOT as i32, + ) + .func(ROCK_LOOT, loot(8, ORE), ROCK_DEPLETED as i32) + .phase_func(ROCK_DEPLETED, regrow_timer(9, ROCK_START as i32)) + .template( + SHEEP, + &[(SHEEP_START, 1), (SHEEP_LOOT, 2), (SHEEP_SHEARED, 2)], + ) + .func( + SHEEP_START, + FuncTemplate::Shear(DoodadFuncShear { + id: 4, + shear_type_id: 1, + shear_term: REGROW_MS, + }), + SHEEP_LOOT as i32, + ) + .func(SHEEP_LOOT, loot(5, WOOL), SHEEP_SHEARED as i32) + .phase_func(SHEEP_SHEARED, regrow_timer(6, SHEEP_START as i32)) + .data; + d +} + +struct Fx { + server: std::sync::Arc, + client: TestClient, + player: PlayerRef, +} + +fn fx() -> Fx { + let mut data = game_data(); + open_client_skills(&mut data); + let server = std::sync::Arc::new(test_server_with(data)); + server.set_self(); + crate::systems::skills::bind(&server); + crate::systems::npcs::install_hooks(&server); + crate::systems::social::install_hooks(&server); + crate::systems::quests::install_hooks(&server); + crate::systems::economy::wiring::install(&server); + crate::systems::economy::bridges::install(&server); + server.systems.npcs.doodads.tasks.set_manual(true); + + let mut client = TestClient::new(&server, 1, 1001); + let mut c = test_character(1, "Miner", 100.0, 100.0); + c.labor_power = LABOR_BASE as i16; + let player = spawn_player(&server, &client, c, 0x100); + client.conn.active_char = Some(player.clone()); + client.drain(); + Fx { + server, + client, + player, + } +} + +impl Fx { + fn doodad(&self, template: u32) -> DoodadRef { + let world = self.server.world.world(0).unwrap(); + let d = manager::create(&self.server, &world, 0x500, template, None, true).unwrap(); + d.data().transform.set_xyz(102.0, 100.0, 100.0); + manager::spawn(&self.server, &world, &d); + manager::init_doodad(&self.server, &world, &d); + d + } + + fn cast(&mut self, skill: u32, d: &DoodadRef) -> Vec<(u16, Vec)> { + self.player.data().unit.skill_last_used_ms = 0; + let packet = CSStartSkillPacket { + skill_id: skill, + caster: SkillCaster::Unit(self.player.obj_id), + target: SkillCastTarget::Doodad(d.obj_id), + flag: 0, + skill_object: SkillObject::None, + }; + start_skill(&self.server, &mut self.client.conn, packet); + self.client.drain() + } + + fn count(&self, item: u32) -> i32 { + Inv::of(&self.player).items_count(item, -1) + } + + fn advance(&self, ms: u64) -> usize { + self.server + .systems + .npcs + .doodads + .tasks + .advance(&self.server, ms) + } +} + +fn body(p: &dyn Marshal) -> Vec { + let mut s = PacketStream::new(); + p.write(&mut s); + s.into_bytes() +} + +#[tokio::test] +async fn ore_mine_pays_labor_grants_ore_and_regrows() { + let mut fx = fx(); + let d = fx.doodad(VEIN); + assert_eq!(d.data().func_group_id, VEIN_START); + + let frames = fx.cast(ORE_MINE_SKILL, &d); + + assert_eq!( + fx.player.data().labor_power, + (LABOR_BASE - MINING_LABOR) as i16 + ); + assert_eq!(fx.count(ORE), 1); + assert_eq!(d.data().func_group_id, VEIN_DEPLETED); + assert!( + frames.iter().any(|f| f.0 == sc::SCDoodadPhaseChangedPacket), + "no phase packet in {frames:?}" + ); + + // The depleted group's timer brings the vein back (the authored Final / RatioRespawn + // chain does the same in the real data). + assert_eq!(fx.advance(REGROW_MS as u64), 1); + assert_eq!(d.data().func_group_id, VEIN_START); +} + +#[tokio::test] +async fn rock_mine_pays_labor_grants_the_authored_loot_and_depletes() { + let mut fx = fx(); + let d = fx.doodad(ROCK); + assert_eq!(d.data().func_group_id, ROCK_START); + + fx.cast(ORE_MINE_SKILL, &d); + + assert_eq!( + fx.player.data().labor_power, + (LABOR_BASE - MINING_LABOR) as i16 + ); + assert_eq!(fx.count(ORE), 1); + assert_eq!(d.data().func_group_id, ROCK_DEPLETED); +} + +#[tokio::test] +async fn shear_pays_labor_grants_wool_and_regrows() { + let mut fx = fx(); + let d = fx.doodad(SHEEP); + assert_eq!(d.data().func_group_id, SHEEP_START); + + fx.cast(SHEAR_SKILL, &d); + + assert_eq!( + fx.player.data().labor_power, + (LABOR_BASE - SHEAR_LABOR) as i16 + ); + assert_eq!(fx.count(WOOL), 1); + assert_eq!(d.data().func_group_id, SHEEP_SHEARED); + + // The sheared group's regrow timer returns the animal to its un-sheared phase. + assert_eq!(fx.advance(REGROW_MS as u64), 1); + assert_eq!(d.data().func_group_id, SHEEP_START); +} + +#[tokio::test] +async fn mining_without_labor_is_refused_and_changes_nothing() { + let mut fx = fx(); + fx.player.data().labor_power = (MINING_LABOR - 1) as i16; + let d = fx.doodad(VEIN); + + let frames = fx.cast(ORE_MINE_SKILL, &d); + + assert_eq!(fx.player.data().labor_power, (MINING_LABOR - 1) as i16); + assert_eq!(fx.count(ORE), 0); + assert_eq!(d.data().func_group_id, VEIN_START); + let mut expected = crate::systems::skills::packets::SCSkillStartedPacket::new( + ORE_MINE_SKILL, + 0, + SkillCaster::Unit(fx.player.obj_id), + SkillCastTarget::Doodad(d.obj_id), + SkillObject::None, + ); + expected.set_skill_result(skill_result::NEED_LABOR_POWER); + assert!( + frames.contains(&(sc::SCSkillStartedPacket, body(&expected))), + "no NEED_LABOR_POWER in {frames:?}" + ); +} diff --git a/rust/crates/aaemu-game/src/systems/npcs/doodad/mod.rs b/rust/crates/aaemu-game/src/systems/npcs/doodad/mod.rs index 435320e701..13150748c6 100644 --- a/rust/crates/aaemu-game/src/systems/npcs/doodad/mod.rs +++ b/rust/crates/aaemu-game/src/systems/npcs/doodad/mod.rs @@ -62,3 +62,7 @@ pub async fn save( } Ok(0) } + +#[cfg(test)] +#[path = "gather_tests.rs"] +mod gather_tests; From e20d55df68854252a7b41392a827ca515cf44579 Mon Sep 17 00:00:00 2001 From: stsiakal Date: Thu, 22 Oct 2026 06:26:20 +0300 Subject: [PATCH 03/14] fix(housing): construction steps need their materials Co-Authored-By: Claude Opus 5.5 --- rust/crates/aaemu-game/PORTING.md | 17 +++ .../aaemu-game/src/systems/housing/tests.rs | 104 ++++++++++++++++++ .../aaemu-game/src/systems/skills/skill.rs | 9 +- .../src/systems/skills/validation.rs | 41 +++++++ 4 files changed, 169 insertions(+), 2 deletions(-) diff --git a/rust/crates/aaemu-game/PORTING.md b/rust/crates/aaemu-game/PORTING.md index 1ca30539d6..3f3bf47f5c 100644 --- a/rust/crates/aaemu-game/PORTING.md +++ b/rust/crates/aaemu-game/PORTING.md @@ -2502,3 +2502,20 @@ running in place). Four mirrored C# bugs and one missing safeguard: `flow_tests::follow_path_command_set_walks_every_route_point` runs the real command-set shape over three routes with an elevated point and checks every point is targeted in order, the set finishes and the NPC settles in HoldPosition without further movement. + +## Construction step materials (2026-10-22) + +* The construction step skill of an unfinished house needs the consume item of its effects: the + Scarecrow Garden (design 267) step skill 18553 "Construct Garden" ("Spend up to 10 Labor and + 1 Lumber") keeps its Lumber (item 8337 x1) in `skill_effects.consume_item_id` / + `consume_item_count`, not in `skill_reagents`. The C# consumed an effect-level item only when + the player had it and never cancelled the cast, so anyone built houses for free (and the + Rust port mirrored that). `systems::skills::validation::check_build_materials` now refuses the + cast, at the start and again at fire time, with `skill_need_reagent` (result 36, the 1.2 + "reagent missing" result the cast already sends for `skill_reagents`) when the target is an + unfinished house, the skill is the house's current build-step skill and the character lacks + the item count. Labor is still checked by `check_resources` as before and nothing is spent on + a refusal. Every other skill keeps the soft effect-level consume. Reason: retail refuses the + construction without the materials; the step tooltip says it spends 1 Lumber. Regression: + `systems::housing::tests::construction_step_needs_its_effect_consume_item`. The error text the + client shows for result 36 was not re-checked in the client binary. diff --git a/rust/crates/aaemu-game/src/systems/housing/tests.rs b/rust/crates/aaemu-game/src/systems/housing/tests.rs index e389d3b59a..157bc329fc 100644 --- a/rust/crates/aaemu-game/src/systems/housing/tests.rs +++ b/rust/crates/aaemu-game/src/systems/housing/tests.rs @@ -267,6 +267,24 @@ fn housing_data(tax_item: bool) -> GameData { show: true, }, ); + // The build step skills' `CraftEffect` (world interaction 1 = Building). + data.systems.skills.add_effect( + crate::systems::skills::data::EffectKind::CraftEffect, + crate::systems::skills::data::EffectTemplate::Craft { + id: 1, + world_interaction: 1, + }, + 1, + ); + data.systems + .npcs + .area_trigger + .world_interaction_groups + .insert( + 1, + crate::systems::npcs::area_trigger::world_interaction_group::BUILDING, + ); + let h = &mut data.systems.housing; let mut build_steps = BTreeMap::new(); build_steps.insert(0, step(0, 710, 11000, 2)); build_steps.insert(1, step(1, 711, 11001, 1)); @@ -1498,3 +1516,89 @@ async fn tax_plaque_distinguishes_paid_due_and_expired_houses() { assert_eq!(i32::from_le_bytes(body[23..27].try_into().unwrap()), weeks); } } + +/// Item hooks of the construction material tests: a bag of template counts, consumption recorded. +#[derive(Default)] +struct Bag { + counts: Mutex>, +} + +impl crate::systems::skills::ext::ItemSkillHooks for Bag { + fn item_count(&self, _server: &GameServer, _player: &PlayerRef, id: u32) -> i32 { + self.counts.lock().unwrap().get(&id).copied().unwrap_or(0) + } + fn consume_item_template( + &self, + _server: &GameServer, + _player: &PlayerRef, + template_id: u32, + amount: i32, + ) { + *self.counts.lock().unwrap().entry(template_id).or_default() -= amount; + } +} + +const LUMBER: u32 = 8337; + +/// Skill `skill_id` (a Building-target skill with a CraftEffect that consumes 1 Lumber at the +/// effect level) cast by `fx.pa` on `house`. +fn cast_build_skill(fx: &Fx, skill_id: u32, house: &HouseRef, labor_cost: i32) -> (u8, u32) { + use crate::systems::skills::data::{EffectKind, SkillTemplate}; + use crate::systems::skills::state::SkillRun; + use crate::systems::skills::types::{SkillCastTarget, SkillCaster, SkillObject}; + let mut effect = crate::systems::skills::tests::skill_effect(1, EffectKind::CraftEffect, 1); + effect.consume_item_id = LUMBER; + effect.consume_item_count = 1; + let template = SkillTemplate { + target_type: crate::systems::skills::types::SkillTargetType::Building as i32, + max_range: 100, + consume_labor_power: labor_cost, + effects: vec![effect], + ..crate::systems::skills::tests::skill_template(skill_id) + }; + let skill = SkillRun::new(Arc::new(template), 1); + crate::systems::skills::skill::use_skill( + &fx.server, + &skill, + &WorldObject::from(&fx.pa), + SkillCaster::Unit(fx.pa.obj_id), + &mut SkillCastTarget::Unit(house.obj_id), + Some(SkillObject::None), + false, + ) +} + +#[tokio::test] +async fn construction_step_needs_its_effect_consume_item() { + let mut fx = fixture(false); + let bag = Arc::new(Bag::default()); + fx.server.systems.skills.ext.items.install(bag.clone()); + crate::systems::skills::install_hooks(&fx.server); + fx.pa.data().labor_power = 50; + fx.pa.data().unit.mp = 100; + let house = place_house(&fx, DESIGN, &fx.pa.clone(), 120.0, 100.0, 0); + fx.a.drain(); + + // No Lumber: refused with the reagent error, nothing spent, the step is unchanged. + let (result, _) = cast_build_skill(&fx, 11000, &house, 5); + assert_eq!( + result, + crate::systems::skills::unit_reqs::skill_result_for_key("skill_need_reagent") + ); + assert_eq!(result, 36); + assert_eq!(fx.pa.data().labor_power, 50); + assert_eq!(house.data().current_action(), 0); + assert_eq!(bag.counts.lock().unwrap().get(&LUMBER).copied(), None); + + // With Lumber the action is built and the Lumber is taken. + bag.counts.lock().unwrap().insert(LUMBER, 2); + let (result, _) = cast_build_skill(&fx, 11000, &house, 5); + assert_eq!(result, 0); + assert_eq!(house.data().current_action(), 1); + assert_eq!(bag.counts.lock().unwrap()[&LUMBER], 1); + + // A skill that is not the step's build skill keeps the soft consume (cast allowed). + bag.counts.lock().unwrap().insert(LUMBER, 0); + let (result, _) = cast_build_skill(&fx, 4242, &house, 0); + assert_ne!(result, 36); +} diff --git a/rust/crates/aaemu-game/src/systems/skills/skill.rs b/rust/crates/aaemu-game/src/systems/skills/skill.rs index 99b3bae24c..8f5c2c0952 100644 --- a/rust/crates/aaemu-game/src/systems/skills/skill.rs +++ b/rust/crates/aaemu-game/src/systems/skills/skill.rs @@ -387,7 +387,9 @@ pub fn use_skill( } return (skill_result::NO_TARGET, 0); }; - if let Err(result) = super::validation::check(server, skill, caster, target) { + if let Err(result) = super::validation::check(server, skill, caster, target) + .and_then(|()| super::validation::check_build_materials(server, skill, caster, target)) + { return result; } // The 1.2 fishing reactions require the caster's own spawned NPC. OwnerId is @@ -767,7 +769,10 @@ pub fn cast(server: &GameServer, skill: &SkillRef, ctx: &CastCtx) { } // Source, target and resources may change while the cast timer is running. let ready = super::validation::check(server, skill, caster, &ctx.target) - .and_then(|()| super::validation::check_resources(server, skill, caster)); + .and_then(|()| super::validation::check_resources(server, skill, caster)) + .and_then(|()| { + super::validation::check_build_materials(server, skill, caster, &ctx.target) + }); if let Err((result, value)) = ready { if let Some(player) = caster.as_player() { let mut packet = SCSkillStartedPacket::new( diff --git a/rust/crates/aaemu-game/src/systems/skills/validation.rs b/rust/crates/aaemu-game/src/systems/skills/validation.rs index af56e0c099..90068379af 100644 --- a/rust/crates/aaemu-game/src/systems/skills/validation.rs +++ b/rust/crates/aaemu-game/src/systems/skills/validation.rs @@ -91,6 +91,47 @@ pub(super) fn check_resources( Ok(()) } +/// Parity deviation (`PORTING.md`): the construction step of an unfinished house needs the +/// consume item of its step skill's effects (e.g. 1 Lumber for the Scarecrow Garden). The C# +/// consumed an effect-level item only when present and built for free otherwise; retail refuses +/// the cast with the reagent error. Every other skill keeps the soft behaviour. +pub(super) fn check_build_materials( + server: &GameServer, + skill: &SkillRun, + caster: &WorldObject, + target: &Target, +) -> Result<(), (u8, u32)> { + let Some(player) = caster.as_player() else { + return Ok(()); + }; + let Some(house) = target.as_obj().and_then(WorldObject::as_house) else { + return Ok(()); + }; + let (finished, step) = { + let h = house.data(); + (h.current_step < 0, h.current_step) + }; + if finished { + return Ok(()); + } + let Some(template) = crate::systems::housing::manager::template_of(server, house) else { + return Ok(()); + }; + if template.build_steps.get(&step).map(|s| s.skill_id) != Some(skill.id) { + return Ok(()); + } + let items = server.systems.skills.ext.items(); + let missing = skill.template.effects.iter().any(|e| { + e.consume_item_id != 0 + && e.consume_item_count > 0 + && items.item_count(server, player, e.consume_item_id) < e.consume_item_count + }); + if missing { + return fail("skill_need_reagent"); + } + Ok(()) +} + pub(super) fn check( server: &GameServer, skill: &SkillRun, From ad80590e65ab4c6a097b16c494aa722d4c4d7656 Mon Sep 17 00:00:00 2001 From: Nick Messer Date: Fri, 23 Oct 2026 10:00:28 -0400 Subject: [PATCH 04/14] test(world): cover repeated select and forced session release Exercise live and stale character selection against a closed pool, and verify forced cleanup retains departing financial state without disturbing other sessions. Co-Authored-By: GPT-6.1 Sol --- .../aaemu-game/src/world/session_tests.rs | 274 ++++++++++++++++++ 1 file changed, 274 insertions(+) diff --git a/rust/crates/aaemu-game/src/world/session_tests.rs b/rust/crates/aaemu-game/src/world/session_tests.rs index 93b37d1b3d..f0a5102946 100644 --- a/rust/crates/aaemu-game/src/world/session_tests.rs +++ b/rust/crates/aaemu-game/src/world/session_tests.rs @@ -4,9 +4,283 @@ use std::sync::{Arc, Barrier}; +use crate::managers::save::capture_financial_snapshot; +use crate::net::connection::GameState; +use crate::systems::vehicles::mates::MateDb; use crate::test_support::{spawn_player, test_character, test_server, TestClient}; use crate::world::session::{self, SelectDbData}; +async fn assert_select_preserves_live_session(selected_id: u32) { + let server = test_server(); + // Any attempted load must fail immediately, without reaching a real database. + server.db.close().await; + let mut client = TestClient::new(&server, 1, 1007); + let character = test_character(7, "Live", 100.0, 100.0); + let mut sibling = test_character(8, "Other", 200.0, 200.0); + sibling.account_id = character.account_id; + client.conn.characters = vec![character.clone(), sibling]; + assert_eq!(server.enter_world.reserve_character(7, 1), Ok(true)); + session::select_loaded( + &server, + &mut client.conn, + character, + SelectDbData::default(), + ) + .expect("initial select"); + let player = client.conn.active_char.clone().unwrap(); + { + let mut c = player.data(); + c.money = 4321; + c.money2 = 8765; + c.labor_power_unsaved = -25; + c.unit.hp = 37; + c.unit.mp = 19; + c.is_online = true; + } + let world = server.world.world(0).unwrap(); + world.spawn(&player, &server.view_ctx()); + client.conn.state = GameState::World; + let region = player.region().expect("spawned player's region"); + + server.systems.vehicles.mates.character(7, |mates| { + mates.mates.push(MateDb { + id: 70, + item_id: 700, + name: "Mount".into(), + xp: 100, + level: 2, + mileage: 3, + hp: 41, + mp: 23, + owner: 7, + updated_at: Default::default(), + created_at: Default::default(), + }); + // Progress and deletions accumulated since the original load must survive a select. + mates.get_mut(700).unwrap().xp += 300; + mates.removed.push(71); + }); + let mates = server.systems.vehicles.mates.character_mates(7).unwrap(); + client.drain(); + + for _ in 0..2 { + session::select_character(&server, &mut client.conn, selected_id) + .await + .expect("an in-world select is ignored before any database access"); + assert!(Arc::ptr_eq( + client.conn.active_char.as_ref().unwrap(), + &player + )); + assert_eq!(client.conn.state, GameState::World); + assert!(!client.conn.is_closing()); + let live = server.world.character_by_id(7).unwrap(); + assert!(Arc::ptr_eq(&live, &player)); + let spawned = world.character_by_obj_id(player.obj_id).unwrap(); + assert!(Arc::ptr_eq(&spawned, &player)); + assert_eq!(server.world.all_characters().len(), 1); + assert!(server.world.character_by_id(8).is_none()); + assert_eq!(player.region(), Some(region)); + assert!(player.is_visible()); + assert_eq!(server.enter_world.character_owner(7), Some(1)); + assert_eq!(server.enter_world.character_owner(8), None); + assert!(server.save.pending_departure(7).is_none()); + { + let c = player.data(); + assert_eq!( + (c.money, c.money2, c.labor_power_unsaved), + (4321, 8765, -25) + ); + assert_eq!((c.unit.hp, c.unit.mp), (37, 19)); + assert!(c.is_online); + } + assert_eq!( + server.systems.vehicles.mates.character_mates(7), + Some(mates.clone()) + ); + assert_eq!( + client.conn.characters[0].money, 0, + "the lobby copy stays stale" + ); + assert!( + client.drain().is_empty(), + "no second select's initial packets" + ); + assert!(client.commands().is_empty()); + } +} + +#[tokio::test] +async fn repeated_select_preserves_the_live_session() { + assert_select_preserves_live_session(7).await; +} + +#[tokio::test] +async fn selecting_another_character_preserves_the_live_session() { + assert_select_preserves_live_session(8).await; +} + +#[tokio::test] +async fn select_without_an_active_character_still_attempts_the_load() { + let server = test_server(); + server.db.close().await; + let mut client = TestClient::new(&server, 1, 1007); + client.conn.characters = vec![test_character(7, "Lobby", 100.0, 100.0)]; + + let error = session::select_character(&server, &mut client.conn, 7) + .await + .expect_err("an initial select must reach the database"); + assert!( + matches!(error, crate::GameError::Db(sqlx::Error::PoolClosed)), + "{error}" + ); + assert!(client.conn.active_char.is_none()); + assert_eq!(server.enter_world.character_owner(7), None); + assert!(server.world.all_characters().is_empty()); +} + +#[tokio::test] +async fn a_stale_active_character_does_not_block_selecting_after_departure() { + let server = test_server(); + server.db.close().await; + let mut old = TestClient::new(&server, 1, 1007); + let mut sibling = test_character(8, "Other", 100.0, 100.0); + sibling.account_id = 1007; + old.conn.characters = vec![sibling]; + let stale = spawn_player( + &server, + &old, + test_character(7, "Returner", 100.0, 100.0), + 0x107, + ); + old.conn.active_char = Some(stale.clone()); + let world = server.world.world(0).unwrap(); + world.delete(&stale); + assert!(server.world.try_remove_character(stale.obj_id)); + + // A connection keeps active_char after departure. Even if the object id is reused by a + // newer session, only the exact Player still registered in the world triggers the guard. + let newer = TestClient::new(&server, 2, 1007); + let replacement = spawn_player( + &server, + &newer, + test_character(7, "Returner", 100.0, 100.0), + stale.obj_id, + ); + assert_eq!(server.enter_world.reserve_character(7, 2), Ok(true)); + let error = session::select_character(&server, &mut old.conn, 8) + .await + .expect_err("a departed active_char must not bypass the next select's load"); + assert!( + matches!(error, crate::GameError::Db(sqlx::Error::PoolClosed)), + "{error}" + ); + assert!(Arc::ptr_eq(old.conn.active_char.as_ref().unwrap(), &stale)); + assert!(Arc::ptr_eq( + &server.world.character_by_id(7).unwrap(), + &replacement + )); + assert_eq!(server.enter_world.character_owner(7), Some(2)); + assert_eq!(server.enter_world.character_owner(8), None); + assert!(server.save.pending_departure(7).is_none()); +} + +#[tokio::test] +async fn force_release_retains_departing_state_for_the_next_financial_snapshot() { + let server = test_server(); + server.db.close().await; + let departing_client = TestClient::new(&server, 1, 1007); + let other_client = TestClient::new(&server, 2, 1008); + let departing = spawn_player( + &server, + &departing_client, + test_character(7, "Departing", 100.0, 100.0), + 0x107, + ); + let other = spawn_player( + &server, + &other_client, + test_character(8, "Staying", 110.0, 110.0), + 0x108, + ); + { + let mut c = departing.data(); + c.money = 4321; + c.money2 = 8765; + c.labor_power_unsaved = -25; + c.unit.hp = 37; + } + other.data().money = 99; + assert_eq!(server.enter_world.reserve_character(7, 1), Ok(true)); + // An abandoned select can leave a reservation without a corresponding world entry. + assert_eq!(server.enter_world.reserve_character(9, 1), Ok(true)); + assert_eq!(server.enter_world.reserve_character(8, 2), Ok(true)); + let weak = Arc::downgrade(&departing); + let obj_id = departing.obj_id; + let region = other.region().unwrap(); + drop(departing); + + // There need not be an active_char on the failed connection for fallback cleanup to work. + assert!(departing_client.conn.active_char.is_none()); + session::force_release_connection(&server, 1); + let retained = weak + .upgrade() + .expect("the departure set must retain the removed Player"); + let pending = server.save.pending_departure(7).expect("pending departure"); + assert!(Arc::ptr_eq(&pending, &retained)); + assert!(server.world.character_by_id(7).is_none()); + assert!(server.world.character_by_obj_id(obj_id).is_none()); + let world = server.world.world(0).unwrap(); + assert!(world.object(obj_id).is_none()); + assert!(retained.region().is_none()); + assert!(!retained.is_visible()); + assert_eq!(server.enter_world.character_owner(7), None); + assert_eq!(server.enter_world.character_owner(9), None); + assert!(server.save.pending_departure(9).is_none()); + + // Repeated fallback cleanup and a connection with no active player are harmless. + session::force_release_connection(&server, 1); + session::force_release_connection(&server, 999); + assert!(Arc::ptr_eq( + &server.world.character_by_id(8).unwrap(), + &other + )); + assert!(Arc::ptr_eq( + &world.character_by_obj_id(other.obj_id).unwrap(), + &other + )); + assert_eq!(server.world.all_characters().len(), 1); + assert_eq!(server.enter_world.character_owner(8), Some(2)); + assert_eq!(other.region(), Some(region)); + assert!(other.is_visible()); + assert_eq!(other.data().money, 99); + assert!(server.save.pending_departure(8).is_none()); + + let snapshot = capture_financial_snapshot(&server); + assert_eq!( + snapshot.characters.len(), + 2, + "each live/departing wallet once" + ); + let (player, saved) = snapshot + .characters + .iter() + .find(|(p, _)| p.character_id == 7) + .expect("force-removed player in the next save"); + assert!(Arc::ptr_eq(player, &retained)); + assert_eq!( + (saved.money, saved.money2, saved.labor_power_unsaved), + (4321, 8765, -25) + ); + assert_eq!(saved.unit.hp, 37); + let (player, saved) = snapshot + .characters + .iter() + .find(|(p, _)| p.character_id == 8) + .expect("unrelated player still saved"); + assert!(Arc::ptr_eq(player, &other)); + assert_eq!(saved.money, 99); +} + #[tokio::test] async fn the_same_character_cannot_enter_the_world_twice() { let server = test_server(); From 6ac9def668acdb36665a3bd8a1778c4da99b3d45 Mon Sep 17 00:00:00 2001 From: Nick Messer Date: Fri, 23 Oct 2026 10:27:28 -0400 Subject: [PATCH 05/14] ci: run Rust checks on rust-rewrite pushes --- .github/workflows/rust.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index ca30e632c5..d1134012be 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -2,7 +2,7 @@ name: Build & Unit Test on: push: - branches: [master, develop] + branches: [master, develop, rust-rewrite] pull_request: # The branches below must be a subset of the branches above branches: From bf18d3f5fcc1e9d894146e19f927cb93cb36c967 Mon Sep 17 00:00:00 2001 From: Nick Messer Date: Fri, 23 Oct 2026 10:43:18 -0400 Subject: [PATCH 06/14] npcs: SCNpcInteractionSkillList lists the skills of the NPC's interaction set CSStartInteraction answered 0 for an NPC without a function flag, so the client never offered what npc_interactions gives it (the beauty salon helper's 'Enter the beauty salon', skill 22780). npc_interactions is loaded per npc_interaction_set_id; when no function applies the answer lists the set's skills in table order, and the function still wins when there is one. Co-Authored-By: Claude Sonnet 5.5 --- .../aaemu-game/src/systems/npcs/npc/data.rs | 18 +++++++++ .../src/systems/npcs/npc/packets.rs | 39 +++++++++++++++---- 2 files changed, 50 insertions(+), 7 deletions(-) diff --git a/rust/crates/aaemu-game/src/systems/npcs/npc/data.rs b/rust/crates/aaemu-game/src/systems/npcs/npc/data.rs index dcc8b97aed..d8b63f176e 100644 --- a/rust/crates/aaemu-game/src/systems/npcs/npc/data.rs +++ b/rust/crates/aaemu-game/src/systems/npcs/npc/data.rs @@ -495,6 +495,9 @@ pub struct NpcData { pub grade_holdable_dps: HashMap, /// `localized_texts` `npcs.name` in the configured language. pub localized_names: HashMap, + /// `npc_interactions` (`npc_interaction_set_id` -> `skills.id` in table order): what the client's talk offers + /// an NPC that has no function flag (the beauty salon helper offers "Enter the beauty salon"). + pub interactions: HashMap>, } fn dup(what: &str, id: u32) -> crate::data::GameDataError { @@ -935,6 +938,7 @@ impl NpcData { d.load_models(conn)?; d.load_weapons(conn)?; d.load_localized_names(conn, language)?; + d.load_interactions(conn)?; Ok(d) } @@ -1058,6 +1062,16 @@ impl NpcData { } /// `localized_texts` rows for `npcs.name` (`LocalizationManager`). + fn load_interactions(&mut self, conn: &Connection) -> rusqlite::Result<()> { + for_each_row(conn, "SELECT * FROM npc_interactions ORDER BY id", [], |r| { + self.interactions + .entry(r.i32("npc_interaction_set_id")?) + .or_default() + .push(r.u32("skill_id")?); + Ok(()) + }) + } + fn load_localized_names(&mut self, conn: &Connection, language: &str) -> rusqlite::Result<()> { let sql = format!( "SELECT idx, \"{}\" AS txt FROM localized_texts \ @@ -1235,6 +1249,8 @@ mod tests { INSERT INTO item_weapons VALUES (1, 601, 1); CREATE TABLE items (id INT, level INT); INSERT INTO items VALUES (601, 20); + CREATE TABLE npc_interactions (id INT, npc_interaction_set_id INT, skill_id INT); + INSERT INTO npc_interactions VALUES (1, 12, 22780), (2, 12, 23469), (3, 13, 999); CREATE TABLE localized_texts (id INT, tbl_name TEXT, tbl_column_name TEXT, idx INT, en_us TEXT); INSERT INTO localized_texts VALUES (1, 'npcs', 'name', 100, 'Guard'), @@ -1318,6 +1334,8 @@ mod tests { assert!(d.is_fly_or_swim(2) && !d.is_fly_or_swim(10) && !d.is_fly_or_swim(3)); assert_eq!(d.weapons[&601].level, 20); assert_eq!(d.localized_name(100, "x"), "Guard"); + assert_eq!(d.interactions[&12], vec![22780, 23469]); + assert_eq!(d.interactions[&13], vec![999]); assert_eq!(d.localized_name(101, "x"), "x"); assert_eq!(d.total_character_customs.len(), 1); assert_eq!(d.total_character_custom(5).unwrap().modifier.len(), 128); diff --git a/rust/crates/aaemu-game/src/systems/npcs/npc/packets.rs b/rust/crates/aaemu-game/src/systems/npcs/npc/packets.rs index 874ade08de..37a04a9521 100644 --- a/rust/crates/aaemu-game/src/systems/npcs/npc/packets.rs +++ b/rust/crates/aaemu-game/src/systems/npcs/npc/packets.rs @@ -235,6 +235,18 @@ pub fn interaction_option(t: &super::data::NpcTemplate) -> u32 { } } +/// The skills `SCNpcInteractionSkillList` lists for an NPC: its function ([`interaction_option`]), else the skills of its +/// `npc_interaction_set_id` (`npc_interactions`: the beauty salon helper offers "Enter the beauty salon", 22780), else 0. +pub fn interaction_skills(data: &super::data::NpcData, t: &super::data::NpcTemplate) -> Vec { + match interaction_option(t) { + 0 => match data.interactions.get(&t.npc_interaction_set_id) { + Some(skills) if !skills.is_empty() => skills.clone(), + _ => vec![0], + }, + option => vec![option], + } +} + impl ClientPacket for CSStartInteractionPacket { const NAME: &'static str = "CSStartInteractionPacket"; @@ -284,14 +296,11 @@ impl ClientPacket for CSStartInteractionPacket { if let Some(npc) = world.npc(self.npc_obj_id) { let template_id = npc.data().unit.template_id; // `npc.Template` is never null for a created NPC. - let option = server - .game_data - .systems - .npcs - .npc + let npcs = &server.game_data.systems.npcs.npc; + let skills = npcs .template(template_id) - .map_or(0, interaction_option); - me.send(packet(vec![option])); + .map_or_else(|| vec![0], |t| interaction_skills(npcs, t)); + me.send(packet(skills)); } if let Some(WorldObject::Mate(_)) = world.unit(self.npc_obj_id) { me.send(packet(vec![skills_enum::SLAVE_MOUNTING])); @@ -729,4 +738,20 @@ mod tests { t.banker = true; assert_eq!(interaction_option(&t), skills_enum::USE_WAREHOUSE); } + + #[test] + fn interaction_set_skills_fill_in_for_a_functionless_npc() { + let mut data = super::super::data::NpcData::default(); + data.interactions.insert(12, vec![22780, 23469]); + let mut t = super::super::data::NpcTemplate::default(); + assert_eq!(interaction_skills(&data, &t), vec![0]); + t.npc_interaction_set_id = 12; + assert_eq!(interaction_skills(&data, &t), vec![22780, 23469]); + t.npc_interaction_set_id = 99; + assert_eq!(interaction_skills(&data, &t), vec![0]); + // a function stays what the answer lists + t.npc_interaction_set_id = 12; + t.merchant = true; + assert_eq!(interaction_skills(&data, &t), vec![skills_enum::USE_STORE]); + } } From 8466cb561cff277d5efac296c01ccd4cb487b16a Mon Sep 17 00:00:00 2001 From: Nick Messer Date: Fri, 23 Oct 2026 11:28:50 -0400 Subject: [PATCH 07/14] fix(housing): make construction material payments atomic Commit each selected building effect only after a checked full material debit, then flush item callbacks after releasing the housing lock. Preserve optional consumption for other effects. Report actual container consumption exactly once, including depleted preferred stacks, while preserving item tasks and callback order. Add deterministic race, payment, callback and compatibility regressions. Validation: 204 focused library tests passed; 15 housing tests ignored. Game all-target clippy with -D warnings and cargo fmt --all -- --check passed. Co-Authored-By: Codex --- rust/crates/aaemu-game/PORTING.md | 26 +- .../crates/aaemu-game/src/models/container.rs | 47 +- .../aaemu-game/src/models/container_tests.rs | 223 +++++++- .../aaemu-game/src/systems/economy/bridges.rs | 45 ++ .../src/systems/housing/lifecycle_tests.rs | 490 ++++++++++++++++++ .../aaemu-game/src/systems/housing/mod.rs | 26 +- .../aaemu-game/src/systems/housing/ops.rs | 108 ++-- .../aaemu-game/src/systems/housing/tests.rs | 86 --- .../systems/skills/cast_validation_tests.rs | 38 ++ .../aaemu-game/src/systems/skills/ext.rs | 14 + .../aaemu-game/src/systems/skills/skill.rs | 63 ++- 11 files changed, 1016 insertions(+), 150 deletions(-) diff --git a/rust/crates/aaemu-game/PORTING.md b/rust/crates/aaemu-game/PORTING.md index 3f3bf47f5c..bf2c463319 100644 --- a/rust/crates/aaemu-game/PORTING.md +++ b/rust/crates/aaemu-game/PORTING.md @@ -2517,5 +2517,29 @@ finishes and the NPC settles in HoldPosition without further movement. the item count. Labor is still checked by `check_resources` as before and nothing is spent on a refusal. Every other skill keeps the soft effect-level consume. Reason: retail refuses the construction without the materials; the step tooltip says it spends 1 Lumber. Regression: - `systems::housing::tests::construction_step_needs_its_effect_consume_item`. The error text the + `systems::housing::lifecycle_tests::construction_step_needs_its_effect_consume_item_before_cast`. + The error text the client shows for result 36 was not re-checked in the client binary. +* `systems::housing`: the final availability check is early feedback, not the payment boundary. + A selected player-to-house Building `CraftEffect` now checks the live house and current step + under the housing operation lock, then consumes its full effect-level material through + `ItemSkillHooks::pay_building_material` immediately before advancing progress. The economy + bridge preflights inventory, equipment and bank under one item transaction; a defensive short + debit restores exact container snapshots and discards queued effects. Persistence completes + under the economy lock, which is released before progress callbacks; item callbacks flush + after the housing lock. Missing payment cancels with result 36, without progress, labor or + the success interaction quest event. Rejected/stale house effects never fall back to the + legacy optional debit. Other effects retain that optional behavior. Regressions remove the + last real item after the final availability snapshot, retry after replenishing, check exact + and extra stock in every supported container, and prove non-building NPC damage still applies + without its optional item. Zero-step designs already finish during placement; a subsequent + construction action is rejected before payment. +* `systems::economy`: container consumption callbacks now report the actual consumed delta + exactly once for full, partial and preferred stacks. The C# `ItemContainer.ConsumeItem` + decremented a depleted stack to zero before `RemoveItem` reported its count; the Rust port + mirrored that zero-count event (plus a second, correct event for a preferred stack). Removal + now accepts the consumed delta internally while direct removals keep their remaining-count + semantics. The callback still precedes `EquipLeave`, and wire item tasks are unchanged. + Container regressions cover full/preferred/partial/multiple stacks, equipment callback order + and direct removal; the housing payment callback test covers both the last unit and a partial + stack, with both operation locks released. diff --git a/rust/crates/aaemu-game/src/models/container.rs b/rust/crates/aaemu-game/src/models/container.rs index 5777f51548..1ccb96cf7f 100644 --- a/rust/crates/aaemu-game/src/models/container.rs +++ b/rust/crates/aaemu-game/src/models/container.rs @@ -744,6 +744,20 @@ impl ItemContainer { item_id: u64, release_id: bool, env: &mut ItemEnv<'_>, + ) -> Option { + self.remove_item_task_with_consumed_count(task, item_id, release_id, None, env) + } + + /// Consumption has already decremented a depleted stack to zero. Carry its actual delta + /// through removal so the one Consumed event still precedes EquipLeave, just as for an + /// ordinary direct removal (which uses the item's remaining count). + fn remove_item_task_with_consumed_count( + &mut self, + task: u8, + item_id: u64, + release_id: bool, + consumed_count: Option, + env: &mut ItemEnv<'_>, ) -> Option { let idx = self.items.iter().position(|i| i.id == item_id)?; if !env.rules.can_destroy(&self.items[idx]) { @@ -769,11 +783,14 @@ impl ItemContainer { env.fx.push(ItemFx::ReleaseId(item.id)); } self.update_free_slot_count(); - env.fx.push(ItemFx::Consumed { - owner: self.owner_id, - template_id: item.template_id, - count: item.count, - }); + let consumed_count = consumed_count.unwrap_or(item.count); + if consumed_count > 0 { + env.fx.push(ItemFx::Consumed { + owner: self.owner_id, + template_id: item.template_id, + count: consumed_count, + }); + } self.on_leave_container(&item, old_slot, &mut env.fx); Some(item) } @@ -805,13 +822,13 @@ impl ItemContainer { return 0; }; found.remove(pos); - total += self.consume_one(task, pid, &mut amount, &mut tasks, env, true); + total += self.consume_one(task, pid, &mut amount, &mut tasks, env); } } if amount > 0 { found.sort_by_key(|id| self.get_item_by_id(*id).map_or(0, |i| i.slot)); for id in found { - total += self.consume_one(task, id, &mut amount, &mut tasks, env, false); + total += self.consume_one(task, id, &mut amount, &mut tasks, env); if amount <= 0 { break; // We are done with the list, leave the rest as is } @@ -831,7 +848,6 @@ impl ItemContainer { amount: &mut i32, tasks: &mut Vec, env: &mut ItemEnv<'_>, - preferred: bool, ) -> i32 { let Some(item) = self.items.iter_mut().find(|i| i.id == id) else { return 0; @@ -842,23 +858,14 @@ impl ItemContainer { *amount -= to_remove; let template_id = item.template_id; if item.count > 0 { - if !preferred { - env.fx.push(ItemFx::Consumed { - owner: self.owner_id, - template_id, - count: to_remove, - }); - } - tasks.push(ItemTask::count_update(item, -to_remove)); - } else { - self.remove_item_task(task, id, true, env); // Normally, this can never fail - } - if preferred { env.fx.push(ItemFx::Consumed { owner: self.owner_id, template_id, count: to_remove, }); + tasks.push(ItemTask::count_update(item, -to_remove)); + } else { + self.remove_item_task_with_consumed_count(task, id, true, Some(to_remove), env); } to_remove } diff --git a/rust/crates/aaemu-game/src/models/container_tests.rs b/rust/crates/aaemu-game/src/models/container_tests.rs index 63db29d6e9..ac3b3cfb59 100644 --- a/rust/crates/aaemu-game/src/models/container_tests.rs +++ b/rust/crates/aaemu-game/src/models/container_tests.rs @@ -8,7 +8,7 @@ use crate::data::items::{bind_type, ItemData, ItemTemplate}; use crate::models::container::{slot_type, ContainerKind, ItemContainer}; use crate::models::item::Item; -use crate::models::item_task::{task_type, ItemFxList}; +use crate::models::item_task::{task_type, ItemFx, ItemFxList, ItemTask}; /// `CharacterMock` (a `Character` with no connection; only its id is used here). struct CharacterMock { @@ -65,3 +65,224 @@ fn inventory_adds_item() { .collect(); assert_eq!(found.len(), 1, "SingleOrDefault"); } + +fn consumption_fixture(count: i32, equipment: bool) -> (crate::GameServer, ItemContainer) { + let mut data = crate::data::GameData::empty(); + let mut template = ItemTemplate::plain(1, 100); + if equipment { + template.kind = + crate::data::items::TemplateKind::Armor(crate::data::items::EquipTemplate { + slot_type_id: 3, // chest + ..Default::default() + }); + template.max_count = 1; + } + data.items.templates.insert(1, template); + let server = crate::test_support::test_server_with(data); + let (kind, st, slot) = if equipment { + (ContainerKind::Equipment, slot_type::EQUIPMENT, 2) + } else { + (ContainerKind::Item, slot_type::INVENTORY, 0) + }; + let mut container = ItemContainer::new(kind, 7, st, 100); + container.has_owner = true; + let item = Item::create( + 1, + server.game_data.items.template(1).unwrap(), + count, + 0, + 1, + &server.game_data.items, + 0, + ); + assert_eq!( + container.add_new_item(item, slot, &server.game_data.items), + Ok(true) + ); + (server, container) +} + +fn consumed(fx: &ItemFxList) -> Vec<(u32, u32, i32)> { + fx.0.iter() + .filter_map(|fx| match fx { + ItemFx::Consumed { + owner, + template_id, + count, + } => Some((*owner, *template_id, *count)), + _ => None, + }) + .collect() +} + +fn tasks(fx: &ItemFxList) -> Vec { + fx.0.iter() + .filter_map(|fx| match fx { + ItemFx::Tasks { tasks, .. } => Some(tasks.iter().cloned()), + _ => None, + }) + .flatten() + .collect() +} + +fn full_stack_consumption(preferred: Option) { + let (server, mut container) = consumption_fixture(3, false); + let before = container.get_item_by_id(1).unwrap().clone(); + let mut env = crate::systems::economy::inventory::server_env(&server); + assert_eq!( + container.consume_item( + task_type::SKILL_EFFECT_CONSUMPTION, + 1, + 3, + preferred, + &mut env + ), + 3 + ); + assert!(container.items.is_empty()); + assert_eq!(consumed(&env.fx), vec![(7, 1, 3)]); + assert_eq!(tasks(&env.fx), vec![ItemTask::remove_slot(&before)]); + assert_eq!( + env.fx + .0 + .iter() + .filter(|fx| matches!(fx, ItemFx::ReleaseId(1))) + .count(), + 1 + ); +} + +#[tokio::test] +async fn consumption_full_stack_reports_actual_count_once() { + full_stack_consumption(None); +} + +#[tokio::test] +async fn consumption_preferred_full_stack_reports_actual_count_once() { + full_stack_consumption(Some(1)); +} + +#[tokio::test] +async fn consumption_partial_stack_reports_delta_instead_of_remaining_count() { + for preferred in [None, Some(1)] { + let (server, mut container) = consumption_fixture(3, false); + let before = container.get_item_by_id(1).unwrap().clone(); + let mut env = crate::systems::economy::inventory::server_env(&server); + assert_eq!( + container.consume_item( + task_type::SKILL_EFFECT_CONSUMPTION, + 1, + 1, + preferred, + &mut env + ), + 1 + ); + assert_eq!(container.get_item_by_id(1).unwrap().count, 2); + assert_eq!(consumed(&env.fx), vec![(7, 1, 1)]); + assert_eq!(tasks(&env.fx), vec![ItemTask::count_update(&before, -1)]); + assert!(!env.fx.0.iter().any(|fx| matches!(fx, ItemFx::ReleaseId(_)))); + } +} + +#[tokio::test] +async fn consumption_multiple_stacks_reports_each_actual_delta_once() { + for preferred in [None, Some(2)] { + let (server, mut container) = consumption_fixture(2, false); + let first = container.get_item_by_id(1).unwrap().clone(); + let second = Item::create( + 2, + server.game_data.items.template(1).unwrap(), + 3, + 0, + 1, + &server.game_data.items, + 0, + ); + assert_eq!( + container.add_new_item(second, 1, &server.game_data.items), + Ok(true) + ); + let second = container.get_item_by_id(2).unwrap().clone(); + let mut env = crate::systems::economy::inventory::server_env(&server); + assert_eq!( + container.consume_item( + task_type::SKILL_EFFECT_CONSUMPTION, + 1, + 4, + preferred, + &mut env + ), + 4 + ); + if preferred.is_some() { + assert_eq!(consumed(&env.fx), vec![(7, 1, 3), (7, 1, 1)]); + assert_eq!(container.get_item_by_id(1).unwrap().count, 1); + assert_eq!( + tasks(&env.fx), + vec![ + ItemTask::remove_slot(&second), + ItemTask::count_update(&first, -1) + ] + ); + } else { + assert_eq!(consumed(&env.fx), vec![(7, 1, 2), (7, 1, 2)]); + assert_eq!(container.get_item_by_id(2).unwrap().count, 1); + assert_eq!( + tasks(&env.fx), + vec![ + ItemTask::remove_slot(&first), + ItemTask::count_update(&second, -2) + ] + ); + } + } +} + +#[tokio::test] +async fn consumption_equipment_notifies_consumption_before_equip_leave() { + for preferred in [None, Some(1)] { + let (server, mut container) = consumption_fixture(1, true); + let before = container.get_item_by_id(1).unwrap().clone(); + let mut env = crate::systems::economy::inventory::server_env(&server); + assert_eq!( + container.consume_item( + task_type::SKILL_EFFECT_CONSUMPTION, + 1, + 1, + preferred, + &mut env + ), + 1 + ); + assert_eq!(consumed(&env.fx), vec![(7, 1, 1)]); + let consumed_at = env + .fx + .0 + .iter() + .position(|fx| matches!(fx, ItemFx::Consumed { .. })) + .unwrap(); + let leave_at = env + .fx + .0 + .iter() + .position(|fx| matches!(fx, ItemFx::EquipLeave { .. })) + .unwrap(); + assert!(consumed_at < leave_at); + assert_eq!(tasks(&env.fx), vec![ItemTask::remove_slot(&before)]); + } +} + +#[tokio::test] +async fn consumption_direct_removal_retains_the_original_stack_count_and_task() { + let (server, mut container) = consumption_fixture(3, false); + let before = container.get_item_by_id(1).unwrap().clone(); + let mut env = crate::systems::economy::inventory::server_env(&server); + assert_eq!( + container.remove_item_task(task_type::DESTROY, 1, true, &mut env), + Some(before.clone()) + ); + assert_eq!(consumed(&env.fx), vec![(7, 1, 3)]); + assert_eq!(tasks(&env.fx), vec![ItemTask::remove_slot(&before)]); + assert!(container.items.is_empty()); +} diff --git a/rust/crates/aaemu-game/src/systems/economy/bridges.rs b/rust/crates/aaemu-game/src/systems/economy/bridges.rs index 5aa80ac605..6b8be07d59 100644 --- a/rust/crates/aaemu-game/src/systems/economy/bridges.rs +++ b/rust/crates/aaemu-game/src/systems/economy/bridges.rs @@ -957,6 +957,51 @@ impl ItemSkillHooks for EconomyForSkills { ); } + fn pay_building_material( + &self, + server: &GameServer, + player: &PlayerRef, + template_id: u32, + amount: i32, + ) -> Option { + if template_id == 0 || amount <= 0 { + return Some(ItemFxList::default()); + } + let mut txn = ItemTxn::begin(server); + let inv = Inv::of(player); + // Match both the availability check and Inventory.ConsumeItem's container set. + if inv.items_count(template_id, -1) < amount { + return None; + } + let snapshots: Vec<_> = [slot_type::INVENTORY, slot_type::EQUIPMENT, slot_type::BANK] + .into_iter() + .filter_map(|st| inv.get(st)) + .map(|container| { + let snapshot = lock(&container).clone(); + (container, snapshot) + }) + .collect(); + let consumed = inventory::consume_item( + &mut txn, + &inv, + None, + task_type::SKILL_EFFECT_CONSUMPTION, + template_id, + amount, + None, + ); + if consumed != amount { + // ItemTxn drops by COMMITTING its effects. Restore the exact items (ids, slots, + // flags and container state) and discard every queued effect before it drops. + for (container, snapshot) in snapshots { + *lock(&container) = snapshot; + } + txn.env.take_fx(); + return None; + } + Some(txn.into_fx()) + } + fn item_set(&self, server: &GameServer, item_set_id: u32) -> Vec<(u32, i32)> { server .game_data diff --git a/rust/crates/aaemu-game/src/systems/housing/lifecycle_tests.rs b/rust/crates/aaemu-game/src/systems/housing/lifecycle_tests.rs index cab0bcf41b..5c8a8bd2e8 100644 --- a/rust/crates/aaemu-game/src/systems/housing/lifecycle_tests.rs +++ b/rust/crates/aaemu-game/src/systems/housing/lifecycle_tests.rs @@ -21,6 +21,11 @@ use crate::opcodes::sc; use crate::server::GameServer; use crate::systems::economy::bridges::EconomyForHousing; use crate::systems::economy::inventory::Inv; +use crate::systems::skills::data::{EffectKind, EffectTemplate, SkillTemplate}; +use crate::systems::skills::ext::ItemSkillHooks; +use crate::systems::skills::skill::{self, CastCtx}; +use crate::systems::skills::state::{SkillRef, SkillRun}; +use crate::systems::skills::types::{SkillCastTarget, SkillCaster, SkillObject, SkillTargetType}; use crate::test_support::{spawn_player, test_character, test_server_with, TestClient}; use crate::world::{Entity, HouseRef, PlayerRef, WorldObject}; @@ -28,6 +33,9 @@ const DESIGN: u32 = 300; const DESIGN_ITEM: u32 = 9000; const CHAIR_ITEM: u32 = 8000; const CHAIR_DOODAD: u32 = 5000; +const LUMBER: u32 = 8337; +const BUILD_SKILL: u32 = 11000; +const BUILD_QUEST: u32 = 77; struct Fixture { server: GameServer, @@ -196,6 +204,488 @@ fn count(f: &Fixture, template_id: u32) -> i32 { Inv::of(&f.player).items_count_in(slot_type::INVENTORY, template_id, -1) } +fn material_fixture() -> (Fixture, HouseRef) { + material_fixture_with_item(ItemTemplate::plain(LUMBER, 100)) +} + +fn material_fixture_with_item(material: ItemTemplate) -> (Fixture, HouseRef) { + use crate::systems::quests::model::{detail, kind}; + use crate::systems::quests::templates::{ActKind, QuestComponentTemplate, QuestTemplate}; + + let mut data = GameData::empty(); + data.items.templates.insert(LUMBER, material); + data.systems.skills.add_effect( + EffectKind::CraftEffect, + EffectTemplate::Craft { + id: 1, + world_interaction: 77, + }, + 1, + ); + data.systems + .npcs + .area_trigger + .world_interaction_groups + .insert( + 77, + crate::systems::npcs::area_trigger::world_interaction_group::BUILDING, + ); + // A real interaction objective distinguishes a failed payment from the old router's + // "handled" result. Two actions are required, so the first success remains observable. + let quests = &mut data.systems.quests; + quests.add_template(QuestTemplate { + id: BUILD_QUEST, + detail_id: detail::NORMAL, + ..Default::default() + }); + for (id, kind_id) in [(771, kind::START), (772, kind::PROGRESS)] { + quests.add_component(QuestComponentTemplate { + id, + quest_id: BUILD_QUEST, + kind_id, + ..Default::default() + }); + } + quests.add_act(771, 771, 771, 0, ActKind::ConAutoComplete); + quests.add_act( + 772, + 772, + 772, + 2, + ActKind::ObjInteraction { + wi_id: 77, + doodad_id: DESIGN, + use_alias: false, + team_share: false, + highlight_doodad_id: 0, + highlight_doodad_phase: -1, + alias_id: 0, + phase: 0, + }, + ); + quests.finish(); + let mut f = fixture_with_data(false, 400_000, None, data); + f.server + .systems + .skills + .ext + .items + .install(Arc::new(crate::systems::economy::bridges::EconomyForSkills)); + crate::systems::skills::install_hooks(&f.server); + f.player.data().labor_power = 50; + f.player.data().unit.mp = 100; + let design = give(&f, slot_type::INVENTORY, DESIGN_ITEM, 1, 0); + ops::build(&f.server, &f.player, 1001, &packet(design)); + let house = f.server.systems.housing.manager.all()[0].clone(); + assert_eq!( + crate::systems::quests::events::add_quest(&f.server, &f.player, BUILD_QUEST, true), + Some(true) + ); + f.server.systems.quests.run_queued_evaluations(&f.server); + assert_eq!( + f.player + .data() + .quest_state + .active_quest(BUILD_QUEST) + .unwrap() + .step, + kind::PROGRESS + ); + f.client.drain(); + (f, house) +} + +fn build_skill(id: u32, amount: i32) -> SkillRef { + let mut effect = crate::systems::skills::tests::skill_effect(1, EffectKind::CraftEffect, 1); + effect.consume_item_id = LUMBER; + effect.consume_item_count = amount; + SkillRun::new( + Arc::new(SkillTemplate { + target_type: SkillTargetType::Building as i32, + consume_labor_power: 5, + effects: vec![effect], + ..crate::systems::skills::tests::skill_template(id) + }), + 1, + ) +} + +fn build_ctx(f: &Fixture, house: &HouseRef) -> CastCtx { + CastCtx { + caster: WorldObject::from(&f.player), + caster_caster: SkillCaster::Unit(f.player.obj_id), + target: crate::systems::skills::geometry::Target::Obj(WorldObject::from(house)), + target_caster: SkillCastTarget::Unit(house.obj_id), + skill_object: SkillObject::None, + } +} + +fn fire_build(f: &Fixture, house: &HouseRef, skill: &SkillRef) -> u16 { + let timeline = f.server.systems.skills.tl_ids.next_id(0, 0); + skill.state().tl_id = timeline; + skill.state().initial_target = house.obj_id; + skill::cast(&f.server, skill, &build_ctx(f, house)); + assert_eq!(skill.tl_id(), 0); + assert!(!f.server.systems.skills.tl_ids.is_assigned(timeline)); + timeline +} + +fn interaction_progress(f: &Fixture) -> i32 { + f.player + .data() + .quest_state + .active_quest(BUILD_QUEST) + .unwrap() + .objectives[0] +} + +/// Remove the last real material immediately after taking the final availability snapshot. +/// `cast`, called directly below, performs exactly that check before applying the effect. +/// The old optional-consumption path then sees zero and advances the house for free. +struct RemoveAfterFinalCheck(std::sync::atomic::AtomicBool); + +impl ItemSkillHooks for RemoveAfterFinalCheck { + fn item_count(&self, server: &GameServer, player: &PlayerRef, id: u32) -> i32 { + use crate::systems::economy::{ + bridges::EconomyForSkills, + inventory::{self, ItemTxn}, + }; + let snapshot = EconomyForSkills.item_count(server, player, id); + if self.0.swap(false, std::sync::atomic::Ordering::SeqCst) { + assert_eq!(id, LUMBER); + assert_eq!(snapshot, 1); + let mut txn = ItemTxn::begin(server); + assert_eq!( + inventory::consume_item( + &mut txn, + &Inv::of(player), + None, + crate::models::item_task::task_type::DESTROY, + id, + 1, + None + ), + 1 + ); + } + snapshot + } + + fn pay_building_material( + &self, + server: &GameServer, + player: &PlayerRef, + id: u32, + amount: i32, + ) -> Option { + crate::systems::economy::bridges::EconomyForSkills + .pay_building_material(server, player, id, amount) + } + + fn consume_item_template(&self, server: &GameServer, player: &PlayerRef, id: u32, amount: i32) { + crate::systems::economy::bridges::EconomyForSkills + .consume_item_template(server, player, id, amount); + } +} + +#[tokio::test] +async fn construction_material_removed_after_final_check_cancels_without_progress_and_can_retry() { + let (mut f, house) = material_fixture(); + give(&f, slot_type::INVENTORY, LUMBER, 1, 0); + let remover = Arc::new(RemoveAfterFinalCheck(std::sync::atomic::AtomicBool::new( + true, + ))); + f.server.systems.skills.ext.items.install(remover.clone()); + let skill = build_skill(BUILD_SKILL, 1); + let timeline = fire_build(&f, &house, &skill); + assert!(!remover.0.load(std::sync::atomic::Ordering::SeqCst)); + assert_eq!(count(&f, LUMBER), 0); + assert!(skill.cancelled()); + assert_eq!(house.data().current_action(), 0); + assert_eq!(f.player.data().labor_power, 50); + assert_eq!(interaction_progress(&f), 0); + let frames = f.client.drain(); + assert!(!frames + .iter() + .any(|(op, _)| *op == sc::SCHouseBuildProgressPacket)); + let mut expected = crate::systems::skills::packets::SCSkillStartedPacket::new( + BUILD_SKILL, + timeline, + SkillCaster::Unit(f.player.obj_id), + SkillCastTarget::Unit(house.obj_id), + SkillObject::None, + ); + expected.set_skill_result(36); + let mut body = aaemu_commons::PacketStream::new(); + aaemu_commons::Marshal::write(&expected, &mut body); + assert!(frames.contains(&(sc::SCSkillStartedPacket, body.into_bytes()))); + assert!(frames + .iter() + .any(|(op, _)| *op == sc::SCCastingStoppedPacket)); + + // A failed payment leaves neither a progress reservation nor a stale cancellation. + give(&f, slot_type::INVENTORY, LUMBER, 1, 0); + let retry = build_skill(BUILD_SKILL, 1); + fire_build(&f, &house, &retry); + assert!(!retry.cancelled()); + assert_eq!(house.data().current_action(), 1); + assert_eq!(count(&f, LUMBER), 0); + assert_eq!(f.player.data().labor_power, 45); + assert_eq!(interaction_progress(&f), 1); +} + +#[tokio::test] +async fn construction_material_exact_and_extra_stock_pay_once_for_one_action() { + for stock in [1, 2] { + for container in [slot_type::INVENTORY, slot_type::EQUIPMENT, slot_type::BANK] { + let (f, house) = if container == slot_type::EQUIPMENT { + // An equippable synthetic material exercises the same container contract + // without putting an invalid Lumber stack into a player's equipment. + let mut material = ItemTemplate::plain(LUMBER, 1); + material.kind = crate::data::items::TemplateKind::Accessory( + crate::data::items::EquipTemplate { + slot_type_id: 10, // ear slots 9 and 10 + ..Default::default() + }, + ); + let f = material_fixture_with_item(material); + for n in 0..stock { + give(&f.0, container, LUMBER, 1, 9 + n); + } + f + } else { + let f = material_fixture(); + give(&f.0, container, LUMBER, stock, 0); + f + }; + let skill = build_skill(BUILD_SKILL, 1); + fire_build(&f, &house, &skill); + assert!(!skill.cancelled()); + assert_eq!(house.data().current_action(), 1); + assert_eq!(Inv::of(&f.player).items_count(LUMBER, -1), stock - 1); + assert_eq!(f.player.data().labor_power, 45); + assert_eq!(interaction_progress(&f), 1); + } + } +} + +#[tokio::test] +async fn construction_step_needs_its_effect_consume_item_before_cast() { + let (f, house) = material_fixture(); + let skill = build_skill(BUILD_SKILL, 1); + let ctx = build_ctx(&f, &house); + let mut target_caster = ctx.target_caster; + assert_eq!( + skill::use_skill( + &f.server, + &skill, + &ctx.caster, + ctx.caster_caster, + &mut target_caster, + Some(SkillObject::None), + false + ), + (36, 0) + ); + assert_eq!(house.data().current_action(), 0); + assert_eq!(f.player.data().labor_power, 50); + assert_eq!(interaction_progress(&f), 0); +} + +#[tokio::test] +async fn construction_material_rejection_preserves_stock_labor_and_quest_progress() { + for rejection in [ + "wrong skill", + "completed", + "missing step", + "stale", + "abandoned", + "wrong instance", + "unknown template", + ] { + let (mut f, house) = material_fixture(); + let material = give(&f, slot_type::INVENTORY, LUMBER, 2, 0); + let id = match rejection { + "wrong skill" => BUILD_SKILL + 1, + "completed" => { + manager::set_current_step(&f.server, &house, -1, false); + BUILD_SKILL + } + "missing step" => { + house.data().current_step = 1; + BUILD_SKILL + } + "stale" => { + f.server.world.world(0).unwrap().remove_object(house.obj_id); + BUILD_SKILL + } + "abandoned" => { + house.data().unit.owner_id = 0; + BUILD_SKILL + } + "wrong instance" => { + house.data().unit.transform.instance_id = 99; + BUILD_SKILL + } + "unknown template" => { + house.data().unit.template_id = u32::MAX; + BUILD_SKILL + } + _ => unreachable!(), + }; + let snapshot = || { + let h = house.data(); + (h.current_step, h.current_action()) + }; + let before = snapshot(); + f.client.drain(); + let skill = build_skill(id, 1); + fire_build(&f, &house, &skill); + assert!(skill.cancelled(), "{rejection}"); + assert_eq!(count(&f, LUMBER), 2, "{rejection}"); + assert_eq!(Inv::of(&f.player).item_by_id(material).unwrap().count, 2); + assert_eq!(snapshot(), before, "{rejection}"); + assert_eq!(f.player.data().labor_power, 50, "{rejection}"); + assert_eq!(interaction_progress(&f), 0, "{rejection}"); + assert!( + !f.client + .drain_ops() + .contains(&sc::SCHouseBuildProgressPacket), + "{rejection}" + ); + } +} + +#[tokio::test] +async fn construction_material_preflight_rejects_partial_payment_without_mutating_items() { + let (f, house) = material_fixture(); + let bag_item = give(&f, slot_type::INVENTORY, LUMBER, 1, 2); + let bank_item = give(&f, slot_type::BANK, LUMBER, 1, 4); + let inv = Inv::of(&f.player); + let bag_before = inv.item_by_id(bag_item).unwrap(); + let bank_before = inv.item_by_id(bank_item).unwrap(); + // Exercise the checked production hook after validation; neither stack can cover the + // complete payment, so it must not debit the first stack and then fail on the second. + assert_eq!( + ops::craft_building_paid(&f.server, &f.player, &house, BUILD_SKILL, LUMBER, 3), + Err(ops::BuildActionError::MissingMaterial) + ); + assert_eq!(inv.item_by_id(bag_item), Some(bag_before)); + assert_eq!(inv.item_by_id(bank_item), Some(bank_before)); + assert_eq!(house.data().current_action(), 0); +} + +#[tokio::test] +async fn construction_material_callbacks_run_after_housing_and_economy_unlock() { + struct Observe { + remaining: i32, + progress: std::sync::Mutex>, + } + impl crate::systems::economy::hooks::QuestItemHooks for Observe { + fn on_items_consumed(&self, server: &GameServer, player: &PlayerRef, id: u32, amount: i32) { + assert_eq!((id, amount), (LUMBER, 1)); + let _housing = server + .systems + .housing + .operation_lock + .try_lock() + .expect("housing lock released before item callbacks"); + assert!(!crate::systems::economy::System::ops_held_on_this_thread()); + let _txn = crate::systems::economy::inventory::ItemTxn::begin(server); + assert_eq!(Inv::of(player).items_count(LUMBER, -1), self.remaining); + let house = server.systems.housing.manager.all()[0].clone(); + self.progress + .lock() + .unwrap() + .push(house.data().current_action()); + } + } + for stock in [1, 3] { + let (f, house) = material_fixture(); + let observer = Arc::new(Observe { + remaining: stock - 1, + progress: std::sync::Mutex::new(Vec::new()), + }); + f.server + .systems + .economy + .hooks + .quests + .install(observer.clone()); + give(&f, slot_type::INVENTORY, LUMBER, stock, 0); + fire_build(&f, &house, &build_skill(BUILD_SKILL, 1)); + assert_eq!(*observer.progress.lock().unwrap(), vec![1]); + } +} + +#[tokio::test] +async fn construction_material_default_hook_rejects_positive_payment() { + struct NoPayment; + impl ItemSkillHooks for NoPayment {} + let (f, house) = material_fixture(); + give(&f, slot_type::INVENTORY, LUMBER, 1, 0); + f.server + .systems + .skills + .ext + .items + .install(Arc::new(NoPayment)); + assert_eq!( + ops::craft_building_paid(&f.server, &f.player, &house, BUILD_SKILL, LUMBER, 1), + Err(ops::BuildActionError::MissingMaterial) + ); + assert_eq!(house.data().current_action(), 0); + assert_eq!(count(&f, LUMBER), 1); +} + +#[tokio::test] +async fn construction_zero_step_design_is_finished_at_placement_without_a_build_action() { + const FREE_DESIGN: u32 = 301; + const FREE_DESIGN_ITEM: u32 = 9001; + let mut data = GameData::empty(); + data.systems.housing.add_template(HousingTemplate { + id: FREE_DESIGN, + hp: 1000, + main_model_id: 701, + garden_radius: 8.0, + taxation: Some(Taxation { + id: 1, + tax: 100_001, + show: true, + }), + ..Default::default() + }); + data.systems.housing.add_item_housing(HousingItemHousings { + id: 2, + item_id: FREE_DESIGN_ITEM, + design_id: FREE_DESIGN, + }); + data.items + .templates + .insert(FREE_DESIGN_ITEM, ItemTemplate::plain(FREE_DESIGN_ITEM, 1)); + let f = fixture_with_data(false, 400_000, None, data); + let design = give(&f, slot_type::INVENTORY, FREE_DESIGN_ITEM, 1, 0); + let mut packet = packet(design); + packet.design_id = FREE_DESIGN; + ops::build(&f.server, &f.player, 1001, &packet); + let house = f.server.systems.housing.manager.all()[0].clone(); + assert_eq!(house.data().current_step, -1); + assert_eq!(house.data().unit.model_id, 701); + assert_eq!(house.data().all_action, 0); + // Both wrappers reject an action on the already completed zero-step house. Placement + // handles its completion, so the former step=None fallthrough is not a valid free action. + assert!(!ops::craft_building( + &f.server, + &f.player, + &house, + BUILD_SKILL + )); + assert_eq!( + ops::craft_building_paid(&f.server, &f.player, &house, BUILD_SKILL, LUMBER, 1), + Err(ops::BuildActionError::Rejected) + ); +} + fn packet(item_id: u64) -> CSCreateHousePacket { CSCreateHousePacket { design_id: DESIGN, diff --git a/rust/crates/aaemu-game/src/systems/housing/mod.rs b/rust/crates/aaemu-game/src/systems/housing/mod.rs index fbf5767ce1..f1e865a8bc 100644 --- a/rust/crates/aaemu-game/src/systems/housing/mod.rs +++ b/rust/crates/aaemu-game/src/systems/housing/mod.rs @@ -356,15 +356,8 @@ pub fn house_radius(server: &GameServer, obj: &WorldObject) -> Option { Some(r * scale) } -/// The `CraftEffect` `Building` branch (routed from `ExtHooks::route_effect` before the other -/// subsystems): a character building a house. `true` = handled. -pub fn apply_effect( - server: &GameServer, - kind: EffectKind, - template: &EffectTemplate, - args: &EffectArgs<'_>, -) -> bool { - let _ = kind; +/// Structural classification shared by skill payment and the ordinary effect router. +pub(crate) fn is_building_effect(server: &GameServer, template: &EffectTemplate) -> bool { let EffectTemplate::Craft { world_interaction, .. } = template @@ -377,7 +370,19 @@ pub fn apply_effect( .npcs .area_trigger .get_world_interaction_group(*world_interaction); - if group != Some(crate::systems::npcs::area_trigger::world_interaction_group::BUILDING) { + group == Some(crate::systems::npcs::area_trigger::world_interaction_group::BUILDING) +} + +/// The `CraftEffect` `Building` branch (routed from `ExtHooks::route_effect` before the other +/// subsystems): a character building a house. `true` = handled. +pub fn apply_effect( + server: &GameServer, + kind: EffectKind, + template: &EffectTemplate, + args: &EffectArgs<'_>, +) -> bool { + let _ = kind; + if !is_building_effect(server, template) { return false; } let Some(player) = args.caster.as_ref().and_then(|c| c.as_player()).cloned() else { @@ -389,7 +394,6 @@ pub fn apply_effect( let Some(house) = target.as_house().cloned() else { return false; }; - tracing::debug!("CraftEffect, {world_interaction}"); let used_skill = match args.cast { crate::systems::skills::types::CastAction::Skill { skill_id, .. } => skill_id, _ => 0, diff --git a/rust/crates/aaemu-game/src/systems/housing/ops.rs b/rust/crates/aaemu-game/src/systems/housing/ops.rs index 256d65706c..bac0bcf95c 100644 --- a/rust/crates/aaemu-game/src/systems/housing/ops.rs +++ b/rust/crates/aaemu-game/src/systems/housing/ops.rs @@ -1566,77 +1566,125 @@ pub fn craft_building( house: &HouseRef, used_skill: u32, ) -> bool { - let _operation = server + craft_building_with_payment(server, player, house, used_skill, || { + Some(crate::models::item_task::ItemFxList::default()) + }) + .is_ok() +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum BuildActionError { + Rejected, + MissingMaterial, +} + +/// The selected skill effect pays immediately before committing progress, while the housing +/// operation lock still protects the current house and step from demolition / another action. +pub(crate) fn craft_building_paid( + server: &GameServer, + player: &PlayerRef, + house: &HouseRef, + used_skill: u32, + material_id: u32, + material_count: i32, +) -> Result<(), BuildActionError> { + craft_building_with_payment(server, player, house, used_skill, || { + server.systems.skills.ext.items().pay_building_material( + server, + player, + material_id, + material_count, + ) + }) +} + +fn craft_building_with_payment( + server: &GameServer, + player: &PlayerRef, + house: &HouseRef, + used_skill: u32, + pay: impl FnOnce() -> Option, +) -> Result<(), BuildActionError> { + let operation = server .systems .housing .operation_lock .lock() .unwrap_or_else(|e| e.into_inner()); let Some(template) = template_of(server, house) else { - return false; + return Err(BuildActionError::Rejected); }; if super::dominion::fort::is_fort(server, house) && !super::dominion::fort::allowed_to_interact(server, house, player) { - return false; + return Err(BuildActionError::Rejected); } let char_name = player.data().unit.name.clone(); - let (current_action, current_step, owner, house_instance) = { + let (current_action, current_step, owner, house_instance, house_id) = { let h = house.data(); ( h.current_action(), h.current_step, h.unit.owner_id, h.unit.transform.instance_id, + h.id, ) }; if owner == 0 || current_step < 0 || player.data().unit.transform.instance_id != house_instance { - return false; + return Err(BuildActionError::Rejected); + } + let current = server.systems.housing.manager.by_id(house_id); + let world_house = server + .world + .world(house_instance) + .and_then(|w| w.house(house.obj_id)); + if current.is_none_or(|h| !std::sync::Arc::ptr_eq(&h, house)) + || world_house.is_none_or(|h| !std::sync::Arc::ptr_eq(&h, house)) + { + return Err(BuildActionError::Rejected); } // Get the house's current build step let step = if current_action >= 0 && current_step < template.build_steps.len() as i32 { match template.build_steps.get(¤t_step) { - Some(s) => Some(*s), + Some(s) => *s, None => { // C#: BuildSteps[-1] of a finished house throws KeyNotFoundException. tracing::error!( "CraftEffect: house {} has no build step {current_step}", house.obj_id ); - return false; + return Err(BuildActionError::Rejected); } } } else { - None + return Err(BuildActionError::Rejected); }; // Compare if the used skill (correct pack) is still valid when used - if let Some(step) = step.filter(|s| used_skill != s.skill_id) { + if used_skill != step.skill_id { tracing::warn!( "{char_name} tried to building using the wrong skill, {used_skill} instead of {}", step.skill_id ); player.data().skill_char.skill_cancelled = true; crate::systems::skills::skill::interrupt_skills(server, &WorldObject::from(player)); - return false; - } - // When done, set step to -1 - if template.build_steps.is_empty() { - manager::set_current_step(server, house, -1, false); - } else { - manager::add_build_action(server, house); - // MAKE_HOUSING: the owner's last build action finished the house (design id value1). - if owner == player.character_id && house.data().current_step == -1 { - crate::systems::report_achievement( - server, - player, - AchievementInput::Increment { - kind_id: char_record_kind::MAKE_HOUSING, - amount: 1, - matcher: RecordMatch::Value1(template.id), - }, - ); - } + return Err(BuildActionError::Rejected); + } + // No world/object lock is held while taking the economy lock. Payment releases it and + // returns deferred item callbacks, so progress callbacks can safely use the economy. + let item_fx = pay().ok_or(BuildActionError::MissingMaterial)?; + manager::add_build_action(server, house); + // MAKE_HOUSING: the owner's last build action finished the house (design id value1). + if owner == player.character_id && house.data().current_step == -1 { + crate::systems::report_achievement( + server, + player, + AchievementInput::Increment { + kind_id: char_record_kind::MAKE_HOUSING, + amount: 1, + matcher: RecordMatch::Value1(template.id), + }, + ); } let packet = { let h = house.data(); @@ -1662,5 +1710,7 @@ pub fn craft_building( } } } - true + drop(operation); + crate::systems::economy::fx::flush(server, item_fx); + Ok(()) } diff --git a/rust/crates/aaemu-game/src/systems/housing/tests.rs b/rust/crates/aaemu-game/src/systems/housing/tests.rs index 157bc329fc..a41c7e6de2 100644 --- a/rust/crates/aaemu-game/src/systems/housing/tests.rs +++ b/rust/crates/aaemu-game/src/systems/housing/tests.rs @@ -1516,89 +1516,3 @@ async fn tax_plaque_distinguishes_paid_due_and_expired_houses() { assert_eq!(i32::from_le_bytes(body[23..27].try_into().unwrap()), weeks); } } - -/// Item hooks of the construction material tests: a bag of template counts, consumption recorded. -#[derive(Default)] -struct Bag { - counts: Mutex>, -} - -impl crate::systems::skills::ext::ItemSkillHooks for Bag { - fn item_count(&self, _server: &GameServer, _player: &PlayerRef, id: u32) -> i32 { - self.counts.lock().unwrap().get(&id).copied().unwrap_or(0) - } - fn consume_item_template( - &self, - _server: &GameServer, - _player: &PlayerRef, - template_id: u32, - amount: i32, - ) { - *self.counts.lock().unwrap().entry(template_id).or_default() -= amount; - } -} - -const LUMBER: u32 = 8337; - -/// Skill `skill_id` (a Building-target skill with a CraftEffect that consumes 1 Lumber at the -/// effect level) cast by `fx.pa` on `house`. -fn cast_build_skill(fx: &Fx, skill_id: u32, house: &HouseRef, labor_cost: i32) -> (u8, u32) { - use crate::systems::skills::data::{EffectKind, SkillTemplate}; - use crate::systems::skills::state::SkillRun; - use crate::systems::skills::types::{SkillCastTarget, SkillCaster, SkillObject}; - let mut effect = crate::systems::skills::tests::skill_effect(1, EffectKind::CraftEffect, 1); - effect.consume_item_id = LUMBER; - effect.consume_item_count = 1; - let template = SkillTemplate { - target_type: crate::systems::skills::types::SkillTargetType::Building as i32, - max_range: 100, - consume_labor_power: labor_cost, - effects: vec![effect], - ..crate::systems::skills::tests::skill_template(skill_id) - }; - let skill = SkillRun::new(Arc::new(template), 1); - crate::systems::skills::skill::use_skill( - &fx.server, - &skill, - &WorldObject::from(&fx.pa), - SkillCaster::Unit(fx.pa.obj_id), - &mut SkillCastTarget::Unit(house.obj_id), - Some(SkillObject::None), - false, - ) -} - -#[tokio::test] -async fn construction_step_needs_its_effect_consume_item() { - let mut fx = fixture(false); - let bag = Arc::new(Bag::default()); - fx.server.systems.skills.ext.items.install(bag.clone()); - crate::systems::skills::install_hooks(&fx.server); - fx.pa.data().labor_power = 50; - fx.pa.data().unit.mp = 100; - let house = place_house(&fx, DESIGN, &fx.pa.clone(), 120.0, 100.0, 0); - fx.a.drain(); - - // No Lumber: refused with the reagent error, nothing spent, the step is unchanged. - let (result, _) = cast_build_skill(&fx, 11000, &house, 5); - assert_eq!( - result, - crate::systems::skills::unit_reqs::skill_result_for_key("skill_need_reagent") - ); - assert_eq!(result, 36); - assert_eq!(fx.pa.data().labor_power, 50); - assert_eq!(house.data().current_action(), 0); - assert_eq!(bag.counts.lock().unwrap().get(&LUMBER).copied(), None); - - // With Lumber the action is built and the Lumber is taken. - bag.counts.lock().unwrap().insert(LUMBER, 2); - let (result, _) = cast_build_skill(&fx, 11000, &house, 5); - assert_eq!(result, 0); - assert_eq!(house.data().current_action(), 1); - assert_eq!(bag.counts.lock().unwrap()[&LUMBER], 1); - - // A skill that is not the step's build skill keeps the soft consume (cast allowed). - bag.counts.lock().unwrap().insert(LUMBER, 0); - let (result, _) = cast_build_skill(&fx, 4242, &house, 0); - assert_ne!(result, 36); -} diff --git a/rust/crates/aaemu-game/src/systems/skills/cast_validation_tests.rs b/rust/crates/aaemu-game/src/systems/skills/cast_validation_tests.rs index b11099a62b..b29d862658 100644 --- a/rust/crates/aaemu-game/src/systems/skills/cast_validation_tests.rs +++ b/rust/crates/aaemu-game/src/systems/skills/cast_validation_tests.rs @@ -223,6 +223,44 @@ async fn guaranteed_hit_is_per_effect_and_does_not_change_the_cast_miss_cache() assert_eq!(skill.hit_type(npc.obj_id), Some(SkillHitType::MeleeMiss)); } +#[tokio::test] +async fn nonbuilding_damage_still_applies_without_its_optional_effect_item() { + let mut data = GameData::empty(); + data.systems.skills.add_effect( + EffectKind::DamageEffect, + EffectTemplate::Damage(Box::new(super::tests::damage_effect(1, 100))), + 1, + ); + let mut effect = super::tests::skill_effect(1, EffectKind::DamageEffect, 1); + effect.consume_item_id = 8337; + effect.consume_item_count = 1; + effect.always_hit = true; + let (server, _client, player, npc) = fixture(data); + server + .systems + .skills + .ext + .items + .install(Arc::new(crate::systems::economy::bridges::EconomyForSkills)); + assert_eq!( + crate::systems::economy::inventory::Inv::of(&player).items_count(8337, -1), + 0 + ); + let skill = SkillRun::new( + Arc::new(SkillTemplate { + effects: vec![effect], + ..super::tests::skill_template(1) + }), + 1, + ); + assert_eq!( + cast(&server, &skill, &player, &npc).0, + skill_result::SUCCESS + ); + assert!(!skill.cancelled()); + assert_eq!(npc.data().unit.hp, 900); +} + #[tokio::test] async fn channel_buffs_have_distinct_owners_and_cancel_stops_mana_ticks() { let mut data = GameData::empty(); diff --git a/rust/crates/aaemu-game/src/systems/skills/ext.rs b/rust/crates/aaemu-game/src/systems/skills/ext.rs index 32bab28082..c4dd031d97 100644 --- a/rust/crates/aaemu-game/src/systems/skills/ext.rs +++ b/rust/crates/aaemu-game/src/systems/skills/ext.rs @@ -14,6 +14,7 @@ use crate::data::world_data::Portal; use crate::models::item::Item; +use crate::models::item_task::ItemFxList; use crate::models::movement::{GameStanceType, MoveTypeAlertness}; use crate::models::npc::Npc; use crate::models::transform::PositionAndRotation; @@ -427,6 +428,19 @@ pub trait ItemSkillHooks: Send + Sync { ) { } + /// Pay for a house build action atomically. Positive payments must fail unless the full + /// amount was consumed. Return item notifications for flushing after the housing lock is + /// released; implementations must release their economy lock before returning. + fn pay_building_material( + &self, + _server: &GameServer, + _player: &PlayerRef, + template_id: u32, + amount: i32, + ) -> Option { + (template_id == 0 || amount <= 0).then(ItemFxList::default) + } + /// `Inventory.Bag.AcquireDefaultItem(SkillEffectGainItem, itemId, amount)`. fn acquire_item( &self, diff --git a/rust/crates/aaemu-game/src/systems/skills/skill.rs b/rust/crates/aaemu-game/src/systems/skills/skill.rs index 8f5c2c0952..68b6393c9c 100644 --- a/rust/crates/aaemu-game/src/systems/skills/skill.rs +++ b/rust/crates/aaemu-game/src/systems/skills/skill.rs @@ -1617,6 +1617,16 @@ pub fn apply_effects(server: &GameServer, skill: &SkillRef, ctx: &CastCtx) { let items = server.systems.skills.ext.items(); let mut consumed_items: Vec<(u64, i32)> = Vec::new(); let mut consumed_templates: Vec<(u32, i32)> = Vec::new(); + let paid_building = |target: &Target, effect: &SkillEffect| { + player.is_some() + && target.as_obj().and_then(WorldObject::as_house).is_some() + && effect + .template + .and_then(|(kind, id)| data.effect(kind, id)) + .is_some_and(|template| { + crate::systems::housing::is_building_effect(server, template) + }) + }; if let Some(last) = last_applied { // Deviation: C# looked at the last applied effect only. Skills with mixed flags (a // consuming GainItem followed by an Interaction effect) never consumed the item, so the @@ -1642,7 +1652,13 @@ pub fn apply_effects(server: &GameServer, skill: &SkillRef, ctx: &CastCtx) { } } if let Some(p) = &player { - if let Some(e) = template_effect { + if let Some(e) = template_effect.filter(|e| { + // House construction pays at the progress commit, including stale/rejected + // targets. Never fall back to the optional debit for that same effect. + !to_apply.iter().any(|(target, candidate)| { + std::ptr::eq(*candidate, *e) && paid_building(target, candidate) + }) + }) { // source item consumption, or enough of the item in the bag / equipment if e.consume_source_item || items.item_count(server, p, e.consume_item_id) >= e.consume_item_count @@ -1730,7 +1746,50 @@ pub fn apply_effects(server: &GameServer, skill: &SkillRef, ctx: &CastCtx) { skill_object: &ctx.skill_object, }; args.source.always_hit = effect.always_hit; - if let EffectTemplate::KillNpcWithoutCorpse(k) = template { + if paid_building(target, effect) { + // This is the actual selected effect and target, rather than the router's + // "handled" bool (which says nothing about whether construction succeeded). + let p = player.as_ref().expect("paid building has a player"); + let house = target + .as_obj() + .and_then(WorldObject::as_house) + .expect("paid building has a house"); + match crate::systems::housing::ops::craft_building_paid( + server, + p, + house, + t.id, + effect.consume_item_id, + effect.consume_item_count, + ) { + Ok(()) => { + let template_id = house.data().unit.template_id; + crate::systems::quests::events::on_doodad_interaction( + server, + p, + p, + template_id, + ); + } + Err(error) => { + if error == crate::systems::housing::ops::BuildActionError::MissingMaterial { + let mut packet = SCSkillStartedPacket::new( + skill.id, + tl, + ctx.caster_caster, + this_target_caster, + ctx.skill_object.clone(), + ); + packet + .set_skill_result(unit_reqs::skill_result_for_key("skill_need_reagent")) + .set_result_uint(0); + p.send(packet); + } + stop(server, skill, caster, 0); + return; + } + } + } else if let EffectTemplate::KillNpcWithoutCorpse(k) = template { let npc = world_of(server, caster).and_then(|w| w.npc_by_template_id(k.npc_id)); let effective = npc .clone() From d4979d8dc7be794e612bf36c8d10d090289f455f Mon Sep 17 00:00:00 2001 From: Nick Messer Date: Fri, 23 Oct 2026 11:41:51 -0400 Subject: [PATCH 08/14] fix(game): SC layouts the 1.2 client reads differently (criminal arrested, tower def list, play sound) - SCCriminalArrested: the criminal's obj id is a 3-byte bc (x2game 397b6870), not a u32. - SCTowerDefList: the count is a u8 and the client reads at most 100 entries (397caad0). - SCPlaySound: the NPC of a kind-2 (bubble) cue is a bc (397bea30), not a u32. Each extra byte shifted the following fields, so the client read garbage names / ids. Co-Authored-By: Claude Opus 5.5 --- rust/crates/aaemu-game/src/systems/ai/packets.rs | 5 +++-- rust/crates/aaemu-game/src/systems/instances/packets.rs | 9 +++++++-- rust/crates/aaemu-game/src/systems/instances/tests.rs | 2 +- .../aaemu-game/src/systems/social/packets/trial.rs | 8 ++++---- 4 files changed, 15 insertions(+), 9 deletions(-) diff --git a/rust/crates/aaemu-game/src/systems/ai/packets.rs b/rust/crates/aaemu-game/src/systems/ai/packets.rs index fcc9130f39..1dda4beaad 100644 --- a/rust/crates/aaemu-game/src/systems/ai/packets.rs +++ b/rust/crates/aaemu-game/src/systems/ai/packets.rs @@ -20,9 +20,10 @@ packet_def!( ); impl Marshal for SCPlaySoundPacket { fn write(&self, s: &mut PacketStream) { + // The 1.2 client's reader (x2game 397bea30) takes the NPC of a kind-2 cue as a 3-byte bc. s.write_u8(self.kind) .write_u32(self.bubble_id) - .write_u32(self.npc_obj_id); + .write_bc(self.npc_obj_id); } } @@ -37,6 +38,6 @@ mod tests { bubble_id: 0x0102_0304, npc_obj_id: 0x00AB_CDEF, }); - assert_eq!(body, vec![2, 4, 3, 2, 1, 0xEF, 0xCD, 0xAB, 0x00]); + assert_eq!(body, vec![2, 4, 3, 2, 1, 0xEF, 0xCD, 0xAB]); } } diff --git a/rust/crates/aaemu-game/src/systems/instances/packets.rs b/rust/crates/aaemu-game/src/systems/instances/packets.rs index 54b00b1dfb..66aae4c5a9 100644 --- a/rust/crates/aaemu-game/src/systems/instances/packets.rs +++ b/rust/crates/aaemu-game/src/systems/instances/packets.rs @@ -728,10 +728,15 @@ packet_def!( level = LEVEL_PLAIN, opcode = sc::SCTowerDefListPacket ); +impl SCTowerDefListPacket { + /// The 1.2 client reads the count as a byte and at most this many entries (x2game 397caad0). + pub const MAX_INFOS: usize = 100; +} impl Marshal for SCTowerDefListPacket { fn write(&self, s: &mut PacketStream) { - s.write_i32(self.infos.len() as i32); - for i in &self.infos { + let infos = &self.infos[..self.infos.len().min(Self::MAX_INFOS)]; + s.write_u8(infos.len() as u8); + for i in infos { i.write(s); } } diff --git a/rust/crates/aaemu-game/src/systems/instances/tests.rs b/rust/crates/aaemu-game/src/systems/instances/tests.rs index 1e00ccb462..1e585f2616 100644 --- a/rust/crates/aaemu-game/src/systems/instances/tests.rs +++ b/rust/crates/aaemu-game/src/systems/instances/tests.rs @@ -349,7 +349,7 @@ fn tower_def_packets_are_byte_exact() { current_step: 4, }; let mut e = PacketStream::new(); - e.write_i32(1) + e.write_u8(1) .write_u32(12) .write_u16(5) .write_u32(129) diff --git a/rust/crates/aaemu-game/src/systems/social/packets/trial.rs b/rust/crates/aaemu-game/src/systems/social/packets/trial.rs index 315e01a223..712298399f 100644 --- a/rust/crates/aaemu-game/src/systems/social/packets/trial.rs +++ b/rust/crates/aaemu-game/src/systems/social/packets/trial.rs @@ -205,11 +205,11 @@ sc_packet!( ); sc_packet!( - /// `SCCriminalArrestedPacket(criminalObjId, criminal, arrestor)` (the obj id is a plain - /// `uint`, not a bc). + /// `SCCriminalArrestedPacket(criminalObjId, criminal, arrestor)`. The 1.2 client's reader + /// (x2game 397b6870) takes the obj id as a 3-byte bc before the two names. SCCriminalArrestedPacket { criminal_obj_id: u32, criminal: String, arrestor: String } |self, s| { - s.write_u32(self.criminal_obj_id) + s.write_bc(self.criminal_obj_id) .write_str(&self.criminal) .write_str(&self.arrestor); } @@ -765,7 +765,7 @@ mod tests { criminal: "C".into(), arrestor: "A".into() }), - vec![0x0C, 0x0B, 0x0A, 0x00, 1, 0, b'C', 1, 0, b'A'] + vec![0x0C, 0x0B, 0x0A, 1, 0, b'C', 1, 0, b'A'] ); assert_eq!( body(&SCForceAttackSetPacket { From 8e8352611d048026e2fd39791f365d68c5f63e05 Mon Sep 17 00:00:00 2001 From: Nick Messer Date: Fri, 23 Oct 2026 11:49:33 -0400 Subject: [PATCH 09/14] fix(doodads): enforce gathering skill and caster authorization Authorize gathering before cast mutations and phase execution. Preserve explicit Use/FakeUse bindings and automatic loot, and define the scoped legacy server compatibility mapping with normal labor and quest requirements. Prevent an owned mate from advancing a paid gathering phase for a free character loot retry. Add packet-flow regressions and compact coverage. Ore uses its real item definition; removed rock/sheep loot definitions are explicit test-only stand-ins. Native UI dispatch remains unverified. Co-Authored-By: GPT-6.1 Sol --- rust/crates/aaemu-game/PORTING.md | 25 + .../src/systems/npcs/doodad/data.rs | 14 +- .../src/systems/npcs/doodad/funcs/mod.rs | 7 +- .../src/systems/npcs/doodad/funcs/tests.rs | 11 +- .../src/systems/npcs/doodad/gather_tests.rs | 588 +++++++++++++++++- .../src/systems/npcs/doodad/gathering.rs | 165 +++++ .../aaemu-game/src/systems/npcs/doodad/mod.rs | 1 + .../src/systems/npcs/doodad/phase.rs | 4 + .../src/systems/skills/validation.rs | 6 + 9 files changed, 804 insertions(+), 17 deletions(-) create mode 100644 rust/crates/aaemu-game/src/systems/npcs/doodad/gathering.rs diff --git a/rust/crates/aaemu-game/PORTING.md b/rust/crates/aaemu-game/PORTING.md index 77a936bb18..35d9022b54 100644 --- a/rust/crates/aaemu-game/PORTING.md +++ b/rust/crates/aaemu-game/PORTING.md @@ -1445,6 +1445,31 @@ is no longer mirrored (see "Known deviations", dead NPC returned and healed). tool is data only: the C# server never validated `SkillTemplate.MainhandToolId` (the 1.2 mining / shear ids 2654 and 15607 do not even resolve to `items` rows) and neither does Rust, so there is no server-side tool refusal at 1.2 parity. + Authorization hardening (2026-10-23): phase progression now requires the current func's + authored skill before cast resources/effects and again at phase execution. A gathering + caster must be a character: an owned mate/slave cannot advance the phase while + bypassing character labor/quest checks, leaving a free loot retry for its owner. The generic + `GetFunc` skill-less fallback is still used for automatic loot chaining, but cannot authorize + gathering. Legacy `OreMine`/`RockMine`/`Shear` rows have zero/null `func_skill_id`; their + intentional server compatibility adapter uses the shipped basic skills 11106 for ore + (3 LP), 11107 for rock (0 LP), and 11642 for shearing (0 LP, quest 266 requirement). Skill + names, tools and effects support these pairings, but local 1.2 native/UI selection was not + verified; this is a defined server deviation, not a claim of native dispatch parity. An + explicit row skill takes precedence. The adapter selects a matching legacy function + before the generic fallback, including phases exposing multiple gathering types. Free Use + skill 15212 cannot mine ore 1534 (phase 2387 -> loot 8077), nor can the zero-labor rock skill + replace the ore skill. Skill-driven `Use` and `FakeUse` gathering keeps its binding (shearing + 13802 on template 518 phase 5649, rock 11107 on template 1354 phase 2244). Gathering dispatch + is recognized by compact's tool asset and interaction metadata; authorization is + always an exact row/template/implicit skill match, without requiring every gather to cost + labor or requiring inventory tools that do not exist in the 1.2 item data. + Content limitation: the shipped compact retains rock 310's loot reference to item 4734 + and sheep 307's references to item 3, but neither item exists in `items`. This skill + adapter does not create those production item definitions or replace their loot; normal + economy validation still refuses those missing drops with `BagInvalidItem`. + The ignored compact regression explicitly supplies in-memory, test-only item templates + for 4734 and 3 to exercise the authored rock/sheep dispatch and quantities. Ore 1534 uses + real item 8077. Passing the stand-in cases is not proof of complete live/client content. * systems::ai (2026-10-15): the optional compact patch `SQL/patches/compact/2026-10-14-fix-npc-ai-param-syntax.sql` repairs malformed Lua syntax diff --git a/rust/crates/aaemu-game/src/systems/npcs/doodad/data.rs b/rust/crates/aaemu-game/src/systems/npcs/doodad/data.rs index 72f937fc1d..f48d178552 100644 --- a/rust/crates/aaemu-game/src/systems/npcs/doodad/data.rs +++ b/rust/crates/aaemu-game/src/systems/npcs/doodad/data.rs @@ -1864,7 +1864,8 @@ impl DoodadData { /// `GetFunc(funcGroupId, skillId)`: the first func of the group whose `SkillId` is the /// skill, or whose `DoodadFuncFakeUse.FakeSkillId` / `DoodadFuncUse.SkillId` (> 0) is the - /// skill; else the first func without skill and with `NextPhase != -1`; else the first func + /// skill; else a matching legacy gathering compatibility skill; else the first func without + /// skill and with `NextPhase != -1`; else the first func /// without skill. pub fn func_for_skill(&self, func_group_id: u32, skill_id: u32) -> Option<&DoodadFunc> { let funcs = self.funcs_by_groups.get(&func_group_id)?; @@ -1886,6 +1887,17 @@ impl DoodadData { _ => {} } } + // The legacy gathering compatibility adapter supplies a skill when func_skill_id + // is absent. Resolve it before the unchanged generic skill-less fallback. + if let Some(func) = funcs.iter().find(|f| { + f.skill_id == 0 + && self + .func_template(f.func_id, &f.func_type) + .and_then(super::gathering::legacy_skill) + == Some(skill_id) + }) { + return Some(func); + } // First we skip functions with NextPhase = -1 if let Some(func) = funcs.iter().find(|f| f.skill_id == 0 && f.next_phase != -1) { return Some(func); diff --git a/rust/crates/aaemu-game/src/systems/npcs/doodad/funcs/mod.rs b/rust/crates/aaemu-game/src/systems/npcs/doodad/funcs/mod.rs index 8b98213302..f618154c67 100644 --- a/rust/crates/aaemu-game/src/systems/npcs/doodad/funcs/mod.rs +++ b/rust/crates/aaemu-game/src/systems/npcs/doodad/funcs/mod.rs @@ -75,6 +75,9 @@ pub fn use_func( let Some(_operation) = super::phase::Operation::enter(&ctx.doodad) else { return; }; + if !super::gathering::allows_template(ctx.server, &ctx.doodad, t, skill_id, caster) { + return; + } use FuncTemplate as F; match t { // --- items / loot --- @@ -135,7 +138,9 @@ pub fn use_func( // (`doodad_func_shears`); loot, depletion and regrowth live in the next func group // (e.g. ore 255 -> 425 LootItem -> 426 Final / RatioRespawn, sheared 56 -> 57 LootItem // + Timer). The C# bodies only logged, so the phase never advanced; advancing is what - // makes the authored loot / respawn chain run. The gathering skill covers labor + // makes the authored loot / respawn chain run. Gathering authorization above and + // before the cast prevents skill-less fallback from substituting a free Use skill. + // The gathering skill covers labor // (`consume_lp`) and the 1.2 server never validated `mainhand_tool_id`. F::OreMine(_) => { tracing::trace!("DoodadFuncOreMine"); diff --git a/rust/crates/aaemu-game/src/systems/npcs/doodad/funcs/tests.rs b/rust/crates/aaemu-game/src/systems/npcs/doodad/funcs/tests.rs index b5ddd87f92..6ee632ba9b 100644 --- a/rust/crates/aaemu-game/src/systems/npcs/doodad/funcs/tests.rs +++ b/rust/crates/aaemu-game/src/systems/npcs/doodad/funcs/tests.rs @@ -210,19 +210,16 @@ async fn to_next_phase_funcs_and_stubs() { FuncTemplate::Harvest(DoodadFuncHarvest { id: 1 }), FuncTemplate::OpenFarmInfo(DoodadFuncOpenFarmInfo { id: 1, farm_id: 0 }), FuncTemplate::PuzzleRoll(DoodadFuncPuzzleRoll::default()), - FuncTemplate::OreMine(DoodadFuncOreMine { id: 1 }), - FuncTemplate::RockMine(DoodadFuncRockMine { id: 1 }), - FuncTemplate::Shear(DoodadFuncShear { - id: 1, - shear_type_id: 1, - shear_term: 60_000, - }), ] { fx.doodad.data().phase.to_next_phase = false; fx.run(t, 0, 0); assert!(fx.to_next()); } for t in [ + // Gathering templates cannot advance without an authorized current-phase skill. + FuncTemplate::OreMine(DoodadFuncOreMine { id: 1 }), + FuncTemplate::RockMine(DoodadFuncRockMine { id: 1 }), + FuncTemplate::Shear(DoodadFuncShear::default()), FuncTemplate::StoreUi(DoodadFuncStoreUi::default()), FuncTemplate::EvidenceItemLoot(DoodadFuncEvidenceItemLoot::default()), FuncTemplate::TreeByProductsCollect(DoodadFuncTreeByProductsCollect::default()), diff --git a/rust/crates/aaemu-game/src/systems/npcs/doodad/gather_tests.rs b/rust/crates/aaemu-game/src/systems/npcs/doodad/gather_tests.rs index 7ed404dffe..448a8e5f45 100644 --- a/rust/crates/aaemu-game/src/systems/npcs/doodad/gather_tests.rs +++ b/rust/crates/aaemu-game/src/systems/npcs/doodad/gather_tests.rs @@ -12,6 +12,7 @@ use aaemu_commons::{Marshal, PacketStream}; use crate::data::items::{GradeTemplate, ItemTemplate}; use crate::data::GameData; +use crate::net::registry::ClientPacket; use crate::opcodes::sc; use crate::server::GameServer; use crate::systems::economy::inventory::Inv; @@ -51,6 +52,7 @@ const SHEEP_SHEARED: u32 = 22; const ORE_MINE_SKILL: u32 = 9100; const SHEAR_SKILL: u32 = 9101; +const GENERIC_USE_SKILL: u32 = 15212; /// `mainhand_tool_id` of the 1.2 mining skills (data only: no server-side check). const PICKAXE: u32 = 2654; @@ -108,6 +110,19 @@ impl DoodadBuilder { self } + fn skill(mut self, group: u32, skill_id: u32) -> Self { + let f = self + .data + .funcs_by_groups + .get_mut(&group) + .unwrap() + .last_mut() + .unwrap(); + f.skill_id = skill_id; + self.data.funcs_by_id.insert(f.func_key, f.clone()); + self + } + fn phase_func(mut self, group: u32, t: FuncTemplate) -> Self { let (class, id) = (t.func_type(), t.id()); self.data @@ -197,6 +212,7 @@ fn game_data() -> GameData { s.add_skill(mining); let mut shear = crate::systems::skills::tests::skill_template(SHEAR_SKILL); shear.consume_labor_power = SHEAR_LABOR; + shear.mainhand_tool_id = 15607; shear.target_type = SkillTargetType::Doodad as i32; shear .effects @@ -206,6 +222,16 @@ fn game_data() -> GameData { SHEAR_EFFECT, )); s.add_skill(shear); + let mut generic = crate::systems::skills::tests::skill_template(GENERIC_USE_SKILL); + generic.target_type = SkillTargetType::Doodad as i32; + generic + .effects + .push(crate::systems::skills::tests::skill_effect( + SHEAR_EFFECT, + EffectKind::InteractionEffect, + SHEAR_EFFECT, + )); + s.add_skill(generic); d.systems.npcs.doodad = DoodadBuilder::default() .template(VEIN, &[(VEIN_START, 1), (VEIN_LOOT, 2), (VEIN_DEPLETED, 2)]) @@ -214,6 +240,7 @@ fn game_data() -> GameData { FuncTemplate::OreMine(DoodadFuncOreMine { id: 1 }), VEIN_LOOT as i32, ) + .skill(VEIN_START, ORE_MINE_SKILL) .func(VEIN_LOOT, loot(2, ORE), VEIN_DEPLETED as i32) .phase_func(VEIN_DEPLETED, regrow_timer(3, VEIN_START as i32)) .template(ROCK, &[(ROCK_START, 1), (ROCK_LOOT, 2), (ROCK_DEPLETED, 2)]) @@ -222,6 +249,7 @@ fn game_data() -> GameData { FuncTemplate::RockMine(DoodadFuncRockMine { id: 7 }), ROCK_LOOT as i32, ) + .skill(ROCK_START, ORE_MINE_SKILL) .func(ROCK_LOOT, loot(8, ORE), ROCK_DEPLETED as i32) .phase_func(ROCK_DEPLETED, regrow_timer(9, ROCK_START as i32)) .template( @@ -237,6 +265,7 @@ fn game_data() -> GameData { }), SHEEP_LOOT as i32, ) + .skill(SHEEP_START, SHEAR_SKILL) .func(SHEEP_LOOT, loot(5, WOOL), SHEEP_SHEARED as i32) .phase_func(SHEEP_SHEARED, regrow_timer(6, SHEEP_START as i32)) .data; @@ -250,8 +279,15 @@ struct Fx { } fn fx() -> Fx { - let mut data = game_data(); + fx_with(game_data()) +} + +fn fx_with(mut data: GameData) -> Fx { open_client_skills(&mut data); + fx_loaded(data) +} + +fn fx_loaded(data: GameData) -> Fx { let server = std::sync::Arc::new(test_server_with(data)); server.set_self(); crate::systems::skills::bind(&server); @@ -265,6 +301,10 @@ fn fx() -> Fx { let mut client = TestClient::new(&server, 1, 1001); let mut c = test_character(1, "Miner", 100.0, 100.0); c.labor_power = LABOR_BASE as i16; + c.unit.hp = 1000; + c.unit.max_hp = 1000; + c.unit.mp = 1000; + c.unit.max_mp = 1000; let player = spawn_player(&server, &client, c, 0x100); client.conn.active_char = Some(player.clone()); client.drain(); @@ -286,14 +326,19 @@ impl Fx { } fn cast(&mut self, skill: u32, d: &DoodadRef) -> Vec<(u16, Vec)> { + self.cast_as(skill, SkillCaster::Unit(self.player.obj_id), d) + } + + fn cast_as(&mut self, skill: u32, caster: SkillCaster, d: &DoodadRef) -> Vec<(u16, Vec)> { + self.client.drain(); // Only observe frames caused by this cast, not doodad creation. self.player.data().unit.skill_last_used_ms = 0; - let packet = CSStartSkillPacket { - skill_id: skill, - caster: SkillCaster::Unit(self.player.obj_id), - target: SkillCastTarget::Doodad(d.obj_id), - flag: 0, - skill_object: SkillObject::None, - }; + let mut wire = PacketStream::new(); + wire.write_u32(skill); + caster.write(&mut wire); + SkillCastTarget::Doodad(d.obj_id).write(&mut wire); + wire.write_u8(0); + let packet = + CSStartSkillPacket::read(&mut PacketStream::from_bytes(wire.into_bytes())).unwrap(); start_skill(&self.server, &mut self.client.conn, packet); self.client.drain() } @@ -310,6 +355,22 @@ impl Fx { .tasks .advance(&self.server, ms) } + + async fn cast_and_wait(&mut self, skill: u32, d: &DoodadRef) -> Vec<(u16, Vec)> { + let mut frames = self.cast(skill, d); + let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(8); + while self.player.data().unit.skill_state.skill_task.is_some() + && tokio::time::Instant::now() < deadline + { + tokio::time::sleep(std::time::Duration::from_millis(10)).await; + } + assert!( + self.player.data().unit.skill_state.skill_task.is_none(), + "cast {skill} did not finish" + ); + frames.extend(self.client.drain()); + frames + } } fn body(p: &dyn Marshal) -> Vec { @@ -318,6 +379,517 @@ fn body(p: &dyn Marshal) -> Vec { s.into_bytes() } +fn assert_refused(fx: &Fx, d: &DoodadRef, skill: u32, frames: &[(u16, Vec)]) { + let mut expected = crate::systems::skills::packets::SCSkillStartedPacket::new( + skill, + 0, + SkillCaster::Unit(fx.player.obj_id), + SkillCastTarget::Doodad(d.obj_id), + SkillObject::None, + ); + expected.set_skill_result(skill_result::INVALID_TARGET); + assert!( + frames.contains(&(sc::SCSkillStartedPacket, body(&expected))), + "{frames:?}" + ); + assert!(!frames.iter().any(|f| f.0 == sc::SCDoodadPhaseChangedPacket)); + let c = fx.player.data(); + assert_eq!(c.unit.global_cooldown_ms, 0); + assert_eq!(c.unit.skill_last_used_ms, 0); + assert!(c.unit.skill_state.skill_task.is_none()); +} + +#[tokio::test] +async fn generic_use_15212_cannot_gather_at_zero_labor() { + for (template, start, authored) in [ + (VEIN, VEIN_START, false), + (ROCK, ROCK_START, false), + (SHEEP, SHEEP_START, false), + (VEIN, VEIN_START, true), + (ROCK, ROCK_START, true), + (SHEEP, SHEEP_START, true), + ] { + let mut data = game_data(); + if !authored { + data.systems + .npcs + .doodad + .funcs_by_groups + .get_mut(&start) + .unwrap()[0] + .skill_id = 0; + } + let mut fx = fx_with(data); + let d = fx.doodad(template); + fx.player.data().labor_power = 0; + let mana = fx.player.data().unit.mp; + + let frames = fx.cast(GENERIC_USE_SKILL, &d); + + assert_eq!(d.data().func_group_id, start, "target {template}"); + assert_eq!(fx.count(ORE), 0); + assert_eq!(fx.count(WOOL), 0); + assert_eq!(fx.player.data().labor_power, 0); + assert_eq!(fx.player.data().unit.mp, mana); + assert_refused(&fx, &d, GENERIC_USE_SKILL, &frames); + assert_eq!(fx.advance(REGROW_MS as u64), 0); + } +} + +#[tokio::test] +async fn a_cheaper_mining_skill_cannot_replace_the_authored_skill() { + let mut data = game_data(); + let mut cheap = (**data.systems.skills.skill(ORE_MINE_SKILL).unwrap()).clone(); + cheap.id = 9200; + cheap.consume_labor_power = 0; + cheap.mana_cost = 25; + // Same tool and InteractionEffect as the real gathering skill: classification alone + // is not enough; the current function's authored skill must match. + data.systems.skills.add_skill(cheap); + let mut fx = fx_with(data); + fx.player.data().labor_power = 0; + let d = fx.doodad(VEIN); + let mana = fx.player.data().unit.mp; + let frames = fx.cast(9200, &d); + assert_eq!(fx.player.data().unit.mp, mana); + assert_eq!(d.data().func_group_id, VEIN_START); + assert_eq!(fx.count(ORE), 0); + assert_refused(&fx, &d, 9200, &frames); +} + +#[tokio::test] +async fn gathering_use_and_fake_use_dispatch_require_their_authored_skill() { + for fake in [false, true] { + let mut data = game_data(); + let doodads = &mut data.systems.npcs.doodad; + let t = if fake { + FuncTemplate::FakeUse(DoodadFuncFakeUse { + id: 50, + fake_skill_id: ORE_MINE_SKILL, + ..Default::default() + }) + } else { + FuncTemplate::Use(DoodadFuncUse { + id: 50, + skill_id: 0, + }) + }; + let f = &mut doodads.funcs_by_groups.get_mut(&VEIN_START).unwrap()[0]; + f.func_type = t.func_type().into(); + f.func_id = t.id(); + // Match compact's normal Use row binding and FakeUse template binding. + f.skill_id = if fake { 0 } else { ORE_MINE_SKILL }; + doodads.funcs_by_id.insert(f.func_key, f.clone()); + doodads + .func_templates + .entry(t.func_type()) + .or_default() + .insert(t.id(), t); + let mut fx = fx_with(data); + let d = fx.doodad(VEIN); + fx.player.data().labor_power = 0; + let frames = fx.cast(GENERIC_USE_SKILL, &d); + assert_eq!(d.data().func_group_id, VEIN_START); + assert_eq!(fx.count(ORE), 0); + assert_refused(&fx, &d, GENERIC_USE_SKILL, &frames); + + fx.player.data().labor_power = LABOR_BASE as i16; + fx.cast(ORE_MINE_SKILL, &d); + assert_eq!(d.data().func_group_id, VEIN_DEPLETED, "fake={fake}"); + assert_eq!(fx.count(ORE), 1); + assert_eq!( + fx.player.data().labor_power, + (LABOR_BASE - MINING_LABOR) as i16 + ); + } +} + +#[tokio::test] +async fn authorized_gathering_runs_every_skill_less_automatic_loot_row() { + let mut data = game_data(); + let mut builder = DoodadBuilder { + data: std::mem::take(&mut data.systems.npcs.doodad), + }; + builder = builder.func(VEIN_LOOT, loot(60, WOOL), VEIN_DEPLETED as i32); + data.systems.npcs.doodad = builder.data; + let mut fx = fx_with(data); + let d = fx.doodad(VEIN); + fx.cast(ORE_MINE_SKILL, &d); + assert_eq!(fx.count(ORE), 1); + assert_eq!(fx.count(WOOL), 1); + assert_eq!(d.data().func_group_id, VEIN_DEPLETED); + assert_eq!( + fx.player.data().labor_power, + (LABOR_BASE - MINING_LABOR) as i16 + ); +} + +#[tokio::test] +async fn owned_mate_cannot_advance_gathering_without_character_labor() { + let mut fx = fx(); + fx.player.data().labor_power = 0; + let mut mate_data = crate::models::mate::Mate::new(1, 1); + mate_data.owner_obj_id = fx.player.obj_id; + mate_data.unit.hp = 1000; + mate_data.unit.mp = 1000; + mate_data.unit.transform.set_xyz(100.0, 100.0, 100.0); + let mate = crate::world::Entity::new(0x600, mate_data); + fx.server + .world + .world(0) + .unwrap() + .spawn(&mate, &fx.server.view_ctx()); + let d = fx.doodad(VEIN); + fx.cast_as( + ORE_MINE_SKILL, + SkillCaster::Mount { + obj_id: mate.obj_id, + mount_skill_template_id: 0, + }, + &d, + ); + assert_eq!(d.data().func_group_id, VEIN_START); + assert_eq!(fx.count(ORE), 0); + assert_eq!(fx.player.data().labor_power, 0); + assert_eq!(mate.data().unit.mp, 1000); + assert_eq!(mate.data().unit.skill_last_used_ms, 0); + assert!(mate.data().unit.skill_state.skill_task.is_none()); + + // The owner cannot follow a free mate cast with a generic loot retry. + let frames = fx.cast(GENERIC_USE_SKILL, &d); + assert_refused(&fx, &d, GENERIC_USE_SKILL, &frames); + assert_eq!(fx.count(ORE), 0); + assert_eq!(d.data().func_group_id, VEIN_START); + + // The same target/skill works for its character caster and pays the normal cost. + fx.player.data().labor_power = LABOR_BASE as i16; + fx.cast(ORE_MINE_SKILL, &d); + assert_eq!(fx.count(ORE), 1); + assert_eq!( + fx.player.data().labor_power, + (LABOR_BASE - MINING_LABOR) as i16 + ); +} + +#[tokio::test] +async fn direct_phase_execution_cannot_bypass_gathering_authorization() { + let mut data = game_data(); + data.systems + .npcs + .doodad + .funcs_by_groups + .get_mut(&VEIN_START) + .unwrap()[0] + .skill_id = 0; + let fx = fx_with(data); + let d = fx.doodad(VEIN); + let world = fx.server.world.world(0).unwrap(); + let ctx = super::runtime::DoodadCtx::new(&fx.server, world, d.clone()); + let caster = crate::world::WorldObject::from(&fx.player); + super::phase::use_doodad(&ctx, Some(&caster), GENERIC_USE_SKILL, 0); + assert_eq!(d.data().func_group_id, VEIN_START); + assert_eq!(fx.count(ORE), 0); +} + +#[tokio::test] +async fn unbound_gathering_funcs_require_their_implicit_skill() { + let mut data = game_data(); + data.systems + .npcs + .doodad + .funcs_by_groups + .get_mut(&VEIN_START) + .unwrap()[0] + .skill_id = 0; + let mut fx = fx_with(data); + let d = fx.doodad(VEIN); + let frames = fx.cast(ORE_MINE_SKILL, &d); + assert_eq!(fx.player.data().labor_power, LABOR_BASE as i16); + assert_eq!(fx.count(ORE), 0); + assert_eq!(d.data().func_group_id, VEIN_START); + assert_refused(&fx, &d, ORE_MINE_SKILL, &frames); +} + +#[tokio::test] +async fn legacy_gathering_uses_implicit_skills_and_authored_labor() { + for (template, group, skill, source, cost, item, after) in [ + ( + VEIN, + VEIN_START, + 11106, + ORE_MINE_SKILL, + 3, + ORE, + VEIN_DEPLETED, + ), + ( + ROCK, + ROCK_START, + 11107, + ORE_MINE_SKILL, + 0, + ORE, + ROCK_DEPLETED, + ), + ( + SHEEP, + SHEEP_START, + 11642, + SHEAR_SKILL, + 0, + WOOL, + SHEEP_SHEARED, + ), + ] { + let mut data = game_data(); + let mut gather = (**data.systems.skills.skill(source).unwrap()).clone(); + gather.id = skill; + gather.consume_labor_power = cost; + data.systems.skills.add_skill(gather); + data.systems + .npcs + .doodad + .funcs_by_groups + .get_mut(&group) + .unwrap()[0] + .skill_id = 0; + if template == VEIN { + // A phase can expose multiple legacy funcs. Select the matching implicit + // skill before the generic first skill-less row, even if that row is RockMine. + let builder = DoodadBuilder { + data: std::mem::take(&mut data.systems.npcs.doodad), + } + .func( + VEIN_START, + FuncTemplate::RockMine(DoodadFuncRockMine { id: 70 }), + VEIN_LOOT as i32, + ); + data.systems.npcs.doodad = builder.data; + data.systems + .npcs + .doodad + .funcs_by_groups + .get_mut(&group) + .unwrap() + .swap(0, 1); + } + let mut fx = fx_with(data); + let d = fx.doodad(template); + fx.cast(skill, &d); + assert_eq!(fx.player.data().labor_power, (LABOR_BASE - cost) as i16); + assert_eq!(fx.count(item), 1); + assert_eq!(d.data().func_group_id, after); + } +} + +#[tokio::test] +async fn shearing_without_labor_is_refused_before_gathering() { + let mut fx = fx(); + fx.player.data().labor_power = 0; + let d = fx.doodad(SHEEP); + let frames = fx.cast(SHEAR_SKILL, &d); + assert_eq!(fx.count(WOOL), 0); + assert_eq!(d.data().func_group_id, SHEEP_START); + assert_eq!(fx.player.data().labor_power, 0); + let mut expected = crate::systems::skills::packets::SCSkillStartedPacket::new( + SHEAR_SKILL, + 0, + SkillCaster::Unit(fx.player.obj_id), + SkillCastTarget::Doodad(d.obj_id), + SkillObject::None, + ); + expected.set_skill_result(skill_result::NEED_LABOR_POWER); + assert!(frames.contains(&(sc::SCSkillStartedPacket, body(&expected)))); +} + +#[tokio::test] +#[ignore = "needs AAEMU_COMPACT_DB"] +async fn real_compact_gathering_with_test_only_removed_item_templates() { + use crate::data::client_files::ClientFileManager; + + let Ok(path) = std::env::var("AAEMU_COMPACT_DB") else { + return; + }; + let conn = + rusqlite::Connection::open_with_flags(path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY) + .unwrap(); + let mut data = game_data(); + data.skills = crate::data::skills::SkillData::load(&conn).unwrap(); + data.systems.skills = + crate::systems::skills::Data::load_from(&conn, &ClientFileManager::new()).unwrap(); + data.systems.npcs.doodad = DoodadData::load_from(&conn).unwrap(); + data.items = crate::data::items::ItemData::load(&conn).unwrap(); + let has_base_item = |id| { + conn.query_row( + "SELECT EXISTS(SELECT 1 FROM items WHERE id = ?1)", + [id], + |row| row.get::<_, bool>(0), + ) + .unwrap() + }; + // Ore 1534 uses its complete, real compact item definition; never synthesize 8077. + assert!(has_base_item(8077)); + // TEST ONLY: compact retains rock/sheep loot references to removed items 4734 and 3. + // Minimal in-memory stand-ins isolate authored dispatch, quantities and authorization. + // No skill, requirement, loot row, compact file or production item data is modified; + // successful stand-in cases do not establish complete usable live/client content. + for test_only_missing_item_template in [4734, 3] { + if !has_base_item(test_only_missing_item_template) { + // The loader can retain orphan subtype shells: item 3 has an item_weapons + // row but no base item, leaving max_count at zero. Replace that shell too. + data.items.templates.insert( + test_only_missing_item_template, + ItemTemplate::plain(test_only_missing_item_template, 100), + ); + } + } + assert!(data.skills.is_client_sourced_skill(GENERIC_USE_SKILL)); + let generic = data.systems.skills.skill(GENERIC_USE_SKILL).unwrap(); + assert_eq!(generic.consume_labor_power, 0); + assert_eq!(generic.casting_time, 0); + assert!(!data + .systems + .skills + .unit_reqs + .get("Skill") + .unwrap() + .iter() + .any(|r| r.owner_id == GENERIC_USE_SKILL)); + + let mut fx = fx_loaded(data); + fx.player.data().labor_power = 0; + for (template, group, row) in [(1534, 2387, 2213), (310, 61, 1293), (307, 56, 53)] { + let f = fx.server.game_data.systems.npcs.doodad.func(row).unwrap(); + assert_eq!(f.skill_id, 0); + assert_eq!(f.group_id, group); + let d = fx.doodad(template); + d.data().func_group_id = group; + fx.client.drain(); + let frames = fx.cast(GENERIC_USE_SKILL, &d); + assert_eq!(d.data().func_group_id, group, "template {template}"); + for item in [8077, 4734, 3] { + assert_eq!(fx.count(item), 0, "template {template}, item {item}"); + } + assert_eq!(fx.player.data().labor_power, 0); + assert_refused(&fx, &d, GENERIC_USE_SKILL, &frames); + manager::delete(&fx.server, &fx.server.world.world(0).unwrap(), &d); + } + // Real compact encodes authored shearing on Use.func_skill_id, and the legacy rock + // skill on FakeUse.fake_skill_id. Neither is inferred from a generic Use effect. + for (template, group, skill) in [(518, 5649, 13802), (1354, 2244, 11107)] { + let d = fx.doodad(template); + d.data().func_group_id = group; + let skills = &fx.server.game_data.systems.skills; + assert!(super::gathering::allows_skill( + &fx.server, + &d, + skills.skill(skill).unwrap(), + &crate::world::WorldObject::from(&fx.player), + )); + assert!(!super::gathering::allows_skill( + &fx.server, + &d, + skills.skill(GENERIC_USE_SKILL).unwrap(), + &crate::world::WorldObject::from(&fx.player), + )); + manager::delete(&fx.server, &fx.server.world.world(0).unwrap(), &d); + } + // Rock's free skill has the same mining InteractionEffect kind. It cannot substitute + // for ore's implicit three-labor skill, even though both skills are client-common. + fx.player.data().unit.global_cooldown_ms = 0; + let ore = fx.doodad(1534); + ore.data().func_group_id = 2387; + let frames = fx.cast(11107, &ore); + assert_refused(&fx, &ore, 11107, &frames); + assert_eq!(fx.count(8077), 0); + assert_eq!(ore.data().func_group_id, 2387); + fx.player.data().labor_power = 2; + let frames = fx.cast(11106, &ore); + let mut expected = crate::systems::skills::packets::SCSkillStartedPacket::new( + 11106, + 0, + SkillCaster::Unit(fx.player.obj_id), + SkillCastTarget::Doodad(ore.obj_id), + SkillObject::None, + ); + expected.set_skill_result(skill_result::NEED_LABOR_POWER); + assert!( + frames.contains(&(sc::SCSkillStartedPacket, body(&expected))), + "{frames:?}" + ); + assert_eq!(fx.player.data().labor_power, 2); + assert_eq!(fx.count(8077), 0); + assert_eq!(ore.data().func_group_id, 2387); + manager::delete(&fx.server, &fx.server.world.world(0).unwrap(), &ore); + + for (template, group, skill, cost, item, minimum, after) in [ + (1534, 2387, 11106, 3, 8077, 1, 2389), + (310, 61, 11107, 0, 4734, 1, 1280), + (307, 56, 11642, 0, 3, 8, 57), + ] { + assert!(fx.server.game_data.skills.is_common_skill(skill)); + let authored = fx.server.game_data.systems.skills.skill(skill).unwrap(); + assert_eq!(authored.consume_labor_power, cost); + assert_eq!(authored.casting_time, 5000); + fx.player.data().labor_power = LABOR_BASE as i16; + fx.player.data().unit.global_cooldown_ms = 0; + let d = fx.doodad(template); + d.data().func_group_id = group; + let before = fx.count(item); + if skill == 11642 { + // Keep the real precomplete-quest requirement (kind 37) operative. Establish + // its state immediately before this cast: preceding loot events sync quests. + let frames = fx.cast(skill, &d); + let mut expected = crate::systems::skills::packets::SCSkillStartedPacket::new( + skill, + 0, + SkillCaster::Unit(fx.player.obj_id), + SkillCastTarget::Doodad(d.obj_id), + SkillObject::None, + ); + expected + .set_skill_result(crate::systems::skills::unit_reqs::skill_result_for_key( + "skill_urk_precomplete_quest_context", + )) + .set_result_uint(266); + assert!( + frames.contains(&(sc::SCSkillStartedPacket, body(&expected))), + "{frames:?}" + ); + assert_eq!(d.data().func_group_id, group); + assert_eq!(fx.count(item), before); + fx.player + .data() + .quests + .active + .push(crate::models::char_data::ActiveQuest { + id: 266, + template_id: 266, + status: crate::systems::quests::model::status::PROGRESS, + objectives: [0; 5], + step: crate::systems::quests::model::kind::PROGRESS, + acceptor_type: 0, + component_id: 0, + acceptor_id: 0, + time_ms: crate::models::char_data::ActiveQuest::DATETIME_MIN_MS, + }); + } + let frames = fx.cast_and_wait(skill, &d).await; + assert_eq!( + fx.player.data().labor_power, + (LABOR_BASE - cost) as i16, + "skill {skill}, {frames:?}" + ); + assert!( + fx.count(item) >= before + minimum, + "skill {skill}, {frames:?}" + ); + assert_eq!(d.data().func_group_id, after, "skill {skill}"); + assert!(frames.iter().any(|f| f.0 == sc::SCDoodadPhaseChangedPacket)); + manager::delete(&fx.server, &fx.server.world.world(0).unwrap(), &d); + } +} + #[tokio::test] async fn ore_mine_pays_labor_grants_ore_and_regrows() { let mut fx = fx(); diff --git a/rust/crates/aaemu-game/src/systems/npcs/doodad/gathering.rs b/rust/crates/aaemu-game/src/systems/npcs/doodad/gathering.rs new file mode 100644 index 0000000000..73a7c7a22b --- /dev/null +++ b/rust/crates/aaemu-game/src/systems/npcs/doodad/gathering.rs @@ -0,0 +1,165 @@ +//! Gathering authorization is separate from `func_for_skill`'s skill-less chaining fallback. + +use super::data::DoodadData; +use super::templates::{DoodadFunc, FuncTemplate}; +use crate::server::GameServer; +use crate::systems::skills::data::{EffectTemplate, SkillTemplate}; +use crate::world::{DoodadRef, WorldObject}; + +/// Intentional server compatibility policy for legacy funcs with no `func_skill_id`. +/// The shipped basic skills match their names, tool assets and InteractionEffects: ore +/// 11106 costs 3 LP, rock 11107 costs 0 LP, shear 11642 costs 0 LP and requires quest 266. +/// Local 1.2 UI/native selection of these skills was NOT verified. This adapter defines +/// server behavior rather than claiming native dispatch parity. Explicit bindings win; +/// the normal skill engine still enforces the selected template's costs/requirements. +#[derive(Clone, Copy)] +#[repr(u32)] +enum LegacyGatheringSkill { + OreMine = 11106, + RockMine = 11107, + Shear = 11642, +} + +pub(super) fn legacy_skill(template: &FuncTemplate) -> Option { + Some(match template { + FuncTemplate::OreMine(_) => LegacyGatheringSkill::OreMine, + FuncTemplate::RockMine(_) => LegacyGatheringSkill::RockMine, + FuncTemplate::Shear(_) => LegacyGatheringSkill::Shear, + _ => return None, + } as u32) +} + +fn is_gathering_func(template: &FuncTemplate) -> bool { + legacy_skill(template).is_some() +} + +fn is_gathering_skill(server: &GameServer, id: u32) -> bool { + let skills = &server.game_data.systems.skills; + let Some(skill) = skills.skill(id) else { + return false; + }; + // Tool ids here identify the authored skill, not an equipped-item requirement. The + // 1.2 pickaxe/shears assets are not inventory item templates. In particular, shearing + // uses both Use (19) and SkinOff (67); interaction 19 alone is not authorization. + skill.effects.iter().any(|effect| { + let Some(EffectTemplate::Interaction { + world_interaction, .. + }) = effect + .template + .and_then(|(kind, id)| skills.effect(kind, id)) + else { + return false; + }; + match skill.mainhand_tool_id { + 2654 => *world_interaction == 73, + 15607 => matches!(world_interaction, 19 | 67), + _ => false, + } + }) +} + +fn bound_skills(data: &DoodadData, func: &DoodadFunc) -> [u32; 2] { + let template_skill = match data.func_template(func.func_id, &func.func_type) { + Some(FuncTemplate::Use(t)) => t.skill_id, + Some(FuncTemplate::FakeUse(t)) => t.fake_skill_id, + _ => 0, + }; + [func.skill_id, template_skill] +} + +/// Check only gathering funcs and gathering Use/FakeUse dispatch. All other skill-less +/// fallback behavior, including automatic loot rows, retains its existing semantics. +pub(super) fn allows_func( + server: &GameServer, + func: &DoodadFunc, + skill_id: u32, + caster: Option<&WorldObject>, +) -> bool { + let data = &server.game_data.systems.npcs.doodad; + let Some(template) = data.func_template(func.func_id, &func.func_type) else { + return true; + }; + // Only characters pay labor and receive gathering loot. A Mount caster naming an + // owned mate/slave must not advance a paid gathering phase on the character's behalf. + let player_caster = caster.is_some_and(|caster| caster.as_player().is_some()); + if let Some(implicit) = legacy_skill(template) { + let expected = if func.skill_id == 0 { + implicit + } else { + func.skill_id + }; + return player_caster && skill_id != 0 && skill_id == expected; + } + let bound = bound_skills(data, func); + let dispatches_gathering = matches!(template, FuncTemplate::Use(_) | FuncTemplate::FakeUse(_)) + && (bound + .iter() + .any(|&id| id != 0 && is_gathering_skill(server, id)) + || (func.next_phase > 0 + && data + .funcs_for_group(func.next_phase as u32) + .iter() + .any(|next| { + data.func_template(next.func_id, &next.func_type) + .is_some_and(is_gathering_func) + }))); + !dispatches_gathering || (player_caster && skill_id != 0 && bound.contains(&skill_id)) +} + +/// Some interactions call the template directly rather than `DoFunc`. +pub(super) fn allows_template( + server: &GameServer, + doodad: &DoodadRef, + template: &FuncTemplate, + skill_id: u32, + caster: Option<&WorldObject>, +) -> bool { + if !is_gathering_func(template) { + return true; + } + let group = doodad.data().func_group_id; + server + .game_data + .systems + .npcs + .doodad + .funcs_for_group(group) + .iter() + .any(|func| { + func.func_type == template.func_type() + && func.func_id == template.id() + && allows_func(server, func, skill_id, caster) + }) +} + +/// Resolve against the current phase before cast resources, buffs or effects change. The +/// phase executor checks again because a cast can finish after the phase has changed. +pub fn allows_skill( + server: &GameServer, + doodad: &DoodadRef, + skill: &SkillTemplate, + caster: &WorldObject, +) -> bool { + let data = &server.game_data.systems.npcs.doodad; + let group = doodad.data().func_group_id; + // Restrict only skills that actually dispatch a doodad interaction. Unrelated combat + // skills targeting a doodad must not acquire new gathering restrictions. + let interacts = skill.effects.iter().any(|effect| { + effect + .template + .and_then(|(kind, id)| server.game_data.systems.skills.effect(kind, id)) + .is_some_and(|effect| matches!(effect, EffectTemplate::Interaction { .. })) + }); + if !interacts { + return true; + } + match data.func_for_skill(group, skill.id) { + Some(func) => allows_func(server, func, skill.id, Some(caster)), + // No fallback row exists when the phase has only explicitly bound funcs. Refuse + // a wrong gathering skill here too, before it can spend cast resources. + None => data + .funcs_for_group(group) + .iter() + .all(|func| allows_func(server, func, skill.id, Some(caster))), + } +} diff --git a/rust/crates/aaemu-game/src/systems/npcs/doodad/mod.rs b/rust/crates/aaemu-game/src/systems/npcs/doodad/mod.rs index 13150748c6..140390eb83 100644 --- a/rust/crates/aaemu-game/src/systems/npcs/doodad/mod.rs +++ b/rust/crates/aaemu-game/src/systems/npcs/doodad/mod.rs @@ -6,6 +6,7 @@ pub mod coffer; pub mod data; pub mod db; pub mod funcs; +pub mod gathering; pub mod interactions; pub mod logic; pub mod manager; diff --git a/rust/crates/aaemu-game/src/systems/npcs/doodad/phase.rs b/rust/crates/aaemu-game/src/systems/npcs/doodad/phase.rs index 2db39363ea..96d0e8ae69 100644 --- a/rust/crates/aaemu-game/src/systems/npcs/doodad/phase.rs +++ b/rust/crates/aaemu-game/src/systems/npcs/doodad/phase.rs @@ -401,6 +401,10 @@ pub fn do_func( return true; }; + if !super::gathering::allows_func(ctx.server, func, skill_id, caster) { + return true; + } + // then perform the function (DoodadFunc.Use -> template?.Use) if let Some(t) = ctx.data().func_template(func.func_id, &func.func_type) { if !crate::systems::instances::mentoring::authorize(ctx, caster, skill_id, t) { diff --git a/rust/crates/aaemu-game/src/systems/skills/validation.rs b/rust/crates/aaemu-game/src/systems/skills/validation.rs index af56e0c099..3c6e43ad97 100644 --- a/rust/crates/aaemu-game/src/systems/skills/validation.rs +++ b/rust/crates/aaemu-game/src/systems/skills/validation.rs @@ -98,6 +98,12 @@ pub(super) fn check( target: &Target, ) -> Result<(), (u8, u32)> { let template = &skill.template; + if let Some(doodad) = target.as_obj().and_then(WorldObject::as_doodad) { + if !crate::systems::npcs::doodad::gathering::allows_skill(server, doodad, template, caster) + { + return fail("skill_invalid_target"); + } + } let (hp, buff_ids, moving) = caster .with_unit(|u| { let unit = u.unit(); From f0e355494e81c8928c80b9910241f3bd5a034bdf Mon Sep 17 00:00:00 2001 From: Nick Messer Date: Fri, 23 Oct 2026 11:53:03 -0400 Subject: [PATCH 10/14] style(npcs): format interaction set loader --- .../aaemu-game/src/systems/npcs/npc/data.rs | 22 ++++++++++++------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/rust/crates/aaemu-game/src/systems/npcs/npc/data.rs b/rust/crates/aaemu-game/src/systems/npcs/npc/data.rs index d8b63f176e..e96681b935 100644 --- a/rust/crates/aaemu-game/src/systems/npcs/npc/data.rs +++ b/rust/crates/aaemu-game/src/systems/npcs/npc/data.rs @@ -1061,17 +1061,23 @@ impl NpcData { Ok(()) } - /// `localized_texts` rows for `npcs.name` (`LocalizationManager`). + /// Ordered skills for each `npc_interactions` interaction set. fn load_interactions(&mut self, conn: &Connection) -> rusqlite::Result<()> { - for_each_row(conn, "SELECT * FROM npc_interactions ORDER BY id", [], |r| { - self.interactions - .entry(r.i32("npc_interaction_set_id")?) - .or_default() - .push(r.u32("skill_id")?); - Ok(()) - }) + for_each_row( + conn, + "SELECT * FROM npc_interactions ORDER BY id", + [], + |r| { + self.interactions + .entry(r.i32("npc_interaction_set_id")?) + .or_default() + .push(r.u32("skill_id")?); + Ok(()) + }, + ) } + /// `localized_texts` rows for `npcs.name` (`LocalizationManager`). fn load_localized_names(&mut self, conn: &Connection, language: &str) -> rusqlite::Result<()> { let sql = format!( "SELECT idx, \"{}\" AS txt FROM localized_texts \ From d180fe393aa749b66d88773666146a080e9ca23b Mon Sep 17 00:00:00 2001 From: Nick Messer Date: Fri, 23 Oct 2026 12:42:10 -0400 Subject: [PATCH 11/14] fix(services): create salon hair for empty equipment slots Treat missing hair as template 0 when checking whether a salon hairstyle needs replacement. Keep receipts authoritative and preserve existing certificate settlement and failure behavior. Co-Authored-By: Codex --- rust/crates/aaemu-game/PORTING.md | 7 + .../src/systems/services/beauty_salon.rs | 9 +- .../systems/services/beauty_salon_tests.rs | 266 ++++++++++++++++++ 3 files changed, 279 insertions(+), 3 deletions(-) create mode 100644 rust/crates/aaemu-game/src/systems/services/beauty_salon_tests.rs diff --git a/rust/crates/aaemu-game/PORTING.md b/rust/crates/aaemu-game/PORTING.md index 1ca30539d6..b707310016 100644 --- a/rust/crates/aaemu-game/PORTING.md +++ b/rust/crates/aaemu-game/PORTING.md @@ -680,6 +680,13 @@ is no longer mirrored (see "Known deviations", dead NPC returned and healed). ## Known deviations from the C# +* systems::services (beauty salon): `ApplyBeautySalon` creates the requested hair item when + the equipment hair slot is empty. The C# guard required an existing hair item, so a paid + change could consume a Salon Certificate yet report hair 0. Same-hair requests still keep + the item; receipts still report actual equipment. Hair-creation failure still logs and + continues with the model update, receipt and certificate consumption, as in C#; failed + certificate consumption still logs without undoing the already broadcast appearance. + * systems::skills / systems::npcs (`Interaction` special effect 10): the former C# class was a TODO stub. The 1.2 `special_effects` rows put a `WorldInteractionType` in `value1` (row 11030: 19 `Use`, 36: 10 `DigTerrain`, 215: 29 `SummonBeanstalk`) and an optional doodad id in diff --git a/rust/crates/aaemu-game/src/systems/services/beauty_salon.rs b/rust/crates/aaemu-game/src/systems/services/beauty_salon.rs index 8b9eb6aab0..5ae0a3b0e5 100644 --- a/rust/crates/aaemu-game/src/systems/services/beauty_salon.rs +++ b/rust/crates/aaemu-game/src/systems/services/beauty_salon.rs @@ -65,9 +65,8 @@ pub fn apply_beauty_salon( if items.items_count(server, player, SALON_CERTIFICATE) <= 0 { return; } - let old_hair = hair_template(player); - if old_hair.is_some_and(|t| t != hair_model) && !items.replace_hair(server, player, hair_model) - { + let old_hair = hair_template(player).unwrap_or(0); + if old_hair != hair_model && !items.replace_hair(server, player, hair_model) { let (name, id) = { let c = player.data(); (c.unit.name.clone(), c.id) @@ -224,6 +223,10 @@ impl ClientPacket for CSBeautyshopDataPacket { } } +#[cfg(test)] +#[path = "beauty_salon_tests.rs"] +mod flow_tests; + #[cfg(test)] mod tests { use super::*; diff --git a/rust/crates/aaemu-game/src/systems/services/beauty_salon_tests.rs b/rust/crates/aaemu-game/src/systems/services/beauty_salon_tests.rs new file mode 100644 index 0000000000..e8a1089d0a --- /dev/null +++ b/rust/crates/aaemu-game/src/systems/services/beauty_salon_tests.rs @@ -0,0 +1,266 @@ +//! Salon packet flows through the real economy bridge (no MySQL). + +use std::sync::Arc; + +use super::*; +use crate::data::items::{ItemTemplate, TemplateKind}; +use crate::models::container::slot_type; +use crate::models::unit_model::UnitCustomModelType; +use crate::systems::economy::bridges::EconomyForServices; +use crate::systems::economy::inventory::Inv; +use crate::systems::economy::tests::{give, item_at, test_data, World}; +use crate::systems::services::item_ops::CharacterItemOps; +use crate::test_support::{spawn_player, test_character, test_server_with, TestClient}; + +const OLD_HAIR: u32 = 24127; +const NEW_HAIR: u32 = 24128; + +fn fixture(old_hair: Option, certificates: i32) -> World { + let mut data = test_data(); + for id in [OLD_HAIR, NEW_HAIR] { + data.items.templates.insert( + id, + ItemTemplate { + kind: TemplateKind::BodyPart { + slot_type_id: 24, // EquipmentItemSlotType.Hair + model_id: 10, + }, + ..ItemTemplate::plain(id, 1) + }, + ); + } + data.items.templates.insert( + SALON_CERTIFICATE, + ItemTemplate::plain(SALON_CERTIFICATE, 20), + ); + let server = Arc::new(test_server_with(data)); + server.set_self(); + CHARACTER_ITEM_OPS.install(Arc::new(EconomyForServices)); + let mut a = TestClient::new(&server, 1, 1001); + let mut b = TestClient::new(&server, 2, 1002); + let pa = spawn_player(&server, &a, test_character(1, "Salon", 100.0, 100.0), 0x100); + let pb = spawn_player( + &server, + &b, + test_character(2, "Observer", 101.0, 100.0), + 0x101, + ); + a.conn.active_char = Some(pa.clone()); + b.conn.active_char = Some(pb.clone()); + let mut w = World { + server, + a, + pa, + b, + pb, + }; + for container in [Inv::of(&w.pa).equipment(), Inv::of(&w.pa).bag()] { + w.server.items.add_container(container); + } + if let Some(hair) = old_hair { + give(&w, &w.pa, slot_type::EQUIPMENT, hair, 1, equip_slot::HAIR); + } + if certificates > 0 { + give( + &w, + &w.pa, + slot_type::INVENTORY, + SALON_CERTIFICATE, + certificates, + 0, + ); + } + w.a.drain(); + w.b.drain(); + w +} + +fn edited_model() -> UnitCustomModelParams { + UnitCustomModelParams { + kind: UnitCustomModelType::FACE, + hair_color_id: 728, + skin_color_id: 1, + model_id: 10, + face: Some(Default::default()), + } +} + +async fn apply(w: &mut World, hair: u32) { + CSBeautyshopDataPacket { + hair, + model: edited_model(), + } + .handle(&w.server, &mut w.a.conn) + .await + .unwrap(); +} + +fn assert_receipt_and_payment(w: &mut World, hair: u32) { + assert_eq!(w.pa.data().unit.model_params, edited_model()); + assert_eq!( + EconomyForServices.items_count(&w.server, &w.pa, SALON_CERTIFICATE), + 1 + ); + let mut expected = PacketStream::new(); + expected.write_u32(w.pa.character_id).write_u32(hair); + edited_model().write(&mut expected); + expected.write_u32(0); + let expected = expected.into_bytes(); + let owner = w.a.drain(); + let observer = w.b.drain(); + for frames in [&owner, &observer] { + let receipts: Vec<_> = frames + .iter() + .filter(|(op, _)| *op == sc::SCCharacterGenderAndModelModifiedPacket) + .map(|(_, body)| body) + .collect(); + assert_eq!(receipts, vec![&expected]); + } + let payments: Vec<_> = owner + .iter() + .enumerate() + .filter(|(_, (op, body))| { + *op == sc::SCItemTaskSuccessPacket && body.first() == Some(&item_task::EDIT_COSMETIC) + }) + .collect(); + assert_eq!(payments.len(), 1); + let receipt = owner + .iter() + .position(|(op, _)| *op == sc::SCCharacterGenderAndModelModifiedPacket) + .unwrap(); + assert!( + receipt < payments[0].0, + "receipt precedes certificate consumption, as in C#" + ); + assert!(!observer + .iter() + .any(|(op, _)| *op == sc::SCItemTaskSuccessPacket)); +} + +async fn successful_hair_change(old_hair: Option) { + let mut w = fixture(old_hair, 2); + let before = Inv::of(&w.pa).equipped(equip_slot::HAIR); + apply(&mut w, NEW_HAIR).await; + let after = Inv::of(&w.pa) + .equipped(equip_slot::HAIR) + .expect("equipped hair"); + assert_eq!(after.template_id, NEW_HAIR); + assert_eq!(after.slot_type, slot_type::EQUIPMENT); + assert_eq!(after.slot, equip_slot::HAIR); + assert_eq!(after.owner_id, u64::from(w.pa.character_id)); + assert_eq!(after.count, 1); + assert_eq!(w.server.items.item_by_id(after.id), Some(after.clone())); + if old_hair == Some(NEW_HAIR) { + assert_eq!(Some(after), before, "unchanged hair is not recreated"); + } else { + assert_eq!(after.made_unit_id, w.pa.character_id); + } + assert_receipt_and_payment(&mut w, NEW_HAIR); +} + +#[tokio::test] +async fn absent_hair_is_created_and_received_by_owner_and_observer() { + successful_hair_change(None).await; +} + +#[tokio::test] +async fn same_hair_is_kept_while_model_changes_and_one_certificate_is_consumed() { + successful_hair_change(Some(NEW_HAIR)).await; +} + +#[tokio::test] +async fn changed_hair_is_replaced_and_received_by_owner_and_observer() { + successful_hair_change(Some(OLD_HAIR)).await; +} + +#[tokio::test] +async fn no_certificate_leaves_hair_and_model_unchanged_without_receipt() { + for old_hair in [None, Some(OLD_HAIR)] { + let mut w = fixture(old_hair, 0); + let before = Inv::of(&w.pa).equipped(equip_slot::HAIR); + let model = w.pa.data().unit.model_params.clone(); + apply(&mut w, NEW_HAIR).await; + assert_eq!(Inv::of(&w.pa).equipped(equip_slot::HAIR), before); + assert_eq!(w.pa.data().unit.model_params, model); + assert_eq!( + EconomyForServices.items_count(&w.server, &w.pa, SALON_CERTIFICATE), + 0 + ); + assert!(w.a.drain().is_empty()); + assert!(w.b.drain().is_empty()); + } +} + +#[tokio::test] +async fn failed_hair_creation_preserves_csharp_receipt_and_consumption_behavior() { + for old_hair in [None, Some(OLD_HAIR)] { + let mut w = fixture(old_hair, 2); + // Invalid template: the existing swap removes old hair before attempting creation. + apply(&mut w, u32::MAX).await; + assert!(Inv::of(&w.pa).equipped(equip_slot::HAIR).is_none()); + assert_eq!(item_at(&w.pa, slot_type::INVENTORY, 0).unwrap().count, 1); + // Model edits still apply; the receipt reports actual equipment, never requested hair. + assert_receipt_and_payment(&mut w, 0); + } +} + +#[tokio::test] +async fn failed_certificate_consumption_does_not_undo_the_appearance_receipt() { + struct TakeCertificates; + impl crate::systems::economy::hooks::QuestItemHooks for TakeCertificates { + fn on_items_acquired( + &self, + server: &GameServer, + player: &PlayerRef, + template: u32, + _: i32, + ) { + if template == NEW_HAIR { + // Deterministically remove the certificates between the availability check + // and the final consume, using the real item callbacks and inventory path. + assert_eq!( + EconomyForServices.consume_item( + server, + player, + crate::models::item_task::task_type::INVALID, + SALON_CERTIFICATE, + 2, + ), + 2 + ); + } + } + } + let mut w = fixture(Some(OLD_HAIR), 2); + w.server + .systems + .economy + .hooks + .quests + .install(Arc::new(TakeCertificates)); + apply(&mut w, NEW_HAIR).await; + assert_eq!(hair_template(&w.pa), Some(NEW_HAIR)); + assert_eq!(w.pa.data().unit.model_params, edited_model()); + assert_eq!( + EconomyForServices.items_count(&w.server, &w.pa, SALON_CERTIFICATE), + 0 + ); + let expected = crate::net::packet::encode(&SCCharacterGenderAndModelModifiedPacket { + character_id: w.pa.character_id, + hair_template_id: NEW_HAIR, + model_params: edited_model(), + })[6..] + .to_vec(); + for frames in [w.a.drain(), w.b.drain()] { + let receipts: Vec<_> = frames + .iter() + .filter(|(op, _)| *op == sc::SCCharacterGenderAndModelModifiedPacket) + .map(|(_, body)| body) + .collect(); + assert_eq!(receipts, vec![&expected]); + assert!(!frames + .iter() + .any(|(op, body)| *op == sc::SCItemTaskSuccessPacket + && body.first() == Some(&item_task::EDIT_COSMETIC))); + } +} From bd25494c8ccd373614764a27d53b5669dd74af1c Mon Sep 17 00:00:00 2001 From: Nick Messer Date: Fri, 23 Oct 2026 13:34:56 -0400 Subject: [PATCH 12/14] test(instances): cover client tower list count boundaries --- .../aaemu-game/src/systems/instances/tests.rs | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/rust/crates/aaemu-game/src/systems/instances/tests.rs b/rust/crates/aaemu-game/src/systems/instances/tests.rs index 1e585f2616..cfa28efd65 100644 --- a/rust/crates/aaemu-game/src/systems/instances/tests.rs +++ b/rust/crates/aaemu-game/src/systems/instances/tests.rs @@ -365,6 +365,34 @@ fn tower_def_packets_are_byte_exact() { ); } +#[test] +fn tower_def_list_count_and_payload_are_bounded_for_the_1_2_client() { + for supplied in [0, 100, 101] { + let infos = (1..=supplied) + .map(|id| TowerDefInfo { + key: TowerDefKey { + tower_def_id: id, + zone_group_id: 0, + }, + zone_id: 0, + spot_id: 0, + target_obj_id: 0, + position: (0.0, 0.0, 0.0), + current_step: 0, + }) + .collect(); + let emitted = supplied.min(100); + let mut expected = vec![emitted as u8]; + for id in 1..=emitted { + expected.extend_from_slice(&id.to_le_bytes()); + expected.extend_from_slice(&[0; 37]); + } + let actual = body(&SCTowerDefListPacket { infos }); + assert_eq!(actual.len(), 1 + emitted as usize * 41); + assert_eq!(actual, expected, "supplied {supplied} tower entries"); + } +} + #[test] fn client_packets_decode() { let mut s = PacketStream::from_bytes(vec![7, 0, 0, 0, 2]); From b399dc5f3585184c5b748244b4a797e2d1227501 Mon Sep 17 00:00:00 2001 From: Nick Messer Date: Fri, 23 Oct 2026 13:37:43 -0400 Subject: [PATCH 13/14] fix(pak): release Unix writer locks before closing descriptors --- rust/crates/aaemu-pak/src/store.rs | 41 ++++++++++++++++++++++++++++++ rust/crates/aaemu-pak/src/tests.rs | 4 +-- 2 files changed, 43 insertions(+), 2 deletions(-) diff --git a/rust/crates/aaemu-pak/src/store.rs b/rust/crates/aaemu-pak/src/store.rs index e1f3dfd55f..636aa70a71 100644 --- a/rust/crates/aaemu-pak/src/store.rs +++ b/rust/crates/aaemu-pak/src/store.rs @@ -93,6 +93,19 @@ impl UpdateLock { } } +#[cfg(unix)] +impl Drop for UpdateLock { + fn drop(&mut self) { + use std::os::fd::AsRawFd; + extern "C" { + fn flock(fd: i32, operation: i32) -> i32; + } + // Closing alone leaves the lock held by descriptors inherited during a + // concurrent subprocess spawn. LOCK_UN releases it before our file closes. + let _ = unsafe { flock(self._file.as_raw_fd(), 8) }; + } +} + fn reader_hash(mut reader: impl Read) -> Result<([u8; 32], u64)> { let mut sha = Sha256::new(); let mut bytes = 0; @@ -672,3 +685,31 @@ fn apply_with_hooks( atomic_write(installed, &new_bytes)?; Ok(ApplyResult::Applied) } + +#[cfg(all(test, unix))] +mod tests { + use super::*; + use crate::tests::Fixture; + + #[test] + fn writer_lock_drop_releases_with_cloned_descriptor() { + let fixture = Fixture::new(); + let lock = UpdateLock::acquire(&fixture.0).unwrap(); + // A subprocess inherits the same open file description until exec closes it. + let inherited = lock._file.try_clone().unwrap(); + assert!(matches!( + UpdateLock::acquire(&fixture.0), + Err(crate::Error::Io(error)) if error.kind() == std::io::ErrorKind::WouldBlock + )); + + drop(lock); + let next_lock = UpdateLock::acquire(&fixture.0).unwrap(); + drop(inherited); + assert!(matches!( + UpdateLock::acquire(&fixture.0), + Err(crate::Error::Io(error)) if error.kind() == std::io::ErrorKind::WouldBlock + )); + drop(next_lock); + drop(UpdateLock::acquire(&fixture.0).unwrap()); + } +} diff --git a/rust/crates/aaemu-pak/src/tests.rs b/rust/crates/aaemu-pak/src/tests.rs index 8c35176c9a..c17ca75b51 100644 --- a/rust/crates/aaemu-pak/src/tests.rs +++ b/rust/crates/aaemu-pak/src/tests.rs @@ -2,9 +2,9 @@ use crate::*; use std::fs; use std::path::PathBuf; -struct Fixture(PathBuf); +pub(super) struct Fixture(pub(super) PathBuf); impl Fixture { - fn new() -> Self { + pub(super) fn new() -> Self { let base = std::env::var_os("AAEMU_PAK_TEST_DIR") .map(PathBuf::from) .unwrap_or_else(std::env::temp_dir); From 1e359beb36a222868d705fa1f92742c4a5775d1f Mon Sep 17 00:00:00 2001 From: Nick Messer Date: Fri, 23 Oct 2026 14:12:41 -0400 Subject: [PATCH 14/14] fix(music): serve native uncached note requests Decode the native tooltip and buff-only flags independently and echo the tooltip flag when loading notes. Preserve legacy missing-song replies, buff-only behavior, and note ID widths; cover all flag combinations with actual packet and buff flow tests. Co-Authored-By: OpenAI Codex --- rust/crates/aaemu-game/PORTING.md | 15 + .../aaemu-game/src/systems/services/music.rs | 78 +++-- .../src/systems/services/music_tests.rs | 278 +++++++++++++++++- 3 files changed, 339 insertions(+), 32 deletions(-) diff --git a/rust/crates/aaemu-game/PORTING.md b/rust/crates/aaemu-game/PORTING.md index a87a6b15b5..7f030cced9 100644 --- a/rust/crates/aaemu-game/PORTING.md +++ b/rust/crates/aaemu-game/PORTING.md @@ -680,6 +680,21 @@ is no longer mirrored (see "Known deviations", dead NPC returned and healed). ## Known deviations from the C# +* systems::services (music): 1.2 CS123 has independent `isTooltip` / `showBuffOnly` + bool bytes (native constructor `397acd70`, serializer `397b1480`). The C# packed + ushort switch ignored uncached playing `(false,false)` and `(true,true)`. Native + `39082550` sends `(isTooltip,false)` on a cache miss and `(false,true)` for cached + playing. Requests with `showBuffOnly=false` now load notes and echo `isTooltip` + in SC1e0; `showBuffOnly=true` retains the buff-only ScoreMemorized (6010) path, + including its lack of a song-existence check. `(true,true)` is representable but + is not emitted by the observed native cache flow; it follows the same buff-only + branch. Missing-song empty replies and existing read/ownership behavior remain. + Request u64 / lookup u32 / response 32-bit widths are unchanged: native SC1e0 + sign-extends its signed32 note ID at `391e1691` before callback `391e169b`. + Arbitrary high request bits still alias the low32 song key; IDs >= 2^31 can + differ between zero-extended sheet IDs and sign-extended native cache keys. + No evidence establishes a safe ID-width or ownership-policy change here. + * systems::skills / systems::npcs (`Interaction` special effect 10): the former C# class was a TODO stub. The 1.2 `special_effects` rows put a `WorldInteractionType` in `value1` (row 11030: 19 `Use`, 36: 10 `DigTerrain`, 215: 29 `SummonBeanstalk`) and an optional doodad id in diff --git a/rust/crates/aaemu-game/src/systems/services/music.rs b/rust/crates/aaemu-game/src/systems/services/music.rs index 88ac1ad920..1be3e6e94d 100644 --- a/rust/crates/aaemu-game/src/systems/services/music.rs +++ b/rust/crates/aaemu-game/src/systems/services/music.rs @@ -218,6 +218,7 @@ impl MusicManager { #[derive(Debug, Clone, PartialEq, Eq)] pub struct SCUserNoteLoadedPacket { pub song: Option, + pub is_tooltip: bool, } packet_def!( SCUserNoteLoadedPacket, @@ -228,7 +229,7 @@ impl Marshal for SCUserNoteLoadedPacket { fn write(&self, s: &mut PacketStream) { if let Some(song) = &self.song { s.write_u32(song.id) - .write_u8(1) + .write_bool(self.is_tooltip) .write_i32(song.song.encode_utf16().count() as i32) .write_str(&song.title) .write_str(&format!("{}\0", song.song)); @@ -332,7 +333,8 @@ impl ClientPacket for CSSendUserMusicPacket { #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct CSRequestMusicNotesPacket { pub id64: u64, - pub value2: u16, + pub is_tooltip: bool, + pub show_buff_only: bool, } impl ClientPacket for CSRequestMusicNotesPacket { @@ -341,7 +343,9 @@ impl ClientPacket for CSRequestMusicNotesPacket { fn read(s: &mut PacketStream) -> Result { Ok(Self { id64: s.read_u64()?, - value2: s.read_u16()?, + // Native 1.2 constructor 397acd70 / serializer 397b1480: two bool bytes. + is_tooltip: s.read_bool()?, + show_buff_only: s.read_bool()?, }) } @@ -351,34 +355,38 @@ impl ClientPacket for CSRequestMusicNotesPacket { conn: &'a mut GameConnection, ) -> BoxFuture<'a, Result<()>> { Box::pin(async move { - tracing::warn!("Request Song, id: {}, value2:{}", self.id64, self.value2); + tracing::debug!( + "Request Song, id: {}, isTooltip:{}, showBuffOnly:{}", + self.id64, + self.is_tooltip, + self.show_buff_only + ); let Some(p) = conn.active_char.clone() else { return Ok(()); }; - match self.value2 { - 1 => { - let song = server - .systems - .services - .music - .get_song_by_id(self.id64 as u32); - p.send(SCUserNoteLoadedPacket { song }); - } - 256 => { - let me = WorldObject::from(&p); - crate::systems::skills::buffs::add_buff_by_id( - server, - &me, - BUFF_SCORE_MEMORIZED, - &me, - 0, - ); - } - _ => tracing::warn!( - "Unknown song request type id: {}, value2:{}", - self.id64, - self.value2 - ), + // Native 39082550 sends (isTooltip, false) on a cache miss and + // (false, true) for cached playing. The latter only needs the buff. + if self.show_buff_only { + let me = WorldObject::from(&p); + crate::systems::skills::buffs::add_buff_by_id( + server, + &me, + BUFF_SCORE_MEMORIZED, + &me, + 0, + ); + } else { + // Keep the C# low-32-bit lookup: native SC1e0 reads signed32, + // sign-extended into the cache key at 391e1691/391e169b. + let song = server + .systems + .services + .music + .get_song_by_id(self.id64 as u32); + p.send(SCUserNoteLoadedPacket { + song, + is_tooltip: self.is_tooltip, + }); } Ok(()) }) @@ -452,10 +460,18 @@ mod tests { .write_str("T") .write_str("abc\0"); assert_eq!( - encode(&SCUserNoteLoadedPacket { song: Some(song) })[6..].to_vec(), + encode(&SCUserNoteLoadedPacket { + song: Some(song), + is_tooltip: true, + })[6..] + .to_vec(), e.into_bytes() ); - assert!(encode(&SCUserNoteLoadedPacket { song: None })[6..].is_empty()); + assert!(encode(&SCUserNoteLoadedPacket { + song: None, + is_tooltip: true, + })[6..] + .is_empty()); } #[test] @@ -497,6 +513,6 @@ mod tests { s.write_u64(5).write_u16(256); let p = CSRequestMusicNotesPacket::read(&mut PacketStream::from_bytes(s.into_bytes())).unwrap(); - assert_eq!((p.id64, p.value2), (5, 256)); + assert_eq!((p.id64, p.is_tooltip, p.show_buff_only), (5, false, true)); } } diff --git a/rust/crates/aaemu-game/src/systems/services/music_tests.rs b/rust/crates/aaemu-game/src/systems/services/music_tests.rs index c565ece88c..1285ed8708 100644 --- a/rust/crates/aaemu-game/src/systems/services/music_tests.rs +++ b/rust/crates/aaemu-game/src/systems/services/music_tests.rs @@ -5,7 +5,16 @@ //! dependencies (both are passed per call); construction has no side effects: no songs, no //! queued uploads, no MIDI cache. -use super::MusicManager; +use super::{CSRequestMusicNotesPacket, MusicManager, SongData, BUFF_SCORE_MEMORIZED}; +use crate::data::GameData; +use crate::net::registry::ClientPacket; +use crate::opcodes::sc; +use crate::systems::skills::data::BuffTemplate; +use crate::systems::skills::types::SkillCaster; +use crate::test_support::{spawn_player, test_character, test_server_with, TestClient}; +use crate::world::PlayerRef; +use crate::GameServer; +use aaemu_commons::PacketStream; #[test] fn constructor_does_not_call_deps() { @@ -14,3 +23,270 @@ fn constructor_does_not_call_deps() { assert!(manager.queued_upload(1).is_none()); assert!(manager.get_midi_cache(1).is_empty()); } + +fn request_fixture() -> (GameServer, TestClient, PlayerRef) { + let mut data = GameData::empty(); + data.systems.skills.add_buff(BuffTemplate { + id: BUFF_SCORE_MEMORIZED, + kind: 1, + ..BuffTemplate::default() + }); + let server = test_server_with(data); + crate::systems::skills::install_hooks(&server); + let mut client = TestClient::new(&server, 1, 1); + let player = spawn_player( + &server, + &client, + test_character(1, "Listener", 10.0, 10.0), + 1, + ); + client.conn.active_char = Some(player.clone()); + client.drain(); + (server, client, player) +} + +fn stored_song(id: u32) -> SongData { + // Reading does not require authorship or holding a sheet in the 1.2 server. + SongData { + id, + author_id: 2, + title: "T".into(), + song: "abc".into(), + source_item_id: 0, + } +} + +fn native_request(id: u64, is_tooltip: bool, show_buff_only: bool) -> CSRequestMusicNotesPacket { + let mut body = id.to_le_bytes().to_vec(); + body.extend([u8::from(is_tooltip), u8::from(show_buff_only)]); + let mut stream = PacketStream::from_bytes(body); + let request = CSRequestMusicNotesPacket::read(&mut stream).unwrap(); + assert_eq!(stream.remaining(), 0); + request +} + +fn expected_notes(id: u32, is_tooltip: bool) -> Vec { + let mut body = id.to_le_bytes().to_vec(); + body.extend([ + u8::from(is_tooltip), + 3, + 0, + 0, + 0, + 1, + 0, + b'T', + 4, + 0, + b'a', + b'b', + b'c', + 0, + ]); + body +} + +#[tokio::test] +async fn native_uncached_play_returns_notes() { + let (server, mut client, player) = request_fixture(); + server + .systems + .services + .music + .st() + .all_songs + .insert(7, stored_song(7)); + + // Native 39082550 cache miss: u64 noteId, isTooltip=false, showBuffOnly=false. + let request = CSRequestMusicNotesPacket::read(&mut PacketStream::from_bytes(vec![ + 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, + ])) + .unwrap(); + request.handle(&server, &mut client.conn).await.unwrap(); + assert_eq!( + client.drain(), + vec![( + sc::SCUserNoteLoadedPacket, + vec![7, 0, 0, 0, 0, 3, 0, 0, 0, 1, 0, b'T', 4, 0, b'a', b'b', b'c', 0], + )], + "native uncached playback must receive SC1e0 with isTooltip=false" + ); + assert!(!player.data().unit.buffs.check_buff(BUFF_SCORE_MEMORIZED)); +} + +#[tokio::test] +async fn native_request_flag_combinations_found_and_missing() { + for found in [true, false] { + for is_tooltip in [false, true] { + for show_buff_only in [false, true] { + let (server, mut client, player) = request_fixture(); + let observer = TestClient::new(&server, 2, 2); + let other = spawn_player( + &server, + &observer, + test_character(2, "Author", 12.0, 10.0), + 2, + ); + client.drain(); + if found { + server + .systems + .services + .music + .st() + .all_songs + .insert(7, stored_song(7)); + } + native_request(7, is_tooltip, show_buff_only) + .handle(&server, &mut client.conn) + .await + .unwrap(); + let frames = client.drain(); + let notes: Vec<_> = frames + .iter() + .filter(|(op, _)| *op == sc::SCUserNoteLoadedPacket) + .cloned() + .collect(); + let expected = if show_buff_only { + Vec::new() + } else { + vec![( + sc::SCUserNoteLoadedPacket, + if found { + expected_notes(7, is_tooltip) + } else { + Vec::new() + }, + )] + }; + assert_eq!( + notes, expected, + "found={found}, tooltip={is_tooltip}, buff={show_buff_only}" + ); + // The existing cached path adds the buff even for an unknown song ID. + assert_eq!( + player.data().unit.buffs.check_buff(BUFF_SCORE_MEMORIZED), + show_buff_only + ); + // SCUnitState also queues patron buffs when another player sees + // us; identify ScoreMemorized and verify its actual wire target. + let memorized: Vec<_> = frames + .iter() + .filter(|(op, _)| *op == sc::SCBuffCreatedPacket) + .filter_map(|(_, body)| { + let mut s = PacketStream::from_bytes(body.clone()); + let kind = s.read_u8().unwrap(); + let caster = SkillCaster::read(kind, &mut s).unwrap(); + let caster_id = s.read_u32().unwrap(); + let owner_obj_id = s.read_bc().unwrap(); + let _index = s.read_u32().unwrap(); + (s.read_u32().unwrap() == BUFF_SCORE_MEMORIZED).then_some(( + caster, + caster_id, + owner_obj_id, + )) + }) + .collect(); + assert_eq!( + memorized, + if show_buff_only { + vec![( + SkillCaster::Unit(player.obj_id), + player.character_id, + player.obj_id, + )] + } else { + Vec::new() + } + ); + assert!(!other.data().unit.buffs.check_buff(BUFF_SCORE_MEMORIZED)); + } + } + } +} + +#[tokio::test] +async fn native_request_requires_active_character() { + for is_tooltip in [false, true] { + for show_buff_only in [false, true] { + let (server, mut client, player) = request_fixture(); + server + .systems + .services + .music + .st() + .all_songs + .insert(7, stored_song(7)); + client.conn.active_char = None; + native_request(7, is_tooltip, show_buff_only) + .handle(&server, &mut client.conn) + .await + .unwrap(); + assert!(client.drain().is_empty()); + assert!(!player.data().unit.buffs.check_buff(BUFF_SCORE_MEMORIZED)); + } + } +} + +#[tokio::test] +async fn request_preserves_u32_lookup_and_response_id() { + // The legacy server casts the request's u64 to u32. Native SC1e0 consumes + // signed32 and sign-extends it (391e1691 cdq); changing either width is unsafe. + for id in [ + 0, + 7, + 0x1_0000_0007, + 0x7fff_ffff, + 0x8000_0000, + 0xffff_ffff_8000_0000, + u64::MAX, + ] { + for is_tooltip in [false, true] { + let (server, mut client, _) = request_fixture(); + let key = id as u32; + server + .systems + .services + .music + .st() + .all_songs + .insert(key, stored_song(key)); + native_request(id, is_tooltip, false) + .handle(&server, &mut client.conn) + .await + .unwrap(); + assert_eq!( + client.drain(), + vec![(sc::SCUserNoteLoadedPacket, expected_notes(key, is_tooltip))] + ); + } + } +} + +#[test] +fn native_request_flag_bytes_and_truncation() { + // Original constructor/serializer 397acd70/397b1480; retained native.tsv request_00..11. + for is_tooltip in [0, 1] { + for show_buff_only in [0, 1] { + let body = [4, 3, 2, 1, 8, 7, 6, 5, is_tooltip, show_buff_only]; + for end in 0..body.len() { + assert!( + CSRequestMusicNotesPacket::read(&mut PacketStream::from_bytes( + body[..end].to_vec() + )) + .is_err() + ); + } + let request = + CSRequestMusicNotesPacket::read(&mut PacketStream::from_bytes(body.to_vec())) + .unwrap(); + assert_eq!(request.id64, 0x0506_0708_0102_0304); + assert_eq!(request.is_tooltip, is_tooltip != 0); + assert_eq!(request.show_buff_only, show_buff_only != 0); + assert_eq!( + request, + native_request(request.id64, is_tooltip != 0, show_buff_only != 0) + ); + } + } +}