From b52f2bf1100acfbd4ba5a6785c292d762c36ac57 Mon Sep 17 00:00:00 2001 From: Sam Sung <51686767+samwhosung@users.noreply.github.com> Date: Thu, 29 Oct 2026 12:29:30 +0700 Subject: [PATCH] The movement verbs and DropItemOnUnit apply in their calls (#2797) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The movement verbs and DropItemOnUnit queued their work for frame time, so a cast a movement press should cancel was still running on the script's next line. **Reference** - Every movement verb goes through `SetCommands` (`0x515090`). It sets the bit, and a new press in mask 0x10f0, or the press completing both mouse bits, cancels the cast inside the call (`0x51512a` → `0x6e4940`), then the channel, then runs the tick. - ToggleAutoRun reads the bit at the call (`0x513de7`). - DropItemOnUnit fills the trade or starts one in its call (`0x48da50`, `0x48da62`). **Changed** - With a host lent, the 23 movement verbs and Jump apply in the call. - The autorun bit flips there. - DropItemOnUnit applies in the call. - The mouselook verbs still queue. **Tests:** a press mid-cast cancels before the next line, two toggles in a frame cancel once, and a drop on a player trades in its call. Part of #2202. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 5.5 --- crates/benilla-app/src/bindings.rs | 152 ++++++++------- .../benilla-app/src/bindings/script_input.rs | 101 +++++++--- .../benilla-app/src/lanes/host_read_tests.rs | 4 +- crates/benilla-app/src/player.rs | 2 + crates/benilla-app/src/player/input.rs | 34 +++- crates/benilla-app/src/player/press.rs | 176 +++++++++++++++++- crates/benilla-app/src/script_calls.rs | 21 ++- .../src/script_calls/tests/cast_reports.rs | 56 ++++++ crates/benilla-app/src/spell/inflight.rs | 6 + crates/benilla-app/src/target/mod.rs | 4 +- crates/benilla-app/src/ui_action/drop_item.rs | 74 ++++---- .../src/ui_action/drop_item_tests.rs | 9 +- crates/benilla-app/src/ui_chat/away.rs | 7 +- .../src/ui_script/pet_frame_tests.rs | 6 +- crates/benilla-app/src/ui_trade/call_tests.rs | 52 ++++-- crates/benilla-ui/src/script/calls.rs | 8 + crates/benilla-ui/src/script/gossip.rs | 4 +- crates/benilla-ui/src/script/input_verbs.rs | 61 ++++-- crates/benilla-ui/src/script/model.rs | 3 - crates/benilla-ui/src/script/quest.rs | 5 +- .../src/script/tests/protected_gate.rs | 5 - crates/benilla-ui/src/script/unit/bindings.rs | 5 +- crates/benilla-ui/src/script/unit/mod.rs | 6 - docs/DEVIATIONS.md | 6 +- 24 files changed, 589 insertions(+), 218 deletions(-) diff --git a/crates/benilla-app/src/bindings.rs b/crates/benilla-app/src/bindings.rs index a4a0ebe7b..06317234b 100644 --- a/crates/benilla-app/src/bindings.rs +++ b/crates/benilla-app/src/bindings.rs @@ -75,16 +75,24 @@ impl BindingDispatch { } } -/// This frame's binding activity, which engine-side consumers read instead of raw keys: the -/// [`Input`]s the running bodies' Lua calls set. +/// The engine's input state the binding functions drive, the reference's `[InputControl+4]` and +/// the camera's axes, which engine-side consumers read instead of raw keys: the [`Input`]s the +/// bodies' Lua calls set, each inside its call ([`benilla_ui::script::ScriptCall::Input`]). #[derive(Resource, Default)] pub(crate) struct BindingsState { - /// Live latches, (base input, command): a press not yet released, whose release runs the - /// command's `runOnUp` half. The reference replays the press-time chord at key-up (`0x483bd0`); - /// latching the resolved command is equivalent. - latched: Vec<(Held, String)>, /// The held bits a Start set and no Stop has cleared. held: Vec, + /// This frame's edges, which the frame's readers take after the binding pass. + edges: Edges, + /// The edges of the calls made after this frame's readers ran, for the next frame's. + carry: Edges, + /// The binding pass runs ([`BindingHead`] to [`BindingTail`]), ahead of every reader. + open: bool, +} + +/// One frame's binding edges. +#[derive(Default)] +struct Edges { /// Inputs whose Start, or whose one-shot, came this frame (the press edge). just: Vec, /// One-shots fired this frame. @@ -93,6 +101,18 @@ pub(crate) struct BindingsState { amounts: Vec<(Input, f32)>, /// This frame's `MoveView*` calls in call order, `(axis, start)`, for the camera's axes. view_calls: Vec<(script_input::ViewAxis, bool)>, + /// The edges whose `SetCommands` work ran inside their call ([`BindingsState::call`]). + settled: Vec, +} + +/// The world frame's binding latches and the keys it believes are down: `CBindings`' state, not +/// the input control's. +#[derive(Resource, Default)] +pub(crate) struct BindingLatches { + /// Live latches, (base input, command): a press not yet released, whose release runs the + /// command's `runOnUp` half. The reference replays the press-time chord at key-up (`0x483bd0`); + /// latching the resolved command is equivalent. + latched: Vec<(Held, String)>, /// The keys we believe are down: a press of one is a repeat. The reference classifies /// auto-repeat off its own list (`0x4248b3`), never the Win32 `lParam` repeat bit. /// Normalized like [`latched`](Self::latched) and reconciled against `ButtonInput` every @@ -156,25 +176,36 @@ impl BindingsState { } /// Did this bit's Start, or this one-shot, come this frame (the key-down edge)? pub(crate) fn just_pressed(&self, i: Input) -> bool { - self.just.contains(&i) + self.edges.just.contains(&i) + } + /// Did this frame's edge of `i` come from a call that ran its `SetCommands` work inside it + /// ([`Self::call`])? + pub(crate) fn settled(&self, i: Input) -> bool { + self.edges.settled.contains(&i) } /// Did this one-shot fire this frame? pub(crate) fn fired(&self, i: Input) -> bool { - self.fired.contains(&i) + self.edges.fired.contains(&i) } /// Fire the one-shot `i` this frame, as a body's Lua call would. #[cfg(test)] pub(crate) fn fire_for_test(&mut self, i: Input) { - self.fired.push(i); + self.edges.fired.push(i); } /// End the frame's one-shots. #[cfg(test)] pub(crate) fn clear_for_test(&mut self) { - self.fired.clear(); + self.edges.fired.clear(); + } + /// The binding pass runs, so a call's edge is this frame's ([`Self::call`]). + #[cfg(test)] + pub(crate) fn open_for_test(&mut self) { + self.open = true; } /// Total amount for a one-shot this frame (0.0 when idle): the camera zoom's yards. pub(crate) fn amount(&self, i: Input) -> f32 { - self.amounts + self.edges + .amounts .iter() .filter(|&&(a, _)| a == i) .map(|&(_, v)| v) @@ -182,7 +213,7 @@ impl BindingsState { } /// This frame's `MoveView*` calls in call order, `(axis, start)`. pub(crate) fn view_calls(&self) -> &[(script_input::ViewAxis, bool)] { - &self.view_calls + &self.edges.view_calls } /// Both mouse bits held by their Lua Starts, the both-button run: MOVEANDSTEER's body /// (`Bindings.xml:3-11`) runs `CameraOrSelectOrMoveStart` and `TurnOrActionStart`. @@ -240,6 +271,7 @@ impl Plugin for BindingsPlugin { .configure_sets(Update, BindingHead.before(BindingTail)) .init_resource::() .init_resource::() + .init_resource::() .init_resource::() .add_systems( Update, @@ -556,18 +588,31 @@ impl WheelNotches { /// activity cleared, the bulk clears, Lua's binding calls since the last pass, and the /// pressed-key reconcile. fn begin_dispatch( - mut hosted_vm: crate::script_calls::HostedVm, + // The input state with the host, whose calls write it ([`BindingsState::call`]). + mut vm: crate::script_calls::VmWith>, keys: Res>, - mut state: ResMut, + mut latches: ResMut, mut same_vm: Local>, mut focus_lost: MessageReader, cover: Option>, ) { - state.just.clear(); - state.fired.clear(); - state.amounts.clear(); - state.view_calls.clear(); - hosted_vm.run(|script| begin_with(script, &mut state, &mut same_vm)); + let (script, set) = vm.parts(); + let mut state = set.p0(); + state.begin_pass(); + // Deviation: latches die with the VM that made them, because a latch names a command of that + // VM's table and releasing it against a new one would run another load's up-half. The + // reference keeps a held key running through `ReloadUI`; here it re-latches on its next press. + // The held bits die with it, as the key's Stop would have cleared them. + if let Some(script) = script { + if same_vm.claim(script) { + latches.latched.clear(); + state.held.clear(); + } + // Lua's binding calls made with no host lent since the last pass, before this frame's + // keys. + let inputs = script.take_binding_input(); + state.apply_script_input(inputs); + } // The reference's two bulk clears: the window deactivate (`0x514490`'s `and eax,0xfffff00f`, // the direction bits only, so the mouse pair and autorun survive) and the world enter behind // the loading cover (`0x5144c0`), which clears every bit. A key's latch meets them in the @@ -579,35 +624,10 @@ fn begin_dispatch( .held .retain(|&i| matches!(i, Input::TurnOrAction | Input::CameraOrSelectOrMove)); } - // Lua's binding calls made since the last pass, before this frame's keys. - hosted_vm.run(|script| { - if let Some(s) = script { - let inputs = s.take_binding_input(); - state.apply_script_input(inputs); - } - }); // ── The pressed-key reconcile ── against bevy's button planes, before this frame's records: a // release the window never saw drops off the list, and a window deactivate empties it, the // reference's `0x424790` wipe, so a key held across an alt-tab re-latches on its next repeat. - state.down.reconcile(&keys); -} - -/// [`begin_dispatch`]'s VM swap: the latches and held bits a new VM finds are dropped. -fn begin_with( - script: Option<&mut UiScript>, - state: &mut BindingsState, - same_vm: &mut crate::ui_script::VmMemo, -) { - // Deviation: latches die with the VM that made them, because a latch names a command of that - // VM's table and releasing it against a new one would run another load's up-half. The - // reference keeps a held key running through `ReloadUI`; here it re-latches on its next press. - // The held bits die with it, as the key's Stop would have cleared them. - if let Some(script) = script { - if same_vm.claim(script) { - state.latched.clear(); - state.held.clear(); - } - } + latches.down.reconcile(&keys); } /// How the interface's walk left one key record, which gates the world frame's binding. @@ -627,7 +647,7 @@ pub(crate) struct KeyVerdict { #[derive(bevy::ecs::system::SystemParam)] pub(crate) struct WorldFrameBindings<'w> { dispatch: Option>, - state: Option>, + state: Option>, } impl WorldFrameBindings<'_> { @@ -702,7 +722,7 @@ fn dev_plane(mods: Mods) -> bool { /// and `ButtonInput::release_all` reach the stuck-latch sweep. fn key_leg( dispatch: &BindingDispatch, - state: &mut BindingsState, + state: &mut BindingLatches, mut script: Option<&mut UiScript>, ev: &KeyboardInput, mods: Mods, @@ -811,7 +831,7 @@ const BIND_BUTTONS: [MouseButton; 5] = [ /// clicks), a release always. fn button_leg( dispatch: &BindingDispatch, - state: &mut BindingsState, + state: &mut BindingLatches, script: Option<&mut UiScript>, button: MouseButton, pressed: ButtonState, @@ -843,33 +863,36 @@ fn button_leg( /// The dispatch pass's tail, after the frame's records: the stuck-latch sweep, and the calls the /// pass's bodies made. fn end_dispatch( - mut hosted_vm: crate::script_calls::HostedVm, + // The input state with the host, whose calls write it ([`BindingsState::call`]). + mut vm: crate::script_calls::VmWith>, keys: Res>, buttons: Res>, - mut state: ResMut, + mut latches: ResMut, ) { - hosted_vm.run(|mut script| { + vm.run(|mut script| { // ── The stuck-latch sweep ── a release the window never saw: a latch whose base key reads // up unlatches now and runs its up-half. The reference's two bulk clears land here too, // since bevy zeroes `ButtonInput` for both (see `begin_dispatch`). UI keyboard focus never // reaches here. let mut stuck: Vec = Vec::new(); - for (k, _) in &state.latched { + for (k, _) in &latches.latched { if !physically_down(*k, &keys, &buttons) && !stuck.contains(k) { stuck.push(*k); } } for k in stuck { - release(&mut state, script.as_deref_mut(), k); + release(&mut latches, script.as_deref_mut(), k); } - - // The calls this pass's binding bodies made act this frame, as the reference's return from - // `0x515090` has already moved the bit. - if let Some(s) = script { - let inputs = s.take_binding_input(); - state.apply_script_input(inputs); - } - }) + }); + // The calls this pass's binding bodies made with no host lent act this frame, as the + // reference's return from `0x515090` has already moved the bit. + let (script, set) = vm.parts(); + let mut state = set.p0(); + if let Some(s) = script { + let inputs = s.take_binding_input(); + state.apply_script_input(inputs); + } + state.end_pass(); } /// The world frame's leg of each record alone, for a test of the bindings without the interface's @@ -946,7 +969,7 @@ fn physically_down( /// One matching press: the command's body with `keystate = "down"`, and a latch on its input so /// the release can run the up-half. -fn press(state: &mut BindingsState, script: Option<&mut UiScript>, command: &str, key: Held) { +fn press(state: &mut BindingLatches, script: Option<&mut UiScript>, command: &str, key: Held) { if let Some(s) = script { if let Err(e) = s.execute_binding(command, true) { warn!("bindings({command}): {e}"); @@ -957,7 +980,7 @@ fn press(state: &mut BindingsState, script: Option<&mut UiScript>, command: &str /// A base key's release: drop its latch and run the command's `runOnUp` up-half, even while /// typing (the reference completes a pressed binding's release regardless of focus). -fn release(state: &mut BindingsState, mut script: Option<&mut UiScript>, key: Held) { +fn release(state: &mut BindingLatches, mut script: Option<&mut UiScript>, key: Held) { let mut i = 0; while i < state.latched.len() { if state.latched[i].0 == key { @@ -1120,6 +1143,7 @@ mod tests { .init_resource::() .init_resource::() .init_resource::() + .init_resource::() .init_resource::() .init_resource::() .add_systems( @@ -1609,7 +1633,7 @@ mod tests { ); assert_eq!(lua_str(&app, "PROBE_LAST"), "up"); // Nothing is left latched: no key could end a wheel latch. - assert!(app.world().resource::().latched.is_empty()); + assert!(app.world().resource::().latched.is_empty()); } /// Auto-repeat is classified off our pressed-key set, as the reference's (`0x4248b3`), not the diff --git a/crates/benilla-app/src/bindings/script_input.rs b/crates/benilla-app/src/bindings/script_input.rs index 18852ee13..7d8e4fec2 100644 --- a/crates/benilla-app/src/bindings/script_input.rs +++ b/crates/benilla-app/src/bindings/script_input.rs @@ -77,36 +77,82 @@ fn fired_input(input: FiredInput) -> (Input, f32) { } impl BindingsState { - /// Apply Lua's binding calls, in call order. + /// The binding pass begins: last frame's edges are spent, and the calls made after its + /// readers ran are this frame's. + pub(super) fn begin_pass(&mut self) { + self.edges = std::mem::take(&mut self.carry); + self.open = true; + } + + /// The binding pass ends: the readers follow, so a call from here on is the next frame's. + pub(super) fn end_pass(&mut self) { + self.open = false; + } + + /// Apply Lua's binding calls that waited for no host, in call order. pub(super) fn apply_script_input(&mut self, inputs: Vec) { for input in inputs { - match input { - // The set helper `0x514840` early-outs on a bit already set, so a Start on a held - // bit is no new edge. - BindingInput::Start(held) => { - let i = held_input(held); - if !self.pressed(i) { - self.just.push(i); - self.held.push(i); - } + self.apply(input, false); + } + } + + /// One binding call inside its verb's call: the bit moves now, and its edge goes to this + /// frame's readers while the binding pass runs, else to the next frame's, whose head would + /// clear it unread. The edge is marked settled: the cast cancel and the autorun toggle its + /// `SetCommands` makes ran in the call. Whether the call is a new edge: a Start on a bit not + /// held, or a one-shot. + pub(crate) fn call(&mut self, input: BindingInput) -> bool { + self.apply(input, true) + } + + fn apply(&mut self, input: BindingInput, settled: bool) -> bool { + let edges = if settled && !self.open { + &mut self.carry + } else { + &mut self.edges + }; + match input { + // The set helper `0x514840` early-outs on a bit already set, so a Start on a held + // bit is no new edge. + BindingInput::Start(held) => { + let i = held_input(held); + if self.held.contains(&i) { + return false; } - // `0x514b70` clears the bit whoever set it, so a second key still down on the - // same command stops too, and its release is a no-op second Stop. - BindingInput::Stop(held) => { - let i = held_input(held); - self.held.retain(|&h| h != i); + self.held.push(i); + edges.just.push(i); + if settled { + edges.settled.push(i); } - // A one-shot is its own press edge. - BindingInput::Fire(fired) => { - let (i, amount) = fired_input(fired); - self.fired.push(i); - self.just.push(i); - self.amounts.push((i, amount)); + true + } + // `0x514b70` clears the bit whoever set it, so a second key still down on the + // same command stops too, and its release is a no-op second Stop. + BindingInput::Stop(held) => { + let i = held_input(held); + self.held.retain(|&h| h != i); + false + } + // A one-shot is its own press edge. + BindingInput::Fire(fired) => { + let (i, amount) = fired_input(fired); + edges.fired.push(i); + edges.just.push(i); + edges.amounts.push((i, amount)); + if settled { + edges.settled.push(i); } - // The camera's axes are its own state (`[cam+0x128]`), not `[InputControl+4]`: - // passed through in call order for the camera to apply. - BindingInput::ViewStart(axis) => self.view_calls.push((axis, true)), - BindingInput::ViewStop(axis) => self.view_calls.push((axis, false)), + true + } + // The camera's axes are its own state (`[cam+0x128]`), not `[InputControl+4]`: + // passed through in call order for the camera to apply. + BindingInput::ViewStart(axis) => { + edges.view_calls.push((axis, true)); + false + } + BindingInput::ViewStop(axis) => { + edges.view_calls.push((axis, false)); + false } } } @@ -117,10 +163,7 @@ impl BindingsState { pub(crate) fn after_calls(earlier: Vec, now: Vec) -> Self { let mut state = Self::default(); state.apply_script_input(earlier); - state.just.clear(); - state.fired.clear(); - state.amounts.clear(); - state.view_calls.clear(); + state.edges = Default::default(); state.apply_script_input(now); state } diff --git a/crates/benilla-app/src/lanes/host_read_tests.rs b/crates/benilla-app/src/lanes/host_read_tests.rs index de4af5470..c5763c94c 100644 --- a/crates/benilla-app/src/lanes/host_read_tests.rs +++ b/crates/benilla-app/src/lanes/host_read_tests.rs @@ -43,8 +43,8 @@ use crate::game_plugins::schedule_tests::{census, type_names_available, SyncPoin /// The most rows [`super::guard_tests::READS_FRAME_FINAL`] may hold, and the most inputs across /// them: each only falls, so lower it when a row or an input goes. -const FRAME_FINAL_FEEDS: usize = 15; -const FRAME_FINAL_INPUTS: usize = 98; +const FRAME_FINAL_FEEDS: usize = 14; +const FRAME_FINAL_INPUTS: usize = 95; /// The systems that may run after the dispatch (`apply_net_updates`) and run ahead of the drain /// (`fire_in_order`), by a suffix of the system's name, with what each writes of the state a diff --git a/crates/benilla-app/src/player.rs b/crates/benilla-app/src/player.rs index 63ff99f0f..527a74558 100644 --- a/crates/benilla-app/src/player.rs +++ b/crates/benilla-app/src/player.rs @@ -109,6 +109,7 @@ pub(crate) use approach::{ }; /// `SetStandState` run inside a script call. pub(crate) use posture::{stand_up_for_attack, stand_up_refused, StandSetter}; +pub(crate) use press::CommandSteps; use state::{ MoveSpeed, PlayerRide, AIR_NUDGE_SPEED, FALL_FAR_DROP, FALL_FAR_TIME, FOOT_CONE_HEIGHT, GROUND_COS, GROUND_PROBE, JUMP_SPEED, LAND_PROBE, RUN_BACK_RATIO, SKIN_WIDTH, @@ -331,6 +332,7 @@ impl Plugin for PlayerPlugin { app.init_resource::(); app.init_resource::(); app.init_resource::(); + app.init_resource::(); app.init_resource::(); // Far sight resolves `PLAYER_FARSIGHT` to a pose before `control` seats the camera: a // separate system, as `control` holds our `Transform` mutably and cannot read another's. diff --git a/crates/benilla-app/src/player/input.rs b/crates/benilla-app/src/player/input.rs index 3cdd35b14..e371b1d83 100644 --- a/crates/benilla-app/src/player/input.rs +++ b/crates/benilla-app/src/player/input.rs @@ -109,7 +109,17 @@ pub(super) struct MoveAxes { /// releases it when set (`0x514b70`), whatever drives the body. Whether this frame's press set it: /// the on edge, a press in the cancel mask. The window-deactivate handler (`0x514490`, called only /// from the WM_ACTIVATE slot at `0x493058`) releases every direction bit and keeps `0x1000`. -pub(super) fn toggle_autorun(binds: &crate::bindings::BindingsState, player: &mut Player) -> bool { +pub(super) fn toggle_autorun( + binds: &crate::bindings::BindingsState, + called: Option, + player: &mut Player, +) -> bool { + // The calls that moved the bit inside them ([`super::press::CommandSteps`]) decided their + // cancels there: the latch takes what they left. + if let Some(bit) = called { + player.autorun = bit; + return false; + } if !binds.fired(crate::bindings::Input::ToggleAutoRun) { return false; } @@ -142,10 +152,15 @@ pub(super) fn move_axes( // `control` clears the bit on that path, which never reaches here. // A jump, a chat EditBox taking focus and a zone change leave it set; mounting is untraced and // leaves it set here. A focused chat box releases nothing, so W held through ENTER still runs. - let both_buttons_engaged = both_engaged(binds, rig, both_buttons); + // A press made inside its call cleared the bit there, in its order with the toggles + // ([`super::press::CommandSteps`]). + use crate::bindings::Input; + let called = binds.settled(Input::TurnOrAction) || binds.settled(Input::CameraOrSelectOrMove); + let both_buttons_engaged = !called && both_engaged(binds, rig, both_buttons); + let pressed = |i| binds.just_pressed(i) && !binds.settled(i); if state::autorun_cancelled( - binds.just_pressed(crate::bindings::Input::MoveForward), - binds.just_pressed(crate::bindings::Input::MoveBackward), + pressed(Input::MoveForward), + pressed(Input::MoveBackward), both_buttons_engaged, !may_translate, ) { @@ -210,8 +225,9 @@ pub(super) fn both_engaged( (both_buttons && rig.world_mouse.rose()) || binds.steering_began() } -/// Whether this frame's input cancels the cast in flight, as the press handler `0x515090` and -/// `Script::Jump` (`0x513c43`) decide it: a press that newly set forward, back, strafe or autorun +/// Whether this frame's input cancels the cast in flight, for the edges no call settled inside it +/// ([`super::press::CommandSteps`]), as the press handler `0x515090` and `Script::Jump` +/// (`0x513c43`) decide it: a press that newly set forward, back, strafe or autorun /// (the mask `0x10f0` at `0x5150ce`; a Start on a held bit is no edge, `0x51484c`), the press that /// completed both mouse bits (`0x5150e2`), or the Jump command, which cancels ahead of its own /// checks once the active mover resolves (`0x513be0`-`0x513c02`), so not while control is lost @@ -234,10 +250,10 @@ pub(super) fn cancels_cast( Input::StrafeRight, ] .into_iter() - .any(|i| binds.just_pressed(i)) + .any(|i| binds.just_pressed(i) && !binds.settled(i)) || autorun_on || both_engaged - || has_mover && binds.fired(Input::Jump) + || has_mover && binds.fired(Input::Jump) && !binds.settled(Input::Jump) } #[cfg(test)] @@ -259,7 +275,7 @@ mod tests { ) -> bool { let binds = BindingsState::after_calls(earlier, now); let rig = CameraControl::default(); - let autorun_on = toggle_autorun(&binds, player); + let autorun_on = toggle_autorun(&binds, None, player); let both = both_engaged(&binds, &rig, binds.steering()); move_axes(&binds, player, &rig, binds.steering(), !rooted, true); cancels_cast(&binds, autorun_on, both, true) diff --git a/crates/benilla-app/src/player/press.rs b/crates/benilla-app/src/player/press.rs index 67eec920c..a1e17bb4d 100644 --- a/crates/benilla-app/src/player/press.rs +++ b/crates/benilla-app/src/player/press.rs @@ -3,16 +3,27 @@ //! or clears the bit (`0x514840`, `0x514b70`), cancels the cast for a new direction bit //! (`0x5150ce`-`0x515175`, sending `CMSG_CANCEL_CAST` at once through `0x6e4940`) and ends by //! running the movement tick inside the record (`0x5151a0` → `0x514640`). The tick reads root and -//! stun as they stand then (`0x514560`, `0x5145b0`), so its start or stop is queued, and goes out -//! on the wire, ahead of anything this frame's packets apply. +//! stun as they stand then (`0x514560`, `0x5145b0`). +//! +//! A binding call's bit change, its autorun bit and its cast cancel run inside the call +//! ([`CommandSteps`]), so `MoveForwardStart()` mid-cast has sent `CMSG_CANCEL_CAST` and fired its +//! stop before the script's next line. The tick follows the input records here, and its start or +//! stop is sent there, before the frame's packets +//! ([`benilla_world::schedule::WorldStage::Net`]). The reference's tick only queues it on the mover +//! (`0x617840` → `0x617570`, no send), and the frame's mover update sends it (`0x615b10` → +//! `0x616620` → `0x615c30`) in the frame time, which runs after the frame's packets (`0x420d55`, +//! then `0x420d63`; #2795). //! //! Two systems, around the cast bar's self-cancel (`crate::spell::LocalCancel`), which sends the -//! cancel between them: [`press_commands`], the bit change and the cancel's verdict, then -//! [`press_tick`], the tick. [`super::controller::control`] keeps the frame time: it runs the same -//! axes and flag build after the packets and finds the word this changed already streamed. +//! cancel between them: [`press_commands`], the cancel's verdict for the edges no call settled +//! (a call made with no host lent, a world mouse press), then [`press_tick`], the tick. +//! [`super::controller::control`] keeps the frame time: it runs the same axes and flag build after +//! the packets and finds the word this changed already streamed. use bevy::prelude::*; +use benilla_ui::script::{BindingInput, FiredInput, HeldInput}; + use crate::creature_anim::move_flags; use crate::net::{Embodied, NetCommands}; @@ -27,6 +38,7 @@ use super::{CameraControl, Player, SelfPosture}; #[allow(clippy::type_complexity)] pub(super) fn press_commands( binds: Res, + mut called: ResMut, rig: Res, mut player: ResMut, lock: Res, @@ -49,11 +61,14 @@ pub(super) fn press_commands( // possession sets to the creature and lost control zeroes (`0x5fa600`), so steering a // possessed creature, or pressing while feared, ends a cast but not a channel. let active_mover = active.iter().next(); - let autorun_on = input::toggle_autorun(&binds, &mut player); + let autorun_on = input::toggle_autorun(&binds, called.0.take(), &mut player); + // A mouse command's call decided the both-button cancel inside it ([`CommandSteps`]). + let called = binds.settled(crate::bindings::Input::TurnOrAction) + || binds.settled(crate::bindings::Input::CameraOrSelectOrMove); if input::cancels_cast( &binds, autorun_on, - input::both_engaged(&binds, &rig, both_buttons), + !called && input::both_engaged(&binds, &rig, both_buttons), active_mover.is_some(), ) { cancel.pressed = true; @@ -160,3 +175,150 @@ pub(super) fn press_tick( loot.0 = true; } } + +/// The autorun bit `0x1000` as this frame's calls left it, read and written inside each +/// (`0x513de7`, `0x514a5a`, `0x514a73`), which the frame's latch takes at the command press +/// ([`input::toggle_autorun`]); `None` when no call touched it. +#[derive(Resource, Default)] +pub(crate) struct CallAutorun(Option); + +/// A binding call inside its verb's call ([`benilla_ui::script::ScriptCall::Input`]): the bit +/// set or cleared through `SetCommands` (`0x515090` → `0x514840`, `0x514b70`), and for a press +/// that changed a bit the cast cancel's verdict (`0x5150ce`-`0x515193`), before the call returns. +/// `ToggleAutoRun` (`0x513de0`) presses or releases `0x1000` by its current state, and `Jump` +/// cancels once the active mover resolves (`0x513be0`-`0x513c43`). A one-shot and the camera axes +/// leave their edge for the frame's readers. +#[derive(bevy::ecs::system::SystemParam)] +pub(crate) struct CommandSteps<'w, 's> { + binds: ResMut<'w, crate::bindings::BindingsState>, + autorun: Option>, + player: Option>, + // The active mover `0xc4da98`, as whether it is our own character. + active: Query<'w, 's, Has, With>, +} + +impl CommandSteps<'_, '_> { + /// Apply `input`; when it cancels the cast, whether the player is the active mover, the one + /// extra test of the channel's cancel (`0x51517b`-`0x515191`). + pub(crate) fn call(&mut self, input: BindingInput) -> Option { + let changed = self.binds.call(input); + let player = self.player.as_deref()?; + if !player.active || player.detached || !changed { + return None; + } + let mover = self.active.iter().next(); + // `0x1000` as the frame's calls left it, the latch's until one touches it; with no store + // for it (a harness), a call's write is dropped. + let mut scratch = player.autorun; + let autorun = match self.autorun.as_deref_mut() { + Some(CallAutorun(bit)) => bit.get_or_insert(player.autorun), + None => &mut scratch, + }; + let cancels = match input { + // The mask `0x10f0` (`0x5150ce`): forward, back and the strafes; the turns and the + // pitches (`0x100`-`0x800`) never cancel. A forward or back press clears `0x1000` + // inside it (`test cl,0x30` at `0x514a5a`). + BindingInput::Start(HeldInput::MoveForward | HeldInput::MoveBackward) => { + *autorun = false; + true + } + BindingInput::Start(HeldInput::StrafeLeft | HeldInput::StrafeRight) => true, + // The press that completed both mouse bits (`0x5150d6`-`0x5150ec`), which clears + // `0x1000` too (`0x514a73`). + BindingInput::Start(HeldInput::TurnOrAction | HeldInput::CameraOrSelectOrMove) => { + let both = self.binds.steering(); + if both { + *autorun = false; + } + both + } + // `0x1000` read inside the call (`0x513de7`): pressed when clear, which cancels, and + // released when set, which does not. The frame's latch takes the bit the calls left + // ([`input::toggle_autorun`]). + BindingInput::Fire(FiredInput::ToggleAutoRun) => { + *autorun = !*autorun; + *autorun + } + BindingInput::Fire(FiredInput::Jump) => mover.is_some(), + _ => false, + }; + cancels.then_some(mover == Some(true)) + } +} + +#[cfg(test)] +mod tests { + use bevy::ecs::system::RunSystemOnce; + + use super::*; + use crate::bindings::BindingsState; + use BindingInput::{Fire, Start}; + + /// A world with the input state and our player in control, autorun on or off. + fn world(autorun: bool) -> World { + let mut world = World::new(); + world.init_resource::(); + world.init_resource::(); + world.init_resource::(); + let mut player = world.resource_mut::(); + player.active = true; + player.autorun = autorun; + world + } + + /// Each call inside its verb's call: whether it cancels the cast. + fn calls(world: &mut World, inputs: Vec) -> Vec { + world + .run_system_once(move |mut steps: CommandSteps| { + inputs + .iter() + .map(|&i| steps.call(i).is_some()) + .collect::>() + }) + .unwrap() + } + + /// The frame's latch after the calls: the command press, then the tick's axes. + fn latched(world: &mut World) -> bool { + let called = world.resource_mut::().0.take(); + world.resource_scope(|world, binds: Mut| { + let mut player = world.resource_mut::(); + input::toggle_autorun(&binds, called, &mut player); + input::move_axes( + &binds, + &mut player, + &CameraControl::default(), + false, + true, + true, + ); + player.autorun + }) + } + + /// `ToggleAutoRun` reads `0x1000` inside its call (`0x513de7`): the first of two in one frame + /// presses it, which cancels, and the second finds it set and releases it, which does not. + #[test] + fn a_second_autorun_toggle_in_a_frame_is_a_release() { + let mut w = world(false); + let toggle = Fire(FiredInput::ToggleAutoRun); + assert_eq!(calls(&mut w, vec![toggle, toggle]), [true, false]); + assert!(!latched(&mut w), "pressed then released"); + } + + /// W clears `0x1000` inside its press (`0x514a5a`), so a toggle after it in the same frame + /// finds the bit clear and presses it, cancelling, and autorun stays on. + #[test] + fn a_toggle_after_forward_presses_autorun_and_cancels() { + let mut w = world(true); + let calls = calls( + &mut w, + vec![ + Start(HeldInput::MoveForward), + Fire(FiredInput::ToggleAutoRun), + ], + ); + assert_eq!(calls, [true, true]); + assert!(latched(&mut w), "the toggle came after the clear"); + } +} diff --git a/crates/benilla-app/src/script_calls.rs b/crates/benilla-app/src/script_calls.rs index da6047263..d30a16c74 100644 --- a/crates/benilla-app/src/script_calls.rs +++ b/crates/benilla-app/src/script_calls.rs @@ -154,6 +154,9 @@ disjoint::disjoint_set! { live: live::LiveReads<'static, 'static>, /// The world click's arm, its pick and its legs. click: crate::target::ClickLegs<'static, 'static>, + /// The binding functions' input state, and `DropItemOnUnit`'s legs. + commands: crate::player::CommandSteps<'static, 'static>, + drop_item: crate::ui_action::drop_item::DropItemLeg<'static, 'static>, } } @@ -943,6 +946,14 @@ impl CallHost for ScriptCallHost<'_, '_> { } ScriptCall::RecordAsk(ask) => appliers.asks().apply(ask), ScriptCall::WorldClick(step) => self.world_click(script, &mut at, step), + // `SetCommands` (`0x515090`): the bit, then the cast cancel (`0x51512a` → `0x6e4940`, + // `0x515193` → `0x6e9b70`), whose stop the call's reports signal as it returns. + ScriptCall::Input(input) => { + if let Some(mover_is_player) = appliers.commands().call(input) { + appliers.self_cancel().cancel_for_move(mover_is_player); + } + } + ScriptCall::DropItemOnUnit(token) => appliers.drop_item().drop_on(script, &token), } // A profession opener the call cast toggles its window inside the cast (`0x6e4c22`, // `0x6e4c34`), whose signals' listeners run before the call goes on. @@ -2919,12 +2930,12 @@ mod tests { vec!["ERR_NO_ATTACK_TARGET"], "pressed: {pressed}" ); - let inputs = f + let held = f .app - .world_mut() - .non_send_resource_mut::() - .take_binding_input(); - assert_eq!(!inputs.is_empty(), moved, "pressed: {pressed}"); + .world() + .resource::() + .pressed(crate::bindings::Input::MoveForward); + assert_eq!(held, moved, "pressed: {pressed}"); } } diff --git a/crates/benilla-app/src/script_calls/tests/cast_reports.rs b/crates/benilla-app/src/script_calls/tests/cast_reports.rs index 8f1e31acd..04629a509 100644 --- a/crates/benilla-app/src/script_calls/tests/cast_reports.rs +++ b/crates/benilla-app/src/script_calls/tests/cast_reports.rs @@ -457,3 +457,59 @@ fn only_the_bars_press_toggles_a_running_repeat_off() { .any(|c| matches!(c, ClientCommand::CancelAutoRepeat))); assert_eq!(key(&f), None, "the bar's press stops it"); } + +/// `MoveForwardStart()` mid-cast is `SetCommands` (`0x515090`) inside the call: the bit set +/// (`0x5150a7` → `0x514840`), then for a press of the mask `0x10f0` the cancel of a cast whose +/// `InterruptFlags` has bit 0 (`0x51511e` → `0x51512a` → `0x6e4940`), its `CMSG_CANCEL_CAST` sent +/// and its stop signalled before the verb returns. So the script's next line reads the stop and the +/// held bit, and its send follows the cancel on the wire. The turn keys cancel nothing (`0x5150ce`). +#[test] +fn move_forward_start_mid_cast_cancels_inside_the_call() { + let mut f = frame(false); + with_book_spell( + &mut f, + HEAL, + "Heal", + benilla_formats::SpellDisplay { + interrupt_flags: 0xf, + ..Default::default() + }, + ); + let world = f.app.world_mut(); + world.init_resource::(); + world.resource_mut::().active = true; + world + .resource_mut::() + .open_for_test(); + run(&mut f, r#"CastSpellByName("Heal")"#); + assert_eq!(casts_and_cancels(&f), vec![("cast", HEAL)]); + let _ = reports(&mut f); + + run_pressed(&mut f, &format!("TurnLeftStart() {SNAPSHOT}")); + assert_eq!(seen(&mut f), "", "a turn spares the cast"); + run_pressed( + &mut f, + &format!(r#"MoveForwardStart() {SNAPSHOT} SendChatMessage("hi", "SAY")"#), + ); + assert_eq!( + seen(&mut f), + "SPELLCAST_STOP", + "the next line reads the stop" + ); + let world = f.app.world(); + let binds = world.resource::(); + assert!( + binds.pressed(crate::bindings::Input::MoveForward) + && binds.just_pressed(crate::bindings::Input::MoveForward), + "the bit is held as the call returns" + ); + let sent: Vec<_> = + f.rx.try_iter() + .filter_map(|c| match c { + ClientCommand::CancelCast { spell_id } => Some(format!("cancel {spell_id}")), + ClientCommand::Chat { .. } => Some("chat".to_string()), + _ => None, + }) + .collect(); + assert_eq!(sent, [format!("cancel {HEAL}"), "chat".to_string()]); +} diff --git a/crates/benilla-app/src/spell/inflight.rs b/crates/benilla-app/src/spell/inflight.rs index bd2283d1d..71135de4b 100644 --- a/crates/benilla-app/src/spell/inflight.rs +++ b/crates/benilla-app/src/spell/inflight.rs @@ -453,6 +453,12 @@ impl SelfCancel<'_> { self.cancel(true, false, false); } + /// A movement command's cancel inside its call (`0x51512a`, `0x515193`, `Script::Jump`'s + /// `0x513c43`); `mover_is_player` gates the channel's. + pub(crate) fn cancel_for_move(&mut self, mover_is_player: bool) { + self.cancel(false, true, mover_is_player); + } + /// `CancelCast(1, 1, 0x1c)` (`0x6e4940`) as `UseSoulstone`'s item leg calls it (`0x48ae6b`), /// ungated: a targeting word is dropped (`0x6e4955`), else the cast or queued strike in flight /// is cancelled on the wire (`0x6e4970`), whatever its `InterruptFlags`. Its failed flag fires diff --git a/crates/benilla-app/src/target/mod.rs b/crates/benilla-app/src/target/mod.rs index e694b94ff..6da379bc2 100644 --- a/crates/benilla-app/src/target/mod.rs +++ b/crates/benilla-app/src/target/mod.rs @@ -355,12 +355,10 @@ impl Plugin for TargetPlugin { .chain(), // The units the plate selects parked with the targeting cursor up, bound to its // cast; then the unit interact of a nameplate's right-click and a crate's - // `Interact`, so the cast goes out ahead of the interact it came with; then - // `DropItemOnUnit`'s legs. + // `Interact`, so the cast goes out ahead of the interact it came with. ( crate::script_calls::bind_parked_picks, click::act_on_interact, - crate::ui_action::drop_item::drop_item_on_unit, ) .chain(), // The casts the dispatchers queued (`0x5f35c0`, `0x5f06dc` → `0x6e5a90`). diff --git a/crates/benilla-app/src/ui_action/drop_item.rs b/crates/benilla-app/src/ui_action/drop_item.rs index 0f953f8af..a9aed6edd 100644 --- a/crates/benilla-app/src/ui_action/drop_item.rs +++ b/crates/benilla-app/src/ui_action/drop_item.rs @@ -24,52 +24,54 @@ fn feedable_pet(pet: &benilla_protocol::ObjectFields, self_guid: u64) -> bool { && pet.unit_created_by() == Some(self_guid) } -/// Runs `DropItemOnUnit(unit)`'s legs (`0x48d960`): the trade leg, then the pet leg on a token +/// `DropItemOnUnit(unit)`'s legs (`0x48d960`) inside its call +/// ([`benilla_ui::script::ScriptCall::DropItemOnUnit`]): the trade leg, then the pet leg on a token /// that resolves to the pet's unit (`0x48da6c`-`0x48da7f`, guids compared, so `"target"` and -/// `"targettarget"` feed a targeted pet). The world click's entry into the pet leg, a left click on -/// the pet's model with an item held (`0x4927e8`), is [`ClickFeed`], inside the click's call. -pub(crate) fn drop_item_on_unit( - mut vm: crate::script_calls::VmWith<( - crate::spell::ScriptCast<'static, 'static>, - TradeLeg<'static, 'static>, - )>, - self_q: Query<(&crate::net::Guid, &crate::net::ObjectStore), With>, - stores: Query<&crate::net::ObjectStore>, - index: Res, - learned: Res, -) { - vm.turn(|script, (mut cast, mut trade)| { - let Some(script) = script else { - return; - }; - let pet_guid = cast.ladder.pet_guid(); - let tokens = script.take_drop_item_on_unit(); - if tokens.is_empty() { +/// `"targettarget"` feed a targeted pet). The world click's entry into the pet leg, a left click +/// on the pet's model with an item held (`0x4927e8`), is [`ClickFeed`], inside the click's call. +#[derive(bevy::ecs::system::SystemParam)] +pub(crate) struct DropItemLeg<'w, 's> { + trade: TradeLeg<'w, 's>, + cast: crate::spell::ScriptCast<'w, 's>, + self_q: Query< + 'w, + 's, + (&'static crate::net::Guid, &'static crate::net::ObjectStore), + With, + >, + stores: Query<'w, 's, &'static crate::net::ObjectStore>, + index: Res<'w, crate::net::GuidIndex>, + learned: Res<'w, super::LearnedAbilities>, +} + +impl DropItemLeg<'_, '_> { + /// The drop on the unit `token` names. + pub(crate) fn drop_on(&mut self, script: &mut benilla_ui::script::UiScript, token: &str) { + // Only an item on the cursor drops (`0x48d98f`-`0x48d9aa`). + if !matches!(script.cursor_payload(), Some(CursorPayload::Item(_))) { return; } - let Some((self_guid, self_store)) = self_q.iter().next() else { + let pet_guid = self.cast.ladder.pet_guid(); + let Some((self_guid, self_store)) = self.self_q.iter().next() else { + return; + }; + self.trade.drop_on(script, token); + let Some(guid) = self.trade.unit_guid(token) else { return; }; let leg = PetLeg { pet_guid, - pet: index.0.get(&pet_guid).and_then(|&e| stores.get(e).ok()), + pet: self + .index + .0 + .get(&pet_guid) + .and_then(|&e| self.stores.get(e).ok()), me: self_guid.0, me_store: self_store, - feed_pet: learned.feed_pet, + feed_pet: self.learned.feed_pet, }; - // Each entry in turn: a token's trade leg, then the pet leg on the unit it resolves to - // (`0x515940`). - for token in tokens { - // Only an item on the cursor drops (`0x48d98f`-`0x48d9aa`). - if !matches!(script.cursor_payload(), Some(CursorPayload::Item(_))) { - continue; - } - trade.drop_on(script, &token); - if let Some(guid) = trade.unit_guid(&token) { - leg.run(script, &mut cast, guid); - } - } - }) + leg.run(script, &mut self.cast, guid); + } } /// The world click's pet leg (`0x492793`-`0x4927f8`, in its object leg `0x4925d0`, ahead of the diff --git a/crates/benilla-app/src/ui_action/drop_item_tests.rs b/crates/benilla-app/src/ui_action/drop_item_tests.rs index 6a21ffcac..72e90cb6d 100644 --- a/crates/benilla-app/src/ui_action/drop_item_tests.rs +++ b/crates/benilla-app/src/ui_action/drop_item_tests.rs @@ -7,7 +7,6 @@ use benilla_formats::{SpellCatalog, SpellDisplay}; use benilla_protocol::messages::ObjectType; use benilla_protocol::ObjectFields; use benilla_ui::script::{ContainerSlot, ContainerState, CursorPayload, UiScript, UnitGuids}; -use bevy::ecs::system::SystemId; use bevy::prelude::*; use crossbeam_channel::Receiver; @@ -27,7 +26,6 @@ const HEALTH: u16 = 22; struct Feed { app: App, rx: Receiver, - drop: SystemId, } /// Us, alive or not, a hunter who knows Feed Pet, with Tough Jerky in the backpack and our pet @@ -149,16 +147,11 @@ fn client_with(alive: bool, pet_number: u32, charmed: bool) -> Feed { ); script.set_container(0, Some(bag)); app.world_mut().insert_non_send_resource(script); - let drop = app - .world_mut() - .register_system(super::drop_item::drop_item_on_unit); - Feed { app, rx, drop } + Feed { app, rx } } fn run(f: &mut Feed, lua: &str) { with_hosted_vm(f.app.world_mut(), |vm| vm.expect("a VM").run(lua)).expect("the chunk runs"); - let drop = f.drop; - f.app.world_mut().run_system(drop).expect("the drop runs"); } /// The casts sent since the last read, as their debug lines. diff --git a/crates/benilla-app/src/ui_chat/away.rs b/crates/benilla-app/src/ui_chat/away.rs index d27f9b979..61b813ab1 100644 --- a/crates/benilla-app/src/ui_chat/away.rs +++ b/crates/benilla-app/src/ui_chat/away.rs @@ -186,18 +186,19 @@ pub(crate) fn reconcile_afk_mirror( /// clears; mouse-look turning never reaches `0x514f50`, and knockback, fear and splines press /// nothing. Jump is here but not in `player::follow`'s cancel set: two separate reference tables. pub(crate) fn movement_clears_afk( - binds: Res, // The mirror shares the host's param set, whose chat sends write it too, and so does the - // registry, whose callbacks run inside the calls that write it. + // registry, whose callbacks run inside the calls that write it, and the input state, which + // the binding calls write inside theirs. mut vm: crate::script_calls::VmWith<( ResMut<'static, AfkMirror>, Res<'static, crate::cvars::Cvars>, + Res<'static, crate::bindings::BindingsState>, )>, commands: Res, chat: Res, ) { use crate::bindings::Input; - let (mirror, cvars) = vm.own(); + let (mirror, cvars, binds) = vm.own(); if !mirror.is_afk() || cvars.flag("autoClearAFK") == Some(false) { return; } diff --git a/crates/benilla-app/src/ui_script/pet_frame_tests.rs b/crates/benilla-app/src/ui_script/pet_frame_tests.rs index 5b5b61e92..2f71b3c0e 100644 --- a/crates/benilla-app/src/ui_script/pet_frame_tests.rs +++ b/crates/benilla-app/src/ui_script/pet_frame_tests.rs @@ -399,8 +399,10 @@ fn every_leg_of_the_pet_frame_click_reaches_a_live_binding() { s.run("PetFrame_OnClick(\"LeftButton\")") .expect("the cursor-holds-an-item leg must not error"); assert_eq!( - s.take_drop_item_on_unit(), - vec!["pet".to_string()], + s.take_script_calls(), + vec![benilla_ui::script::ScriptCall::DropItemOnUnit( + "pet".to_string() + )], "a held item + a pet click queues the drop" ); // The drop leg alone: the reference's if/elseif is exclusive. diff --git a/crates/benilla-app/src/ui_trade/call_tests.rs b/crates/benilla-app/src/ui_trade/call_tests.rs index ab6efdb74..12d3699cc 100644 --- a/crates/benilla-app/src/ui_trade/call_tests.rs +++ b/crates/benilla-app/src/ui_trade/call_tests.rs @@ -26,8 +26,6 @@ const JERKY: u64 = 0x4000_0000_0000_0a02; struct Trade { app: App, rx: Receiver, - /// The drop's system, registered once so its memory persists. - drop: SystemId, } /// Our object with `extra` fields: `OBJECT_FIELD_TYPE` a player, alive, the human template, @@ -107,10 +105,7 @@ fn client() -> Trade { ) .expect("the recorder installs"); app.world_mut().insert_non_send_resource(script); - let drop = app - .world_mut() - .register_system(crate::ui_action::drop_item::drop_item_on_unit); - Trade { app, rx, drop } + Trade { app, rx } } /// A left click on `guid`'s model, through the world click's trade leg. @@ -295,8 +290,6 @@ fn held_coins_stay_on_the_cursor_when_a_trade_opens_that_no_drop_started() { fn an_item_dropped_on_a_player_starts_and_fills_a_trade() { let mut t = client(); run(&mut t, "PickupContainerItem(0, 1) DropItemOnUnit('target')"); - let drop = t.drop; - run_system(&mut t, drop); assert!( matches!( sent(&t)[..], @@ -323,8 +316,6 @@ fn an_item_dropped_on_a_player_starts_and_fills_a_trade() { let _ = heard(&mut t); run(&mut t, "PickupContainerItem(0, 2) DropItemOnUnit('target')"); - let drop = t.drop; - run_system(&mut t, drop); assert!( sent(&t) .iter() @@ -335,6 +326,42 @@ fn an_item_dropped_on_a_player_starts_and_fills_a_trade() { assert!(eval::(&mut t, "return CursorHasItem() == nil")); } +/// `DropItemOnUnit` does its legs inside its call (`0x48d960`): on the open partner the held item +/// is placed and the cursor cleared before the script's next line (`0x48da50` → `0x4bfc50`), and +/// with no trade open `CMSG_INITIATE_TRADE` goes out ahead of a send the next line makes +/// (`0x48da62`). +#[test] +fn a_drop_on_a_player_trades_inside_its_call() { + let mut t = client(); + open_with_bob(&mut t); + assert_eq!( + eval::<(bool, Option)>( + &mut t, + "PickupContainerItem(0, 1) DropItemOnUnit('target') \ + return CursorHasItem() == nil, (GetTradePlayerItemInfo(1))" + ), + (true, Some("Linen Cloth".to_string())), + "the next line reads the item placed" + ); + assert_eq!(heard(&mut t), "TRADE_PLAYER_ITEM_CHANGED(1,nil) "); + + let mut t = client(); + run( + &mut t, + "PickupContainerItem(0, 1) DropItemOnUnit('target') RandomRoll(1, 2)", + ); + assert!( + matches!( + sent(&t)[..], + [ + ClientCommand::InitiateTrade { target: BOB }, + ClientCommand::RandomRoll { .. } + ] + ), + "the ask goes out in call order" + ); +} + /// No sender tests the window (`0x5d4680`, `0x4bfa70`, `0x5d4380`, `0x5d4480`): money, a placement /// and a clear go out with none open, and vmangos drops them (`TradeHandler.cpp:668-735`). Each /// edit sent moves the own-edit counter (`0x5d4442`, `0x5d44bc`, `0x5d4712`), two money verbs in @@ -858,7 +885,7 @@ fn the_accept_signal_runs_before_its_packet() { fn a_refused_drop_placement_writes_nothing_and_keeps_the_cursor() { let mut t = client(); open_with_bob(&mut t); - run(&mut t, "PickupContainerItem(0, 1) DropItemOnUnit('target')"); + run(&mut t, "PickupContainerItem(0, 1)"); let world = t.app.world_mut(); if let Some(cloth) = world .resource_mut::() @@ -867,8 +894,7 @@ fn a_refused_drop_placement_writes_nothing_and_keeps_the_cursor() { { world.despawn(cloth); } - let drop = t.drop; - run_system(&mut t, drop); + run(&mut t, "DropItemOnUnit('target')"); assert!(sent(&t).is_empty(), "nothing went out"); assert_eq!(heard(&mut t), "", "no slot signal"); assert_eq!( diff --git a/crates/benilla-ui/src/script/calls.rs b/crates/benilla-ui/src/script/calls.rs index 5e5017672..9df7e5412 100644 --- a/crates/benilla-ui/src/script/calls.rs +++ b/crates/benilla-ui/src/script/calls.rs @@ -299,6 +299,14 @@ pub enum ScriptCall { /// the press (`ArmClick 0x514810` → `0x481f00`), or the last primary's release and its /// dispatch (`ReleaseCommands 0x514b70` → `DispatchWorldClick 0x481f60`), inside the call. WorldClick(super::ClickCall), + /// A movement or camera binding function's call ([`super::BindingInput`]) on the engine's + /// input state, inside the call: a command bit pressed or released through `SetCommands` + /// (`0x515090`) with the cast cancel a new direction makes (`0x5150ce`-`0x515193`), a + /// one-shot, or a camera axis. + Input(super::BindingInput), + /// `DropItemOnUnit(unit)` (`0x48d960`) on the token: the trade leg, then the pet leg's feed + /// on the unit it names, inside the call. + DropItemOnUnit(String), } /// A getter's lookup with a callback, which the host makes inside the getter's call: the cache diff --git a/crates/benilla-ui/src/script/gossip.rs b/crates/benilla-ui/src/script/gossip.rs index c881601c1..e31ad379a 100644 --- a/crates/benilla-ui/src/script/gossip.rs +++ b/crates/benilla-ui/src/script/gossip.rs @@ -60,8 +60,8 @@ pub enum GossipCall { /// `SelectGossipAvailableQuest(i)` (`0x4e24b0`) or `SelectGossipActiveQuest(i)` /// (`0x4e2600`), the 1-based row in its own list: the questgiver query or turn-in for it. Quest { active: bool, index: u32 }, - /// `CloseGossip()` (`0x4e2b20` → `0x4e1fa0` with a zero guid): the cell zeroed in the call - /// (`0x4e1fcc`); the window's teardown and `GOSSIP_CLOSED` follow at the drain. + /// `CloseGossip()` (`0x4e2b20` → `0x4e1fa0` with a zero guid): the interaction's release + /// (`0x4e1fc5`), the cell zeroed (`0x4e1fcc`) and `GOSSIP_CLOSED` (`0x4e1fdc`), in the call. Close, } diff --git a/crates/benilla-ui/src/script/input_verbs.rs b/crates/benilla-ui/src/script/input_verbs.rs index 7e0aa0ed7..228de6058 100644 --- a/crates/benilla-ui/src/script/input_verbs.rs +++ b/crates/benilla-ui/src/script/input_verbs.rs @@ -3,9 +3,10 @@ //! `0x50c089`) and the targeting and posture verbs of the main table `0x83de68` (loop //! `0x49027c`). A key and its Lua function share one path: a held command's Start and Stop are the //! key's press and release ([`HeldInput`]), a one-shot command fires as its key does -//! ([`FiredInput`]), and the targeting and attack calls are script calls ([`ScriptCall`]), -//! applied inside the verb, so a macro's `TargetNearestEnemy()` then `/cast` casts at the new -//! target. +//! ([`FiredInput`]), and each applies to the engine's input state inside the verb through the host +//! lent ([`ScriptCall::Input`]), as `SetCommands` (`0x515090`) sets the bit, cancels the cast and +//! runs the tick before the verb returns. The targeting and attack calls are script calls too, +//! so a macro's `TargetNearestEnemy()` then `/cast` casts at the new target. //! //! Every movement function but the mouselook three opens on the protected-action gate `0x494a50` //! with tag 0 ([`protected`]), which is all twenty-three of its tag-0 callers. The four @@ -182,7 +183,8 @@ pub struct ClickPress { } impl UiScript { - /// Take the binding calls queued since the last call, in call order. + /// Take the binding calls made with no host lent since the last call, in call order; with a + /// host lent each applies inside its call ([`ScriptCall::Input`]). pub fn take_binding_input(&mut self) -> Vec { std::mem::take(&mut self.model_mut().input.queue) } @@ -354,9 +356,15 @@ fn gate(lua: &Lua) -> bool { protected::gate(lua, Tag::MOVEMENT) } -fn push(lua: &Lua, input: BindingInput) { +/// A binding call, applied to the engine's input state inside the call through the host lent +/// ([`ScriptCall::Input`]); with none lent it waits for the app ([`UiScript::take_binding_input`]). +fn push(lua: &Lua, input: BindingInput) -> mlua::Result<()> { + if super::host::open(lua) { + return push_call(lua, ScriptCall::Input(input)); + } let mut model = lua.app_data_mut::().expect("model app_data"); model.input.queue.push(input); + Ok(()) } fn push_look(lua: &Lua, call: LookCall) { @@ -439,7 +447,7 @@ pub(super) fn install(lua: &Lua) -> mlua::Result<()> { if let Some((bit, mode)) = primary { press_primary(lua, bit, Some(mode))?; } - push(lua, BindingInput::Start(input)); + push(lua, BindingInput::Start(input))?; } Ok(()) })?, @@ -451,7 +459,7 @@ pub(super) fn install(lua: &Lua) -> mlua::Result<()> { if let Some((bit, _)) = primary { release_primary(lua, bit)?; } - push(lua, BindingInput::Stop(input)); + push(lua, BindingInput::Stop(input))?; // A mouse bit's release carries its fourth argument to the camera: the sticky // flag through `0x6f1c10` with default 0 (`0x5141f6`), else 0 (`0x51417b`). match input { @@ -481,7 +489,7 @@ pub(super) fn install(lua: &Lua) -> mlua::Result<()> { name, lua.create_function(move |lua, _: MultiValue| { if gate(lua) { - push(lua, BindingInput::Fire(input)); + push(lua, BindingInput::Fire(input))?; } Ok(()) })?, @@ -524,7 +532,7 @@ pub(super) fn install(lua: &Lua) -> mlua::Result<()> { "CameraZoomIn", lua.create_function(|lua, v: Option| { if let Some(yards) = zoom_amount(lua, v) { - push(lua, BindingInput::Fire(FiredInput::CameraZoomIn(yards))); + push(lua, BindingInput::Fire(FiredInput::CameraZoomIn(yards)))?; } Ok(()) })?, @@ -533,7 +541,7 @@ pub(super) fn install(lua: &Lua) -> mlua::Result<()> { "CameraZoomOut", lua.create_function(|lua, v: Option| { if let Some(yards) = zoom_amount(lua, v) { - push(lua, BindingInput::Fire(FiredInput::CameraZoomOut(yards))); + push(lua, BindingInput::Fire(FiredInput::CameraZoomOut(yards)))?; } Ok(()) })?, @@ -553,14 +561,14 @@ pub(super) fn install(lua: &Lua) -> mlua::Result<()> { g.set( start, lua.create_function(move |lua, _: MultiValue| { - push(lua, BindingInput::ViewStart(axis)); + push(lua, BindingInput::ViewStart(axis))?; Ok(()) })?, )?; g.set( stop, lua.create_function(move |lua, _: MultiValue| { - push(lua, BindingInput::ViewStop(axis)); + push(lua, BindingInput::ViewStop(axis))?; Ok(()) })?, )?; @@ -629,7 +637,7 @@ pub(super) fn install(lua: &Lua) -> mlua::Result<()> { g.set( "ToggleSheath", lua.create_function(move |lua, _: MultiValue| { - push(lua, BindingInput::Fire(FiredInput::ToggleSheath)); + push(lua, BindingInput::Fire(FiredInput::ToggleSheath))?; Ok(()) })?, )?; @@ -1017,6 +1025,33 @@ mod tests { ); } + /// With a host lent, every movement and camera binding call applies inside its call, in call + /// order with the other calls (`0x515090` returns with the bit set and the cast cancelled), and + /// nothing waits for the app. + #[test] + fn the_binding_calls_apply_in_the_call_with_a_host_lent() { + let mut s = UiScript::new().unwrap(); + let calls = crate::script::host::test_support::applied_in_call( + &mut s, + "MoveForwardStart() SitOrStand() Jump() MoveForwardStop() CameraZoomOut(2) \ + MoveViewLeftStart() ToggleSheath() PitchUpStart()", + ); + assert_eq!( + calls, + [ + ScriptCall::Input(BindingInput::Start(HeldInput::MoveForward)), + ScriptCall::Posture(PostureCall::SitOrStand), + ScriptCall::Input(BindingInput::Fire(FiredInput::Jump)), + ScriptCall::Input(BindingInput::Stop(HeldInput::MoveForward)), + ScriptCall::Input(BindingInput::Fire(FiredInput::CameraZoomOut(2.0))), + ScriptCall::Input(BindingInput::ViewStart(ViewAxis::Left)), + ScriptCall::Input(BindingInput::Fire(FiredInput::ToggleSheath)), + ScriptCall::Input(BindingInput::Start(HeldInput::PitchUp)), + ] + ); + assert!(s.take_binding_input().is_empty(), "nothing waits"); + } + /// The TAB cyclers, `TargetLastTarget` and `AttackTarget` apply inside their call with a host /// lent. #[test] diff --git a/crates/benilla-ui/src/script/model.rs b/crates/benilla-ui/src/script/model.rs index 57d0fba37..4e156f41d 100644 --- a/crates/benilla-ui/src/script/model.rs +++ b/crates/benilla-ui/src/script/model.rs @@ -416,8 +416,6 @@ pub(crate) struct Model { pub(crate) input: super::input_verbs::InputState, /// The protected-action gate's input events ([`super::protected`]). pub(crate) protected: super::protected::Flags, - /// `DropItemOnUnit` tokens (`0x48d960`), gated by the app; a refusal silently keeps the item. - pub(crate) drop_item_on_unit: Vec, /// The joined channels, in join order: the numbers `GetChannelName` answers. pub(crate) joined_channels: Vec>, @@ -1422,7 +1420,6 @@ impl Model { call_raises: Default::default(), input: Default::default(), protected: Default::default(), - drop_item_on_unit: Vec::new(), joined_channels: Vec::new(), party: party::PartyState::default(), ready_check: party::ReadyCheckState::default(), diff --git a/crates/benilla-ui/src/script/quest.rs b/crates/benilla-ui/src/script/quest.rs index a9cda1155..e6a0689ea 100644 --- a/crates/benilla-ui/src/script/quest.rs +++ b/crates/benilla-ui/src/script/quest.rs @@ -164,8 +164,9 @@ pub enum QuestCall { /// (`0x501d89`-`0x501da8`): on the reward panel, the latch, the choice's range, which raises /// from the verb, and `CMSG_QUESTGIVER_CHOOSE_REWARD`. Reward(i32), - /// `CloseQuest()` (`0x501a10` → `0x501130(0,1)`): a sharer's decline and the zeroed cell - /// (`0x501201`) in the call; the window's teardown and `QUEST_FINISHED` follow at the drain. + /// `CloseQuest()` (`0x501a10` → `0x501130(0,1)`): a sharer's decline, the zeroed cell + /// (`0x501201`), the latch's release (`0x50120d`) and `QUEST_FINISHED` (`0x501217`), in the + /// call. Close, /// `ConfirmAcceptQuest()` (`0x5021b0`): `CMSG_QUEST_CONFIRM_ACCEPT` with the quest the last /// confirm held (`[0xbe0840]`, `0x5021e0`), an engine cell the host keeps. diff --git a/crates/benilla-ui/src/script/tests/protected_gate.rs b/crates/benilla-ui/src/script/tests/protected_gate.rs index a99c167bc..7bbe0563d 100644 --- a/crates/benilla-ui/src/script/tests/protected_gate.rs +++ b/crates/benilla-ui/src/script/tests/protected_gate.rs @@ -534,11 +534,6 @@ fn effects(s: &mut UiScript) -> Vec { } out.extend(s.take_session_requests().iter().map(|r| format!("{r:?}"))); out.extend(s.take_duel_requests().iter().map(|r| format!("{r:?}"))); - out.extend( - s.take_drop_item_on_unit() - .iter() - .map(|t| format!("drop {t}")), - ); out.extend( s.take_pet_autocast_toggles() .iter() diff --git a/crates/benilla-ui/src/script/unit/bindings.rs b/crates/benilla-ui/src/script/unit/bindings.rs index a1493a6f0..5df760485 100644 --- a/crates/benilla-ui/src/script/unit/bindings.rs +++ b/crates/benilla-ui/src/script/unit/bindings.rs @@ -1099,7 +1099,7 @@ pub(in crate::script) fn install(lua: &Lua) -> mlua::Result<()> { )?; // DropItemOnUnit(unit) (`0x48d960`): drop the cursor's item on a unit, feeding a pet or - // opening a trade with a player. Only the token is queued; the app runs every gate. + // opening a trade with a player, inside the call; the host runs every gate. g.set( "DropItemOnUnit", lua.create_function(|lua, token: Value| { @@ -1114,8 +1114,7 @@ pub(in crate::script) fn install(lua: &Lua) -> mlua::Result<()> { if token != "pet" || crate::script::protected::gate(lua, crate::script::protected::Tag::CAST) { - let mut model = lua.app_data_mut::().expect("model app_data"); - model.drop_item_on_unit.push(token); + submit(lua, ScriptCall::DropItemOnUnit(token))?; } Ok(()) })?, diff --git a/crates/benilla-ui/src/script/unit/mod.rs b/crates/benilla-ui/src/script/unit/mod.rs index 8b46b31b3..297a56308 100644 --- a/crates/benilla-ui/src/script/unit/mod.rs +++ b/crates/benilla-ui/src/script/unit/mod.rs @@ -561,12 +561,6 @@ impl super::UiScript { .is_empty() } - /// Drain `DropItemOnUnit`'s tokens; on the pet the app casts the learned Feed Pet spell at - /// the held item (`0x48d960`). - pub fn take_drop_item_on_unit(&mut self) -> Vec { - std::mem::take(&mut self.model_mut().drop_item_on_unit) - } - /// Take the `SpellTargetUnit` calls out of the call stream. pub fn take_spell_target_unit(&mut self) -> Vec { self.take_calls_where(|c| match c { diff --git a/docs/DEVIATIONS.md b/docs/DEVIATIONS.md index edd743fd6..d9bafb590 100644 --- a/docs/DEVIATIONS.md +++ b/docs/DEVIATIONS.md @@ -75,8 +75,8 @@ Each entry is the first sentence of a `Deviation:` comment, linking to where it #### bindings - A press with Super (Cmd) held runs no binding, so a system chord such as Cmd+Tab or Cmd+Q never acts in game. ([`src/bindings.rs:19`](../crates/benilla-app/src/bindings.rs#L19)) -- A trackpad's `Pixel` deltas are carried until they make a line, and step at most once per event (`crate::ui_script::Record::Wheel`). ([`src/bindings.rs:525`](../crates/benilla-app/src/bindings.rs#L525)) -- Latches die with the VM that made them, because a latch names a command of that VM's table and releasing it against a new one would run another load's up-half. ([`src/bindings.rs:601`](../crates/benilla-app/src/bindings.rs#L601)) +- A trackpad's `Pixel` deltas are carried until they make a line, and step at most once per event (`crate::ui_script::Record::Wheel`). ([`src/bindings.rs:557`](../crates/benilla-app/src/bindings.rs#L557)) +- Latches die with the VM that made them, because a latch names a command of that VM's table and releasing it against a new one would run another load's up-half. ([`src/bindings.rs:602`](../crates/benilla-app/src/bindings.rs#L602)) - The Windows key table stops at `VK_F12` and drops later F-keys; they are named here so a stored `F13`-`F24` can be pressed. ([`src/bindings/chord.rs:165`](../crates/benilla-app/src/bindings/chord.rs#L165)) - On the Mac and Linux a key its platform reports no character for keeps its US name too, where the Mac reference drops it (`0x8a4aa`), and a Linux dead key not yet pressed bare stays bindable. ([`src/bindings/layout.rs:116`](../crates/benilla-app/src/bindings/layout.rs#L116)) - A character above U+00FF names the key by itself. The reference's `MapVirtualKeyA` returns an ANSI code-page byte, which `0x42da4b` drops past `0xff` and the namer's UTF-8 encoder (`0x41abb0`) otherwise reads as Latin-1, so such a key is mislabelled or dropped; named by what it types, it stays bindable and readable. ([`src/bindings/layout.rs:216`](../crates/benilla-app/src/bindings/layout.rs#L216)) @@ -742,7 +742,7 @@ Each entry is the first sentence of a `Deviation:` comment, linking to where it - `pow(10, n)` is the platform's, where the reference's (`0x73f940`, `fyl2x`) rounds its extended-precision steps at 53 bits, so a power or a fraction term can differ in the last place. ([`src/script/binding_abi.rs:281`](../crates/benilla-ui/src/script/binding_abi.rs#L281)) - The disabled-checked leg (`0x785380`) tests and reloads the checked slot (`[+0x4e0]`, `0x785388`/`0x7853a5`), a copy of the checked leg's (`0x785270`), so in 1.12.1 a check box with a checked texture repaints that one and never gets its disabled-checked texture from a path. benilla tests and reloads the slot the method names. ([`src/script/button.rs:621`](../crates/benilla-ui/src/script/button.rs#L621)) - The slot is read before the handler, where the reference reads it after (`[esi+0x4dc]`), because reading first keeps the borrow simple and no stock handler re-slots its row. ([`src/script/button.rs:1209`](../crates/benilla-ui/src/script/button.rs#L1209)) -- The reference's only bound is `luaD_call`'s count of 200 nested calls (`0x6f65ae`), past which it raises `C stack overflow` (`0x6f65bf`); eight here, as each level keeps an apply's frame on the Rust stack. ([`src/script/calls.rs:707`](../crates/benilla-ui/src/script/calls.rs#L707)) +- The reference's only bound is `luaD_call`'s count of 200 nested calls (`0x6f65ae`), past which it raises `C stack overflow` (`0x6f65bf`); eight here, as each level keeps an apply's frame on the Rust stack. ([`src/script/calls.rs:715`](../crates/benilla-ui/src/script/calls.rs#L715)) - The reference composes the Shortcut with `GetRealZoneText` alone (`0x49efe8`), so in a capital `/leave Trade` sends `Trade - Stormwind City` and leaves nothing; ours uses the join's city-aware name, because the reference's form cannot leave the channel it joined. ([`src/script/channel.rs:516`](../crates/benilla-ui/src/script/channel.rs#L516)) - The frame's bottom-left origin is snapped onto the device grid so the border art blits 1:1; the reference ceils the anchor point itself onto it (`0x7666a0`, `0x766750`). ([`src/script/chat_bubble.rs:482`](../crates/benilla-ui/src/script/chat_bubble.rs#L482)) - No truncation at 255 characters (`0x49f604`), because vmangos refuses a longer line itself (`Chat.cpp:2177`): it is dropped where the reference sends its first 255. ([`src/script/chat_send.rs:26`](../crates/benilla-ui/src/script/chat_send.rs#L26))