From 4dc5f1c19131c62da6e7573a8626ac89c338afdd Mon Sep 17 00:00:00 2001 From: Sam Sung <51686767+samwhosung@users.noreply.github.com> Date: Mon, 19 Oct 2026 05:37:34 +0700 Subject: [PATCH] Every by-name lookup runs 1.12.1's one resolver (#1966) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1.12.1 resolves every name through one function, `0x493aa0`: party and raid passes for members with no object held, then every held object its mode's filter passes, feeding one matcher (`0x493c60`). benilla had partial copies: the app's scan ran the object pass only, SetLootMethod the roster passes only, and Promote, assistant, duel and emote lookups matched exact names. `benilla_ui::script::by_name::resolve` now runs the passes with each caller's typemask, mode and exact flag: TargetByName, /target, /assist, /follow, DoEmote, SetLootMethod, PromoteByName, PromoteToAssistant, DemoteAssistant and StartDuel. It answers nothing with no active player (`0x493ae0`). Mode 2's filter is `CanAssist` and alive (`0x493eca`). The roster passes stay off for /target, /assist and /follow until the selection can hold a guid (#1965). Tests per caller: prefix, a held stranger, a dead groupmate, a miss, no player. A byte audit re-derived the call sites and the matcher. Fixes #1964 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 5.5 --- crates/benilla-app/src/script_calls.rs | 120 +++++ crates/benilla-app/src/target/by_name.rs | 296 +++++++++--- crates/benilla-app/src/target/mod.rs | 4 +- crates/benilla-app/src/ui_chat/input/mod.rs | 54 +-- crates/benilla-app/src/ui_chat/tests.rs | 57 +-- crates/benilla-app/src/ui_duel.rs | 10 +- crates/benilla-app/src/ui_party/feed.rs | 67 +-- .../benilla-app/src/ui_script/duel_tests.rs | 17 +- .../benilla-app/src/ui_script/raid_tests.rs | 13 +- crates/benilla-app/src/ui_unit.rs | 1 + crates/benilla-app/src/ui_unit/held.rs | 7 + crates/benilla-ui/src/script/duel.rs | 104 ++++- crates/benilla-ui/src/script/party.rs | 340 +++++++++----- .../src/script/tests/protected_gate.rs | 16 + crates/benilla-ui/src/script/unit/by_name.rs | 431 ++++++++++++++++-- crates/benilla-ui/src/script/unit/tests.rs | 1 + docs/DEVIATIONS.md | 6 +- 17 files changed, 1207 insertions(+), 337 deletions(-) diff --git a/crates/benilla-app/src/script_calls.rs b/crates/benilla-app/src/script_calls.rs index c1f3db81d..669c30f9f 100644 --- a/crates/benilla-app/src/script_calls.rs +++ b/crates/benilla-app/src/script_calls.rs @@ -745,6 +745,126 @@ mod tests { } } + /// `SetLootMethod`'s master name runs the resolver in mode 2 (`0x4e9418`, filter `0x493eca`): + /// a held groupmate resolves through the candidate feed while `CanAssist` and alive, and a + /// dead one is no candidate, so the name finds nobody and the binding sends nothing. + #[test] + fn set_loot_method_resolves_a_held_groupmate_only_while_alive() { + use benilla_ui::script::{PartyMemberInfo, PartyRequest, PartyState}; + for (health, resolved) in [(100, true), (0, false)] { + let mut f = frame(false); + // OLD is a friendly player-controlled unit, our groupmate "Olly" in `party1`. + with_factions(&mut f, FRIEND, &[(FLAGS, 0x8), (HEALTH, health)]); + let world = f.app.world_mut(); + let mut names = world.resource_mut::(); + names.insert_player(OLD, "Olly".into(), None); + names.insert_player(ME, "Me".into(), None); + world + .run_system_once(crate::ui_unit::feed_name_candidates) + .expect("the candidate feed runs as a one-shot system"); + let mut script = f.app.world_mut().non_send_resource_mut::(); + script.set_party(PartyState { + members: vec![PartyMemberInfo { + name: "Olly".into(), + guid: OLD, + }], + leader_index: 0, + leader_guid: ME, + own_guid: ME, + ..Default::default() + }); + script.set_unit( + "player", + Some(benilla_ui::script::UnitState { + exists: true, + has_object: true, + guid: ME, + ..Default::default() + }), + ); + script.set_unit( + "party1", + Some(benilla_ui::script::UnitState { + exists: true, + has_object: true, + guid: OLD, + ..Default::default() + }), + ); + script + .run(r#"SetLootMethod("master", "Ol")"#) + .expect("the script runs"); + let sent = script.take_party_requests(); + let expected = resolved.then_some(PartyRequest::LootMethod { + method: 2, + master: OLD, + threshold: 2, + }); + assert_eq!(sent, expected.into_iter().collect::>(), "{health}"); + } + } + + /// Our own name resolves through the object pass at distance 0 (`0x493d30` measures from our + /// own object, which the roster passes skip as held), and passes mode 2 while its health is + /// above 0 (`0x493eca`): a ghost, at health 1, does; a corpse, at 0, does not. + #[test] + fn set_loot_method_resolves_our_own_name_through_the_feed() { + use benilla_ui::script::{PartyRequest, PartyState}; + for (health, resolved) in [(100, true), (1, true), (0, false)] { + let mut f = frame(false); + with_factions(&mut f, FRIEND, &[]); + let world = f.app.world_mut(); + let me = world.resource::().0[&ME]; + world + .entity_mut(me) + .insert(ObjectStore(benilla_protocol::ObjectFields::from_pairs(&[ + (2, 0x19), + (HEALTH, health), + (28, 100), + (FLAGS, 0x8), + (TEMPLATE, OURS), + ]))); + world + .resource_mut::() + .insert_player(ME, "Kelvin".into(), None); + world + .run_system_once(crate::ui_unit::feed_name_candidates) + .expect("the candidate feed runs as a one-shot system"); + let mut script = f.app.world_mut().non_send_resource_mut::(); + script.set_party(PartyState { + members: vec![benilla_ui::script::PartyMemberInfo { + name: "Olly".into(), + guid: OLD, + }], + leader_guid: ME, + own_guid: ME, + ..Default::default() + }); + script.set_unit( + "player", + Some(benilla_ui::script::UnitState { + exists: true, + has_object: true, + guid: ME, + ..Default::default() + }), + ); + script + .run(r#"SetLootMethod("master", "kel")"#) + .expect("the script runs"); + let expected = resolved.then_some(PartyRequest::LootMethod { + method: 2, + master: ME, + threshold: 2, + }); + assert_eq!( + script.take_party_requests(), + expected.into_iter().collect::>(), + "health {health}" + ); + } + } + /// The candidate feed marks a `UNIT_FLAG_NOT_SELECTABLE` unit as the commit's `IsSelectable` /// does (`0x4935ee`): the nearer namesake is the ranked pick and it is refused, so the chunk /// keeps the old target's view and the commit keeps its selection, not the farther namesake. diff --git a/crates/benilla-app/src/target/by_name.rs b/crates/benilla-app/src/target/by_name.rs index 03ce2cdb1..c9ebe6bfc 100644 --- a/crates/benilla-app/src/target/by_name.rs +++ b/crates/benilla-app/src/target/by_name.rs @@ -7,21 +7,21 @@ //! | `AssistByName 0x489c40` | 0x10, players only | 0 | 0 | //! | `FollowByName 0x489ec0` | 0x10, players only | 2, `CanAssist` and alive | Lua arg 2 | //! -//! Filter mode 0 underflows `0x493e40`'s jump table into accept-all: no range, facing, reaction, -//! liveness, visibility or self test. The ranking is the VM's ([`benilla_ui::script::by_name`]), -//! which `TargetByName` runs over [`crate::ui_unit`]'s candidate feed to show its pick to the rest -//! of its chunk; the reference's walk follows the object list's order (a tail append, -//! `0x4646c3`-`0x4646d4`), the deviation documented there. Both walks measure off -//! [`GlobalTransform`] and break a full tie by guid, so the chunk shows the unit the commit picks. +//! The ranking is [`benilla_ui::script::by_name::resolve`], the one resolver `SetLootMethod`'s master +//! name and `TargetByName`'s view of the pick share; this module feeds it the held units, positioned +//! by [`GlobalTransform`] as [`crate::ui_unit`]'s candidate feed does, and breaks a full tie by +//! guid, so the chunk shows the unit the commit picks. The reference's walk follows the object +//! list's order (a tail append, `0x4646c3`-`0x4646d4`), the deviation documented there. //! -//! Not built: the reference's party (`0x493b20`) and raid (`0x493b9d`) pre-scans, which select an -//! unstreamed groupmate; [`Selection::target`] is an `Entity`. +//! Not built for these selecting callers: the roster passes (party `0x493b20`, raid `0x493b9d`), +//! because the selection holds an entity, not a guid, and `0x493540` stores a guid with no object +//! (`0x493605`). `DoEmote`'s [`PlayerLookup`] needs only a guid and runs them. use bevy::ecs::system::SystemParam; use bevy::prelude::*; use benilla_protocol::guid; -use benilla_ui::script::by_name::{rank, Match, Rank}; +use benilla_ui::script::by_name::{resolve, Filter, Held, Kinds, Match, RosterEntry, Search}; use crate::names::NameCache; use crate::net::{Guid, GuidIndex, ObjectStore, SelfPlayer}; @@ -50,6 +50,14 @@ pub(crate) enum Candidacy<'a> { } impl NameSearch { + /// The resolver's typemask argument. + fn kinds(self) -> Kinds { + match self { + Self::AnyUnit => Kinds::AnyUnit, + Self::PlayerOnly => Kinds::PlayerOnly, + } + } + fn accepts(self, guid_val: u64) -> bool { match self { Self::AnyUnit => guid::is_player(guid_val) || guid::is_creature_or_pet(guid_val), @@ -141,15 +149,8 @@ pub(crate) struct ByNameScan<'w, 's> { /// The reaction inputs behind `CanAssist`, for [`Filter::AssistableAlive`] and the follow gate. factions: Option>, reputations: Res<'w, crate::net::Reputations>, -} - -/// The per-candidate filter, the mode argument the reference hands `0x493e40`. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum Filter { - /// Mode 0, which underflows the jump table's bound into accept-all: `/target`, `/assist`. - AcceptAll, - /// Mode 2, `CanAssist` and `UNIT_FIELD_HEALTH > 0`: `/follow`. - AssistableAlive, + /// The guid to entity map, for the owner `CanAssist`'s PvP arm reads. + index: Res<'w, GuidIndex>, } impl ByNameScan<'_, '_> { @@ -162,18 +163,19 @@ impl ByNameScan<'_, '_> { .map(|(_, _, tf, _)| tf.translation()) } - /// The mode-2 arm (`0x493eca`): alive, and `CanAssist 0x6066f0` as a friendly reaction (4+). + /// [`assistable_alive`] for a unit the scan walks. fn assistable_alive(&self, store: Option<&ObjectStore>) -> bool { - if store.is_some_and(|s| s.0.unit_is_dead()) { - return false; - } let self_store = self.self_q.single().ok().and_then(|(_, _, _, s)| s); - super::ring_reaction( + assistable_alive( + store, self.factions.as_deref(), &self.reputations, - store, self_store, - ) >= 4 + |guid| { + let entity = self.index.0.get(&guid)?; + self.units.get(*entity).ok()?.3.cloned() + }, + ) } /// The follow start gate ([`follow_refusal_key`], entered at `0x60ff59`): the key of the first @@ -215,12 +217,36 @@ impl ByNameScan<'_, '_> { &self.names, query, search, + filter, mode, - |store| filter != Filter::AssistableAlive || self.assistable_alive(store), + Roster::default(), + |store| self.assistable_alive(store), ) + // With no roster every pick is a held unit. + .and_then(|(e, g, n)| Some((e?, g, n))) } } +/// The mode-2 filter (`0x493eca`): `CanAssist 0x6066f0` toward the active player and +/// `UNIT_FIELD_HEALTH > 0` (`[unit+0x110]+0x40`). `owner_store` finds an owner's descriptor, for +/// [`super::can_assist`]'s PvP arm. The follow gate and the VM's by-name candidates share it. +pub(crate) fn assistable_alive( + store: Option<&ObjectStore>, + factions: Option<&super::Factions>, + reputations: &crate::net::Reputations, + self_store: Option<&ObjectStore>, + owner_store: impl FnOnce(u64) -> Option, +) -> bool { + super::can_assist( + store, + factions, + reputations, + self_store, + owner_store, + super::Assist::PlayerToUnit, + ) && store.is_some_and(|s| s.0.unit_health().unwrap_or(0) > 0) +} + /// One unit query's candidates, positioned by [`GlobalTransform`] as the VM's candidate feed /// (`ui_unit::held::feed_name_candidates`) does: nothing writes it during `Update`, so both walks /// read one value in a frame, and it adds no undeclared order against the systems that move units. @@ -235,19 +261,31 @@ type UnitQuery<'w, 's> = Query< ), >; +/// The roster passes' input (`0x493b22`, `0x493ba7`): the party slots and the raid members, by the +/// name the wire gave and whether the object manager holds them. Empty for the callers that +/// select ([`Selection::target`] is an entity); a pick from it has a guid and no entity. +#[derive(Default)] +pub(super) struct Roster<'a> { + party: Vec>, + raid: Vec>, +} + /// The resolver's walk (`0x493aa0`): a name to a unit, logging one `by-name:` line per call, -/// ungated since it runs per command: the candidates counted, the winner and on what. `keep` is -/// the per-candidate filter mode; `origin` is the active player's position, without which the -/// reference resolves nothing (`0x493ae0`). +/// ungated since it runs per command: the candidates counted, the winner and on what. `filter` is +/// the mode argument and `assistable` its mode-2 test; `origin` is the active player's position, +/// without which the reference resolves nothing (`0x493ae0`). +#[allow(clippy::too_many_arguments)] // the resolver's own arguments, one call per binding fn scan_units<'a>( units: impl Iterator)>, origin: Option, names: &NameCache, query: &str, search: NameSearch, + filter: Filter, mode: Match, - keep: impl Fn(Option<&ObjectStore>) -> bool, -) -> Option<(Entity, u64, String)> { + roster: Roster<'_>, + assistable: impl Fn(Option<&ObjectStore>) -> bool, +) -> Option<(Option, u64, String)> { let query = query.trim(); if query.is_empty() { return None; @@ -256,44 +294,52 @@ fn scan_units<'a>( info!("by-name: \"{query}\" — no active player object; nothing resolves"); return None; }; - let mut considered = 0usize; let mut nameless = 0usize; - let mut best: Option<(Entity, u64, Rank, String)> = None; + let mut held = Vec::new(); for (entity, guid, pos, store) in units { - let candidacy = search.candidacy(names, guid); - if candidacy == Candidacy::Outside || !keep(store) { - continue; - } - let Candidacy::Named(name) = candidacy else { - nameless += 1; - continue; - }; - considered += 1; - let dist2 = pos.distance_squared(origin); - let Some(r) = rank(query, name, dist2, mode) else { - continue; - }; - if best - .as_ref() - .is_none_or(|(_, g, b, _)| r.beats_at(guid, *b, *g)) - { - best = Some((entity, guid, r, name.to_string())); + match search.candidacy(names, guid) { + Candidacy::Outside => {} + Candidacy::Nameless => nameless += 1, + Candidacy::Named(name) => held.push(Held { + id: entity, + name, + guid, + dist2: pos.distance_squared(origin), + is_player: guid::is_player(guid), + assistable_alive: filter == Filter::AssistableAlive && assistable(store), + }), } } + let considered = held.len(); + let best = resolve( + Search { + query, + kinds: search.kinds(), + filter, + exact: mode, + // The `origin` test above is `0x493ae0`. + active_player: true, + }, + roster.party, + roster.raid, + held, + ); match &best { - Some((_, guid, r, name)) => info!( - "by-name: \"{query}\" ({search:?}) -> \"{name}\" guid {guid:#x} \ + Some(pick) => info!( + "by-name: \"{query}\" ({search:?}) -> \"{}\" guid {:#x} \ ({}, prefix {}, {:.1} yd) over {considered} named candidates ({nameless} unnamed)", - if r.exact { "exact" } else { "prefix" }, - r.prefix, - r.dist2.sqrt(), + pick.name, + pick.guid, + if pick.rank.exact { "exact" } else { "prefix" }, + pick.rank.prefix, + pick.rank.dist2.sqrt(), ), None => info!( "by-name: \"{query}\" ({search:?}) -> NO MATCH over {considered} named candidates \ ({nameless} unnamed, {mode:?}); target left untouched" ), } - best.map(|(e, g, _, name)| (e, g, name)) + best.map(|p| (p.object, p.guid, p.name.to_string())) } /// The player-only name search for a caller that holds the [`NameCache`] mutably and so cannot @@ -308,9 +354,38 @@ pub(crate) struct PlayerLookup<'w, 's> { impl PlayerLookup<'_, '_> { /// `0x493aa0` with typemask `0x10`, filter mode 0 and no exact-only flag, as `/assist ` - /// calls it: any player in the object list, whole name or longest prefix. Selects nothing. - pub(crate) fn find(&self, names: &NameCache, name: &str) -> Option<(Entity, u64)> { + /// calls it: the party slots and the raid members with no object held, then any player in the + /// object list, whole name or longest prefix. Selects nothing, so the pick is only a guid. + /// `group` and `index` are the roster and the object manager's guids, which the chat drain + /// holds itself. + pub(crate) fn find( + &self, + names: &NameCache, + group: &crate::ui_party::GroupState, + index: &GuidIndex, + name: &str, + ) -> Option { let origin = self.self_q.single().ok().map(|tf| tf.translation()); + fn entry<'a>( + m: &'a benilla_protocol::messages::GroupMemberEntry, + index: &GuidIndex, + ) -> RosterEntry<'a> { + RosterEntry { + name: &m.name, + guid: m.guid, + held: index.0.contains_key(&m.guid), + } + } + let in_raid = group.group_type == crate::ui_party::GROUPTYPE_RAID; + let roster = Roster { + party: group.party_slots().map(|m| entry(m, index)).collect(), + raid: group + .members + .iter() + .filter(|_| in_raid) + .map(|m| entry(m, index)) + .collect(), + }; scan_units( self.units .iter() @@ -319,10 +394,12 @@ impl PlayerLookup<'_, '_> { names, name, NameSearch::PlayerOnly, + Filter::AcceptAll, Match::PrefixOk, + roster, |_| true, ) - .map(|(e, g, _)| (e, g)) + .map(|(_, g, _)| g) } } @@ -604,7 +681,7 @@ impl SelectCommit<'_, '_> { #[cfg(test)] mod tests { use super::*; - use benilla_ui::script::by_name::common_prefix_len; + use benilla_ui::script::by_name::{common_prefix_len, rank, Rank}; fn exact(dist2: f32) -> Rank { Rank { @@ -730,4 +807,101 @@ mod tests { assert!(!exact(4.0).beats(exact(4.0))); assert!(!prefix(3, f32::NAN).beats(prefix(3, 4.0))); } + + /// Mode 2 (`0x493eca`) is `CanAssist` and health above 0: a dead friend and a living enemy are + /// both refused, a living friend (PvP-flagged, as a creature must be for the player to assist + /// it, `0x6067a7`) passes. + #[test] + fn the_follow_filter_wants_an_assistable_unit_with_health() { + use crate::spell::targeting::corpse_fixture as fx; + let factions = fx::factions(); + let reps = crate::net::Reputations::default(); + // UNIT_FIELD_FACTIONTEMPLATE, _FLAGS (player-controlled, PvP), _HEALTH and _MAXHEALTH. + let unit = |template: u32, flags: u32, health: u32| { + ObjectStore(benilla_protocol::ObjectFields::from_pairs(&[ + (35, template), + (46, flags), + (22, health), + (28, 50), + ])) + }; + let me = unit(1, 0x8, 50); + let ask = |u: &ObjectStore| { + assistable_alive(Some(u), Some(&factions), &reps, Some(&me), |_| None) + }; + assert!(ask(&unit(1, 0x1000, 50))); + assert!(!ask(&unit(1, 0x1000, 0)), "dead"); + assert!(!ask(&unit(2, 0x1000, 50)), "an enemy"); + assert!(!assistable_alive( + None, + Some(&factions), + &reps, + Some(&me), + |_| None + )); + } + + /// `DoEmote`'s search (`0x49fde9`, typemask 0x10, mode 0) runs the roster passes: a groupmate + /// with no object answers to a prefix, and a streamed player nearer than the roster's + /// placeholder distance with an equal prefix answers instead. + #[test] + fn the_emote_search_finds_a_groupmate_with_no_object() { + use benilla_protocol::messages::GroupMemberEntry; + use bevy::ecs::system::RunSystemOnce; + const ME: u64 = 0x10; + const BOB: u64 = 0x20; + const BOBBY: u64 = 0x30; + let mut world = World::new(); + world.init_resource::(); + world.init_resource::(); + world.spawn(( + SelfPlayer, + Guid(ME), + GlobalTransform::from_translation(Vec3::ZERO), + )); + world + .resource_mut::() + .members + .push(GroupMemberEntry { + name: "Bob".into(), + guid: BOB, + status: 1, + flags: 0, + }); + world.init_resource::(); + world + .resource_mut::() + .insert_player(ME, "Me".into(), None); + let find = |world: &mut World, query: &'static str| { + world + .run_system_once( + move |lookup: PlayerLookup, + names: Res, + group: Res, + index: Res| { + lookup.find(&names, &group, &index, query) + }, + ) + .expect("the lookup runs as a one-shot system") + }; + assert_eq!(find(&mut world, "Bo"), Some(BOB)); + assert_eq!(find(&mut world, "Zed"), None); + // Bobby is streamed and named: nearer than the placeholder, an equal prefix. + let bobby = world + .spawn(( + Guid(BOBBY), + GlobalTransform::from_translation(Vec3::new(9.0, 0.0, 0.0)), + )) + .id(); + world.resource_mut::().0.insert(BOBBY, bobby); + world + .resource_mut::() + .insert_player(BOBBY, "Bobby".into(), None); + assert_eq!(find(&mut world, "Bo"), Some(BOBBY)); + // Once Bob is streamed too, the roster leaves him to the object pass; unnamed, he is + // nobody's candidate. + let bob = world.spawn((Guid(BOB), GlobalTransform::default())).id(); + world.resource_mut::().0.insert(BOB, bob); + assert_eq!(find(&mut world, "Bob"), Some(BOBBY)); + } } diff --git a/crates/benilla-app/src/target/mod.rs b/crates/benilla-app/src/target/mod.rs index 08235ac7f..ca551339d 100644 --- a/crates/benilla-app/src/target/mod.rs +++ b/crates/benilla-app/src/target/mod.rs @@ -76,7 +76,9 @@ pub(crate) use scan::LastEnemy; pub(crate) use scan::{AttackNearestRequest, AttackPick, CreatureTypes}; // The chat layer's by-name asks (`/target`, `/assist`), and the typemask `TargetByName`'s // candidate feed shares. -pub(crate) use by_name::{AssistRequest, Candidacy, NameSearch, PlayerLookup, TargetByNameRequest}; +pub(crate) use by_name::{ + assistable_alive, AssistRequest, Candidacy, NameSearch, PlayerLookup, TargetByNameRequest, +}; // The one SetSelection path, for the loot response's select (`0x48f3a0`). pub(crate) use by_name::SelectCommit; // The reaction decode and its faction catalog, which also tint the target frame diff --git a/crates/benilla-app/src/ui_chat/input/mod.rs b/crates/benilla-app/src/ui_chat/input/mod.rs index 809387c05..61ef469ef 100644 --- a/crates/benilla-app/src/ui_chat/input/mod.rs +++ b/crates/benilla-app/src/ui_chat/input/mod.rs @@ -34,26 +34,22 @@ fn target_player_name( } /// The target guid a `CMSG_TEXT_EMOTE` carries (`DoEmote`'s caller, `0x49fdb1`): the selection, -/// unless the argument is a non-empty word not starting with `%`, which names a player through -/// `named` (the `0x493aa0` player search) and sends guid 0 on a miss. Either way an emote at -/// yourself goes out untargeted (`0x5ef611`), so 1.12 has no self-emote sentence. Compared by -/// entity, which agrees with the guid: [`Selection`]'s one writer sets both from one streamed -/// entity. +/// unless the argument is a non-empty word not starting with `%` (`0x49fdd4`), which names a +/// player through `named` (the `0x493aa0` player search, roster passes included) and sends guid 0 +/// on a miss. Either way an emote at yourself goes out untargeted (`0x5ef611`), so 1.12 has no +/// self-emote sentence. pub(super) fn emote_target( arg: Option<&str>, selection: &Selection, - named: impl FnOnce(&str) -> Option<(Entity, u64)>, - me: Option, + named: impl FnOnce(&str) -> Option, + me: Option, ) -> u64 { - let (entity, guid) = match arg.filter(|a| !a.is_empty() && !a.starts_with('%')) { - Some(name) => match named(name) { - Some((entity, guid)) => (Some(entity), Some(guid)), - None => (None, None), - }, - None => (selection.target, selection.guid), + let guid = match arg.filter(|a| !a.is_empty() && !a.starts_with('%')) { + Some(name) => named(name), + None => selection.guid, }; match guid { - Some(guid) if !(me.is_some() && entity == me) => guid, + Some(guid) if me != Some(guid) => guid, _ => 0, } } @@ -599,27 +595,9 @@ pub(super) fn drain_chat_input( if let Some(name) = name.or_else(|| target_player_name(&selection, &names, &commands)) { - // `CMSG_GROUP_SET_LEADER` takes a guid, resolved against the roster. A miss - // prints the server's error wording; the reference's `PromoteByName` miss is - // untraced. - match group - .members - .iter() - .find(|m| m.name.eq_ignore_ascii_case(&name)) - { - Some(m) => { - let _ = commands - .0 - .send(ClientCommand::GroupSetLeader { guid: m.guid }); - } - None => { - // `ERR_TARGET_NOT_IN_GROUP_S` (`GlobalStrings.lua:1861`). - chat_log.push_event(super::event::ChatEvent::text_only( - super::event::ChatEventKind::System, - format!("{name} is not in your party."), - )); - } - } + // The binding's own resolve and queue (`PromoteByName 0x48a86a`); a miss is + // silent there. + script.promote_by_name(&name); } } // The duel verbs join the intent queue `StartDuel` and `CancelDuel` feed: the stock @@ -628,7 +606,7 @@ pub(super) fn drain_chat_input( if let Some(name) = name.or_else(|| target_player_name(&selection, &names, &commands)) { - script.queue_duel_request(benilla_ui::script::DuelRequest::StartByName(name)); + script.start_duel_by_name(&name); } } ParsedChat::Forfeit => { @@ -797,8 +775,8 @@ pub(super) fn drain_chat_input( let target = emote_target( arg.as_deref(), &selection, - |name| chat_out.players.find(&names, name), - self_player.single().ok().map(|(entity, _, _)| entity), + |name| chat_out.players.find(&names, &group, guids, name), + self_guid.0, ); match commands .0 diff --git a/crates/benilla-app/src/ui_chat/tests.rs b/crates/benilla-app/src/ui_chat/tests.rs index 202366ef7..765b7272a 100644 --- a/crates/benilla-app/src/ui_chat/tests.rs +++ b/crates/benilla-app/src/ui_chat/tests.rs @@ -153,72 +153,55 @@ fn text_emote_lines_are_verbatim_and_never_wear_the_senders_name() { /// `DoEmote` sends a self-target as guid 0 (`0x5ef611`), so 1.12 has no self-emote sentence. #[test] fn emoting_at_your_own_selection_sends_an_untargeted_emote() { - let _data = benilla_formats::wow_data_or_skip!(); use crate::target::Selection; - use bevy::prelude::Entity; - - let me = Entity::from_raw_u32(7).unwrap(); - let them = Entity::from_raw_u32(9).unwrap(); let sel = Selection { - target: Some(me), - guid: Some(0xdead_beef), + guid: Some(0x111), ..Default::default() }; - assert_eq!(emote_target(None, &sel, no_name, Some(me)), 0); + assert_eq!(emote_target(None, &sel, no_name, Some(0x111)), 0); + assert_eq!(emote_target(None, &sel, no_name, Some(0x222)), 0x111); - let sel = Selection { - target: Some(them), - guid: Some(0xdead_beef), - ..Default::default() - }; - assert_eq!(emote_target(None, &sel, no_name, Some(me)), 0xdead_beef); - - // No selection is untargeted, and with no self entity yet a selection goes out untouched. + // No selection is untargeted, and with no self guid yet a selection goes out untouched. assert_eq!( - emote_target(None, &Selection::default(), no_name, Some(me)), + emote_target(None, &Selection::default(), no_name, Some(0x111)), 0 ); - let sel = Selection { - target: Some(them), - guid: Some(0xdead_beef), - ..Default::default() - }; - assert_eq!(emote_target(None, &sel, no_name, None), 0xdead_beef); + assert_eq!(emote_target(None, &sel, no_name, None), 0x111); } -fn no_name(_: &str) -> Option<(bevy::prelude::Entity, u64)> { +fn no_name(_: &str) -> Option { None } -/// `0x49fdb1`: a word not starting with `%` names a player and replaces the selection; a miss is -/// guid 0; no argument or a `%` word is the selection. +/// `0x49fdb1`: a word not starting with `%` (`0x49fdd4`) names a player and replaces the +/// selection; a miss is guid 0; no argument or a `%` word is the selection. #[test] fn an_emote_argument_targets_the_named_player_and_not_the_selection() { use crate::target::Selection; - use bevy::prelude::Entity; - let me = Entity::from_raw_u32(7).unwrap(); - let bob = Entity::from_raw_u32(9).unwrap(); let sel = Selection { - target: Some(Entity::from_raw_u32(11).unwrap()), guid: Some(0x5e1), ..Default::default() }; - let find = |n: &str| (n == "Bob").then_some((bob, 0xb0b)); - assert_eq!(emote_target(Some("Bob"), &sel, find, Some(me)), 0xb0b); + let find = |n: &str| (n == "Bob").then_some(0xb0b); + assert_eq!(emote_target(Some("Bob"), &sel, find, Some(0x111)), 0xb0b); assert_eq!( - emote_target(Some("Nobody"), &sel, find, Some(me)), + emote_target(Some("Nobody"), &sel, find, Some(0x111)), 0, "a miss is untargeted" ); for arg in [None, Some(""), Some("%t"), Some("%x")] { - let panics = |_: &str| -> Option<(Entity, u64)> { panic!("no search for {arg:?}") }; - assert_eq!(emote_target(arg, &sel, panics, Some(me)), 0x5e1, "{arg:?}"); + let panics = |_: &str| -> Option { panic!("no search for {arg:?}") }; + assert_eq!( + emote_target(arg, &sel, panics, Some(0x111)), + 0x5e1, + "{arg:?}" + ); } // Naming yourself is the self-target edge: untargeted. - let own = |_: &str| Some((me, 0x111)); - assert_eq!(emote_target(Some("Me"), &sel, own, Some(me)), 0); + let own = |_: &str| Some(0x111); + assert_eq!(emote_target(Some("Me"), &sel, own, Some(0x111)), 0); } #[test] diff --git a/crates/benilla-app/src/ui_duel.rs b/crates/benilla-app/src/ui_duel.rs index 94027fa4b..4c1495c26 100644 --- a/crates/benilla-app/src/ui_duel.rs +++ b/crates/benilla-app/src/ui_duel.rs @@ -373,7 +373,6 @@ fn drain_duel( selection: Res, index: Res, self_q: Query<&Guid, With>, - names: Res, commands: Res, ) { let Some(mut script) = script else { @@ -410,12 +409,9 @@ fn drain_duel( }; challenge(guid, self_guid, &index, &spells, &actions, &commands); } - DuelRequest::StartByName(name) => { - // `/duel `: `StartDuel` (`0x4d4c40`) matches the name through `0x493aa0` - // with typemask `0x10` (`0x4d4c66`), players only; here, the streamed guid index - // named through the cache. - let guid = streamed_player_named(&name, &index, &names); - challenge(guid, self_guid, &index, &spells, &actions, &commands); + DuelRequest::StartByGuid(guid) => { + // `/duel `: the binding resolved the name through `0x493aa0` (`0x4d4c6d`). + challenge(Some(guid), self_guid, &index, &spells, &actions, &commands); } } } diff --git a/crates/benilla-app/src/ui_party/feed.rs b/crates/benilla-app/src/ui_party/feed.rs index 5b859214d..ee68602f1 100644 --- a/crates/benilla-app/src/ui_party/feed.rs +++ b/crates/benilla-app/src/ui_party/feed.rs @@ -614,29 +614,6 @@ fn raid_name_of( .map(|m| m.name.clone()) } -/// A name to the guid `CMSG_GROUP_SET_LEADER` and `CMSG_GROUP_ASSISTANT_LEADER` want (UnitPopup -/// addresses raid rows by name), matched case-insensitively like every roster name compare. -fn raid_guid_for_name( - group: &GroupState, - self_guid: Option, - names: &NameCache, - name: &str, -) -> Option { - if let Some(g) = self_guid { - if names - .resolve_unit(g, None, Ask::Read) - .is_some_and(|n| n.eq_ignore_ascii_case(name)) - { - return Some(g); - } - } - group - .members - .iter() - .find(|m| m.name.eq_ignore_ascii_case(name)) - .map(|m| m.guid) -} - /// `GetRaidRosterInfo`'s array (`0x4bb560`) in [`raid_row_guids`]' order: empty outside a raid, /// so `GetNumRaidMembers()` answers 0 in a party. The reference's array holds the local player /// and the wire's list does not, so our row comes from [`RaidSelf`]. @@ -956,17 +933,14 @@ pub(crate) fn drain_party( .send(ClientCommand::GroupSwapSubGroup { name, other }); } } - PartyRequest::PromoteName(name) => { - if let Some(guid) = raid_guid_for_name(&group, self_guid, &names, &name) { - let _ = commands.0.send(ClientCommand::GroupSetLeader { guid }); - } + // The binding resolved the name (`0x48a86a`, `0x4bbd6b`, `0x4bbe3b`). + PartyRequest::PromoteGuid(guid) => { + let _ = commands.0.send(ClientCommand::GroupSetLeader { guid }); } - PartyRequest::AssistantLeader { name, grant } => { - if let Some(guid) = raid_guid_for_name(&group, self_guid, &names, &name) { - let _ = commands - .0 - .send(ClientCommand::GroupAssistantLeader { guid, grant }); - } + PartyRequest::AssistantLeader { guid, grant } => { + let _ = commands + .0 + .send(ClientCommand::GroupAssistantLeader { guid, grant }); } PartyRequest::UninviteRaid(index) => { // Sent by name. The reference's `UninviteFromRaid` and `UninviteFromParty` share @@ -1016,7 +990,7 @@ fn test_apply_local( | PartyRequest::SetSubgroup { .. } | PartyRequest::SwapSubgroup { .. } | PartyRequest::UninviteRaid(_) - | PartyRequest::PromoteName(_) + | PartyRequest::PromoteGuid(_) | PartyRequest::AssistantLeader { .. } ) { group.count_list(); @@ -1129,22 +1103,14 @@ fn apply_test_intent( } true } - PartyRequest::PromoteName(name) => { - if let Some(m) = group - .members - .iter() - .find(|m| m.name.eq_ignore_ascii_case(name)) - { - group.leader = m.guid; + PartyRequest::PromoteGuid(guid) => { + if group.members.iter().any(|m| m.guid == *guid) { + group.leader = *guid; } true } - PartyRequest::AssistantLeader { name, grant } => { - if let Some(m) = group - .members - .iter_mut() - .find(|m| m.name.eq_ignore_ascii_case(name)) - { + PartyRequest::AssistantLeader { guid, grant } => { + if let Some(m) = group.members.iter_mut().find(|m| m.guid == *guid) { if *grant { m.flags |= GROUP_MEMBER_ASSISTANT; } else { @@ -2174,13 +2140,6 @@ mod tests { ); assert_eq!(raid_name_of(&group, me, &names, 0xDEAD), None); - assert_eq!( - raid_guid_for_name(&group, me, &names, "alice"), - Some(0xA11CE) - ); - assert_eq!(raid_guid_for_name(&group, me, &names, "KEL"), Some(0x5E1F)); - assert_eq!(raid_guid_for_name(&group, me, &names, "Nobody"), None); - // Outside a raid all are empty, so a raid verb in a party sends nothing. group.group_type = 0; assert!(raid_row_guids(&group, me).is_empty()); diff --git a/crates/benilla-app/src/ui_script/duel_tests.rs b/crates/benilla-app/src/ui_script/duel_tests.rs index 0fbcf4552..cf0c4bb73 100644 --- a/crates/benilla-app/src/ui_script/duel_tests.rs +++ b/crates/benilla-app/src/ui_script/duel_tests.rs @@ -119,6 +119,21 @@ fn finishing_sweeps_both_dialogs_silently() { fn the_era_globals_queue_their_intents() { benilla_formats::wow_data_or_skip!(); let mut s = setup(); + s.set_unit( + "player", + Some(benilla_ui::script::UnitState { + exists: true, + has_object: true, + ..Default::default() + }), + ); + s.set_party(benilla_ui::script::PartyState { + members: vec![benilla_ui::script::PartyMemberInfo { + name: "Onerogue".into(), + guid: 0x0E, + }], + ..Default::default() + }); s.run("AcceptDuel(); CancelDuel(); StartDuel('Onerogue'); StartDuelUnit('target')") .unwrap(); assert_eq!( @@ -126,7 +141,7 @@ fn the_era_globals_queue_their_intents() { vec![ DuelRequest::Accept, DuelRequest::Cancel, - DuelRequest::StartByName("Onerogue".into()), + DuelRequest::StartByGuid(0x0E), DuelRequest::StartByUnit("target".into()), ] ); diff --git a/crates/benilla-app/src/ui_script/raid_tests.rs b/crates/benilla-app/src/ui_script/raid_tests.rs index a12b97d94..78e6e67b1 100644 --- a/crates/benilla-app/src/ui_script/raid_tests.rs +++ b/crates/benilla-app/src/ui_script/raid_tests.rs @@ -564,13 +564,22 @@ fn the_row_menu_offers_the_rank_verbs_by_rank() { ); } -/// Three verbs go by name and the kick by row index (`UnitPopup.lua:624-631`). +/// Three verbs go by name, resolved to a guid by the binding, and the kick by row index (`UnitPopup.lua:624-631`). #[test] fn the_menu_verbs_queue_the_right_requests() { let _data = benilla_formats::wow_data_or_skip!(); let mut s = setup(); open_raid_tab(&mut s); push_raid(&mut s, twelve()); + // The active player object, which the by-name resolver wants (`0x493ae0`). + s.set_unit( + "player", + Some(benilla_ui::script::UnitState { + exists: true, + has_object: true, + ..Default::default() + }), + ); let click = |s: &UiScript, key: &str| { s.run(&format!( "for i = 1, UIDROPDOWNMENU_MAXBUTTONS do \ @@ -585,7 +594,7 @@ fn the_menu_verbs_queue_the_right_requests() { assert_eq!( s.take_party_requests(), vec![PartyRequest::AssistantLeader { - name: "Member2".into(), + guid: twelve()[2].guid, grant: true }] ); diff --git a/crates/benilla-app/src/ui_unit.rs b/crates/benilla-app/src/ui_unit.rs index fe989cf4f..6948ae6e0 100644 --- a/crates/benilla-app/src/ui_unit.rs +++ b/crates/benilla-app/src/ui_unit.rs @@ -3582,6 +3582,7 @@ mod tests { ..Default::default() }, selectable: true, + assistable_alive: true, }), ); assert_eq!( diff --git a/crates/benilla-app/src/ui_unit/held.rs b/crates/benilla-app/src/ui_unit/held.rs index 4f686f566..bc0d2941f 100644 --- a/crates/benilla-app/src/ui_unit/held.rs +++ b/crates/benilla-app/src/ui_unit/held.rs @@ -312,6 +312,13 @@ pub(crate) fn feed_name_candidates( dist2, state, selectable: crate::target::is_selectable(store.as_deref(), self_guid), + assistable_alive: crate::target::assistable_alive( + store.as_deref(), + factions.as_deref(), + &reputations, + me.and_then(|(_, _, s)| s), + by_guid, + ), }), ); memo.pushed.insert(guid, (name.to_string(), record)); diff --git a/crates/benilla-ui/src/script/duel.rs b/crates/benilla-ui/src/script/duel.rs index 47aa79588..38295b94c 100644 --- a/crates/benilla-ui/src/script/duel.rs +++ b/crates/benilla-ui/src/script/duel.rs @@ -6,6 +6,7 @@ use mlua::Lua; +use super::by_name::Filter; use super::protected::{self, Tag}; use super::Model; @@ -17,9 +18,9 @@ pub enum DuelRequest { /// `CancelDuel()`: `CMSG_DUEL_CANCELLED`, which the server reads by duel state as a decline, /// a cancel or a forfeit. Cancel, - /// `StartDuel(name)`: the reference resolves the name through `0x493aa0`, players only, and - /// does nothing on a miss. - StartByName(String), + /// `StartDuel(name)` after the resolver (`0x4d4c6d`, players only, no filter): the duel spell + /// at the guid it returned, nothing on a miss. + StartByGuid(u64), /// `StartDuelUnit(unit)`, the unit popup's Duel row. The app casts only at a player; the /// reference resolves the token (`0x515970`) with no player gate of its own. StartByUnit(String), @@ -31,6 +32,11 @@ impl super::UiScript { std::mem::take(&mut self.model_mut().duel_requests) } + /// `StartDuel(name)` for the app's Rust slash parser: the binding's own resolve and queue. + pub fn start_duel_by_name(&mut self, name: &str) { + start_duel_by_name(&mut self.model_mut(), name); + } + /// Queue an intent from the app's Rust slash parser: `/duel` and `/forfeit`, which the /// reference's `SlashCmdList` handlers send through `StartDuel` and `CancelDuel`. pub fn queue_duel_request(&mut self, request: DuelRequest) { @@ -38,6 +44,14 @@ impl super::UiScript { } } +/// `StartDuel` (`0x4d4c40`): `0x493aa0` with typemask 0x10 and mode 0 (`0x4d4c6d`), then the duel +/// spell at the guid (`0x4d4810`); a zero guid does nothing (`0x4d4c76`). +fn start_duel_by_name(model: &mut Model, name: &str) { + if let Some(guid) = model.closest_player(name, Filter::AcceptAll) { + model.duel_requests.push(DuelRequest::StartByGuid(guid)); + } +} + /// Register the duel globals. pub(super) fn install(lua: &Lua) -> mlua::Result<()> { let g = lua.globals(); @@ -68,7 +82,7 @@ pub(super) fn install(lua: &Lua) -> mlua::Result<()> { // gate's tag 2 (`0x6e4bc1`). if protected::gate(lua, Tag::CAST) { let mut model = lua.app_data_mut::().expect("model app_data"); - model.duel_requests.push(DuelRequest::StartByName(name)); + start_duel_by_name(&mut model, &name); } Ok(()) })?, @@ -87,3 +101,85 @@ pub(super) fn install(lua: &Lua) -> mlua::Result<()> { Ok(()) } + +#[cfg(test)] +mod tests { + use super::*; + use crate::script::{NameCandidate, PartyMemberInfo, PartyState, UiScript, UnitState}; + + fn player_vm(members: &[(&str, u64)]) -> UiScript { + let mut s = UiScript::new().unwrap(); + s.set_unit( + "player", + Some(UnitState { + exists: true, + has_object: true, + ..Default::default() + }), + ); + s.set_party(PartyState { + members: members + .iter() + .map(|(name, guid)| PartyMemberInfo { + name: (*name).into(), + guid: *guid, + }) + .collect(), + ..Default::default() + }); + s + } + + fn held(s: &mut UiScript, guid: u64, name: &str, dist2: f32, is_player: bool) { + s.set_name_candidate( + guid, + Some(NameCandidate { + name: name.into(), + dist2, + state: UnitState { + exists: true, + has_object: true, + guid, + is_player, + ..Default::default() + }, + selectable: true, + assistable_alive: false, + }), + ); + } + + /// `StartDuel` resolves through `0x493aa0` with typemask 0x10 and mode 0 (`0x4d4c6d`): a prefix + /// finds a groupmate with no object, a held player outside the group answers when nearer or + /// longer, accept-all means even a dead or hostile one, a creature is outside the typemask, + /// and a miss queues nothing. + #[test] + fn start_duel_resolves_a_player_by_prefix_in_or_out_of_the_group() { + let mut s = player_vm(&[("Onerogue", 0x0E)]); + s.run("StartDuel('One')").unwrap(); + assert_eq!(s.take_duel_requests(), vec![DuelRequest::StartByGuid(0x0E)]); + // A held stranger with the same prefix is nearer than the roster's placeholder. + held(&mut s, 0x77, "Onemage", 40.0, true); + s.run("StartDuel('One')").unwrap(); + assert_eq!(s.take_duel_requests(), vec![DuelRequest::StartByGuid(0x77)]); + // A creature is no candidate. + let mut s = player_vm(&[]); + held(&mut s, 0xF1, "Onewolf", 1.0, false); + s.run("StartDuel('One')").unwrap(); + assert!(s.take_duel_requests().is_empty()); + // No shared first letter, and no active player object (`0x493ae0`). + let mut s = player_vm(&[("Onerogue", 0x0E)]); + s.run("StartDuel('Zed')").unwrap(); + assert!(s.take_duel_requests().is_empty()); + let mut s = UiScript::new().unwrap(); + s.set_party(PartyState { + members: vec![PartyMemberInfo { + name: "Onerogue".into(), + guid: 0x0E, + }], + ..Default::default() + }); + s.run("StartDuel('One')").unwrap(); + assert!(s.take_duel_requests().is_empty()); + } +} diff --git a/crates/benilla-ui/src/script/party.rs b/crates/benilla-ui/src/script/party.rs index e440d48b9..a818e6abd 100644 --- a/crates/benilla-ui/src/script/party.rs +++ b/crates/benilla-ui/src/script/party.rs @@ -11,6 +11,7 @@ use mlua::{Lua, MultiValue, Value}; use super::binding_abi::{self, number_arg}; +use super::by_name::Filter; use super::Model; use crate::strings::{fill, global, Arg}; @@ -142,10 +143,11 @@ pub enum PartyRequest { /// `SwapRaidSubgroup(index, other)`: trade two raid rows' subgroups /// (`CMSG_GROUP_SWAP_SUB_GROUP`, two names on the wire). SwapSubgroup { index: u32, other: u32 }, - /// `PromoteByName(name)` (`CMSG_GROUP_SET_LEADER`, whose guid the app resolves). - PromoteName(String), - /// `PromoteToAssistant(name)` / `DemoteAssistant(name)` (`CMSG_GROUP_ASSISTANT_LEADER`). - AssistantLeader { name: String, grant: bool }, + /// `PromoteByName(name)` after the resolver (`0x48a86a`): `CMSG_GROUP_SET_LEADER` with the guid. + PromoteGuid(u64), + /// `PromoteToAssistant(name)` / `DemoteAssistant(name)` after the resolver (`0x4bbd6b`, + /// `0x4bbe3b`): `CMSG_GROUP_ASSISTANT_LEADER` with the guid. + AssistantLeader { guid: u64, grant: bool }, /// `UninviteFromRaid(index)`: a 1-based raid row the app resolves to the name /// `CMSG_GROUP_UNINVITE` takes. UninviteRaid(u32), @@ -244,6 +246,11 @@ impl super::UiScript { std::mem::take(&mut self.model_mut().ready_check.lines) } + /// `PromoteByName(name)` for the app's Rust slash parser: the binding's own resolve and queue. + pub fn promote_by_name(&mut self, name: &str) { + promote_by_name(&mut self.model_mut(), name); + } + /// Drain the party/loot intents queued since the last call. pub fn take_party_requests(&mut self) -> Vec { std::mem::take(&mut self.model_mut().party_requests) @@ -258,98 +265,34 @@ impl super::UiScript { /// `SetLootMethod`'s usage line (`0x84c42c`). const USAGE_SET_LOOT_METHOD: &str = "Usage: SetLootMethod(\"method\" [,master][,threshold])"; -/// `CGGameUI::ClosestObjectMatch` (`0x493aa0`) as `SetLootMethod` calls it (mode 2, `0x4e9418`), -/// over the group: the best guid for `name`, or `None`. -/// -/// The reference runs three passes, each offering a name to the matcher `0x493c60`. First the four -/// party slots in order (`0x493b22`), then the raid roster in order (`0x493ba7`), each only when -/// the member has no object held (`0x468460` NULL), at the placeholder distance `0x4f1502f9` -/// (`0x493b74`, `0x493c0c`); then every held living player by real distance (`0x468380` with -/// `0x493d30`, mode 2's filter `0x493eca`). The matcher takes a name equal without case at once -/// when its distance is below the best so far (`0x493c7f`..`0x493c93`); otherwise the length of -/// the case-folded prefix it shares with `name` (`0x493cc0`..`0x493cee`) must reach the best -/// length, which starts at 1, and a longer prefix wins outright while an equal one needs a -/// smaller distance (`0x493cf8`..`0x493d09`). So `"Bo"` finds "Bob", the first of several equal -/// prefixes in roster order keeps the place, and a name sharing no first letter finds nobody. -/// -/// Not modelled: held players outside the group, which the reference's third pass also offers, -/// at real distances; and the real distances among held group members, which keep roster order. -fn closest_group_member(model: &Model, name: &str) -> Option { - struct Best<'a> { - search: &'a [u8], - guid: Option, - len: usize, - distance: f32, +/// `PromoteByName`: `0x493aa0` with typemask 0x10 and mode 2 (`0x48a86a`), then +/// `CMSG_GROUP_SET_LEADER` (`0x78`) for the guid it returns; a zero guid sends nothing, silently +/// (`0x48a875`). No membership test: the server judges the guid. +fn promote_by_name(model: &mut Model, name: &str) { + if let Some(guid) = model.closest_player(name, Filter::AssistableAlive) { + model.party_requests.push(PartyRequest::PromoteGuid(guid)); } - impl Best<'_> { - /// `0x493c60`; `true` once an exact name ends the search. - fn offer(&mut self, candidate: &str, guid: u64, distance: f32) -> bool { - let cand = candidate.as_bytes(); - if cand.eq_ignore_ascii_case(self.search) && distance < self.distance { - self.guid = Some(guid); - return true; - } - let len = cand - .iter() - .zip(self.search) - .take_while(|(c, s)| c.eq_ignore_ascii_case(s)) - .count(); - if len > self.len || (len == self.len && distance < self.distance) { - self.guid = Some(guid); - self.len = len; - self.distance = distance; - } - false - } +} + +/// `PromoteToAssistant` (`0x4bbd6b`) and `DemoteAssistant` (`0x4bbe3b`): the same resolver call, +/// then `CMSG_GROUP_ASSISTANT_LEADER` (`0x28f`) with the guid and a byte, 1 or 0. +fn assistant_by_name(model: &mut Model, name: &str, grant: bool) { + if let Some(guid) = model.closest_player(name, Filter::AssistableAlive) { + model + .party_requests + .push(PartyRequest::AssistantLeader { guid, grant }); } - /// The placeholder distance the roster passes hand the matcher (`0x4f1502f9`). - const ROSTER_DISTANCE: f32 = f32::from_bits(0x4f15_02f9); +} + +/// Whether `guid` is ourselves or on the party slots (`0x4e7f70`), or on the raid roster +/// (`0x4baee0`); a zero guid is neither. +fn is_group_member(lua: &Lua, guid: u64) -> bool { + let model = lua.app_data_ref::().expect("model app_data"); let party = &model.party; - let held = |token: String| model.unit(&token).is_some_and(|u| u.has_object); - let mut best = Best { - search: name.as_bytes(), - guid: None, - len: 1, - distance: f32::MAX, - }; - let mut near: Vec<(&str, u64)> = Vec::new(); - let roster = party - .members - .iter() - .take(4) - .enumerate() - .map(|(i, m)| (m.name.as_str(), m.guid, held(format!("party{}", i + 1)))) - .chain(party.raid.iter().enumerate().map(|(i, m)| { - let me = party.own_guid != 0 && m.guid == party.own_guid; - ( - m.name.as_str(), - m.guid, - me || held(format!("raid{}", i + 1)), - ) - })); - for (candidate, guid, is_held) in roster { - if guid == 0 || candidate.is_empty() { - continue; - } - if is_held { - near.push((candidate, guid)); - } else if best.offer(candidate, guid, ROSTER_DISTANCE) { - return best.guid; - } - } - // The player's own object is the nearest (`0x493d30` measures from it). - let own = model.unit("player").and_then(|u| u.name.as_deref()); - if let Some(own) = own.filter(|n| !n.is_empty() && party.own_guid != 0) { - if best.offer(own, party.own_guid, 0.0) { - return best.guid; - } - } - for (i, (candidate, guid)) in near.into_iter().enumerate() { - if best.offer(candidate, guid, 1.0 + i as f32) { - break; - } - } - best.guid + guid != 0 + && (guid == party.own_guid + || party.members.iter().take(4).any(|m| m.guid == guid) + || party.raid.iter().any(|m| m.guid == guid)) } /// The checks both loot setters open with: not in a group (the first party guid and the raid @@ -675,9 +618,12 @@ pub(super) fn install(lua: &Lua) -> mlua::Result<()> { }; let found = { let model = lua.app_data_ref::().expect("model app_data"); - closest_group_member(&model, &name) + model.closest_player(&name, Filter::AssistableAlive) }; - let Some(guid) = found else { + // The pick must be ourselves (`0x4e7f70`, which also tests the four party slots) + // or in the raid (`0x4baee0`); a stranger the resolver preferred is refused with + // the typed name, and no next-best member is tried. + let Some(guid) = found.filter(|g| is_group_member(lua, *g)) else { chat_error(lua, "ERR_TARGET_NOT_IN_GROUP_S", &[Arg::S(&name)]); return Ok(()); }; @@ -793,8 +739,10 @@ pub(super) fn install(lua: &Lua) -> mlua::Result<()> { g.set( "PromoteByName", lua.create_function(|lua, name: String| { - let mut model = lua.app_data_mut::().expect("model app_data"); - model.party_requests.push(PartyRequest::PromoteName(name)); + promote_by_name( + &mut lua.app_data_mut::().expect("model app_data"), + &name, + ); Ok(()) })?, )?; @@ -803,9 +751,7 @@ pub(super) fn install(lua: &Lua) -> mlua::Result<()> { binding, lua.create_function(move |lua, name: String| { let mut model = lua.app_data_mut::().expect("model app_data"); - model - .party_requests - .push(PartyRequest::AssistantLeader { name, grant }); + assistant_by_name(&mut model, &name, grant); Ok(()) })?, )?; @@ -1322,6 +1268,7 @@ mod tests { #[test] fn intent_natives_queue_the_exact_request_sequence() { let mut s = UiScript::new().unwrap(); + hold(&mut s, "player", 0x5E1F, "Me"); s.set_party(led_party()); assert!(s.take_party_requests().is_empty()); @@ -1358,6 +1305,8 @@ mod tests { fn loot_vm(party: PartyState) -> UiScript { let mut s = UiScript::new().unwrap(); + // The active player object, without which the resolver finds nobody (`0x493ae0`). + hold(&mut s, "player", party.own_guid, "Me"); s.set_party(party); s.run( r#" @@ -1607,6 +1556,138 @@ mod tests { ); } + /// A held player the app's candidate feed pushes: `name` at `dist2`, `assistable_alive` as the + /// mode-2 filter reads it. + fn held_player( + guid: u64, + name: &str, + dist2: f32, + assistable_alive: bool, + ) -> crate::script::NameCandidate { + crate::script::NameCandidate { + name: name.into(), + dist2, + state: crate::script::UnitState { + exists: true, + has_object: true, + guid, + name: Some(name.into()), + is_player: true, + ..Default::default() + }, + selectable: true, + assistable_alive, + } + } + + /// The party token `token` has an object, so the roster passes leave it to the object pass. + fn hold(s: &mut UiScript, token: &str, guid: u64, name: &str) { + s.set_unit( + token, + Some(crate::script::UnitState { + exists: true, + has_object: true, + guid, + name: Some(name.into()), + ..Default::default() + }), + ); + } + + /// `0x493aa0` runs the object pass after the roster passes (`0x493c2c`), so an assistable + /// player in range outranks a groupmate with no object at an equal prefix (the roster's + /// placeholder distance is the larger, `0x4f1502f9`); the pick is then no groupmate and the + /// binding prints game error 0x49 with the typed name (`0x4e9440`, `esi` the argument). + #[test] + fn a_held_stranger_outranks_an_unheld_groupmate_and_is_refused() { + let mut s = loot_vm(led_party()); + s.set_name_candidate(0xB0B1, Some(held_player(0xB0B1, "Bobby", 25.0, true))); + s.run(r#"SetLootMethod("master", "Bo")"#).unwrap(); + assert!(s.take_party_requests().is_empty(), "Bobby is no groupmate"); + assert_eq!( + s.take_shown_chat_lines(), + vec![( + "ERR_TARGET_NOT_IN_GROUP_S", + "Bo is not in your group.".to_string() + )] + ); + // A longer prefix still wins at any distance: the unheld Bob answers "Bob". + s.run(r#"SetLootMethod("master", "Bob")"#).unwrap(); + assert_eq!(s.take_party_requests(), vec![loot_request(2, 0xB0B, 2)]); + // Only the matcher's best is tried: the stranger is not skipped for the next-best member. + let mut s = loot_vm(led_party()); + s.set_name_candidate(0xA1, Some(held_player(0xA1, "Alicia", 4.0, true))); + s.run(r#"SetLootMethod("master", "Ali")"#).unwrap(); + assert!(s.take_party_requests().is_empty()); + assert_eq!(s.take_shown_chat_lines().len(), 1); + } + + /// Mode 2's filter (`0x493eca`) is `CanAssist` and health above 0: a held groupmate who fails it + /// is not offered by the roster passes (they skip held members, `0x493b4d`) nor by the object + /// pass, so nobody resolves; and a creature is outside typemask 0x10. + #[test] + fn a_held_groupmate_who_is_dead_or_unassistable_is_not_resolved() { + let mut s = loot_vm(led_party()); + hold(&mut s, "party2", 0xB0B, "Bob"); + s.set_name_candidate(0xB0B, Some(held_player(0xB0B, "Bob", 9.0, false))); + s.run(r#"SetLootMethod("master", "Bob")"#).unwrap(); + assert!(s.take_party_requests().is_empty()); + assert_eq!(s.take_shown_chat_lines().len(), 1); + // Alive again, the same candidate resolves. + s.set_name_candidate(0xB0B, Some(held_player(0xB0B, "Bob", 9.0, true))); + s.run(r#"SetLootMethod("master", "Bob")"#).unwrap(); + assert_eq!(s.take_party_requests(), vec![loot_request(2, 0xB0B, 2)]); + // A held creature is outside the typemask, so its longer prefix does not displace the + // unheld groupmate Bob's. + let mut s = loot_vm(led_party()); + let mut cat = held_player(0xF130_0001, "Bobcat", 1.0, true); + cat.state.is_player = false; + s.set_name_candidate(0xF130_0001, Some(cat)); + s.run(r#"SetLootMethod("master", "Bobc")"#).unwrap(); + assert_eq!(s.take_party_requests(), vec![loot_request(2, 0xB0B, 2)]); + } + + /// `0x493ae0`: with no active player object the resolver finds nobody, a groupmate with no + /// object included, so the binding shows game error 0x49. + #[test] + fn without_the_player_object_the_master_name_finds_nobody() { + let mut s = UiScript::new().unwrap(); + s.set_party(led_party()); + s.run(r#"ERR_NOT_LEADER = "x" ERR_TARGET_NOT_IN_GROUP_S = "%s is not in your group.""#) + .unwrap(); + s.run(r#"SetLootMethod("master", "Bob")"#).unwrap(); + assert!(s.take_party_requests().is_empty()); + assert_eq!(s.take_shown_chat_lines().len(), 1); + } + + /// Of two held groupmates with an equal prefix the nearer wins (`0x493cfc`, strictly below the + /// best); the roster order decides nothing once both are held. + #[test] + fn of_two_held_groupmates_the_nearer_wins() { + let party = PartyState { + members: vec![ + PartyMemberInfo { + name: "Bob".into(), + guid: 0xB1, + }, + PartyMemberInfo { + name: "Bobby".into(), + guid: 0xB2, + }, + ], + ..led_party() + }; + for (bob, bobby, guid) in [(400.0, 16.0, 0xB2), (16.0, 400.0, 0xB1)] { + let mut s = loot_vm(party.clone()); + hold(&mut s, "party1", 0xB1, "Bob"); + hold(&mut s, "party2", 0xB2, "Bobby"); + s.set_name_candidate(0xB1, Some(held_player(0xB1, "Bob", bob, true))); + s.set_name_candidate(0xB2, Some(held_player(0xB2, "Bobby", bobby, true))); + s.run(r#"SetLootMethod("master", "Bo")"#).unwrap(); + assert_eq!(s.take_party_requests(), vec![loot_request(2, guid, 2)]); + } + } + #[test] fn set_raid_target_icon_queues_the_token_and_index() { let mut s = UiScript::new().unwrap(); @@ -1792,6 +1873,8 @@ mod tests { #[test] fn the_raid_verbs_queue_what_they_name() { let mut s = UiScript::new().unwrap(); + hold(&mut s, "player", 0x5E1F, "Me"); + s.set_party(two_member_party()); s.run( r#" ConvertToRaid() @@ -1815,13 +1898,13 @@ mod tests { index: 7, other: 12 }, - PartyRequest::PromoteName("Alice".into()), + PartyRequest::PromoteGuid(0xA11CE), PartyRequest::AssistantLeader { - name: "Bob".into(), + guid: 0xB0B, grant: true }, PartyRequest::AssistantLeader { - name: "Bob".into(), + guid: 0xB0B, grant: false }, PartyRequest::UninviteRaid(9), @@ -1832,6 +1915,57 @@ mod tests { assert!(s.take_party_requests().is_empty(), "the drain empties"); } + /// `PromoteByName`, `PromoteToAssistant` and `DemoteAssistant` call `0x493aa0` with typemask + /// 0x10 and mode 2 (`0x48a86a`, `0x4bbd6b`, `0x4bbe3b`) and send the guid it returns: a prefix + /// finds a groupmate with no object, a held stranger nearer than the roster's placeholder is + /// sent too (the server judges the guid), a held groupmate who is dead is not found, and a miss + /// sends nothing and prints nothing. + #[test] + fn the_leader_verbs_send_the_resolvers_guid_whoever_it_is() { + let calls = [ + (r#"PromoteByName("Ali")"#, false), + (r#"PromoteToAssistant("Ali")"#, true), + (r#"DemoteAssistant("Ali")"#, false), + ]; + let sent = |guid: u64, call: &str, grant: bool| { + if call.starts_with("Promote") && !call.contains("Assistant") { + PartyRequest::PromoteGuid(guid) + } else { + PartyRequest::AssistantLeader { guid, grant } + } + }; + for (call, grant) in calls { + // The prefix finds Alice, who has no object. + let mut s = loot_vm(two_member_party()); + s.run(call).unwrap(); + assert_eq!( + s.take_party_requests(), + vec![sent(0xA11CE, call, grant)], + "{call}" + ); + // A held stranger "Alina" is nearer than the placeholder and an equal prefix. + s.set_name_candidate(0x57, Some(held_player(0x57, "Alina", 30.0, true))); + s.run(call).unwrap(); + assert_eq!( + s.take_party_requests(), + vec![sent(0x57, call, grant)], + "{call}" + ); + // The same stranger dead is no candidate (`0x493eca`), so Alice answers again. + s.set_name_candidate(0x57, Some(held_player(0x57, "Alina", 30.0, false))); + s.run(call).unwrap(); + assert_eq!( + s.take_party_requests(), + vec![sent(0xA11CE, call, grant)], + "{call}" + ); + // No shared first letter: nothing is sent. + s.run(&call.replace("Ali", "Zed")).unwrap(); + assert!(s.take_party_requests().is_empty(), "{call}"); + assert!(s.take_shown_chat_lines().is_empty(), "{call}"); + } + } + /// The reference's No button passes no argument, Yes passes `1`. #[test] fn confirm_ready_check_treats_an_absent_argument_as_not_ready() { diff --git a/crates/benilla-ui/src/script/tests/protected_gate.rs b/crates/benilla-ui/src/script/tests/protected_gate.rs index 35d5ef6a4..944c27fe1 100644 --- a/crates/benilla-ui/src/script/tests/protected_gate.rs +++ b/crates/benilla-ui/src/script/tests/protected_gate.rs @@ -462,6 +462,22 @@ fn verbs_world(security: AddonSecurity) -> UiScript { ..Default::default() }], }); + // `StartDuel("Bob")` needs a name the resolver finds: the active player, and Bob in the party. + s.set_unit( + "player", + Some(crate::script::UnitState { + exists: true, + has_object: true, + ..Default::default() + }), + ); + s.set_party(crate::script::PartyState { + members: vec![crate::script::PartyMemberInfo { + name: "Bob".into(), + guid: 0xB0B, + }], + ..Default::default() + }); let slot = |name: &str, autocast| PetActionView { name: Some(name.into()), autocast_allowed: autocast, diff --git a/crates/benilla-ui/src/script/unit/by_name.rs b/crates/benilla-ui/src/script/unit/by_name.rs index 8574857e2..a447f8e0b 100644 --- a/crates/benilla-ui/src/script/unit/by_name.rs +++ b/crates/benilla-ui/src/script/unit/by_name.rs @@ -1,14 +1,28 @@ -//! The by-name resolver's ranking (`0x493aa0`), shared by the app's scan, which commits the pick, -//! and `TargetByName`, which shows it to the rest of its chunk: in the reference the binding -//! (`0x489d60`) commits through `SetSelection 0x493540` before it returns, so `UnitName("target")` -//! on the next line already names the new unit. A name matches whole-string first (`0x64a4c0` → CRT +//! The by-name resolver (`CGGameUI::ClosestObjectMatch 0x493aa0`), shared by every caller: the app's +//! `/target`, `/assist` and `/follow` scans, `TargetByName`, which shows the pick to the rest of its +//! chunk (in the reference the binding `0x489d60` commits through `SetSelection 0x493540` before it +//! returns, so `UnitName("target")` on the next line already names the new unit), and +//! `SetLootMethod`'s master name (`0x4e9418`). A name matches whole-string first (`0x64a4c0` → CRT //! `0x414310`), else by the longest common prefix (`0x493cb6`-`0x493cf6`), both case-insensitive. //! -//! Deviation: the reference ends the walk at the first whole-string hit (`0x493ca2`), so its pick -//! follows the object list's order; we rank exact, then longer prefix, then nearest -//! ([`Rank::beats`]), because the nearest namesake is the better pick, and a full tie goes to the -//! lower guid ([`Rank::beats_at`]), so the VM's walk and the app's scan pick the same unit whatever -//! order each walks in. +//! [`resolve`] runs the reference's three passes over the one matcher `0x493c60`: the four party +//! slots (`0x493b22`), then the raid roster (`0x493ba7`), each member offered only when no object is +//! held for it (`0x468460` NULL, `0x493b4d`, `0x493be5`), at the placeholder distance +//! `0x4f1502f9` (`0x493b74`, `0x493c0c`); then every held object of the typemask that the mode's +//! filter `0x493e40` passes, at its squared distance (`0x468380` with `0x493d30`). No pass is gated +//! on the typemask. The filter mode gates the roster instead: mode 1 skips both passes (`0x493b1a`) +//! and mode 3 only the raid pass (`0x493b93`); no caller passes either, so neither is modelled. +//! Without an active player object the whole resolver returns nothing (`0x493ae0`), roster passes +//! included ([`Search::active_player`]). +//! +//! Deviation: the reference's matcher takes a whole-string hit at once only when it is nearer than +//! the best so far (`0x493c88`-`0x493ca2`); an exact hit that is not nearer competes on prefix +//! length alone (`0x493cf8`-`0x493d09`), so a nearer "Bobby" walked first beats an exact "Bob", and +//! the pick follows the object list's order. We rank exact, then longer prefix, then nearest +//! ([`Rank::beats`]), because the namesake is the better pick, and a full tie between held objects +//! goes to the lower guid ([`Rank::beats_at`]), so the VM's walk and the app's scan pick the same +//! unit whatever order each walks in. The roster passes keep the reference's order: of equal ranks +//! the first member offered stays. use std::cmp::Ordering; @@ -92,6 +106,146 @@ pub fn rank(query: &str, name: &str, dist2: f32, mode: Match) -> Option { }) } +/// The distance the roster passes hand the matcher for a member with no object (`0x4f1502f9`, +/// pushed at `0x493b74` and `0x493c0c`), so any held object of an equal prefix is nearer. +pub const ROSTER_DISTANCE: f32 = f32::from_bits(0x4f15_02f9); + +/// Which held objects a search admits, the typemask argument (`edx` of `0x493aa0`). +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Kinds { + /// Typemask 8, creatures, pets and players (a player carries the UNIT bit): `TargetByName`. + AnyUnit, + /// Typemask 0x10, players only: `AssistByName`, `FollowByName`, `SetLootMethod`. + PlayerOnly, +} + +/// The per-object filter, the mode argument `0x493d30` hands `0x493e40`. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Filter { + /// Mode 0, which underflows the jump table's bound into accept-all: no range, facing, reaction, + /// liveness, visibility or self test. + AcceptAll, + /// Mode 2 (`0x493eca`): `CanAssist 0x6066f0` and `UNIT_FIELD_HEALTH > 0`. + AssistableAlive, +} + +/// One by-name search: the arguments of `0x493aa0`. +#[derive(Clone, Copy, Debug)] +pub struct Search<'q> { + /// The name as typed; the callers trim, the resolver does not. + pub query: &'q str, + pub kinds: Kinds, + pub filter: Filter, + /// The exact-only flag. + pub exact: Match, + /// An object is held for the active player; `0x493aa0` returns nothing without one (`0x493ae0`). + pub active_player: bool, +} + +/// A roster member as passes 1 and 2 see it. +#[derive(Clone, Copy, Debug)] +pub struct RosterEntry<'a> { + /// The name cache's answer for the member's guid; empty when it has none, which the matcher + /// skips (`0x493c68`). + pub name: &'a str, + pub guid: u64, + /// The object manager holds an object for the guid, which the roster passes then leave to + /// the object pass (`0x493b4d`, `0x493be5`). + pub held: bool, +} + +/// A held object as the object pass sees it; `id` is the caller's handle for it. +#[derive(Clone, Copy, Debug)] +pub struct Held<'a, T> { + pub id: T, + pub name: &'a str, + pub guid: u64, + /// Squared distance from the active player. + pub dist2: f32, + /// The guid is a player's, for [`Kinds::PlayerOnly`]. + pub is_player: bool, + /// [`Filter::AssistableAlive`]'s test; [`Filter::AcceptAll`] never reads it. + pub assistable_alive: bool, +} + +/// What [`resolve`] picked. +#[derive(Clone, Copy, Debug)] +pub struct Pick<'a, T> { + pub guid: u64, + pub name: &'a str, + pub rank: Rank, + /// The held object's handle; `None` for a roster member with no object. + pub object: Option, +} + +/// `CGGameUI::ClosestObjectMatch` (`0x493aa0`): the best guid for the search over the party +/// slots, the raid roster and the held objects, in that order, or `None`. +/// +/// The roster passes run the matcher `0x493c60` at one distance, so there it is the longest +/// prefix with the first member offered keeping the place on a tie, and a whole-string hit ends the +/// search at once only while nothing has been picked (`0x493c88` wants a distance below the best, +/// which a roster pick has already lowered to [`ROSTER_DISTANCE`]); a later whole-string hit +/// competes by its length like any prefix. A roster pick is therefore never ranked `exact`. The +/// object pass ranks by [`Rank::beats_at`]. +pub fn resolve<'a, T>( + search: Search<'_>, + party: impl IntoIterator>, + raid: impl IntoIterator>, + held: impl IntoIterator>, +) -> Option> { + if !search.active_player { + return None; + } + let mut best: Option> = None; + for member in party.into_iter().chain(raid) { + if member.held || member.guid == 0 || member.name.is_empty() { + continue; + } + let Some(r) = rank(search.query, member.name, ROSTER_DISTANCE, search.exact) else { + continue; + }; + let pick = Pick { + guid: member.guid, + name: member.name, + rank: Rank { exact: false, ..r }, + object: None, + }; + if r.exact && best.is_none() { + return Some(pick); + } + if best.as_ref().is_none_or(|b| pick.rank.beats(b.rank)) { + best = Some(pick); + } + } + for h in held { + let admitted = match search.kinds { + Kinds::AnyUnit => true, + Kinds::PlayerOnly => h.is_player, + } && match search.filter { + Filter::AcceptAll => true, + Filter::AssistableAlive => h.assistable_alive, + }; + if !admitted { + continue; + } + let Some(r) = rank(search.query, h.name, h.dist2, search.exact) else { + continue; + }; + if best + .as_ref() + .is_none_or(|b| r.beats_at(h.guid, b.rank, b.guid)) + { + best = Some(Pick { + guid: h.guid, + name: h.name, + rank: r, + object: Some(h.id), + }); + } + } + best +} + /// One unit `TargetByName` can pick (typemask 8: a creature, pet or player whose name is cached), /// as the app's by-name scan sees it: the name it ranks, its distance, and the snapshot the /// `"target"` token reads once it is picked. @@ -106,6 +260,9 @@ pub struct NameCandidate { /// `IsSelectable`, which `SetSelection` asks before it selects (`0x4935ee`): a pick that is not /// selectable leaves the selection and so the `"target"` view as it was. pub selectable: bool, + /// [`Filter::AssistableAlive`]'s test (`0x493eca`): `CanAssist` toward the active player and + /// `UNIT_FIELD_HEALTH > 0`. + pub assistable_alive: bool, } impl super::super::UiScript { @@ -146,24 +303,71 @@ impl Model { if query.is_empty() { return None; } - let mode = if exact { - Match::ExactOnly - } else { - Match::PrefixOk + let search = Search { + query, + kinds: Kinds::AnyUnit, + filter: Filter::AcceptAll, + exact: if exact { + Match::ExactOnly + } else { + Match::PrefixOk + }, + // The app pushes candidates only while it holds the active player. + active_player: true, }; - let mut best: Option<(Rank, u64, &NameCandidate)> = None; - for (&guid, c) in &self.name_candidates { - let Some(r) = rank(query, &c.name, c.dist2, mode) else { - continue; - }; - if best - .as_ref() - .is_none_or(|(b, g, _)| r.beats_at(guid, *b, *g)) - { - best = Some((r, guid, c)); - } - } - best.map(|(_, _, c)| c) + // No roster: the app selects a held unit only (`Selection::target` is an entity). + resolve( + search, + std::iter::empty(), + std::iter::empty(), + self.held_candidates(), + ) + .and_then(|pick| pick.object) + } + + /// The pushed candidates as the resolver's object pass sees them. + pub(crate) fn held_candidates(&self) -> impl Iterator> { + self.name_candidates.iter().map(|(&guid, c)| Held { + id: c, + name: &c.name, + guid, + dist2: c.dist2, + is_player: c.state.is_player, + assistable_alive: c.assistable_alive, + }) + } + + /// The guid `0x493aa0` resolves for a player's name typed to a binding (typemask 0x10, no + /// exact-only flag, `filter` the binding's mode): the party slots, then the raid roster, each + /// member offered while no object is held for it, then the pushed candidates. Our own row is + /// held, as the active player object always is, and is offered by the object pass at distance 0. + pub(crate) fn closest_player(&self, name: &str, filter: Filter) -> Option { + let party = &self.party; + let held = |token: String| self.unit(&token).is_some_and(|u| u.has_object); + let members = party + .members + .iter() + .take(4) + .enumerate() + .map(|(i, m)| RosterEntry { + name: &m.name, + guid: m.guid, + held: held(format!("party{}", i + 1)), + }); + let raid = party.raid.iter().enumerate().map(|(i, m)| RosterEntry { + name: &m.name, + guid: m.guid, + held: (party.own_guid != 0 && m.guid == party.own_guid) + || held(format!("raid{}", i + 1)), + }); + let search = Search { + query: name, + kinds: Kinds::PlayerOnly, + filter, + exact: Match::PrefixOk, + active_player: held("player".to_string()), + }; + resolve(search, members, raid, self.held_candidates()).map(|pick| pick.guid) } /// What `TargetUnit(token)` shows as `"target"`: the unit the token names when the object @@ -212,3 +416,178 @@ impl Model { self.target_view_moved = true; } } + +#[cfg(test)] +mod tests { + use super::*; + + fn roster(name: &str, guid: u64, held: bool) -> RosterEntry<'_> { + RosterEntry { name, guid, held } + } + + fn held(name: &str, guid: u64, dist2: f32) -> Held<'_, u64> { + Held { + id: guid, + name, + guid, + dist2, + is_player: true, + assistable_alive: true, + } + } + + fn search(query: &str) -> Search<'_> { + Search { + query, + kinds: Kinds::PlayerOnly, + filter: Filter::AcceptAll, + exact: Match::PrefixOk, + active_player: true, + } + } + + fn guid_of<'a>( + search: Search<'_>, + party: Vec>, + raid: Vec>, + held: Vec>, + ) -> Option { + resolve(search, party, raid, held).map(|p| p.guid) + } + + /// `0x493b4d` and `0x493be5` offer a member only when no object is held, and a name the cache + /// does not have, or a zero guid, is no candidate (`0x493c68`). + #[test] + fn the_roster_passes_offer_only_members_with_no_object() { + let party = vec![ + roster("Bob", 1, true), + roster("", 2, false), + roster("Bobby", 0, false), + ]; + assert_eq!(guid_of(search("Bo"), party, vec![], vec![]), None); + let party = vec![roster("Bob", 1, false)]; + assert_eq!(guid_of(search("Bo"), party, vec![], vec![]), Some(1)); + } + + /// The matcher keeps the first of equal prefixes (`0x493cf8`, a strict distance compare), the + /// party slots before the raid; a whole-string hit ends the search only while nothing is + /// picked, and later competes by its length (`0x493c88` against the lowered best). + #[test] + fn the_roster_passes_keep_the_first_of_equal_prefixes() { + let both = |first: &'static str, second: &'static str| { + guid_of( + search("Bob"), + vec![roster(first, 1, false)], + vec![roster(second, 2, false)], + vec![], + ) + }; + assert_eq!(both("Bobby", "Bobbo"), Some(1), "party before raid"); + assert_eq!( + both("Bobby", "Bob"), + Some(1), + "an exact name after a prefix of its length" + ); + assert_eq!(both("Bo", "Bob"), Some(2), "a longer prefix"); + assert_eq!( + both("Bob", "Bobby"), + Some(1), + "an exact name first ends the search" + ); + } + + /// The object pass runs after the roster passes at real distances, below the placeholder: an + /// equal prefix goes to the object, an exact name to the object over a roster prefix, and the + /// roster's exact name, first, ends the search before any object. + #[test] + fn the_object_pass_follows_the_roster_passes() { + let r = |name| vec![roster(name, 1, false)]; + assert_eq!( + guid_of(search("Bo"), r("Bob"), vec![], vec![held("Bobby", 9, 1e9)]), + Some(9) + ); + assert_eq!( + guid_of(search("Bob"), r("Bobby"), vec![], vec![held("Bob", 9, 1e9)]), + Some(9) + ); + assert_eq!( + guid_of(search("Bob"), r("Bob"), vec![], vec![held("Bob", 9, 1.0)]), + Some(1) + ); + assert_eq!( + guid_of( + search("Bobb"), + r("Bobby"), + vec![], + vec![held("Bobx", 9, 1.0)] + ), + Some(1), + "a longer prefix wins at the placeholder distance" + ); + } + + /// The typemask and the mode's filter bind the object pass alone; the roster passes ignore both. + #[test] + fn typemask_and_filter_bind_the_object_pass_only() { + let mut creature = held("Bobcat", 7, 1.0); + creature.is_player = false; + let mut dead = held("Bobby", 8, 1.0); + dead.assistable_alive = false; + let objects = || vec![creature, dead]; + let mode2 = Search { + filter: Filter::AssistableAlive, + ..search("Bob") + }; + assert_eq!(guid_of(mode2, vec![], vec![], objects()), None); + let any = Search { + kinds: Kinds::AnyUnit, + ..search("Bobc") + }; + assert_eq!(guid_of(any, vec![], vec![], objects()), Some(7)); + assert_eq!(guid_of(search("Bob"), vec![], vec![], objects()), Some(8)); + // An unheld dead groupmate is still offered: the client cannot know. + assert_eq!( + guid_of(mode2, vec![roster("Bobby", 3, false)], vec![], objects()), + Some(3) + ); + } + + /// Exact-only applies to every pass (`0x493cab`), and between held namesakes the nearer wins, + /// a full tie going to the lower guid. + #[test] + fn exact_only_and_the_object_tiebreaks() { + let exact = Search { + exact: Match::ExactOnly, + ..search("Bob") + }; + assert_eq!( + guid_of( + exact, + vec![roster("Bobby", 1, false)], + vec![], + vec![held("Bobbo", 2, 1.0)] + ), + None + ); + let near_far = vec![held("Bob", 5, 9.0), held("Bob", 4, 4.0)]; + assert_eq!(guid_of(search("Bob"), vec![], vec![], near_far), Some(4)); + let tie = vec![held("Bob", 5, 4.0), held("Bob", 4, 4.0)]; + assert_eq!(guid_of(search("Bob"), vec![], vec![], tie), Some(4)); + } + + /// `0x493ae0`: without an active player object the resolver returns nothing, the roster passes + /// included. + #[test] + fn no_active_player_resolves_nothing() { + let none = Search { + active_player: false, + ..search("Bob") + }; + let party = || vec![roster("Bob", 1, false)]; + assert_eq!( + guid_of(none, party(), vec![], vec![held("Bob", 2, 1.0)]), + None + ); + assert_eq!(guid_of(search("Bob"), party(), vec![], vec![]), Some(1)); + } +} diff --git a/crates/benilla-ui/src/script/unit/tests.rs b/crates/benilla-ui/src/script/unit/tests.rs index b8f82d5cc..4b7394598 100644 --- a/crates/benilla-ui/src/script/unit/tests.rs +++ b/crates/benilla-ui/src/script/unit/tests.rs @@ -1063,6 +1063,7 @@ fn candidate(guid: u64, name: &str, dist2: f32) -> crate::script::NameCandidate ..Default::default() }, selectable: true, + assistable_alive: true, } } diff --git a/docs/DEVIATIONS.md b/docs/DEVIATIONS.md index 1c65a04a2..c786d8881 100644 --- a/docs/DEVIATIONS.md +++ b/docs/DEVIATIONS.md @@ -311,7 +311,7 @@ Each entry is the first sentence of a `Deviation:` comment, linking to where it - Not run on benilla's same-character reconnect, which the reference lacks (it returns to the login screen), so the window keeps its scrollback there. ([`src/ui_chat.rs:216`](../crates/benilla-app/src/ui_chat.rs#L216)) - A missing global prints nothing, where the reference prints an empty line (`0x703c02`), because benilla's other `DisplayError` routes do the same. ([`src/ui_chat/broadcast.rs:148`](../crates/benilla-app/src/ui_chat/broadcast.rs#L148)) - With a blank city word the reference composes `"Trade - "` (its capital arm checks the row pointer, not the string, `0x49a2d0`-`0x49a2f6`); we decline, because a wrong channel name is joined silently and for good. ([`src/ui_chat/channels.rs:150`](../crates/benilla-app/src/ui_chat/channels.rs#L150)) -- A probe's bare `/assist` assists the live selection, where the stock handler (`ChatFrame.lua:740`) resolves a selected player's name through `AssistByName`, because a name resolve can land on a different player. ([`src/ui_chat/input/mod.rs:649`](../crates/benilla-app/src/ui_chat/input/mod.rs#L649)) +- A probe's bare `/assist` assists the live selection, where the stock handler (`ChatFrame.lua:740`) resolves a selected player's name through `AssistByName`, because a name resolve can land on a different player. ([`src/ui_chat/input/mod.rs:627`](../crates/benilla-app/src/ui_chat/input/mod.rs#L627)) - The files live in `benilla-config/Logs/`, not the install's `Logs`, because the install is read-only. ([`src/ui_chat/logging.rs:4`](../crates/benilla-app/src/ui_chat/logging.rs#L4)) - No re-run when a remote player streams in, because the reference's re-run only repeats the join, which vmangos swallows, or the leave, whose "Not on channel" notice nothing prints. ([`src/ui_chat/recruitment.rs:7`](../crates/benilla-app/src/ui_chat/recruitment.rs#L7)) - `set_chat_window_looks` drops an out-of-range window, where the reference's `WINDOW` bound is off by one (`0x498d1c`, `ja` where the array needs `jae`), because that write would land past the array. ([`src/ui_chat/settings.rs:31`](../crates/benilla-app/src/ui_chat/settings.rs#L31)) @@ -755,8 +755,8 @@ Each entry is the first sentence of a `Deviation:` comment, linking to where it - Kept apart from `Self::vertex_color`, which the reference's `Texture:SetAlpha` (`0x79b580`) rewrites, because the drawn product differs only on a region that sets both, or a gradient and an alpha, which no stock code does, and a FontString's `SetAlpha` then keeps its font colour. ([`src/script/types.rs:421`](../crates/benilla-ui/src/script/types.rs#L421)) - UnitCanCooperate answers 1 for a friendly (5 and up) player, because the engine carries no faction templates; the reference resolves their cooperation masks. ([`src/script/unit/bindings.rs:612`](../crates/benilla-ui/src/script/unit/bindings.rs#L612)) - Among whole-name matches ours picks the nearest, because the reference's first-walked pick is order-dependent and reads as a bug. ([`src/script/unit/bindings.rs:1115`](../crates/benilla-ui/src/script/unit/bindings.rs#L1115)) -- The reference ends the walk at the first whole-string hit (`0x493ca2`), so its pick follows the object list's order; we rank exact, then longer prefix, then nearest (`Rank::beats`), because the nearest namesake is the better pick, and a full tie goes to the lower guid (`Rank::beats_at`), so the VM's walk and the app's scan pick the same unit whatever order each walks in. ([`src/script/unit/by_name.rs:7`](../crates/benilla-ui/src/script/unit/by_name.rs#L7)) -- A full tie goes to the lower guid, where the reference keeps the first unit its walk (`0x493aa0`) reaches, an order neither of ours has; a guid keeps the two picks equal. ([`src/script/unit/by_name.rs:46`](../crates/benilla-ui/src/script/unit/by_name.rs#L46)) +- The reference's matcher takes a whole-string hit at once only when it is nearer than the best so far (`0x493c88`-`0x493ca2`); an exact hit that is not nearer competes on prefix length alone (`0x493cf8`-`0x493d09`), so a nearer "Bobby" walked first beats an exact "Bob", and the pick follows the object list's order. ([`src/script/unit/by_name.rs:18`](../crates/benilla-ui/src/script/unit/by_name.rs#L18)) +- A full tie goes to the lower guid, where the reference keeps the first unit its walk (`0x493aa0`) reaches, an order neither of ours has; a guid keeps the two picks equal. ([`src/script/unit/by_name.rs:60`](../crates/benilla-ui/src/script/unit/by_name.rs#L60)) - `0x4e81d0` has no bound and reads past its four-entry table, which is stale memory, not a mechanism; past it, nobody. ([`src/script/unit/resolve.rs:198`](../crates/benilla-ui/src/script/unit/resolve.rs#L198)) - The reference ties a miss against a hit (`0x5adab6`); no total order can, and `sort_by` may panic on one that is not, so the miss goes last. ([`src/script/who_sort.rs:161`](../crates/benilla-ui/src/script/who_sort.rs#L161)) - The engine's own pushes (the world-enter sync, the explored areas, the landmark sources, the catalog) queue `WORLD_MAP_UPDATE` for the next frame's tick and fire only on a change, where the reference fires in place from the handler that moved the data: the app's feeds run after the frame's tick. ([`src/script/worldmap.rs:13`](../crates/benilla-ui/src/script/worldmap.rs#L13))