diff --git a/crates/benilla-app/src/char_select/mod.rs b/crates/benilla-app/src/char_select/mod.rs index 032dae2d6..91fedc40c 100644 --- a/crates/benilla-app/src/char_select/mod.rs +++ b/crates/benilla-app/src/char_select/mod.rs @@ -95,7 +95,13 @@ impl Plugin for CharSelectPlugin { OnEnter(ClientState::InWorld), refresh::reset_select_background, ) - .add_systems(Update, (debug_glue_roundtrip, debug_logout_smoke)) + .add_systems( + Update, + ( + debug_glue_roundtrip, + debug_logout_smoke.after(crate::player::ControlRestore), + ), + ) .add_systems( Update, ( diff --git a/crates/benilla-app/src/game_plugins.rs b/crates/benilla-app/src/game_plugins.rs index c229f9df3..b1cd524d8 100644 --- a/crates/benilla-app/src/game_plugins.rs +++ b/crates/benilla-app/src/game_plugins.rs @@ -1123,6 +1123,67 @@ pub(crate) mod schedule_tests { /// reason. const OUTSIDE_THE_FEED_PHASE: &[(&str, &str)] = &[]; + /// The create's control restore (`player::regain_control_on_arrival`) is registered in the + /// built client and ordered: after the self create it answers, before the controller and the + /// readers of the flags it clears. A lost `add_systems` line, or a lost `.after`, fails here. + #[test] + fn the_control_restore_runs_after_the_create_and_before_its_readers() { + let mut app = headless_client(); + let c = census(&mut app, Update, SyncPoints::Declared); + if !type_names_available(&c) { + eprintln!( + "skipped: this build carries no type names (bevy/debug rides with the dev feature)" + ); + return; + } + let one = |suffix: &str| -> SystemKey { + let mut hits = c.systems.iter().filter(|(_, s)| s.name.ends_with(suffix)); + match (hits.next(), hits.next()) { + (Some((k, _)), None) => *k, + _ => panic!("exactly one system named `…{suffix}` in Update"), + } + }; + let mut succ: HashMap> = HashMap::new(); + for (a, b) in &c.dependencies { + succ.entry(*a).or_default().push(*b); + } + let reach = |start: SystemKey| { + let mut seen = HashSet::new(); + let mut stack = vec![start]; + while let Some(n) = stack.pop() { + for m in succ.get(&n).into_iter().flatten() { + if seen.insert(*m) { + stack.push(*m); + } + } + } + seen + }; + let restore = one("::wire_in::regain_control_on_arrival"); + let create = one("::net::apply::enter_world_on_self_create"); + assert!( + reach(create).contains(&restore), + "the restore runs after the self create" + ); + let after_restore = reach(restore); + for reader in [ + "::player::controller::control", + "::ui_unit::feed_player_control", + "::ui_action::state::feed_action_state", + "::ui_shapeshift::feed_shapeshift_bar", + "::player::camera_saved::load_camera_pose", + "::tutorial::watch_self", + "::ui_trade::answer_trade_request", + "::poi_marker::expire_marker", + "::char_select::debug_logout_smoke", + ] { + assert!( + after_restore.contains(&one(reader)), + "`{reader}` runs after the control restore" + ); + } + } + /// The VM ticks once a frame (`extract::tick_script`, in `UiInput`): a push the tick must /// see rides `UiFeed`, chained after the net drain and before the tick; a drain of what it /// produced is `.after(UiInput)`. Read off the built graph. Fails a holder with no path to or diff --git a/crates/benilla-app/src/net.rs b/crates/benilla-app/src/net.rs index 367049bdf..96b58dc0d 100644 --- a/crates/benilla-app/src/net.rs +++ b/crates/benilla-app/src/net.rs @@ -140,6 +140,9 @@ impl Plugin for NetPlugin { apply_net_updates, tag_self_player, enter_world_on_self_create, + // The create gives control back (`0x5deb56`), in the Net stage ahead of + // `control`'s read of the flags. + crate::player::regain_control_on_arrival.in_set(crate::player::ControlRestore), sample_splines, // Swim state from the water at the feet (the wire never carries it for // creatures), before the clamp so a swimmer is exempt the same frame. diff --git a/crates/benilla-app/src/player.rs b/crates/benilla-app/src/player.rs index 304c98ef4..da332a3e4 100644 --- a/crates/benilla-app/src/player.rs +++ b/crates/benilla-app/src/player.rs @@ -65,6 +65,12 @@ mod swim; mod view_subject; mod walk; mod wire_in; +pub(crate) use wire_in::regain_control_on_arrival; + +/// The create's control restore (`regain_control_on_arrival`): every system that reads `Player`'s +/// control flags runs after it in the frame, so it sees the restored flags, not the lost ones. +#[derive(SystemSet, Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub(crate) struct ControlRestore; // The last writer of a self body part's render alpha: `entities::apply_unit_mat_alpha` orders // itself before it. diff --git a/crates/benilla-app/src/player/camera_saved.rs b/crates/benilla-app/src/player/camera_saved.rs index 32f637da1..e9da20bd3 100644 --- a/crates/benilla-app/src/player/camera_saved.rs +++ b/crates/benilla-app/src/player/camera_saved.rs @@ -185,7 +185,10 @@ pub(super) fn plugin(app: &mut App) { Update, // Before the controller, so the first in-world frame renders the restored pose. A // capture resolves no state path, so this is inert there. - load_camera_pose.before(super::control).in_set(InWorldGated), + load_camera_pose + .after(super::ControlRestore) + .before(super::control) + .in_set(InWorldGated), ) .add_systems(OnExit(ClientState::InWorld), save_on_session_end); // On the exit edge, never `Update`: the close button's `AppExit` is written in `PostUpdate`. diff --git a/crates/benilla-app/src/player/wire_in.rs b/crates/benilla-app/src/player/wire_in.rs index 322d16585..ac7a1b56f 100644 --- a/crates/benilla-app/src/player/wire_in.rs +++ b/crates/benilla-app/src/player/wire_in.rs @@ -498,6 +498,28 @@ fn apply_self_move( player.wedge_still = 0; } +/// Our own player's create gives control back (`OnActiveArrival 0x5dea50`): with the manager's +/// `+0xc8` clear (`0x5deb49`; its constructor `0x4650e7` is the only store, so every create), +/// `0x5fa600(1)` (`0x5deb56`) raises `[0xb4b3e4]` through `0x4958e0` (`PLAYER_CONTROL_GAINED` if it +/// was down) and `0x4958a0` (`0x5deb5b`) stores 1 and re-claims our own mover (the claim is sent +/// by `enter_world_on_self_create`). vmangos sends a battleground's closing `control 0` and no +/// restore (`BattleGround.cpp:905-908`). The event is the `ui_unit::feed_player_control` edge. +pub(crate) fn regain_control_on_arrival( + mut arrivals: MessageReader, + mut player: ResMut, +) { + if arrivals.read().next().is_none() { + return; + } + if player.own_control_lost || player.control_lost || player.foreign_mover.is_some() { + player.own_control_lost = false; + player.control_lost = false; + // The mover is ours again, as `ControlVerdict::Restored` seats it. + player.foreign_mover = None; + player.reseat = true; + } +} + /// On a `/logout` or a lost session, reset the whole resource to its boot state, so the next login /// owes nothing to the ended one. Whole, not by field: `/logout` roots us for the countdown /// (`MiscHandler.cpp:329`) and the next session never unroots, so any kept mover state persists. @@ -796,3 +818,91 @@ mod teleport_tests { assert!(player.settling && player.ride_abort && player.world_stale); } } + +#[cfg(test)] +mod arrival_tests { + use super::*; + use crate::net::WorldEnterCascadeMessage; + + const ME: u64 = 0x45; + + fn harness() -> App { + let mut app = App::new(); + app.add_plugins(MinimalPlugins) + .init_resource::() + .add_message::() + .add_systems(Update, regain_control_on_arrival); + app + } + + /// A battleground's end sends `control 0` for us and never the restore; the teleport out + /// creates us afresh and that create gives control back, the movement lock and the bar's + /// `[0xb4b3e4]` flag both. + #[test] + fn a_control_loss_does_not_survive_the_next_self_create() { + let mut app = harness(); + let mut player = app.world_mut().resource_mut::(); + track_control(&mut player, control_verdict(ME, false, Some(ME))); + assert!(player.control_lost && player.own_control_lost); + app.update(); + assert!( + app.world().resource::().own_control_lost, + "nothing restores it without a create" + ); + + app.world_mut().write_message(WorldEnterCascadeMessage); + app.update(); + let player = app.world().resource::(); + assert!(!player.own_control_lost, "the bar's flag is back"); + assert!(!player.control_lost, "and the controller's movement lock"); + assert_eq!(player.foreign_mover, None); + } + + /// The real create system feeds it: a control-0 packet's verdict, then our own player's + /// create (`enter_world_on_self_create`), and the lock and the flag are gone. + #[test] + fn our_own_create_system_gives_control_back() { + let (tx, _rx) = crossbeam_channel::unbounded(); + let mut app = harness(); + app.insert_resource(crate::net::NetCommands(tx)) + .add_systems( + Update, + crate::net::enter_world_on_self_create.before(regain_control_on_arrival), + ); + let mut player = app.world_mut().resource_mut::(); + track_control(&mut player, control_verdict(ME, false, Some(ME))); + app.update(); + assert!(app.world().resource::().own_control_lost); + + app.world_mut() + .spawn((crate::net::Guid(ME), crate::net::SelfPlayer)); + app.update(); + let player = app.world().resource::(); + assert!(!player.own_control_lost && !player.control_lost); + } + + /// A possession does not outlive the world either: the create claims our own mover. + #[test] + fn a_create_ends_a_possession_too() { + let mut app = harness(); + { + let mut player = app.world_mut().resource_mut::(); + player.foreign_mover = Some(0x99); + player.control_lost = true; + } + app.world_mut().write_message(WorldEnterCascadeMessage); + app.update(); + let player = app.world().resource::(); + assert_eq!(player.foreign_mover, None); + assert!(!player.control_lost && player.reseat); + } + + /// A login in control touches nothing. + #[test] + fn a_create_in_control_changes_nothing() { + let mut app = harness(); + app.world_mut().write_message(WorldEnterCascadeMessage); + app.update(); + assert!(!app.world().resource::().reseat); + } +} diff --git a/crates/benilla-app/src/poi_marker.rs b/crates/benilla-app/src/poi_marker.rs index 52d1b55d4..146fc5e97 100644 --- a/crates/benilla-app/src/poi_marker.rs +++ b/crates/benilla-app/src/poi_marker.rs @@ -145,8 +145,13 @@ impl Plugin for PoiMarkerPlugin { use benilla_protocol::SessionEventKind as K; app.net_handler(K::GossipPoi, on_gossip_poi); } - app.init_resource::() - .add_systems(Update, (expire_marker, clear_on_world_entry)); + app.init_resource::().add_systems( + Update, + ( + expire_marker.after(crate::player::ControlRestore), + clear_on_world_entry, + ), + ); } } diff --git a/crates/benilla-app/src/spell/cast_send.rs b/crates/benilla-app/src/spell/cast_send.rs index bf3388a07..ff0450cf4 100644 --- a/crates/benilla-app/src/spell/cast_send.rs +++ b/crates/benilla-app/src/spell/cast_send.rs @@ -535,7 +535,13 @@ fn send_spell_cast( CastCommit::Item { entry, .. } => entry, CastCommit::Spell => 0, }; - if cooldowns.not_ready(spell_id, queried_item, def, now) { + // The item's own category for this spell replaces the spell's in the category leg (`0x6e1492`). + let item_category = items + .template_cached(queried_item) + .and_then(|t| t.use_spell) + .filter(|u| u.spell_id == spell_id) + .map_or(0, |u| u.category); + if cooldowns.not_ready(spell_id, queried_item, item_category, def, now) { debug!("ui_action: cast {spell_id} refused locally — not ready (the validator's rung 1)"); // The one packet a local refusal sends (`0x609576–0x60960f`, spell leg only): a running // repeat with AttributesEx3 0x400000 (wand Shoot) gets `CMSG_CANCEL_CAST`, then the local @@ -1592,6 +1598,46 @@ mod tests { assert!(world.resource::().0.is_empty()); } + /// The item press queries with its own spell-slot category (`0x6e1457`-`0x6e1499`): another + /// item's running category-28 timer refuses it 0x28, though the spell row carries no category. + #[test] + fn an_item_press_not_readies_on_its_own_category() { + use benilla_protocol::messages::ItemUseSpell; + let (mut world, rx) = world(); + let mut template = crate::items::test_template("Hearthstone"); + template.use_spell = Some(ItemUseSpell { + spell_id: HEARTHSTONE, + cooldown_ms: 0, + category: 28, + category_cooldown_ms: 0, + }); + world + .resource_mut::() + .insert_template(6948, Some(template)); + let other = ItemUseSpell { + spell_id: MOUNT, + cooldown_ms: 0, + category: 28, + category_cooldown_ms: 30_000, + }; + world.resource_mut::().start_item( + 7001, + &other, + None, + Instant::now(), + ); + + send(&mut world, HEARTHSTONE, HEARTH_COMMIT); + assert!( + rx.try_recv().is_err(), + "the shared category holds the press" + ); + assert_eq!( + world.resource::().0, + vec![CastFail::local(HEARTHSTONE, 0x28)] + ); + } + /// `SendCast 0x6e54f0`: two opcodes, one targets block; a key's lock rides it as /// `TARGET_FLAG_GAMEOBJECT|LOCKED`. #[test] diff --git a/crates/benilla-app/src/spell/cooldowns.rs b/crates/benilla-app/src/spell/cooldowns.rs index 93dc7e347..ebfc7ab6b 100644 --- a/crates/benilla-app/src/spell/cooldowns.rs +++ b/crates/benilla-app/src/spell/cooldowns.rs @@ -57,15 +57,24 @@ struct Record { /// The recovery timers hold their durations but have not started. on_hold: bool, gcd_category: u32, - gcd: Timer, + /// The GCD's time; it runs from [`Self::recovery`]'s start, the one `+0x10` start the + /// reference's GCD leg reads (`0x6e15d8`), so `SMSG_COOLDOWN_EVENT` restarts it too. + gcd: Duration, } -/// One action's cooldown read (`GetActionCooldown`): the winning timer's start, duration and -/// remainder, and `enabled == false` for an on-hold record, which `CooldownFrame_SetTimer` -/// hides. The start is what `GetCooldownInfo 0x6e13e0` returns, so two arms never alias. +impl Record { + fn gcd_remaining(&self, now: Instant) -> Duration { + (self.recovery.start + self.gcd).saturating_duration_since(now) + } +} + +/// One action's cooldown read (`GetActionCooldown`): the winning leg's start and duration, the +/// remainder to the latest end, and `enabled == false` once a parked leg passed, which +/// `CooldownFrame_SetTimer` hides. The start is what `GetCooldownInfo 0x6e13e0` returns, so two +/// arms never alias. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) struct CooldownInfo { - /// For an on-hold record, when it was inserted. + /// A parked leg reports the query's `now`. pub start: Instant, pub remaining_ms: u32, pub duration_ms: u32, @@ -73,11 +82,16 @@ pub(crate) struct CooldownInfo { } impl CooldownInfo { - /// `(start_ms on the GetTime clock, duration_ms, enabled)`, or `None` when cold. `anchor` and + /// `(start_ms on the GetTime clock, duration_ms, enabled)`, or `None` when cold. A held read + /// (`enabled` false) pushes a start of 0: its start is the query's now (`0x6e1517`, + /// `0x6e15a1`), which the Lua bindings answer at call time, so the pushed state never moves. `anchor` and /// `ui_now` must be the frame's one clock pair ([`crate::ui_script::UiClock`]), so one arm /// derives the same start every frame; a fresh `Instant::now()` here would jitter it. pub(crate) fn ui_triple(&self, anchor: Instant, ui_now: f64) -> Option<(i64, u32, bool)> { (self.remaining_ms > 0).then(|| { + if !self.enabled { + return (0, self.duration_ms, false); + } // Signed both ways: a timer armed after the anchor sample projects forward. let start = match self.start.checked_duration_since(anchor) { Some(ahead) => ui_now + ahead.as_secs_f64(), @@ -131,7 +145,7 @@ impl Cooldowns { !r.on_hold && r.recovery.remaining(now).is_zero() && r.category_recovery.remaining(now).is_zero() - && r.gcd.remaining(now).is_zero() + && r.gcd_remaining(now).is_zero() }) } @@ -153,13 +167,13 @@ impl Cooldowns { category_recovery: Timer, on_hold: bool, gcd_category: u32, - gcd: Timer, + gcd: Duration, ) { // The client's early-out when nothing is tracked (`0x6e12c3`). if recovery.duration.is_zero() && category_recovery.duration.is_zero() && !on_hold - && gcd.duration.is_zero() + && gcd.is_zero() { return; } @@ -188,7 +202,7 @@ impl Cooldowns { r.on_hold || !r.recovery.remaining(now).is_zero() || !r.category_recovery.remaining(now).is_zero() - || !r.gcd.remaining(now).is_zero() + || !r.gcd_remaining(now).is_zero() }); if self.records.len() != before { self.expiry_epoch = self.expiry_epoch.wrapping_add(1); @@ -236,7 +250,7 @@ impl Cooldowns { }, spell.cooldown_on_event(), 0, - Timer::none(now), + Duration::ZERO, ); } @@ -276,7 +290,7 @@ impl Cooldowns { }, spell.is_some_and(|s| s.cooldown_on_event()), 0, - Timer::none(now), + Duration::ZERO, ); } @@ -320,10 +334,7 @@ impl Cooldowns { Timer::none(now), spell.cooldown_on_event(), spell.start_recovery_category, - Timer { - start: now, - duration: Duration::from_millis(duration_ms as u64), - }, + Duration::from_millis(duration_ms as u64), ); } @@ -331,10 +342,10 @@ impl Cooldowns { pub(crate) fn clear_gcd(&mut self, spell_id: u32, now: Instant) { let mut touched = false; for r in &mut self.records { - if r.spell_id == spell_id && !r.gcd.duration.is_zero() { + if r.spell_id == spell_id && !r.gcd.is_zero() { // `0x6e1630` zeroes both the category and the time. r.gcd_category = 0; - r.gcd = Timer::none(now); + r.gcd = Duration::ZERO; touched = true; } } @@ -350,7 +361,8 @@ impl Cooldowns { } } - /// `SMSG_COOLDOWN_EVENT` (`0x6e1790`, force 0): an on-hold record's timers start now. + /// `SMSG_COOLDOWN_EVENT` (`0x6e1790`, force 0): an on-hold record's recovery and category + /// starts become now (`0x6e185a`-`0x6e1863`), and with the recovery start the GCD leg's. pub(crate) fn cooldown_event(&mut self, spell_id: u32, now: Instant) { let mut touched = false; for r in &mut self.records { @@ -441,10 +453,7 @@ impl Cooldowns { }, on_hold, gcd_category, - Timer { - start: now, - duration: Duration::from_millis(u64::from(gcd_ms)), - }, + Duration::from_millis(u64::from(gcd_ms)), ); } @@ -468,7 +477,7 @@ impl Cooldowns { Timer::none(now), false, 0, - Timer::none(now), + Duration::ZERO, ); } @@ -496,7 +505,7 @@ impl Cooldowns { }, false, 0, - Timer::none(now), + Duration::ZERO, ); } @@ -531,7 +540,7 @@ impl Cooldowns { }, false, 0, - Timer::none(now), + Duration::ZERO, ); self.generation = generation; } @@ -557,23 +566,38 @@ impl Cooldowns { /// refused whatever its own `startRecoveryTime`. The caller picks the reason (`0x60952b`): /// 0x28 for an item, 0x3c for a spell. Refusing locally matters: the server's NOT_READY /// failure would clear the running GCD. + /// `item_category` is [`Self::info_item`]'s: the item's own for an item press, else 0. pub(crate) fn not_ready( &self, spell_id: u32, item_entry: u32, + item_category: u32, spell: Option<&SpellDisplay>, now: Instant, ) -> bool { - self.info(spell_id, item_entry, spell, now).remaining_ms > 0 + self.info_item(spell_id, item_entry, item_category, spell, now) + .remaining_ms + > 0 } - /// `GetCooldownInfo 0x6e13e0`: the longest remainder over every record's three legs. + /// `GetCooldownInfo 0x6e13e0`: the latest end over every record's three legs, in list order. /// /// - `Effect[0]` of ATTACK or TRADE_SKILL always reads cold (`0x6e1439`). - /// - Spell leg: id and item match; a parked record reads its full duration, disabled. - /// - Category leg: equal category, or any query for a wildcard row; parked likewise. - /// - GCD leg (`0x6e15cc`): the node's GCD category equals the query's - /// `startRecoveryCategory` and the node's time is nonzero; it ignores on-hold. + /// - A leg passes when its end is not before the best so far (`0x6e14f7`, `0x6e1588`, + /// `0x6e15df`, `js`), so on a tie the later leg writes; it writes its duration and start. + /// - Spell leg: id and item match, time or held nonzero (`0x6e14d2`). A parked record ends at + /// its time past `now + 1 ms` and writes a duration of 1 ms and a start of now + /// (`0x6e14ea`, `0x6e1503`, `0x6e1517`). + /// - Category leg (`0x6e155a`-`0x6e156d`): equal nonzero category, or any query for a wildcard + /// row, with a category time. A parked record ends at its time past `now`, writes that time + /// and a start of now (`0x6e15a1`). + /// - Both legs set `enabled` to "not parked" only while it is still true (`0x6e152d`, + /// `0x6e15b2`): one parked leg that passes disables the read for the rest of the walk. + /// - GCD leg (`0x6e15cc`): the node's GCD category equals the query's `startRecoveryCategory` + /// and the node's time is nonzero; it ignores on-hold and never touches `enabled`. It runs + /// from the recovery start (`0x6e15d8`). + /// - With an item, the category leg queries the item's own spell-slot category instead of the + /// spell's when that is positive (`0x6e1457`-`0x6e1499`): see [`Self::info_item`]. pub(crate) fn info( &self, spell_id: u32, @@ -581,53 +605,87 @@ impl Cooldowns { spell: Option<&SpellDisplay>, now: Instant, ) -> CooldownInfo { - let mut best = CooldownInfo { + self.info_item(spell_id, item_entry, 0, spell, now) + } + + /// [`Self::info`] for an item's on-use spell: a positive `item_category` (the item's + /// `spellcategory` for that spell, `+0x16c` of its slot) replaces the spell's own category in + /// the category leg (`0x6e1492`), as Fishliver Oil's 28 replaces the spell's 4. The GCD leg + /// keeps the spell's `startRecoveryCategory`. 0 keeps the spell's. + pub(crate) fn info_item( + &self, + spell_id: u32, + item_entry: u32, + item_category: u32, + spell: Option<&SpellDisplay>, + now: Instant, + ) -> CooldownInfo { + let mut out = CooldownInfo { start: now, remaining_ms: 0, duration_ms: 0, enabled: true, }; if spell.is_some_and(|s| s.cooldown_query_excluded()) { - return best; + return out; } - let category = spell.map_or(0, |s| s.category); - let start_recovery_category = spell.map_or(0, |s| s.start_recovery_category); - let mut consider = |timer: &Timer, remaining: Duration, enabled: bool| { - let remaining_ms = remaining.as_millis().min(u128::from(u32::MAX)) as u32; - if remaining_ms > best.remaining_ms { - best = CooldownInfo { - start: timer.start, - remaining_ms, - duration_ms: timer.duration.as_millis().min(u128::from(u32::MAX)) as u32, - enabled, - }; - } + let category = match item_category { + 0 => spell.map_or(0, |s| s.category), + c => c, }; + let start_recovery_category = spell.map_or(0, |s| s.start_recovery_category); + let ms = |d: Duration| d.as_millis().min(u128::from(u32::MAX)) as u32; + let mut best_end = now; + let mut leg = |end: Instant, start: Instant, duration: Duration| { + if end < best_end { + return false; + } + best_end = end; + out.start = start; + out.duration_ms = ms(duration); + true + }; + let mut enabled = true; for r in &self.records { - if r.spell_id == spell_id && r.item_id == item_entry { - if r.on_hold { - // Parked: full duration, disabled (enable 0 hides the sweep). - consider(&r.recovery, r.recovery.duration, false); + if r.spell_id == spell_id + && r.item_id == item_entry + && (!r.recovery.duration.is_zero() || r.on_hold) + { + let passed = if r.on_hold { + let end = now + r.recovery.duration + Duration::from_millis(1); + leg(end, now, Duration::from_millis(1)) } else { - consider(&r.recovery, r.recovery.remaining(now), true); + let end = r.recovery.start + r.recovery.duration; + leg(end, r.recovery.start, r.recovery.duration) + }; + if passed { + enabled &= !r.on_hold; } } - if (r.category != 0 && r.category == category) || r.category_wildcard { - if r.on_hold { - consider(&r.category_recovery, r.category_recovery.duration, false); + if ((r.category != 0 && r.category == category) || r.category_wildcard) + && !r.category_recovery.duration.is_zero() + { + let passed = if r.on_hold { + leg( + now + r.category_recovery.duration, + now, + r.category_recovery.duration, + ) } else { - consider( - &r.category_recovery, - r.category_recovery.remaining(now), - true, - ); + let end = r.category_recovery.start + r.category_recovery.duration; + leg(end, r.category_recovery.start, r.category_recovery.duration) + }; + if passed { + enabled &= !r.on_hold; } } - if r.gcd_category == start_recovery_category && !r.gcd.duration.is_zero() { - consider(&r.gcd, r.gcd.remaining(now), true); + if r.gcd_category == start_recovery_category && !r.gcd.is_zero() { + leg(r.recovery.start + r.gcd, r.recovery.start, r.gcd); } } - best + out.remaining_ms = ms(best_end.saturating_duration_since(now)); + out.enabled = enabled; + out } } @@ -733,7 +791,7 @@ mod tests { assert_eq!(ch.remaining_ms, 0, "no startRecoveryCategory — no GCD read"); // The press gate reads the same getter; `0x6e1690` stays false with nothing parked. - assert!(cds.not_ready(133, 0, Some(&fireball()), mid)); + assert!(cds.not_ready(133, 0, 0, Some(&fireball()), mid)); assert!(!cds.has_on_hold_record(133, 0, fireball().category)); } @@ -756,7 +814,7 @@ mod tests { "the GO self-insert must not eat the GCD node" ); assert!( - cds.not_ready(133, 0, Some(&fireball()), mid), + cds.not_ready(133, 0, 0, Some(&fireball()), mid), "the local lock holds too" ); // Frost Nova's own button reads the longer, its own cooldown. @@ -772,12 +830,12 @@ mod tests { cds.start_gcd(5384, &fd, t0, &super::SpellModifiers::default()); cds.start_spell(5384, &fd, 0, t0, None); let mid = t0 + Duration::from_millis(100); - assert!(cds.not_ready(5384, 0, Some(&fd), mid)); + assert!(cds.not_ready(5384, 0, 0, Some(&fd), mid)); // The fail path (0x6e1a00): GCD cleared (0x6e1630), the record removed (0x6e3050). cds.clear_gcd(5384, mid); cds.clear_spell(5384); - assert!(!cds.not_ready(5384, 0, Some(&fd), mid)); + assert!(!cds.not_ready(5384, 0, 0, Some(&fd), mid)); assert_eq!(cds.info(5384, 0, Some(&fd), mid).remaining_ms, 0); } @@ -793,7 +851,7 @@ mod tests { let s = cds.info(999, 0, Some(&sibling), mid); assert_eq!((s.remaining_ms, s.duration_ms), (10_000, 15_000)); assert!( - cds.not_ready(999, 0, Some(&sibling), mid), + cds.not_ready(999, 0, 0, Some(&sibling), mid), "category lock is a not-ready" ); // An unrelated spell reads nothing. @@ -808,14 +866,14 @@ mod tests { let fd = spell(0, 30_000, 0, (0, 0), 0x0200_0000); cds.start_spell(5384, &fd, 0, t0, None); - // Parked: full duration, disabled, and still not ready. + // Parked: the 30 s past now + 1 ms (`0x6e14ea`), disabled, and still not ready. let parked = cds.info(5384, 0, Some(&fd), t0 + Duration::from_secs(60)); assert_eq!( (parked.remaining_ms, parked.enabled), - (30_000, false), + (30_001, false), "an on-hold record never elapses on its own" ); - assert!(cds.not_ready(5384, 0, Some(&fd), t0 + Duration::from_secs(60))); + assert!(cds.not_ready(5384, 0, 0, Some(&fd), t0 + Duration::from_secs(60))); assert!( cds.has_on_hold_record(5384, 0, fd.category), "the corrected 0x6e1690: an on-hold record — the usable walk's grey-while-parked" @@ -831,6 +889,160 @@ mod tests { ); } + /// Stealth-shaped: 10 s recovery, GCD category 133 for 1 s, `SPELL_ATTR_COOLDOWN_ON_EVENT`. + fn stealth() -> SpellDisplay { + spell(0, 10_000, 0, (133, 1_000), 0x0200_0000) + } + + /// `0x6e1503`, `0x6e1517`: a parked spell leg writes a duration of 1 ms and the query's now, + /// not the record's recovery and insert time. + #[test] + fn a_parked_spell_leg_reads_one_ms_from_now() { + let t0 = Instant::now(); + let mut cds = Cooldowns::default(); + cds.start_spell(1784, &stealth(), 0, t0, None); + + let now = t0 + Duration::from_secs(7); + let info = cds.info(1784, 0, Some(&stealth()), now); + assert_eq!( + (info.start, info.duration_ms, info.enabled), + (now, 1, false), + "(now, 0.001, 0), where the old read gave (insert time, 10, 0)" + ); + assert_eq!(info.remaining_ms, 10_001, "the end is time + now + 1 ms"); + let (start, duration, enabled) = info.ui_triple(now, 42.0).unwrap(); + assert_eq!( + (start, duration, enabled), + (0, 1, false), + "a held read pushes the marker, not a moving start" + ); + } + + /// `0x6e15a1`: a parked category leg keeps the category time as the duration and reads a + /// start of now. + #[test] + fn a_parked_category_leg_reads_its_time_from_now() { + let t0 = Instant::now(); + let mut cds = Cooldowns::default(); + // Recovery 0, category 12 for 5 s, parked. + let parked = spell(12, 0, 5_000, (0, 0), 0x0200_0000); + cds.start_spell(900, &parked, 0, t0, None); + + let now = t0 + Duration::from_secs(3); + let sibling = spell(12, 0, 0, (0, 0), 0); + let info = cds.info(901, 0, Some(&sibling), now); + assert_eq!( + ( + info.start, + info.duration_ms, + info.remaining_ms, + info.enabled + ), + (now, 5_000, 5_000, false) + ); + } + + /// `0x6e152d`, `0x6e15b2`: once a parked leg that passed has set enable to 0 a later leg that + /// is not parked leaves it 0; in the other order the parked leg that ends earlier does not + /// pass, so the read stays enabled. + #[test] + fn a_disabled_read_stays_disabled_whatever_leg_follows() { + let t0 = Instant::now(); + let plain = |recovery| spell(0, recovery, 0, (0, 0), 0); + let held = |recovery| spell(0, recovery, 0, (0, 0), 0x0200_0000); + + let mut cds = Cooldowns::default(); + cds.start_spell(77, &held(5_000), 0, t0, None); + cds.start_spell(77, &plain(60_000), 0, t0, None); + let info = cds.info(77, 0, Some(&plain(0)), t0); + assert_eq!((info.remaining_ms, info.duration_ms), (60_000, 60_000)); + assert!(!info.enabled, "the later unparked leg does not re-enable"); + + let mut cds = Cooldowns::default(); + cds.start_spell(77, &plain(60_000), 0, t0, None); + cds.start_spell(77, &held(5_000), 0, t0, None); + let info = cds.info(77, 0, Some(&plain(0)), t0); + assert_eq!((info.remaining_ms, info.duration_ms), (60_000, 60_000)); + assert!( + info.enabled, + "5 s parked ends before the 60 s: it does not pass" + ); + } + + /// A held read's start is the query's now, which moves with it; the triple a feed pushes is + /// the held marker, so it does not move and the feeds see no change. + #[test] + fn a_held_triple_is_the_same_whatever_the_query_time() { + let t0 = Instant::now(); + let mut cds = Cooldowns::default(); + cds.start_spell(1784, &stealth(), 0, t0, None); + let at = |ms: u64| { + cds.info(1784, 0, Some(&stealth()), t0 + Duration::from_millis(ms)) + .ui_triple(t0, 7.0) + }; + assert_ne!( + cds.info(1784, 0, Some(&stealth()), t0).start, + cds.info(1784, 0, Some(&stealth()), t0 + Duration::from_millis(20)) + .start, + "the read's own start moves" + ); + assert_eq!(at(0), at(20)); + assert_eq!(at(0), Some((0, 1, false))); + } + + /// A parked record with no recovery (Shadowform) still passes the spell leg (`0x6e14d9`): the + /// read is not cold and a press is refused. + #[test] + fn a_parked_record_with_no_recovery_still_reads() { + let t0 = Instant::now(); + let mut cds = Cooldowns::default(); + let form = spell(0, 0, 0, (133, 1_500), 0x0200_0000); + cds.start_spell(15473, &form, 0, t0, None); + + let info = cds.info(15473, 0, Some(&form), t0); + assert_eq!( + ( + info.start, + info.duration_ms, + info.remaining_ms, + info.enabled + ), + (t0, 1, 1, false) + ); + assert!(cds.not_ready(15473, 0, 0, Some(&form), t0)); + } + + /// `0x6e185a`-`0x6e1863`, `0x6e15d8`: the event moves the one start the GCD leg reads, so the + /// global cooldown runs again from the event. + #[test] + fn a_cooldown_event_restarts_the_gcd_from_the_event() { + let t0 = Instant::now(); + let mut cds = Cooldowns::default(); + let mods = SpellModifiers::default(); + let form = spell(0, 0, 0, (133, 1_500), 0x0200_0000); + cds.start_gcd(15473, &form, t0, &mods); + cds.start_spell(15473, &form, 0, t0, None); + + let event_at = t0 + Duration::from_secs(60); + cds.cooldown_event(15473, event_at); + + let now = event_at + Duration::from_millis(500); + let info = cds.info(15473, 0, Some(&form), now); + assert_eq!( + ( + info.start, + info.duration_ms, + info.remaining_ms, + info.enabled + ), + (event_at, 1_500, 1_000, true) + ); + // A sibling of the GCD category reads the same run. + let sibling = spell(0, 0, 0, (133, 1_500), 0); + assert_eq!(cds.info(133, 0, Some(&sibling), now).remaining_ms, 1_000); + assert!(cds.not_ready(133, 0, 0, Some(&sibling), now)); + } + #[test] fn wire_cooldowns_take_the_server_duration_or_fall_back_to_the_dbc() { let t0 = Instant::now(); @@ -931,6 +1143,44 @@ mod tests { assert_eq!(other.remaining_ms, 45_000); } + /// `0x6e1457`-`0x6e1499`: with an item, the category leg queries the item's own category for + /// the spell (Fishliver Oil: spell category 4, item category 28), so the oil's record reaches + /// a sibling of category 28 and no longer a bare category-4 spell. + #[test] + fn an_item_query_uses_the_items_category_override() { + let t0 = Instant::now(); + let mut cds = Cooldowns::default(); + let oil_spell = spell(4, 0, 0, (0, 0), 0); + let oil = ItemUseSpell { + spell_id: 1322, + cooldown_ms: 0, + category: 28, + category_cooldown_ms: 20_000, + }; + cds.start_item(1322, &oil, Some(&oil_spell), t0); + let mid = t0 + Duration::from_secs(5); + + // The oil's own query, and a second item of category 28 over the same spell. + let own = cds.info_item(1322, 1322, 28, Some(&oil_spell), mid); + assert_eq!((own.remaining_ms, own.duration_ms), (15_000, 20_000)); + assert!(cds.not_ready(1322, 1322, 28, Some(&oil_spell), mid)); + // Another item whose slot carries category 28 reads the oil's category timer; the spell's + // own category 4 does not match the record's 28. + let other = cds.info_item(1322, 4096, 28, Some(&oil_spell), mid); + assert_eq!(other.remaining_ms, 15_000); + let by_spell = cds.info(1322, 4096, Some(&oil_spell), mid); + assert_eq!( + by_spell.remaining_ms, 0, + "the spell's category 4 is not the record's 28" + ); + // No override keeps the spell's category: a category-4 record reaches it. + cds.start_spell(77, &spell(4, 0, 9_000, (0, 0), 0), 0, t0, None); + assert_eq!( + cds.info(1322, 4096, Some(&oil_spell), mid).remaining_ms, + 4_000 + ); + } + #[test] fn prune_drops_only_fully_elapsed_records() { let t0 = Instant::now(); @@ -1183,24 +1433,30 @@ mod tests { let t0 = Instant::now(); let mut cds = Cooldowns::default(); assert!( - !cds.not_ready(133, 0, Some(&fireball()), t0), + !cds.not_ready(133, 0, 0, Some(&fireball()), t0), "no GCD running — nothing locks" ); cds.start_gcd(772, &fireball(), t0, &super::SpellModifiers::default()); let mid = t0 + Duration::from_millis(200); assert!( - cds.not_ready(133, 0, Some(&fireball()), mid), + cds.not_ready(133, 0, 0, Some(&fireball()), mid), "the spam press 200 ms later is locked — refused, never sent, the GCD lives" ); // Scroll of Armor's shape. let scroll = spell(0, 0, 0, (133, 0), 0x10000); assert!( - cds.not_ready(8091, 0, Some(&scroll), mid), + cds.not_ready(8091, 0, 0, Some(&scroll), mid), "a zero-GCD press in the shared category is locked on the reference" ); - assert!(!cds.not_ready(100, 0, Some(&charge()), mid)); - assert!(!cds.not_ready(133, 0, Some(&fireball()), t0 + Duration::from_millis(1_501))); + assert!(!cds.not_ready(100, 0, 0, Some(&charge()), mid)); + assert!(!cds.not_ready( + 133, + 0, + 0, + Some(&fireball()), + t0 + Duration::from_millis(1_501) + )); } /// The getter's exclusion (`0x6e1439`, `0x6e1442`). @@ -1216,7 +1472,7 @@ mod tests { ..Default::default() }; assert_eq!(cds.info(6603, 0, Some(&attack), mid).remaining_ms, 0); - assert!(!cds.not_ready(6603, 0, Some(&attack), mid)); + assert!(!cds.not_ready(6603, 0, 0, Some(&attack), mid)); } /// The wildcard leg (`0x6e1563`): wand Shoot's category 351 sweeps every button. @@ -1236,8 +1492,14 @@ mod tests { // Unrelated Fireball reads the wand swing and is not ready for its duration. let fb = cds.info(133, 0, Some(&fireball()), mid); assert_eq!((fb.remaining_ms, fb.duration_ms), (1000, 1500)); - assert!(cds.not_ready(133, 0, Some(&fireball()), mid)); - assert!(!cds.not_ready(133, 0, Some(&fireball()), t0 + Duration::from_millis(1_501))); + assert!(cds.not_ready(133, 0, 0, Some(&fireball()), mid)); + assert!(!cds.not_ready( + 133, + 0, + 0, + Some(&fireball()), + t0 + Duration::from_millis(1_501) + )); } #[test] @@ -1269,9 +1531,9 @@ mod tests { assert_eq!(info.duration_ms, 2200, "the sweep is the weapon speed"); assert_eq!(info.remaining_ms, 1200); assert!(info.enabled, "running, not parked"); - assert!(cds.not_ready(2764, 0, Some(&throw), mid)); + assert!(cds.not_ready(2764, 0, 0, Some(&throw), mid)); assert!( - !cds.not_ready(2764, 0, Some(&throw), t0 + Duration::from_millis(2300)), + !cds.not_ready(2764, 0, 0, Some(&throw), t0 + Duration::from_millis(2300)), "free again after the weapon speed elapses" ); } @@ -1290,7 +1552,7 @@ mod tests { "no sweep for a category-0 record" ); assert!( - !cds.not_ready(75, 0, Some(&auto_shot), mid), + !cds.not_ready(75, 0, 0, Some(&auto_shot), mid), "no local refusal either" ); } diff --git a/crates/benilla-app/src/spell/net.rs b/crates/benilla-app/src/spell/net.rs index af8fe670d..66e5abf66 100644 --- a/crates/benilla-app/src/spell/net.rs +++ b/crates/benilla-app/src/spell/net.rs @@ -1355,6 +1355,28 @@ mod tests { use super::*; use benilla_protocol::messages::ACTION_KIND_SPELL; + /// `SMSG_COOLDOWN_EVENT` (`0x6e9670`): the event moves the held record's one start, which the + /// GCD leg reads (`0x6e15d8`), so the global cooldown runs again from the packet. + #[test] + fn a_cooldown_event_packet_restarts_the_held_records_gcd() { + let form = benilla_formats::SpellDisplay { + start_recovery_category: 133, + start_recovery_ms: 1_500, + attributes: 0x0200_0000, + ..Default::default() + }; + let t0 = Instant::now(); + let mut cooldowns = Cooldowns::default(); + cooldowns.start_gcd(15473, &form, t0, &crate::spell::SpellModifiers::default()); + std::thread::sleep(Duration::from_millis(40)); + cooldown_event(15473, 10, &mut cooldowns); + + // 20 ms past the original GCD's end: only a restart from the packet is still running. + let info = cooldowns.info(15473, 0, Some(&form), t0 + Duration::from_millis(1_520)); + assert!(info.remaining_ms >= 10, "the GCD runs from the event"); + assert!(info.start > t0, "and reads the event's start"); + } + /// A catalog holding one row, so the announce tests can name a real `Attributes` value. fn catalog_with(id: u32, display: benilla_formats::SpellDisplay) -> Spells { let mut spells = Spells::empty_for_tests(); diff --git a/crates/benilla-app/src/spell/usable.rs b/crates/benilla-app/src/spell/usable.rs index 13537e6db..f537d2b8f 100644 --- a/crates/benilla-app/src/spell/usable.rs +++ b/crates/benilla-app/src/spell/usable.rs @@ -2,14 +2,13 @@ //! `IsUsableAction`'s grey tint. Any tripped gate answers `(usable, oom) = (false, false)`; only //! the power leg, the last, sets `notEnoughMana`. //! -//! Built: the TRADE_SKILL early-out, dead (leg 1), reagents and totems (3), the equipped item (4), -//! combo points (5), shapeshift form (6), only-stealthed (7), not-in-combat (8), CasterAuraState -//! (9), TargetAuraState and its CanAttack/CanAssist fork (10/10b, the only legs that read the -//! current target), the bit-25 cooldown fold (11) and power (12). +//! Built: the TRADE_SKILL early-out, dead (leg 1), lost control (2), reagents and totems (3), the +//! equipped item (4), combo points (5), shapeshift form (6), only-stealthed (7), not-in-combat +//! (8), CasterAuraState (9), TargetAuraState and its CanAttack/CanAssist fork (10/10b, the only +//! legs that read the current target), the bit-25 cooldown fold (11) and power (12). //! -//! Not built, each answering usable: leg 2's caster aura-immunity helpers (`0x6e9f20/40/60`), leg -//! 4's `AttributesEx3` sub-conditions. CanAssist in leg 10b is a reaction-rank test (friendly or -//! better), not the reference's `0x6066f0`. +//! Not built, answering usable: leg 4's `AttributesEx3` sub-conditions. CanAssist in leg 10b is a +//! reaction-rank test (friendly or better), not the reference's `0x6066f0`. use benilla_protocol::messages::ItemUseSpell; @@ -44,6 +43,9 @@ pub(crate) struct UsableCtx<'a> { pub(crate) cooldowns: &'a Cooldowns, /// The talent spell-modifier tables leg 12's cost goes through. pub(crate) spell_mods: &'a SpellModifiers, + /// `[0xb4b3e4]` clear (`0x4958e0`): the player does not control the character. Leg 2 greys + /// every spell its immunity scans do not exempt. + pub(crate) control_lost: bool, /// Every carried entry's count for the frame ([`crate::ui_items::carried_counts`]). pub(crate) carried: &'a std::collections::HashMap, } @@ -303,7 +305,8 @@ fn equipped_slots_match( /// 3. the item's first on-use spell runs the whole plain-spell walk, [`spell_usable`] (`0x4e5a50` /// hands it back with type 0; `4e51b0`). This is where food greys in combat: its rows carry /// [`ATTR_NOT_IN_COMBAT`], leg 8. -/// 4. an item with no on-use spell, or no template yet, is usable (`4e5127`..`4e5135`). +/// 4. an item with no on-use spell, or no template yet, is usable (`4e5127`..`4e5135`) while the +/// player has control (`4e50f4`). /// /// An on-use spell with no catalog row reads grey with `notEnoughMana = 0` (`4e51aa`). pub(crate) fn item_usable( @@ -321,7 +324,8 @@ pub(crate) fn item_usable( } // Gate 4: no on-use spell, or no template yet. let Some(use_spell) = use_spell else { - return (true, false); + // The spell-less leg (`0x4e50f4`): lost control greys it before the item word is read. + return (!ctx.control_lost, false); }; let spell_id = use_spell.spell_id; let d = spells.and_then(|s| s.catalog.get(spell_id)); @@ -359,6 +363,13 @@ pub(crate) fn spell_usable( if ctx.store.0.is_dead_or_ghost() && d.attributes & ATTR_CASTABLE_WHILE_DEAD == 0 { return (false, false); } + // Leg 2 (`0x6e3dc3`-`0x6e3e4c`): without control, only a spell whose immunity covers the aura + // that took it (fear, confusion, charm) passes. + if ctx.control_lost + && !crate::ui_unit::control_gate::exempts_lost_control(&spells.catalog, d, &ctx.store.0) + { + return (false, false); + } // Leg 3 (`0x6e4000`): every reagent count carried, every totem tool present. let carried = |entry: u32| ctx.carried.get(&entry).copied().unwrap_or(0); for &(entry, count) in &d.reagents { @@ -740,6 +751,7 @@ mod tests { cooldowns, carried, spell_mods, + control_lost: false, } } @@ -1001,6 +1013,7 @@ mod tests { cooldowns: &cooldowns, carried: &carried, spell_mods: &SpellModifiers::default(), + control_lost: false, }; assert_eq!( spell_usable(5308, &execute, &spells, &ctx, &objects, &items, &commands), @@ -1008,4 +1021,96 @@ mod tests { ); } } + + /// The walk with the control flag set as given, against `spells`' catalog. + fn walk_lost( + d: &SpellDisplay, + store: &ObjectStore, + spells: &Spells, + control_lost: bool, + ) -> (bool, bool) { + let cooldowns = Cooldowns::default(); + let reputations = Reputations::default(); + let items = Items::default(); + let (tx, _rx) = crossbeam_channel::unbounded(); + let commands = NetCommands(tx); + let mut objs = crate::ui_items::TestObjects::new(); + let objects = objs.get(); + let carried = crate::ui_items::carried_counts(&store.0, &objects); + let spell_mods = SpellModifiers::default(); + let mut c = ctx(store, &cooldowns, &reputations, &carried, &spell_mods); + c.control_lost = control_lost; + spell_usable(1, d, spells, &c, &objects, &items, &commands) + } + + /// `UNIT_FIELD_FLAGS` (46) bit 23 and the first `UNIT_FIELD_AURA` slot (47). + const FLEEING: u32 = 0x0080_0000; + + /// Leg 2 (`0x6e3dc3`-`0x6e3e4c`): with `[0xb4b3e4]` clear every spell greys, but the one whose + /// immunity covers the fear that took control (Will of the Forsaken's shape) stays lit. + #[test] + fn lost_control_greys_every_spell_an_immunity_scan_does_not_exempt() { + const FEAR_AURA: u32 = 5782; + let mut fear = SpellDisplay { + mechanic: 5, + ..Default::default() + }; + fear.effects[0] = 6; + fear.effect_apply_aura[0] = 7; + let mut immunity = SpellDisplay { + attributes_ex: 0x8000, + ..Default::default() + }; + immunity.effects[0] = 6; + immunity.effect_apply_aura[0] = 77; + immunity.effect_misc_value[0] = 5; + let mut spells = Spells::empty_for_tests(); + spells.catalog = benilla_formats::SpellCatalog::from_displays([(FEAR_AURA, fear)].into()); + let plain = SpellDisplay::default(); + + let feared = player(&[(46, (1 << 3) | FLEEING), (47, FEAR_AURA)]); + assert_eq!(walk_lost(&plain, &feared, &spells, false), (true, false)); + assert_eq!( + walk_lost(&plain, &feared, &spells, true), + (false, false), + "a plain spell greys while control is lost" + ); + assert_eq!( + walk_lost(&immunity, &feared, &spells, true), + (true, false), + "the fear immunity passes the scan" + ); + // The same spell without the fear flag asks no scan: control lost for another reason. + let rooted = player(&[(47, FEAR_AURA)]); + assert_eq!(walk_lost(&immunity, &rooted, &spells, true), (false, false)); + // A charm reads `UNIT_FIELD_CHARMEDBY` (10) with no aura of its type on the caster: no + // aura found, no exemption. + let charmed = player(&[(10, 0x77)]); + assert_eq!( + walk_lost(&immunity, &charmed, &spells, true), + (false, false) + ); + } + + /// The spell-less leg (`0x4e50f4`) of the item arm: an item with no on-use spell greys while + /// control is lost. + #[test] + fn an_item_with_no_on_use_spell_greys_without_control() { + let cooldowns = Cooldowns::default(); + let reputations = Reputations::default(); + let items = Items::default(); + let (tx, _rx) = crossbeam_channel::unbounded(); + let commands = NetCommands(tx); + let mut objs = crate::ui_items::TestObjects::new(); + let objects = objs.get(); + let store = player(&[]); + let carried = std::collections::HashMap::new(); + let spell_mods = SpellModifiers::default(); + let mut c = ctx(&store, &cooldowns, &reputations, &carried, &spell_mods); + let usable = + |c: &UsableCtx| item_usable(6948, None, true, c, None, &objects, &items, &commands); + assert_eq!(usable(&c), (true, false)); + c.control_lost = true; + assert_eq!(usable(&c), (false, false)); + } } diff --git a/crates/benilla-app/src/tutorial.rs b/crates/benilla-app/src/tutorial.rs index bbf1eb0a6..d981f1395 100644 --- a/crates/benilla-app/src/tutorial.rs +++ b/crates/benilla-app/src/tutorial.rs @@ -557,7 +557,10 @@ impl Plugin for TutorialPlugin { on_world_enter.before(run_world_enter_cascade), run_world_enter_cascade.before(feed_tutorials), watch_windows.before(feed_tutorials), - watch_self.after(on_world_enter).before(feed_tutorials), + watch_self + .after(on_world_enter) + .after(crate::player::ControlRestore) + .before(feed_tutorials), // Not before the in-game UI exists: `fired` is taken once, with no `VmMemo` // behind it, so the login's Welcome and Questgivers fired into the boot VM // during the one frame it is still live in the world would be lost. `fired` diff --git a/crates/benilla-app/src/ui_action/mod.rs b/crates/benilla-app/src/ui_action/mod.rs index e46296f18..f35158754 100644 --- a/crates/benilla-app/src/ui_action/mod.rs +++ b/crates/benilla-app/src/ui_action/mod.rs @@ -273,6 +273,7 @@ impl Plugin for UiActionPlugin { state::feed_action_state .in_set(UnitFeed) .in_set(CooldownEvents) + .after(crate::player::ControlRestore) .after(feed::feed_actions), drain::drain_action_sets.after(UiInput), // The target chain queues the openers earlier in the frame. diff --git a/crates/benilla-app/src/ui_action/state.rs b/crates/benilla-app/src/ui_action/state.rs index 9ede17f40..2ef1f2835 100644 --- a/crates/benilla-app/src/ui_action/state.rs +++ b/crates/benilla-app/src/ui_action/state.rs @@ -77,8 +77,8 @@ pub(super) fn feed_action_state( mut cooldowns: ResMut, clock: Res, auto_repeat: Res, - // One tuple for Bevy's 16-param ceiling: cast tracking, macro bindings, spell mods and the - // range units. + // One tuple for Bevy's 16-param ceiling: cast tracking, macro bindings, spell mods, the + // range units and the control flag. cast_state: ( Res, Res, @@ -88,6 +88,8 @@ pub(super) fn feed_action_state( Res, // The caster's and the target's reach and motion, which the range compare reads. crate::spell::RangeUnits, + // `[0xb4b3e4]`, which the usable walk reads. + Option>, ), self_q: Query<(&ObjectStore, &Transform, Has, Option<&Casting>), With>, selection: Res, @@ -120,8 +122,10 @@ pub(super) fn feed_action_state( memory.last_cd_trace = Some(now); } - let (pending, queued_melee, channel, targeting, bound, spell_mods, range_units) = &cast_state; + let (pending, queued_melee, channel, targeting, bound, spell_mods, range_units, player) = + &cast_state; let me = self_q.iter().next(); + let control_lost = player.as_ref().is_some_and(|p| p.own_control_lost); // The bags, walked once per frame for every reagent, totem and item count below. let carried = me .map(|(s, _, _, _)| carried_counts(&s.0, &objects)) @@ -153,10 +157,9 @@ pub(super) fn feed_action_state( let (kind, id) = match resolve_through_macro(button.kind, button.action, bound) { SlotResolve::Action(kind, id) => (kind, id), SlotResolve::BareMacro => { - // `0x4e5050`'s spell-less leg: usable. It also greys every spell-less macro and - // item while the player-control flag `[0xb4b3e4]` is clear (taxi, fear, charm, - // `0x4958e0`; set at boot, `0x48f626`); that gate is not built. - st.usable = true; + // `0x4e5050`'s spell-less leg: usable while the player-control flag `[0xb4b3e4]` + // is set (`0x4e50f4`; `SMSG_CLIENT_CONTROL_UPDATE` clears it, `0x4958e0`). + st.usable = !control_lost; fresh.insert(action, st); continue; } @@ -203,6 +206,7 @@ pub(super) fn feed_action_state( cooldowns: &cooldowns, carried: &carried, spell_mods, + control_lost, }; let (u, oom) = usable::spell_usable( button.action, @@ -283,6 +287,7 @@ pub(super) fn feed_action_state( cooldowns: &cooldowns, carried: &carried, spell_mods, + control_lost, }; let (u, oom) = usable::item_usable( button.action, @@ -299,7 +304,7 @@ pub(super) fn feed_action_state( } if let Some(u) = use_spell { let d = spells.as_ref().and_then(|s| s.catalog.get(u.spell_id)); - let info = cooldowns.info(u.spell_id, button.action, d, now); + let info = cooldowns.info_item(u.spell_id, button.action, u.category, d, now); st.cooldown = info.ui_triple(anchor, ui_now); } } @@ -847,4 +852,223 @@ mod tests { "in combat the food's on-use spell fails leg 8 and the button greys" ); } + + /// `SMSG_CLIENT_CONTROL_UPDATE` clears `[0xb4b3e4]` (`0x4958e0`), and `IsUsableAction` answers + /// nil for every spell button and spell-less macro but the spell whose immunity covers the fear + /// (`0x6e3dc3`-`0x6e3e4c`, `0x4e50f4`); control back, they all light. + #[test] + fn lost_control_greys_the_bar_but_the_immunity_spell() { + use benilla_protocol::messages::{ActionButton, ACTION_KIND_MACRO}; + use benilla_protocol::ObjectFields; + + const FIREBALL: u32 = 133; + const FEAR_AURA: u32 = 5782; + const WILL: u32 = 7744; + /// `UNIT_FIELD_FLAGS` bit 23, fleeing. + const FLEEING: u32 = 0x0080_0000; + + let mut fear = SpellDisplay { + mechanic: 5, + ..Default::default() + }; + fear.effects[0] = 6; + fear.effect_apply_aura[0] = 7; + let mut will = SpellDisplay { + attributes_ex: 0x8000, + ..Default::default() + }; + will.effects[0] = 6; + will.effect_apply_aura[0] = 77; + will.effect_misc_value[0] = 5; + + let (tx, _rx) = crossbeam_channel::unbounded(); + let mut app = App::new(); + let mut actions = PlayerActions::default(); + for (slot, action, kind) in [ + (0u8, FIREBALL, ACTION_KIND_SPELL), + (1, WILL, ACTION_KIND_SPELL), + (2, 1, ACTION_KIND_MACRO), + ] { + actions + .buttons + .insert(slot, ActionButton { slot, action, kind }); + } + let mut bound = crate::ui_macro::MacroBoundSpells::default(); + bound.0.insert(1, crate::ui_macro::BoundSpell::None); + app.insert_resource(actions) + .insert_resource(bound) + .insert_resource(Spells { + catalog: benilla_formats::SpellCatalog::from_displays( + [ + (FIREBALL, SpellDisplay::default()), + (WILL, will), + (FEAR_AURA, fear), + ] + .into_iter() + .collect(), + ), + ..Spells::empty_for_tests() + }) + .init_resource::() + .init_resource::() + .init_resource::() + .init_resource::() + .init_resource::() + .init_resource::() + .init_resource::() + .init_resource::() + .init_resource::() + .init_resource::() + .init_resource::() + .init_resource::() + .init_resource::() + .init_resource::() + .insert_resource(NetCommands(tx)); + app.world_mut().spawn(( + SelfPlayer, + Transform::default(), + ObjectStore(ObjectFields::from_pairs(&[ + (22, 100), + (23, 500), + (46, (1 << 3) | FLEEING), + (47, FEAR_AURA), + ])), + )); + let script = UiScript::new().unwrap(); + script + .run( + r#" + USABLE_EVENTS = 0 + local f = CreateFrame("Frame") + f:RegisterEvent("ACTIONBAR_UPDATE_USABLE") + f:SetScript("OnEvent", function() USABLE_EVENTS = USABLE_EVENTS + 1 end) + "#, + ) + .unwrap(); + app.insert_non_send_resource(script); + app.add_systems(Update, feed_action_state); + let events = |app: &mut App| -> i64 { + let mut s = app.world_mut().non_send_resource_mut::(); + s.resolve(); + s.eval::("local n = USABLE_EVENTS; USABLE_EVENTS = 0; return n") + .unwrap() + }; + + let lit = |app: &App| -> Vec { + let script = app.world().non_send_resource::(); + (1..=3) + .map(|n| { + script + .eval::(&format!("return (IsUsableAction({n})) and true or false")) + .unwrap() + }) + .collect() + }; + + app.update(); + assert_eq!( + lit(&app), + [true, true, true], + "in control, the whole bar is lit" + ); + events(&mut app); // the first push's own signal + + app.world_mut() + .resource_mut::() + .own_control_lost = true; + app.update(); + assert_eq!( + lit(&app), + [false, true, false], + "only the fear immunity stays lit" + ); + assert_eq!(events(&mut app), 1, "the cache change signals the bar once"); + + app.world_mut() + .resource_mut::() + .own_control_lost = false; + app.update(); + assert_eq!(lit(&app), [true, true, true], "control back, all lit again"); + assert_eq!(events(&mut app), 1); + } + + /// A held action (Stealth) reaches the VM as the held marker, and `GetActionCooldown` answers + /// the poll's own now (`0x6e1517`) with no feed change between polls. + #[test] + fn a_held_action_polls_answer_their_own_now() { + use benilla_protocol::messages::ActionButton; + use benilla_protocol::ObjectFields; + + const STEALTH: u32 = 1784; + let stealth = || SpellDisplay { + attributes: 0x0200_0000, + recovery_ms: 10_000, + ..Default::default() + }; + let (tx, _rx) = crossbeam_channel::unbounded(); + let mut app = App::new(); + let mut actions = PlayerActions::default(); + actions.buttons.insert( + 0, + ActionButton { + slot: 0, + action: STEALTH, + kind: ACTION_KIND_SPELL, + }, + ); + app.insert_resource(actions) + .insert_resource(crate::ui_macro::MacroBoundSpells::default()) + .insert_resource(Spells { + catalog: benilla_formats::SpellCatalog::from_displays( + [(STEALTH, stealth())].into_iter().collect(), + ), + ..Spells::empty_for_tests() + }) + .init_resource::() + .init_resource::() + .init_resource::() + .init_resource::() + .init_resource::() + .init_resource::() + .init_resource::() + .init_resource::() + .init_resource::() + .init_resource::() + .init_resource::() + .init_resource::() + .init_resource::() + .insert_resource(NetCommands(tx)); + app.world_mut().spawn(( + SelfPlayer, + Transform::default(), + ObjectStore(ObjectFields::from_pairs(&[(22, 100), (23, 500)])), + )); + app.world_mut().resource_mut::().start_spell( + STEALTH, + &stealth(), + 0, + Instant::now(), + None, + ); + app.insert_non_send_resource(UiScript::new().unwrap()); + app.add_systems(Update, feed_action_state); + + let read = |app: &App| { + let script = app.world().non_send_resource::(); + let (start, duration, enable) = script + .eval::<(f64, f64, i64)>("return GetActionCooldown(1)") + .unwrap(); + (start, duration, enable, script.now()) + }; + app.update(); + let first = read(&app); + assert_eq!((first.1, first.2), (0.001, 0), "(now, 0.001, 0)"); + assert_eq!(first.0, first.3); + app.world_mut() + .non_send_resource_mut::() + .tick(0.02); + let second = read(&app); + assert_eq!(second.0, second.3, "the poll answers its own now"); + assert!((second.0 - first.0 - 0.02).abs() < 1e-9, "20 ms apart"); + } } diff --git a/crates/benilla-app/src/ui_items/feed.rs b/crates/benilla-app/src/ui_items/feed.rs index 20f355256..259adcca5 100644 --- a/crates/benilla-app/src/ui_items/feed.rs +++ b/crates/benilla-app/src/ui_items/feed.rs @@ -775,7 +775,7 @@ fn resolve_slot( cooldown: t.use_spell.and_then(|u| { let sd = spells.and_then(|s| s.get(u.spell_id)); cooldowns - .info(u.spell_id, entry, sd, now) + .info_item(u.spell_id, entry, u.category, sd, now) .ui_triple(now, ui_now) }), }) diff --git a/crates/benilla-app/src/ui_shapeshift.rs b/crates/benilla-app/src/ui_shapeshift.rs index 79dcebe4d..a9e87becf 100644 --- a/crates/benilla-app/src/ui_shapeshift.rs +++ b/crates/benilla-app/src/ui_shapeshift.rs @@ -128,6 +128,7 @@ impl Plugin for UiShapeshiftPlugin { // cast is a script call (`cast_form`). feed_shapeshift_bar .in_set(UnitFeed) + .after(crate::player::ControlRestore) .before(crate::ui_action::CooldownEvents) .before(crate::ui_aura::AuraEvents), ); @@ -152,6 +153,7 @@ fn feed_shapeshift_bar( commands: Res, clock: Res, spell_mods: Res, + player: Option>, mut memory: Local>, ) { let Some(mut script) = script else { @@ -213,6 +215,7 @@ fn feed_shapeshift_bar( cooldowns: &cooldowns, carried: &carried, spell_mods: &spell_mods, + control_lost: player.as_ref().is_some_and(|p| p.own_control_lost), }; usable::spell_usable(id, d, &spells, &ctx, &objects, &items, &commands).0 }); @@ -401,4 +404,141 @@ mod tests { "out of the form: a live aura row is not what the MOD_SHAPESHIFT arm reads" ); } + + const FEAR_AURA: u32 = 5782; + const PLAIN_FORM: u32 = 5487; + const WARDED_FORM: u32 = 7744; + /// `UNIT_FIELD_FLAGS` bit 23, fleeing. + const FLEEING: u32 = 0x0080_0000; + + /// The bar feed over two forms and a feared player: the plain form and the form whose spell + /// carries the fear immunity (`AttributesEx` bit 15, aura 77 over mechanic 5). + fn bar_rig() -> App { + let mut fear = SpellDisplay { + mechanic: 5, + ..Default::default() + }; + fear.effects[0] = 6; + fear.effect_apply_aura[0] = 7; + let plain = SpellDisplay { + name: "Bear Form".into(), + shapeshift_form: Some(5), + ..Default::default() + }; + let mut warded = SpellDisplay { + name: "Warded".into(), + shapeshift_form: Some(6), + attributes_ex: 0x8000, + ..Default::default() + }; + warded.effects[0] = 6; + warded.effect_apply_aura[0] = 77; + warded.effect_misc_value[0] = 5; + let (tx, _rx) = crossbeam_channel::unbounded(); + let mut app = App::new(); + let mut actions = PlayerActions::default(); + actions.spells.extend([PLAIN_FORM, WARDED_FORM]); + app.insert_resource(actions) + .insert_resource(Spells { + catalog: benilla_formats::SpellCatalog::from_displays( + [ + (PLAIN_FORM, plain), + (WARDED_FORM, warded), + (FEAR_AURA, fear), + ] + .into_iter() + .collect(), + ), + ..Spells::empty_for_tests() + }) + .init_resource::() + .init_resource::() + .init_resource::() + .init_resource::() + .init_resource::() + .init_resource::() + .init_resource::() + .init_resource::() + .insert_resource(NetCommands(tx)); + app.world_mut().spawn(( + SelfPlayer, + ObjectStore(ObjectFields::from_pairs(&[ + (22, 100), + (23, 500), + (46, (1 << 3) | FLEEING), + (47, FEAR_AURA), + ])), + )); + app.insert_non_send_resource(UiScript::new().unwrap()); + app.add_systems(Update, feed_shapeshift_bar); + app + } + + fn castable(app: &App, index: u32) -> bool { + app.world() + .non_send_resource::() + .eval::(&format!( + "local _, _, _, c = GetShapeshiftFormInfo({index}) return c == 1" + )) + .unwrap() + } + + /// Leg 2 reaches the stance bar's `isCastable` (`0x4b45c0` runs `0x6e3d60`): lost control + /// greys the plain form, the fear-immune one stays castable, control back lights both. + #[test] + fn lost_control_greys_the_stance_bar_but_the_immunity_form() { + let mut app = bar_rig(); + app.update(); + assert!(castable(&app, 1) && castable(&app, 2), "in control"); + + app.world_mut() + .resource_mut::() + .own_control_lost = true; + app.update(); + assert!(!castable(&app, 1), "the plain form greys"); + assert!(castable(&app, 2), "the fear immunity passes the scan"); + + app.world_mut() + .resource_mut::() + .own_control_lost = false; + app.update(); + assert!(castable(&app, 1) && castable(&app, 2), "control back"); + } + + /// A held form (Shadowform in the bar) reaches the VM as the held marker, and + /// `GetShapeshiftFormCooldown` answers the poll's own now (`0x6e1517`). + #[test] + fn a_held_form_polls_answer_their_own_now() { + let mut app = bar_rig(); + let d = SpellDisplay { + shapeshift_form: Some(5), + attributes: 0x0200_0000, + ..Default::default() + }; + app.world_mut().resource_mut::().start_spell( + PLAIN_FORM, + &d, + 0, + Instant::now(), + None, + ); + let read = |app: &App| { + let script = app.world().non_send_resource::(); + let (start, duration, enable) = script + .eval::<(f64, f64, i64)>("return GetShapeshiftFormCooldown(1)") + .unwrap(); + (start, duration, enable, script.now()) + }; + app.update(); + let first = read(&app); + assert_eq!((first.1, first.2), (0.001, 0), "(now, 0.001, 0)"); + assert_eq!(first.0, first.3); + app.world_mut() + .non_send_resource_mut::() + .tick(0.02); + app.update(); + let second = read(&app); + assert_eq!(second.0, second.3, "the poll answers its own now"); + assert!((second.0 - first.0 - 0.02).abs() < 1e-9, "20 ms apart"); + } } diff --git a/crates/benilla-app/src/ui_spellbook.rs b/crates/benilla-app/src/ui_spellbook.rs index ad93d9301..ea9eac037 100644 --- a/crates/benilla-app/src/ui_spellbook.rs +++ b/crates/benilla-app/src/ui_spellbook.rs @@ -113,8 +113,9 @@ fn feed_spellbook( return; }; let (memory, vm_reset) = memory.get_reset(&script); - // The book depends on these inputs alone. `UiClock` is not one: `ui_triple` is frame-stable - // per arm, and expiry moves the store's `feed_epoch`. + // The book depends on these inputs alone. `UiClock` is not one: a running read's `ui_triple` + // is frame-stable per arm (a held read's start is the query's `anchor`, so it moves with + // `ui_now`, but nothing held moves an input), and expiry moves the store's `feed_epoch`. let objects_moved = inv.changes.moved(); let templates_moved = memory.items_templates.moved(items.template_epoch()); let cooldowns_moved = memory.cooldown_epoch.moved(cooldowns.feed_epoch()); @@ -234,7 +235,8 @@ fn feed_spellbook( } } // Each slot's cooldown (`GetCooldownInfo` `0x6e13e0`: id, category and GCD alike) on the - // `GetTime` clock, frame-stable per arm, so a running cooldown never churns the diff. + // `GetTime` clock, frame-stable per arm while it runs, so a running cooldown never churns the + // diff; a held read starts at `anchor`, so it differs per push. let (anchor, ui_now) = (clock.anchor, clock.ui_now); for slot in &mut fresh.slots { slot.cooldown = cooldowns diff --git a/crates/benilla-app/src/ui_trade/mod.rs b/crates/benilla-app/src/ui_trade/mod.rs index 132ff1f70..2813762d1 100644 --- a/crates/benilla-app/src/ui_trade/mod.rs +++ b/crates/benilla-app/src/ui_trade/mod.rs @@ -392,7 +392,9 @@ impl Plugin for UiTradePlugin { // latch's watchdog leashes the partner at 14 yd. feed_trade.after(crate::ui_unit::UnitFeed).in_set(UiFeed), // Ahead of the feed, so an accepted partner shows the frame the window opens. - answer_trade_request.before(feed_trade), + answer_trade_request + .after(crate::player::ControlRestore) + .before(feed_trade), // The coinage-change reflex's trade half, after the world's fields land. trim_offer_to_purse .after(crate::ui_unit::UnitFeed) diff --git a/crates/benilla-app/src/ui_unit.rs b/crates/benilla-app/src/ui_unit.rs index 6dd1c3581..6a8dea62e 100644 --- a/crates/benilla-app/src/ui_unit.rs +++ b/crates/benilla-app/src/ui_unit.rs @@ -21,7 +21,7 @@ use crate::net::{ use crate::target::{ring_reaction, Factions, Selection}; use crate::ui_script::{gate, SweepApp, UiInput}; -mod control_gate; +pub(crate) mod control_gate; mod held; /// The unit-feed pass, gated so none of its login one-shots or per-VM memos runs before the in-game @@ -137,7 +137,7 @@ impl Plugin for UiUnitPlugin { // After every snapshot above is pushed, so a handler reads the new reaction. fire_faction_on_forced_table.after(crate::ui_aura::AuraEvents), held::feed_name_candidates, - feed_player_control, + feed_player_control.after(crate::player::ControlRestore), // After the control edge, whose flag the exemption is asked for. control_gate::feed_control_bypass, feed_farsight_focus, diff --git a/crates/benilla-app/src/ui_unit/control_gate.rs b/crates/benilla-app/src/ui_unit/control_gate.rs index 42347739d..2a380015f 100644 --- a/crates/benilla-app/src/ui_unit/control_gate.rs +++ b/crates/benilla-app/src/ui_unit/control_gate.rs @@ -7,7 +7,7 @@ use std::collections::HashSet; use bevy::prelude::*; -use benilla_formats::{cc_exemption, SpellCatalog}; +use benilla_formats::{cc_exemption, SpellCatalog, SpellDisplay}; use benilla_protocol::ObjectFields; use benilla_ui::script::UiScript; @@ -22,30 +22,37 @@ const UNIT_FLAG_FLEEING: u32 = 0x0080_0000; /// (`0x6e9d7e`-`0x6e9d83`): without it no spell can pass, so only these are candidates. const ATTR_EX_BIT_15: u32 = 0x0000_8000; -/// The on-use spells that pass the gate now. Each helper of the reference asks its scanner -/// (`0x6e9ca0`) about the caster's aura slots: fleeing (flag bit 23) is `0x6e9f20`, aura type 7; -/// confused (bit 22) `0x6e9f40`, type 5; charmed (`UNIT_FIELD_CHARMEDBY` nonzero, whoever holds it) -/// `0x6e9f60`, types 6, 177 and 2. A spell passes if any applicable arm exempts it, the arms -/// ORed, and the scanner exempts when an aura of the type is on the caster and the spell's -/// immunity effects cover every such effect ([`benilla_formats::grants_immunity`]). +/// Whether `cast` passes the lost-control gate for `caster`, the three arms of the item +/// dispatcher (`0x5d8ef9`-`0x5d8f66`) and the usability predicate (`0x6e3dd0`-`0x6e3e4c`) alike. +/// Each helper of the reference asks its scanner (`0x6e9ca0`) about the caster's aura slots: +/// fleeing (flag bit 23) is `0x6e9f20`, aura type 7; confused (bit 22) `0x6e9f40`, type 5; charmed +/// (`UNIT_FIELD_CHARMEDBY` nonzero, whoever holds it) `0x6e9f60`, types 6, 177 and 2. A spell +/// passes if any applicable arm exempts it, the arms ORed, and the scanner exempts when an aura +/// of the type is on the caster and the spell's immunity effects cover every such effect +/// ([`benilla_formats::grants_immunity`]). +pub(crate) fn exempts_lost_control( + catalog: &SpellCatalog, + cast: &SpellDisplay, + caster: &ObjectFields, +) -> bool { + let flags = caster.unit_flags(); + let scan = + |ty: u32| cc_exemption(cast, caster.unit_aura_ids(), ty, |id| catalog.get(id)).exempt; + (flags & UNIT_FLAG_FLEEING != 0 && scan(7)) + || (flags & UNIT_FLAG_CONFUSED != 0 && scan(5)) + || (caster.unit_charmed_by().is_some() && [6, 177, 2].into_iter().any(scan)) +} + +/// The on-use spells that pass the gate now ([`exempts_lost_control`]). pub(crate) fn control_bypass_spells( catalog: &SpellCatalog, candidates: &[u32], caster: &ObjectFields, ) -> HashSet { - let flags = caster.unit_flags(); - let charmed = caster.unit_charmed_by().is_some(); candidates .iter() .filter_map(|&id| catalog.get(id).map(|cast| (id, cast))) - .filter(|(_, cast)| { - let scan = |ty: u32| { - cc_exemption(cast, caster.unit_aura_ids(), ty, |id| catalog.get(id)).exempt - }; - (flags & UNIT_FLAG_FLEEING != 0 && scan(7)) - || (flags & UNIT_FLAG_CONFUSED != 0 && scan(5)) - || (charmed && [6, 177, 2].into_iter().any(scan)) - }) + .filter(|(_, cast)| exempts_lost_control(catalog, cast, caster)) .map(|(id, _)| id) .collect() } @@ -93,7 +100,6 @@ pub(super) fn feed_control_bypass( #[cfg(test)] mod tests { use super::*; - use benilla_formats::SpellDisplay; const FEAR_AURA: u32 = 5782; const INSIGNIA: u32 = 7744; diff --git a/crates/benilla-ui/src/script/action.rs b/crates/benilla-ui/src/script/action.rs index 2d2a68cce..8c212ec50 100644 --- a/crates/benilla-ui/src/script/action.rs +++ b/crates/benilla-ui/src/script/action.rs @@ -408,9 +408,11 @@ pub(super) fn install(lua: &Lua) -> mlua::Result<()> { let model = lua.app_data_ref::().expect("model app_data"); Ok( match model.action_states.get(&action).and_then(|s| s.cooldown) { - Some((start, duration, enabled)) if start + duration > now || !enabled => { - (start, duration, i32::from(enabled)) - } + Some((start, duration, enabled)) if start + duration > now || !enabled => ( + crate::script::clock::held_start(start, enabled, now), + duration, + i32::from(enabled), + ), _ => (0.0, 0.0, 1), }, ) diff --git a/crates/benilla-ui/src/script/clock.rs b/crates/benilla-ui/src/script/clock.rs index 20e3176fe..0cd474ad8 100644 --- a/crates/benilla-ui/src/script/clock.rs +++ b/crates/benilla-ui/src/script/clock.rs @@ -30,6 +30,17 @@ impl super::UiScript { } } +/// The start a cooldown binding answers: a held one (`enabled` false) reports the call's own now, +/// as the reference's held legs write the query time (`0x6e1517`, `0x6e15a1`), so the pushed +/// triple carries no moving start. +pub(crate) fn held_start(start: f64, enabled: bool, now: f64) -> f64 { + if enabled { + start + } else { + now + } +} + /// `GetTime()`'s clock, for a caller holding no model borrow; one that holds it reads `model.now`. pub(crate) fn now(lua: &Lua) -> f64 { lua.app_data_ref::().expect("model app_data").now diff --git a/crates/benilla-ui/src/script/container.rs b/crates/benilla-ui/src/script/container.rs index 986856de4..20c649cef 100644 --- a/crates/benilla-ui/src/script/container.rs +++ b/crates/benilla-ui/src/script/container.rs @@ -757,9 +757,11 @@ pub(super) fn install(lua: &Lua) -> mlua::Result<()> { }); Ok(match key.and_then(|k| model.container_cooldowns.get(&k)) { _ if !held => (0.0, 0.0, 0), - Some(&(start, duration, enabled)) if start + duration > now || !enabled => { - (start, duration, i32::from(enabled)) - } + Some(&(start, duration, enabled)) if start + duration > now || !enabled => ( + crate::script::clock::held_start(start, enabled, now), + duration, + i32::from(enabled), + ), _ => (0.0, 0.0, 1), }) })?, @@ -2192,4 +2194,23 @@ mod tests { assert_eq!(s.cursor_payload(), Some(row), "no vendor: kept"); assert!(s.take_merchant_slot_buys().is_empty()); } + + /// A held bag item answers the call's own now, whatever was pushed (`0x6e1517`). + #[test] + fn a_held_container_item_answers_the_polls_now() { + let mut s = UiScript::new().unwrap(); + s.tick(100.0); + let mut state = backpack(); + state.slots.get_mut(&1).unwrap().cooldown = Some((0, 1, false)); + s.set_container(0, Some(state)); + let poll = |s: &UiScript| { + s.eval::<(f64, f64, i32)>("return GetContainerItemCooldown(0, 1)") + .unwrap() + }; + assert_eq!(poll(&s), (100.0, 0.001, 0)); + s.tick(0.02); + let (start, _, _) = poll(&s); + assert_eq!(start, s.eval::("return GetTime()").unwrap()); + assert!((start - 100.02).abs() < 1e-9); + } } diff --git a/crates/benilla-ui/src/script/pet.rs b/crates/benilla-ui/src/script/pet.rs index 95a5c944b..f69f801f5 100644 --- a/crates/benilla-ui/src/script/pet.rs +++ b/crates/benilla-ui/src/script/pet.rs @@ -416,9 +416,11 @@ pub(super) fn install(lua: &Lua) -> mlua::Result<()> { let now = crate::script::clock::now(lua); let model = lua.app_data_ref::().expect("model app_data"); Ok(match slot_at(&model, i).and_then(|s| s.cooldown) { - Some((start, duration, enabled)) if start + duration > now || !enabled => { - (start, duration, i32::from(enabled)) - } + Some((start, duration, enabled)) if start + duration > now || !enabled => ( + crate::script::clock::held_start(start, enabled, now), + duration, + i32::from(enabled), + ), _ => (0.0, 0.0, 1), }) })?, @@ -1357,4 +1359,23 @@ mod tests { assert!(s.eval::("return GetPetLoyalty() == nil").unwrap()); assert_eq!(s.arity("GetPetFoodTypes()").unwrap(), 0); } + + /// A held pet action answers the call's own now, whatever was pushed (`0x6e1517`). + #[test] + fn a_held_pet_action_answers_the_polls_now() { + let mut s = UiScript::new().unwrap(); + s.tick(10.0); + let mut v = slots(); + v[1].cooldown = Some((0, 1, false)); + s.set_pet_actions(true, true, true, v); + let poll = |s: &UiScript| { + s.eval::<(f64, f64, i32)>("return GetPetActionCooldown(2)") + .unwrap() + }; + assert_eq!(poll(&s), (10.0, 0.001, 0)); + s.tick(0.02); + let (start, _, _) = poll(&s); + assert_eq!(start, s.eval::("return GetTime()").unwrap()); + assert!((start - 10.02).abs() < 1e-9); + } } diff --git a/crates/benilla-ui/src/script/shapeshift.rs b/crates/benilla-ui/src/script/shapeshift.rs index e86eeb924..19b37e482 100644 --- a/crates/benilla-ui/src/script/shapeshift.rs +++ b/crates/benilla-ui/src/script/shapeshift.rs @@ -121,9 +121,11 @@ pub(super) fn install(lua: &Lua) -> mlua::Result<()> { let now = crate::script::clock::now(lua); let model = lua.app_data_ref::().expect("model app_data"); Ok(match form_at(&model, i).and_then(|f| f.cooldown) { - Some((start, duration, enabled)) if start + duration > now || !enabled => { - (start, duration, i32::from(enabled)) - } + Some((start, duration, enabled)) if start + duration > now || !enabled => ( + crate::script::clock::held_start(start, enabled, now), + duration, + i32::from(enabled), + ), _ => (0.0, 0.0, 1), }) })?, @@ -238,4 +240,23 @@ mod tests { assert_eq!(s.take_shapeshift_casts(), vec![71]); assert!(s.take_shapeshift_casts().is_empty(), "drain empties"); } + + /// A held form answers the call's own now, whatever was pushed (`0x6e1517`). + #[test] + fn a_held_form_answers_the_polls_now() { + let mut s = UiScript::new().unwrap(); + s.tick(10.0); + let mut f = forms(); + f[1].cooldown = Some((0, 1, false)); + s.set_shapeshift_forms(f); + let poll = |s: &UiScript| { + s.eval::<(f64, f64, i32)>("return GetShapeshiftFormCooldown(2)") + .unwrap() + }; + assert_eq!(poll(&s), (10.0, 0.001, 0)); + s.tick(0.02); + let (start, _, _) = poll(&s); + assert_eq!(start, s.eval::("return GetTime()").unwrap()); + assert!((start - 10.02).abs() < 1e-9); + } } diff --git a/crates/benilla-ui/src/script/spellbook.rs b/crates/benilla-ui/src/script/spellbook.rs index d2b026eee..96089c1c6 100644 --- a/crates/benilla-ui/src/script/spellbook.rs +++ b/crates/benilla-ui/src/script/spellbook.rs @@ -485,7 +485,11 @@ pub(super) fn install(lua: &Lua) -> mlua::Result<()> { let (start, duration) = (start_ms as f64 / 1000.0, f64::from(duration_ms) / 1000.0); if start + duration > now || !enabled { - (start, duration, i32::from(enabled)) + ( + crate::script::clock::held_start(start, enabled, now), + duration, + i32::from(enabled), + ) } else { (0.0, 0.0, 1) } @@ -822,11 +826,20 @@ mod tests { .unwrap(), (14.0, 10.0, 1) ); - // On hold survives the expiry guard. + // On hold survives the expiry guard, and its start is the call's now (`0x6e1517`). assert_eq!( s.eval::<(f64, f64, i64)>("return GetSpellCooldown(2, BOOKTYPE_SPELL)") .unwrap(), - (2.0, 8.0, 0) + (20.0, 8.0, 0) + ); + s.tick(0.02); + let (start, _, _) = s + .eval::<(f64, f64, i64)>("return GetSpellCooldown(2, BOOKTYPE_SPELL)") + .unwrap(); + assert_eq!(start, s.eval::("return GetTime()").unwrap()); + assert!( + (start - 20.02).abs() < 1e-9, + "a second poll reads its own now" ); // Elapsed goes cold. assert_eq!( diff --git a/crates/benilla-ui/src/script/tests/cooldown.rs b/crates/benilla-ui/src/script/tests/cooldown.rs index db669b042..ec4b9eafd 100644 --- a/crates/benilla-ui/src/script/tests/cooldown.rs +++ b/crates/benilla-ui/src/script/tests/cooldown.rs @@ -171,3 +171,28 @@ fn shapeshift_and_container_cooldowns_keep_their_anchors_too() { .eval::("local st = GetContainerItemCooldown(0, 1); return math.abs(st - 50) < 1e-3") .unwrap()); } + +/// A held action (enable 0) answers the call's own now (`0x6e1517`, `0x6e15a1`): two polls with +/// no feed change in between return starts as far apart as `GetTime()`. +#[test] +fn a_held_action_answers_the_polls_now() { + let mut s = script(); + s.tick(50.0); + s.set_action_state( + 3, + Some(ActionState { + cooldown: Some((0, 1, false)), + ..Default::default() + }), + ); + let poll = |s: &UiScript| { + s.eval::<(f64, f64, i32)>("return GetActionCooldown(3)") + .unwrap() + }; + let first = poll(&s); + assert_eq!(first, (50.0, 0.001, 0)); + s.tick(0.02); + let second = poll(&s); + assert_eq!(second.0, s.eval::("return GetTime()").unwrap()); + assert!((second.0 - first.0 - 0.02).abs() < 1e-9, "20 ms apart"); +}