From 36f7b7e9eefff736c10b57fae0187d90bf96ceb0 Mon Sep 17 00:00:00 2001 From: sindoring Date: Fri, 30 Oct 2026 18:23:50 +0400 Subject: [PATCH] Sync upstream through c137bdd5 Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 12 + crates/benilla-app/src/account_data/mod.rs | 4 +- crates/benilla-app/src/addon_harness/mod.rs | 4 +- crates/benilla-app/src/area.rs | 37 +- crates/benilla-app/src/bindings.rs | 531 +++-- .../benilla-app/src/bindings/script_input.rs | 107 +- crates/benilla-app/src/capture/fixtures.rs | 133 +- crates/benilla-app/src/capture/mod.rs | 120 + .../benilla-app/src/capture/probe_binder.rs | 5 +- .../src/capture/probe_vendor_swap.rs | 2 +- crates/benilla-app/src/capture/scenarios.rs | 2 +- crates/benilla-app/src/chat_bubble.rs | 8 +- crates/benilla-app/src/combat_text/mod.rs | 6 +- crates/benilla-app/src/creature_anim.rs | 112 +- .../benilla-app/src/creature_anim/driver.rs | 25 + crates/benilla-app/src/creature_anim/edits.rs | 121 +- crates/benilla-app/src/creature_anim/net.rs | 14 + .../benilla-app/src/creature_anim/sheath.rs | 31 + .../src/creature_anim/spell_visual.rs | 7 - .../src/creature_anim/spell_visual/tests.rs | 4 - crates/benilla-app/src/cursor.rs | 7 +- crates/benilla-app/src/cvars/callbacks.rs | 202 ++ crates/benilla-app/src/cvars/inert.rs | 2 +- crates/benilla-app/src/cvars/mod.rs | 548 +++-- crates/benilla-app/src/death/mod.rs | 790 +++---- crates/benilla-app/src/death/net.rs | 169 +- crates/benilla-app/src/entities/missile.rs | 2 - crates/benilla-app/src/field_callbacks.rs | 56 +- crates/benilla-app/src/field_watch.rs | 390 +++- crates/benilla-app/src/game_plugins.rs | 296 +-- crates/benilla-app/src/game_tip.rs | 10 +- crates/benilla-app/src/glue_session/login.rs | 4 +- crates/benilla-app/src/item_lane.rs | 214 +- crates/benilla-app/src/item_watch.rs | 149 +- crates/benilla-app/src/items.rs | 326 ++- crates/benilla-app/src/lanes.rs | 363 ++- .../src/lanes/account_data_live_tests.rs | 455 ++++ .../src/lanes/action_live_tests.rs | 760 ++++++- .../benilla-app/src/lanes/alert_live_tests.rs | 276 +++ .../src/lanes/arrival_live_tests.rs | 300 ++- .../src/lanes/auction_live_tests.rs | 21 +- .../benilla-app/src/lanes/aura_view_tests.rs | 13 +- crates/benilla-app/src/lanes/bag_tests.rs | 9 +- .../benilla-app/src/lanes/bank_live_tests.rs | 23 +- .../benilla-app/src/lanes/book_live_tests.rs | 81 + .../benilla-app/src/lanes/cast_live_tests.rs | 297 ++- .../src/lanes/chat_clock_live_tests.rs | 320 +++ .../src/lanes/close_parked_tests.rs | 345 +++ .../src/lanes/cooldown_live_tests.rs | 289 ++- .../src/lanes/deactivate_live_tests.rs | 324 +++ .../benilla-app/src/lanes/death_live_tests.rs | 263 +++ .../src/lanes/dialog_live_tests.rs | 131 +- .../src/lanes/follow_live_tests.rs | 550 +++++ .../src/lanes/gossip_live_tests.rs | 47 +- .../benilla-app/src/lanes/group_live_tests.rs | 560 +++++ .../benilla-app/src/lanes/group_view_tests.rs | 48 +- crates/benilla-app/src/lanes/guard_tests.rs | 1844 ++++++++------- .../benilla-app/src/lanes/guild_live_tests.rs | 33 + .../benilla-app/src/lanes/host_read_tests.rs | 321 ++- .../src/lanes/instance_live_tests.rs | 105 + .../benilla-app/src/lanes/item_live_tests.rs | 6 +- crates/benilla-app/src/lanes/item_tests.rs | 8 + .../src/lanes/item_text_live_tests.rs | 432 ++++ .../src/lanes/item_view_live_tests.rs | 171 ++ .../benilla-app/src/lanes/lock_live_tests.rs | 195 ++ .../src/lanes/logout_live_tests.rs | 115 + .../benilla-app/src/lanes/loot_live_tests.rs | 111 +- .../src/lanes/loot_roll_live_tests.rs | 136 ++ .../benilla-app/src/lanes/mail_live_tests.rs | 55 +- .../src/lanes/merchant_live_tests.rs | 89 +- .../src/lanes/packet_signal_tests.rs | 285 ++- .../src/lanes/petition_live_tests.rs | 66 +- .../benilla-app/src/lanes/plate_live_tests.rs | 405 ++++ .../src/lanes/profession_live_tests.rs | 762 +++++++ .../src/lanes/quest_log_live_tests.rs | 140 +- .../src/lanes/record_callback_tests.rs | 432 ++++ .../src/lanes/reputation_live_tests.rs | 29 + .../src/lanes/requirement_live_tests.rs | 81 +- .../src/lanes/selection_live_tests.rs | 9 +- .../src/lanes/social_live_tests.rs | 26 + .../src/lanes/spell_slot_live_tests.rs | 395 ++++ .../src/lanes/stable_live_tests.rs | 62 +- .../benilla-app/src/lanes/stat_live_tests.rs | 29 +- .../src/lanes/tabard_live_tests.rs | 41 +- .../benilla-app/src/lanes/taxi_live_tests.rs | 21 +- crates/benilla-app/src/lanes/tests.rs | 32 +- .../benilla-app/src/lanes/token_live_tests.rs | 293 ++- .../src/lanes/tooltip_live_tests.rs | 232 ++ .../benilla-app/src/lanes/trade_live_tests.rs | 91 +- .../src/lanes/trainer_live_tests.rs | 49 +- .../src/lanes/tutorial_live_tests.rs | 312 +++ .../src/lanes/ui_error_live_tests.rs | 437 ++++ .../src/lanes/unit_feed_live_tests.rs | 60 + .../benilla-app/src/lanes/unit_live_tests.rs | 35 +- .../benilla-app/src/lanes/unit_view_tests.rs | 415 +++- .../src/lanes/world_map_live_tests.rs | 300 +++ .../src/lanes/world_map_update_tests.rs | 400 ++++ .../src/lanes/world_state_live_tests.rs | 143 ++ .../benilla-app/src/lanes/worn_live_tests.rs | 269 +++ crates/benilla-app/src/lib.rs | 1 - crates/benilla-app/src/minimap/mod.rs | 43 +- crates/benilla-app/src/minimap/ping.rs | 250 ++- crates/benilla-app/src/nameplates.rs | 6 +- crates/benilla-app/src/names.rs | 247 +-- crates/benilla-app/src/net.rs | 31 +- crates/benilla-app/src/net/apply.rs | 24 +- crates/benilla-app/src/net/game_time.rs | 17 + crates/benilla-app/src/net/handlers.rs | 166 +- crates/benilla-app/src/net/io/fake.rs | 14 +- crates/benilla-app/src/net/objects.rs | 516 +++-- crates/benilla-app/src/net/objects/arrival.rs | 18 +- .../src/net/objects/item_deactivate.rs | 40 + crates/benilla-app/src/net/objects/update.rs | 379 +++- crates/benilla-app/src/net/reputations.rs | 19 +- crates/benilla-app/src/net/reputations/log.rs | 16 +- crates/benilla-app/src/net/session.rs | 378 +++- crates/benilla-app/src/net/world.rs | 2 +- crates/benilla-app/src/npc_text.rs | 13 +- crates/benilla-app/src/perf/journal.rs | 6 +- crates/benilla-app/src/perf/mod.rs | 1 - crates/benilla-app/src/player.rs | 32 +- crates/benilla-app/src/player/approach.rs | 192 +- crates/benilla-app/src/player/camera.rs | 792 ++++--- .../src/player/camera/mouselook_tests.rs | 431 +++- crates/benilla-app/src/player/camera_axes.rs | 80 +- .../benilla-app/src/player/camera_dynamics.rs | 5 +- crates/benilla-app/src/player/camera_saved.rs | 12 +- crates/benilla-app/src/player/camera_view.rs | 285 ++- crates/benilla-app/src/player/camera_zoom.rs | 56 +- crates/benilla-app/src/player/controller.rs | 103 +- .../src/player/controller/tests.rs | 202 +- crates/benilla-app/src/player/embody.rs | 13 +- crates/benilla-app/src/player/follow.rs | 208 +- crates/benilla-app/src/player/input.rs | 128 +- crates/benilla-app/src/player/net.rs | 137 +- crates/benilla-app/src/player/posture.rs | 75 +- crates/benilla-app/src/player/press.rs | 584 ++++- crates/benilla-app/src/player/state.rs | 24 +- crates/benilla-app/src/player/swim.rs | 17 +- crates/benilla-app/src/player/view_subject.rs | 110 +- crates/benilla-app/src/player/wire_in.rs | 6 + crates/benilla-app/src/poi_marker.rs | 123 +- crates/benilla-app/src/portrait/mod.rs | 18 +- .../benilla-app/src/portrait/panes_tests.rs | 2 + crates/benilla-app/src/quest_markers/mod.rs | 6 +- crates/benilla-app/src/realmlist.rs | 12 +- crates/benilla-app/src/screenshot.rs | 3 +- crates/benilla-app/src/script_calls.rs | 911 ++++++-- crates/benilla-app/src/script_calls/census.rs | 31 +- crates/benilla-app/src/script_calls/engine.rs | 184 +- crates/benilla-app/src/script_calls/live.rs | 68 +- .../src/script_calls/tests/asks.rs | 77 +- .../src/script_calls/tests/cast_reports.rs | 265 ++- .../src/script_calls/tests/census.rs | 61 +- .../src/script_calls/tests/dialogs.rs | 64 +- .../src/script_calls/tests/engine.rs | 33 + .../src/script_calls/tests/plates.rs | 330 +++ .../src/script_calls/tests/selection.rs | 545 ++++- .../src/script_calls/tests/sends.rs | 44 +- .../src/script_calls/tests/ticks.rs | 544 +++++ .../benilla-app/src/script_calls/windows.rs | 152 +- .../src/script_calls/world_click.rs | 188 +- crates/benilla-app/src/sound/glue.rs | 5 +- crates/benilla-app/src/sound/kit.rs | 3 +- crates/benilla-app/src/sound/mod.rs | 14 +- crates/benilla-app/src/sound/money.rs | 6 +- crates/benilla-app/src/sound/movie.rs | 4 +- crates/benilla-app/src/sound/ui.rs | 8 +- crates/benilla-app/src/sound/zone.rs | 9 +- crates/benilla-app/src/spell/cast_send.rs | 37 +- crates/benilla-app/src/spell/cast_target.rs | 5 +- crates/benilla-app/src/spell/cooldowns.rs | 308 +-- .../benilla-app/src/spell/cooldowns/live.rs | 8 +- crates/benilla-app/src/spell/cooldowns/log.rs | 51 +- .../benilla-app/src/spell/cooldowns_tests.rs | 49 +- .../benilla-app/src/spell/group_relation.rs | 66 +- crates/benilla-app/src/spell/inflight.rs | 157 +- crates/benilla-app/src/spell/known.rs | 8 +- crates/benilla-app/src/spell/level.rs | 26 + crates/benilla-app/src/spell/mod.rs | 179 +- crates/benilla-app/src/spell/mods.rs | 80 +- crates/benilla-app/src/spell/net.rs | 744 ++++--- .../src/spell/net/tests/cooldown_sites.rs | 78 +- .../src/spell/net/tests/learned.rs | 12 +- .../src/spell/net/tests/openers.rs | 22 +- crates/benilla-app/src/spell/reads.rs | 70 - crates/benilla-app/src/spell/report.rs | 75 +- .../benilla-app/src/spell/targeting/live.rs | 40 + crates/benilla-app/src/spell/targeting/mod.rs | 211 +- .../benilla-app/src/spell/targeting/pick.rs | 8 +- .../benilla-app/src/spell/targeting/world.rs | 3 +- crates/benilla-app/src/spell/usable.rs | 125 +- crates/benilla-app/src/target/arm.rs | 38 +- crates/benilla-app/src/target/by_name.rs | 173 +- crates/benilla-app/src/target/click.rs | 456 ++-- .../src/target/click_loot_tests.rs | 1 - crates/benilla-app/src/target/died.rs | 37 +- crates/benilla-app/src/target/front.rs | 2 +- crates/benilla-app/src/target/front_tests.rs | 160 +- crates/benilla-app/src/target/gate_tests.rs | 110 +- crates/benilla-app/src/target/mod.rs | 69 +- .../src/target/record_click_tests.rs | 134 ++ crates/benilla-app/src/target/release.rs | 2 +- crates/benilla-app/src/target/scan.rs | 230 +- crates/benilla-app/src/target/script.rs | 42 +- crates/benilla-app/src/target/unheld_tests.rs | 52 +- crates/benilla-app/src/test_support.rs | 24 + crates/benilla-app/src/text_filter.rs | 14 +- crates/benilla-app/src/tutorial.rs | 1051 ++++----- crates/benilla-app/src/ui_action/cast_fail.rs | 10 + .../benilla-app/src/ui_action/cast_lines.rs | 91 +- .../src/ui_action/cooldown_lane.rs | 16 +- crates/benilla-app/src/ui_action/drain.rs | 82 +- crates/benilla-app/src/ui_action/drop_item.rs | 154 +- .../src/ui_action/drop_item_tests.rs | 89 +- crates/benilla-app/src/ui_action/errors.rs | 267 ++- crates/benilla-app/src/ui_action/feed.rs | 372 +--- .../benilla-app/src/ui_action/feed_tests.rs | 748 +------ crates/benilla-app/src/ui_action/mod.rs | 368 +-- crates/benilla-app/src/ui_action/net.rs | 55 +- .../benilla-app/src/ui_action/range_tests.rs | 22 +- crates/benilla-app/src/ui_action/ranks.rs | 103 +- crates/benilla-app/src/ui_action/reactive.rs | 29 +- .../src/ui_action/reactive_tests.rs | 52 +- crates/benilla-app/src/ui_action/recount.rs | 224 +- .../benilla-app/src/ui_action/spell_slots.rs | 286 +++ crates/benilla-app/src/ui_action/state.rs | 963 +++++--- .../benilla-app/src/ui_action/state_tests.rs | 629 +++--- crates/benilla-app/src/ui_action/unlearn.rs | 208 -- crates/benilla-app/src/ui_auction/mod.rs | 5 - crates/benilla-app/src/ui_auction/net.rs | 19 +- .../benilla-app/src/ui_auction/verb_tests.rs | 4 + crates/benilla-app/src/ui_auction/verbs.rs | 5 - crates/benilla-app/src/ui_aura.rs | 166 +- crates/benilla-app/src/ui_aura/units.rs | 160 +- crates/benilla-app/src/ui_bank/lane.rs | 4 +- crates/benilla-app/src/ui_battlefield.rs | 6 +- crates/benilla-app/src/ui_bind_confirm.rs | 113 +- crates/benilla-app/src/ui_binder.rs | 68 +- crates/benilla-app/src/ui_cast.rs | 105 +- crates/benilla-app/src/ui_cast/views.rs | 90 +- crates/benilla-app/src/ui_char.rs | 838 +++---- crates/benilla-app/src/ui_chat.rs | 87 +- crates/benilla-app/src/ui_chat/away.rs | 21 +- crates/benilla-app/src/ui_chat/broadcast.rs | 208 +- crates/benilla-app/src/ui_chat/channels.rs | 225 +- crates/benilla-app/src/ui_chat/combat.rs | 6 +- .../benilla-app/src/ui_chat/combat/watch.rs | 38 +- crates/benilla-app/src/ui_chat/edit.rs | 29 +- crates/benilla-app/src/ui_chat/feed.rs | 145 +- crates/benilla-app/src/ui_chat/frames.rs | 14 +- crates/benilla-app/src/ui_chat/input/mod.rs | 52 +- crates/benilla-app/src/ui_chat/input/send.rs | 191 +- crates/benilla-app/src/ui_chat/language.rs | 181 +- crates/benilla-app/src/ui_chat/logging.rs | 232 +- crates/benilla-app/src/ui_chat/net.rs | 82 +- crates/benilla-app/src/ui_chat/recruitment.rs | 141 +- crates/benilla-app/src/ui_chat/settings.rs | 222 +- crates/benilla-app/src/ui_chat/slot_tests.rs | 71 +- crates/benilla-app/src/ui_chat/tests.rs | 105 +- .../src/ui_chat/walk_live_tests.rs | 346 +++ crates/benilla-app/src/ui_craft.rs | 901 ++++---- crates/benilla-app/src/ui_dialog_verbs.rs | 146 +- .../benilla-app/src/ui_dialog_verbs/live.rs | 31 +- crates/benilla-app/src/ui_dressup.rs | 215 +- crates/benilla-app/src/ui_follow.rs | 77 - crates/benilla-app/src/ui_gamma.rs | 9 +- crates/benilla-app/src/ui_gossip/lane.rs | 4 +- crates/benilla-app/src/ui_guild/mod.rs | 21 +- crates/benilla-app/src/ui_instance.rs | 345 +-- crates/benilla-app/src/ui_item_text.rs | 1530 +++++++------ crates/benilla-app/src/ui_item_text/live.rs | 86 + crates/benilla-app/src/ui_items/bags.rs | 37 +- .../src/ui_items/bags_cooldown_tests.rs | 8 +- .../src/ui_items/bags_link_tests.rs | 8 +- crates/benilla-app/src/ui_items/calls.rs | 184 +- crates/benilla-app/src/ui_items/drain.rs | 113 +- crates/benilla-app/src/ui_items/feed.rs | 605 ++--- crates/benilla-app/src/ui_items/locks.rs | 133 +- crates/benilla-app/src/ui_items/mod.rs | 28 +- .../benilla-app/src/ui_items/requirements.rs | 29 +- crates/benilla-app/src/ui_items/verb_tests.rs | 44 + crates/benilla-app/src/ui_layout.rs | 198 +- crates/benilla-app/src/ui_logout.rs | 283 +-- crates/benilla-app/src/ui_loot/call_tests.rs | 181 +- crates/benilla-app/src/ui_loot/calls.rs | 15 +- crates/benilla-app/src/ui_loot/mod.rs | 157 +- crates/benilla-app/src/ui_loot/net.rs | 157 +- .../benilla-app/src/ui_loot/receive_tests.rs | 2 + crates/benilla-app/src/ui_loot/sweep_tests.rs | 66 +- crates/benilla-app/src/ui_loot_roll.rs | 1971 +++++++++-------- crates/benilla-app/src/ui_macro/mod.rs | 582 ++--- crates/benilla-app/src/ui_macro/tests.rs | 391 ++-- crates/benilla-app/src/ui_mail/lane.rs | 22 +- crates/benilla-app/src/ui_mail/mod.rs | 12 +- crates/benilla-app/src/ui_mail/stationery.rs | 25 +- crates/benilla-app/src/ui_mail/verb_tests.rs | 40 +- crates/benilla-app/src/ui_mail/verbs.rs | 22 +- crates/benilla-app/src/ui_merchant/lane.rs | 4 +- crates/benilla-app/src/ui_merchant/mod.rs | 6 +- crates/benilla-app/src/ui_merchant/net.rs | 12 +- crates/benilla-app/src/ui_models/mod.rs | 3 +- crates/benilla-app/src/ui_party/call_tests.rs | 3 - crates/benilla-app/src/ui_party/cells.rs | 16 - crates/benilla-app/src/ui_party/feed.rs | 1218 +++------- .../src/ui_party/feed/roster_update_tests.rs | 111 +- crates/benilla-app/src/ui_party/live.rs | 16 +- crates/benilla-app/src/ui_party/mod.rs | 212 +- crates/benilla-app/src/ui_party/net.rs | 187 +- crates/benilla-app/src/ui_party/pets.rs | 313 +-- crates/benilla-app/src/ui_party/records.rs | 157 +- crates/benilla-app/src/ui_pet/flush_tests.rs | 77 +- crates/benilla-app/src/ui_pet/mod.rs | 25 +- crates/benilla-app/src/ui_pet/net.rs | 31 +- crates/benilla-app/src/ui_pet/press_tests.rs | 10 +- crates/benilla-app/src/ui_pet/tests.rs | 163 +- crates/benilla-app/src/ui_pet/unit.rs | 196 +- crates/benilla-app/src/ui_petition/lane.rs | 4 +- crates/benilla-app/src/ui_quest/lane.rs | 38 +- crates/benilla-app/src/ui_quest/lines.rs | 560 +++-- crates/benilla-app/src/ui_quest/mod.rs | 6 +- crates/benilla-app/src/ui_quest/net.rs | 124 +- crates/benilla-app/src/ui_quest/verb_tests.rs | 7 +- crates/benilla-app/src/ui_quest/verbs.rs | 4 + crates/benilla-app/src/ui_quest_log.rs | 584 ++--- crates/benilla-app/src/ui_quest_log/live.rs | 39 +- crates/benilla-app/src/ui_quest_share.rs | 448 ++-- crates/benilla-app/src/ui_reputation.rs | 4 +- .../src/ui_script/action_bar_tests.rs | 2 +- crates/benilla-app/src/ui_script/bag_tests.rs | 2 + .../src/ui_script/bagnon_render_tests.rs | 4 +- .../ui_script/battlefield_minimap_tests.rs | 44 +- .../benilla-app/src/ui_script/binder_tests.rs | 4 +- .../src/ui_script/character_tests.rs | 4 +- .../benilla-app/src/ui_script/death_tests.rs | 17 +- .../src/ui_script/dressup_tests.rs | 6 + .../src/ui_script/durability_tests.rs | 37 +- .../benilla-app/src/ui_script/extract/mod.rs | 41 +- crates/benilla-app/src/ui_script/fire_scan.rs | 249 ++- crates/benilla-app/src/ui_script/gate.rs | 135 -- crates/benilla-app/src/ui_script/glue_mgr.rs | 61 +- .../src/ui_script/group_loot_tests.rs | 5 +- crates/benilla-app/src/ui_script/input.rs | 98 +- crates/benilla-app/src/ui_script/lifecycle.rs | 102 +- crates/benilla-app/src/ui_script/mod.rs | 57 +- crates/benilla-app/src/ui_script/movie.rs | 8 +- .../src/ui_script/pet_frame_tests.rs | 8 +- .../benilla-app/src/ui_script/raid_tests.rs | 2 +- .../benilla-app/src/ui_script/raise_origin.rs | 212 ++ .../src/ui_script/record_order_tests.rs | 18 +- crates/benilla-app/src/ui_script/session.rs | 18 - crates/benilla-app/src/ui_script/sweep.rs | 39 +- .../src/ui_script/talent_wipe_tests.rs | 4 +- crates/benilla-app/src/ui_script/test_ui.rs | 6 +- .../src/ui_script/tick_order_tests.rs | 148 +- .../src/ui_script/unit_frame_tests.rs | 156 +- .../src/ui_script/world_entry_tests.rs | 252 ++- .../src/ui_script/world_map_tests.rs | 64 +- crates/benilla-app/src/ui_session.rs | 124 +- crates/benilla-app/src/ui_session/latch.rs | 51 +- .../benilla-app/src/ui_social/call_tests.rs | 32 +- crates/benilla-app/src/ui_social/feed.rs | 19 +- crates/benilla-app/src/ui_social/lane.rs | 2 - crates/benilla-app/src/ui_social/steps.rs | 5 +- crates/benilla-app/src/ui_spellbook.rs | 29 +- crates/benilla-app/src/ui_stable/lane.rs | 4 +- crates/benilla-app/src/ui_tabard/lane.rs | 6 +- crates/benilla-app/src/ui_talent.rs | 11 +- crates/benilla-app/src/ui_talent/live.rs | 8 +- .../benilla-app/src/ui_talent_call_tests.rs | 8 +- crates/benilla-app/src/ui_talent_wipe.rs | 72 +- crates/benilla-app/src/ui_taxi/lane.rs | 12 +- crates/benilla-app/src/ui_taxi/mod.rs | 75 +- crates/benilla-app/src/ui_taxi/net.rs | 20 +- crates/benilla-app/src/ui_tooltip/bench.rs | 216 -- .../benilla-app/src/ui_tooltip/deps_tests.rs | 1862 ---------------- .../benilla-app/src/ui_tooltip/feed_tests.rs | 565 ----- .../src/ui_tooltip/go_lock_tests.rs | 51 +- crates/benilla-app/src/ui_tooltip/live.rs | 105 + .../benilla-app/src/ui_tooltip/live_tests.rs | 223 ++ crates/benilla-app/src/ui_tooltip/mod.rs | 360 +-- crates/benilla-app/src/ui_tooltip/plate.rs | 271 +++ .../benilla-app/src/ui_tooltip/spell_deps.rs | 423 ---- .../{spell_feed.rs => spell_view.rs} | 606 +---- crates/benilla-app/src/ui_tooltip/tests.rs | 662 +----- crates/benilla-app/src/ui_trade/call_tests.rs | 149 +- crates/benilla-app/src/ui_trade/calls.rs | 21 +- crates/benilla-app/src/ui_trade/lane.rs | 63 +- crates/benilla-app/src/ui_trade/mod.rs | 37 +- crates/benilla-app/src/ui_tradeskill.rs | 1266 ++++++----- crates/benilla-app/src/ui_trainer/lane.rs | 4 +- crates/benilla-app/src/ui_trainer/law.rs | 6 +- crates/benilla-app/src/ui_trainer/mod.rs | 157 +- crates/benilla-app/src/ui_trainer/tests.rs | 5 +- crates/benilla-app/src/ui_unit.rs | 1020 ++------- .../benilla-app/src/ui_unit/field_events.rs | 332 ++- crates/benilla-app/src/ui_unit/held.rs | 80 +- crates/benilla-app/src/ui_unit/live.rs | 170 +- crates/benilla-app/src/ui_unit/reach.rs | 100 + crates/benilla-app/src/ui_unit/views.rs | 610 +++-- .../benilla-app/src/ui_unit/views/families.rs | 175 -- crates/benilla-app/src/ui_world_enter.rs | 36 +- crates/benilla-app/src/ui_world_map.rs | 405 ++-- crates/benilla-app/src/video.rs | 348 +-- crates/benilla-app/src/vm_pass.rs | 33 +- crates/benilla-app/src/vplates.rs | 83 +- crates/benilla-app/src/wdb/tests.rs | 37 +- crates/benilla-app/src/world_backdrop.rs | 11 +- crates/benilla-app/src/world_state.rs | 38 +- crates/benilla-app/src/world_state_ui.rs | 143 +- crates/benilla-formats/src/area_poi.rs | 11 + crates/benilla-ui/src/script/action.rs | 343 ++- .../src/script/action_bar_toggles.rs | 11 +- crates/benilla-ui/src/script/addon_message.rs | 1 + crates/benilla-ui/src/script/aura/mod.rs | 13 +- .../src/script/battlefield_queue.rs | 16 +- crates/benilla-ui/src/script/binder.rs | 4 +- crates/benilla-ui/src/script/button.rs | 32 +- crates/benilla-ui/src/script/calls.rs | 194 +- crates/benilla-ui/src/script/camera_view.rs | 45 +- crates/benilla-ui/src/script/census.rs | 10 +- crates/benilla-ui/src/script/channel.rs | 117 +- crates/benilla-ui/src/script/char_stats.rs | 370 +++- crates/benilla-ui/src/script/chat_misc.rs | 50 +- crates/benilla-ui/src/script/chat_send.rs | 3 +- crates/benilla-ui/src/script/chat_window.rs | 3 +- crates/benilla-ui/src/script/client.rs | 43 +- crates/benilla-ui/src/script/clock.rs | 37 +- crates/benilla-ui/src/script/console_exec.rs | 2 +- crates/benilla-ui/src/script/container.rs | 11 +- crates/benilla-ui/src/script/craft.rs | 277 ++- crates/benilla-ui/src/script/cursor.rs | 125 +- crates/benilla-ui/src/script/cursor/bar.rs | 66 +- crates/benilla-ui/src/script/cursor/doll.rs | 7 +- crates/benilla-ui/src/script/cursor/equip.rs | 35 +- crates/benilla-ui/src/script/cursor/swap.rs | 5 +- crates/benilla-ui/src/script/cvars.rs | 141 +- crates/benilla-ui/src/script/death.rs | 129 +- crates/benilla-ui/src/script/dialog_live.rs | 7 +- crates/benilla-ui/src/script/dressup.rs | 47 +- crates/benilla-ui/src/script/event.rs | 5 +- crates/benilla-ui/src/script/glue_addons.rs | 4 +- crates/benilla-ui/src/script/glue_core.rs | 12 +- crates/benilla-ui/src/script/glue_realm.rs | 2 + crates/benilla-ui/src/script/gm_ticket.rs | 3 + crates/benilla-ui/src/script/gossip.rs | 4 +- crates/benilla-ui/src/script/host.rs | 35 +- crates/benilla-ui/src/script/input_verbs.rs | 177 +- crates/benilla-ui/src/script/inspect.rs | 12 +- .../benilla-ui/src/script/inventory_verbs.rs | 15 +- crates/benilla-ui/src/script/item_stats.rs | 115 +- crates/benilla-ui/src/script/item_text.rs | 150 +- crates/benilla-ui/src/script/keybind.rs | 52 +- crates/benilla-ui/src/script/lfg.rs | 4 +- crates/benilla-ui/src/script/loot_roll.rs | 112 +- crates/benilla-ui/src/script/macros.rs | 38 +- crates/benilla-ui/src/script/mail.rs | 5 +- crates/benilla-ui/src/script/merchant.rs | 14 +- crates/benilla-ui/src/script/minimap.rs | 7 +- crates/benilla-ui/src/script/mod.rs | 85 +- crates/benilla-ui/src/script/model.rs | 124 +- crates/benilla-ui/src/script/mouseover.rs | 28 +- crates/benilla-ui/src/script/nameplate.rs | 114 +- crates/benilla-ui/src/script/origin.rs | 385 ++++ crates/benilla-ui/src/script/party.rs | 291 +-- crates/benilla-ui/src/script/pet.rs | 3 +- crates/benilla-ui/src/script/pointer.rs | 316 ++- crates/benilla-ui/src/script/pvp/mod.rs | 1 + crates/benilla-ui/src/script/quest.rs | 5 +- crates/benilla-ui/src/script/quest_live.rs | 53 +- crates/benilla-ui/src/script/quest_log.rs | 244 +- crates/benilla-ui/src/script/roster_read.rs | 22 +- crates/benilla-ui/src/script/spellbook.rs | 47 +- crates/benilla-ui/src/script/stat_read.rs | 35 + crates/benilla-ui/src/script/talent.rs | 22 +- crates/benilla-ui/src/script/taxi.rs | 11 +- crates/benilla-ui/src/script/tests/capture.rs | 186 ++ .../benilla-ui/src/script/tests/flag_args.rs | 3 +- .../benilla-ui/src/script/tests/nameplate.rs | 129 +- .../src/script/tests/protected_gate.rs | 5 - .../src/script/tests/tooltip_item/rebuild.rs | 26 + .../src/script/tests/tooltip_spell.rs | 95 - .../src/script/tests/tooltip_unit.rs | 33 +- .../src/script/tests/tooltip_unit_status.rs | 63 +- .../benilla-ui/src/script/tests/worldmap.rs | 386 +++- crates/benilla-ui/src/script/tick.rs | 67 +- crates/benilla-ui/src/script/tooltip/mod.rs | 15 +- crates/benilla-ui/src/script/tooltip_aura.rs | 69 +- .../src/script/tooltip_item/build.rs | 90 +- .../src/script/tooltip_item/compare.rs | 1 + .../benilla-ui/src/script/tooltip_item/mod.rs | 28 +- .../src/script/tooltip_item/render.rs | 16 +- crates/benilla-ui/src/script/tooltip_spell.rs | 212 +- crates/benilla-ui/src/script/tooltip_text.rs | 2 +- crates/benilla-ui/src/script/tooltip_unit.rs | 363 ++- crates/benilla-ui/src/script/trade.rs | 14 +- .../benilla-ui/src/script/tradeskill/api.rs | 87 +- .../benilla-ui/src/script/tradeskill/mod.rs | 241 +- .../benilla-ui/src/script/tradeskill/tests.rs | 14 +- crates/benilla-ui/src/script/tutorial.rs | 57 +- crates/benilla-ui/src/script/unit/bindings.rs | 38 +- crates/benilla-ui/src/script/unit/by_name.rs | 22 +- .../benilla-ui/src/script/unit/chain_tests.rs | 25 +- crates/benilla-ui/src/script/unit/mod.rs | 99 +- .../benilla-ui/src/script/unit/relations.rs | 31 +- crates/benilla-ui/src/script/unit/resolve.rs | 78 +- .../src/script/unit/selection_tests.rs | 52 +- .../benilla-ui/src/script/unit/state_read.rs | 4 +- crates/benilla-ui/src/script/unit/tests.rs | 19 +- crates/benilla-ui/src/script/use_gates.rs | 12 + crates/benilla-ui/src/script/video_pairs.rs | 10 +- .../benilla-ui/src/script/weapon_enchant.rs | 26 +- crates/benilla-ui/src/script/worldmap.rs | 256 ++- .../benilla-ui/src/script/worldmap_arrow.rs | 4 +- crates/benilla-ui/src/script/worldstate.rs | 44 +- crates/benilla-ui/src/script/worn.rs | 72 + crates/benilla-ui/src/script/worn_display.rs | 4 +- crates/benilla-ui/src/script/zone_text.rs | 22 +- crates/benilla-ui/src/widget/kinds/mod.rs | 6 + crates/benilla-ui/tests/vm_parity.golden | 4 +- crates/benilla-world/src/bgwin.rs | 4 - crates/benilla-world/src/clutter.rs | 5 +- crates/benilla-world/src/view.rs | 6 +- crates/benilla-world/src/weather/mod.rs | 8 +- crates/benilla/build.rs | 18 +- docs/DEVIATIONS.md | 252 ++- docs/MAP.md | 22 +- 527 files changed, 48077 insertions(+), 28675 deletions(-) create mode 100644 crates/benilla-app/src/cvars/callbacks.rs create mode 100644 crates/benilla-app/src/lanes/account_data_live_tests.rs create mode 100644 crates/benilla-app/src/lanes/alert_live_tests.rs create mode 100644 crates/benilla-app/src/lanes/chat_clock_live_tests.rs create mode 100644 crates/benilla-app/src/lanes/close_parked_tests.rs create mode 100644 crates/benilla-app/src/lanes/deactivate_live_tests.rs create mode 100644 crates/benilla-app/src/lanes/death_live_tests.rs create mode 100644 crates/benilla-app/src/lanes/follow_live_tests.rs create mode 100644 crates/benilla-app/src/lanes/group_live_tests.rs create mode 100644 crates/benilla-app/src/lanes/instance_live_tests.rs create mode 100644 crates/benilla-app/src/lanes/item_text_live_tests.rs create mode 100644 crates/benilla-app/src/lanes/item_view_live_tests.rs create mode 100644 crates/benilla-app/src/lanes/lock_live_tests.rs create mode 100644 crates/benilla-app/src/lanes/logout_live_tests.rs create mode 100644 crates/benilla-app/src/lanes/loot_roll_live_tests.rs create mode 100644 crates/benilla-app/src/lanes/plate_live_tests.rs create mode 100644 crates/benilla-app/src/lanes/profession_live_tests.rs create mode 100644 crates/benilla-app/src/lanes/record_callback_tests.rs create mode 100644 crates/benilla-app/src/lanes/spell_slot_live_tests.rs create mode 100644 crates/benilla-app/src/lanes/tooltip_live_tests.rs create mode 100644 crates/benilla-app/src/lanes/tutorial_live_tests.rs create mode 100644 crates/benilla-app/src/lanes/ui_error_live_tests.rs create mode 100644 crates/benilla-app/src/lanes/world_map_live_tests.rs create mode 100644 crates/benilla-app/src/lanes/world_map_update_tests.rs create mode 100644 crates/benilla-app/src/lanes/world_state_live_tests.rs create mode 100644 crates/benilla-app/src/lanes/worn_live_tests.rs create mode 100644 crates/benilla-app/src/net/objects/item_deactivate.rs create mode 100644 crates/benilla-app/src/script_calls/tests/plates.rs create mode 100644 crates/benilla-app/src/script_calls/tests/ticks.rs create mode 100644 crates/benilla-app/src/spell/level.rs delete mode 100644 crates/benilla-app/src/spell/reads.rs create mode 100644 crates/benilla-app/src/spell/targeting/live.rs create mode 100644 crates/benilla-app/src/ui_action/spell_slots.rs delete mode 100644 crates/benilla-app/src/ui_action/unlearn.rs create mode 100644 crates/benilla-app/src/ui_chat/walk_live_tests.rs delete mode 100644 crates/benilla-app/src/ui_follow.rs create mode 100644 crates/benilla-app/src/ui_item_text/live.rs delete mode 100644 crates/benilla-app/src/ui_script/gate.rs create mode 100644 crates/benilla-app/src/ui_script/raise_origin.rs delete mode 100644 crates/benilla-app/src/ui_tooltip/bench.rs delete mode 100644 crates/benilla-app/src/ui_tooltip/deps_tests.rs delete mode 100644 crates/benilla-app/src/ui_tooltip/feed_tests.rs create mode 100644 crates/benilla-app/src/ui_tooltip/live.rs create mode 100644 crates/benilla-app/src/ui_tooltip/live_tests.rs create mode 100644 crates/benilla-app/src/ui_tooltip/plate.rs delete mode 100644 crates/benilla-app/src/ui_tooltip/spell_deps.rs rename crates/benilla-app/src/ui_tooltip/{spell_feed.rs => spell_view.rs} (50%) create mode 100644 crates/benilla-app/src/ui_unit/reach.rs delete mode 100644 crates/benilla-app/src/ui_unit/views/families.rs create mode 100644 crates/benilla-ui/src/script/origin.rs create mode 100644 crates/benilla-ui/src/script/worn.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ad8569898..f53a04693 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -89,3 +89,15 @@ jobs: - name: name the test a crash took down if: failure() run: cargo test --workspace --no-fail-fast -- --test-threads=1 + # The player binary links with the main thread's stack its build script asks for: MSVC's own + # 1 MB overflows at the login screen. Read from the PE header (PE32+: optional header +72). + - name: player stack + if: ${{ !cancelled() }} + shell: pwsh + run: | + cargo build -p benilla --no-default-features + $b = [IO.File]::ReadAllBytes("target\debug\benilla.exe") + $pe = [BitConverter]::ToInt32($b, 0x3c) + $reserve = [BitConverter]::ToUInt64($b, $pe + 24 + 72) + "SizeOfStackReserve: $reserve" + if ($reserve -lt 8MB) { exit 1 } diff --git a/crates/benilla-app/src/account_data/mod.rs b/crates/benilla-app/src/account_data/mod.rs index 5981a6a21..495866291 100644 --- a/crates/benilla-app/src/account_data/mod.rs +++ b/crates/benilla-app/src/account_data/mod.rs @@ -21,7 +21,9 @@ //! (`0x4900c2`), the bindings (`0x4b62ef`, `0x4b6300`), the macros (`0x4f0a7c`, `0x4f0a8d`) and //! the chat setup (`0x498a2c`). It runs at once on a settled section, else it is held and runs //! once the section settles, at the check (`0x5afaca`) or the download (`0x5afd19`), and again at -//! every later settling ([`AccountData::register`], [`AccountData::take_owed`]). A server that +//! every later settling ([`AccountData::register`], [`AccountData::take_owed`]). A settled +//! reader runs on its own lane at its settling's stamp ([`AccountData::owed_at`]), so inside the +//! packet that settled it, ahead of the next packet's events. A server that //! sends no digests leaves every section pending and its reader unrun. A held reader's section //! is written by none of benilla's saves, as `0x5afed0` writes no pending section (`0x5afee0`). diff --git a/crates/benilla-app/src/addon_harness/mod.rs b/crates/benilla-app/src/addon_harness/mod.rs index 4c4f3c77a..af80a4737 100644 --- a/crates/benilla-app/src/addon_harness/mod.rs +++ b/crates/benilla-app/src/addon_harness/mod.rs @@ -1390,8 +1390,8 @@ fn equip_slot(item_id: u32, name: &str) -> benilla_ui::script::InvSlotView { // A cached record of a wearable type. inventory_type: Some(1), name: Some(name.to_string()), - // Full durability: the setter fires `UPDATE_INVENTORY_ALERTS`, and a worn item would light - // DurabilityFrame. + // Full durability: a worn item short of it would light DurabilityFrame at an alert + // recompute. durability: Some((100, 100)), link: Some(format!("|cff1eff00|Hitem:{item_id}:0:0:0|h[{name}]|h|r")), ..Default::default() diff --git a/crates/benilla-app/src/area.rs b/crates/benilla-app/src/area.rs index 31a9915f7..3ba99d599 100644 --- a/crates/benilla-app/src/area.rs +++ b/crates/benilla-app/src/area.rs @@ -123,7 +123,7 @@ fn elect_event(cache: &ZoneCache, next: &ZoneSignal) -> Option<&'static str> { /// active player's, and nothing with neither held (`0x5db937`, `0x5db956`, `0x5db95d`): after a /// worldport frees every object, the commit waits for our player's create. It runs on the tick /// after the tick's packets (category 6's drain `0x403620`, then category 5's `0x401ec0`), so it -/// reads what the unit feed pushed of a player that arrived this frame. +/// reads a player that arrived this frame. #[allow(clippy::too_many_arguments)] // a Bevy system's full input set fn feed_zone_events( mut ticks: Local, @@ -342,11 +342,15 @@ impl Plugin for AreaPlugin { Update, // After the leaf authority: leaf, indoor bit and names must come from one frame, // as in the client's single-pass resolve (`0x67e510`), or a stale leaf fires a - // spurious splash. After the unit feed too, by the sets: the commit's handlers read - // our template as the frame's packets left it. + // spurious splash. The commit's handlers read our template through the host, as the + // frame's packets left it. feed_zone_events .after(crate::ui_script::UiTick) - .after(benilla_world::terrain_stream::AreaAuthoritySet), + .after(benilla_world::terrain_stream::AreaAuthoritySet) + // And after the stream, the sound's listener and the hover, which read CVar + // knobs (the clip and detail, the volumes, the rig) its handlers' calls write. + .after(benilla_world::schedule::WorldStage::Stream) + .after(crate::target::TargetUpdate), ); } } @@ -543,17 +547,17 @@ mod tests { world.resource_mut::().0.insert(ME, me); let pvp = |app: &mut App| { let world = app.world_mut(); - crate::ui_unit::run_feed_units_once(world); // The poll's tenth tick (`0x5db906`). for _ in 0..10 { world.run_system_cached(feed_zone_events).unwrap(); } - world - .non_send_resource::() - .eval::<(Option, Option)>( - "local t, f = GetZonePVPInfo() return t, f", - ) - .unwrap() + crate::script_calls::with_hosted_vm(world, |s| { + s.expect("a VM") + .eval::<(Option, Option)>( + "local t, f = GetZonePVPInfo() return t, f", + ) + .unwrap() + }) }; assert_eq!(pvp(&mut app), (None, None), "no template: nil"); app.world_mut().entity_mut(me).insert(store(Some(ORC))); @@ -611,7 +615,6 @@ mod tests { world.insert_non_send_resource(script); let frame = |app: &mut App| { let world = app.world_mut(); - crate::ui_unit::run_feed_units_once(world); // The poll's tenth tick (`0x5db906`). for _ in 0..10 { world.run_system_cached(feed_zone_events).unwrap(); @@ -634,16 +637,6 @@ mod tests { assert_eq!(frame(&mut app), ["friendly"]); } - /// The commit reads what the unit feed pushed of a player that arrived this frame. - #[test] - fn the_zone_commit_runs_after_the_unit_feed() { - let mut app = crate::game_plugins::schedule_tests::headless_client(); - assert!(crate::ui_unit::feed_units_runs_before( - &mut app, - feed_zone_events - )); - } - /// The poll `0x5db900` counts its calls (`0xc4d790`) and reports the area only on the tenth /// (`0x5db906`, `jl 0x5db975`), subtracting ten (`0x5db917`): the first commit lands on the /// tenth tick, and a subzone crossed and recrossed between two polls signals nothing. diff --git a/crates/benilla-app/src/bindings.rs b/crates/benilla-app/src/bindings.rs index 3eb5f7192..6988a9e50 100644 --- a/crates/benilla-app/src/bindings.rs +++ b/crates/benilla-app/src/bindings.rs @@ -30,7 +30,7 @@ use bevy::input::ButtonState; use bevy::prelude::*; use benilla_ui::script::keybind::KeybindRequest; -use benilla_ui::script::{KeyUp, KeyWalk, UiScript}; +use benilla_ui::script::{KeyUp, KeyWalk, PointerTarget, UiScript}; use crate::client_state::InWorldGated; use crate::textinput::keymap::Mods; @@ -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`. @@ -195,10 +226,31 @@ impl BindingsState { && (self.just_pressed(Input::TurnOrAction) || self.just_pressed(Input::CameraOrSelectOrMove)) } + /// A primary bit is held (`[InputControl+4] & 3`), whichever call set it: a mouse command's, + /// or `MouselookStart`'s TurnOrAction bit. + pub(crate) fn primary_held(&self) -> bool { + self.pressed(Input::TurnOrAction) || self.pressed(Input::CameraOrSelectOrMove) + } + /// A call made with no host lent, applied where the engine takes it, its edge unsettled for + /// the frame's readers: `MouselookStart`'s bit, which the look session takes at its latch. + pub(crate) fn apply_unhosted(&mut self, input: benilla_ui::script::BindingInput) { + self.apply_script_input(vec![input]); + } + /// The release of both primary bits (`0x5144c0` → `0x514b70(-1, …)`), the session's end. + pub(crate) fn release_primaries(&mut self) { + self.held + .retain(|&i| !matches!(i, Input::TurnOrAction | Input::CameraOrSelectOrMove)); + } + /// The next frame begins: this one's edges are spent, as the binding pass's head spends them. + #[cfg(test)] + pub(crate) fn next_frame_for_test(&mut self) { + self.begin_pass(); + self.end_pass(); + } } -/// Which files this session's bindings live in: written by [`seed_bindings_for_vm`], read by the -/// save. +/// Which files this session's bindings live in: written by [`register_binding_readers`], read by +/// the save. #[derive(Resource, Default)] struct BindingFiles { account: Option, @@ -229,6 +281,7 @@ pub(crate) struct BindingsPlugin; impl Plugin for BindingsPlugin { fn build(&self, app: &mut App) { + use crate::lanes::LaneApp; app.add_plugins(layout::plugin) .configure_sets( Update, @@ -240,60 +293,71 @@ impl Plugin for BindingsPlugin { .configure_sets(Update, BindingHead.before(BindingTail)) .init_resource::() .init_resource::() + .init_resource::() .init_resource::() .add_systems( Update, ( - // The key sets are seeded at the VM's birth, not here: `seed_bindings_for_vm` - // runs in `load_ingame_ui_on_world_entry`, before FrameXML and every addon; + // The key sets are read by the interface load, not here: the defaults at the + // VM's birth (`seed_bindings_for_vm`), before FrameXML and every addon, and + // the stored sets at the readers' registration (`register_binding_readers`); // the commands come with the load. (sync_dispatch, begin_dispatch).chain().in_set(BindingHead), end_dispatch.in_set(BindingTail), // After the tick: the requests are Lua's own (`SaveBindings`), queued by // handlers the tick dispatched, and a save must not wait a frame. drain_binding_requests.in_set(crate::ui_script::UiDrain), - reread_arrived_bindings - .run_if(crate::ui_script::ingame_ui_up) - .in_set(crate::ui_script::UiFeed) - .in_set(InWorldGated), ), + ) + // The readers of the binding sections, each at its section's settling. + .add_exclusive_lane( + "binding arrivals", + peek_arrived_bindings, + fire_arrived_bindings, + arrived_bindings_reads, ); } } -/// Seed the key sets at the VM's birth, before any interface file runs: the defaults off the -/// player's chain (`WTF\DefaultBindings.wtf`), the account set, and the character's set if it has -/// one. The keys are their own table, so a command a later file declares finds its keys there, -/// and stock `ActionButton_OnLoad` paints its hotkey corner from `GetBindingKey` at load. +/// Seed set 0, the defaults off the player's chain (`WTF\DefaultBindings.wtf`), at the VM's +/// birth, before any interface file runs. The live table stays empty until the readers run +/// ([`register_binding_readers`]). /// /// The reference reads the defaults later in `UI_Init` (`0x4b62b0` at `0x4900c7`); here they are /// read first because the stored sets are diffs against them ([`store`]'s deviation), and nothing /// reads set 0 before `LoadBindings(0)`. -pub(crate) fn seed_bindings_for_vm(world: &mut World, script: &mut UiScript) { - let defaults = crate::ui_script::default_bindings(); - script.set_default_bindings(defaults); +pub(crate) fn seed_bindings_for_vm(script: &mut UiScript) { + script.set_default_bindings(crate::ui_script::default_bindings()); +} + +/// The reader's registration (`0x4b6240` through `0x5afe50` at `0x4b62ef` and `0x4b6300`), which +/// the interface load makes after the layout's and ahead of the macros' (`0x4900c7` → `0x4b62b0`): +/// a set is read now on a settled section (a `/reload`), else held until it settles +/// ([`fire_arrived_bindings`]). Until set 2's read chooses, the live table is empty, as the load +/// builds the binding object anew (`0x48feb0` → `0x4b6050`) after the last shutdown destroyed it +/// (`0x490cb5` → `0x4b6100`). The reads run with the host lent, for the set choice's signal. +pub(crate) fn register_binding_readers(world: &mut World, script: &mut UiScript) { let account = crate::local_state::bindings_account_path(); - // No roster identity (a rigged or capture run) leaves set 2 unseeded. + // No roster identity (a rigged or capture run) leaves set 2 unread. let id = world .get_resource::() .and_then(crate::ui_macro::identity); let character = id .as_ref() .and_then(|(realm, name)| crate::local_state::bindings_character_path(realm, name)); - // The reader (`0x4b6240`) registers for each section through `0x5afe50` (`0x4b62ef`, - // `0x4b6300`): a set is read now on a settled section, else held until it settles - // ([`reread_arrived_bindings`]), the live table empty until set 2's read chooses. let held = world .get_resource::() .map_or([false; 2], |data| { crate::account_data::BINDINGS.map(|section| !data.register(section)) }); - if !held[0] { - read_account_set(script, &account); - } - if !held[1] { - read_character_set(script, &character); - } + crate::script_calls::lent_by_world(world, script, |script| { + if !held[0] { + read_account_set(script, &account); + } + if !held[1] { + read_character_set(script, &character); + } + }); if let Some(mut files) = world.get_resource_mut::() { *files.held.get(script) = held; files.account = account; @@ -317,40 +381,91 @@ fn read_account_set(script: &mut UiScript, account: &Option) /// Section 3's read (`0x4b6240` with set 2): set 2 from the character file as /// [`read_account_set`] reads set 1, then the set choice (`0x4b629a` → `0x4b64b0`): the /// character's set in use when it has keys, else set 1 as it then stands, the defaults when it is -/// still empty (`0x4b64e2`). +/// still empty (`0x4b64e2`). Its copy into the live set signals `UPDATE_BINDINGS` in place +/// (`0x4b6310(2, 3)`, `0x4b6498`). fn read_character_set(script: &mut UiScript, character: &Option) { if let Some(overrides) = read_diff(character) { let defaults = script.default_bindings(); script.seed_binding_set(2, Some(store::resolve(&overrides, &defaults))); info!("bindings: character-specific set read"); } + // The choice zeroes the dirty mask before its copy into the live set (`0x4b6506`), so no + // `SaveBindings` made ahead of it is written: its queued files are dropped. + script.take_keybind_requests(); script.load_binding_set(if script.character_bindings_exist() { 2 } else { 1 }); + if script.take_keybinds_signal_owed() { + script.fire_event("UPDATE_BINDINGS", vec![]); + } } -/// A binding section that settled: its set read again, as the reference's reader (`0x4b6240`) -/// runs once its section settles (`0x5afaca`, `0x5afd19`), in the table's order. -fn reread_arrived_bindings( - mut hosted_vm: crate::script_calls::HostedVm, - mut files: ResMut, - data: Option>, -) { - let Some(data) = data else { return }; - hosted_vm.run(|script| { - let Some(script) = script else { return }; - let [account, character] = crate::account_data::BINDINGS.map(|s| data.take_owed(s)); - if account { - read_account_set(script, &files.account); - files.held.get(script)[0] = false; +/// The binding section that settled first, its reader still owed, with its settling's stamp. +fn arrived_binding(world: &World) -> Option<(usize, crate::lanes::Stamp)> { + let data = world.get_resource::()?; + crate::account_data::BINDINGS + .into_iter() + .filter_map(|section| Some((section, data.owed_at(section)?))) + .min_by_key(|(_, at)| *at) +} + +/// A binding section's settling, the head of its lane: the reader (`0x4b6240`) runs where the +/// handler that settled it ran (`0x5afaca` in the digests' check, `0x5afd19` in a download), in +/// the packets' order with the other lanes' events. +fn peek_arrived_bindings(world: &World) -> Option { + arrived_binding(world).map(|(_, at)| at) +} + +/// The settled section's set read into the VM, as the firing of its settling's stamp: section 2 +/// reads set 1, section 3 reads set 2 and chooses the set in use, signalling `UPDATE_BINDINGS` +/// ([`read_character_set`]). +fn fire_arrived_bindings(In(until): In, world: &mut World) { + let Some((section, at)) = arrived_binding(world).filter(|(_, at)| until.admits(*at)) else { + return; + }; + // No VM: the settling waits for one. + if !world.contains_non_send::() { + return; + } + world + .resource::() + .take_owed(section); + crate::lanes::firing(at, || { + world.try_resource_scope(|world, mut files: Mut| { + crate::script_calls::with_hosted_vm(world, |script| { + let Some(script) = script else { return }; + if section == crate::account_data::BINDINGS[0] { + read_account_set(script, &files.account); + files.held.get(script)[0] = false; + return; + } + read_character_set(script, &files.character); + files.held.get(script)[1] = false; + }) + }) + }); +} + +/// What the bindings lane's firing touches beside the call host and its own lane: the files. +fn arrived_bindings_reads(world: &mut World) -> bevy::ecs::query::FilteredAccessSet { + fn read(_: Option>) {} + crate::lanes::system_access(world, read) +} + +/// Every binding settling fired alone, in order, for a test that drives the lane without the +/// others. +#[cfg(test)] +fn reread_arrived_bindings(world: &mut World) { + while let Some(head) = peek_arrived_bindings(world) { + world + .run_system_cached_with(fire_arrived_bindings, crate::lanes::Until::all()) + .expect("the bindings lane fires"); + if peek_arrived_bindings(world) == Some(head) { + break; } - if character { - read_character_set(script, &files.character); - files.held.get(script)[1] = false; - } - }) + } } /// Read and parse one diff file; `None` (the defaults) when absent or unreadable. @@ -367,7 +482,11 @@ fn read_diff(path: &Option) -> Option, @@ -430,11 +549,10 @@ fn write_file(path: &Option, text: &str) { } /// Rebuild the dispatch map when the engine table moved (a rebind, a set switch, the seed, a -/// load, a registration), and fire the `UPDATE_BINDINGS` a host-side load owes so the Lua -/// consumers (the action bar's hotkey corners) repaint. The reference signals it from `SetBinding` -/// (`0x4b805b`), which signals in place, and from the copy of a set into the live table -/// (`0x4b649d`); reading a `Bindings.xml` (`0x4b6f70`) signals nothing. -fn sync_dispatch( +/// load, a registration). It signals nothing: `SetBinding` (`0x4b805b`) and the copy of a set +/// into the live table (`0x4b649d`, [`read_character_set`]) signal in place, and reading a +/// `Bindings.xml` (`0x4b6f70`) signals nothing. +pub(crate) fn sync_dispatch( mut hosted_vm: crate::script_calls::HostedVm, mut dispatch: ResMut, ) { @@ -453,9 +571,6 @@ fn sync_dispatch( } } } - if script.take_keybinds_signal_owed() { - script.fire_event("UPDATE_BINDINGS", vec![]); - } }) } @@ -553,18 +668,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 @@ -576,35 +704,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. @@ -624,7 +727,7 @@ pub(crate) struct KeyVerdict { #[derive(bevy::ecs::system::SystemParam)] pub(crate) struct WorldFrameBindings<'w> { dispatch: Option>, - state: Option>, + state: Option>, } impl WorldFrameBindings<'_> { @@ -643,18 +746,18 @@ impl WorldFrameBindings<'_> { } } - /// One button record; `over_ui` is whether a frame was hovered when it came. + /// One button record, which the interface's walk sent to `reach`. pub(crate) fn button( &mut self, script: Option<&mut UiScript>, button: MouseButton, pressed: ButtonState, mods: Mods, - over_ui: bool, + reach: PointerTarget, ) { if let (Some(dispatch), Some(state)) = (self.dispatch.as_deref(), self.state.as_deref_mut()) { - button_leg(dispatch, state, script, button, pressed, mods, over_ui); + button_leg(dispatch, state, script, button, pressed, mods, reach); } } @@ -699,7 +802,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, @@ -804,23 +907,29 @@ const BIND_BUTTONS: [MouseButton; 5] = [ MouseButton::Back, ]; -/// A button record's binding: a press only with the cursor over the world (a frame owns its -/// clicks), a release always. +/// A button record's binding, the world frame's slot's (`0x483c40`, `0x483cb0`): a press whose +/// target was the world frame runs it; a release runs the up-half of what its press latched, +/// unless a frame of the interface's took it, and with none latched, as for a press that went to +/// a frame before freelook released through the hook (`0x492be5`), the chord the release makes +/// (`0x4b6aa0` → `0x4b7990(…, 0)`) when it reached the world frame. fn button_leg( dispatch: &BindingDispatch, - state: &mut BindingsState, + state: &mut BindingLatches, script: Option<&mut UiScript>, button: MouseButton, pressed: ButtonState, mods: Mods, - over_ui: bool, + reach: PointerTarget, ) { if !BIND_BUTTONS.contains(&button) { return; } match pressed { ButtonState::Pressed => { - if mods.sup || over_ui || state.latched.iter().any(|(k, _)| *k == Held::Mouse(button)) { + if mods.sup + || reach == PointerTarget::Ui + || state.latched.iter().any(|(k, _)| *k == Held::Mouse(button)) + { return; } let chord = Chord { @@ -833,40 +942,62 @@ fn button_leg( press(state, script, command, Held::Mouse(button)); } } - ButtonState::Released => release(state, script, Held::Mouse(button)), + ButtonState::Released => { + let latched = state.latched.iter().any(|(k, _)| *k == Held::Mouse(button)); + if reach == PointerTarget::Ui { + state.latched.retain(|(k, _)| *k != Held::Mouse(button)); + } else if latched { + release(state, script, Held::Mouse(button)); + } else if reach == PointerTarget::World && !mods.sup { + let chord = Chord { + alt: mods.alt, + ctrl: mods.ctrl, + shift: mods.shift, + key: BindKey::Mouse(button), + }; + if let (Some(command), Some(s)) = (dispatch.resolve(chord, false), script) { + if let Err(e) = s.execute_binding(command, false) { + warn!("bindings({command}): {e}"); + } + } + } + } } } /// 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 @@ -894,8 +1025,14 @@ fn dispatch_records( }; legs.key(s.as_deref_mut(), ev, r.mods, verdict, &layout); } + // A release reached no frame: the test leaves no capture to route it. Record::Button { button, state } => { - legs.button(s.as_deref_mut(), *button, *state, r.mods, hover.0.is_some()); + let reach = match (*state, hover.0) { + (ButtonState::Released, _) => PointerTarget::Nothing, + (_, Some(_)) => PointerTarget::Ui, + (_, None) => PointerTarget::World, + }; + legs.button(s.as_deref_mut(), *button, *state, r.mods, reach); } Record::Move => {} Record::Wheel { up } => legs.wheel(s.as_deref_mut(), r.mods, *up), @@ -943,7 +1080,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}"); @@ -954,7 +1091,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 { @@ -1117,6 +1254,7 @@ mod tests { .init_resource::() .init_resource::() .init_resource::() + .init_resource::() .init_resource::() .init_resource::() .add_systems( @@ -1190,8 +1328,9 @@ mod tests { } /// Only the two reference sites signal `UPDATE_BINDINGS`: a set's copy into the live table - /// (`0x4b649d`, here the host's load) and a stored `SetBinding`. Reading an addon's - /// `Bindings.xml` (`0x4b6f70`) moves the dispatch table and signals nothing. + /// (`0x4b649d`, here the reader's set choice, in place) and a stored `SetBinding`. Reading an + /// addon's `Bindings.xml` (`0x4b6f70`) moves the dispatch table and signals nothing, and the + /// frame's dispatch pass signals nothing of its own. #[test] fn registering_an_addons_bindings_signals_nothing_but_a_load_does() { let script = core_script(); @@ -1205,11 +1344,9 @@ mod tests { app.update(); assert_eq!( lua_count(&app, "UPDATES"), - 1, - "the seed's load owes its signal" + 0, + "the fixture's load is no reader's: the frame pays it nothing" ); - app.update(); - assert_eq!(lua_count(&app, "UPDATES"), 1, "once"); { let script = app.world().non_send_resource::(); @@ -1237,11 +1374,17 @@ mod tests { "but the dispatch map re-derives" ); - app.world_mut() - .non_send_resource_mut::() - .load_binding_set(1); + read_character_set( + &mut app.world_mut().non_send_resource_mut::(), + &None, + ); + assert_eq!( + lua_count(&app, "UPDATES"), + 1, + "the set choice does, inside the read" + ); app.update(); - assert_eq!(lua_count(&app, "UPDATES"), 1, "a load does"); + assert_eq!(lua_count(&app, "UPDATES"), 1, "once"); } /// A `runOnUp` body is one chunk run twice, `keystate` "down" then "up"; a plain one runs on @@ -1606,7 +1749,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 @@ -2280,6 +2423,60 @@ mod tests { assert!(!state(&app).steering()); } + /// Emptied button planes end a held drag, as a window's focus loss or the cover's reset leaves + /// them, with no release record: the stuck-latch sweep runs MOVEANDSTEER's up-half, whose + /// Stops lower both mouse bits. + #[test] + fn emptied_button_planes_end_a_held_drag() { + let mut app = harness(); + mouse(&mut app, MouseButton::Middle, ButtonState::Pressed); + app.update(); + assert!(state(&app).steering()); + app.world_mut() + .resource_mut::>() + .reset_all(); + app.update(); + assert!(!state(&app).steering(), "the sweep ran the up-half"); + } + + /// A rebound BUTTON2 runs only its own command: the release of a right press the world frame + /// took lowers no TurnOrAction bit a `MouselookStart` holds, as the world frame's release slot + /// runs the button's binding alone (`0x483cb0` → `0x4b7990`). + #[test] + fn a_rebound_right_buttons_release_ends_no_mouselook() { + use bevy::ecs::system::RunSystemOnce; + let mut script = UiScript::new().expect("VM"); + script.set_default_bindings(benilla_ui::script::keybind::parse_bindings_wtf(&format!( + "{DEFAULTS}bind BUTTON2 TOGGLEUI\r\n" + ))); + script.load_binding_set(1); + script.register_bindings(&benilla_ui::bindings_xml::parse(CORE).expect("well-formed")); + let mut app = vm_harness(script); + app.init_resource::(); + app.update(); + let latch = |app: &mut App| { + app.world_mut() + .run_system_once(crate::player::camera::latch_world_mouse) + .expect("the latch runs"); + }; + app.world() + .non_send_resource::() + .run("MouselookStart()") + .expect("runs"); + latch(&mut app); + assert!(state(&app).pressed(Input::TurnOrAction)); + for pressed in [ButtonState::Pressed, ButtonState::Released] { + mouse(&mut app, MouseButton::Right, pressed); + app.update(); + latch(&mut app); + } + assert_eq!(lua_count(&app, "UITOGGLES"), 1, "BUTTON2's own command ran"); + assert!( + state(&app).pressed(Input::TurnOrAction), + "the MouselookStart still holds the bit" + ); + } + /// The notches the sweep left to the world each run CAMERAZOOMIN's `CameraZoomIn(1.0)`, and /// none left run nothing. #[test] @@ -2627,7 +2824,8 @@ mod tests { .init_resource::() .add_systems(Update, reread_arrived_bindings); let mut script = core_script(); - seed_bindings_for_vm(app.world_mut(), &mut script); + seed_bindings_for_vm(&mut script); + register_binding_readers(app.world_mut(), &mut script); app.insert_non_send_resource(script); let jump = r#"return GetBindingKey("JUMP") or """#; assert_ne!(eval_str(&app, jump), "G", "pending: the sets are held"); @@ -2692,7 +2890,8 @@ mod tests { .resource::() .settle_section_for_test(2); let mut script = core_script(); - seed_bindings_for_vm(app.world_mut(), &mut script); + seed_bindings_for_vm(&mut script); + register_binding_readers(app.world_mut(), &mut script); app.insert_non_send_resource(script); app.world() .non_send_resource::() @@ -2713,6 +2912,58 @@ mod tests { std::fs::remove_dir_all(&tmp).ok(); } + /// A `/reload` meets both binding sections settled, so the readers run at their registration, + /// after the addons' files (`0x4900c7` → `0x4b62b0`). A `SaveBindings(1)` at file scope is + /// never written: the set choice zeroes the dirty mask (`0x4b6506`), so the character's file + /// stays and its set is the one in use. + #[test] + fn a_save_before_the_set_choice_is_never_written() { + let _l = crate::local_state::test_env::ENV_LOCK + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let tmp = std::env::temp_dir().join(format!("benilla-bind-early-{}", std::process::id())); + std::fs::remove_dir_all(&tmp).ok(); + let _c = crate::local_state::test_env::EnvGuard::unset("WOW_CAPTURE"); + let _h = crate::local_state::test_env::EnvGuard::set("BENILLA_HOME", tmp.to_str().unwrap()); + let account = crate::local_state::bindings_account_path().unwrap(); + crate::local_state::write_atomic(&account, "bind JUMP G\n").unwrap(); + let character = crate::local_state::bindings_character_path("Realm", "Probeone").unwrap(); + crate::local_state::write_atomic(&character, "bind JUMP H\n").unwrap(); + let mut app = App::new(); + app.insert_resource(crate::glue_session::roster::Roster::with_pending_pick( + vec![crate::glue_session::roster::test_character(7, "Probeone")], + 7, + )) + .init_resource::() + .init_resource::() + .add_systems( + Update, + (reread_arrived_bindings, drain_binding_requests).chain(), + ); + app.world() + .resource::() + .settle_for_test(Some(("Realm".into(), "Probeone".into()))); + let mut script = core_script(); + seed_bindings_for_vm(&mut script); + // An addon's file scope, ahead of the readers. + script.run("SaveBindings(1)").unwrap(); + register_binding_readers(app.world_mut(), &mut script); + app.insert_non_send_resource(script); + app.update(); + assert_eq!( + std::fs::read_to_string(&character).ok().as_deref(), + Some("bind JUMP H\n"), + "the character's file stays" + ); + assert_eq!( + eval_str(&app, "return tostring(GetCurrentBindingSet())"), + "2" + ); + assert_eq!(eval_str(&app, r#"return GetBindingKey("JUMP") or """#), "H"); + drop(app); + std::fs::remove_dir_all(&tmp).ok(); + } + /// `SaveBindings(1)` marks both sections and `SaveBindings(2)` the character's (`0x4b65ed`, /// `0x4b6617`) for the interface's shutdown, the reference's one write of them (`0x490c64`); /// the save itself arms no upload. diff --git a/crates/benilla-app/src/bindings/script_input.rs b/crates/benilla-app/src/bindings/script_input.rs index 18852ee13..945e4117b 100644 --- a/crates/benilla-app/src/bindings/script_input.rs +++ b/crates/benilla-app/src/bindings/script_input.rs @@ -77,36 +77,88 @@ 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) + } + + /// Whether `input` is a Stop of a bit held now: the release `0x514b70` answers a change, so + /// its `SetCommands` runs the tick after it (`0x5151a0`). + pub(crate) fn releases(&self, input: BindingInput) -> bool { + matches!(input, BindingInput::Stop(held) if self.held.contains(&held_input(held))) + } + + 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]`: a call + // with no host lent passes 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 +169,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/capture/fixtures.rs b/crates/benilla-app/src/capture/fixtures.rs index 5e8530eb3..59283ae22 100644 --- a/crates/benilla-app/src/capture/fixtures.rs +++ b/crates/benilla-app/src/capture/fixtures.rs @@ -85,9 +85,10 @@ const TRAINER_BLACKSMITH: TrainerSeed = TrainerSeed { ], }; -/// Seeds the fixture window's state once the scene is resident; the real feeds push it into the VM -/// during the settle window as live wire data would. Icons resolve through the offline -/// `ItemDisplayCatalog`, and names go straight into the caches. +/// Seeds the fixture window's state once the scene is resident: the getters read the world it +/// spawns through the host, and the remaining feeds push their copies into the VM during the settle +/// window, as live wire data would. Icons resolve through the offline `ItemDisplayCatalog`, and +/// names go straight into the caches. #[allow(clippy::type_complexity)] // a Bevy system's full input set pub(super) fn seed_ui_fixture( mut vm: crate::script_calls::VmWith<( @@ -106,6 +107,8 @@ pub(super) fn seed_ui_fixture( ResMut<'static, crate::loading_screen::LoadingScreen>, ResMut<'static, crate::ui_gossip::GossipState>, ResMut<'static, crate::ui_quest::QuestGiver>, + // The quest cache, which the host's rebuild lookups ask too. + ResMut<'static, crate::ui_quest_log::QuestLog>, ), // The tooltip fixture's set row and its members' names, read by the set block's host. ( @@ -116,7 +119,6 @@ pub(super) fn seed_ui_fixture( mut ctx: ResMut, mut commands: Commands, progress: Res, - mut quest_log: ResMut, icons: Option>, ) { let icons = icons.as_deref(); @@ -126,7 +128,7 @@ pub(super) fn seed_ui_fixture( vm.turn(|script, parts| { let (mut loot, mut names, mut selection, mut player, store, rest, set_parts) = parts; let (mut item_sets, mut item_names) = set_parts; - let (mut actions, mut exit, mut loading, mut gossip, mut quest) = rest; + let (mut actions, mut exit, mut loading, mut gossip, mut quest, mut quest_log) = rest; let (mut items, mut index, mut home_bind) = store; // A glue-screen capture has no world scenario, and no glue screen opens a UI fixture. let Some(scenario) = ctx.scenario else { @@ -220,14 +222,17 @@ pub(super) fn seed_ui_fixture( match fixture { // Nothing to open: the loaded UI and `demo_unit_feed`'s player and target are the - // fixture. The combo dots read the active player's class (`0x51a1cc`), so - // `ui-combopoints` holds one: a level-12 rogue on the demo's health, at 45 energy. + // fixture. The combo dots read the active player's class (`0x51a1cc`) and its two + // combo fields against the selection (`0x51a1f3`-`0x51a20d`), so `ui-combopoints` + // holds a level-12 rogue on the demo's health, at 45 energy, with four points banked + // on the wolf it targets. UiFixture::Bare => { if scenario.name == "ui-combopoints" { const PLAYER_GUID: u64 = 0x51; names.insert_player(PLAYER_GUID, "Benilla".into(), None); commands.spawn(( crate::net::ObjectStore(benilla_protocol::ObjectFields::from_pairs(&[ + (2, 0x19), // OBJECT_FIELD_TYPE: object, unit, player (22, 72), // UNIT_FIELD_HEALTH (26, 45), // UNIT_FIELD_POWER4, energy (28, 100), // UNIT_FIELD_MAXHEALTH @@ -235,10 +240,52 @@ pub(super) fn seed_ui_fixture( (34, 12), // UNIT_FIELD_LEVEL // UNIT_FIELD_BYTES_0: night elf, rogue, male, energy (36, 4 | (4 << 8) | (3 << 24)), + // PLAYER_FIELD_COMBO_TARGET, the wolf + (714, WOLF_GUID as u32), + (715, (WOLF_GUID >> 32) as u32), + // PLAYER_FIELD_BYTES byte 1: four combo points + (1222, 4 << 8), ])), crate::net::SelfPlayer, crate::net::Guid(PLAYER_GUID), )); + // The wolf, a level-3 beast on 30 of 50 health, held and selected; the + // select's `PLAYER_TARGET_CHANGED` (`0x49389c`) shows the target frame and + // its dots. + names.insert_creature( + WOLF_ENTRY, + Some(crate::names::CreatureRecord { + name: "Timber Wolf".into(), + subname: None, + creature_type: 1, + pet_family: 0, + rank: 0, + type_flags: 0, + pet_spell_list: 0, + civilian: false, + racial_leader: false, + display_id: 0, + }), + ); + let wolf = commands + .spawn(( + crate::net::Guid(WOLF_GUID), + crate::net::ObjectStore(benilla_protocol::ObjectFields::from_pairs( + &[ + (2, 0x9), // OBJECT_FIELD_TYPE: object, unit + (3, WOLF_ENTRY), // OBJECT_FIELD_ENTRY + (22, 30), // UNIT_FIELD_HEALTH + (28, 50), // UNIT_FIELD_MAXHEALTH + (34, 3), // UNIT_FIELD_LEVEL + (35, WOLF_FACTION), // UNIT_FIELD_FACTIONTEMPLATE + ], + )), + )) + .id(); + index.0.insert(WOLF_GUID, wolf); + selection.target = Some(wolf); + selection.guid = Some(WOLF_GUID); + commands.queue(signal_fixture_target); } } // Holds the world-entry loading screen, tip and all, over the settled scene. @@ -651,8 +698,9 @@ pub(super) fn seed_ui_fixture( } UiFixture::QuestLog => { // The log reads the self player's PLAYER_QUEST_LOG slots, so a synthetic self - // player carries two and `feed_quest_log` runs the real chain. A slot is id, packed - // 6-bit counters plus a state byte, and timer, from field 198. + // player carries two and the rebuild asks the cache for their records through the + // host, the real chain. A slot is id, packed 6-bit counters plus a state byte, and + // timer, from field 198. use benilla_protocol::messages::{ObjectFields, QuestObjective, QuestTemplate}; const KOBOLD_ENTRY: u32 = 90_002; names.insert_creature( @@ -1070,8 +1118,8 @@ pub(super) fn seed_ui_fixture( })); } UiFixture::Character => { - // A synthetic self player carrying the full stat block, which the `ui_char` feed - // turns into snapshots and events as live. A level-12 warrior; positive (stamina, + // A synthetic self player carrying the full stat block, which the stat and slot + // getters read through the host as live. A level-12 warrior; positive (stamina, // fire) and negative (spirit) buffs exercise the green and red stat colours. use benilla_protocol::messages::ObjectFields; const PLAYER_GUID: u64 = 0x51; @@ -1169,18 +1217,18 @@ pub(super) fn seed_ui_fixture( items.insert_template(93_012, Some(arrows)); names.insert_player(PLAYER_GUID, "Benilla".into(), None); - commands.spawn(( - crate::net::ObjectStore(fields), - crate::net::SelfPlayer, - crate::net::Guid(PLAYER_GUID), - )); + // In the index, where the stat getters find the unit the token names (`0x468460`). + let me = commands + .spawn(( + crate::net::ObjectStore(fields), + crate::net::SelfPlayer, + crate::net::Guid(PLAYER_GUID), + )) + .id(); + index.0.insert(PLAYER_GUID, me); - // The C binding's path; the feed pushes over the settle window. - lua = Some(Box::new(move |s: &mut UiScript| { - if let Err(e) = s.run("ToggleCharacter(\"PaperDollFrame\")") { - warn!("capture: ui-char seed failed to open the window: {e}"); - } - })); + // The window opens behind the spawns ([`open_character_fixture`]). + commands.run_system_cached_with(open_character_fixture, PLAYER_GUID); } UiFixture::VPlates => { use benilla_protocol::messages::ObjectFields; @@ -1717,6 +1765,43 @@ pub(super) fn seed_ui_fixture( } } +/// The character fixture's window by the C binding's path, run behind the seed's spawns: the doll +/// and the stat lines read the player `me` and its items at the open, as in game, where they exist +/// before it. Ahead of it, what a login makes: the Enter World commit's copy of the char-enum row +/// the level line reads (`0x5abd9e`), our guid in the token resolver as the world entry seats it, +/// which the stat getters' own-buff leg tests, and the items' creates' signal, +/// `UNIT_INVENTORY_CHANGED` for the owner's tokens (`0x5d85ed`-`0x5d8606`), which the doll's +/// buttons repaint on. +fn open_character_fixture( + In(me): In, + mut vm: crate::script_calls::HostedVm, + names: crate::ui_unit::NameTables, +) { + let names = names.get(); + let named = + |pair: Option<(&str, &str)>| pair.map(|(name, file)| (name.to_string(), file.to_string())); + let record = benilla_ui::script::PlayerRecord { + name: "Benilla".into(), + race: named(names.race(4)), + class: named(names.class(1)), + sex: 2, + }; + vm.run(|s| { + let open = s.map(|s| { + s.set_player_record(record); + s.seat_player_guid(me); + s.fire_event( + "UNIT_INVENTORY_CHANGED", + vec![benilla_ui::script::ScriptValue::Str("player".into())], + ); + s.run("ToggleCharacter(\"PaperDollFrame\")") + }); + if let Some(Err(e)) = open { + warn!("capture: ui-char seed failed to open the window: {e}"); + } + }); +} + /// The `GetTime()` the cooldown filmstrip pins the VM's session clock at, seconds. Large, as /// `CooldownFrame_SetTimer` ignores a start not above 0 (`Cooldown.lua:2`) and the starts here /// are `now - fraction * span`. @@ -1951,8 +2036,8 @@ fn seed_equipped_bags( }; // The equipped-bag slots (inv ids 20-23, `Bag0Slot`-`Bag3Slot`) get an icon each, so each - // window's portrait shows its own bag through `SetBagPortaitTexture`; live, the char feed - // does this. + // window's portrait shows its own bag through `SetBagPortaitTexture`. With no player held the + // getters read this copy; live, they read the player's bags through the host. let mut inv: benilla_ui::script::InventorySlots = Default::default(); for (id, icon_name) in [ (20usize, "INV_Misc_Bag_08"), diff --git a/crates/benilla-app/src/capture/mod.rs b/crates/benilla-app/src/capture/mod.rs index 07cab49de..b5b36f25d 100644 --- a/crates/benilla-app/src/capture/mod.rs +++ b/crates/benilla-app/src/capture/mod.rs @@ -1131,6 +1131,126 @@ mod tests { "the census reads the capture seed among the client's systems" ); } + /// The combo-points fixture's rogue banks its points on the wolf it selects, so the getter + /// the dots read answers four through the host, as in game (`0x51a1f3`-`0x51a20d`). + #[test] + fn the_combo_fixture_banks_its_points_on_its_target() { + use bevy::ecs::system::RunSystemOnce; + let _l = ENV_LOCK + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let _c = EnvGuard::set("WOW_CAPTURE", "ui-combopoints"); + let mut app = crate::game_plugins::schedule_tests::headless_client_with(|app| { + app.add_plugins(super::CapturePlugin); + }); + let world = app.world_mut(); + { + let mut progress = world.resource_mut::(); + progress.ready = 1; + progress.total = 1; + } + world.insert_non_send_resource(benilla_ui::script::UiScript::new().unwrap()); + world.init_resource::(); + world.init_resource::(); + world.init_resource::(); + world.init_resource::(); + world.init_resource::(); + world + .run_system_once(super::fixtures::seed_ui_fixture) + .unwrap(); + world.flush(); + let read = crate::script_calls::with_hosted_vm(world, |s| { + s.expect("a VM") + .eval::<(i64, Option)>("return GetComboPoints(), UnitExists('target')") + .unwrap() + }); + assert_eq!(read, (4, Some(1))); + } + /// The character fixture's doll, by number: once its seed's spawns land, the worn slots' + /// texture getters answer through the host, and the window opened over them shows those + /// textures on the doll's buttons and the buffed stamina green. + #[test] + fn the_char_fixture_fills_the_doll() { + use bevy::ecs::system::RunSystemOnce; + let _data = benilla_formats::wow_data_or_skip!(); + let _l = ENV_LOCK + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let _c = EnvGuard::set("WOW_CAPTURE", "ui-char"); + let mut app = crate::game_plugins::schedule_tests::headless_client_with(|app| { + app.add_plugins(super::CapturePlugin); + }); + let world = app.world_mut(); + { + let mut progress = world.resource_mut::(); + progress.ready = 1; + progress.total = 1; + } + let script = benilla_ui::script::UiScript::new().unwrap(); + for f in crate::ui_script::test_ui::CHARACTER_UI { + crate::ui_script::test_ui::load_ui_strict(&script, f); + } + world.insert_non_send_resource(script); + world.init_resource::(); + world.init_resource::(); + world.init_resource::(); + world.init_resource::(); + world.init_resource::(); + // The level line's race and class names. + let tables = crate::ui_unit::TestNames::english(); + world.insert_resource(crate::chr_classes::ChrRaceTable(tables.races)); + world.insert_resource(crate::chr_classes::ChrClassTable(tables.classes)); + // The fixture's displays (sword, shield, hearthstone), each with its own icon. + let icon = |name: &str| benilla_formats::ItemDisplay { + icon: Some(name.into()), + ..Default::default() + }; + world.insert_resource(crate::entities::ItemDisplays::icons_for_tests( + benilla_formats::ItemDisplayCatalog::from_displays(std::collections::HashMap::from([ + (1542, icon("SWORD")), + (18730, icon("SHIELD")), + (6418, icon("STONE")), + ])), + )); + world + .run_system_once(super::fixtures::seed_ui_fixture) + .unwrap(); + world.flush(); + // Chest, main hand, ranged and ammo: the getters, then the buttons the window drew. + let read = crate::script_calls::with_hosted_vm(world, |s| { + s.expect("a VM") + .eval::>( + r#"local t = {} + for i, slot in ipairs({5, 16, 18, 0}) do + t[i] = GetInventoryItemTexture("player", slot) or "none" + end + for i, name in ipairs({"Chest", "MainHand", "Ranged", "Ammo"}) do + local tex = getglobal("Character" .. name .. "SlotIconTexture") + t[4 + i] = tex:GetTexture() or "none" + end + t[9] = CharacterStatFrame3StatText:GetText() or "none" + t[10] = CharacterFrame:IsVisible() and "shown" or "hidden" + return t"#, + ) + .unwrap() + }); + let errors = world + .non_send_resource::() + .errors(); + assert!(errors.is_empty(), "the open runs clean: {errors:?}"); + assert_eq!(read[9], "shown"); + let icons = ["SHIELD", "SWORD", "STONE", "STONE"]; + let shown = |t: &str, icon: &str| t.to_ascii_uppercase().ends_with(icon); + for (i, icon) in icons.iter().enumerate() { + assert!(shown(&read[i], icon), "the getter, slot {i}: {read:?}"); + assert!(shown(&read[4 + i], icon), "the button, slot {i}: {read:?}"); + } + assert!( + read[8].starts_with("|cff20ff20"), + "the stamina line: {read:?}" + ); + } + /// The vendor and trainer fixtures open through the lists' own opens, so each queues its /// window's `MERCHANT_SHOW` or `TRAINER_SHOW` as a list does. #[test] diff --git a/crates/benilla-app/src/capture/probe_binder.rs b/crates/benilla-app/src/capture/probe_binder.rs index 71cee1825..4c98eabae 100644 --- a/crates/benilla-app/src/capture/probe_binder.rs +++ b/crates/benilla-app/src/capture/probe_binder.rs @@ -27,7 +27,6 @@ use crate::net::{ChatKind, ClientCommand, Guid, HomeBind, NetCommands, NetEntity use crate::player::Player; use crate::ui_binder::BinderState; use crate::ui_gossip::GossipState; -use crate::ui_session::NpcSession; /// Innkeeper Keldamyr's spawn (vmangos `creature` guid 46343), the `.go xyz` target. const INNKEEPER_AT: [f32; 3] = [9802.21, 982.608, 1313.98]; @@ -337,7 +336,7 @@ fn binder_probe( probe.phase = Phase::Done; return; }; - let pending = binder.npc() == Some(innkeeper); + let pending = binder.pending() == Some(innkeeper); let fired = events_len(script) > events_baseline; let area = last_event(script); if pending && fired && !area.is_empty() { @@ -358,7 +357,7 @@ fn binder_probe( {innkeeper:#x}), CONFIRM_BINDER fired={fired}, arg1={area:?}. A packet \ with no parse arm at all falls through to ServerPacket::Other — that is \ what this reading looks like.", - binder.npc() + binder.pending() ); probe.fails += 1; probe.phase = Phase::Done; diff --git a/crates/benilla-app/src/capture/probe_vendor_swap.rs b/crates/benilla-app/src/capture/probe_vendor_swap.rs index d580cdd5d..ee8444124 100644 --- a/crates/benilla-app/src/capture/probe_vendor_swap.rs +++ b/crates/benilla-app/src/capture/probe_vendor_swap.rs @@ -374,7 +374,7 @@ fn vendor_swap_probe( probe.phase = Phase::Done; } None => {} - // The unit feed drops the token the frame after the session clears. + // The token names nobody the frame after the session clears. Some(at) if now - at >= 0.25 => { // `and 1 or 0` turns `UnitExists`'s `1` or nil into a number. let exists: i64 = script diff --git a/crates/benilla-app/src/capture/scenarios.rs b/crates/benilla-app/src/capture/scenarios.rs index 8c3a97dd9..96f47cb82 100644 --- a/crates/benilla-app/src/capture/scenarios.rs +++ b/crates/benilla-app/src/capture/scenarios.rs @@ -747,7 +747,7 @@ pub(super) const ON_DEMAND: &[Scenario] = &[ minute: 720, ui: Some(UiFixture::Bare), }, - // The fixture holds a rogue player and `demo_unit_feed` banks four points on the wolf, for this + // The fixture holds a rogue player with four points banked on the wolf it targets, for this // scenario only; the demo player is otherwise a warrior, which lights no dot. Scenario { name: "ui-combopoints", diff --git a/crates/benilla-app/src/chat_bubble.rs b/crates/benilla-app/src/chat_bubble.rs index 3b09ca9a5..c818cbb48 100644 --- a/crates/benilla-app/src/chat_bubble.rs +++ b/crates/benilla-app/src/chat_bubble.rs @@ -41,7 +41,7 @@ use crate::vplates::{gx_px, plate_basis, text_px, VPlateSet, VPlates}; use benilla_world::view::WorldCamera; /// The two bubble CVars (registrar `0x603280`), booting at the reference's defaults. -#[derive(Resource)] +#[derive(Resource, Clone, Copy)] pub(crate) struct BubbleConfig { /// `ChatBubbles`: say, yell and their monster variants. pub(crate) all: bool, @@ -616,7 +616,10 @@ pub(crate) struct BubbleSet; pub(crate) struct ChatBubblePlugin; /// The two bubble CVars' change callback. -pub(crate) fn on_cvar(ev: On, mut bubbles: ResMut) { +pub(crate) fn on_cvar( + ev: &crate::cvars::CvarChanged, + mut bubbles: bevy::prelude::Mut<'_, BubbleConfig>, +) { match ev.key().as_str() { "chatbubbles" => bubbles.all = ev.flag(), "chatbubblesparty" => bubbles.party = ev.flag(), @@ -626,7 +629,6 @@ pub(crate) fn on_cvar(ev: On, mut bubbles: ResMut() .init_resource::() .init_resource::() diff --git a/crates/benilla-app/src/combat_text/mod.rs b/crates/benilla-app/src/combat_text/mod.rs index 3cf3b268f..ec135c5b5 100644 --- a/crates/benilla-app/src/combat_text/mod.rs +++ b/crates/benilla-app/src/combat_text/mod.rs @@ -467,7 +467,10 @@ fn melee_impact_text( pub(crate) struct CombatTextPlugin; /// The damage-text rows' change callback: three flags. -pub(crate) fn on_cvar(ev: On, mut gates: ResMut) { +pub(crate) fn on_cvar( + ev: &crate::cvars::CvarChanged, + mut gates: bevy::prelude::Mut<'_, DamageTextGates>, +) { match ev.key().as_str() { "combatdamage" => gates.combat_damage = ev.flag(), "petmeleedamage" => gates.pet_melee = ev.flag(), @@ -479,7 +482,6 @@ pub(crate) fn on_cvar(ev: On, mut gates: ResMut() .init_resource::() .init_resource::() diff --git a/crates/benilla-app/src/creature_anim.rs b/crates/benilla-app/src/creature_anim.rs index 90893c4f7..69e4fe5e8 100644 --- a/crates/benilla-app/src/creature_anim.rs +++ b/crates/benilla-app/src/creature_anim.rs @@ -204,13 +204,13 @@ pub(crate) fn cancel_auto_repeat_local( core.reports.auto_repeat(false); } -/// The local StopAttack, reference `0x5ecac0`: when attacking, `CMSG_ATTACKSTOP` (`0x624370`), -/// then `CancelQueuedCast` (`0x6e6f30`, [`crate::spell::CastCore::cancel_queued`]), which cancels -/// a queued on-next-swing spell with `CMSG_CANCEL_CAST`: in the slot, as Esc does, with its pop's -/// signal and `SPELLCAST_STOP`; in the save under a cast, by the packet alone, which is why Auto -/// Shot (`0x6e5976`) darkens a Raptor Strike ring. `Engaged` stays until the `SMSG_ATTACKSTOP` echo -/// (`0x624e40`), as in the reference. The send marks `me`'s stop in flight in `word` -/// (`0x6243b2`). Ahead of the send, `low`'s Food and Drink tutorials (`0x5ecb17`, `0x5ecb54`). +/// The local StopAttack, reference `0x5ecac0`, for a caller with nobody to signal between its +/// steps: [`stop_attack_head`], [`stop_attack_send`], then the save's leg of `CancelQueuedCast` +/// ([`crate::spell::CastCore::cancel_queued_save`]). A queued on-next-swing spell is cancelled +/// with `CMSG_CANCEL_CAST`: in the slot, as Esc does, with its pop's signal and `SPELLCAST_STOP`; +/// in the save under a cast, by the packet alone, which is why Auto Shot (`0x6e5976`) darkens a +/// Raptor Strike ring. `Engaged` stays until the `SMSG_ATTACKSTOP` echo (`0x624e40`), as in the +/// reference. pub(crate) fn stop_attack_local( me: Option, low: crate::tutorial::LowVitals, @@ -218,20 +218,50 @@ pub(crate) fn stop_attack_local( word: &mut AttackStopInFlight, core: &mut crate::spell::CastCore, ) { - // The reference's `!IsAttacking(0x60ecb0) && [+0xc50] == 0` early-out: nothing sent, a queued - // strike survives. `[+0xc50]` is set only beside `[+0xc48]` (`0x47bf70`), so the attack - // target as the queue leaves it answers both. - if !me.is_some_and(|me| edits.attacking(me)) { - return; + if let Some(tail) = stop_attack_head(me, low, edits, core) { + stop_attack_send(tail, word, core); + core.cancel_queued_save(); } +} + +/// StopAttack's head (`0x5ecac0`-`0x5ecb54`): the reference's `!IsAttacking(0x60ecb0) && +/// [+0xc50] == 0` early-out, which sends nothing and leaves a queued strike, then `low`'s Food and +/// Drink tutorials (`0x5ecb17`, `0x5ecb54`), whose `TUTORIAL_TRIGGER` signals before the send. +/// What follows, when it goes on ([`stop_attack_send`]). +pub(crate) fn stop_attack_head( + me: Option, + low: crate::tutorial::LowVitals, + edits: &UnitEdits, + core: &mut crate::spell::CastCore, +) -> Option { + // `[+0xc50]` is set only beside `[+0xc48]` (`0x47bf70`), so the attack target as the queue + // leaves it answers both. + let me = me.filter(|&me| edits.attacking(me))?; for id in low.tutorials() { core.trigger_tutorial(id); } + Some(StopTail { me }) +} + +/// What StopAttack does past its tutorials ([`stop_attack_head`]). +#[must_use] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct StopTail { + me: Entity, +} + +/// StopAttack past its tutorials: `CMSG_ATTACKSTOP` (`0x5ecb5b` → `0x624370`), which marks +/// `me`'s stop in flight in `word` (`0x6243b2`), then `CancelQueuedCast`'s first leg (`0x5ecb63` +/// → `0x6e6f30`, [`crate::spell::CastCore::cancel_queued_slot`]), whose cancel signals before the +/// save's leg. Whether that cancel ran. +pub(crate) fn stop_attack_send( + tail: StopTail, + word: &mut AttackStopInFlight, + core: &mut crate::spell::CastCore, +) -> bool { let _ = core.net.0.send(crate::net::ClientCommand::AttackStop); - if let Some(me) = me { - word.set(me); - } - core.cancel_queued(); + word.set(tail.me); + core.cancel_queued_slot() } /// What StartAttack (`0x5ecb70`) reads of the active player before it does anything: the pacified @@ -502,14 +532,9 @@ impl AttackSeam<'_, '_> { } /// `0x48f200(1, 0, 0)`, the close with its release and `dl` clear (`0x493970`, `0x5e9a58`): - /// a disenchant window with rows left is swept, not closed; any other window closes as - /// `CloseLoot` does. Nothing with no window open (`0x48f23f`). + /// [`crate::ui_loot::end_loot_window`]. pub(crate) fn close_loot(&mut self) { - if self.loot.disenchant_holds() { - self.loot.owe_sweep(); - return; - } - crate::ui_loot::close_interaction(&mut self.loot, &mut self.loot_latch, Some(&self.net)); + crate::ui_loot::end_loot_window(&mut self.loot, &mut self.loot_latch, &self.net); } /// The selection release's pet leg (`0x493910`): `0x5ee5a0` asked of the player @@ -534,16 +559,31 @@ impl AttackSeam<'_, '_> { self.me.single().is_ok_and(|me| self.edits.attacking(me)) } - /// StopAttack (`0x5ecac0`). + /// StopAttack (`0x5ecac0`), with nobody to signal between its steps. pub(crate) fn stop(&mut self) { + if let Some(tail) = self.stop_head() { + self.stop_send(tail); + self.stop_save(); + } + } + + /// StopAttack's head ([`stop_attack_head`]): its gate and its tutorials, whose listeners a + /// caller runs before [`Self::stop_send`]. + pub(crate) fn stop_head(&mut self) -> Option { let me = self.me.single().ok(); - stop_attack_local( - me, - self.start_gate().low, - &self.edits, - &mut self.stop_word, - &mut self.slots.core(&self.net), - ); + let low = self.start_gate().low; + stop_attack_head(me, low, &self.edits, &mut self.slots.core(&self.net)) + } + + /// StopAttack's send and its next-swing cancel ([`stop_attack_send`]), whose listeners a + /// caller runs before [`Self::stop_save`]: whether the cancel ran. + pub(crate) fn stop_send(&mut self, tail: StopTail) -> bool { + stop_attack_send(tail, &mut self.stop_word, &mut self.slots.core(&self.net)) + } + + /// StopAttack's last leg, the save's `CMSG_CANCEL_CAST` (`0x6e6ff3`), read where it runs. + pub(crate) fn stop_save(&mut self) { + self.slots.core(&self.net).cancel_queued_save(); } /// `unit`'s stop in flight cleared, as its death zeroes it (`0x6058a8`). @@ -635,12 +675,6 @@ pub(crate) struct CastEvent { pub(crate) entity: Entity, pub(crate) spell_id: u32, pub(crate) kind: CastEventKind, - /// `SMSG_SPELL_GO`'s cast flags, 0 on every other edge: the tradeskill repeat's hook skips a - /// GO with `0x41` set (`0x6e81de`, vmangos `Spell.h:54`). - pub(crate) cast_flags: u16, - /// `SMSG_SPELL_GO`'s first guid is an item, not the caster: the tradeskill repeat's hook runs - /// only when that guid is the player (`0x6e81d3`-`0x6e81dc`). - pub(crate) item_cast: bool, /// `PlaySeq` stamp, carried to the kit's `EmoteAnim`. pub(crate) seq: u64, } @@ -842,8 +876,8 @@ pub(crate) use gesture::{select_gesture, Gesture, GestureQueue}; /// The Bevy systems that execute the state machine `select` picks. mod driver; -pub(crate) use driver::oneshot_is_live; use driver::{drive_animations, drive_hand_grip}; +pub(crate) use driver::{oneshot_is_live, toggle_model_refuses}; /// The model event-keyframe scanner. mod events; @@ -863,6 +897,8 @@ pub(crate) use impact::{DefenseAnim, PendingImpacts, SwingImpact, SwingSlowdown} /// The cast and auto-repeat state the seams queue for after the pass. mod edits; +#[cfg(test)] +pub(crate) use edits::applied_resources; pub(crate) use edits::{apply_unit_edits, flush_unit_edits, UnitEdit, UnitEdits}; /// The unit's precast spell and its busy bit. diff --git a/crates/benilla-app/src/creature_anim/driver.rs b/crates/benilla-app/src/creature_anim/driver.rs index bb7ecedb1..c08ef09c1 100644 --- a/crates/benilla-app/src/creature_anim/driver.rs +++ b/crates/benilla-app/src/creature_anim/driver.rs @@ -109,6 +109,17 @@ fn armed_id( }) } +/// The manual toggle's model tests (`0x5eb542`, `0x5eb580`) on the animation armed now +/// (`0x5fdb50`), for a toggle made inside its call. +pub(crate) fn toggle_model_refuses( + drv: &AnimDriver, + player: &AnimationPlayer, + tr: &AnimationTransitions, + anims: &ModelAnimations, +) -> bool { + model_refuses_toggle(anims, armed_id(drv, player, tr, anims)) +} + /// Whether a one-shot is live on the unit; the missile queue polls it to launch a missile whose /// release keyframe never fired when the cast ends (the reference's `0x5fc920` → `0x60c9b0`). pub(crate) fn oneshot_is_live( @@ -739,6 +750,20 @@ pub(super) fn drive_animations( // The setter: a no-op when unchanged (`newState == CUR`), else commit, volunteer // `CMSG_SETSHEATHED` for the local player, and for the manual toggle play the ceremony, // per-arm masked overlays (`0x60b770`) by each item's stow family (hip 90, back 89). + // A toggle committed inside its call plays its ceremony from the state it left. + if let Some((from, to)) = committed.owed_ceremony.take() { + start_sheath_ceremony( + &mut commands, + entity, + &mut drv, + &mut player, + anims, + wielded, + from, + to, + catalog, + ); + } if let Some(req) = pending_sheath.get(&entity) { let cur = committed.cur.unwrap_or(0); // Deviation: a mounted draw is refused at the setter, because our rider track never diff --git a/crates/benilla-app/src/creature_anim/edits.rs b/crates/benilla-app/src/creature_anim/edits.rs index df3ca7052..22e1219ec 100644 --- a/crates/benilla-app/src/creature_anim/edits.rs +++ b/crates/benilla-app/src/creature_anim/edits.rs @@ -320,6 +320,22 @@ pub(crate) fn flush_unit_edits(queued: Res, mut commands: Commands) { } } +/// The resources the edits write as they apply, beside the units' own components: the loot +/// closes a precast end's tail owes the active player (`0x60d0ee`-`0x60d10b`), and the cast edges +/// with their stamps. A handler's edits apply after it in the net drain, by an exclusive system +/// whose writes Bevy's access does not show, so the lanes' guards count these as what a handler +/// writes. +#[cfg(test)] +pub(crate) fn applied_resources() -> [std::any::TypeId; 4] { + use std::any::TypeId; + [ + TypeId::of::(), + TypeId::of::(), + TypeId::of::(), + TypeId::of::>(), + ] +} + fn run_all(world: &mut World, runs: Vec) { for run in runs { run(world); @@ -402,9 +418,110 @@ fn cast_event(world: &mut World, entity: Entity, spell_id: u32, kind: CastEventK entity, spell_id, kind, - cast_flags: 0, - item_cast: false, seq, }); } } + +#[cfg(test)] +mod tests { + use bevy::ecs::component::ComponentId; + + use super::*; + + /// Every resource an edit writes as it applies is one [`applied_resources`] names, so the + /// guards that follow what a handler writes see it: each kind applied to the active player + /// with a precast, at rest and moving. + #[test] + fn the_edits_write_no_resource_but_the_applied_ones() { + const SPELL: u32 = 133; + let mut app = crate::game_plugins::schedule_tests::headless_client_unrun(); + let world = app.world_mut(); + super::super::precast::install_visuals_for_tests(world, &[SPELL], &[]); + let me = world.spawn(crate::net::SelfPlayer).id(); + let declared: Vec = applied_resources() + .into_iter() + .filter_map(|t| world.components().get_resource_id(t)) + .collect(); + assert_eq!( + declared.len(), + applied_resources().len(), + "the client holds every applied resource" + ); + let edits = [ + UnitEdit::StartPrecast { + entity: me, + spell_id: SPELL, + }, + UnitEdit::EndPrecastBusy(me), + UnitEdit::EndPrecast { + entity: me, + spell_id: Some(SPELL), + tail: true, + }, + UnitEdit::SendPrecast { + entity: me, + spell_id: SPELL, + }, + UnitEdit::EndPrecast { + entity: me, + spell_id: None, + tail: true, + }, + UnitEdit::ArmAutoRepeat(me), + UnitEdit::StartPrecast { + entity: me, + spell_id: SPELL, + }, + UnitEdit::ClearAutoRepeat { + entity: me, + spell_id: SPELL, + }, + UnitEdit::ReapCasting { + entity: me, + spell_id: SPELL, + }, + UnitEdit::AbortCasting { + entity: me, + spell_id: SPELL, + }, + UnitEdit::StopSpellKits { + entity: me, + spell_id: SPELL, + }, + UnitEdit::StartAttack { + entity: me, + target: 0x2, + }, + UnitEdit::EndAttack(me), + ]; + let mut written = std::collections::BTreeSet::new(); + let mut owed = std::collections::BTreeSet::new(); + for flags in [0, crate::creature_anim::move_flags::FORWARD] { + world.insert_resource(crate::player::Player::with_move_flags(flags)); + let last = world.increment_change_tick(); + for edit in edits { + world.resource::().push(edit); + } + apply_unit_edits(world); + let now = world.change_tick(); + let resources: Vec<(ComponentId, String)> = world + .iter_resources() + .map(|(info, _)| (info.id(), info.name().to_string())) + .collect(); + for (id, name) in resources { + let changed = world + .get_resource_change_ticks_by_id(id) + .is_some_and(|t| t.is_changed(last, now)); + if changed && !declared.contains(&id) { + written.insert(name); + } else if changed { + owed.insert(id); + } + } + } + assert!(written.is_empty(), "written but not declared: {written:?}"); + // By id: without the `debug` feature every resource shares one placeholder name. + assert_eq!(owed.len(), declared.len(), "each applied resource written"); + } +} diff --git a/crates/benilla-app/src/creature_anim/net.rs b/crates/benilla-app/src/creature_anim/net.rs index 9c762ab62..6b458e731 100644 --- a/crates/benilla-app/src/creature_anim/net.rs +++ b/crates/benilla-app/src/creature_anim/net.rs @@ -166,8 +166,14 @@ fn on_attacker_state( tutorials: Option>, // The self-defence acquire the swing owes, absent in a harness without the target plugin. acquires: Option>, + // The attacker's auto-move, which the swing ends, and the lane its `AUTOFOLLOW_END` goes on. + mut auto_move: ( + crate::player::AutoMoveStop, + Option>, + ), ) { if let SessionEvent::AttackerState(s) = ev { + let attacker = s.attacker; attacker_state( tutorials.as_deref(), acquires.map(|a| a.into_inner()), @@ -181,6 +187,14 @@ fn on_attacker_state( &mut sinks, play_seq.next(), ); + // A held attacker's auto-move other than mode 2, the facing turn, ends (`0x625a03`- + // `0x625a21` → `StopAutoMove(1, 1)`), after the self-defence acquire (`0x6259fe`) and ahead + // of the packet's line (`0x625a2c`); it acts only on the active mover, so only on our own + // swing. + if index.0.contains_key(&attacker) { + let (stop, lane) = &mut auto_move; + stop.stop_unless_facing_turn(attacker, lane.as_deref_mut()); + } } } diff --git a/crates/benilla-app/src/creature_anim/sheath.rs b/crates/benilla-app/src/creature_anim/sheath.rs index 2f9f7a50e..05f44b6db 100644 --- a/crates/benilla-app/src/creature_anim/sheath.rs +++ b/crates/benilla-app/src/creature_anim/sheath.rs @@ -23,6 +23,9 @@ pub(crate) struct CommittedSheath { /// The state the driver's last pass left, so a change made between its passes, such as a /// script call's, still meets its leave-ranged edge. pub(super) driven: Option, + /// The draw/stow ceremony a toggle committed inside its call owes the driver, `(from, to)` + /// ([`Self::toggle_now`]). + pub(super) owed_ceremony: Option<(u8, u8)>, } impl CommittedSheath { @@ -54,6 +57,34 @@ impl CommittedSheath { } } +impl CommittedSheath { + /// A toggle committed inside its call owes its ceremony, whose draw starts inside the setter + /// (`0x611cea` → `0x611a20` → `0x7121a0`): the toggle's arm test reads it running + /// (`0x5eb5a0`-`0x5eb5e2`). + pub(crate) fn ceremony_owed(&self) -> bool { + self.owed_ceremony.is_some() + } + + /// The manual toggle's `SetSheatheState(state, 0, …)` (`0x5eb6a8` → `0x611cf0`) inside its + /// call: committed as [`Self::set_now`] commits, with the draw/stow ceremony (`bInstant = 0`) + /// owed to the driver from the state it left. Whether it changed, and so whether the active + /// player's `CMSG_SETSHEATHED` is owed (`0x611dbc`). + pub(crate) fn toggle_now( + &mut self, + state: u8, + fields: Option<&benilla_protocol::ObjectFields>, + classes: Option<&benilla_formats::ChrClasses>, + ) -> bool { + let byte = fields.and_then(|f| f.unit_sheath_state()).unwrap_or(0); + let from = self.cur.unwrap_or(byte); + let changed = self.set_now(state, fields, classes); + if changed { + self.owed_ceremony = Some((from, state)); + } + changed + } +} + /// A unit's visual sheath state per arm while a draw/stow ceremony plays: each weapon moves at its /// own clip's `$SHL`/`$SHR` key, not when the state changes. Absent, the committed state rules. #[derive(Component, Clone, Copy)] diff --git a/crates/benilla-app/src/creature_anim/spell_visual.rs b/crates/benilla-app/src/creature_anim/spell_visual.rs index 02b8231a7..b2de59bcc 100644 --- a/crates/benilla-app/src/creature_anim/spell_visual.rs +++ b/crates/benilla-app/src/creature_anim/spell_visual.rs @@ -1390,7 +1390,6 @@ pub(super) fn arm_loot_fx( visuals: Option>, mut fx: MessageWriter, mut armed: Local, - mut tutorials: Option>, ) { let full_sweep = visuals.as_ref().is_some_and(|v| v.is_changed()); let Some((effect, path)) = visuals.as_ref().and_then(|v| v.0.loot_art_effect()) else { @@ -1426,12 +1425,6 @@ pub(super) fn arm_loot_fx( store.0.unit_is_dead() && store.0.unit_lootable() }; if lootable && armed.insert(entity) { - // The Looting tutorial on the rise (`0x60049b`). - if let Some(t) = tutorials.as_mut() { - t.write(crate::tutorial::TutorialEvent::trigger( - crate::tutorial::id::LOOTING, - )); - } fx.write(SpellKitFx::Begin { entity, spell_id: LOOT_FX_KEY, diff --git a/crates/benilla-app/src/creature_anim/spell_visual/tests.rs b/crates/benilla-app/src/creature_anim/spell_visual/tests.rs index 295e53100..20b8587df 100644 --- a/crates/benilla-app/src/creature_anim/spell_visual/tests.rs +++ b/crates/benilla-app/src/creature_anim/spell_visual/tests.rs @@ -107,8 +107,6 @@ fn cast_event(entity: Entity, spell_id: u32, kind: CastEventKind) -> CastEvent { entity, spell_id, kind, - cast_flags: 0, - item_cast: false, seq: 1, } } @@ -1158,8 +1156,6 @@ fn a_targetless_dest_go_spawns_a_ground_missile_whose_arrival_sounds_at_the_poin entity: caster, spell_id: GROUND, kind: CastEventKind::GroundImpact { pos: at }, - cast_flags: 0, - item_cast: false, seq: 2, }); app.update(); diff --git a/crates/benilla-app/src/cursor.rs b/crates/benilla-app/src/cursor.rs index 83ed80f54..d92b6d363 100644 --- a/crates/benilla-app/src/cursor.rs +++ b/crates/benilla-app/src/cursor.rs @@ -335,7 +335,12 @@ impl Plugin for CursorPlugin { app.add_systems(Startup, macos::setup.after(AssetSet::Open)) .add_systems( Update, - (read_glue_pointer, drive_displayed_cursor, macos::drive) + ( + read_glue_pointer, + drive_displayed_cursor, + // After every call, which may move the camera's rig whose look it shows. + macos::drive.after(crate::vm_pass::VmPass::End), + ) .chain() // After the tick: a FrameXML `SetCursor` made this frame is read here; and // after the target chain, whose clicks, calls and selects end or raise the diff --git a/crates/benilla-app/src/cvars/callbacks.rs b/crates/benilla-app/src/cvars/callbacks.rs new file mode 100644 index 000000000..21b0dc4fe --- /dev/null +++ b/crates/benilla-app/src/cvars/callbacks.rs @@ -0,0 +1,202 @@ +//! Every row's change callback, the reference's function handed to `CVar::Register` (`0x63db90`) +//! and called inside `CVar::Set` (`0x63df50`, at `0x63df7d`): one param holding each knob a +//! callback writes ([`CvarCallbacks`]), so a write runs its callback wherever it is made. A Lua +//! verb's write runs it inside the verb's call ([`CvarSteps`], as the call host's applier), and the +//! frame's sync runs it for the writes no call made; the boot load and a dying VM's fold trigger +//! [`CvarChanged`], which [`on_cvar_changed`] runs the same callbacks for. Each callback takes its +//! knob as a [`Mut`], so only the arm that writes it marks it changed. + +use bevy::ecs::system::SystemParam; +use bevy::prelude::*; + +use benilla_ui::script::UiScript; + +use super::{CvarChanged, Cvars}; + +/// Each knob a row's change callback writes, one field per owner; a knob absent from the world (a +/// harness without its plugin) skips its callback. +#[derive(SystemParam)] +pub(crate) struct CvarCallbacks<'w> { + approach: Option>, + sound: Option>, + ui_scale: Option>, + video: Option>, + look: Option>, + zoom: Option>, + follow: Option>, + camera_options: Option>, + click: Option>, + assist: Option>, + self_cast: Option>, + damage_text: Option>, + log_ranges: Option>, + log_periodic: Option>, + loot: Option>, + names: Option>, + game_tip: Option>, + text_filter: Option>, + bubbles: Option>, + guild_notify: Option>, + block_trades: Option>, + minimap_zoom: Option>, + pane_rate: Option>, + fps_journal: Option>, + realmlist: Option>, + gamma: Option>, + render_scale: Option>, +} + +impl CvarCallbacks<'_> { + /// Run every callback on the move `ev`; a callback that writes the registry back (a second + /// spelling's mirror, a console line) writes `cvars`. + pub(crate) fn run(&mut self, ev: &CvarChanged, cvars: &mut Cvars) { + if let Some(k) = self.approach.as_mut() { + crate::player::approach_on_cvar(ev, k.reborrow()); + } + if let Some(k) = self.sound.as_mut() { + crate::sound::on_cvar(ev, k.reborrow()); + } + if let Some(k) = self.ui_scale.as_mut() { + crate::ui_script::on_cvar(ev, k.reborrow()); + } + if let Some(k) = self.video.as_mut() { + k.on_cvar(ev, cvars); + } + if let (Some(look), Some(zoom), Some(follow)) = + (self.look.as_mut(), self.zoom.as_mut(), self.follow.as_mut()) + { + crate::player::camera::on_cvar(ev, look.reborrow(), zoom.reborrow(), follow.reborrow()); + } + if let Some(k) = self.camera_options.as_mut() { + crate::player::camera_dynamics::on_cvar(ev, k.reborrow()); + } + if let (Some(click), Some(assist)) = (self.click.as_mut(), self.assist.as_mut()) { + crate::target::on_cvar(ev, click.reborrow(), assist.reborrow()); + } + if let Some(k) = self.self_cast.as_mut() { + crate::spell::cast_target::on_cvar(ev, k.reborrow()); + } + if let Some(k) = self.damage_text.as_mut() { + crate::combat_text::on_cvar(ev, k.reborrow()); + } + if let (Some(ranges), Some(periodic)) = + (self.log_ranges.as_mut(), self.log_periodic.as_mut()) + { + crate::ui_chat::combat::on_cvar(ev, ranges.reborrow(), periodic.reborrow()); + } + if let Some(k) = self.loot.as_mut() { + crate::ui_loot::on_cvar(ev, k.reborrow()); + } + if let Some(k) = self.names.as_mut() { + crate::nameplates::on_cvar(ev, k.reborrow()); + } + if let Some(k) = self.game_tip.as_mut() { + crate::game_tip::on_cvar(ev, k.reborrow()); + } + if let Some(k) = self.text_filter.as_mut() { + crate::text_filter::on_cvar(ev, k.reborrow()); + } + if let Some(k) = self.bubbles.as_mut() { + crate::chat_bubble::on_cvar(ev, k.reborrow()); + } + if let Some(k) = self.guild_notify.as_mut() { + crate::ui_guild::on_cvar(ev, k.reborrow()); + } + if let Some(k) = self.block_trades.as_mut() { + crate::ui_trade::on_cvar(ev, k.reborrow()); + } + if let Some(k) = self.minimap_zoom.as_mut() { + crate::minimap::on_cvar(ev, k.reborrow()); + } + if let Some(k) = self.pane_rate.as_mut() { + crate::portrait::on_cvar(ev, k.reborrow()); + } + if let Some(k) = self.fps_journal.as_mut() { + crate::perf::on_cvar(ev, k.reborrow()); + } + if let Some(k) = self.realmlist.as_mut() { + crate::realmlist::on_cvar(ev, k.reborrow()); + } + if let Some(k) = self.gamma.as_mut() { + crate::ui_gamma::on_cvar(ev, k.reborrow()); + } + if let Some(k) = self.render_scale.as_mut() { + crate::world_backdrop::on_cvar(ev, k.reborrow()); + } + } +} + +/// The callbacks for a move triggered as an event: the boot load's, a dying VM's fold, a latch +/// commit's. With no registry nothing moved. +pub(crate) fn on_cvar_changed( + ev: On, + cvars: Option>, + mut callbacks: CvarCallbacks, +) { + if let Some(mut cvars) = cvars { + callbacks.run(&ev, &mut cvars); + } +} + +/// The registry and the callbacks, as the call host applies a write inside the call that made it +/// and as the frame's sync takes the rest ([`CvarSteps::sync`]). +#[derive(SystemParam)] +pub(crate) struct CvarSteps<'w> { + cvars: Option>, + callbacks: CvarCallbacks<'w>, +} + +impl CvarSteps<'_> { + /// The registry, absent in a harness without the plugin. + pub(crate) fn cvars(&mut self) -> Option<&mut Cvars> { + self.cvars.as_deref_mut() + } + + /// Host writes an engine verb makes inside its call (`CVar::Set`, `0x63df50`), each through + /// its row's check and callback, then the VM's mirror synced, before the verb returns. + pub(crate) fn write(&mut self, script: &mut UiScript, writes: &[(&str, String)]) { + let Some(cvars) = self.cvars.as_deref_mut() else { + return; + }; + for (name, value) in writes { + cvars.set(name, value); + } + self.sync(Some(script)); + } + + /// Take the VM's queued writes into the registry, run each accepted move's callback, then hand + /// the VM what the registry wrote (a host write, a callback's mirror of a second spelling). + /// Read before taking, so a quiet sync never deref-muts the registry. + pub(crate) fn sync(&mut self, script: Option<&mut UiScript>) { + let Some(cvars) = self.cvars.as_deref_mut() else { + return; + }; + let script = match script { + Some(script) => { + if script.has_cvar_traffic() || script.cvar_lua_created() != cvars.lua_created { + cvars.drain_vm(script); + cvars.log_console_lines(); + } + Some(script) + } + None => None, + }; + if cvars.has_events() { + for event in cvars.take_events() { + self.callbacks.run(&event, cvars); + } + } + if cvars.has_console_lines() { + cvars.log_console_lines(); + } + if cvars.has_outbox() { + let outbox = cvars.take_outbox(); + // With no VM there is no mirror; a later VM is seeded from the table. + if let Some(script) = script { + for (name, value) in outbox { + script.set_cvar_host(&name, &value); + } + } + } + } +} diff --git a/crates/benilla-app/src/cvars/inert.rs b/crates/benilla-app/src/cvars/inert.rs index f2ee20f15..f0947eeb5 100644 --- a/crates/benilla-app/src/cvars/inert.rs +++ b/crates/benilla-app/src/cvars/inert.rs @@ -4,7 +4,7 @@ //! on a miss (`0x488be7`, `0x488c53`, `0x488d37`). So every such record the reference registers is //! registered here with its registered default, or an addon that sets one stops with an error. //! -//! A row is inert: no observer reads it, `GetCVar` answers what was written, and it persists like +//! A row is inert: no change callback reads it, `GetCVar` answers what was written, and it persists like //! any row, as a `[cvars]` entry in `benilla-config/config.toml` only while off its default. The //! flag bit1 rows are latched, as in the reference (a write is kept until a restart that never //! comes for the sound block, and `RestartGx` commits the `gx*` pair). A row whose callback diff --git a/crates/benilla-app/src/cvars/mod.rs b/crates/benilla-app/src/cvars/mod.rs index 45fdea218..9d98d54bf 100644 --- a/crates/benilla-app/src/cvars/mod.rs +++ b/crates/benilla-app/src/cvars/mod.rs @@ -8,15 +8,16 @@ //! [`inert::INERT`] the reference's other script-visible ones, which `GetCVar` and `SetCVar` //! would otherwise raise on. A row's default is the reference's, and //! [`table::Registered::reference`] says where it stands against it. -//! - The change callback is a Bevy observer on [`CvarChanged`], beside the knob it writes; the -//! registry applies nothing itself. A callback that can refuse a write is also the row's +//! - The change callbacks are plain functions beside the knobs they write, run together by +//! [`callbacks::CvarCallbacks`]: inside a Lua verb's call for its writes ([`CvarSteps`]), and for a move +//! triggered as [`CvarChanged`]; the registry applies nothing itself. A callback that can refuse a write is also the row's //! [`CvarCheck`], which the registry and the VM's mirror run before storing. //! - A latched row's write is staged in [`Row::pending`] until [`Cvars::commit_latched`], the //! reference's `0x639ec0` inside `RestartGx`. A stage never committed is what the save writes, //! as the reference's `SaveConfig` takes the latched text first (`rec+0x38`, `0x63da27`), so it //! applies at the next launch. -//! - Boot folds `benilla-config/config.toml` in and fires the observers before anything after -//! [`CvarLoad`]; each frame drains the VM's writes in and pushes the registry's out; a dirty +//! - Boot folds `benilla-config/config.toml` in and runs the callbacks before anything after +//! [`CvarLoad`]; each frame drains the VM writes no call took in and pushes the registry's out; a dirty //! registry saves after one quiet second or at exit, writing only values off their default and //! keeping unknown keys verbatim. //! @@ -31,6 +32,7 @@ use bevy::prelude::*; use crate::ui_script::VmMemo; use benilla_ui::script::{CvarCheck, CvarWrite, SeededCvar, UiScript}; +mod callbacks; #[cfg(test)] mod deviations_doc; mod inert; @@ -38,6 +40,7 @@ mod listing; #[cfg(test)] mod reference_table; mod table; +pub(crate) use callbacks::CvarSteps; pub(crate) use listing::list_rank; pub(crate) use listing::reference_help; #[cfg(test)] @@ -69,13 +72,13 @@ impl CvarChanged { self.name.eq_ignore_ascii_case(name) } - /// The lowercased name, as observers' `match` arms spell it. + /// The lowercased name, as the callbacks' `match` arms spell it. pub(crate) fn key(&self) -> String { self.name.to_ascii_lowercase() } /// The new value as the record's float (`rec+0x24`, `SStrToFloat` at `0x63e130`): text that - /// is no number reads as 0, and a string row's observer reads [`Self::new`]. + /// is no number reads as 0, and a string row's callback reads [`Self::new`]. pub(crate) fn num(&self) -> f32 { record_float(&self.new) } @@ -159,7 +162,7 @@ pub(crate) struct Cvars { /// A change since the last save; `last_change` drives the one-quiet-second debounce. dirty: bool, last_change: Option, - /// Lines change callbacks and observers printed to the console (`0x63cb50`), which go to the + /// Lines the rows' checks and change callbacks printed to the console (`0x63cb50`), which go to the /// log, as the reference's go to a console screen nobody has open. console: Vec, /// The CVars Lua's `RegisterCVar` created this process, the reference's `[0xb4e3c8]`: kept @@ -433,10 +436,11 @@ impl Cvars { /// stage (`+0x38`). So the value reaches `GetCVar` and the save, and the knob at the next /// launch. /// - /// Deviation: for a row that is not latched the observers fire, where the reference runs no - /// callback here (`0x63dff0`, `0x63e010`), because a knob moves only through its - /// [`CvarChanged`] observer, which also stands in for the reference's direct reads of the - /// record; without it knob and value would disagree until the next write. + /// Deviation: for a row that is not latched the change callback runs, inside the call that + /// restored it, where the reference runs no callback here (`0x63dff0`, `0x63e010`), because a + /// knob moves only through its callback ([`callbacks::CvarCallbacks`]), which also stands in + /// for the reference's direct reads of the record; without it knob and value would disagree + /// until the next write. fn restore_from_vm(&mut self, name: &str, value: &str) -> SetOutcome { let Some(i) = self.slot(name) else { warn!("cvar {name}: not registered — restore ignored"); @@ -460,8 +464,8 @@ impl Cvars { /// Follow a value the engine already applied, for a second spelling of one knob /// (`WorldDetail`/`frillDensity`): the row moves, persists and reaches the mirror, but no - /// observer fires, since a full write would queue an event that lands a flush late and wins - /// stale. Returns whether the row moved. + /// callback runs, since a full write would run the other spelling's callback, which would + /// re-derive the knob from the mirrored, rounded value. Returns whether the row moved. pub(crate) fn mirror(&mut self, name: &str, value: &str) -> bool { let Some(i) = self.slot(name) else { warn!("cvar {name}: not registered — mirror ignored"); @@ -515,7 +519,7 @@ impl Cvars { } /// The session owns this row: it is never saved and the file's entry is left alone. `value` is - /// what it answers this session; `None` marks it without moving it. No observer fires: the knob + /// what it answers this session; `None` marks it without moving it. No callback runs: the knob /// already read the env. pub(crate) fn own_for_session(&mut self, name: &str, value: Option<&str>) { let key = name.to_ascii_lowercase(); @@ -585,7 +589,7 @@ impl Cvars { // value and its answer is not tested: the file is read before these rows are // registered (`0x402375`), and `CVar::Register` on the record it made calls the // callback and ignores the result (`0x63dc58`), so the value stands. A refusing - // callback applied nothing, so no observer fires for it. + // callback applied nothing, so its callback does not run for it. let applies = verdict.is_none_or(|verdict| { self.console.extend(verdict.lines); verdict.accept @@ -672,7 +676,7 @@ impl Cvars { !self.console.is_empty() } - /// A line an observer prints to the console, such as `spellEffectLevel`'s "Spell effect level + /// A line a change callback prints to the console, such as `spellEffectLevel`'s "Spell effect level /// set to %d." (`0x689537`-`0x689554`); logged with the callbacks' at the next sync. pub(crate) fn print(&mut self, line: String) { self.console.push(line); @@ -847,17 +851,18 @@ pub(crate) struct CvarPlugin; impl Plugin for CvarPlugin { fn build(&self, app: &mut App) { app.init_resource::() + .add_observer(callbacks::on_cvar_changed) .add_systems( Startup, (load_config, publish_filter_policy) .chain() .in_set(CvarLoad), ) - // After the tick, so a `SetCVar` from this frame reaches the registry and its observers + // After the tick, so a write no call took reaches the registry and its callbacks // before the frame's drains; `video::drain_restart_gx` orders after this so the commit - // finds the stage. Before the world's input stage, so the observers run ahead of the - // camera's controller: the reference calls the change callback inside the call - // (`CVar::Set` `0x63df50`, `0x63df7d`). + // finds the stage. Before the world's input stage, so the callbacks run ahead of the + // camera's controller. A Lua verb's write ran them inside its call (`CVar::Set` + // `0x63df50`, `0x63df7d`). .add_systems( Update, sync_cvars @@ -865,7 +870,7 @@ impl Plugin for CvarPlugin { .before(benilla_world::schedule::WorldStage::Input), ) // And after the input records' calls, ahead of the world's mouse, whose look session - // reads the knobs their observers write. + // reads the knobs their callbacks write. .add_systems( Update, sync_input_cvars @@ -949,8 +954,8 @@ fn session_values(world: &World) -> Vec<(&'static str, Option)> { out } -/// Startup: mark what the session owns, fold `config.toml` in (no file means all defaults) and fire -/// the observers now, so everything after [`CvarLoad`] finds its knob written. The VM does not +/// Startup: mark what the session owns, fold `config.toml` in (no file means all defaults) and run +/// the callbacks now, so everything after [`CvarLoad`] finds its knob written. The VM does not /// exist yet; [`sync_cvars`] seeds its mirror. fn load_config(world: &mut World) { let session = session_values(world); @@ -1037,35 +1042,15 @@ pub(crate) fn boot_cvar(name: &str) -> Option { } } -/// After the UI's input pass and its bindings: drain the writes their calls made into the registry, -/// push the registry's writes into the mirror and trigger the accepted moves, so the observers -/// (the look's rates, the camera's dynamics) run before the world's mouse reads their knobs, as -/// the reference's `CVar::Set` (`0x63df50`) calls the change callback inside the call -/// (`0x63df7d`). A new VM is seeded by [`sync_cvars`], which drains its writes first as well. -pub(crate) fn sync_input_cvars( - mut hosted_vm: crate::script_calls::HostedVm, - mut cvars: ResMut, - mut commands: Commands, -) { - hosted_vm.run(|script| { - let Some(script) = script else { - return; - }; - if script.has_cvar_traffic() || script.cvar_lua_created() != cvars.lua_created { - cvars.drain_vm(script); - cvars.log_console_lines(); - } - if cvars.has_outbox() { - for (name, value) in cvars.take_outbox() { - script.set_cvar_host(&name, &value); - } - } - if cvars.has_events() { - for event in cvars.take_events() { - commands.trigger(event); - } - } - }) +/// After the UI's input pass and its bindings: take in the writes no call took, run their +/// callbacks and push the registry's writes into the mirror, so the look's rates and the camera's +/// dynamics have moved before the world's mouse reads them. A Lua verb's write ran its callback +/// inside its call already ([`CvarSteps`]), as the reference's `CVar::Set` (`0x63df50`) calls it +/// inside the write (`0x63df7d`). The host's writes outside any call since the last packets (the +/// tip cursor's, the fullscreen size) reach the mirror here, ahead of the frame's packets. A new VM +/// is seeded by [`sync_cvars`], which drains its writes first as well. +pub(crate) fn sync_input_cvars(mut vm: crate::script_calls::VmWith>) { + vm.turn(|script, mut steps| steps.sync(script)) } /// The device's multisample formats as `GetMultisampleFormats` lists them; none before @@ -1089,17 +1074,18 @@ pub(crate) fn multisample_formats( .unwrap_or_default() } -/// Per frame: seed a new VM's mirror, drain its registrations and writes into the registry, push -/// the registry's writes into the mirror, and trigger every accepted move. +/// Per frame: seed a new VM's mirror, take in the registrations and the writes no call took, run +/// their callbacks and push the registry's writes into the mirror. pub(crate) fn sync_cvars( - mut hosted_vm: crate::script_calls::HostedVm, - mut cvars: ResMut, + mut vm: crate::script_calls::VmWith>, adapter: Option>, msaa_formats: Option>, mut seeded: Local>, - mut commands: Commands, ) { - hosted_vm.run(|script| { + vm.turn(|script, mut steps| { + let Some(cvars) = steps.cvars() else { + return; + }; // The live render backend; absent headless, where the registered `""` stands. if let Some(adapter) = adapter.as_deref() { let backend = adapter.backend.to_str(); @@ -1107,29 +1093,17 @@ pub(crate) fn sync_cvars( cvars.own_for_session("gxApi", Some(backend)); } } - if cvars.has_console_lines() { - cvars.log_console_lines(); - } let Some(script) = script else { // Nothing to mirror into; a later VM is seeded from the table, which carries it all. - if cvars.has_outbox() { - cvars.take_outbox(); - } - if cvars.has_events() { - for event in cvars.take_events() { - commands.trigger(event); - } - } + steps.sync(None); return; }; - // The VM's writes before the seed: an addon's `SetCVar` at load is already queued, and - // seeding first would overwrite the mirror with the older value. Read before taking, so a - // quiet frame never deref-muts the registry. - if script.has_cvar_traffic() || script.cvar_lua_created() != cvars.lua_created { - cvars.drain_vm(script); - cvars.log_console_lines(); - } if seeded.claim(script) { + // The VM's writes before the seed: an addon's `SetCVar` at load is already queued, and + // seeding first would overwrite the mirror with the older value. + if script.has_cvar_traffic() || script.cvar_lua_created() != cvars.lua_created { + cvars.drain_vm(script); + } cvars.seed_vm(script); if cvars.has_outbox() { cvars.take_outbox(); // the seed just carried everything @@ -1153,23 +1127,14 @@ pub(crate) fn sync_cvars( hardware_cursor: true, }); } - if cvars.has_outbox() { - for (name, value) in cvars.take_outbox() { - script.set_cvar_host(&name, &value); - } - } - if cvars.has_events() { - for event in cvars.take_events() { - commands.trigger(event); - } - } + steps.sync(Some(script)); }) } /// Fold the dying VM's last writes into the registry. Called from the shutdown /// ([`crate::ui_script::SessionEnd::Shutdown`]) after its events (a `PLAYER_LOGOUT` handler may /// `SetCVar`, and the reference keeps that write) and before the VM is replaced, so a final-frame -/// write is not lost to the next VM's seed. The observers fire here. +/// write is not lost to the next VM's seed. The callbacks run here. pub(crate) fn fold_dying_vm_cvars(world: &mut World) { // No registry: a test or stripped world without the plugin. if !world.contains_resource::() { @@ -1282,6 +1247,7 @@ fn publish_filter_policy(filter: Res) { mod tests { use super::*; use crate::chat_bubble::BubbleConfig; + use crate::local_state::test_env::{EnvGuard, ENV_LOCK}; use crate::minimap::MinimapZoom; use crate::nameplates::NameConfig; use crate::player::camera::{FollowConfig, FollowStyle, LookConfig}; @@ -1414,8 +1380,9 @@ mod tests { /// owns both video knobs for the session and takes precedence over the locale defaults. #[test] fn a_locale_default_reaches_its_knob_at_load() { + let env = CvarEnv::hold(); let boot = |locale: usize| { - let mut app = cvar_app(); + let mut app = cvar_app_in(&env); app.insert_resource(Cvars::for_locale(locale)); app.update(); let video = *res::(&app); @@ -1682,8 +1649,32 @@ mod tests { assert!(res::(&app).maximize, "the commit applies it"); } + /// A move marks only the knob its callback writes: the other callbacks see the event but take + /// their knobs mutably only in the arm that writes them. #[test] - fn the_observers_apply_every_arm() { + fn a_move_marks_only_the_knob_its_callback_writes() { + let mut app = cvar_app(); + let click = |app: &App| { + app.world() + .get_resource_change_ticks::() + .expect("the knob") + .changed + }; + let sound = |app: &App| { + app.world() + .get_resource_change_ticks::() + .expect("the knob") + .changed + }; + let (click_before, sound_before) = (click(&app), sound(&app)); + app.world_mut().increment_change_tick(); + apply(&mut app, "deselectOnClick", "0"); + assert_ne!(click(&app), click_before, "its own knob moved"); + assert_eq!(sound(&app), sound_before, "another knob stays unmarked"); + } + + #[test] + fn the_callbacks_apply_every_arm() { let mut app = cvar_app(); apply(&mut app, "MusicVolume", "0.7"); assert_eq!(res::(&app).music, 0.7); @@ -2541,19 +2532,12 @@ mod tests { #[test] fn a_change_saves_after_one_quiet_second_with_no_exit() { - use crate::local_state::test_env::{EnvGuard, ENV_LOCK}; - let _l = ENV_LOCK - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); + let env = CvarEnv::hold(); let tmp = std::env::temp_dir().join(format!("benilla-cvar-quiet-{}", std::process::id())); std::fs::remove_dir_all(&tmp).ok(); - let _c = EnvGuard::unset("WOW_CAPTURE"); - let _u = EnvGuard::unset("WOW_UI_SCALE"); - let _f = EnvGuard::unset("WOW_FARCLIP"); - let _d = EnvGuard::unset("WOW_CLUTTER_DENSITY"); let _h = EnvGuard::set("BENILLA_HOME", tmp.to_str().unwrap()); - let mut app = cvar_app(); + let mut app = cvar_app_in(&env); app.update(); app.world_mut() .non_send_resource_mut::() @@ -2584,19 +2568,15 @@ mod tests { /// boot reads the row. #[test] fn the_old_saved_account_file_moves_into_config_toml_once() { - use crate::local_state::test_env::{EnvGuard, ENV_LOCK}; - let _l = ENV_LOCK - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); + let env = CvarEnv::hold(); let tmp = std::env::temp_dir().join(format!("benilla-cvar-acct-{}", std::process::id())); std::fs::remove_dir_all(&tmp).ok(); std::fs::create_dir_all(&tmp).unwrap(); - let _c = EnvGuard::unset("WOW_CAPTURE"); let _h = EnvGuard::set("BENILLA_HOME", tmp.to_str().unwrap()); let old = tmp.join("account"); std::fs::write(&old, "PLAYER\n").unwrap(); - let mut app = cvar_app(); + let mut app = cvar_app_in(&env); app.update(); assert_eq!(res::(&app).get("accountName"), Some("PLAYER")); let glue = app @@ -2615,7 +2595,7 @@ mod tests { // The next boot reads the row; a stale file beside it is not read over it. std::fs::write(&old, "STALE").unwrap(); - let mut next = cvar_app(); + let mut next = cvar_app_in(&env); next.update(); assert_eq!(res::(&next).get("accountName"), Some("PLAYER")); std::fs::remove_dir_all(&tmp).ok(); @@ -2626,20 +2606,16 @@ mod tests { #[cfg(unix)] #[test] fn the_old_saved_account_file_outlives_a_failed_save() { - use crate::local_state::test_env::{EnvGuard, ENV_LOCK}; use std::os::unix::fs::PermissionsExt; - let _l = ENV_LOCK - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); + let env = CvarEnv::hold(); let tmp = std::env::temp_dir().join(format!("benilla-cvar-acct2-{}", std::process::id())); std::fs::remove_dir_all(&tmp).ok(); std::fs::create_dir_all(&tmp).unwrap(); - let _c = EnvGuard::unset("WOW_CAPTURE"); let _h = EnvGuard::set("BENILLA_HOME", tmp.to_str().unwrap()); let old = tmp.join("account"); std::fs::write(&old, "PLAYER").unwrap(); - let mut app = cvar_app(); + let mut app = cvar_app_in(&env); app.update(); // The folder turns read-only: the write of `config.toml` fails (unless the run is root's, // which no mode stops). @@ -2655,7 +2631,7 @@ mod tests { std::fs::write(&old, "PLAYER").unwrap(); std::fs::write(tmp.join("config.toml"), "not [ toml").unwrap(); - let mut bad = cvar_app(); + let mut bad = cvar_app_in(&env); bad.update(); assert_eq!(res::(&bad).get("accountName"), Some("PLAYER")); assert!( @@ -2693,16 +2669,9 @@ mod tests { #[test] fn a_lua_setcvar_lands_in_config_toml_end_to_end() { - use crate::local_state::test_env::{EnvGuard, ENV_LOCK}; - let _l = ENV_LOCK - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); + let env = CvarEnv::hold(); let tmp = std::env::temp_dir().join(format!("benilla-cvar-e2e-{}", std::process::id())); std::fs::remove_dir_all(&tmp).ok(); - let _c = EnvGuard::unset("WOW_CAPTURE"); - let _u = EnvGuard::unset("WOW_UI_SCALE"); - let _f = EnvGuard::unset("WOW_FARCLIP"); - let _d = EnvGuard::unset("WOW_CLUTTER_DENSITY"); let _h = EnvGuard::set("BENILLA_HOME", tmp.to_str().unwrap()); crate::local_state::write_atomic( &tmp.join("config.toml"), @@ -2710,7 +2679,7 @@ mod tests { ) .unwrap(); - let mut app = cvar_app(); + let mut app = cvar_app_in(&env); // Startup: the file's MusicVolume reaches the knob; Update: the VM table seeds from it. app.update(); @@ -2742,9 +2711,91 @@ mod tests { std::fs::remove_dir_all(&tmp).ok(); } - /// A client with a real CVar host: every knob resource an observer writes, every observer, + /// What a CVar host reads from the environment when it is built and when it loads + /// ([`session_values`], [`crate::video::windowed_env`], [`crate::local_state::home`]); the + /// persistence variables are `ENV_LOCK`'s own, the window ones are the capture tests'. + const HOST_ENV: [&str; 13] = [ + "WOW_WIN", + "WOW_CAPTURE", + "WOW_CAPTURE_UI", + "WOW_UI_SCALE", + "WOW_FARCLIP", + "WOW_CLUTTER_DENSITY", + "WOW_NOVSYNC", + "WOW_TRILINEAR", + "WOW_ANISO", + "WOW_MSAA", + "WOW_RENDER_SCALE", + "WOW_HOST", + "BENILLA_HOME", + ]; + + /// [`HOST_ENV`] cleared for an attended run with no state folder, until dropped. The caller + /// holds `ENV_LOCK`. `background_run` counts any env under a run-driving prefix + /// (`WOW_UNATTENDED`, `WOW_RIG…`), so it is answered with `WOW_BG=0`, which forces no. + fn scrub_host_env() -> Vec { + let mut guards: Vec<_> = HOST_ENV.into_iter().map(EnvGuard::unset).collect(); + guards.push(EnvGuard::set("WOW_BG", "0")); + guards + } + + /// `ENV_LOCK` held with [`HOST_ENV`] cleared, so a client built under it reads the same + /// environment whichever tests run beside it. A test that sets variables of its own (a state + /// folder) sets them after this. Not reentrant: the one thread holds one, builds its clients + /// with [`cvar_app_in`] and takes no `ENV_LOCK` of its own. + struct CvarEnv { + // Dropped first: the variables come back while the lock is still held. + _scrubbed: Vec, + _lock: std::sync::MutexGuard<'static, ()>, + } + + impl CvarEnv { + fn hold() -> Self { + let lock = ENV_LOCK + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + Self { + _scrubbed: scrub_host_env(), + _lock: lock, + } + } + } + + /// A [`cvar_app`] and the environment it was built under, which it keeps for as long as the + /// test has it: its load reads the environment again. + struct CvarApp { + app: App, + // After `app`, so the client is gone before the variables come back. + _env: CvarEnv, + } + + impl std::ops::Deref for CvarApp { + type Target = App; + fn deref(&self) -> &App { + &self.app + } + } + + impl std::ops::DerefMut for CvarApp { + fn deref_mut(&mut self) -> &mut App { + &mut self.app + } + } + + /// A client with a real CVar host, hermetic: it holds [`CvarEnv`] for its life. A test that + /// builds a second client, or sets variables of its own, holds one itself and builds with + /// [`cvar_app_in`]. + fn cvar_app() -> CvarApp { + let env = CvarEnv::hold(); + CvarApp { + app: cvar_app_in(&env), + _env: env, + } + } + + /// A client with a real CVar host: every knob resource a callback writes, the callbacks, /// [`CvarPlugin`] and a VM for the mirror. - fn cvar_app() -> App { + fn cvar_app_in(_env: &CvarEnv) -> App { let mut app = App::new(); app.add_plugins(bevy::MinimalPlugins) .insert_resource(SoundConfig::default()) @@ -2799,88 +2850,69 @@ mod tests { .init_resource::() .init_resource::() .add_plugins(CvarPlugin); - for observer in ALL_OBSERVERS { - observer(&mut app); - } app.insert_non_send_resource(UiScript::new().unwrap()); app } - /// Every CVar observer in the crate; a new one is a line here and an `add_observer` in its - /// plugin. - const ALL_OBSERVERS: &[fn(&mut App)] = &[ - |app| { - app.add_observer(crate::player::approach_on_cvar); - }, - |app| { - app.add_observer(crate::sound::on_cvar); - }, - |app| { - app.add_observer(crate::ui_script::on_cvar); - }, - |app| { - app.add_observer(crate::video::on_cvar); - }, - |app| { - app.add_observer(crate::player::camera::on_cvar); - }, - |app| { - app.add_observer(crate::player::camera_dynamics::on_cvar); - }, - |app| { - app.add_observer(crate::target::on_cvar); - }, - |app| { - app.add_observer(crate::spell::cast_target::on_cvar); - }, - |app| { - app.add_observer(crate::combat_text::on_cvar); - }, - |app| { - app.add_observer(crate::ui_chat::combat::on_cvar); - }, - |app| { - app.add_observer(crate::ui_loot::on_cvar); - }, - |app| { - app.add_observer(crate::nameplates::on_cvar); - }, - |app| { - app.add_observer(crate::game_tip::on_cvar); - }, - |app| { - app.add_observer(crate::text_filter::on_cvar); - }, - |app| { - app.add_observer(crate::chat_bubble::on_cvar); - }, - |app| { - app.add_observer(crate::ui_guild::on_cvar); - }, - |app| { - app.add_observer(crate::ui_trade::on_cvar); - }, - |app| { - app.add_observer(crate::minimap::on_cvar); - }, - |app| { - app.add_observer(crate::portrait::on_cvar); - }, - |app| { - app.add_observer(crate::perf::on_cvar); - }, - |app| { - app.add_observer(crate::realmlist::on_cvar); - }, - |app| { - app.add_observer(crate::ui_gamma::on_cvar); - }, - |app| { - app.add_observer(crate::world_backdrop::on_cvar); - }, - ]; + /// A test built on [`cvar_app`] reads the same environment whichever tests run beside it: a + /// capture that sets the window variables under `ENV_LOCK` on another thread leaves the build + /// waiting for the lock, and it then sees the attended default, not that run's windowed one. + #[test] + fn a_cvar_app_is_built_outside_another_tests_window_variables() { + use std::sync::mpsc; + let (set_tx, set_rx) = mpsc::channel(); + let (go_tx, go_rx) = mpsc::channel(); + let capture = std::thread::spawn(move || { + let _l = ENV_LOCK + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let _w = EnvGuard::set("WOW_WIN", "800x600"); + let _c = EnvGuard::set("WOW_CAPTURE", "ui-trainer"); + set_tx.send(()).unwrap(); + go_rx.recv().unwrap(); + // Held for as long as a capture test builds its client: far past the build below. + std::thread::sleep(std::time::Duration::from_millis(250)); + }); + set_rx.recv().unwrap(); + go_tx.send(()).unwrap(); + let app = cvar_app(); + assert_eq!( + res::(&app).display, + crate::video::DisplayMode::Fullscreen + ); + drop(app); + capture.join().unwrap(); + } - /// A host write, its latch committed at once, and its observers run before this returns. + /// The scrub leaves nothing a CVar host reads: no window variable, no state folder, and no + /// run-driving variable the list does not name; it gives them back. + #[test] + fn the_host_environment_is_scrubbed_and_comes_back() { + use crate::video::windowed_env; + let _l = ENV_LOCK + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let _set: Vec<_> = HOST_ENV + .into_iter() + .map(|k| EnvGuard::set(k, "1")) + .collect(); + let _run = EnvGuard::set("WOW_UNATTENDED", "1"); + assert!(windowed_env(), "the premise: a run that owns its window"); + + let scrub = scrub_host_env(); + assert!(!windowed_env(), "the prefix scan too, whatever is set"); + for key in HOST_ENV { + assert!(std::env::var_os(key).is_none(), "{key}"); + } + drop(scrub); + assert!(windowed_env()); + for key in HOST_ENV { + assert_eq!(std::env::var(key).as_deref(), Ok("1"), "{key}"); + } + assert!(std::env::var_os("WOW_BG").is_none()); + } + + /// A host write, its latch committed at once, and its callbacks run before this returns. fn apply(app: &mut App, name: &str, value: &str) -> SetOutcome { let world = app.world_mut(); let (outcome, events) = { @@ -2955,8 +2987,8 @@ mod tests { } /// `ConsoleExec(line)` as the typed `/console` runs it: on a VM seeded from the app's registry, - /// its writes drained back and their observers run; the console lines the callbacks and the - /// observers printed. + /// its writes drained back and their callbacks run; the console lines the checks and the + /// callbacks printed. fn console_exec(app: &mut App, line: &str) -> Vec { let world = app.world_mut(); let mut script = UiScript::new().unwrap(); @@ -3017,7 +3049,7 @@ mod tests { } /// A reset of a latched row moves the record, not the device: `GetCVar` and the save take - /// it, no observer fires, and a stage it found stays staged and is what the file holds. + /// it, no callback runs, and a stage it found stays staged and is what the file holds. #[test] fn a_latched_reset_moves_the_value_and_not_the_window() { let mut app = cvar_app(); @@ -3078,16 +3110,9 @@ mod tests { #[test] fn a_minimap_setzoom_reaches_the_knob_and_the_file() { - use crate::local_state::test_env::{EnvGuard, ENV_LOCK}; - let _l = ENV_LOCK - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); + let env = CvarEnv::hold(); let tmp = std::env::temp_dir().join(format!("benilla-mmzoom-{}", std::process::id())); std::fs::remove_dir_all(&tmp).ok(); - let _c = EnvGuard::unset("WOW_CAPTURE"); - let _u = EnvGuard::unset("WOW_UI_SCALE"); - let _f = EnvGuard::unset("WOW_FARCLIP"); - let _d = EnvGuard::unset("WOW_CLUTTER_DENSITY"); let _h = EnvGuard::set("BENILLA_HOME", tmp.to_str().unwrap()); // The previous session left the outdoor map zoomed right in. crate::local_state::write_atomic( @@ -3096,7 +3121,7 @@ mod tests { ) .unwrap(); - let mut app = cvar_app(); + let mut app = cvar_app_in(&env); app.update(); assert_eq!(app.world().resource::().outdoor, 5); @@ -3154,7 +3179,7 @@ mod tests { /// The string-valued rows, a closed list, each default checked on its own terms: `realmName` /// and `accountName` (the reference's registered `""`, `0x882748`) and `gxApi` are empty until - /// the session or the login screen writes them; `gxResolution` and `realmList` pass their observers' parsers + /// the session or the login screen writes them; `gxResolution` and `realmList` pass their callbacks' parsers /// ([`crate::video::parse_resolution`], [`crate::realmlist::normalize`]). #[test] fn the_string_valued_cvars_are_the_realm_and_the_windowed_size() { @@ -3515,17 +3540,9 @@ mod tests { /// [`CvarLoad`]. #[test] fn the_loaded_file_reaches_a_knob_before_anything_ordered_after_cvar_load() { - use crate::local_state::test_env::{EnvGuard, ENV_LOCK}; - let _l = ENV_LOCK - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); + let env = CvarEnv::hold(); let tmp = std::env::temp_dir().join(format!("benilla-cvar-load-{}", std::process::id())); std::fs::remove_dir_all(&tmp).ok(); - let _c = EnvGuard::unset("WOW_CAPTURE"); - let _u = EnvGuard::unset("WOW_UI_SCALE"); - let _f = EnvGuard::unset("WOW_FARCLIP"); - let _d = EnvGuard::unset("WOW_CLUTTER_DENSITY"); - let _m = EnvGuard::unset("WOW_MSAA"); let _h = EnvGuard::set("BENILLA_HOME", tmp.to_str().unwrap()); crate::local_state::write_atomic( &tmp.join("config.toml"), @@ -3541,7 +3558,7 @@ mod tests { ) { seen.0 = Some((sound.music, msaa.samples)); } - let mut app = cvar_app(); + let mut app = cvar_app_in(&env); app.init_resource::() .add_systems(Startup, after_load.after(CvarLoad)); app.update(); @@ -3642,7 +3659,7 @@ mod tests { } assert!( orphans.is_empty(), - "registered rows nothing in the source reads (an observer arm, a `cvars.get`, or a \ + "registered rows nothing in the source reads (a callback's arm, a `cvars.get`, or a \ `LUA_ONLY` entry with its stock reader): {orphans:?}" ); for (name, _) in LUA_ONLY { @@ -3683,4 +3700,87 @@ mod tests { ] ); } + + /// The engine verbs that write a CVar run its callback inside the call, as `SetCVar` does: + /// `SetGamma` (`0x489267`), `SetWorldDetail` (`0x488e51`), a video pair's setter (`0x488f30`) + /// and the minimap's `SetZoom` (`0x6da974`) each call `CVar::Set` (`0x63df50`), and + /// `RestartGx`'s handler commits the latched rows synchronously (`0x48dab0` → `0x639f60`). + /// So each knob has moved, and `GetCVar` reads the committed `gxWindow`, before the chunk's + /// next line, with no frame run. + #[test] + fn the_engine_cvar_verbs_run_their_callbacks_inside_the_call() { + let mut app = crate::game_plugins::schedule_tests::headless_client(); + app.insert_resource(bevy::ecs::error::DefaultErrorHandler( + bevy::ecs::error::ignore, + )); + let (tx, _rx) = crossbeam_channel::unbounded(); + app.insert_resource(crate::net::NetCommands(tx)); + app.update(); + app.insert_non_send_resource(UiScript::new().expect("a VM")); + // The registry seeds the new VM's mirror. + app.update(); + let window: String = crate::script_calls::with_hosted_vm(app.world_mut(), |s| { + s.expect("a VM").eval( + r#" + CreateFrame("Minimap", "ProbeMinimap", UIParent):SetZoom(2) + SetGamma(0.25) + SetWorldDetail(0) + SetFarclip(500) + SetCVar("gxWindow", "1") + RestartGx() + return GetCVar("gxWindow") + "#, + ) + }) + .expect("the chunk runs"); + assert_eq!( + window, "1", + "the restart committed the stage inside its call" + ); + let cvars = res::(&app); + assert_eq!(cvars.get("gamma"), Some("0.750000")); + assert_eq!(cvars.get("frillDensity"), Some("16")); + assert_eq!(cvars.get("farclip"), Some("500.000000")); + assert_eq!(cvars.get("minimapZoom"), Some("2")); + assert_eq!(cvars.get("gxWindow"), Some("1")); + assert_eq!(res::(&app).0, 0.75); + assert_eq!(res::(&app).outdoor, 2); + } + + /// The Video options' Okay sets the resolution, then the multisample format + /// (`OptionsFrame.lua:239-240`), with no `RestartGx` when no other row asked one. Each verb + /// runs `gxRestart` inside its call (`0x48c0bc`, `0x48c79b`), so both latched changes commit. + #[test] + fn an_okay_with_a_new_resolution_and_multisample_commits_both() { + let mut app = crate::game_plugins::schedule_tests::headless_client(); + app.insert_resource(bevy::ecs::error::DefaultErrorHandler( + bevy::ecs::error::ignore, + )); + let (tx, _rx) = crossbeam_channel::unbounded(); + app.insert_resource(crate::net::NetCommands(tx)); + app.insert_resource(benilla_world::view::MsaaFormats { + formats: vec![(24, 24, 1), (24, 24, 4)], + }); + app.update(); + let mut script = UiScript::new().expect("a VM"); + let size = |width, height| benilla_ui::script::ScreenResolution { width, height }; + script.set_screen_resolutions(vec![size(800, 600), size(1024, 768)], Some(size(800, 600))); + app.insert_non_send_resource(script); + app.update(); + let (resolution, samples): (String, String) = + crate::script_calls::with_hosted_vm(app.world_mut(), |s| { + s.expect("a VM").eval( + r#" + SetScreenResolution(2) + SetMultisampleFormat(2) + return GetCVar("gxResolution"), GetCVar("gxMultisample") + "#, + ) + }) + .expect("the chunk runs"); + assert_eq!((resolution.as_str(), samples.as_str()), ("1024x768", "4")); + let cvars = res::(&app); + assert_eq!(cvars.get("gxResolution"), Some("1024x768")); + assert_eq!(cvars.get("gxMultisample"), Some("4")); + } } diff --git a/crates/benilla-app/src/death/mod.rs b/crates/benilla-app/src/death/mod.rs index 97fb60e60..13f3e3d76 100644 --- a/crates/benilla-app/src/death/mod.rs +++ b/crates/benilla-app/src/death/mod.rs @@ -1,21 +1,24 @@ //! Death and resurrection: the wire-fed stores, the events into the Lua UI and the intents back -//! to the wire. Dead is health 0 and ghost is `PLAYER_FLAGS` bit 0x10, read off the self -//! descriptor each frame. The death state signals (`PLAYER_DEAD` or `PLAYER_ALIVE`) inside our -//! own death's handler ([`signal_death_state`]) and after each arrival's world-enter cascade -//! ([`feed_death`]), and `PLAYER_ALIVE` on release and on a pre-release res. The -//! cascade releases a body it finds dead ([`repop_on_world_enter`]). -//! `PLAYER_UNGHOST` is the ghost state's (`0x5de9c0`), signalled where it runs: the ghost bit's -//! clear ([`crate::field_watch`]) and an alive arrival (`crate::ui_unit`). +//! to the wire. Dead is health 0 and ghost is `PLAYER_FLAGS` bit 0x10. The getters read the +//! stores through the host as they run ([`DeathView`]). The death state signals (`PLAYER_DEAD` or +//! `PLAYER_ALIVE`) inside our own death's handler and after each arrival's world-enter cascade +//! ([`signal_death_state`]), and `PLAYER_ALIVE` in the health watcher's revive arm, on release +//! and on a res ([`crate::field_watch`]). The offers and the corpse-range signals that packets +//! raise go on the dialogs' lane at their handlers ([`net`]); the corpse range's own poll runs in +//! the world frame's update ([`poll_corpse`]). The cascade releases a body it finds dead +//! ([`repop_on_world_enter`]). `PLAYER_UNGHOST` is the ghost state's (`0x5de9c0`), signalled where +//! it runs: the ghost bit's clear ([`crate::field_watch`]) and an alive arrival (`crate::ui_unit`). use bevy::prelude::*; use benilla_assets::coords::wow_to_bevy; -use benilla_ui::script::{DeathAction, DeathUiState, ScriptValue, UiScript}; +use benilla_ui::script::{ + DeathAction, DeathQuery, DeathUiState, ResSicknessLevelQuery, ScriptValue, UiScript, +}; use crate::net::{ClientCommand, NetCommands, ObjectStore, Objects, SelfGuid, SelfPlayer}; use crate::query_cache::Ask; use crate::ui_action::Spells; -use crate::ui_script::UiFeed; pub(crate) mod net; @@ -42,6 +45,9 @@ pub(crate) struct ResurrectOffer { pub(crate) sickness: bool, /// The reclaim-delay gate still holds: RESURRECT, not RESURRECT_NO_TIMER. pub(crate) has_timer: bool, + /// The caster's name was asked with the callback `0x5e7ca0` (`0x5e7c82`), whose answer shows + /// the offer or forgets it. + pub(crate) waits_name: bool, } /// The release timer our own death arms (`0x5e99b0`, `0xb4e340` and its no-timer byte @@ -69,22 +75,15 @@ pub(crate) struct DeathNet { pub(crate) release: ReleaseTimer, /// When the corpse becomes reclaimable: `SMSG_CORPSE_RECLAIM_DELAY` anchored at arrival. pub(crate) reclaim_at: Option, - /// Bumped per `SMSG_CORPSE_RECLAIM_DELAY`: the 1.12 client's handler re-fires the range - /// events on each. - pub(crate) reclaim_generation: u32, /// The last `MSG_CORPSE_QUERY` answer; a not-found drops it. pub(crate) corpse: Option, - /// A pending resurrection offer; cleared when answered or when the popup times out. + /// A pending resurrection offer (`[0xc4d760]`); cleared when answered, or by a refused name. pub(crate) resurrect: Option, - /// Bumped per `SMSG_RESURRECT_REQUEST`: the offer announces per message (`0x5e7bc0` through - /// `0x5ded50`), because the stock UI can hide the popup without answering it. - pub(crate) resurrect_generation: u32, /// Our streamed corpse object's guid, which `CMSG_RECLAIM_CORPSE` carries like the 1.12 client. pub(crate) corpse_guid: Option, - /// The spirit healer awaiting the XP-loss answer; Accept sends `CMSG_SPIRIT_HEALER_ACTIVATE`. + /// The spirit healer awaiting the XP-loss answer (`[0xc4d798]`); Accept sends + /// `CMSG_SPIRIT_HEALER_ACTIVATE`. pub(crate) spirit_healer: Option, - /// Bumped per ask: a Cancel clears nothing, so only a fresh ask re-shows the dialog. - pub(crate) confirm_generation: u32, /// Water-walking is granted on our mover; mirrored, not applied: walking on the water surface /// is not built. #[allow(dead_code)] @@ -107,61 +106,82 @@ impl DeathNet { pub(crate) fn zero_release(&mut self) { self.release = ReleaseTimer::Unset; } - - /// Arm the spirit healer's XP-loss question. The reference raises it on the click with no - /// packet (`0x5df730`), and vmangos also pushes `SMSG_SPIRIT_HEALER_CONFIRM`; both come here. - pub(crate) fn ask_spirit_healer(&mut self, npc: u64) { - self.spirit_healer = Some(npc); - self.confirm_generation = self.confirm_generation.wrapping_add(1); - } } -/// The feed's memory in two scopes: the body's state survives a `/reload`, while what the VM was -/// told dies with the VM. +/// The interface's death globals beside the stores, world-scoped and cleared at the session's end: +/// the corpse-range latch. A `/reload` keeps it. #[derive(Resource, Default)] -pub(crate) struct DeathFeedState { - /// World-scoped: the last `(guid, dead, ghost)` the self body showed. - mirror: Option<(u64, bool, bool)>, - /// World-scoped: the corpse-range latch `[0xb4e324]`, the last verdict signalled +pub(crate) struct DeathLatches { + /// The corpse-range latch `[0xb4e324]`: whether the last verdict signalled was in range /// (`0x4920f0`), which the cascade's corpse step zeroes into whichever VM is live. - corpse_range: Option, - /// A fresh reclaim delay re-fires the range events, as the 1.12 client does (`0x4962d0`), - /// so RECOVER_CORPSE re-shows with the new delay. - reclaim_generation: u32, - /// VM-scoped: the announce latches. - vm: crate::ui_script::VmMemo, + corpse_in_range: bool, } -impl DeathFeedState { +impl DeathLatches { /// The corpse-range latch set, as a ghost in range of its corpse left it. #[cfg(test)] pub(crate) fn latch_corpse_in_range_for_test(&mut self) { - self.corpse_range = Some(CorpseRange::In); + self.corpse_in_range = true; + } + + /// `SetCorpseInRange 0x4920f0`: on a change (`0x4920f6`), the latch stored and its signal, + /// [`CorpseSignal::in_range`] for in range, `CORPSE_OUT_OF_RANGE` (399, `0x49211f`) for out. + fn set_in_range( + &mut self, + in_range: bool, + corpse: Option<&CorpsePoint>, + ) -> Option { + if std::mem::replace(&mut self.corpse_in_range, in_range) == in_range { + return None; + } + Some(if in_range { + CorpseSignal::in_range(corpse) + } else { + CorpseSignal::Out + }) } } -/// What the live VM has been told. A fresh VM's first sight of the body is no edge: a `/reload`'s -/// cascade signals no death state (`0x490168` never reaches `0x495850`), and an arrival signals it -/// after its cascade (`0x5deb65`, [`signal_death_state`]). -#[derive(Default)] -struct DeathAnnounced { - /// The last `(guid, dead, ghost)` this VM was given an event for. - last: Option<(u64, bool, bool)>, - /// Held back while a player caster's name is still resolving. - offer_generation: u32, - /// The offer whose caster's name was looked up as its packet's (`0x5e7c82`, callback - /// `0x5e7ca0`): the frames that wait on it read. - offer_asked: u32, - /// A fresh ask re-fires `CONFIRM_XP_LOSS`. - confirm_generation: u32, +/// A corpse-range event, each argumentless (`0x703e50`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum CorpseSignal { + /// `CORPSE_IN_RANGE` (397). + In, + /// `CORPSE_IN_INSTANCE` (398). + InInstance, + /// `CORPSE_OUT_OF_RANGE` (399). + Out, } -/// The corpse-range verdicts the reference's events distinguish. -#[derive(Clone, Copy, PartialEq, Eq)] -enum CorpseRange { - Out, - In, - InInstance, +impl CorpseSignal { + /// The in-range event for the cached corpse: [`Self::InInstance`] when the cache's display + /// map is not the corpse's own, a dungeon's entrance (`0x492102`-`0x492114`, + /// `0x4962f5`-`0x496307`). + fn in_range(corpse: Option<&CorpsePoint>) -> Self { + if corpse.is_some_and(|c| u32::try_from(c.display_map) != Ok(c.corpse_map)) { + Self::InInstance + } else { + Self::In + } + } + + /// Signalled in place. + fn fire(self, script: &mut UiScript) { + match self { + Self::In => script.fire_event("CORPSE_IN_RANGE", vec![]), + Self::InInstance => script.fire_event("CORPSE_IN_INSTANCE", vec![]), + Self::Out => script.fire_event("CORPSE_OUT_OF_RANGE", vec![]), + } + } + + /// Queued on the dialogs' lane at a handler's place. + fn queue(self, lane: &mut crate::ui_dialog_verbs::DialogLane) { + match self { + Self::In => lane.event("CORPSE_IN_RANGE", vec![]), + Self::InInstance => lane.event("CORPSE_IN_INSTANCE", vec![]), + Self::Out => lane.event("CORPSE_OUT_OF_RANGE", vec![]), + } + } } /// The corpse-range dialog radius, 40 yd inclusive: the 1.12 client compares d² ≤ `[0xb4e2ac]` @@ -172,8 +192,8 @@ const CORPSE_RANGE_SQ: f32 = 40.0 * 40.0; /// The spirit-healer dialog range: `CheckSpiritHealerDist` compares d² ≤ `[0xc4c28c]` (30.864). const SPIRIT_HEALER_RANGE_SQ: f32 = 5.5556 * 5.5556; -/// What the death snapshot reads ([`DeathView::snapshot`]): the self body, the death stores and -/// what `HasSoulstone()` walks. +/// What the death getters read through the host as they run ([`DeathQuery`]): the self body, the +/// death stores and what `HasSoulstone()` walks. #[derive(bevy::ecs::system::SystemParam)] pub(crate) struct DeathView<'w, 's> { self_q: Query<'w, 's, (&'static ObjectStore, &'static Transform), With>, @@ -200,9 +220,9 @@ impl DeathView<'_, '_> { Some((guid, store, self_t)) } - /// The snapshot the death verbs read, pushed before an event fires so its handlers read - /// current values. - fn snapshot(&self, script: &UiScript, store: &ObjectStore, self_t: &Transform) -> DeathUiState { + /// The death state as the getters read it now: the timers off the stores, and what reads + /// the live body (the healer's range, the self-res) while one is held. + fn state(&self) -> DeathUiState { let now = self.time.elapsed_secs_f64(); let death_net = &self.death_net; let release_remaining = match death_net.release { @@ -214,196 +234,116 @@ impl DeathView<'_, '_> { let recovery_delay = death_net .reclaim_at .map_or(0.0, |at| (at - now).max(0.0) as f32); - let spirit_healer_in_range = death_net.spirit_healer.is_some_and(|npc| { - self.objects - .entity(npc) - .and_then(|e| self.transforms.get(e).ok()) - .is_some_and(|t| { - t.translation.distance_squared(self_t.translation) <= SPIRIT_HEALER_RANGE_SQ - }) + let body = self.body(); + let spirit_healer_in_range = body.is_some_and(|(_, _, self_t)| { + death_net.spirit_healer.is_some_and(|npc| { + self.objects + .entity(npc) + .and_then(|e| self.transforms.get(e).ok()) + .is_some_and(|t| { + t.translation.distance_squared(self_t.translation) <= SPIRIT_HEALER_RANGE_SQ + }) + }) }); - let sickness = sickness_duration( - store.0.unit_level().unwrap_or(0), - benilla_ui::strings::Strings::Vm(script.lua()), - ); DeathUiState { release_remaining, recovery_delay, resurrect_sickness: death_net.resurrect.as_ref().is_some_and(|o| o.sickness), resurrect_has_timer: death_net.resurrect.as_ref().is_some_and(|o| o.has_timer), spirit_healer_in_range, - sickness_duration: sickness, + // Worded by the getter off [`ResSicknessLevelQuery`]. + sickness_duration: None, // `HasSoulstone()`; the dead gate is first, so the inventory walk runs only while dead. - self_res_label: resolve_self_res( - &store.0, - &self.objects, - &self.items, - self.spells.as_deref(), - ) - .map(|r| r.label().to_owned()), + self_res_label: body.and_then(|(_, store, _)| { + resolve_self_res(&store.0, &self.objects, &self.items, self.spells.as_deref()) + .map(|r| r.label().to_owned()) + }), } } } -/// Derive the death state from the self descriptor, push the snapshot, and fire the death events -/// on its edges. Our player's arrival signals the death state itself, after its world-enter -/// cascade (`0x5deb65` → `0x495850`, [`signal_death_state`]): a login, a reconnect or a worldport -/// to a dead body hears `PLAYER_DEAD`, any other `PLAYER_ALIVE`. -pub(crate) fn feed_death( - // The death stores, which the death calls write: an engine turn, its events signalled after. - mut vm: crate::script_calls::VmWith>, - mut feed: ResMut, - names: Res, - net: Res, - map: Option>, - // Our player's create this frame, which runs no watcher (`0x465d80`): its death state is the - // arrival's own signal, not an edge. - arrivals: Query<(), Added>, -) { - let arrived = !arrivals.is_empty(); - vm.turn(|script, view| { - let Some(script) = script else { +/// The death getters' family of the host's live reads. +impl crate::script_calls::live::LiveFamily for DeathView<'_, '_> { + fn answer(&mut self, ask: &mut benilla_ui::script::live::LiveAsk<'_>) -> bool { + ask.answer(|_: &DeathQuery| Some(self.state())) + || ask.answer(|_: &ResSicknessLevelQuery| { + self.body() + .map(|(_, store, _)| store.0.unit_level().unwrap_or(0)) + }) + } +} + +/// What the corpse poll reads and writes beside the host: the self body's place and the session, +/// the death stores, the latches and the map shown. +type CorpsePoll = ( + Query<'static, 'static, &'static Transform, With>, + Res<'static, SelfGuid>, + Res<'static, crate::net::NetStatus>, + Res<'static, DeathNet>, + ResMut<'static, DeathLatches>, + Option>, +); + +/// `CheckCorpseRange 0x492130`, which the world frame's update runs every frame after its pick +/// (`0x4818c5`, in `0x481790`'s unconditional tail): the active player on the map shown within 40 +/// yards of the cached corpse is in range (`0x492196`), and `SetCorpseInRange` signals a change in +/// place ([`DeathLatches::set_in_range`]). The cache holds a corpse only for a ghost: an answer is +/// stored for one alone, and the ghost bit's edges reset it ([`reset_corpse`]). +pub(crate) fn poll_corpse(mut vm: crate::script_calls::VmWith) { + let signal = { + let (self_q, self_guid, status, death_net, mut latches, map) = vm.own(); + // A disconnect keeps the self avatar with its frozen descriptor; only a live session's + // body counts. + let body = self_guid + .0 + .filter(|_| status.connected) + .and_then(|_| self_q.single().ok()); + let Some(self_t) = body else { return; }; - let Some((guid, store, self_t)) = view.body() else { - return; - }; - let death_net = &view.death_net; - let dead = store.0.unit_is_dead(); - let ghost = store.0.player_is_ghost(); - - // ── The snapshot, set before the events fire so their handlers read current values ── - let snapshot = view.snapshot(script, store, self_t); - script.set_death(snapshot); - - // ── The world edges: the corpse asks, which a `/reload` must not repeat. - let prev = feed.mirror.filter(|&(g, ..)| g == guid); - feed.mirror = Some((guid, dead, ghost)); - match (prev, dead, ghost) { - // Dead to ghost (released): ask where the corpse is. - (Some((_, true, false)), _, true) => { - let _ = net.0.send(ClientCommand::CorpseQuery); + // Against the query's display position; the coordinate transform is isometric, so the + // Bevy-space compare is in yards. + let corpse = death_net.corpse.as_ref(); + let in_range = corpse.is_some_and(|cp| { + // Deviation: `0x492130` compares the positions whatever map we stand on, so a + // ghost on another map at the corpse's coordinates reads in range for a reclaim + // the server refuses; here only the corpse's display map counts. + let on_display_map = map + .as_ref() + .is_some_and(|m| m.0 == u32::try_from(cp.display_map).unwrap_or(u32::MAX)); + on_display_map + && wow_to_bevy(cp.position).distance_squared(self_t.translation) <= CORPSE_RANGE_SQ + }); + latches.set_in_range(in_range, corpse) + }; + if let Some(signal) = signal { + vm.run(|script| { + if let Some(script) = script { + signal.fire(script); } - // Ghost to alive: reclaim, spirit healer or an accepted res. - (Some((_, _, true)), false, false) => { - // The not-found answer drops the map markers. The reference sends nothing on this - // edge: its ghost-bit watcher (`0x5ee990`) clears the corpse cache, and `0x491f50` - // queries only while a ghost. The server's own push needs a looter - // (`Map.cpp:3617-3629`). - let _ = net.0.send(ClientCommand::CorpseQuery); - } - _ => {} - } - - // ── The VM edges: a fresh VM's memo is empty, and its first sight is no edge. - let memo = feed.vm.get(script); - let prev = memo.last.filter(|&(g, ..)| g == guid && !arrived); - memo.last = Some((guid, dead, ghost)); - fire_vm_edges(script, prev.map(|(_, d, g)| (d, g)), dead, ghost); - - // ── The offer and confirm announcements ── - let ask = Ask::at( - std::mem::replace(&mut memo.offer_asked, death_net.resurrect_generation) - != death_net.resurrect_generation, - &net, - ); - if let Some(name) = - offer_announcement(memo, death_net, store.0.is_dead_or_ghost(), |offer| { - // A player caster's name is empty on the wire; hold the popup until the cache - // resolves it. - if offer.name.is_empty() { - names.resolve_player(offer.caster, ask).map(str::to_owned) - } else { - Some(offer.name.clone()) - } - }) - { - script.fire_event("RESURRECT_REQUEST", vec![ScriptValue::Str(name)]); - } - if death_net.spirit_healer.is_some() - && memo.confirm_generation != death_net.confirm_generation - { - memo.confirm_generation = death_net.confirm_generation; - // `arg1` is the XP the res costs: `PLAYER_NEXT_LEVEL_XP` × 0.05, truncated - // (`0x5df837`), and 0 without the field, as `0x5df806` pushes 0 for a non-local object. - // No stock FrameXML reads it; `UIParent.lua:399` asks `GetResSicknessDuration()`. - let xp_cost = store - .0 - .player_next_level_xp() - .map_or(0, |next| (f64::from(next) * 0.05) as i64); - script.fire_event("CONFIRM_XP_LOSS", vec![ScriptValue::Int(xp_cost)]); - } - - // ── The corpse-run range gate: only a ghost, against the query's display position; the - // coordinate transform is isometric, so the Bevy-space compare is in yards. - let range = if ghost { - death_net.corpse.map(|cp| { - // Within range on the display map: IN_RANGE when it is the corpse's map, else - // IN_INSTANCE, at a dungeon's entrance (`0x492130`, `0x4920f0`). - let on_display_map = map - .as_ref() - .is_some_and(|m| m.0 == u32::try_from(cp.display_map).unwrap_or(u32::MAX)); - let near = on_display_map - && wow_to_bevy(cp.position).distance_squared(self_t.translation) - <= CORPSE_RANGE_SQ; - let same_map = u32::try_from(cp.display_map) == Ok(cp.corpse_map); - match (near, same_map) { - (false, _) => CorpseRange::Out, - (true, true) => CorpseRange::In, - (true, false) => CorpseRange::InInstance, - } - }) - } else { - None - }; - if feed.reclaim_generation != death_net.reclaim_generation { - feed.reclaim_generation = death_net.reclaim_generation; - feed.corpse_range = None; // re-announce whatever holds now - } - if range != feed.corpse_range { - match range { - Some(CorpseRange::In) => script.fire_event("CORPSE_IN_RANGE", vec![]), - Some(CorpseRange::InInstance) => script.fire_event("CORPSE_IN_INSTANCE", vec![]), - // Leaving range and the ghost state ending both fire the one hide event. - Some(CorpseRange::Out) | None if feed.corpse_range.is_some() => { - script.fire_event("CORPSE_OUT_OF_RANGE", vec![]); - } - _ => {} - } - feed.corpse_range = range; - } - }) + }); + } } /// `SignalDeathState 0x495850`, where our own death's `PresentUnitDeath` ends (`0x6251cc`, for /// the active player alone, `0x5fa6d0` at `0x6251c2`): with our health 0 or less (`jg` at /// `0x495876`) `PLAYER_DEAD` (`0x113`, `0x49587d`), its handlers reading the timer the death armed, /// then `ClearCursor(1, 1)` (`0x495889` → `0x495190`); else `PLAYER_ALIVE` (`0x112`, `0x495893`). -/// The VM's memo takes the state, so the feed signals no edge of it again. -pub(crate) fn signal_death( - mut vm: crate::script_calls::VmWith>, - mut feed: ResMut, -) { - signal(&mut vm, &mut feed); +/// Its handlers read the timer the death armed through the host. +pub(crate) fn signal_death(mut vm: crate::script_calls::VmWith>) { + signal(&mut vm); } /// [`signal_death`]'s body; false with no VM or no live body, which signals nothing. -fn signal( - vm: &mut crate::script_calls::VmWith>, - feed: &mut DeathFeedState, -) -> bool { +fn signal(vm: &mut crate::script_calls::VmWith>) -> bool { let dead = { - let (Some(script), set) = vm.parts() else { + let (Some(_), set) = vm.parts() else { return false; }; let view = set.p0(); - let Some((guid, store, self_t)) = view.body() else { + let Some((_, store, _)) = view.body() else { return false; }; - let snapshot = view.snapshot(script, store, self_t); - script.set_death(snapshot); - let memo = feed.vm.get(script); - memo.last = Some((guid, store.0.unit_is_dead(), store.0.player_is_ghost())); store.0.unit_health().unwrap_or(0) as i32 <= 0 }; // `0x495850`: the signal's listeners run before the cursor clears (`0x49587d`, `0x495889`). @@ -449,29 +389,40 @@ fn send_repop_request(store: &benilla_protocol::ObjectFields, net: &NetCommands) /// The corpse cache and the range latch, beside the host. type CorpseStores = ( Option>, - Option>, + Option>, ); -/// `QueryCorpse 0x491f50` in the world-enter cascade (`0x490a28`), after its other sends: the -/// corpse cache reset (`0x491f74` → `0x492010(-1, …)`), the range latch zeroed (`0x491f7b` → -/// `0x4920f0(0)`), which signals `CORPSE_OUT_OF_RANGE` from a set latch, then, for a ghost -/// (`PLAYER_FLAGS` bit 4, `0x491fad`), `MSG_CORPSE_QUERY` (`0x491fb2`). The flags watcher's -/// release and revive asks are [`feed_death`]'s. +/// `QueryCorpse 0x491f50`'s head: the corpse cache reset (`0x491f74` → `0x492010(-1, …)`) and the +/// range latch zeroed (`0x491f7b` → `0x4920f0(0)`). Whether the latch was set, so its caller +/// signals `CORPSE_OUT_OF_RANGE` (`0x49211f`) in place, ahead of [`ask_corpse`]. +pub(crate) fn reset_corpse( + death_net: Option<&mut DeathNet>, + latches: Option<&mut DeathLatches>, +) -> bool { + if let Some(death_net) = death_net { + death_net.corpse = None; + } + latches.is_some_and(|latches| std::mem::take(&mut latches.corpse_in_range)) +} + +/// `QueryCorpse 0x491f50`'s tail: `MSG_CORPSE_QUERY` (`0x491fb2`-`0x491fdf`) while the active +/// player is a ghost (`PLAYER_FLAGS` bit 4, `0x491fa1`-`0x491fb0`), nothing otherwise. +pub(crate) fn ask_corpse(ghost: bool, net: &NetCommands) { + if ghost { + let _ = net.0.send(ClientCommand::CorpseQuery); + } +} + +/// `QueryCorpse 0x491f50` in the world-enter cascade (`0x490a28`), after its other sends +/// ([`reset_corpse`], [`ask_corpse`]). The flags watcher's run on the ghost bit's edges is the +/// update packet's (`0x5eeac1`, [`crate::field_watch::FieldNotice::QueryCorpse`]). pub(crate) fn query_corpse_on_world_enter( self_q: Query<&ObjectStore, With>, mut vm: crate::script_calls::VmWith, net: Res, ) { - let (death_net, feed) = vm.own(); - if let Some(mut death_net) = death_net { - death_net.corpse = None; - } - let was_in = feed.is_some_and(|mut feed| { - matches!( - feed.corpse_range.take(), - Some(CorpseRange::In | CorpseRange::InInstance) - ) - }); + let (mut death_net, mut latches) = vm.own(); + let was_in = reset_corpse(death_net.as_deref_mut(), latches.as_deref_mut()); if was_in { vm.run(|script| { if let Some(script) = script { @@ -479,9 +430,10 @@ pub(crate) fn query_corpse_on_world_enter( } }); } - if self_q.single().is_ok_and(|store| store.0.player_is_ghost()) { - let _ = net.0.send(ClientCommand::CorpseQuery); - } + ask_corpse( + self_q.single().is_ok_and(|store| store.0.player_is_ghost()), + &net, + ); } /// The world-enter cascade's last test (`0x490a2d`-`0x490a38`): with our health 0 or less it @@ -594,26 +546,6 @@ fn self_res( }) } -/// The sickness a spirit-healer res applies at `level`, per vmangos `Player::ResurrectPlayer`: -/// none below 11, `level - 10` minutes through 19, 10 minutes from 20. Worded with `GENERIC_MIN`, -/// the minute arm of the reference's formatter (`0x51a3a0` into `0x52fa50`). -/// -/// Deviation: the minutes come from the server's table, not from spell 15007's `Spell.dbc` -/// duration, because the aura the server applies is what the dialog must warn about. -fn sickness_duration(level: u32, strings: benilla_ui::strings::Strings<'_>) -> Option { - let minutes = match level { - 0..=10 => return None, - 11..=19 => level - 10, - _ => 10, - }; - // `GetText(token, nil, ordinal)`, the VM's own. - let template = benilla_ui::strings::plural("GENERIC_MIN", Some(minutes), strings)?; - Some(benilla_ui::strings::fill( - &template, - &[benilla_ui::strings::Arg::D(i64::from(minutes))], - )) -} - /// Drive the FFXDeath screen pass off `PLAYER_FLAGS_GHOST`, instant both ways; in the reference /// the flag's watcher `0x5ee990` also drives the death light and ambience. fn drive_death_look( @@ -830,133 +762,90 @@ impl DeathSteps<'_, '_> { } } -/// Clear [`DeathFeedState`]'s world scope on `DisconnectedMessage`, the edge [`DeathNet`] resets -/// on: a relog as a ghost must find no mirror, or the corpse query is never re-sent. -fn end_session_death_feed( - mut msgs: MessageReader, - mut feed: ResMut, -) { - if msgs.read().next().is_some() { - *feed = DeathFeedState::default(); +/// `SpiritHealerDialog 0x5df730(npc)` asking: for a ghost (`PLAYER_FLAGS` bit 0x10, `0x5df74a`), +/// the healer `npc` held as a unit (`0x5df77a`) within the interaction range (`0x5df7c1`, +/// `[0xc4c28c]`) is remembered (`0x5df7e6`), and `CONFIRM_XP_LOSS` (396, `0x5df837`) is owed with +/// the XP the res costs, `PLAYER_NEXT_LEVEL_XP` × 0.05 truncated (`0x5df815`-`0x5df827`). No stock +/// FrameXML reads the cost; `UIParent.lua:399` asks `GetResSicknessDuration()`. +#[derive(bevy::ecs::system::SystemParam)] +pub(crate) struct SpiritHealerAsk<'w, 's> { + death_net: ResMut<'w, DeathNet>, + me: Query<'w, 's, (&'static ObjectStore, &'static Transform), With>, + objects: Objects<'w, 's>, + transforms: Query<'w, 's, &'static Transform>, +} + +impl SpiritHealerAsk<'_, '_> { + /// The ask for `npc`; the cost the signal carries when its gates pass, else nothing is + /// remembered and nothing signals. + pub(crate) fn ask(&mut self, npc: u64) -> Option { + let (store, self_t) = self.me.single().ok()?; + if !store.0.player_is_ghost() { + return None; + } + let healer = self + .objects + .entity(npc) + .filter(|_| self.objects.store(npc).is_some_and(|s| s.is_unit())) + .and_then(|e| self.transforms.get(e).ok())?; + if healer.translation.distance_squared(self_t.translation) > SPIRIT_HEALER_RANGE_SQ { + return None; + } + self.death_net.spirit_healer = Some(npc); + Some( + store + .0 + .player_next_level_xp() + .map_or(0, |next| (f64::from(next) * 0.05) as i64), + ) } } -/// The death stores, the feed into the UI, the intent drain and the root and water-walk messages. +/// [`SpiritHealerAsk`] from the click on a spirit healer, which the reference raises with no +/// packet (`0x5f0130` → `0x5df730`): `CONFIRM_XP_LOSS` signalled in place with the host. +pub(crate) fn ask_spirit_healer( + In(npc): In, + mut vm: crate::script_calls::VmWith>, +) { + let Some(cost) = vm.own().ask(npc) else { + return; + }; + vm.run(|script| { + if let Some(script) = script { + script.fire_event("CONFIRM_XP_LOSS", vec![ScriptValue::Int(cost)]); + } + }); +} + +/// The death stores, the corpse poll, the intent drain and the root and water-walk messages. pub(crate) struct DeathPlugin; impl Plugin for DeathPlugin { fn build(&self, app: &mut App) { net::register(app); + crate::ui_dialog_verbs::add_dialog_lane(app); app.init_resource::() - .init_resource::() + .init_resource::() .add_systems( Update, ( - feed_death - .in_set(UiFeed) - .after(crate::ui_unit::UnitSnapshots), + // The world frame's update, after its pick (`0x48184a`, then `0x4818c5`), as + // the area spirit healer's poll; gated, as the poll re-derives every frame. + poll_corpse + .after(crate::target::TargetUpdate) + .run_if(crate::ui_script::ingame_ui_up) + .in_set(crate::client_state::InWorldGated), drive_death_look, - // Before the feed, so the frame a session ends carries no memory of it. - end_session_death_feed.before(feed_death), ), ); } } -/// The name `RESURRECT_REQUEST` fires with this frame, if any. Per message, and only while dead -/// or a ghost (`0x5ded50` gated on `0x605f30`); an unresolved name holds without consuming it. -fn offer_announcement( - memo: &mut DeathAnnounced, - death_net: &DeathNet, - dead_or_ghost: bool, - name_of: impl FnOnce(&ResurrectOffer) -> Option, -) -> Option { - if !dead_or_ghost || memo.offer_generation == death_net.resurrect_generation { - return None; - } - let name = name_of(death_net.resurrect.as_ref()?)?; - memo.offer_generation = death_net.resurrect_generation; - Some(name) -} - #[cfg(test)] mod tests { use super::*; use bevy::ecs::system::RunSystemOnce; - fn offer(caster: u64, name: &str) -> ResurrectOffer { - ResurrectOffer { - caster, - name: name.into(), - sickness: false, - has_timer: true, - } - } - - /// The offer's packet looks a player caster's name up with the callback `0x5e7ca0` - /// (`0x5e7c82`); the frames the popup waits through read. A refused name is asked by no frame - /// after it, only by the next offer. - #[test] - fn a_refused_resurrecter_is_asked_by_the_next_offer_never_by_a_frame() { - use benilla_protocol::messages::ObjectType; - use benilla_protocol::ObjectFields; - const ME: u64 = 0x7; - const CASTER: u64 = 0x9; - let (tx, rx) = crossbeam_channel::unbounded(); - let mut app = App::new(); - app.insert_resource(NetCommands(tx)) - .insert_resource(crate::net::NetStatus { - connected: true, - last_reason: None, - }) - .init_resource::() - .init_resource::() - .init_resource::() - .init_resource::() - .init_resource::() - .init_resource::() - .init_resource::>() - .add_systems(Update, feed_death); - app.insert_non_send_resource(UiScript::new().unwrap()); - // `UNIT_FIELD_HEALTH` 0 of a `UNIT_FIELD_MAXHEALTH` 100: dead. - let dead = ObjectFields::from_pairs(&[(22, 0), (28, 100)]).into_created(ObjectType::Player); - let me = app - .world_mut() - .spawn((ObjectStore(dead), Transform::default(), SelfPlayer)) - .id(); - app.world_mut() - .resource_mut::() - .0 - .insert(ME, me); - app.world_mut().resource_mut::().0 = Some(ME); - let offer = |app: &mut App| { - net::resurrect_request_for_tests( - CASTER, - &mut app.world_mut().resource_mut::(), - ); - app.update(); - }; - app.update(); - offer(&mut app); - assert_eq!(crate::query_cache::queries(&rx).len(), 1); - app.world_mut() - .resource_mut::() - .insert_player(CASTER, String::new(), None); - for _ in 0..600 { - app.update(); - } - assert!( - crate::query_cache::queries(&rx).is_empty(), - "no frame asks a refusal" - ); - offer(&mut app); - assert_eq!( - crate::query_cache::queries(&rx).len(), - 1, - "the next offer asks again" - ); - } - /// `0x495850` signals `PLAYER_DEAD` (`0x49587d`) before it clears the cursor (`0x495889`): a /// listener still finds the coins it held. #[test] @@ -973,7 +862,7 @@ mod tests { }) .init_resource::() .init_resource::() - .init_resource::() + .init_resource::() .init_resource::() .init_resource::() .init_resource::>(); @@ -1004,48 +893,6 @@ mod tests { assert!(script.cursor_payload().is_none(), "then the clear"); } - /// PLAYER_UNGHOST hides the popup with `StaticPopup_Hide`, which runs no `OnCancel`, so no - /// Decline clears `resurrect`. - #[test] - fn every_resurrect_message_announces_while_dead_and_never_while_alive() { - let mut net = DeathNet::default(); - let mut memo = DeathAnnounced::default(); - let name = |o: &ResurrectOffer| Some(o.name.clone()); - - net.resurrect = Some(offer(1, "Healer")); - net.resurrect_generation += 1; - assert_eq!( - offer_announcement(&mut memo, &net, true, name).as_deref(), - Some("Healer") - ); - assert_eq!( - offer_announcement(&mut memo, &net, true, name), - None, - "once per message" - ); - - // Alive with the offer unanswered: a fresh VM must not announce it. - let mut reloaded = DeathAnnounced::default(); - assert_eq!(offer_announcement(&mut reloaded, &net, false, name), None); - - // Dead again, a new priest offers. - net.resurrect = Some(offer(2, "Ptwo")); - net.resurrect_generation += 1; - assert_eq!( - offer_announcement(&mut memo, &net, true, name).as_deref(), - Some("Ptwo"), - "the second offer announces" - ); - - // A name still resolving holds the announcement without consuming it. - net.resurrect_generation += 1; - assert_eq!(offer_announcement(&mut memo, &net, true, |_| None), None); - assert_eq!( - offer_announcement(&mut memo, &net, true, name).as_deref(), - Some("Ptwo") - ); - } - const STONE: u64 = 0x4000_0000_0000_5232; const SELF_RES: u32 = 20707; const FIREBALL: u32 = 133; @@ -1493,46 +1340,32 @@ mod tests { ); } - /// A `/reload` keeps the body's mirror, so it re-sends no corpse ask; a relog must clear it. + /// The session's end clears the range latch, so a relog starts out of range. A `/logout` is a + /// session edge although `session_over` is false for it. #[test] - fn the_session_edge_clears_the_world_scoped_death_memory_and_nothing_else_does() { - let mut app = App::new(); - app.add_message::() - .insert_resource(DeathFeedState { - mirror: Some((0x1234, true, true)), - ..Default::default() - }); - - // No session edge: the memory stands. - app.world_mut() - .run_system_once(end_session_death_feed) + fn the_session_edge_clears_the_world_scoped_death_memory() { + let mut world = World::new(); + world.init_resource::(); + world.insert_resource(DeathLatches { + corpse_in_range: true, + }); + world + .run_system_cached_with( + net::on_session_end, + benilla_protocol::SessionEvent::Disconnected { + reason: "logged out".into(), + end: benilla_protocol::SessionEnd::LoggedOut, + }, + ) .expect("the teardown runs"); - assert_eq!( - app.world().resource::().mirror, - Some((0x1234, true, true)), - "nothing but the session edge may clear the body's own state machine" - ); - - // A `/logout` is a session edge although `session_over` is false for it. - app.world_mut() - .write_message(crate::net::DisconnectedMessage::new( - "logged out".into(), - benilla_protocol::SessionEnd::LoggedOut, - )); - app.world_mut() - .run_system_once(end_session_death_feed) - .expect("the teardown runs"); - let feed = app.world().resource::(); - assert!( - feed.mirror.is_none(), - "a relog must find no mirror, or the login-while-ghost arm cannot fire" - ); + let latches = world.resource::(); + assert!(!latches.corpse_in_range, "a relog starts out of range"); } /// `PLAYER_FIELD_BYTES`, whose bit 0x8 our own death's timer reads (`0x5e9a27`). const BYTES: u16 = 1222; - /// A world with our player at `health`, the release-timer bit set, the death feed and the + /// A world with our player at `health`, the release-timer bit set, the death stores and the /// arrival's signal, and a VM that records each death-state event with the timer it reads. fn arrival_app(health: u32) -> App { use benilla_protocol::field::{FIELD_UNIT_HEALTH, FIELD_UNIT_MAXHEALTH}; @@ -1548,14 +1381,13 @@ mod tests { }) .init_resource::() .init_resource::() - .init_resource::() + .init_resource::() .init_resource::() .init_resource::() .init_resource::() .init_resource::>() .insert_resource(State::new(crate::client_state::ClientState::InWorld)) - .add_plugins(crate::ui_world_enter::WorldEnterPlugin) - .add_systems(Update, feed_death); + .add_plugins(crate::ui_world_enter::WorldEnterPlugin); app.insert_non_send_resource(recording_vm()); let body = ObjectFields::from_pairs(&[ (FIELD_UNIT_HEALTH, health), @@ -1634,70 +1466,6 @@ mod tests { } } -/// Run the death feed once on `world`, for a test of what it pushes. -#[cfg(test)] -pub(crate) fn run_feed_death_once(world: &mut World) { - use bevy::ecs::system::RunSystemOnce; - world - .run_system_once(feed_death) - .expect("the death feed runs"); -} - -/// The body's VM events between the last `(dead, ghost)` seen, if any, and this one. -fn fire_vm_edges(script: &mut UiScript, prev: Option<(bool, bool)>, dead: bool, ghost: bool) { - match (prev, dead, ghost) { - (Some((true, false)), d, g) if g || !d => { - // The health edge out of 0 (`0x6047f0`) unlocks every item (`0x5fefae`), then fires - // `PLAYER_ALIVE` (`0x5fefb8`). - script.unlock_all_items(); - script.fire_event("PLAYER_ALIVE", vec![]); - } - _ => {} - } -} - -#[cfg(test)] -mod edge_tests { - use benilla_ui::script::UiScript; - - /// The revive edge unlocks every item, its one `ITEM_LOCK_CHANGED` ahead of `PLAYER_ALIVE` - /// (`0x5fefae`, `0x5fefb8`); the ghost's own revive, no health edge, unlocks nothing. - #[test] - fn the_revive_edge_unlocks_every_item_before_player_alive() { - const ITEM: u64 = 0x4000_0000_0000_0042; - let mut s = UiScript::new().unwrap(); - s.run( - "SEEN = {} local f = CreateFrame('Frame') \ - f:RegisterEvent('ITEM_LOCK_CHANGED') f:RegisterEvent('PLAYER_ALIVE') \ - f:RegisterEvent('PLAYER_UNGHOST') \ - f:SetScript('OnEvent', function() table.insert(SEEN, event) end)", - ) - .unwrap(); - let seen = |s: &UiScript| { - let out = s.eval::>("return SEEN").unwrap(); - s.run("SEEN = {}").unwrap(); - out - }; - s.lock_item(ITEM); - let _ = seen(&s); - super::fire_vm_edges(&mut s, Some((true, false)), true, true); - assert_eq!( - seen(&s), - ["ITEM_LOCK_CHANGED", "PLAYER_ALIVE"], - "the release" - ); - assert!(!s.item_locked(ITEM)); - s.lock_item(ITEM); - let _ = seen(&s); - super::fire_vm_edges(&mut s, Some((true, true)), false, false); - assert!( - seen(&s).is_empty(), - "the corpse run's end: its event is the ghost bit's (`0x5de9c0`)" - ); - assert!(s.item_locked(ITEM)); - } -} - #[cfg(test)] mod self_res_tests { use std::collections::HashMap; diff --git a/crates/benilla-app/src/death/net.rs b/crates/benilla-app/src/death/net.rs index c196b42c0..6de8de358 100644 --- a/crates/benilla-app/src/death/net.rs +++ b/crates/benilla-app/src/death/net.rs @@ -1,11 +1,15 @@ -//! The death packet handlers filling [`DeathNet`], the movement-mode forward for our own mover, -//! and the corpse-guid latch's hooks on the object lifecycle, called from the drain's object arms. +//! The death packet handlers filling [`DeathNet`], each signal they raise on the dialogs' lane at +//! the packet's place, the movement-mode forward for our own mover, and the corpse-guid latch's +//! hooks on the object lifecycle, called from the drain's object arms. use benilla_protocol::{EntityKind, MoveMode, ObjectFields, SessionEvent, SessionEventKind}; +use benilla_ui::script::ScriptValue; use bevy::prelude::*; -use super::{CorpsePoint, DeathNet, ResurrectOffer}; -use crate::net::{MoveModeMessage, NetHandlerApp, SelfGuid}; +use super::{CorpsePoint, DeathLatches, DeathNet, ResurrectOffer}; +use crate::net::{MoveModeMessage, NetHandlerApp, ObjectStore, SelfGuid, SelfPlayer}; +use crate::query_cache::Ask; +use crate::ui_dialog_verbs::DialogLane; /// Register the death handlers and the session-end listener. pub(super) fn register(app: &mut App) { @@ -19,7 +23,18 @@ pub(super) fn register(app: &mut App) { .net_handler(K::Disconnected, on_session_end); } -fn on_corpse_query(In(ev): In, mut death_net: ResMut) { +/// `MSG_CORPSE_QUERY`'s two arms of `0x48f690`: a found answer to a ghost fills the cache +/// (`0x48f7d1` → `0x492010`), the found byte, the active player (`0x468460`) and its ghost bit +/// tested first (`0x48f75f`-`0x48f779`); any other answer resets it (`0x48f800`) and lowers the +/// range latch (`0x48f807` → `0x4920f0(0)`), whose `CORPSE_OUT_OF_RANGE` signals at the packet +/// when it was set. +fn on_corpse_query( + In(ev): In, + me: Query<&ObjectStore, With>, + mut death_net: ResMut, + mut latches: ResMut, + mut lane: ResMut, +) { if let SessionEvent::CorpseQuery { found, display_map, @@ -27,21 +42,51 @@ fn on_corpse_query(In(ev): In, mut death_net: ResMut) { corpse_map, } = ev { - corpse_query(found, display_map, position, corpse_map, &mut death_net); + let ghost = me.iter().next().is_some_and(|s| s.0.player_is_ghost()); + let stored = corpse_query( + found && ghost, + display_map, + position, + corpse_map, + &mut death_net, + ); + if !stored { + if let Some(signal) = latches.set_in_range(false, None) { + signal.queue(&mut lane); + } + } } } +/// `SMSG_CORPSE_RECLAIM_DELAY` (`0x48f828` → `SetCorpseReclaimDelay 0x4962d0`): the delay stored, +/// then the in-range event again while the latch is set (`0x4962ec`-`0x49630d`), at the packet, so +/// `RECOVER_CORPSE` re-shows over the new delay. fn on_corpse_reclaim_delay( In(ev): In, mut death_net: ResMut, + latches: Res, + mut lane: ResMut, real_clock: Res>, ) { if let SessionEvent::CorpseReclaimDelay { delay_ms } = ev { corpse_reclaim_delay(delay_ms, real_clock.elapsed_secs_f64(), &mut death_net); + if latches.corpse_in_range { + super::CorpseSignal::in_range(death_net.corpse.as_ref()).queue(&mut lane); + } } } -fn on_resurrect_request(In(ev): In, mut death_net: ResMut) { +/// `ReadResurrectRequest 0x5e7bc0`: the offer stored (`0x5e7c13`-`0x5e7c2d`); with the active +/// player held (`0x5e7c4a`), a name on the wire shows it at once (`0x5e7c56`), else the caster's +/// name is looked up with the callback `0x5e7ca0` (`0x5e7c82`), a cached one showing it at once. +fn on_resurrect_request( + In(ev): In, + mut death_net: ResMut, + names: Res, + net: Res, + me: Query<&ObjectStore, With>, + mut lane: ResMut, +) { if let SessionEvent::ResurrectRequest { caster, name, @@ -49,13 +94,79 @@ fn on_resurrect_request(In(ev): In, mut death_net: ResMut show_resurrect_request(&me.0, &name, &mut lane), + None => { + if let Some(offer) = death_net.resurrect.as_mut() { + offer.waits_name = true; + } + } + } } } -fn on_spirit_healer_confirm(In(ev): In, mut death_net: ResMut) { +/// The callback `0x5e7ca0` for `guid`'s answer, the offer's caster whose name it waited on: a found +/// name shows the offer while the active player is held (`0x5e7d02` → `0x5e7d09`), a refused one +/// forgets it (`0x5e7d19`-`0x5e7d2b`). +pub(crate) fn resurrecter_named( + death_net: &mut DeathNet, + me: Option<&ObjectStore>, + lane: &mut DialogLane, + guid: u64, + name: Option<&str>, +) { + let Some(offer) = death_net + .resurrect + .as_mut() + .filter(|o| o.waits_name && o.caster == guid) + else { + return; + }; + offer.waits_name = false; + match name.filter(|n| !n.is_empty()) { + Some(name) => { + if let Some(me) = me { + show_resurrect_request(&me.0, name, lane); + } + } + None => death_net.resurrect = None, + } +} + +/// `ShowResurrectRequest 0x5ded50`: `RESURRECT_REQUEST` with a non-empty `name` (`0x5ded5b`) +/// while the active player is dead or a ghost (`0x5ded60` → `0x605f30`). +fn show_resurrect_request(me: &ObjectFields, name: &str, lane: &mut DialogLane) { + if !name.is_empty() && me.is_dead_or_ghost() { + lane.event( + "RESURRECT_REQUEST", + vec![ScriptValue::Str(name.to_string())], + ); + } +} + +/// `SMSG_SPIRIT_HEALER_CONFIRM`'s arm of the notice handler (`0x5e38c0` → `0x5df730`): the +/// healer's gossip re-sends it on every ask, and each that passes the ask's gates signals at its +/// packet. +fn on_spirit_healer_confirm( + In(ev): In, + mut ask: super::SpiritHealerAsk, + mut lane: ResMut, +) { if let SessionEvent::SpiritHealerConfirm { npc } = ev { - spirit_healer_confirm(npc, &mut death_net); + if let Some(cost) = ask.ask(npc) { + lane.event("CONFIRM_XP_LOSS", vec![ScriptValue::Int(cost)]); + } } } @@ -90,9 +201,15 @@ fn on_move_mode( } } -/// The death stores are session-scoped; a reconnect while dead re-sends the reclaim delay. -fn on_session_end(In(_): In, mut death_net: ResMut) { +/// The death stores and latches are session-scoped; a reconnect while dead re-sends the reclaim +/// delay, and a relog as a ghost asks for its corpse in the world-enter cascade. +pub(super) fn on_session_end( + In(_): In, + mut death_net: ResMut, + mut latches: ResMut, +) { *death_net = DeathNet::default(); + *latches = DeathLatches::default(); } /// Our corpse streaming in: latch its guid for the reclaim send. The reference's latch @@ -146,26 +263,26 @@ pub(crate) fn forget_corpse(guid: u64, death_net: &mut DeathNet) { } } -/// `MSG_CORPSE_QUERY`'s answer; a not-found, asked or pushed at bones conversion, drops the marker. +/// `MSG_CORPSE_QUERY`'s answer, `store` when it is found for a ghost; any other, a not-found asked +/// or pushed at bones conversion among them, drops the marker. Whether it stored. fn corpse_query( - found: bool, + store: bool, display_map: i32, position: [f32; 3], corpse_map: u32, death_net: &mut DeathNet, -) { - death_net.corpse = found.then_some(CorpsePoint { +) -> bool { + death_net.corpse = store.then_some(CorpsePoint { display_map, position, corpse_map, }); + store } -/// `SMSG_CORPSE_RECLAIM_DELAY`, anchored at arrival on the clock the feed reads. The 1.12 client -/// re-fires the corpse-range events on each (`0x4962d0`), hence the generation bump. +/// `SMSG_CORPSE_RECLAIM_DELAY`, anchored at arrival on the clock the getters read. fn corpse_reclaim_delay(delay_ms: u32, now_secs: f64, death_net: &mut DeathNet) { death_net.reclaim_at = Some(now_secs + f64::from(delay_ms) / 1000.0); - death_net.reclaim_generation = death_net.reclaim_generation.wrapping_add(1); } /// `SMSG_RESURRECT_REQUEST`, the RESURRECT popup's data. @@ -181,20 +298,8 @@ fn resurrect_request( name, sickness, has_timer, + waits_name: false, }); - death_net.resurrect_generation = death_net.resurrect_generation.wrapping_add(1); -} - -/// A player caster's offer, its name empty on the wire, as [`resurrect_request`] records it. -#[cfg(test)] -pub(super) fn resurrect_request_for_tests(caster: u64, death_net: &mut DeathNet) { - resurrect_request(caster, String::new(), false, true, death_net); -} - -/// `SMSG_SPIRIT_HEALER_CONFIRM`: the healer's gossip re-sends it on every ask, and the reference -/// fires `CONFIRM_XP_LOSS` per arrival. -fn spirit_healer_confirm(npc: u64, death_net: &mut DeathNet) { - death_net.ask_spirit_healer(npc); } /// `SMSG_DURABILITY_DAMAGE_DEATH`, the 10% death durability loss: a combat-log line at chat type diff --git a/crates/benilla-app/src/entities/missile.rs b/crates/benilla-app/src/entities/missile.rs index bab57521a..c71b1c783 100644 --- a/crates/benilla-app/src/entities/missile.rs +++ b/crates/benilla-app/src/entities/missile.rs @@ -445,8 +445,6 @@ fn arrival_handoff( entity, spell_id, kind, - cast_flags: 0, - item_cast: false, seq: play_seq.next(), }; match missile.aim { diff --git a/crates/benilla-app/src/field_callbacks.rs b/crates/benilla-app/src/field_callbacks.rs index 4fd53d1fe..f0f78d491 100644 --- a/crates/benilla-app/src/field_callbacks.rs +++ b/crates/benilla-app/src/field_callbacks.rs @@ -14,7 +14,9 @@ //! //! What a callback pushes onto a lane is stamped under its edge, so it fires where the watcher ran //! among what the packets raised. The Lua a callback's cores signal is held as it runs and parked -//! behind it on this module's lane ([`Parked`]), at a stamp taken as it ends. +//! behind it on this module's lane ([`Parked`]), at a stamp taken as it ends. The item cache's +//! answer parks its VM callbacks here too ([`crate::net::objects`]): the equip replays and the +//! quest log's `QUEST_LOG_UPDATE`; and a refused record's walk goes on here behind its signals. use std::collections::VecDeque; @@ -26,10 +28,28 @@ use benilla_protocol::{SessionEvent, SessionEventKind}; use crate::lanes::{Stamp, Until}; use crate::net::{AuraFieldsChanged, FieldChanged, NetHandlerApp}; -/// The Lua the callbacks' legs signalled, parked in the VM, each with its stamp and the VM's -/// session and key, for the field callbacks' lane. +/// The Lua the callbacks' legs signalled, parked in the VM, each with its stamp, for the field +/// callbacks' lane. #[derive(Resource, Default)] -pub(crate) struct FieldCallbacks(VecDeque<(Stamp, u64, u64)>); +pub(crate) struct FieldCallbacks(VecDeque<(Stamp, Item)>); + +/// One item of the lane. +#[derive(Clone, Copy)] +pub(crate) enum Item { + /// A leg's signals, under the VM's session and key. + Parked(u64, u64), + /// A refused record's walk, gone on behind its signals + /// ([`crate::net::continue_refusal_walk`]). + Walk(u32, crate::lanes::Mark), +} + +/// Queue the walk of `entry` that began at `from` to go on behind what it has signalled so far. +pub(crate) fn walk_on(world: &mut World, entry: u32, from: crate::lanes::Mark) { + let at = crate::lanes::stamp(); + if let Some(mut lane) = world.get_resource_mut::() { + lane.0.push_back((at, Item::Walk(entry, from))); + } +} /// The VM's end, a reload's or the session's: what the callbacks parked goes with it. pub(crate) fn drop_parked(world: &mut World) { @@ -97,6 +117,12 @@ impl Parked { Self(crate::script_calls::defer_vm(world)) } + /// [`Self::new`] split as a close's halves: the legs' calls apply at once through the lent + /// host, their signals and writes park ([`crate::script_calls::defer_vm_split`]). + pub(crate) fn split(world: &World) -> Self { + Self(crate::script_calls::defer_vm_split(world)) + } + /// Run `leg`, then park what it signalled. pub(crate) fn leg(&mut self, world: &mut World, leg: impl FnOnce(&mut World)) { leg(world); @@ -106,7 +132,7 @@ impl Parked { if let Some((session, key)) = crate::script_calls::park_since(world, *mark) { let at = crate::lanes::stamp(); if let Some(mut lane) = world.get_resource_mut::() { - lane.0.push_back((at, session, key)); + lane.0.push_back((at, Item::Parked(session, key))); } } } @@ -118,26 +144,28 @@ fn peek_parked(world: &World) -> Option { .get_resource::()? .0 .front() - .map(|(at, ..)| *at) + .map(|(at, _)| *at) } -/// Each leg's signals `until` admits, run as the firing of their stamp with the host lent; the -/// lane stops after one whose firing stamped anything, so what it pushed fires next. It reads -/// nothing beside the host and its own lane. +/// Each item `until` admits, run as the firing of its stamp: a leg's signals with the host lent, +/// or a walk's next callbacks. The lane stops after one whose firing stamped anything, so what it +/// pushed fires next. fn fire_parked(In(until): In, world: &mut World) { loop { - let Some((at, session, key)) = world + let Some((at, item)) = world .resource::() .0 .front() .copied() - .filter(|(at, ..)| until.admits(*at)) + .filter(|(at, _)| until.admits(*at)) else { return; }; world.resource_mut::().0.pop_front(); - let ((), moved) = - crate::lanes::firing(at, || crate::script_calls::run_parked(world, session, key)); + let ((), moved) = crate::lanes::firing(at, || match item { + Item::Parked(session, key) => crate::script_calls::run_parked(world, session, key), + Item::Walk(entry, from) => crate::net::continue_refusal_walk(world, entry, from), + }); if moved { return; } @@ -152,7 +180,7 @@ pub(crate) fn fire_parked_lane(world: &mut World) { .resource::() .0 .front() - .is_some_and(|(at, ..)| Until::all().admits(*at)) + .is_some_and(|(at, _)| Until::all().admits(*at)) { world .run_system_cached_with(fire_parked, Until::all()) diff --git a/crates/benilla-app/src/field_watch.rs b/crates/benilla-app/src/field_watch.rs index 7596bc728..28facb090 100644 --- a/crates/benilla-app/src/field_watch.rs +++ b/crates/benilla-app/src/field_watch.rs @@ -18,10 +18,10 @@ //! type watchers `0x6041f0` and the player type watchers `0x5e2510` whose callbacks signal; the //! active player's `0x5de4b0`, rest-state, coinage and charmed-by watches registered in //! `0x5dd8a0`, its skill watches `0x5de180`, `0x5de450` and `0x5de470`, its ammunition watch -//! `0x4c70b0`, and the weapon arms of the visible-item watch `0x5e2810`. The item watchers' and the -//! inventory watcher's runs are [`crate::item_watch`]'s. +//! `0x4c70b0`, its explored-bytes watch `0x4a6460`, and the weapon arms of the visible-item watch +//! `0x5e2810`. The item watchers' and the inventory watcher's runs are [`crate::item_watch`]'s. -use benilla_protocol::messages::{ObjectType, PLAYER_QUEST_LOG_SLOTS}; +use benilla_protocol::messages::{quest_slot_state, ObjectType, PLAYER_QUEST_LOG_SLOTS}; use benilla_protocol::{ObjectFields, OwnerFallback}; use bevy::prelude::*; @@ -37,6 +37,17 @@ pub(crate) enum FieldNotice { /// Any other callback's own `0x515e50(guid, id)`: a type watcher's, a packet handler's or a /// cache answer's. It reaches every token naming `guid`, with no watcher of the unit's own. Signal { guid: u64, id: u16 }, + /// `RefreshTooltipForUnit` (`0x4919d0`) on a held unit: `GameTooltip`'s unit plate built + /// again while it still shows `guid`. `NotifyUnitNameUpdate` (`0x491a00`) runs it for a unit the + /// object manager holds (`0x491a1a`-`0x491a27`) ahead of its `UNIT_NAME_UPDATE`, from the name + /// and creature callbacks (`0x5fb875`, `0x6046d1`), the entry watcher (`0x604651`), the + /// `PLAYER_BYTES_3` watchers (`0x5e2a36`, `0x5e2a56`) and the party record's pet name + /// (`0x5e5873`); the unit-flags watcher runs it on the skinnable bit (`0x5ff7be`). + TooltipUnit { guid: u64 }, + /// `CGTooltip::OnCorpseOwnerName` (`0x52afe0`), which the corpse plate's name lookup registered + /// (`0x52af77`), on a found name: `GameTooltip`'s corpse plate built again while it keeps a + /// corpse (`0x52b004`-`0x52b022`). + CorpsePlate, /// A callback's `FrameScript_SignalEvent2(id, "%s", "player")`: `0x5de4b0` on the active /// player, the event its registration pushes as the argument (`0x5de4b3`, `0x5de4c1`); the /// ammunition watch's, the item slot path's and the ammo getters' record callback's @@ -60,6 +71,12 @@ pub(crate) enum FieldNotice { /// A callback's `FrameScript_SignalEvent(id)` (`0x703e50`): the event with no arguments, for /// every listener, whatever unit raised it. Global { id: u16 }, + /// The quest-slot watcher `0x5ddd80` on one of the active player's twenty quest-log entries, + /// registered in `0x5dd8a0`, for a slot that gained `quest_id`: a new id over none, or the + /// same id with its failed bit cleared (`0x5dde17`-`0x5dde34`). The update packet's handler + /// shows its accept line at its place ([`crate::ui_quest::lines`]), so this never reaches the + /// lane. + QuestAccepted { quest_id: u32 }, /// The quest log's watcher `0x4de4d0` on the active player, registered at world entry on the /// 0xf0 bytes at the player section's `+0x28` (`0x4de43b`-`0x4de456`): the rebuild and its /// `QUEST_LOG_UPDATE`. @@ -85,6 +102,10 @@ pub(crate) enum FieldNotice { /// (`0x4bc872`) and, for a player or our hunter's pet, `PET_UI_CLOSE` (`0x4bc907`); then /// `PET_BAR_UPDATE` every time (`0x4bc90c`). PetGuidSet { changed: bool, guid: u64 }, + /// `SMSG_PET_SPELLS`' derivation after its book's sort (`0x4bdae0` → + /// `DeriveUnresolvedBoundSpells 0x4f0ce0`): the macros that follow the pet's book bound again, + /// with nothing signalled ([`crate::ui_macro::derive_pet_followers`]). + PetMacros, /// `SMSG_LEVELUP_INFO`'s arm of the notice handler `0x5e38c0`: `PLAYER_LEVEL_UP` with the /// message's level, health, first power, `level >= 10` and five stats (`0x5e413e`). LevelUp(benilla_protocol::messages::LevelUpInfo), @@ -120,6 +141,15 @@ pub(crate) enum FieldNotice { /// The maximum's and the permanent bonus's watch `0x5de450`: the profession list's rebuild /// (`0x5de457`), then the skill list's (`0x5de45c`). SkillMax, + /// A spell packet's slot write, `0x4e58e0` from the unlearn's or the supersede's walk of the + /// bar ([`crate::ui_action::SpellSlots`]): the slot's usable pair recomputed (`0x4e5903`), + /// then `ACTIONBAR_SLOT_CHANGED` with the 1-based `action` (`0x4e5998`). + ActionSlotChanged { action: u32 }, + /// `NotifySpellSlots 0x4e5de0` from an aura handler of the active player's (`0x61237e`, + /// `0x612440`): each of the 120 slots in order that resolves to `spell` in the player's book + /// (`0x4e5a50`, book 0) has its usable pair recomputed and signals `ACTIONBAR_SLOT_CHANGED`, + /// with no send (`0x4e5e05`-`0x4e5e0b` into `0x4e58e0`). + SpellSlots { spell: u32 }, /// `0x4b25b0`'s live tail for a learned spell that entered the book: `LEARNED_SPELL_IN_TAB` /// (510) with its tab's 1-based place (`0x4b2b92`). LearnedInTab { tab: i64 }, @@ -152,6 +182,64 @@ pub(crate) enum FieldNotice { /// `AREA_SPIRIT_HEALER_OUT_OF_RANGE`. The packet's handler runs it at its place and writes /// the signal, so this never reaches the lane. AreaSpiritHealerClear, + /// `QueryCorpse 0x491f50` behind the ghost state, on either edge of the active player's ghost + /// bit (`0x5eeac1`): the corpse cache reset, the range latch out and, for a ghost, the corpse + /// query ([`crate::death::reset_corpse`]). The packet's handler runs it at its place and + /// writes the signal, so this never reaches the lane. + QueryCorpse, + /// `SMSG_PLAYED_TIME`'s handler `0x401850`, after its console lines: `TIME_PLAYED_MSG` with + /// the total and the level's time (`0x4018df`). + PlayedTime { total: u32, level: u32 }, + /// `SMSG_PLAYER_SKINNED`'s handler `0x5e7d40`: `PLAYER_SKINNED` with the byte's truth + /// (`0x5e7d57` → `0x48f412`). + Skinned { free_repop: bool }, + /// The guild recruitment cascade `0x49ea90` behind the active player's guild tag: its create's + /// `PostInit` (`0x5dec1e`) and its `PLAYER_GUILDID` watcher (`0x5e279a`), each right after the + /// tag's signals ([`guild_tag`]). It runs on AUTO alone, and arms the retry when it cannot act + /// ([`crate::ui_chat::GuildRecruitmentCascade`]). + RecruitmentCascade, + /// The explored bytes' watcher `0x4a6460` on the active player (`PLAYER_EXPLORED_ZONES`, 0x100 + /// bytes at the player section's `+0xe6c`, armed by `0x4a6430` in the world-enter cascade): + /// `0x4a6477` calls the map setter `0x4a67a0` over the map already shown. It reads the bytes + /// as the packet left them, rebuilds the overlays and the landmark list they gate and signals + /// `WORLD_MAP_UPDATE` (`0x4a6ce4`). + ExploredZones, + /// A group member's ping, `0x4ee330` from `MSG_MINIMAP_PING`'s handler (`0x5e41bd`): the + /// VM's statics store the point, then `MINIMAP_PING` with the token the packet resolved + /// (`0x4ee48d`). + MinimapPing(crate::minimap::MemberPing), + /// The health watcher's revive arm on the active player (`0x6047ee` → `0x5fef70`): every item + /// unlocked with its one `ITEM_LOCK_CHANGED` (`0x5fefae` → `0x495460`), then `PLAYER_ALIVE` + /// (274, `0x5fefb8`). + Revived, + /// A packet handler's `DisplayError(id)` (`0x496720`): the message row's line, by its + /// `GlobalStrings` key, shown at once. + Line { key: &'static str }, + /// A watcher's stop of the unit's auto-move, which the notify walk runs at its place when the + /// unit is the active mover, and which reaches the lane only as the `AUTOFOLLOW_END` it owes: + /// the taxi flag's rise on the active player (`0x5ff538`-`0x5ff55a`, `StopAutoMove(0, 1)`), and + /// the feign-death bit's rise (`0x6004f5`-`0x600530`), whose tick runs with `apply` clear, so + /// both its predicates fail (`0x51468d`, `0x5146a6`) and it stops (`0x5146d6`). + AutoMoveStop, + /// The active player's flags watcher's taxi arm, the flag's clear (`0x5ff538`-`0x5ff56e`): + /// the zone channels walked at the watcher's place, unless a cinematic runs (`0x5ff565`), with + /// the walk's tail ([`crate::ui_chat::TaxiWalk`]). + ZoneChannelWalk, + /// A follow's stop clearing autorun (`0x60fc08` → `0x514630` at `0x60e83f`), right behind its + /// `AUTOFOLLOW_END`, which `StopAutoMove` signals first (`0x60fb84`): it runs after that + /// event's listeners, so a toggle one of them made is undone + /// ([`crate::player::CallAutorun::clear`]). + AutorunClear, + /// The stun bit's flip on the active player (`0x5ff4ef`-`0x5ff501`): the mover's input tick + /// with `apply` set, which stops the auto-move when the unit may neither translate nor turn + /// (`0x5146c1`-`0x5146d6`). + InputTick, + /// The far-sight field's change to `object`, 0 for none (`0x5de0d0`): with the object held the + /// start (`0x5de144` → `0x5ee270`), whose update while far sight is off sends + /// `CMSG_FAR_SIGHT` 1, puts the view out and stops the auto-move, through the mover's tick + /// (`0x5ee4a2`) or a controlled unit's mover switch (`0x5ee477` → `0x600742`); else the end + /// (`0x5de15d` → `0x5ee590`). Both run ahead of the change's signal. + FarSight { object: u64 }, } /// The notice lane: each notice stamped as a handler writes it ([`crate::lanes::stamp`]), fired @@ -210,6 +298,7 @@ impl NoticeLane { } /// The notices waiting, in order. + #[cfg(test)] pub(crate) fn iter(&self) -> impl Iterator { self.0.iter().map(|(_, n)| n) } @@ -266,6 +355,7 @@ pub(crate) mod id { pub(crate) const TABARD_CANSAVE_CHANGED: u16 = 376; pub(crate) const MERCHANT_UPDATE: u16 = 317; pub(crate) const PLAYER_UNGHOST: u16 = 401; + pub(crate) const CORPSE_OUT_OF_RANGE: u16 = 399; pub(crate) const PLAYER_UPDATE_RESTING: u16 = 405; pub(crate) const PET_UI_UPDATE: u16 = 427; pub(crate) const PLAYTIME_CHANGED: u16 = 530; @@ -274,6 +364,10 @@ pub(crate) mod id { pub(crate) const PET_BAR_UPDATE: u16 = 353; pub(crate) const AREA_SPIRIT_HEALER_IN_RANGE: u16 = 527; pub(crate) const AREA_SPIRIT_HEALER_OUT_OF_RANGE: u16 = 528; + pub(crate) const PLAYER_CAMPING: u16 = 276; + pub(crate) const PLAYER_QUITING: u16 = 277; + pub(crate) const LOGOUT_CANCEL: u16 = 278; + pub(crate) const AUTOFOLLOW_END: u16 = 368; } /// `CGPlayer_C::RefreshGuildTag` (`0x5e08e0`) on the player `guid`: `TABARD_CANSAVE_CHANGED` bare @@ -379,6 +473,11 @@ const QUEST_SLOT_BYTES: u16 = 12; /// the player section's `+0xe48`, 8 bytes, registered at world entry (`0x4c6fce`, `0x4c6fd8`). const CHARACTER_POINTS: (u16, u16) = (0xe48, 8); +/// The active player's explored-bytes watch `0x4a6460`, `PLAYER_EXPLORED_ZONES_1` onward at the +/// player section's `+0xe6c`, 0x100 bytes (64 dwords), armed by `ClntObjMgrSetObjectMirrorHandler(4, +/// 0xe6c, player, 0x100, 0x4a6460)` in `0x4a6430`, from the world-enter cascade (`0x4908c0`). +const EXPLORED_ZONES: (u16, u16) = (0xe6c, 0x100); + /// The active player's ammunition watch `0x4c70b0`, `PLAYER_AMMO_ID` at the player section's /// `+0x102c`, registered at world entry (`0x4c6fea`, from `0x49097e`). const AMMO_ID: (u16, u16) = (0x102c, 4); @@ -447,6 +546,9 @@ const WEAPON_SLOTS: [u8; 3] = [15, 16, 17]; /// (`0x60441a`, `0x604b30` → `0x600440`); and in the object section `OBJECT_FIELD_ENTRY` /// (`0x60427d`, `0x604600`). const UNIT_FLAGS: (u16, u16) = (0xa0, 4); +/// `UNIT_FLAG_SKINNABLE`, `UNIT_FIELD_FLAGS` bit 26, which the unit tooltip's `UNIT_SKINNABLE` line +/// reads (`0x52a914`). +const UNIT_FLAG_SKINNABLE: u32 = 0x0400_0000; const FACTION_TEMPLATE: (u16, u16) = (0x74, 4); const OWNERS: (u16, u16) = (0x10, 0x10); const PERSUADED: (u16, u16) = (0x30, 8); @@ -656,6 +758,15 @@ impl Pass { } } + /// `NotifyUnitNameUpdate` (`0x491a00`) on the watched unit: the tooltip's refresh, then + /// `UNIT_NAME_UPDATE` (`0x491a3c`). + fn name_update(&mut self, at: Place, guid: u64) { + if guid != 0 { + self.push(at, FieldNotice::TooltipUnit { guid }); + } + self.signal(at, guid, id::UNIT_NAME_UPDATE); + } + /// `CGUnit_C::RefreshReaction` (`0x606e20`) on `guid`: `UNIT_FACTION` for it (`0x606e57`), /// for its `SUMMON` (`0x606e9d`) and its `CHARM` (`0x606edf`) when set, then, for the active /// player, for every other unit not its own (`0x606efb`). @@ -752,6 +863,17 @@ pub(crate) fn placed_values( // The unit type watchers (`0x6041f0`), on every unit. let mine = around.me == Some(guid); + // The health watcher's revive arm (`0x6047ee`-`0x6047f4`, a health of 0 or less rising above + // it) for the active player (`0x5fef9f`): `0x5fef70`'s unlock and `PLAYER_ALIVE`, ahead of the + // watcher's usable refresh. + if let Some(at) = at(UNIT_SECTION, HEALTH, List::Type).filter(|_| mine) { + let rose = block + .edge(UNIT_SECTION + HEALTH.0 / 4) + .is_some_and(|(old, new)| old as i32 <= 0 && new as i32 > 0); + if rose { + pass.push(at, FieldNotice::Revived); + } + } // The health's and the powers' for the active player (`0x60483c`, `0x604868`), the aura // state's for it or the target (`0x604898`-`0x6048b4`). for (range, runs) in [ @@ -774,7 +896,7 @@ pub(crate) fn placed_values( if let Some(at) = at(OBJECT_SECTION, ENTRY, List::Type) { // `0x604600`: a cached record names the unit at once (`0x604651`); a miss asks. if (around.creature_lookup)(fields.object_entry().unwrap_or(0)) { - pass.signal(at, guid, id::UNIT_NAME_UPDATE); + pass.name_update(at, guid); } } for range in [OWNERS, PERSUADED, FACTION_TEMPLATE] { @@ -786,6 +908,10 @@ pub(crate) fn placed_values( // `0x5ff580` on the flipped bits, against the new flags. let flipped = block.flipped(UNIT_SECTION + UNIT_FLAGS.0 / 4); let flags = fields.unit_flags(); + // The active player's arm opens on the stun bit's tick (`0x5ff4ef`-`0x5ff501`). + if mine && flipped & crate::player::UNIT_FLAG_STUNNED != 0 { + pass.push(at, FieldNotice::InputTick); + } // The active player's arm first (`0x5ff5b4`, `0x5ff5c7` → `0x5ff4e0`): a usable refresh // on bits 0x1c20000 (`0x5ff50e`), then the in-combat bit 0x80000's own (`0x5ff51b`) and // `PLAYER_REGEN_DISABLED` when now set, else `PLAYER_REGEN_ENABLED` (`0x5ff513`- @@ -802,6 +928,16 @@ pub(crate) fn placed_values( }; pass.push(at, FieldNotice::Global { id }); } + // Last in the active player's arm, the taxi flag's edge (`0x5ff538`): its rise stops the + // auto-move (`0x5ff55a`), its clear walks the zone channels (`0x5ff565`-`0x5ff56e`). + if mine && flipped & crate::player::UNIT_FLAG_TAXI_FLIGHT != 0 { + let notice = if flags & crate::player::UNIT_FLAG_TAXI_FLIGHT != 0 { + FieldNotice::AutoMoveStop + } else { + FieldNotice::ZoneChannelWalk + }; + pass.push(at, notice); + } // The reaction on 0x4080 (`0x5ff71c`) and again on 0x1000 (`0x5ff72b`). if flipped & 0x4080 != 0 { pass.reaction(at, guid, fields, around); @@ -831,6 +967,10 @@ pub(crate) fn placed_values( }; pass.push(at, FieldNotice::Global { id }); } + // The tooltip's refresh on the skinnable bit 0x4000000 (`0x5ff7a4`-`0x5ff7be`). + if flipped & UNIT_FLAG_SKINNABLE != 0 { + pass.push(at, FieldNotice::TooltipUnit { guid }); + } // `UNIT_AURA` on 0x8000000 (`0x5ff7e2`). if flipped & 0x0800_0000 != 0 { pass.signal(at, guid, id::UNIT_AURA); @@ -846,13 +986,25 @@ pub(crate) fn placed_values( } } if let Some(at) = at(UNIT_SECTION, DYNAMIC_FLAGS, List::Type) { - // `0x600440` on the flipped bits: 0x20, the dead look, signals `UNIT_HEALTH` and the power + // `0x600440` on the flipped bits: first 0x1, the lootable bit, whose rise triggers Looting + // (`0x600482`-`0x60049b`); then 0x20, the dead look, signals `UNIT_HEALTH` and the power // event of `UNIT_FIELD_BYTES_0` byte 3 (`0x6004cd`, `0x6004f0`); 0x4, the tap, // `UNIT_FACTION` (`0x6005bb`). - let flipped = block.flipped(UNIT_SECTION + DYNAMIC_FLAGS.0 / 4); + let (old, new) = block + .edge(UNIT_SECTION + DYNAMIC_FLAGS.0 / 4) + .unwrap_or_default(); + if old & 0x1 == 0 && new & 0x1 != 0 { + let id = tutorial::LOOTING; + pass.push(at, FieldNotice::Tutorial { id }); + } + let flipped = old ^ new; if flipped & 0x20 != 0 { pass.signal(at, guid, id::UNIT_HEALTH); pass.signal(at, guid, id::POWER + u16::from(fields.unit_power_type())); + // Now set, the active mover's tick runs with `apply` clear (`0x600501`-`0x600530`). + if new & 0x20 != 0 { + pass.push(at, FieldNotice::AutoMoveStop); + } } if flipped & 0x4 != 0 { pass.signal(at, guid, id::UNIT_FACTION); @@ -900,7 +1052,7 @@ pub(crate) fn placed_values( let flags = fields.player_flags(); // 0x10, the ghost state (`0x5eeab4` → `0x5de9c0`) on either edge: set, its // tutorial (`0x5de9eb`-`0x5de9f0`); clear, the healer's clear (`0x5dea20`), then - // `PLAYER_UNGHOST` (`0x5dea2a`). + // `PLAYER_UNGHOST` (`0x5dea2a`). Then the corpse query (`0x5eeac1` → `0x491f50`). if flipped & 0x10 != 0 { if flags & 0x10 != 0 { pass.push( @@ -914,6 +1066,7 @@ pub(crate) fn placed_values( let id = id::PLAYER_UNGHOST; pass.push(at, FieldNotice::Global { id }); } + pass.push(at, FieldNotice::QueryCorpse); } // 0x20, resting: the rest tutorial when now set (`0x5eeae6`-`0x5eeaed`), then // `PLAYER_UPDATE_RESTING` on either edge (`0x5eead0`, `0x5eeaf2`). @@ -942,10 +1095,14 @@ pub(crate) fn placed_values( } } if let Some(at) = at(PLAYER_SECTION, GUILD_ID, List::Type) { - // `0x5e2770`: the player's guild tag (`0x5e2795`). + // `0x5e2770`: the player's guild tag (`0x5e2795`), then the recruitment cascade + // (`0x5e279a`), ours alone (the module's deviation in `crate::ui_chat`). for notice in guild_tag(guid) { pass.push(at, notice); } + if around.me == Some(guid) { + pass.push(at, FieldNotice::RecruitmentCascade); + } } if let Some(at) = at(PLAYER_SECTION, GUILD_RANK, List::Type) { // `0x5e27b0`: `PLAYER_GUILD_UPDATE` bare (`0x5e27b5`). @@ -953,10 +1110,10 @@ pub(crate) fn placed_values( pass.push(at, FieldNotice::Global { id }); } if let Some(at) = at(PLAYER_SECTION, BYTES_3_BYTE_2, List::Type) { - pass.signal(at, guid, id::UNIT_NAME_UPDATE); + pass.name_update(at, guid); } if let Some(at) = at(PLAYER_SECTION, BYTES_3_BYTE_3, List::Type) { - pass.signal(at, guid, id::UNIT_NAME_UPDATE); + pass.name_update(at, guid); pass.reaction(at, guid, fields, around); } if let Some(at) = at(PLAYER_SECTION, BYTES_3_BYTE_1, List::Type) { @@ -995,26 +1152,42 @@ pub(crate) fn placed_values( pass.push(at, FieldNotice::UsableRefresh); pass.push(at, FieldNotice::ComboPoints); } - // `0x5de0d0`: the far-sight update, then `PLAYER_FARSIGHT_FOCUS_CHANGED` bare on every - // change, whether or not the new guid resolves (`0x5de14e`, `0x5de167`). + // `0x5de0d0`: the far-sight start or end, then `PLAYER_FARSIGHT_FOCUS_CHANGED` bare on + // every change, whether or not the new guid resolves (`0x5de14e`, `0x5de167`). if let Some(at) = at(PLAYER_SECTION, FARSIGHT, List::Object) { + let object = fields.player_farsight().unwrap_or(0); + pass.push(at, FieldNotice::FarSight { object }); let id = id::PLAYER_FARSIGHT_FOCUS_CHANGED; pass.push(at, FieldNotice::Global { id }); } // The slot watchers `0x5ddd80`, one 12-byte watch a quest slot (`0x5dd974`-`0x5dd99e`), - // registered on the active player's arrival (`0x5dd8a0`): each run ends in the quest-list - // rebuild `0x4e8be0` (`0x5dde98`), which signals `UPDATE_LFG_TYPES` (`0x4e8c70`). One run - // per slot that moved, ahead of the log's own watcher below. + // registered on the active player's arrival (`0x5dd8a0`), ahead of the log's own watcher + // below. Each compares its slot against the copy its packet's write took (`0x5dde14`, + // `[ebx+0x10]`), the id and the state byte (`+0x7`): a quest gained shows its accept line + // (`0x5dde66`); then the run ends in the quest-list rebuild `0x4e8be0` (`0x5dde98`), which + // signals `UPDATE_LFG_TYPES` (`0x4e8c70`). One run per slot that moved. for slot in 0..u16::from(PLAYER_QUEST_LOG_SLOTS) { let slot_watch = ( QUEST_LOG_WATCH.0 + QUEST_SLOT_BYTES * slot, QUEST_SLOT_BYTES, ); - if let Some((fired, _, list)) = at(PLAYER_SECTION, slot_watch, List::Object) { - let first = PLAYER_SECTION + QUEST_LOG_WATCH.0 / 4; - let id = id::UPDATE_LFG_TYPES; - pass.push((fired, first, list), FieldNotice::Global { id }); + let Some((fired, _, list)) = at(PLAYER_SECTION, slot_watch, List::Object) else { + continue; + }; + let place = (fired, PLAYER_SECTION + QUEST_LOG_WATCH.0 / 4, list); + if let Some(now) = fields.player_quest_log(slot as u8) { + let id_field = PLAYER_SECTION + slot_watch.0 / 4; + let was = |field: u16, now: u32| block.edge(field).map_or(now, |(old, _)| old); + let (id, was_id) = (now.quest_id, was(id_field, now.quest_id)); + let fail = now.state & quest_slot_state::FAIL != 0; + let was_state = was(id_field + 1, u32::from(now.state) << 24) >> 24; + let was_fail = was_state as u8 & quest_slot_state::FAIL != 0; + if id != 0 && (was_id == 0 || (was_id == id && !fail && was_fail)) { + pass.push(place, FieldNotice::QuestAccepted { quest_id: id }); + } } + let id = id::UPDATE_LFG_TYPES; + pass.push(place, FieldNotice::Global { id }); } // Registered at world entry (`0x4de430`), after the bridge's watch on the same range and // the slot watchers. @@ -1074,6 +1247,10 @@ pub(crate) fn placed_values( }, ); } + // `0x4a6460`: the map setter over the shown map, which signals `WORLD_MAP_UPDATE`. + if let Some(at) = at(PLAYER_SECTION, EXPLORED_ZONES, List::Object) { + pass.push(at, FieldNotice::ExploredZones); + } // `0x4c70b0` sets the ammunition model (`0x4c70fc`, not built) and signals (`0x4c7110`). if let Some(at) = at(PLAYER_SECTION, AMMO_ID, List::Object) { let id = id::UNIT_INVENTORY_CHANGED; @@ -1227,6 +1404,71 @@ mod tests { PLAYER_SECTION + offset / 4 } + /// The quest-slot watcher `0x5ddd80`, one 12-byte watch a slot (`0x5dd990`), against the copy + /// (`0x5dde14`): a quest in a slot that held none, or the same quest with its failed bit + /// cleared (`0x5dde17`-`0x5dde34`); a kept quest, a kept failure, a slot swapping quests and a + /// cleared slot announce nothing. It runs ahead of the log's watcher, which world entry + /// registered after it (`0x4de430`), its line ahead of its rebuild's `UPDATE_LFG_TYPES`. + #[test] + fn the_quest_slot_watcher_announces_a_filled_slot_and_a_cleared_failure_only() { + let accepted = |notices: &[FieldNotice]| -> Vec { + notices + .iter() + .filter_map(|n| match n { + FieldNotice::QuestAccepted { quest_id } => Some(*quest_id), + _ => None, + }) + .collect() + }; + let slot = |k: u16| pf(0x28 + 12 * k); + let failed = 2u32 << 24; + let mut me = player(); + let prior = [ + (slot(1), 7), + (slot(2), 8), + (slot(2) + 1, failed), + (slot(3), 9), + (slot(3) + 1, failed), + (slot(4), 10), + (slot(5), 11), + ]; + assert_eq!( + accepted(&block(&mut me, Some(ME), ME, &prior)), + [7, 8, 9, 10, 11] + ); + let now = [ + (slot(0), 783), + (slot(2) + 1, 0), + (slot(3) + 1, failed | 1), + (slot(4), 12), + (slot(5), 0), + ]; + assert_eq!(accepted(&block(&mut me, Some(ME), ME, &now)), [783, 8]); + let lfg = FieldNotice::Global { + id: id::UPDATE_LFG_TYPES, + }; + assert_eq!( + block(&mut me, Some(ME), ME, &[(slot(0), 0)]), + [ + bridge(ME, id::UNIT_QUEST_LOG_CHANGED), + lfg, + FieldNotice::QuestLog + ], + "a cleared slot" + ); + assert_eq!( + block(&mut me, Some(ME), ME, &[(slot(0), 50)]), + [ + bridge(ME, id::UNIT_QUEST_LOG_CHANGED), + FieldNotice::QuestAccepted { quest_id: 50 }, + lfg, + FieldNotice::QuestLog + ] + ); + let mut other = player(); + assert!(accepted(&block(&mut other, Some(ME), OTHER, &[(slot(0), 50)])).is_empty()); + } + /// The bridge's event id names the field `id + 6`; each moved field is one notice, in field /// order, and an equal rewrite runs nothing. #[test] @@ -1373,7 +1615,9 @@ mod tests { assert_eq!( block(&mut other, Some(ME), OTHER, &[(bytes_3, 0x0102_0001)]), [ + tooltip(OTHER), signal(OTHER, id::UNIT_NAME_UPDATE), + tooltip(OTHER), signal(OTHER, id::UNIT_NAME_UPDATE), signal(OTHER, id::UNIT_FACTION), FieldNotice::Drunk { @@ -1666,6 +1910,11 @@ mod tests { FieldNotice::Signal { guid, id } } + /// `0x4919d0` on `guid`, the tooltip's refresh ahead of a name signal. + fn tooltip(guid: u64) -> FieldNotice { + FieldNotice::TooltipUnit { guid } + } + fn bridge(guid: u64, id: u16) -> FieldNotice { FieldNotice::Unit { guid, id } } @@ -1779,15 +2028,21 @@ mod tests { ); } - /// `0x600440`: the dead look signals the health and the power of the unit's power type, the - /// tap `UNIT_FACTION`, any other bit nothing of its own; the bridge follows. + /// `0x600440`: the dead look signals the health and the power of the unit's power type, then + /// on its rise stops the auto-move of a unit that is the active mover; the tap `UNIT_FACTION`, + /// any other bit nothing of its own; the bridge follows. #[test] fn the_dynamic_flags_watcher_signals_on_its_two_bits() { // Rage: `UNIT_FIELD_BYTES_0` byte 3 is 1. let mut mob = ObjectFields::from_pairs(&[(36, 1 << 24)]).into_created(ObjectType::Unit); assert_eq!( block(&mut mob, Some(ME), MOB, &[(143, 0x20)]), - [signal(MOB, 16), signal(MOB, 18), bridge(MOB, 137)] + [ + signal(MOB, 16), + signal(MOB, 18), + FieldNotice::AutoMoveStop, + bridge(MOB, 137) + ] ); assert_eq!( block(&mut mob, Some(ME), MOB, &[(143, 0x24)]), @@ -1799,6 +2054,37 @@ mod tests { ); } + /// `0x600440`'s first leg: the lootable bit's rise triggers Looting (`0x600482`-`0x60049b`), + /// ahead of the dead look's signals; its fall triggers nothing, and a rise again asks again, + /// for the fire-once bank to gate. + #[test] + fn the_lootable_bits_rise_triggers_looting_ahead_of_the_dead_look() { + let looting = FieldNotice::Tutorial { + id: crate::tutorial::id::LOOTING, + }; + let mut mob = ObjectFields::from_pairs(&[(36, 1 << 24)]).into_created(ObjectType::Unit); + assert_eq!( + block(&mut mob, Some(ME), MOB, &[(143, 0x21)]), + [ + looting, + signal(MOB, 16), + signal(MOB, 18), + FieldNotice::AutoMoveStop, + bridge(MOB, 137) + ] + ); + assert_eq!( + block(&mut mob, Some(ME), MOB, &[(143, 0x20)]), + [bridge(MOB, 137)], + "the fall" + ); + assert_eq!( + block(&mut mob, Some(ME), MOB, &[(143, 0x21)]), + [looting, bridge(MOB, 137)], + "a rise again" + ); + } + /// Every player's flags signal `PLAYER_FLAGS_CHANGED` on any bit, after the reaction 0x180 /// runs; `PLAYER_BYTES_3` bytes 2 and 3 name the player, byte 3 refreshing its reaction too, /// ahead of the active player's own rank watch on the same dword. @@ -1815,12 +2101,16 @@ mod tests { ); assert_eq!( block(&mut other, Some(ME), OTHER, &[(195, 0x0100_0000)]), - [signal(OTHER, 183), signal(OTHER, 29)] + [tooltip(OTHER), signal(OTHER, 183), signal(OTHER, 29)] ); let mut me = player(); assert_eq!( block(&mut me, Some(ME), ME, &[(195, 0x0001_0000)]), - [signal(ME, 183), FieldNotice::Player { id: 524 }] + [ + tooltip(ME), + signal(ME, 183), + FieldNotice::Player { id: 524 } + ] ); // The duel team. assert_eq!( @@ -1846,8 +2136,9 @@ mod tests { /// The active player's log carries the quest log's own watcher (`0x4de430`, registered after /// the bridge's on the same 0xf0 bytes): one run a block, however many slots moved, and none - /// for an equal rewrite. Each slot that moved also runs its own watcher `0x5ddd80`, whose - /// quest-list rebuild signals `UPDATE_LFG_TYPES` (`0x5dde98` → `0x4e8c70`), ahead of the log's. + /// for an equal rewrite. Each slot that moved also runs its own watcher `0x5ddd80`: a quest + /// gained shows its accept line, then its quest-list rebuild signals `UPDATE_LFG_TYPES` + /// (`0x5dde98` → `0x4e8c70`), ahead of the log's. #[test] fn the_active_players_quest_log_watcher_runs_once_per_block() { let mut me = player(); @@ -1864,7 +2155,15 @@ mod tests { ME, &[(198, 5), (199, 3), (201, 7), (257, 1)] ), - [bridge(ME, 522), lfg, FieldNotice::QuestLog, lfg, lfg] + [ + bridge(ME, 522), + FieldNotice::QuestAccepted { quest_id: 5 }, + lfg, + FieldNotice::QuestLog, + FieldNotice::QuestAccepted { quest_id: 7 }, + lfg, + lfg, + ] ); assert!(block(&mut me, Some(ME), ME, &[(198, 5), (201, 7)]).is_empty()); } @@ -1880,7 +2179,12 @@ mod tests { let mut me = player(); assert_eq!( block(&mut me, Some(ME), ME, &[(198, 5), (199, 3), (200, 9)]), - [bridge(ME, 522), lfg, FieldNotice::QuestLog] + [ + bridge(ME, 522), + FieldNotice::QuestAccepted { quest_id: 5 }, + lfg, + FieldNotice::QuestLog + ] ); // The slot's counter word alone is a change of the slot. assert_eq!( @@ -1913,7 +2217,7 @@ mod tests { }; assert_eq!( block_around(&mut mob, &cached, MOB, &[(3, 299)]), - [signal(MOB, 183)] + [tooltip(MOB), signal(MOB, 183)] ); assert!(block_around(&mut mob, &cached, MOB, &[(3, 300)]).is_empty()); } @@ -1999,7 +2303,8 @@ mod tests { /// `0x5ee990`'s ghost arm runs the ghost state `0x5de9c0` on either edge of bit 0x10 /// (`0x5eeab4` → `0x5eeabc`), after `PLAYER_FLAGS_CHANGED` (`0x5eea35`): set, its tutorial /// (`0x5de9eb`-`0x5de9f0`); clear, the healer's clear (`0x5dea20`) and `PLAYER_UNGHOST` - /// (`0x5dea25`-`0x5dea2a`), with no gate before them, so the health plays no part. Another player's ghost bit reaches neither. + /// (`0x5dea25`-`0x5dea2a`), with no gate before them, so the health plays no part; then, on + /// either edge, the corpse query (`0x5eeac1`). Another player's ghost bit reaches neither. #[test] fn the_ghost_bit_runs_the_ghost_state_on_either_edge() { let flags = pf(PLAYER_FLAGS.0); @@ -2007,14 +2312,19 @@ mod tests { let mut me = player(); assert_eq!( block(&mut me, Some(ME), ME, &[(flags, 0x10)]), - [changed, FieldNotice::Tutorial { id: 0x18 }] + [ + changed, + FieldNotice::Tutorial { id: 0x18 }, + FieldNotice::QueryCorpse + ] ); assert_eq!( block(&mut me, Some(ME), ME, &[(flags, 0)]), [ changed, FieldNotice::AreaSpiritHealerClear, - FieldNotice::Global { id: 401 } + FieldNotice::Global { id: 401 }, + FieldNotice::QueryCorpse ], "with no health in the store" ); @@ -2126,14 +2436,15 @@ mod tests { ); assert_eq!( block(&mut me, Some(ME), ME, &[(flags, 0x10)]), - [changed, tutorial(0x18)] + [changed, tutorial(0x18), FieldNotice::QueryCorpse] ); assert_eq!( block(&mut me, Some(ME), ME, &[(flags, 0)]), [ changed, FieldNotice::AreaSpiritHealerClear, - FieldNotice::Global { id: 401 } + FieldNotice::Global { id: 401 }, + FieldNotice::QueryCorpse ], "the ghost bit's clear runs the ghost state too, its event and no tutorial" ); @@ -2168,7 +2479,8 @@ mod tests { ); } - /// `PLAYER_GUILDID` runs the guild tag on any player (`0x5e2770`), `PLAYER_GUILDRANK` signals + /// `PLAYER_GUILDID` runs the guild tag on any player (`0x5e2770`), and on the active player + /// the recruitment cascade behind it (`0x5e279a`); `PLAYER_GUILDRANK` signals /// `PLAYER_GUILD_UPDATE` bare (`0x5e27b0`). #[test] fn the_guild_watchers_reach_every_player() { @@ -2192,6 +2504,7 @@ mod tests { [ FieldNotice::Global { id: 376 }, signal(ME, 345), + FieldNotice::RecruitmentCascade, FieldNotice::Global { id: 345 } ] ); @@ -2269,8 +2582,13 @@ mod tests { let mut me = player(); assert_eq!( block(&mut me, Some(ME), ME, &[(22, 90)]), + [FieldNotice::Revived, R, bridge(ME, 16)], + "the health, out of none: the revive arm runs first (`0x6047ee`)" + ); + assert_eq!( + block(&mut me, Some(ME), ME, &[(22, 80)]), [R, bridge(ME, 16)], - "the health" + "the health, alive" ); assert_eq!( block(&mut me, Some(ME), ME, &[(23, 480)]), diff --git a/crates/benilla-app/src/game_plugins.rs b/crates/benilla-app/src/game_plugins.rs index 175bf92aa..5beb08223 100644 --- a/crates/benilla-app/src/game_plugins.rs +++ b/crates/benilla-app/src/game_plugins.rs @@ -47,7 +47,6 @@ use crate::ui_chat::UiChatPlugin; use crate::ui_craft::UiCraftPlugin; use crate::ui_dialog_verbs::UiDialogVerbsPlugin; use crate::ui_duel::UiDuelPlugin; -use crate::ui_follow::UiFollowPlugin; use crate::ui_gm_ticket::UiGmTicketPlugin; use crate::ui_gossip::UiGossipPlugin; use crate::ui_guild::UiGuildPlugin; @@ -176,7 +175,6 @@ impl PluginGroup for GamePlugins { .add(crate::swing_refusal::SwingRefusalPlugin) .add(UiSummonPlugin) .add(UiGmTicketPlugin) - .add(UiFollowPlugin) .add(UiInstancePlugin) .add(crate::ui_billing::UiBillingPlugin) .add(crate::ui_memory::UiMemoryPlugin) @@ -379,25 +377,21 @@ pub(crate) mod schedule_tests { self.components.get(&id).map(String::as_str).unwrap_or("?") } - /// Whether what `a` queues has applied by the time `b` runs: a sync point of the build - /// lies on a path from `a` to `b`, so it runs after `a` and before `b`, and applies every - /// buffer of a system that ran before it. Reads a [`SyncPoints::Built`] census. - pub fn applies_before(&self, a: SystemKey, b: SystemKey) -> bool { + /// Whether the build runs `a` before `b`: a path of its order leads from `a` to `b`. + pub fn runs_before(&self, a: SystemKey, b: SystemKey) -> bool { let mut next: HashMap> = HashMap::new(); for (x, y) in &self.built { next.entry(*x).or_default().push(*y); } - // Each node at most twice: before a sync point and past one. - let mut seen: HashSet<(SystemKey, bool)> = HashSet::new(); - let mut stack = vec![(a, false)]; - while let Some((n, synced)) = stack.pop() { + let mut seen: HashSet = HashSet::new(); + let mut stack = vec![a]; + while let Some(n) = stack.pop() { for m in next.get(&n).into_iter().flatten() { - let synced = synced || is_sync_point(self.name(*m)); - if *m == b && synced { + if *m == b { return true; } - if seen.insert((*m, synced)) { - stack.push((*m, synced)); + if seen.insert(*m) { + stack.push(*m); } } } @@ -767,7 +761,7 @@ pub(crate) mod schedule_tests { /// - A pure cache, where a miss records itself (`NameCache`, the GameObject templates, the /// page texts, `WorldAssets`, `Creatures`' display models): two misses for one key commute. /// A cache that is also a window's state is not pure, and not here. - /// - An append-only sink (`ChatLog`, `MessageSounds`, `UiErrorKeys`, `UiErrorTexts`): + /// - An append-only sink (`ChatLog`, `MessageSounds`, `UiErrorKeys`): /// writers commute, and a drain's order against a writer is one frame of latency. /// - A random stream (`SoundKits`, `AnimRng`): any interleaving of draws is a valid draw, /// the reference's contract for its single stream. @@ -801,7 +795,6 @@ pub(crate) mod schedule_tests { ("ChatLog", TypeId::of::), ("MessageSounds", TypeId::of::), ("UiErrorKeys", TypeId::of::), - ("UiErrorTexts", TypeId::of::), ]; const STREAMS: &[ClassRow] = &[ ("SoundKits", TypeId::of::), @@ -884,7 +877,7 @@ pub(crate) mod schedule_tests { #[test] fn the_worldport_sweep_is_not_gated_on_the_interface() { let mut app = headless_client(); - let update = census(&mut app, Update, SyncPoints::Built); + let update = census(&mut app, PreUpdate, SyncPoints::Built); if !type_names_available(&update) { eprintln!( "skipped: this build carries no type names (bevy/debug rides with the dev feature)" @@ -895,7 +888,7 @@ pub(crate) mod schedule_tests { .systems .values() .find(|s| s.name.ends_with("::sweep_on_worldport")) - .expect("the worldport's sweep is in Update"); + .expect("the worldport's sweep is in PreUpdate"); assert!( !sweep .conditions @@ -971,7 +964,7 @@ pub(crate) mod schedule_tests { /// Raising the ceiling is a claim that a new undeclared order is acceptable: make it with the /// reason read off the dump, or declare the order (`.after`, a set, a `chain`). A resource /// that commutes by construction belongs in [`Classes`]. - const UPDATE_ACTIONABLE_CEILING: usize = 1_731; + const UPDATE_ACTIONABLE_CEILING: usize = 1_467; const UPDATE_ACTIONABLE_SLACK: usize = 40; fn ratchet(what: &str, n: usize, ceiling: usize, slack: usize) { @@ -1077,15 +1070,17 @@ pub(crate) mod schedule_tests { /// on the dev build, whose schedule holds every system the player build does. Raised from 54 /// when the frame's input records moved ahead of the net drain: what their handlers queue /// applies before the drain, as the reference's input acts inside its handlers; to 57 for the - /// input's CVar sync, whose observers must run before the look session reads their knobs; and + /// input's CVar sync, whose callbacks must run before the look session reads their knobs; and /// to 58 on the movie frame (#2398): `movie::upload_movie_pictures` runs after /// `video::apply_present_mode` and `video::apply_window_mode` and before `paint_script`, which /// puts the barrier between `video::drain_restart_gx` and those two applies on the paint's path - /// (its commands fire the `gx*` CVar events whose observer writes the `VideoConfig` they read). + /// (its commands fired the `gx*` CVar events whose callback writes the `VideoConfig` they read). /// Without those two edges the count is 57. Lowered to 54 when the click's dispatchers queued /// their window opens as unit edits, the call host applying the world click inside its call. - /// `WOW_SYNC_DUMP=1` lists each barrier's neighbours. - const UPDATE_SYNC_POINT_CEILING: usize = 54; + /// Lowered to 46 when the CVar callbacks ran in place, inside the call or the sync that takes + /// the write, where their events had waited for a barrier. `WOW_SYNC_DUMP=1` lists each + /// barrier's neighbours. + const UPDATE_SYNC_POINT_CEILING: usize = 46; const UPDATE_SYNC_POINT_SLACK: usize = 4; #[test] @@ -1338,11 +1333,6 @@ pub(crate) mod schedule_tests { lanes' drain, which fires the tick's packets' signals (`0x420d55`), and ahead of the \ `OnUpdate` walk (`0x420d6a`)", ), - ( - "::ui_unit::views::mark_frame_start", - "a debug snapshot of what the frame starts from, ahead of the net stage by design: it \ - reads the units the resolver's last inputs name and pushes nothing", - ), ]; /// The create's control restore (`player::regain_control_on_arrival`) runs inside the net @@ -1387,8 +1377,6 @@ pub(crate) mod schedule_tests { "::player::controller::control", // The drain, which fires the notices the restore signals. "::lanes::fire_in_order", - "::ui_action::state::feed_action_state", - "::player::camera_saved::load_camera_pose", "::tutorial::watch_self", "::poi_marker::expire_marker", "::glue_session::logout_smoke::debug_logout_smoke", @@ -1398,63 +1386,18 @@ pub(crate) mod schedule_tests { "`{reader}` runs after the control restore" ); } - } - - /// A nameplate's right-click is `SelectTarget` (`0x492870`), which with a targeting cursor up - /// binds the cast and returns, and then the unit's interact (`0x492881`), so the cast goes out - /// ahead of what the interact does. The click's select parks the unit; the target chain's bind - /// gives it to the cast; the interact runs after that, or its attack leg would swing before the - /// cast and select nothing. - #[test] - fn a_plates_interact_runs_after_the_bind_of_the_unit_its_click_parked() { - let mut app = headless_client(); - let c = census( - &mut app, - crate::target::WorldClickLegs, - SyncPoints::Declared, - ); - if !type_names_available(&c) { - eprintln!( - "skipped: this build carries no type names (bevy/debug rides with the dev feature)" + // The camera pose loads ahead of the frame's input records and packets, as the reference + // reads its file at the interface load (`0x481b4e` → `0x50c0e0`), before any listener. + let pose = reach(one("::player::camera_saved::load_camera_pose")); + for later in [ + "::ui_script::input::dispatch_input_records", + "::net::apply::apply_net_updates", + ] { + assert!( + pose.contains(&one(later)), + "the camera pose loads ahead of `{later}`" ); - return; } - let one = |suffix: &str| { - let mut hits = c.systems.iter().filter(|(_, s)| s.name.ends_with(suffix)); - match (hits.next(), hits.next()) { - (Some((k, _)), None) => *k, - _ => panic!("exactly one system named `…{suffix}` in the click's legs"), - } - }; - let (select, bind, interact) = ( - one("::target::click::select_on_plate_click"), - one("::script_calls::bind_parked_picks"), - one("::target::click::act_on_interact"), - ); - let mut succ: HashMap> = HashMap::new(); - for (a, b) in &c.dependencies { - succ.entry(*a).or_default().push(*b); - } - let runs_before = |from: SystemKey, to: SystemKey| { - let mut seen = HashSet::new(); - let mut stack = vec![from]; - while let Some(n) = stack.pop() { - for m in succ.get(&n).into_iter().flatten() { - if seen.insert(*m) { - stack.push(*m); - } - } - } - seen.contains(&to) - }; - assert!( - runs_before(select, bind), - "the click parks before the chain binds" - ); - assert!( - runs_before(bind, interact), - "the interact runs after the chain's bind" - ); } /// A command press cancels the cast inside `SetCommands` (`0x51512a` → `0x6e4940`), after the @@ -1503,50 +1446,6 @@ pub(crate) mod schedule_tests { assert!(after(cancel).contains(&tick), "the cancel before the tick"); } - /// A plate click's trade leg runs ahead of its select (`0x4925d0`: the trade request at - /// `0x49278e`, `SelectTarget` at `0x49280c`), so the targeting cursor it tests (`0x492668`) - /// is the one the click found, not what the select's bind left. - #[test] - fn a_plate_clicks_trade_leg_runs_before_its_select() { - let mut app = headless_client(); - let c = census( - &mut app, - crate::target::WorldClickLegs, - SyncPoints::Declared, - ); - if !type_names_available(&c) { - eprintln!( - "skipped: this build carries no type names (bevy/debug rides with the dev feature)" - ); - return; - } - let one = |suffix: &str| { - let mut hits = c.systems.iter().filter(|(_, s)| s.name.ends_with(suffix)); - match (hits.next(), hits.next()) { - (Some((k, _)), None) => *k, - _ => panic!("exactly one system named `…{suffix}` in the click's legs"), - } - }; - let trade = one("::ui_action::drop_item::trade_on_plate_click"); - let mut succ: HashMap> = HashMap::new(); - for (a, b) in &c.dependencies { - succ.entry(*a).or_default().push(*b); - } - let mut seen = HashSet::new(); - let mut stack = vec![trade]; - while let Some(n) = stack.pop() { - for m in succ.get(&n).into_iter().flatten() { - if seen.insert(*m) { - stack.push(*m); - } - } - } - assert!( - seen.contains(&one("::target::click::select_on_plate_click")), - "the trade leg runs before the plate's select" - ); - } - /// The `Startup` VM, the stock glue's, is built after the glyph cache: /// its first screen sizes frames by measured text in the show (`TOSFrameHeader` off /// `TOSFrameTitle:GetWidth()`, `AccountLogin.lua`), which with no cache measures 0. @@ -1630,95 +1529,6 @@ pub(crate) mod schedule_tests { assert!(seen.contains(&watch), "the show runs before the callback"); } - /// The party feed fires `RAID_TARGET_UPDATE` after the unit feed has pushed this frame's - /// snapshots: TargetFrame answers it with `GetRaidTargetIndex("target")`, which reads the - /// target snapshot's `raid_target`, so a party feed that ran first left a new mark off the - /// target frame until the target changed. Read off the declared graph. - #[test] - fn the_party_feed_runs_after_the_unit_snapshots() { - let mut app = headless_client(); - let c = census(&mut app, Update, SyncPoints::Declared); - if !type_names_available(&c) { - eprintln!( - "skipped: this build carries no type names (bevy/debug rides with the dev feature)" - ); - return; - } - let one = |suffix: &str| -> SystemKey { - let mut hits = c.systems.iter().filter(|(_, s)| s.name.ends_with(suffix)); - match (hits.next(), hits.next()) { - (Some((k, _)), None) => *k, - _ => panic!("exactly one system named `…{suffix}` in Update"), - } - }; - let mut succ: HashMap> = HashMap::new(); - for (a, b) in &c.dependencies { - succ.entry(*a).or_default().push(*b); - } - let (units, party) = ( - one("::ui_unit::feed_units"), - one("::ui_party::feed::feed_party"), - ); - let mut seen = HashSet::new(); - let mut stack = vec![units]; - while let Some(n) = stack.pop() { - for m in succ.get(&n).into_iter().flatten() { - if seen.insert(*m) { - stack.push(*m); - } - } - } - assert!( - seen.contains(&party), - "feed_party runs after feed_units, whose snapshots RAID_TARGET_UPDATE's handler reads" - ); - } - - /// Every latched window's show reads `"npc"` (`GossipFrame.lua:33-35`, `QuestFrame.lua:63-65`, - /// `BankFrame.lua:127-128`, …), which the reference seats before the show: the packet's handler - /// writes `[0xb4e2d0]` (`0x4e26fa` → `0x4e1fe9` → `0x4930d0`) and only then fires - /// `GOSSIP_SHOW` (`0x4e27df`). Here the latch reaches the token through `feed_interact_npc` and - /// `feed_units`, so `feed_units` runs after the first; each window's show fires on its lane in - /// the drain, after every feed ([`crate::lanes`]). Read off the declared graph. - #[test] - fn every_latched_windows_show_reads_the_token_its_latch_seated() { - let mut app = headless_client(); - let c = census(&mut app, Update, SyncPoints::Declared); - if !type_names_available(&c) { - eprintln!( - "skipped: this build carries no type names (bevy/debug rides with the dev feature)" - ); - return; - } - let one = |suffix: &str| -> SystemKey { - let mut hits = c.systems.iter().filter(|(_, s)| s.name.ends_with(suffix)); - match (hits.next(), hits.next()) { - (Some((k, _)), None) => *k, - _ => panic!("exactly one system named `…{suffix}` in Update"), - } - }; - let mut succ: HashMap> = HashMap::new(); - for (a, b) in &c.dependencies { - succ.entry(*a).or_default().push(*b); - } - let after = |from: SystemKey| -> HashSet { - let (mut seen, mut stack) = (HashSet::new(), vec![from]); - while let Some(n) = stack.pop() { - for m in succ.get(&n).into_iter().flatten() { - if seen.insert(*m) { - stack.push(*m); - } - } - } - seen - }; - let units = one("::ui_unit::feed_units"); - assert!( - after(one("::ui_session::feed_interact_npc")).contains(&units), - "feed_units runs after feed_interact_npc, which publishes the latch it names \"npc\" by" - ); - } - /// The sets of the frame's input records, which run ahead of the net drain. const INPUT_RECORD_SETS: &[&str] = &["UiInput", "WorldMouse"]; @@ -1858,9 +1668,8 @@ pub(crate) mod schedule_tests { } /// The consumer markers: a VM holder that does one of these to host state has spent - /// something this frame that nothing can re-spend. A feed posts its events - /// (`script_calls::Fires::post`) to fire once its pushes are in. - const CONSUMES: &[&str] = &["fire_event(", "fires.post(", "mem::take(", ".drain("]; + /// something this frame that nothing can re-spend. + const CONSUMES: &[&str] = &["fire_event(", "mem::take(", ".drain("]; /// Why an ungated one-shot consumer holding the VM loses nothing in the one-frame window /// where the wire is in world and the glue VM is still live. @@ -1868,13 +1677,8 @@ pub(crate) mod schedule_tests { enum Because { /// The consumed queue is filled only by Lua asking; a frameless VM asks for nothing. FilledByVm, - /// Filled only by a server reply to a click in the interface, or (noted in the reason) - /// another player's act on us, which meets the login burst only by coincidence. - PlayerRoundTrip, /// Consumed in the window or not, the state is re-asked or re-derived once the UI is up. SelfHealing, - /// The publication is driven by a `VmMemo` diff, so a new VM re-derives and re-fires it. - MemoLatched, /// Documented at the line as intentional. Deliberate, } @@ -1882,18 +1686,18 @@ pub(crate) mod schedule_tests { /// Every one-shot VM consumer not gated on `ingame_ui_up` (read off the schedule) and not a /// memo-diffed `fire_event`, keyed `(path under src/, fn)`, with the reason it is safe. const EXEMPT: &[(&str, &str, Because, &str)] = &[ - ("bindings.rs", "sync_dispatch", Because::MemoLatched, - "`seen_generation` is a `VmMemo`: a new VM reads `None` and rebuilds, and its seed's load owes the UPDATE_BINDINGS"), ("capture/probe_bg.rs", "bg_probe", Because::SelfHealing, "the battleground probe: dev-only (`WOW_PROBE_BG`, `cfg(feature = \"dev\")`) so it is not in a player build at all, and its `mem::take` is of its OWN pending-events string, not a queue anything else fills. Its one real VM dependency is the Lua event tap, which self-heals: `EVENT_DRAIN` returns a `` sentinel when the tap's globals are missing — the case this window causes, since a tap installed in the glue VM is discarded when `mint_entry_vm` builds the interface — and the probe re-installs on the next frame"), + ("capture/fixtures.rs", "open_character_fixture", Because::Deliberate, + "a capture's fixture, dev tooling: its `fire_event` is the character fixture's stand-in for its items' creates' `UNIT_INVENTORY_CHANGED`, fired in the same VM and ahead of the window's open, so a VM with no frames to take it has no window to open either"), ("capture/probes/act.rs", "fire_probe_drag", Because::FilledByVm, "the drag probe: dev-only (`WOW_PROBE_DRAG`), it starts past `WOW_PROBE_DRAG_AT` with the \ player's body in the world, and its `.drain(..)` is of the VM's own script errors, \ raised by the gesture it just made"), - ("death/mod.rs", "feed_death", Because::MemoLatched, - "`feed.vm: VmMemo`: a fresh memo takes the first snapshot as no edge and re-announces a held offer, confirm and corpse range, and skips the edges of our create's frame, whose arrival item signals the state itself"), - ("death/mod.rs", "signal", Because::MemoLatched, - "the death state's signal: our death's leg (`signal_death`), run in its packet with the VM deferred, its `PLAYER_DEAD` parked for the deaths lane, whose drain runs only with the interface up (`ingame_ui_up`); and an arrival's, run by the arrival lane's firing inside the lanes' drain, which runs only with the interface up (`ingame_ui_up`). Its memo is `feed.vm`, a `VmMemo`"), + ("death/mod.rs", "signal", Because::Deliberate, + "the death state's signal: our death's leg (`signal_death`), run in its packet with the VM deferred, its `PLAYER_DEAD` parked for the deaths lane, whose drain runs only with the interface up (`ingame_ui_up`); and an arrival's, run by the arrival lane's firing inside the lanes' drain, which runs only with the interface up (`ingame_ui_up`)"), + ("death/mod.rs", "ask_spirit_healer", Because::Deliberate, + "no system: the spirit healer click's world edit runs it, inside the input pass's click legs, with the interface up"), ("death/mod.rs", "query_corpse_on_world_enter", Because::Deliberate, "no system: a leg the arrival lane's firing runs, inside the drain, which runs only with the interface up; its take is the range latch, which it zeroes into the live VM"), ("net/objects/update.rs", "on_update_end", Because::Deliberate, @@ -1904,38 +1708,20 @@ pub(crate) mod schedule_tests { "the outcome chain starts with the VM's own `Screenshot()` call"), ("vplates.rs", "drive_vplates", Because::Deliberate, "its take is the hits queued for plates: a hit before the interface is up has no plate to flash, since a plate exists only once this driver has bound it under a loaded interface, so a dropped one loses nothing"), - ("target/click.rs", "select_on_plate_click", Because::FilledByVm, - "filled only by a nameplate frame's click, which a frameless VM has no plate to make"), ("ui_action/cooldown_lane.rs", "fire_cooldowns", Because::Deliberate, "a lane's firing, run only by the drain: `drop_cooldown_log`, gated on the interface being down, drops the log the frame it is written, so no signal fires into a later VM"), ("ui_action/drain.rs", "drain_click_casts", Because::FilledByVm, - "filled only by a nameplate's right-click, which a frameless VM has no plate to make, or a crate's `Interact`; the world click's own casts drain inside its call, and the drain sends casts to the wire"), + "filled only by a crate's `Interact`; the world click's and a nameplate click's own casts drain inside their calls, and the drain sends casts to the wire"), + ("ui_action/recount.rs", "arrival_slot_pass", Because::Deliberate, + "no system: a leg the arrival lane's firing runs, inside the drain, which runs only with the interface up"), ("ui_action/recount.rs", "recount", Because::Deliberate, "no system: the item lane's firing calls it per run (`item_lane::fire_run`), inside the lanes' drain, which runs only with the interface up (`ingame_ui_up`)"), - ("ui_char.rs", "feed_char", Because::FilledByVm, - "its take is the ammo getters' hits, which only a getter's call leaves, and a frameless VM \ - calls none; the doll's own pushes ride `VmMemo`s"), - ("ui_chat/feed.rs", "played_time_bridge", Because::FilledByVm, - "the answer it takes follows `RequestTimePlayed()`, Lua's own ask, which a frameless VM \ - never makes"), - ("ui_follow.rs", "feed_follow", Because::MemoLatched, - "`feed.vm: VmMemo`; a fresh VM re-fires BEGIN for a follow in progress"), ("ui_guild/lane.rs", "fire_guild", Because::Deliberate, "a lane's firing, run only by the drain, which runs only with the interface up (`ingame_ui_up`): the lane holds what the packets queue until a drain fires it, so the login's message of the day, which lands ahead of the interface, fires into the VM that comes up"), - ("ui_item_text.rs", "feed_item_text", Because::MemoLatched, - "`told` is a `VmMemo` inside the session (a fresh VM re-begins), and the open is a player click"), - ("ui_logout.rs", "feed_logout", Because::PlayerRoundTrip, - "both packets answer the `CMSG_LOGOUT_REQUEST`/cancel the game menu sent"), ("ui_loot/mod.rs", "drain_loot", Because::Deliberate, "its takes of `LootMoveStart` and `LootCloseAtRest` close on the engine's side and publish nothing to the VM, whose `LOOT_CLOSED` is the loot lane's; the at-rest sweep signals only on a disenchant window, which the interface's own cast opens"), - ("ui_loot_roll.rs", "feed_loot_rolls", Because::PlayerRoundTrip, - "a roll exists only after a group member loots under group loot; leftovers are cleared at socket teardown (another player's act: coincidence-only residual)"), - ("ui_macro/mod.rs", "load_macros", Because::MemoLatched, - "`MacroFiles.identity` is a `VmMemo`, so a new session re-reads the files and re-fires UPDATE_MACROS; also `InWorldGated`"), ("ui_panes.rs", "feed_character_panes", Because::FilledByVm, "the answers answer the VM's own build requests and arms on panes it listed; a frameless VM lists none, and an answer for another VM's rows is dropped"), - ("ui_quest_share.rs", "feed_quest_share", Because::PlayerRoundTrip, - "a verdict answers our own push and a confirm follows a party member's escort accept, both held until the name resolves (the confirm is another player's act: coincidence-only residual)"), ("ui_script/glue_mgr.rs", "drive_glue_mgr", Because::Deliberate, "it acts only on a glue-kind VM (`script.filter(vm_kind() == Glue)`, documented at the fire sites), never the entry VM the window leaves frameless; news that arrives with no glue VM is held in `AddonInfoReply` for the next one"), ("ui_script/extract/mod.rs", "paint_script", Because::Deliberate, @@ -1950,6 +1736,8 @@ pub(crate) mod schedule_tests { "a lane's firing, run only by the drain: `drop_list_rebuilds`, gated on the interface being down, empties the lane the frame its items land, so none fires into a later VM"), ("ui_trade/lane.rs", "open", Because::Deliberate, "no system: the trade lane's firing calls it for the open's item, inside the drain, which runs only with the interface up; `drop_trade_events`, gated on the interface being down, empties the lane the frame its items land"), + ("ui_logout.rs", "leave_world", Because::Deliberate, + "runs only with a world load posted, which `SMSG_NEW_WORLD` posts: the world session's packets wait for the entry load (`net::apply::InboundHold`), so none is posted before the interface is up"), ("ui_logout.rs", "set_in_world", Because::Deliberate, "no system: the arrival lane's firing runs it as the arrival's last leg, inside the drain, which runs only with the interface up; `drop_arrivals` empties the lane at the session's end"), ("ui_world_enter.rs", "control_rose", Because::Deliberate, @@ -2012,7 +1800,7 @@ pub(crate) mod schedule_tests { // `PreUpdate` holds the frame's head: the script memory watch, ahead of the reload. let pre = census(&mut app, PreUpdate, SyncPoints::Built); // The leave-world sweep's legs run only inside its schedule, whose callers hold the - // interface up: the worldport's producer is gated with the unit feed, the shutdown edges + // interface up: the worldport's producer is gated with the unit feeds, the shutdown edges // run the sweep before a parked glue VM returns, and the quit returns inside the // entry-load window. let swept: Vec = census( diff --git a/crates/benilla-app/src/game_tip.rs b/crates/benilla-app/src/game_tip.rs index 9f7c54e57..d33d0cd6a 100644 --- a/crates/benilla-app/src/game_tip.rs +++ b/crates/benilla-app/src/game_tip.rs @@ -367,7 +367,10 @@ pub(crate) struct GameTipPlugin; /// The tip CVars' change callback. A hand-edited cursor lands verbatim; [`raise`] clamps it, as the /// reference does (`0x46b682`). -pub(crate) fn on_cvar(ev: On, mut setting: ResMut) { +pub(crate) fn on_cvar( + ev: &crate::cvars::CvarChanged, + mut setting: bevy::prelude::Mut<'_, GameTipSetting>, +) { match ev.key().as_str() { "showgametips" => setting.show = ev.flag(), "gametip" => setting.next = ev.num() as i64, @@ -377,10 +380,9 @@ pub(crate) fn on_cvar(ev: On, mut setting: ResMut() - // Initialised here, not by the CVar host: [`on_cvar`] takes it as a plain `ResMut` and - // panics without it. + // Initialised here, not by the CVar host: without it [`on_cvar`]'s writes go nowhere + // ([`crate::cvars::CvarCallbacks`]). .init_resource::() .add_systems( Startup, diff --git a/crates/benilla-app/src/glue_session/login.rs b/crates/benilla-app/src/glue_session/login.rs index 3a1e204fe..e143d2b42 100644 --- a/crates/benilla-app/src/glue_session/login.rs +++ b/crates/benilla-app/src/glue_session/login.rs @@ -46,7 +46,9 @@ pub(super) fn build(app: &mut App) { (answer_glue, drive_policy, to_select_on_auth, drive_quit) .chain() .in_set(LoginPolicy) - .after(benilla_world::schedule::WorldStage::Net), + .after(benilla_world::schedule::WorldStage::Net) + // After the calls, whose `realmList` callback writes the address it logs on to. + .after(crate::vm_pass::VmPass::End), ) .add_systems(Update, debug_login_shot.after(LoginPolicy)); } diff --git a/crates/benilla-app/src/item_lane.rs b/crates/benilla-app/src/item_lane.rs index b8138dcdb..a02f2e743 100644 --- a/crates/benilla-app/src/item_lane.rs +++ b/crates/benilla-app/src/item_lane.rs @@ -20,16 +20,14 @@ use bevy::prelude::*; use benilla_ui::script::UiScript; use crate::field_watch::FieldNotice; -use crate::item_watch::{BagEvent, ItemNotice, Run, TradeTouch, Unlock}; +use crate::item_watch::{BagEvent, Freed, ItemNotice, Run, TradeTouch, Unlock}; use crate::lanes::{Stamp, Until}; -use crate::net::{ObjectStore, SelfPlayer}; /// The item watchers' runs, each stamped as its packet's handler readied it /// ([`crate::lanes::stamp`]), with the trade half a close may run ahead of the lane -/// ([`Self::take_trade_touches`]), and the count of the `RaiseBagUpdate` calls readied -/// ([`Self::bag_raises`]). +/// ([`Self::take_trade_touches`]). #[derive(Resource, Default)] -pub(crate) struct ItemLane(VecDeque<(Stamp, Run, Option)>, u64); +pub(crate) struct ItemLane(VecDeque<(Stamp, Run, Option)>); impl ItemLane { /// Queue `run` behind everything stamped before it; a run that does nothing is not queued. @@ -37,7 +35,6 @@ impl ItemLane { if run.is_empty() { return; } - self.1 = self.1.wrapping_add(run.bag_raises() as u64); let stamp = crate::lanes::stamp(); let trade = run.notice.as_ref().and_then(ItemNotice::trade); let at = self.0.partition_point(|(s, _, _)| *s < stamp); @@ -60,12 +57,6 @@ impl ItemLane { self.0.clear(); } - /// How many `RaiseBagUpdate` calls (`0x4f9370`) the runs readied so far make, each the action - /// bar's usable refresh (`0x4e5c00`, `0x4f9374`), which the action feed runs on its edge. - pub(crate) fn bag_raises(&self) -> u64 { - self.1 - } - /// Take every run waiting with its stamp, in order, unfired. #[cfg(test)] pub(crate) fn drain_stamped(&mut self) -> Vec<(Stamp, Run)> { @@ -96,6 +87,11 @@ pub(crate) fn add_item_lane(app: &mut App) { fire_item_runs, None, ) + .add_drain_end(|world| { + if let Some(items) = world.get_resource::() { + items.end_refusal_walks(); + } + }) .add_systems( Update, drop_item_runs @@ -111,11 +107,10 @@ fn drop_item_runs(mut lane: ResMut) { lane.clear(); } -/// What a run's firing reads: the active player, and what the trade scan reads, the objects and -/// the item records the recount counts with among them. +/// What a run's firing reads: what the trade scan reads, and the message sink. The recount counts +/// through the host's action states. #[derive(bevy::ecs::system::SystemParam)] pub(crate) struct RunReads<'w, 's> { - me: Query<'w, 's, &'static ObjectStore, With>, trade: crate::ui_trade::TouchReads<'w, 's>, sink: crate::ui_action::MessageSink<'w>, } @@ -172,46 +167,57 @@ pub(crate) fn seat_item_lane(world: &mut World) { /// One run, in its handler's order: its unlocks, the recount of each entry it passes `0x4e5c70`, /// its trade half unless a close ran it, then its own tail ([`fire_tail`]). A run with no notice -/// unlocks, then signals its bag events and its unit signals. +/// unlocks, then signals its bag events and its unit signals. Its alert recompute (`0x4c7ee0`) +/// reads the objects as of its place through the lent host: behind a visible item's rebuilds, +/// ahead of its recounts (`0x5dee75`, `0x5dee7a`), else last, behind the stack count's quest log +/// ask (`0x5d9519`, `0x5d952a`), the enchantment's slot signal (`0x5d9b2a`, `0x5d9b2f`), and alone +/// for the flags' and the durability's. The objects it frees go last ([`forget_freed`]); a +/// deactivate's cursor leg goes first ([`let_cursor_go`]). fn fire_run(vm: &mut RunVm, reads: &mut RunReads, run: Run, touch: Option) { let Run { notice, signals, unlocks, bags, + alerts, + freed, + cursor, } = run; + if let Some(item) = cursor { + on_vm(vm, |script| let_cursor_go(script, item)); + } let Some(notice) = notice else { - vm.run(|script| { - if let Some(script) = script { - fire_unlocks(script, unlocks); - fire_bags(script, &bags); - fire_signals(script, &mut reads.sink, signals); - } - }); + on_vm(vm, |script| fire_unlocks(script, unlocks)); + fire_bags(vm, &bags); + on_vm(vm, |script| fire_signals(script, &mut reads.sink, signals)); + if alerts { + on_vm(vm, UiScript::recompute_inventory_alerts); + } + on_vm(vm, |script| forget_freed(script, freed)); return; }; let rebuild = rebuild_at(¬ice); + let alerts_first = alerts + && matches!( + notice, + ItemNotice::Visible { .. } | ItemNotice::ForeignVisible + ); let held = vm.run(|script| { let Some(script) = script else { return false; }; fire_unlocks(script, unlocks); if rebuild == Some(Rebuild::BeforeRecount) { - rebuild_lists(script, &|entry| { - carried(&reads.me, &reads.trade.objects, entry) - }); + rebuild_lists(script); + } + if alerts_first { + script.recompute_inventory_alerts(); } true }); if held { - let counter = crate::ui_action::recount::Counter { - store: reads.me.iter().next(), - objects: &reads.trade.objects, - items: &reads.trade.items, - commands: &reads.trade.commands, - }; for entry in notice.recounts() { - crate::ui_action::recount::recount(vm, &counter, entry); + crate::ui_action::recount::recount(vm, entry); } } if let Some(touch) = touch { @@ -221,17 +227,41 @@ fn fire_run(vm: &mut RunVm, reads: &mut RunReads, run: Run, touch: Option {} + Freed::Items(guids) => { + for guid in guids { + script.forget_item_lock(guid); + } + } + Freed::All => script.forget_all_item_locks(), + } +} + +/// `f` on the VM with the host lent; nothing with no VM. +fn on_vm(vm: &mut RunVm, f: impl FnOnce(&mut UiScript)) { vm.run(|script| { if let Some(script) = script { - let count = |entry| carried(&reads.me, &reads.trade.objects, entry); - fire_tail( - script, - &mut reads.sink, - ¬ice, - &bags, - signals, - (rebuild, &count), - ); + f(script); } }); } @@ -241,7 +271,7 @@ fn fire_run(vm: &mut RunVm, reads: &mut RunReads, run: Run, touch: Option Option { ItemNotice::Record { .. } | ItemNotice::Destroyed { .. } | ItemNotice::StackCount { .. } - | ItemNotice::Visible { .. } => Some(Rebuild::BeforeRecount), + | ItemNotice::Visible { .. } + | ItemNotice::ForeignVisible => Some(Rebuild::BeforeRecount), ItemNotice::Seat { .. } => Some(Rebuild::BeforeBags), ItemNotice::Bag { .. } => Some(Rebuild::AfterBags), ItemNotice::EntryRecord { .. } | ItemNotice::SpellCharges { .. } | ItemNotice::Entry { .. } | ItemNotice::Enchantment { .. } - | ItemNotice::TradeRecord { .. } => None, + | ItemNotice::TradeRecord { .. } + | ItemNotice::TooltipRecord { .. } + | ItemNotice::LockKeyRecord + | ItemNotice::ActionRecord { .. } => None, } } -/// The two rebuilds, each signalling its window's update while that window is open; `count` is -/// the carried count of an entry the builds read (`0x622130`). -fn rebuild_lists(script: &mut UiScript, count: &dyn Fn(u32) -> u32) { - script.rebuild_trade_skill(&mut |t| t.recount(count)); - if script.rebuild_craft(&mut |c| c.recount(count)) { +/// The two rebuilds, each reading its list as it stands and signalling its window's update while +/// that window is open. +fn rebuild_lists(script: &mut UiScript) { + script.rebuild_trade_skill(&mut |_| {}); + if script.rebuild_craft(&mut |_| {}) { script.fire_event("CRAFT_UPDATE", vec![]); } } -/// The player's carried count of an entry, 0 with no active player. -fn carried( - me: &Query<&crate::net::ObjectStore, With>, - objects: &crate::net::Objects, - entry: u32, -) -> u32 { - me.iter().next().map_or(0, |s| { - crate::ui_items::count_of( - &s.0, - objects, - entry, - crate::ui_items::InventoryScope::DEFAULT, - ) - }) -} - /// What a run does after its recount and trade half, in its handler's order: the quest log's ask /// for the item (`0x4df7b0`) ahead of the `BAG_UPDATE` and the slot's signal in the record set-up /// (`0x5d85d9`, `0x5d85e8`, `0x5d8606`) and the destroy (`0x5d87b2` before `0x5d87c1`), and behind /// both in the stack count's (`0x5d94ff`, `0x5d950e`, `0x5d9519`); the spell charges' /// `BAG_UPDATE_COOLDOWN` (`0x4f93d0`); a trade getter's record callback's `TRADE_UPDATE` -/// (`0x4c034f`); and every other run's bag events, then its signals. +/// (`0x4c034f`); the tooltips' record callbacks (`0x52e530`, `0x52f820`, `0x52ad10`); and every +/// other run's bag events, then its signals. fn fire_tail( - script: &mut UiScript, + vm: &mut RunVm, sink: &mut crate::ui_action::MessageSink, notice: &ItemNotice, bags: &[BagEvent], signals: Vec, - (rebuild, count): (Option, &dyn Fn(u32) -> u32), + rebuild: Option, ) { match *notice { ItemNotice::Record { entry, .. } | ItemNotice::Destroyed { entry, .. } => { - script.quest_item_changed(entry); - fire_bags(script, bags); - fire_signals(script, sink, signals); + on_vm(vm, |script| script.quest_item_changed(entry)); + fire_bags(vm, bags); + on_vm(vm, |script| fire_signals(script, sink, signals)); } ItemNotice::StackCount { entry, .. } => { - fire_bags(script, bags); - fire_signals(script, sink, signals); - script.quest_item_changed(entry); + fire_bags(vm, bags); + on_vm(vm, |script| { + fire_signals(script, sink, signals); + script.quest_item_changed(entry); + }); } - ItemNotice::SpellCharges { .. } => { + ItemNotice::SpellCharges { .. } => on_vm(vm, |script| { script.fire_event("BAG_UPDATE_COOLDOWN", vec![]); fire_signals(script, sink, signals); - } + }), // Literal names: `reference_ui`'s producer test finds fire sites by literal. - ItemNotice::TradeRecord { .. } => script.fire_event("TRADE_UPDATE", vec![]), + ItemNotice::TradeRecord { .. } => { + on_vm(vm, |script| script.fire_event("TRADE_UPDATE", vec![])); + } + ItemNotice::TooltipRecord { entry } => { + on_vm(vm, |script| script.answer_item_tooltips(entry)); + } + ItemNotice::LockKeyRecord => { + on_vm(vm, |script| { + script.tooltip_object_refresh(); + }); + } _ => { if rebuild == Some(Rebuild::BeforeBags) { - rebuild_lists(script, count); + on_vm(vm, rebuild_lists); } - fire_bags(script, bags); + fire_bags(vm, bags); if rebuild == Some(Rebuild::AfterBags) { - rebuild_lists(script, count); + on_vm(vm, rebuild_lists); } - fire_signals(script, sink, signals); + on_vm(vm, |script| fire_signals(script, sink, signals)); } } } @@ -348,20 +379,23 @@ fn fire_unlocks(script: &mut UiScript, unlocks: Vec) { } } -/// A run's bag events, each with its number (`"%d"`, `0x835154`). -fn fire_bags(script: &mut UiScript, bags: &[BagEvent]) { +/// A run's bag events, each with its number (`"%d"`, `0x835154`); a `RaiseBagUpdate` refreshes +/// the bar's usable cache first, whatever it signals (`0x4f9374` into `0x4e5c00`). +fn fire_bags(vm: &mut RunVm, bags: &[BagEvent]) { use benilla_ui::script::ScriptValue; for &event in bags { - match event { + if let BagEvent::Raise(_) = event { + vm.engine_usable_cache_refresh(); + } + on_vm(vm, |script| match event { BagEvent::Raise(Some(n)) | BagEvent::Update(n) => { script.fire_event("BAG_UPDATE", vec![ScriptValue::Int(n)]); } - // The usable refresh alone, the action feed's ([`ItemLane::bag_raises`]). BagEvent::Raise(None) => {} BagEvent::Closed(n) => script.fire_event("BAG_CLOSED", vec![ScriptValue::Int(n)]), BagEvent::BankSlots => script.fire_event("PLAYERBANKSLOTS_CHANGED", vec![]), BagEvent::Open(n) => script.fire_event("BAG_OPEN", vec![ScriptValue::Int(n)]), - } + }); } } @@ -405,8 +439,10 @@ mod tests { let mut app = App::new(); app.insert_resource(crate::net::NetCommands(tx)); app.insert_non_send_resource(rx); - app.world_mut() - .spawn((SelfPlayer, ObjectStore(Default::default()))); + app.world_mut().spawn(( + crate::net::SelfPlayer, + crate::net::ObjectStore(Default::default()), + )); let mut script = UiScript::new().unwrap(); script.set_trade_skill(Some(TradeSkillState { line: 197, diff --git a/crates/benilla-app/src/item_watch.rs b/crates/benilla-app/src/item_watch.rs index b3830d7a0..f6ce0d824 100644 --- a/crates/benilla-app/src/item_watch.rs +++ b/crates/benilla-app/src/item_watch.rs @@ -67,11 +67,28 @@ pub(crate) enum ItemNotice { /// One of our visible items changed (`0x5dee30`, for the active player): the old and new /// `PLAYER_VISIBLE_ITEM__0`. Visible { old: u32, new: u32 }, + /// Another player's visible item changed (`0x5dee30` ahead of its test for the active player, + /// `0x5dee82`): the profession and craft lists' rebuilds (`0x5dee70`, `0x5dee75`) and the + /// alert recompute (`0x5dee7a`) alone, with no recount. + ForeignVisible, /// The record a trade getter asked for landed: its callback `0x4c0340` signals `TRADE_UPDATE` /// (`0x4c034f`), for a ready record only. Each getter call that missed registered one callback /// with no dedupe (`0x4c017f`, `0x4c0582`), so an answer writes one notice per call, after the /// notices of the handlers that registered earlier. It concerns no item of ours. TradeRecord { entry: u32 }, + /// A record landed that tooltips wait on: the item tooltips' callback `0x52e530` rebuilds + /// each from what it keeps, and the spell tooltips' `0x52f820` counts its answers down + /// ([`crate::ui_items::feed::tooltips_answered`]), for a found record only + /// (`0x52e551`, `0x52f826`). It concerns no item of ours. + TooltipRecord { entry: u32 }, + /// A record landed that an action slot's lookup asked for: the bar's callback `0x4e5b80` + /// recounts the entry (`0x4e5b8a` → `0x4e5c70`), for a found record only (`0x4e5b86`). It + /// concerns no item of ours. + ActionRecord { entry: u32 }, + /// The key record a game object plate's lock line waited on landed: its callback `0x52ad10` + /// builds `GameTooltip`'s game object plate again while it keeps one (`0x52ad34`-`0x52ad52`), + /// for a found record only (`0x52ad2f`). It concerns no item of ours. + LockKeyRecord, } /// What a notice asks of the trade's own column (`0x4bfb10`, `0x4bfb60`). @@ -96,6 +113,23 @@ pub(crate) enum Unlock { Entry(Vec), } +/// The item objects a run frees, whose locks go with them silently, at its packet's place. The +/// lock is the object's bit (`item+0x314` bit 0), which the constructor alone zeroes (`0x5d823e`) +/// and a release leaves set, as the object lives on in the released table (`0x464920`) and a block +/// that brings it back reuses it (`0x464530`): only a free takes it, and the next object under the +/// guid starts unlocked. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub(crate) enum Freed { + #[default] + Nothing, + /// The destroy's free of a live or released item (`0x467521`), or a new object's free of the + /// oldest released one of its type (`0x466e55`). + Items(Vec), + /// Every object, as the world's load and the session's end free them (`0x467700` → + /// `0x467800`). + All, +} + /// A bag event a run signals after its recount, at its handler's place in the run. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) enum BagEvent { @@ -124,6 +158,16 @@ pub(crate) struct Run { pub(crate) signals: Vec, pub(crate) unlocks: Vec, pub(crate) bags: Vec, + /// The handler runs the alert recompute `0x4c7ee0`, which signals `UPDATE_INVENTORY_ALERTS` + /// (`0x4c8085`): the ammunition's stack count (`0x5d952a`), the enchantment (`0x5d9b2f`) and a + /// visible item (`0x5dee7a`) among their steps, and alone the flags' force-red bit + /// (`0x5d97aa`) and the durability (`0x5d9920`). + pub(crate) alerts: bool, + /// The item objects freed at the run's place, after everything else it does. + pub(crate) freed: Freed, + /// The item whose deactivate lets the cursor go when it holds it, before everything else the + /// run does ([`Self::clearing_cursor`]). + pub(crate) cursor: Option, } impl Run { @@ -133,15 +177,36 @@ impl Run { && self.signals.is_empty() && self.unlocks.is_empty() && self.bags.is_empty() + && !self.alerts + && self.freed == Freed::Nothing + && self.cursor.is_none() } - /// How many times the run calls `RaiseBagUpdate` (`0x4f9370`), each of which runs the action - /// bar's usable refresh (`0x4e5c00`, `0x4f9374`) whether or not it signals. - pub(crate) fn bag_raises(&self) -> usize { - self.bags - .iter() - .filter(|e| matches!(e, BagEvent::Raise(_))) - .count() + /// A run that frees `freed` and does nothing else. + pub(crate) fn freeing(freed: Freed) -> Self { + Self { + freed, + ..Self::default() + } + } + + /// `CGItem_C::Deactivate`'s cursor leg on `item` (`0x5d86c9`-`0x5d86e9`): an item the cursor + /// holds (`GetCursorItemGuid 0x494c60`) is let go as `ClearCursor(1, 1)` (`0x495190`), which + /// unlocks it (`0x4951d9`) and signals as it runs. The cursor is the interface's, so the run + /// compares it where it fires, at the deactivate's place. + pub(crate) fn clearing_cursor(item: u64) -> Self { + Self { + cursor: Some(item), + ..Self::default() + } + } + + /// A handler's run that does nothing but the alert recompute. + fn alerts() -> Self { + Self { + alerts: true, + ..Self::default() + } } } @@ -325,7 +390,8 @@ impl ItemNotice { | Self::EntryRecord { entry, .. } | Self::StackCount { entry, .. } | Self::SpellCharges { entry, .. } - | Self::Enchantment { entry, .. } => vec![*entry], + | Self::Enchantment { entry, .. } + | Self::ActionRecord { entry } => vec![*entry], Self::Entry { old, new, @@ -341,7 +407,10 @@ impl ItemNotice { Self::Seat { old, new } => old.iter().chain(new.iter()).copied().collect(), Self::Bag { entries } => entries.clone(), Self::Visible { old, new } => vec![*old, *new], - Self::TradeRecord { .. } => Vec::new(), + Self::TradeRecord { .. } + | Self::TooltipRecord { .. } + | Self::LockKeyRecord + | Self::ForeignVisible => Vec::new(), } } @@ -383,6 +452,15 @@ fn inventory_watched(seat: u8) -> bool { matches!(seat, 0..=22 | 39..=68 | 81..=112) } +/// `ITEM_FIELD_FLAGS` and `ITEM_FIELD_DURABILITY`, the watches `0x5d9360` registers at item +/// offsets `0x3c` and `0xa0` (`0x5d93d0`, `0x5d93ea`). +const FIELD_ITEM_FLAGS: u16 = 21; +const FIELD_ITEM_DURABILITY: u16 = 46; + +/// `INVTYPE_AMMO` (vmangos `ItemPrototype.h`), the stack-count watcher's recompute gate +/// (`0x5d9525`). +const INVTYPE_AMMO: u32 = 0x18; + /// The equipment slots with a visible-item watcher: mask `0x7c3fd` of `0x5e2510`, slots 0 and 2-9 /// and 14-18; the neck, rings and trinkets have none. const VISIBLE_WATCHED: u32 = 0x7c3fd; @@ -506,9 +584,28 @@ where } } out.extend(notices.into_iter().map(|(at, n)| (at, self.run(n, bags)))); + // `0x5d96e0`: the force-red bit (`0x10`) moved (`0x5d9722`) on an item the active + // player, found live, wears in slots 0 to 18 of its list (`0x5d97a1`-`0x5d97a8`). + let force_red_moved = block + .edge(FIELD_ITEM_FLAGS) + .is_some_and(|(old, new)| (old ^ new) & 0x10 != 0); + if let Some(at) = place(FIELD_ITEM_FLAGS..FIELD_ITEM_FLAGS + 1, List::Type) { + let me = self.me.and_then(|g| (self.lookup)(g)); + let worn = me.is_some_and(|me| (0..19).any(|n| seat_guid(me, n) == guid)); + if force_red_moved && worn { + out.push((at, Run::alerts())); + } + } } _ => {} } + // `0x5d97c0` on any item, ours or not: whatever it finds, it ends in the recompute + // (`0x5d97fb`, `0x5d9829` and the fall-through all reach `0x5d9920`). + if matches!(kind, ObjectType::Item | ObjectType::Container) { + if let Some(at) = place(FIELD_ITEM_DURABILITY..FIELD_ITEM_DURABILITY + 1, List::Type) { + out.push((at, Run::alerts())); + } + } // A bag's own seats, watched while it is in the bag cache (`0x4f932a`, `0x4f9299`). if kind == ObjectType::Container { let count = fields.container_num_slots().unwrap_or(0); @@ -540,6 +637,20 @@ where out.push((at, run)); } } + // `0x5dee30` on another player's visible item: the rebuilds and the recompute ahead of + // its test for the active player (`0x5dee70`-`0x5dee7a`, `0x5dee82`); the rest is the + // active player's. + if kind == ObjectType::Player && self.me != Some(guid) { + for i in 0..19u8 { + if VISIBLE_WATCHED & (1 << i) == 0 { + continue; + } + let base = FIELD_PLAYER_VISIBLE_ITEM_1_CREATOR + 12 * u16::from(i); + if let Some(at) = place(base..base + 12, List::Type) { + out.push((at, self.run(ItemNotice::ForeignVisible, bags))); + } + } + } if kind == ObjectType::Player && self.me == Some(guid) { for i in 0..19u8 { if VISIBLE_WATCHED & (1 << i) == 0 { @@ -642,13 +753,23 @@ where run.unlocks .extend(self.entry_unlock(guid, entry, Walk::Stack)); run.bags.extend(self.item_bag(guid, bags)); + // `0x5d9520`: the record's inventory type (`0x5d9ff0`, `[rec+0x2c]`, 0 uncached) + // is ammunition. + run.alerts = self + .items + .template(entry, 0, Ask::Read) + .is_some_and(|t| t.inventory_type == INVTYPE_AMMO); } ItemNotice::Entry { guid, new_cached: true, .. + } => run.bags.extend(self.item_bag(guid, bags)), + ItemNotice::Enchantment { guid, .. } => { + run.bags.extend(self.item_bag(guid, bags)); + run.alerts = true; } - | ItemNotice::Enchantment { guid, .. } => run.bags.extend(self.item_bag(guid, bags)), + ItemNotice::Visible { .. } | ItemNotice::ForeignVisible => run.alerts = true, _ => {} } run.notice = Some(notice); @@ -1162,9 +1283,13 @@ mod tests { // A ring (slot 10) has no watcher. let ring = FIELD_PLAYER_VISIBLE_ITEM_1_CREATOR + 12 * 10; assert!(w.values(ME, &[(ring + 2, 1)]).is_empty()); - // Another player's visible items run nothing for us. + // Another player's visible item runs the rebuilds and the recompute alone (`0x5dee70`- + // `0x5dee7a`, ahead of `0x5dee82`'s test for us). w.objects.insert(OTHER, player(&[])); - assert!(w.values(OTHER, &[(base + 2, 1)]).is_empty()); + assert_eq!( + w.values(OTHER, &[(base + 2, 1)]), + [ItemNotice::ForeignVisible] + ); } #[test] diff --git a/crates/benilla-app/src/items.rs b/crates/benilla-app/src/items.rs index 62ff652b1..342fb231a 100644 --- a/crates/benilla-app/src/items.rs +++ b/crates/benilla-app/src/items.rs @@ -102,8 +102,7 @@ impl Countdowns { remaining_ms(self.enchant(slot)) } - /// [`Self::enchant_remaining_ms`] floored to the second, for the snapshot feeds: a per-ms read - /// would push a new snapshot every frame while a timer runs. + /// [`Self::enchant_remaining_ms`] floored to the second, the whole seconds a slot's view shows. pub(crate) fn enchant_remaining_display_ms(&self, slot: u32) -> Option { self.enchant_remaining_ms(slot).map(|ms| ms - ms % 1000) } @@ -124,23 +123,6 @@ impl Countdowns { pub(crate) fn lifetime_remaining_display_ms(&self) -> Option { self.lifetime_remaining_ms().map(|ms| ms - ms % 1000) } - - /// This item's share of [`ItemChanges::countdown_steps`]: `floor(seconds left) + 1` per live - /// cell, 0 when unset or elapsed, so the final `Some(0)` to `None` collapse is its own step. - fn steps(&self, now: Instant) -> u64 { - std::iter::once(self.lifetime) - .chain(self.enchants) - .flatten() - .map(|at| { - let left = at.saturating_duration_since(now); - if left.is_zero() { - 0 - } else { - left.as_secs() + 1 - } - }) - .sum() - } } /// An item entity whose fields or countdown cells were written since the reader last ran. @@ -149,12 +131,12 @@ type ItemMoved = ( Or<(Changed, Changed)>, ); -/// Whether any item object was created, written or destroyed this frame; the inventory feeds' gate. +/// Whether any item object was created, written or destroyed this frame; the worn-model +/// resolve's gate. #[derive(SystemParam)] pub(crate) struct ItemChanges<'w, 's> { changed: Query<'w, 's, (), ItemMoved>, removed: RemovedComponents<'w, 's, ItemObject>, - countdowns: Query<'w, 's, &'static Countdowns>, } impl ItemChanges<'_, '_> { @@ -163,23 +145,6 @@ impl ItemChanges<'_, '_> { let removed = self.removed.read().count() > 0; !self.changed.is_empty() || removed } - - /// The sum of every item's [`Countdowns`] steps: it moves exactly when a second-floored read - /// can, and each term only falls between landings, so no change masks another. - pub(crate) fn countdown_steps(&self) -> u64 { - let now = Instant::now(); - self.countdowns.iter().map(|c| c.steps(now)).sum() - } -} - -/// The player's inventory as one read: the self descriptor, the object lookup and the item watch. -#[derive(SystemParam)] -pub(crate) struct Inventory<'w, 's> { - pub(crate) self_store: Query<'w, 's, &'static ObjectStore, With>, - pub(crate) self_changed: - Query<'w, 's, (), (With, Changed)>, - pub(crate) objects: Objects<'w, 's>, - pub(crate) changes: ItemChanges<'w, 's>, } /// The Copy slice of an [`ItemInfo`] that equipment rendering and combat animation read. @@ -481,10 +446,11 @@ pub(crate) struct Items { /// [`Items::template_answered_unknown`] and asked again by the next event's lookup /// ([`QueryCache::refuse`]); it is never kept as a record. templates: QueryCache, - /// Each entry's last record change: the change count it landed or went at, and whether it is - /// held now. Read, never drained, by whoever follows the records ([`Self::changed_since`]): - /// the item-tooltip feed pushes a landed record unprompted and drops a removed one. - changes: std::collections::HashMap, + /// Each entry's last record change: the change count it landed or went at, whether it is held + /// now, and whether the VM's copy took it at its answer ([`Self::vm_took`]). Read, never + /// drained, by whoever follows the records ([`Self::changed_since`]): the item-tooltip feed + /// pushes a landed record unprompted and drops a removed one. + changes: std::collections::HashMap, /// How many record changes [`Self::changes`] has seen. change_count: u64, /// The reference's `PlayerPendingItemExpiration` list (`0x5ebd40`, at `CGPlayer_C + 0x1cc8`): @@ -497,9 +463,42 @@ pub(crate) struct Items { /// dedupe for the dedupe flag 0, `dbcache/callbacks#callback-order`). A getter registers one /// from a lookup, so the list is locked like the in-flight asks and registering takes `&self`. callbacks: std::sync::Mutex>, - /// The callbacks an answer ran that need the VM, `(entry, callback, found)` in the order - /// they ran: the equip replays ([`crate::ui_bind_confirm::replay_equip_records`]). - vm_callbacks: std::sync::Mutex>, + /// The refusals' walks: the one running now, and each of this drain's, whose signals the + /// drain fires under its marks ([`Self::walk_takes`]). + walks: std::sync::Mutex, +} + +/// [`Items::walks`]. +#[derive(Default)] +struct RefusalWalks { + now: Option, + done: Vec, +} + +/// A refused entry's callbacks run with status 0 (`0x55be91`-`0x55bead`), while its node stands +/// with no record. A lookup in a callback links its own at the head (`0x55ba30`), and the walk +/// goes from the tail toward the head, reading each link before the call (`0x55be9c`): it reaches +/// one a callback adds unless the adder was at the head, whose link was read as the end. The +/// node's destroy frees what is left uncalled (`0x55bed2`). Nothing is sent meanwhile: the lookup +/// finds the node. +struct RefusalWalk { + entry: u32, + /// The list as it stands, walked and to walk, for the dedupe scan (`0x55bbb3`). + list: Vec, + /// The next to run. + next: usize, + /// Whether the callback running now was the last when it began. + last: bool, + /// The marks around the walk, and the start of its last callback: a signal stamped between + /// `from` and `last_from` was raised by a callback with a next. + from: crate::lanes::Mark, + last_from: crate::lanes::Mark, + to: crate::lanes::Mark, + /// The callbacks a listener of the walk's signals added, which the walk reaches + /// ([`Items::take_walk_tail`]), and whether one came from a listener of a callback with a + /// next, so the last callback's next is no longer the end. + tail: Vec, + extended: bool, } /// A callback an item record's lookup registered, which the record's answer runs. @@ -529,8 +528,20 @@ pub(crate) enum RecordCallback { /// A trainer row's product, asked by `GetTrainerServiceIcon` and `GetTrainerServiceDescription` /// (`0x4d907e` with `0x4d9140`, `0x4d9cef` with `0x4d9db0`), one per call. Trainer, + /// A profession getter's, asked by `GetTradeSkillIcon`, `GetTradeSkillItemStats`, + /// `GetTradeSkillReagentInfo` and `GetTradeSkillTools` (`0x4fdb90`, `0x4fdf77`, `0x4ff6cd`, + /// `0x4ffac6` with `0x4fdc30`), one per call. + TradeSkill, + /// A profession list build's product (`0x4fcd4d` with `0x4fc8e0`), one per row that missed. + TradeSkillBuild, + /// A craft getter's, asked by `GetCraftReagentInfo` and `GetCraftSpellFocus` (`0x4f75dd`, + /// `0x4f79f2` with `0x4f7710`), one per call. + Craft, /// A questgiver row's, asked by `GetQuestItemInfo` (`0x5017de` with `0x5018c0`), one per call. Quest, + /// A turn-in's reward line whose item was not cached (`0x5dc647`, `0x5dc6a1` with + /// `0x5dc7b0`), one per line. + QuestReward, /// A mail row's, asked by `GetInboxHeaderInfo` and `GetInboxItem` (`0x4aecc7`, `0x4aed63`, /// `0x4af66f` with `0x4af0a0`), one per call, or an auction notice's at the list parse /// (`0x4acf38` with `0x4ad010`), one per notice. @@ -543,6 +554,33 @@ pub(crate) enum RecordCallback { /// The sell slot item's, asked by `CalculateAuctionDeposit` and `GetAuctionSellItemInfo` /// (`0x4ce25e`, `0x4ce5e3` with `0x4ce2f0`), one per call. AuctionSellItem, + /// A paper's item the world-enter init missed (`0x4acbba` with `0x4acbf0`), one per row. + Stationery, + /// A spell go's item cooldown held for its record (`0x6e84c2` with `0x6e8830`), one per go. + ItemCooldown, + /// A cooldown query's miss, the action bar's, the bags' or the paper doll's (`0x6e2efb` with + /// `0x6e2f70`), deduped (`0x6e2ef4`). + CooldownQuery, + /// The quest log's leaderboard and reward getters (`0x4e05e0`, `0x4e0bb3`, `0x4e0da3` with + /// `0x4e0830`), one per entry as the VM keeps its waits. + QuestLog, + /// A tooltip build's miss (`0x52e530`, `0x52f820`), one per entry as the VM keeps each + /// tooltip's wait. + Tooltip, + /// A group loot roll's or one of its lines', by the wait's serial: a start's (`0x61b40e` with + /// `0x61b460`), an announcement's (`0x61c047` with `0x61c4b0`), a result's (`0x61b96a` with + /// `0x61bd50`) or an all-passed's (`0x61b5c0` with `0x61b7d0`). + LootRoll(u32), + /// The action bar's, asked by an item slot's icon, count and spell lookups (`0x4e6b10`, + /// `0x4e6d69`, `0x4e5b30` with `0x4e5b80`), deduped. + ActionSlots, + /// A game object plate's key line whose item was not cached (`0x52aca6` with + /// `CGTooltip::OnLockKeyItem` `0x52ad10`), deduped (`0x52ac8b`). + LockKey, + /// A refused cast's reagent or tool line whose item was not cached (`0x6e1ea4` with + /// `ShowItemCastFailure 0x6e29b0` and the reason), one per refusal; the spell picks the + /// line's message as its first pass would. + CastFailure { spell: u32, reason: u8 }, } impl Items { @@ -555,9 +593,23 @@ impl Items { /// A lookup of `entry` that missed registered `callback`. pub(crate) fn wait(&self, entry: u32, callback: RecordCallback) { + if self.walk_takes(entry, callback, false) { + return; + } self.callbacks.lock_recover().push((entry, callback)); } + /// [`Self::wait`] with the dedupe flag set (`0x55bbb3`): no second `callback` on `entry`. + pub(crate) fn wait_once(&self, entry: u32, callback: RecordCallback) { + if self.walk_takes(entry, callback, true) { + return; + } + let mut callbacks = self.callbacks.lock_recover(); + if !callbacks.contains(&(entry, callback)) { + callbacks.push((entry, callback)); + } + } + /// The answer for `entry` landed, or refused it: the callbacks waiting on it, in the order /// they asked, spent either way. pub(crate) fn take_callbacks(&mut self, entry: u32) -> Vec { @@ -573,22 +625,129 @@ impl Items { taken } + /// A refusal of `entry` begins walking `list` ([`RefusalWalk`]). + pub(crate) fn begin_refusal_walk(&self, entry: u32, list: Vec) { + let at = crate::lanes::mark(); + self.walks.lock_recover().now = Some(RefusalWalk { + entry, + list, + next: 0, + last: false, + from: at, + last_from: at, + to: at, + tail: Vec::new(), + extended: false, + }); + } + + /// The walk's next callback, with what its callbacks added so far. + pub(crate) fn next_walk_step(&self) -> Option { + let mut walks = self.walks.lock_recover(); + let walk = walks.now.as_mut()?; + let callback = *walk.list.get(walk.next)?; + walk.next += 1; + walk.last = walk.next == walk.list.len(); + if walk.last { + walk.last_from = crate::lanes::mark(); + } + Some(callback) + } + + /// The walk ended and the node went (`0x55bed2`). Whether a signal a callback with a next + /// raised may still add to it, through a listener the drain runs later: then the walk goes on + /// behind its signals ([`Self::take_walk_tail`]). + pub(crate) fn end_refusal_walk(&self) -> bool { + let mut walks = self.walks.lock_recover(); + let Some(mut walk) = walks.now.take() else { + return false; + }; + walk.to = crate::lanes::mark(); + let goes_on = walk.last_from != walk.from; + walks.done.push(walk); + goes_on + } + + /// What the listeners of the walk of `entry` that began at `from` added, spent, to walk on with + /// after its signals: the reference's listeners run inside the callbacks. + pub(crate) fn take_walk_tail( + &self, + entry: u32, + from: crate::lanes::Mark, + ) -> Vec { + let mut walks = self.walks.lock_recover(); + walks + .done + .iter_mut() + .find(|w| w.entry == entry && w.from == from) + .map(|w| std::mem::take(&mut w.tail)) + .unwrap_or_default() + } + + /// The mark the walk running now began at. + pub(crate) fn walk_began(&self) -> Option { + self.walks.lock_recover().now.as_ref().map(|w| w.from) + } + + /// The drain fired what the walks raised. Locked, so the drain's end leaves the records' + /// change detection alone. + pub(crate) fn end_refusal_walks(&self) { + self.walks.lock_recover().done.clear(); + } + + /// Whether a lookup of `entry` now runs inside its refusal's walk: in a callback, or in a + /// listener of a signal one raised. Its lookup finds the dying node, so it sends nothing + /// (`0x556aa0`). + fn in_refusal_walk(&self, entry: u32) -> bool { + let walks = self.walks.lock_recover(); + walks.now.as_ref().is_some_and(|w| w.entry == entry) + || walks + .done + .iter() + .any(|w| w.entry == entry && crate::lanes::firing_between(w.from, w.to)) + } + + /// A lookup inside a refusal's walk of `entry` registering `callback` (`once`: with the dedupe + /// flag): linked for the walk to reach, or dropped, as [`RefusalWalk`] says. Whether the walk + /// took it, so it is not kept as a wait. + fn walk_takes(&self, entry: u32, callback: RecordCallback, once: bool) -> bool { + let mut walks = self.walks.lock_recover(); + let RefusalWalks { now, done } = &mut *walks; + if let Some(walk) = now.as_mut().filter(|w| w.entry == entry) { + if !walk.last && !(once && walk.list.contains(&callback)) { + walk.list.push(callback); + } + return true; + } + let Some(walk) = done + .iter_mut() + .rev() + .find(|w| w.entry == entry && crate::lanes::firing_between(w.from, w.to)) + else { + return false; + }; + let with_next = crate::lanes::firing_between(walk.from, walk.last_from); + let reached = with_next || walk.extended; + let seen = once && (walk.list.contains(&callback) || walk.tail.contains(&callback)); + if reached && !seen { + walk.tail.push(callback); + walk.extended |= with_next; + } + true + } + /// Drop every waiting callback of `kind`, as a cancel by callback drops its registrations /// (`0x55c0c0`). pub(crate) fn cancel_waits(&self, kind: RecordCallback) { self.callbacks.lock_recover().retain(|&(_, cb)| cb != kind); } - /// Run `callback` for the record of `entry`, answered (`found`) or refused, with the VM. - pub(crate) fn run_with_vm(&self, entry: u32, callback: RecordCallback, found: bool) { - self.vm_callbacks + /// `DBCache::CancelCallback` (`0x55c0c0`): `callback`'s registrations off the pending record + /// of `entry` alone. + pub(crate) fn cancel_wait(&self, entry: u32, callback: RecordCallback) { + self.callbacks .lock_recover() - .push((entry, callback, found)); - } - - /// The callbacks [`Self::run_with_vm`] queued, in order, spent. - pub(crate) fn take_vm_callbacks(&self) -> Vec<(u32, RecordCallback, bool)> { - std::mem::take(&mut *self.vm_callbacks.lock_recover()) + .retain(|&waiting| waiting != (entry, callback)); } /// An entry change asked for the record of `entry` with the callback `0x5d96b0`. @@ -643,6 +802,9 @@ impl Items { /// The template for `entry` if known, read as `ask` says; an ask goes once while in flight /// (`guid` rides along, `0` for template-only). A refused entry is also `None`. pub(crate) fn template(&self, entry: u32, guid: u64, ask: Ask<'_>) -> Option<&ItemInfo> { + if !matches!(ask, Ask::Read) && self.in_refusal_walk(entry) { + return None; + } self.templates.read(entry, ask, |commands| { Self::send_template(entry, guid, commands) }) @@ -665,9 +827,8 @@ impl Items { self.templates.answered(entry) } - /// Whether the server refused `entry`, not still pending; the cast-fail redisplay then shows - /// the reference's `"UNKNOWN"` instead of waiting (`0x6e29b0` runs on the status-0 callback and - /// finds no record, `0x6e2a49`). + /// Whether the server refused `entry` and nothing has asked since, not still pending: the + /// status-0 answer its waiters were told. pub(crate) fn template_answered_unknown(&self, entry: u32) -> bool { self.templates.answered_unknown(entry) } @@ -685,7 +846,7 @@ impl Items { self.templates.insert(entry, info); } // A refusal moves the generation too: "still asking" to "unknown" is a display - // transition for the cast-fail redisplay. + // transition. None => { if self.templates.refuse(entry) == crate::query_cache::Refused::Record { self.note_change(entry, false); @@ -697,7 +858,14 @@ impl Items { /// `entry`'s record landed (`held`) or went. fn note_change(&mut self, entry: u32, held: bool) { self.change_count += 1; - self.changes.insert(entry, (self.change_count, held)); + self.changes.insert(entry, (self.change_count, held, false)); + } + + /// The VM's copy took `entry`'s last change at its answer, so the feed need not push it again. + pub(crate) fn vm_took(&mut self, entry: u32) { + if let Some(change) = self.changes.get_mut(&entry) { + change.2 = true; + } } /// How many record changes have been made: a reader's cursor for [`Self::changed_since`]. @@ -705,12 +873,13 @@ impl Items { self.change_count } - /// Each entry whose record landed or went after change `count`, with whether it is held now. + /// Each entry whose record landed or went after change `count` and that the VM's copy did not + /// take at its answer, with whether it is held now. pub(crate) fn changed_since(&self, count: u64) -> impl Iterator + '_ { self.changes .iter() - .filter(move |(_, &(at, _))| at > count) - .map(|(&entry, &(_, held))| (entry, held)) + .filter(move |(_, &(at, _, took))| at > count && !took) + .map(|(&entry, &(_, held, _))| (entry, held)) } /// The template store, the one [`crate::wdb`] saves. @@ -732,8 +901,7 @@ impl Items { self.templates.clear(); } - /// Bumped by every landed answer, for consumers besides the drain; the stand-in for the - /// reference's `DBCACHECALLBACK` redisplay (`0x6e29b0`). + /// Bumped by every landed answer, for consumers besides the drain. pub(crate) fn template_epoch(&self) -> u64 { self.templates.generation() } @@ -743,7 +911,7 @@ impl Items { self.templates.iter().map(|(&id, _)| id).collect() } - /// Disconnect: drop the callbacks waiting on asks or on the VM, and the queued enchant times, + /// Disconnect: drop the callbacks waiting on asks and the queued enchant times, /// keep the templates; [`crate::wdb`] clears their in-flight asks. The item objects and their /// countdowns go with the index's sweep. pub(crate) fn clear_session(&mut self) { @@ -752,10 +920,6 @@ impl Items { .get_mut() .unwrap_or_else(|e| e.into_inner()) .clear(); - self.vm_callbacks - .get_mut() - .unwrap_or_else(|e| e.into_inner()) - .clear(); } } @@ -987,19 +1151,11 @@ mod tests { assert_ne!(items.template_epoch(), t0, "a landing is"); } - /// The step count is bounded, not exact: the test cannot pin the sub-second phase. + /// The display reads floor to the second, and a cleared cell reads none. #[test] - fn countdown_steps_move_by_displayable_seconds() { - let now = Instant::now(); + fn the_display_reads_floor_to_the_second() { let mut c = Countdowns::default(); - assert_eq!(c.steps(now), 0, "no deadlines, no steps"); - assert!(c.set_enchant(1, 90)); - let steps = c.steps(Instant::now()); - assert!( - (90..=91).contains(&steps), - "a 90 s deadline contributes floor(secs)+1, got {steps}" - ); let shown = c.enchant_remaining_display_ms(1).unwrap(); assert_eq!(shown % 1000, 0, "the display read is second-floored"); assert!(shown <= 90_000); @@ -1008,15 +1164,9 @@ mod tests { let shown = c.lifetime_remaining_display_ms().expect("parked"); assert_eq!(shown % 1000, 0); assert!(shown <= 1_800_000); - let steps = c.steps(Instant::now()); - assert!( - (1890..=1892).contains(&steps), - "both cells step, got {steps}" - ); assert!(c.set_enchant(1, 0)); c.set_lifetime(0); - assert_eq!(c.steps(Instant::now()), 0, "cleared cells, terms gone"); assert_eq!(c.enchant_remaining_display_ms(1), None); assert_eq!(c.lifetime_remaining_ms(), None); } @@ -1210,7 +1360,7 @@ mod tests { .merge(ObjectFields::from_pairs(&[(14, 4)])); assert_eq!(world.run_system(read).unwrap(), (Some(117), Some(4), true)); assert!(!world.run_system(read).unwrap().2); - // A countdown landing is the item's own change, and its cell joins the step sum. + // A countdown landing is the item's own change. world .get_mut::(e) .expect("every item carries its cells") @@ -1219,10 +1369,6 @@ mod tests { world.run_system(read).unwrap().2, "a landing moves the watch" ); - let steps = world - .run_system_once(|c: ItemChanges| c.countdown_steps()) - .unwrap(); - assert!((90..=91).contains(&steps), "got {steps}"); // The destroy: the index drops the guid, the entity goes, the watch moves once more. world.resource_mut::().0.remove(&GUID); world.despawn(e); diff --git a/crates/benilla-app/src/lanes.rs b/crates/benilla-app/src/lanes.rs index 96160e1f9..4389ec637 100644 --- a/crates/benilla-app/src/lanes.rs +++ b/crates/benilla-app/src/lanes.rs @@ -3,10 +3,11 @@ //! handler whole (`0x537aa0`, `0x537ae5`), and a handler's events fire inside it, every listener //! before the signal returns (`0x703e50`, `0x703f50`). Here a handler queues what it raises on a //! lane, a producer's queue that stamps each item from one clock as it is pushed ([`stamp`]). -//! Once every feed has pushed what the events' listeners read, as the update handler writes every -//! block of its packet before its notify pass (`0x465277`), [`fire_in_order`] fires the lowest -//! stamp across the lanes, so the events come out in the order their handlers raised them, -//! whichever lane holds them. +//! Once a packet's handlers are done, the dispatch fires the lowest stamp across the lanes until +//! none is left ([`flush`]), so the events come out in the order their handlers raised them, +//! whichever lane holds them, and each listener reads, and sends into, the world its packet left, +//! ahead of the next packet's handler. What is pushed after the dispatch, by the feeds and the +//! frame's systems, fires in the frame's drain ([`fire_in_order`]). //! //! An item pushed while another fires is stamped under it ([`firing`]) and fires straight after //! it, ahead of everything stamped before it, as a signal raised inside a listener runs to its @@ -21,8 +22,8 @@ use bevy::ecs::system::SystemId; use bevy::prelude::*; /// How deep a stamp nests: an item pushed by one fired that deep is stamped as a fresh one and -/// waits for the next drain, so a listener that queues an item each time it hears one cannot -/// hold the frame. +/// waits for the next drain, the next packet's flush or the frame's, so a listener that queues an +/// item each time it hears one cannot hold the dispatch. /// /// Deviation: the reference has no such cap. A signal raised inside a listener runs nested in /// its call, bounded by `luaD_call`'s C-stack count of 200 (`0x6f65ae`), whose error ends the @@ -104,11 +105,15 @@ static CLOCK: AtomicU64 = AtomicU64::new(1); thread_local! { /// The item firing on this thread, which what is pushed meanwhile nests under. static FIRING: Cell> = const { Cell::new(None) }; + /// The stamps taken on this thread: what a firing pushed, never another thread's, whose + /// stamps nest under nothing it fires. + static TAKEN: Cell = const { Cell::new(0) }; } /// The next stamp: a fresh one, or with an item firing, one nested under it. pub(crate) fn stamp() -> Stamp { let n = CLOCK.fetch_add(1, Ordering::Relaxed); + TAKEN.set(TAKEN.get() + 1); match FIRING.get() { Some(cause) if usize::from(cause.len) < DEPTH => cause.child(n), _ => Stamp::root(n), @@ -120,9 +125,43 @@ pub(crate) fn firing_now() -> Option { FIRING.get() } +/// Whether the item firing on this thread was pushed between `from` and `to`, or nests under one +/// that was: it is part of what ran between the two marks. +pub(crate) fn firing_between(from: Mark, to: Mark) -> bool { + FIRING + .get() + .is_some_and(|s| s.path().iter().any(|n| (from.0..to.0).contains(n))) +} + thread_local! { /// A close core is running held behind a lane: what a core it re-enters signals is its. static BEHIND: Cell = const { Cell::new(false) }; + /// The net dispatch is running the frame's packet handlers on this thread ([`at_packets`]). + static AT_PACKETS: Cell = const { Cell::new(false) }; +} + +/// Run `f` as the dispatch of the frame's packets, each handler whole in wire order: a close core +/// a handler runs with no item firing takes its place on its lane there ([`waits_behind`]), so its +/// signals fire after every earlier packet's and ahead of every later one's, as the reference's +/// fire inside the handler that closes (`0x537ae5`, `0x703e50`). +pub(crate) fn at_packets(f: impl FnOnce() -> R) -> R { + let _restore = AtPackets::set(true); + f() +} + +/// [`AT_PACKETS`] as it stood before [`AtPackets::set`], put back at the drop. +struct AtPackets(bool); + +impl AtPackets { + fn set(now: bool) -> Self { + Self(AT_PACKETS.replace(now)) + } +} + +impl Drop for AtPackets { + fn drop(&mut self) { + AT_PACKETS.set(self.0); + } } /// Where [`behind`] ran its core. @@ -136,11 +175,11 @@ pub(crate) enum Behind { Nested, } -/// Run a close `core` behind a lane whose head is `head`: at once unless the lane holds an item -/// stamped before the item firing now (any item, with none firing), else with the world's VM held, -/// what it signalled parked under a key `park` queues on the lane, so a close never fires ahead of -/// the open it closes. A core it re-enters, as a release re-enters its close (`0x493310`), runs -/// inside the hold. +/// Run a close `core` behind a lane whose head is `head`: at once unless it waits +/// ([`waits_behind`]), else with the world's VM held, what it signalled parked under a key `park` +/// queues on the lane, so a close never fires ahead of the open it closes, nor ahead of an earlier +/// packet's signals when a handler runs it. A core it re-enters, as a release re-enters its close +/// (`0x493310`), runs inside the hold. pub(crate) fn behind( world: &mut World, head: Option, @@ -167,21 +206,26 @@ pub(crate) fn behind( Behind::Parked } -/// Whether a close run now must wait behind a lane whose head is `head`: the lane holds an item -/// stamped before the item firing now (any item, with none firing), and no other core's hold -/// already takes what it signals ([`behind`]). +/// Whether a close run now must wait behind a lane whose head is `head`, as no other core's hold +/// already takes what it signals ([`behind`]): with an item firing, the lane holds one stamped +/// before it; with none, a packet handler runs it ([`at_packets`]), whose place is the lane's +/// next stamp, or the lane holds any item. pub(crate) fn waits_behind(head: Option) -> bool { - !BEHIND.get() && head.is_some_and(|head| firing_now().is_none_or(|now| head < now)) + !BEHIND.get() + && match firing_now() { + Some(now) => head.is_some_and(|head| head < now), + None => AT_PACKETS.get() || head.is_some(), + } } /// Run `f` as the firing of the item stamped `at`, so what it pushes nests under the item; with -/// whether anything was stamped meanwhile, after which the drain takes the lowest stamp again. +/// whether it stamped anything, after which the drain takes the lowest stamp again. pub(crate) fn firing(at: Stamp, f: impl FnOnce() -> R) -> (R, bool) { - let before = CLOCK.load(Ordering::Relaxed); + let before = TAKEN.get(); let outer = FIRING.replace(Some(at)); - let r = f(); + let r = benilla_ui::script::origin::within(benilla_ui::script::origin::Origin::Lane, f); FIRING.set(outer); - (r, CLOCK.load(Ordering::Relaxed) != before) + (r, TAKEN.get() != before) } /// What a lane's firing may fire, among the stamps whose outermost push came before the drain @@ -229,13 +273,15 @@ pub(crate) fn system_access Option, fire: SystemId>, begin: Option, reads: Option, + raises: Option bool>, } /// Every lane, in registration order. @@ -316,6 +362,29 @@ pub(crate) fn measure(world: &mut World) { #[derive(Resource, Default)] struct DrainEnds(Vec); +/// What runs once ahead of the frame's drain alone ([`fire_in_order`]), never ahead of a +/// [`flush`]: a pass that counts frames. +#[derive(Resource, Default)] +struct FrameBegins(Vec); + +/// What runs where a span of packets begins ([`span_starts`]): a log's starting state, read +/// before the span's first packet moves it. +#[derive(Resource, Default)] +struct SpanStarts(Vec); + +thread_local! { + /// The flushes that fired ([`flush`]) and the lane firings every drain ran, counted for the + /// `drn` trace ([`tally`]). + static FLUSHES: Cell = const { Cell::new(0) }; + static FIRED: Cell = const { Cell::new(0) }; +} + +/// The flushes fired and the lane firings run on this thread so far: a caller takes the +/// difference across what it measures. +pub(crate) fn tally() -> (u64, u64) { + (FLUSHES.get(), FIRED.get()) +} + /// The drain's place: after every feed in [`crate::ui_script::UiFeed`] has pushed, and before /// the tick ([`crate::ui_script::UiTick`]). #[derive(SystemSet, Debug, Clone, Copy, PartialEq, Eq, Hash)] @@ -345,6 +414,17 @@ pub(crate) trait LaneApp { /// Run `end` once after each drain, whether it fired every item or stopped. fn add_drain_end(&mut self, end: fn(&mut World)) -> &mut Self; + + /// Run `begin` once ahead of the frame's drain, after the lanes' own begins. + fn add_frame_begin(&mut self, begin: fn(&mut World)) -> &mut Self; + + /// Run `start` where each span of packets begins ([`span_starts`]). + fn add_span_start(&mut self, start: fn(&mut World)) -> &mut Self; + + /// The lane `name`, whose head waits at the origin while its log holds entries, raises an + /// event when `raises` holds, which makes it [`due`]; a log that raises nothing waits for the + /// next drain that fires. + fn lane_raises(&mut self, name: &'static str, raises: fn(&World) -> bool) -> &mut Self; } impl LaneApp for App { @@ -356,6 +436,7 @@ impl LaneApp for App { begin: Option, ) -> &mut Self { if self.world().get_resource::().is_none() { + crate::ui_script::raise_origin::arm_each_frame(self); self.init_resource::() .configure_sets( Update, @@ -386,6 +467,7 @@ impl LaneApp for App { fire, begin, reads: None, + raises: None, }); self } @@ -415,19 +497,97 @@ impl LaneApp for App { self.world_mut().resource_mut::().0.push(end); self } + + fn add_frame_begin(&mut self, begin: fn(&mut World)) -> &mut Self { + self.init_resource::(); + self.world_mut().resource_mut::().0.push(begin); + self + } + + fn add_span_start(&mut self, start: fn(&mut World)) -> &mut Self { + self.init_resource::(); + self.world_mut().resource_mut::().0.push(start); + self + } + + fn lane_raises(&mut self, name: &'static str, raises: fn(&World) -> bool) -> &mut Self { + if let Some(lane) = self + .world_mut() + .get_resource_mut::() + .and_then(|lanes| lanes.into_inner().0.iter_mut().find(|l| l.name == name)) + { + lane.raises = Some(raises); + } + self + } } -/// Fire every lane's items in stamp order: each lane's `begin`, then, while any lane's head was -/// stamped before the drain began, the lane holding the lowest fires up to the next lane's head, -/// its Lua run with the call host lent. A lane that fires nothing (no VM) ends the drain, its -/// items waiting for the next. +/// The frame's drain: what the feeds and the frame's systems pushed after the dispatch, and what +/// no flush fired, in stamp order, with the frame's begins ahead ([`fire_through`]). pub(crate) fn fire_in_order(world: &mut World) { + fire_through(world, true); +} + +/// Whether some lane holds what a drain would fire now: a head that is an item, or a log's start +/// at the origin whose log raises something ([`LaneApp::lane_raises`]). A log that raises nothing +/// keeps its entries for the next drain that fires, whose rewind takes them all in stamp order. +pub(crate) fn due(world: &World) -> bool { + world.get_resource::().is_some_and(|lanes| { + lanes.0.iter().any(|lane| { + (lane.peek)(world).is_some_and(|head| { + head != Stamp::origin() || lane.raises.is_some_and(|raises| raises(world)) + }) + }) + }) +} + +/// The lanes fired where a handler's signals would have fired inside its packet: every item +/// stamped so far, in stamp order, when the in-game interface is up and some lane is [`due`], +/// then the next span's starts. Whether it fired. +pub(crate) fn flush(world: &mut World) -> bool { + if !crate::ui_script::ingame_ui_up_in(world) || !due(world) { + return false; + } + FLUSHES.set(FLUSHES.get() + 1); + fire_through(world, false); + span_starts(world); + true +} + +/// Where a span of packets begins: each log reads its starting state ([`LaneApp::add_span_start`]). +pub(crate) fn span_starts(world: &mut World) { + let starts = world + .get_resource::() + .map(|s| s.0.clone()) + .unwrap_or_default(); + for start in starts { + start(world); + } +} + +/// Fire every lane's items in stamp order: each lane's `begin`, the frame's begins when `frame`, +/// then, while any lane's head was stamped before the drain began, the lane holding the lowest +/// fires up to the next lane's head, its Lua run with the call host lent; then the drain's ends. +/// A lane that fires nothing (no VM) ends the drain, its items waiting for the next. Its listeners +/// run outside the packets' dispatch ([`at_packets`]), as a signal's listeners run inside their +/// signal's call (`0x703e50`), not as a handler. +fn fire_through(world: &mut World, frame: bool) { let Some(lanes) = world.remove_resource::() else { return; }; + let _restore = AtPackets::set(false); for begin in lanes.0.iter().filter_map(|l| l.begin) { begin(world); } + if frame { + let begins = world + .get_resource::() + .map(|b| b.0.clone()) + .unwrap_or_default(); + for begin in begins { + begin(world); + } + } let fence = CLOCK.load(Ordering::Relaxed); loop { let heads: Vec> = lanes @@ -459,7 +619,12 @@ pub(crate) fn fire_in_order(world: &mut World) { fence, }; let lane = &lanes.0[i]; - if let Err(e) = world.run_system_with(lane.fire, until) { + FIRED.set(FIRED.get() + 1); + let fired = + benilla_ui::script::origin::within(benilla_ui::script::origin::Origin::Lane, || { + world.run_system_with(lane.fire, until) + }); + if let Err(e) = fired { error!("lanes: `{}` did not fire: {e}", lane.name); break; } @@ -478,9 +643,13 @@ pub(crate) fn fire_in_order(world: &mut World) { } } +#[cfg(test)] +mod account_data_live_tests; #[cfg(test)] mod action_live_tests; #[cfg(test)] +mod alert_live_tests; +#[cfg(test)] mod arrival_live_tests; #[cfg(test)] mod auction_live_tests; @@ -499,14 +668,26 @@ mod book_live_tests; #[cfg(test)] mod cast_live_tests; #[cfg(test)] +mod chat_clock_live_tests; +#[cfg(test)] +mod close_parked_tests; +#[cfg(test)] mod cooldown_live_tests; #[cfg(test)] +mod deactivate_live_tests; +#[cfg(test)] +mod death_live_tests; +#[cfg(test)] mod dialog_live_tests; #[cfg(test)] mod duration_live_tests; #[cfg(test)] +mod follow_live_tests; +#[cfg(test)] mod gossip_live_tests; #[cfg(test)] +mod group_live_tests; +#[cfg(test)] mod group_view_tests; #[cfg(test)] mod guard_tests; @@ -517,12 +698,24 @@ mod host_read_tests; #[cfg(test)] mod inspect_live_tests; #[cfg(test)] +mod instance_live_tests; +#[cfg(test)] mod item_live_tests; #[cfg(test)] mod item_tests; #[cfg(test)] +mod item_text_live_tests; +#[cfg(test)] +mod item_view_live_tests; +#[cfg(test)] +mod lock_live_tests; +#[cfg(test)] +mod logout_live_tests; +#[cfg(test)] mod loot_live_tests; #[cfg(test)] +mod loot_roll_live_tests; +#[cfg(test)] mod mail_live_tests; #[cfg(test)] mod merchant_live_tests; @@ -535,10 +728,16 @@ mod pet_live_tests; #[cfg(test)] mod petition_live_tests; #[cfg(test)] +mod plate_live_tests; +#[cfg(test)] +mod profession_live_tests; +#[cfg(test)] mod quest_log_live_tests; #[cfg(test)] mod quiet_tests; #[cfg(test)] +mod record_callback_tests; +#[cfg(test)] mod reputation_live_tests; #[cfg(test)] mod requirement_live_tests; @@ -547,6 +746,8 @@ mod selection_live_tests; #[cfg(test)] mod social_live_tests; #[cfg(test)] +mod spell_slot_live_tests; +#[cfg(test)] mod stable_live_tests; #[cfg(test)] mod stance_live_tests; @@ -563,16 +764,31 @@ mod tests; #[cfg(test)] mod token_live_tests; #[cfg(test)] +mod tooltip_live_tests; +#[cfg(test)] mod trade_live_tests; #[cfg(test)] mod trainer_live_tests; #[cfg(test)] +mod tutorial_live_tests; +#[cfg(test)] +mod ui_error_live_tests; +#[cfg(test)] mod unit_feed_live_tests; #[cfg(test)] mod unit_live_tests; #[cfg(test)] mod unit_view_tests; +#[cfg(test)] +mod world_map_live_tests; +#[cfg(test)] +mod world_map_update_tests; +#[cfg(test)] +mod world_state_live_tests; +#[cfg(test)] +mod worn_live_tests; + #[cfg(test)] mod unit_tests { use super::*; @@ -696,6 +912,103 @@ mod unit_tests { ); } + /// What ran around the drains, in order. + #[derive(Resource, Default)] + struct Around(Vec<&'static str>); + + /// A lane whose log's start waits at the origin, as the views' do; whether its log raises. + #[derive(Resource, Default)] + struct OriginLog { + logged: bool, + raises: bool, + } + + fn origin_peek(world: &World) -> Option { + world.resource::().logged.then(Stamp::origin) + } + + fn origin_fire(In(_): In, mut log: ResMut, mut fired: ResMut) { + log.logged = false; + fired.0.push("origin"); + } + + /// The toy lanes with the origin log behind them, the hooks noting each run, and the in-game + /// interface up. + fn hooked() -> App { + let mut app = app(&[]); + app.init_resource::() + .init_resource::() + .insert_resource(State::new(crate::client_state::ClientState::InWorld)) + .add_lane("origin", origin_peek, origin_fire, None) + .lane_raises("origin", |world| world.resource::().raises) + .add_frame_begin(|world| world.resource_mut::().0.push("frame")) + .add_span_start(|world| { + let at_packets = AT_PACKETS.get(); + world.resource_mut::().0.push(if at_packets { + "span at packets" + } else { + "span" + }); + }) + .add_drain_end(|world| { + let at_packets = AT_PACKETS.get(); + world.resource_mut::().0.push(if at_packets { + "end at packets" + } else { + "end" + }); + }); + app + } + + fn around(app: &mut App) -> Vec<&'static str> { + std::mem::take(&mut app.world_mut().resource_mut::().0) + } + + /// A lane is due for a head that is an item, and for a log's start at the origin only when its + /// log raises: a log that raises nothing waits for the next drain that fires. + #[test] + fn a_lane_is_due_for_an_item_or_a_raising_log() { + let mut app = hooked(); + assert!(!due(app.world()), "nothing held"); + app.world_mut().resource_mut::().logged = true; + assert!(!due(app.world()), "a log that raises nothing"); + app.world_mut().resource_mut::().raises = true; + assert!(due(app.world()), "a log that raises"); + app.world_mut().resource_mut::().raises = false; + push::<1>(app.world_mut(), "a"); + assert!(due(app.world()), "an item"); + } + + /// A flush fires only when due and the interface is up, outside the packets' dispatch even + /// inside it, then runs the next span's starts back in the dispatch; the frame's begins are + /// the frame's drain's alone, and each drain runs its ends. + #[test] + fn a_flush_fires_when_due_then_starts_the_span() { + let mut app = hooked(); + app.world_mut().resource_mut::().logged = true; + let (flushes, fired) = tally(); + assert!(!at_packets(|| flush(app.world_mut())), "not due"); + assert!(around(&mut app).is_empty()); + push::<0>(app.world_mut(), "a"); + app.world_mut() + .remove_resource::>(); + assert!(!flush(app.world_mut()), "no interface up"); + app.world_mut() + .insert_resource(State::new(crate::client_state::ClientState::InWorld)); + assert!(at_packets(|| flush(app.world_mut()))); + assert_eq!( + std::mem::take(&mut app.world_mut().resource_mut::().0), + ["origin", "a"], + "the log's start and the item, in stamp order" + ); + assert_eq!(around(&mut app), ["end", "span at packets"]); + assert_eq!(tally(), (flushes + 1, fired + 2)); + push::<1>(app.world_mut(), "b"); + assert_eq!(drain(&mut app), ["b"]); + assert_eq!(around(&mut app), ["frame", "end"], "the frame's drain"); + } + /// benilla's own choice, not the reference's ([`DEPTH`]'s `Deviation:`): past four levels a /// pushed item is stamped fresh and waits for the next drain. #[test] diff --git a/crates/benilla-app/src/lanes/account_data_live_tests.rs b/crates/benilla-app/src/lanes/account_data_live_tests.rs new file mode 100644 index 000000000..2026ef241 --- /dev/null +++ b/crates/benilla-app/src/lanes/account_data_live_tests.rs @@ -0,0 +1,455 @@ +//! The account-data readers as a listener reads them: each runs inside the handler that settles +//! its section, the digests' check (`0x5afa10` → `0x5afe50` at `0x5afaca`, from `0x5af8e0`) or a +//! download (`0x5afc60` → `0x5afe50` at `0x5afd19`), so a listener of an earlier packet of the +//! frame reads the section as it stood, and one of a later packet reads what the reader read. + +use benilla_protocol::field::FIELD_UNIT_HEALTH; +use benilla_protocol::messages::{AccountDataDigest, UpdateAccountData, ACCOUNT_DATA_SECTIONS}; +use benilla_protocol::{EntityKind, SessionEvent}; +use benilla_ui::script::UiScript; +use bevy::prelude::*; +use crossbeam_channel::{Receiver, Sender}; + +use super::unit_view_tests::{created, wire_packets}; +use crate::local_state::test_env::{EnvGuard, ENV_LOCK}; +use crate::net::ClientCommand; + +const ME: u64 = 0x7; + +/// The whole client, headless, in the world, over a state folder of its own. +struct Client { + app: App, + inbound: Sender, + sent: Receiver, + home: std::path::PathBuf, + _env: (EnvGuard, EnvGuard), +} + +impl Client { + /// One frame of the client's, with `packets` in the inbound channel, each one packet. + fn frame(&mut self, packets: Vec>) { + for ev in wire_packets(packets) { + self.inbound.send(ev).expect("the inbound channel"); + } + self.app.update(); + } + + /// What the spy heard since the last call. + fn seen(&mut self) -> Vec { + crate::script_calls::eval_in_vm(self.app.world(), "local s = Seen Seen = {} return s") + } + + /// Our player's create, whose arrival loads the staged bar (`0x5deae2`), and a quiet frame. + fn arrive(&mut self) { + self.frame(vec![vec![created( + ME, + EntityKind::Player, + &[(FIELD_UNIT_HEALTH, 100)], + )]]); + self.frame(vec![]); + } + + /// The `CMSG_SET_ACTION_BUTTON`s sent since the last call, `(wire slot, word)`. + fn placed(&mut self) -> Vec<(u8, u32)> { + self.sent + .try_iter() + .filter_map(|c| match c { + ClientCommand::SetActionButton { button, packed } => Some((button, packed)), + _ => None, + }) + .collect() + } + + /// The bar's words, `(wire slot, word)` in slot order. + fn bar(&self) -> Vec<(u8, u32)> { + let slots = self.app.world().resource::(); + let mut words: Vec<(u8, u32)> = slots + .buttons + .values() + .map(|b| (b.slot, (u32::from(b.kind) << 24) | b.action)) + .collect(); + words.sort_unstable(); + words + } +} + +impl Drop for Client { + fn drop(&mut self) { + std::fs::remove_dir_all(&self.home).ok(); + } +} + +/// The client in the world as `Probeone`, its interface loaded with every account-data reader +/// registered while its section is pending, as a world entry leaves them (`0x5af840`), our player +/// arrived, and a spy whose line for each of `events` carries its name and what `Probe()` answers +/// then. `files` are written first, each `(path, text)`. +fn client( + name: &str, + events: &[&str], + probe: &str, + files: impl FnOnce() -> Vec<(std::path::PathBuf, &'static str)>, +) -> Client { + let mut c = unarrived(name, events, probe, files); + c.arrive(); + c.seen(); + c +} + +/// [`client`] before our player's create: the bar as the game entry leaves it, empty. +fn unarrived( + name: &str, + events: &[&str], + probe: &str, + files: impl FnOnce() -> Vec<(std::path::PathBuf, &'static str)>, +) -> Client { + let home = + std::env::temp_dir().join(format!("benilla-acct-live-{name}-{}", std::process::id())); + std::fs::remove_dir_all(&home).ok(); + let env = ( + EnvGuard::unset("WOW_CAPTURE"), + EnvGuard::set("BENILLA_HOME", home.to_str().unwrap()), + ); + for (path, text) in files() { + crate::local_state::write_atomic(&path, text).unwrap(); + } + let mut app = crate::game_plugins::schedule_tests::headless_client(); + app.insert_resource(bevy::ecs::error::DefaultErrorHandler( + bevy::ecs::error::ignore, + )); + let (tx, sent) = crossbeam_channel::unbounded(); + app.insert_resource(crate::net::NetCommands(tx)); + let (inbound, rx) = crossbeam_channel::unbounded(); + app.insert_resource(crate::net::NetEvents::for_test(rx)); + app.insert_resource(crate::glue_session::roster::Roster::with_pending_pick( + vec![crate::glue_session::roster::test_character(ME, "Probeone")], + ME, + )); + app.update(); + assert!( + app.world() + .resource::() + .pending(crate::account_data::LAYOUT), + "the sections pend until the server's digests" + ); + let mut script = UiScript::new().expect("a VM"); + let events: Vec = events.iter().map(|e| format!("{e:?}")).collect(); + script + .run(&format!( + r#" + Seen = {{}} + local f = CreateFrame("Frame") + for _, e in ipairs({{{}}}) do + f:RegisterEvent(e) + end + f:SetScript("OnEvent", function() + table.insert(Seen, event .. ":" .. Probe()) + end) + local p = CreateFrame("Frame", "LayoutProbe") + p:SetWidth(100) p:SetHeight(100) p:SetPoint("BOTTOMLEFT", 0, 0) + p:SetMovable(true) p:SetResizable(true) + function Probe() {probe} end + "#, + events.join(", ") + )) + .unwrap(); + register_readers(app.world_mut(), &mut script); + app.insert_non_send_resource(script); + app.insert_resource(State::new(crate::client_state::ClientState::InWorld)); + benilla_world::world_point::init_world_point_resources(app.world_mut()); + app.world_mut().resource_mut::().0 = Some(ME); + Client { + app, + inbound, + sent, + home, + _env: env, + } +} + +/// The interface load's registrations, as `CGGameUI::Initialize` makes them (`0x4900c2` the +/// layout's, `0x4900c7` → `0x4b62b0` the bindings', `0x4900d1` → `0x4f0a70` the macros'). +fn register_readers(world: &mut World, script: &mut UiScript) { + crate::bindings::seed_bindings_for_vm(script); + crate::ui_layout::register_layout_reader(world, script); + crate::bindings::register_binding_readers(world, script); + crate::ui_macro::register_macro_readers(world, script); +} + +/// `SMSG_ACCOUNT_DATA_MD5`: the server holds no copy of any section but those of `asked`, whose +/// copies differ from ours, so the check asks for each (`0x5afa6c`) and settles the rest. +fn digests(asked: &[usize]) -> SessionEvent { + let mut server: [AccountDataDigest; ACCOUNT_DATA_SECTIONS] = Default::default(); + for &s in asked { + server[s] = [0xab; 16]; + } + SessionEvent::AccountDataMd5(server) +} + +/// `SMSG_UPDATE_ACCOUNT_DATA` with `file` for `section`. +fn download(section: u32, file: &str) -> SessionEvent { + let body = benilla_protocol::messages::update_account_data(section, file.as_bytes()); + SessionEvent::UpdateAccountData(UpdateAccountData { + section, + size: file.len() as u32, + stream: body[8..].to_vec(), + }) +} + +/// `SMSG_PLAYED_TIME`, which signals `TIME_PLAYED_MSG` inside itself (`0x4018df`). +fn played() -> SessionEvent { + SessionEvent::PlayedTime { + total: 60, + level: 1, + } +} + +/// The character's binding section, downloaded between two packets of a frame, is read inside its +/// handler (`0x5afd19` → `0x4b6240` with set 2), whose set choice copies set 2 into the live set +/// and signals `UPDATE_BINDINGS` there (`0x4b629a` → `0x4b64b0` → `0x4b6310`, `0x4b6498`): the +/// earlier packet's listener reads the key unbound, the signal's and the later packet's read it. +#[test] +fn a_binding_download_is_read_inside_its_packet() { + let _l = ENV_LOCK + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let mut c = client( + "bindings", + &["TIME_PLAYED_MSG", "UPDATE_BINDINGS"], + r#"local key = GetBindingKey("BENILLAPROBE") return tostring(key)"#, + Vec::new, + ); + // The macro sections asked for too, so only the bindings' reader runs. + let [_, character] = crate::account_data::BINDINGS; + c.frame(vec![vec![digests(&[character, 4, 5])]]); + c.seen(); + c.frame(vec![ + vec![played()], + vec![download(3, "bind CTRL-F12 BENILLAPROBE\r\n")], + vec![played()], + ]); + assert_eq!( + c.seen(), + [ + "TIME_PLAYED_MSG:nil", + "UPDATE_BINDINGS:CTRL-F12", + "TIME_PLAYED_MSG:CTRL-F12" + ] + ); +} + +/// The digests' check settles both macro sections in one packet, each in turn (`0x5af91b` → +/// `0x5afaca`), and each settling runs the reader for its scope (`0x4f0600`), which rebuilds the +/// order and signals `UPDATE_MACROS` (`0x4f0a50` → `0x4f0d30`): the earlier packet's listener reads +/// no macro, each signal's reads the scopes read so far, the later packet's reads both. +#[test] +fn the_macro_scopes_are_read_inside_the_digests_packet() { + let _l = ENV_LOCK + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let mut c = client( + "macros", + &["TIME_PLAYED_MSG", "UPDATE_MACROS"], + r#"local a, c = GetNumMacros() return a .. ":" .. c"#, + || { + vec![ + ( + crate::local_state::macros_account_path().unwrap(), + "MACRO 1 \"Acct\" Ability_Ambush\n/say a\nEND\n", + ), + ( + crate::local_state::macros_character_path("Realm", "Probeone").unwrap(), + "MACRO 16777217 \"Alt\" Ability_Ambush\n/say b\nEND\n", + ), + ] + }, + ); + c.frame(vec![vec![played()], vec![digests(&[])], vec![played()]]); + assert_eq!( + c.seen(), + [ + "TIME_PLAYED_MSG:0:0", + "UPDATE_MACROS:1:0", + "UPDATE_MACROS:1:1", + "TIME_PLAYED_MSG:1:1" + ] + ); +} + +/// The layout section, downloaded between two packets of a frame, is read inside its handler +/// (`0x5afd19` → `0x490380`), which seats the window it names: the earlier packet's listener reads +/// the authored size, the later packet's the file's. +#[test] +fn a_layout_download_is_read_inside_its_packet() { + let _l = ENV_LOCK + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let mut c = client( + "layout", + &["TIME_PLAYED_MSG"], + r#"return math.floor(LayoutProbe:GetWidth() + 0.5)"#, + Vec::new, + ); + // The macro sections asked for too, so only the layout's reader runs. + c.frame(vec![vec![digests(&[crate::account_data::LAYOUT, 4, 5])]]); + c.seen(); + c.frame(vec![ + vec![played()], + vec![download(6, "Frame: LayoutProbe\r\nW: 413\r\nH: 147\r\n")], + vec![played()], + ]); + assert_eq!(c.seen(), ["TIME_PLAYED_MSG:100", "TIME_PLAYED_MSG:413"]); +} + +/// A character file of the builds that numbered macros by position, ids 2, 1 and 3 in the order +/// they were made: those builds read it back by id, so Alpha (1) sat first, Bravo (2) second and +/// Charlie (3) third, on buttons `0x40000013` to `0x40000015`. +const OLD_CHARACTER_FILE: &str = "MACRO 2 \"Bravo\" Ability_Ambush\n/say b\nEND\n\ + MACRO 1 \"Alpha\" Ability_Ambush\n/say a\nEND\n\ + MACRO 3 \"Charlie\" Ability_Ambush\n/say c\nEND\n"; + +/// `SMSG_ACTION_BUTTONS` with three of those macros, one past the last (cleared), an account macro +/// and a word past 36, each `(wire slot, word)`. +fn old_bar() -> SessionEvent { + let buttons = [ + (0u8, 0x4000_0013u32), + (1, 0x4000_0015), + (2, 0x4000_0014), + (3, 0x4000_0016), + (5, 0x4000_0001), + (6, 0x4000_0025), + ] + .map(|(slot, word)| benilla_protocol::messages::ActionButton { + slot, + action: word & 0x00ff_ffff, + kind: (word >> 24) as u8, + }); + SessionEvent::ActionButtons { + buttons: buttons.to_vec(), + } +} + +/// The moves of [`old_bar`]: Alpha, Charlie and Bravo by their ids, the button past the last +/// macro cleared, each once, as a placement goes. +const MOVED: [(u8, u32); 4] = [(0, 0x4100_0001), (1, 0x4100_0003), (2, 0x4100_0002), (3, 0)]; + +/// The bar after the moves: the account macro and the word past 36 stay. +const MOVED_BAR: [(u8, u32); 5] = [ + (0, 0x4100_0001), + (1, 0x4100_0003), + (2, 0x4100_0002), + (5, 0x4000_0001), + (6, 0x4000_0025), +]; + +/// The character's macro file on disk. +fn character_file() -> String { + let path = crate::local_state::macros_character_path("Realm", "Probeone").unwrap(); + std::fs::read_to_string(path).unwrap() +} + +/// At a login the macro sections settle ahead of the bar, which vmangos sends after the account +/// data (`CharacterHandler.cpp:525`, `:575`) and our player's arrival loads (`0x5deae2`): the +/// older numbering's moves wait for that load, and only once they have run is the file +/// renumbered. +#[test] +fn an_older_character_file_moves_its_buttons_once_the_bar_is_loaded() { + let _l = ENV_LOCK + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let mut c = unarrived("renumber-bar-later", &[], "return ''", || { + vec![( + crate::local_state::macros_character_path("Realm", "Probeone").unwrap(), + OLD_CHARACTER_FILE, + )] + }); + c.frame(vec![vec![digests(&[])]]); + assert!(c.placed().is_empty(), "no bar yet: nothing moves"); + assert!( + character_file().starts_with("MACRO 2 \"Bravo\""), + "the file waits for the moves" + ); + c.frame(vec![vec![old_bar()]]); + assert!(c.placed().is_empty(), "the bar is only staged"); + c.arrive(); + assert_eq!(c.placed(), MOVED); + assert_eq!(c.bar(), MOVED_BAR); + assert!( + character_file().starts_with("MACRO 16777217 \"Alpha\""), + "renumbered, in name order: {}", + character_file() + ); + // The sections settle again: the renumbered file has no old ids, so nothing moves, though a + // word from 19 to 36 would now be an account macro's. + c.frame(vec![vec![digests(&[])]]); + assert!(c.placed().is_empty(), "the buttons move once"); + assert_eq!(c.bar(), MOVED_BAR); +} + +/// A server whose digests come after our player's arrival finds the bar loaded at the read: the +/// buttons move there, and the file is renumbered. +#[test] +fn an_older_character_file_moves_a_loaded_bar_at_its_read() { + let _l = ENV_LOCK + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let mut c = unarrived("renumber-bar-first", &[], "return ''", || { + vec![( + crate::local_state::macros_character_path("Realm", "Probeone").unwrap(), + OLD_CHARACTER_FILE, + )] + }); + c.frame(vec![vec![old_bar()]]); + c.arrive(); + assert!(c.placed().is_empty(), "no macro read yet: nothing moves"); + c.frame(vec![vec![digests(&[])]]); + assert_eq!(c.placed(), MOVED); + assert_eq!(c.bar(), MOVED_BAR); + assert!( + character_file().starts_with("MACRO 16777217 \"Alpha\""), + "renumbered, in name order: {}", + character_file() + ); +} + +/// An edit while the moves wait for the bar, a `CreateMacro` in a listener of the character +/// scope's `UPDATE_MACROS`, leaves the file in the older numbering, so a session that ends before +/// the arrival still finds the buttons' old places at its next load; the arrival moves them and +/// writes the table, the edit with it. +#[test] +fn an_edit_while_the_moves_wait_keeps_the_older_file_until_they_run() { + let _l = ENV_LOCK + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let mut c = unarrived( + "renumber-edit", + &["UPDATE_MACROS"], + r#"local _, c = GetNumMacros() + if c > 0 and not Made then Made = 1 CreateMacro("Delta", 1, "/say d", nil, 1) end + return ''"#, + || { + vec![( + crate::local_state::macros_character_path("Realm", "Probeone").unwrap(), + OLD_CHARACTER_FILE, + )] + }, + ); + c.frame(vec![vec![digests(&[])]]); + c.frame(vec![]); + assert!( + crate::script_calls::eval_in_vm::>(c.app.world(), "return Made").is_some(), + "the listener made its macro" + ); + assert_eq!( + character_file(), + OLD_CHARACTER_FILE, + "the edit waits for the moves" + ); + c.frame(vec![vec![old_bar()]]); + c.arrive(); + assert_eq!(c.placed(), MOVED); + let file = character_file(); + assert!( + file.starts_with("MACRO 16777217 \"Alpha\"") && file.matches(" \"Delta\" ").count() == 1, + "renumbered, the edit with it: {file}" + ); +} diff --git a/crates/benilla-app/src/lanes/action_live_tests.rs b/crates/benilla-app/src/lanes/action_live_tests.rs index 8eb2d7be5..623c2e21c 100644 --- a/crates/benilla-app/src/lanes/action_live_tests.rs +++ b/crates/benilla-app/src/lanes/action_live_tests.rs @@ -5,8 +5,7 @@ //! read the active player's object inside the call: `IsCurrentAction`'s form arm the form byte //! (`0x4e558b`, `[unit+0x110]+0x212`) and `IsEquippedAction` the worn slots (`0x4e5310` → //! `0x622270` at mask 1). The bonus bar's offset is stored where the form watcher runs -//! (`0x5de01b` → `0x4e4fc0`), off that packet's form. The live answer and the frame's snapshot -//! agree on every getter wherever the snapshot is current. +//! (`0x5de01b` → `0x4e4fc0`), off that packet's form. Every getter reads through the lent host. use std::collections::HashMap; @@ -31,9 +30,26 @@ const POTION: u32 = 118; /// The spells on the bar: a Frostbolt at 50 mana, the druid's Cat and Bear forms, and Attack. const FROSTBOLT: u32 = 116; +/// Frostbolt's second rank, which supersedes the first. +const FROSTBOLT_2: u32 = 205; const CAT: u32 = 768; const BEAR: u32 = 5487; const ATTACK: u32 = 6603; +/// A ranged auto-repeat shot (`Attributes & 0x2`, `AttributesEx2 & 0x20`), off the bar. +const AUTO_SHOT: u32 = 75; +/// Two reactive spells (`AttributesEx4 & 0x200`) that need the defense aura state, off the bar, +/// which the login lists Overpower first. +const OVERPOWER: u32 = 7384; +const REVENGE: u32 = 6572; +/// A spell whose `ActiveIconID` shows while its own cancelable aura is on (`0x4e55f0`), and that +/// icon. +const TOGGLE: u32 = 2645; +const TOGGLE_ACTIVE: &str = "Interface\\Icons\\Spell_Active"; +/// `UNIT_FIELD_AURA` and `UNIT_FIELD_AURAFLAGS`, slot 0's aura and its nibble. +const AURA_0: u16 = 47; +const AURA_FLAGS_0: u16 = 95; +/// `UNIT_FIELD_AURASTATE`, whose bit 0 is the state the two need. +const AURA_STATE: u16 = 125; /// The form bytes of Cat and Bear, and the bonus bars their rows page to. const CAT_FORM: u32 = 1; const BEAR_FORM: u32 = 5; @@ -139,6 +155,10 @@ impl Client { /// The spells' rows and the two forms' rows. fn spells() -> crate::ui_action::Spells { + let reactive = |d: &mut SpellDisplay| { + d.attributes_ex4 = 0x200; + d.caster_aura_state = 1; + }; let row = |id: u32, f: fn(&mut SpellDisplay)| { let mut d = SpellDisplay { id, @@ -151,10 +171,24 @@ fn spells() -> crate::ui_action::Spells { }; let catalog = SpellCatalog::from_displays(HashMap::from([ row(FROSTBOLT, |d| d.mana_cost = 50), + row(FROSTBOLT_2, |d| { + d.mana_cost = 60; + d.recovery_ms = 120_000; + }), row(CAT, |d| d.shapeshift_form = Some(CAT_FORM)), row(BEAR, |d| d.shapeshift_form = Some(BEAR_FORM)), // `SPELL_EFFECT_ATTACK`, which makes the slot the Attack slot (`0x4e59de`). row(ATTACK, |d| d.effects[0] = 78), + row(AUTO_SHOT, |d| { + d.attributes = 0x2; + d.attributes_ex2 = 0x20; + }), + row(OVERPOWER, reactive), + row(REVENGE, reactive), + row(TOGGLE, |d| { + d.active_icon_id = 1; + d.active_icon = Some(TOGGLE_ACTIVE.to_string()); + }), ])); let form = |bonus_bar: u32| ShapeshiftForm { bonus_bar, @@ -172,6 +206,16 @@ fn spells() -> crate::ui_action::Spells { /// whose line for each event carries what its listener read of the bar: Frostbolt's usable pair /// and the sword's equipped flag, the two forms' checked state, the bonus bar's offset. fn client() -> Client { + client_with(|_| {}) +} + +/// [`client`] with `more` run on its world before our player's create. +fn client_with(more: impl FnOnce(&mut World)) -> Client { + client_created_with(more, &[]) +} + +/// [`client_with`], our player's create carrying the fields `extra` too. +fn client_created_with(more: impl FnOnce(&mut World), extra: &[(u16, u32)]) -> Client { let mut app = crate::game_plugins::schedule_tests::headless_client(); app.insert_resource(bevy::ecs::error::DefaultErrorHandler( bevy::ecs::error::ignore, @@ -214,10 +258,13 @@ fn client() -> Client { benilla_world::world_point::init_world_point_resources(app.world_mut()); let world = app.world_mut(); world.resource_mut::().0 = Some(ME); - world - .resource_mut::() - .spells - .extend([FROSTBOLT, CAT, BEAR, ATTACK]); + { + let mut actions = world.resource_mut::(); + actions + .spells + .extend([FROSTBOLT, CAT, BEAR, ATTACK, OVERPOWER, REVENGE]); + actions.initial = vec![OVERPOWER, REVENGE]; + } world .resource_mut::() .insert_template(SWORD, Some(crate::items::test_template("Sword"))); @@ -235,10 +282,9 @@ fn client() -> Client { (6, POTION, benilla_protocol::messages::ACTION_KIND_ITEM), ] { slots - .buttons + .staged .insert(slot, ActionButton { slot, action, kind }); } - slots.dirty = true; } // The sword: entry, stack 1, durability 30 of 40, so the worn walk counts it. crate::items::test_spawn_item( @@ -261,25 +307,24 @@ fn client() -> Client { .into_created(benilla_protocol::messages::ObjectType::Item), false, ); + more(world); let mut c = Client { app, inbound, _sent: sent, }; - c.frame(vec![vec![created( - ME, - EntityKind::Player, - &[ - (OBJECT_TYPE, TYPE_PLAYER), - (FIELD_UNIT_HEALTH, 100), - (FIELD_UNIT_MAXHEALTH, 100), - (MANA, 100), - (MAX_MANA, 100), - (FLAGS, PLAYER_CONTROLLED), - (PACK_SLOT_1, POTION_GUID as u32), - (PACK_SLOT_1 + 1, (POTION_GUID >> 32) as u32), - ], - )]]); + let mut fields = vec![ + (OBJECT_TYPE, TYPE_PLAYER), + (FIELD_UNIT_HEALTH, 100), + (FIELD_UNIT_MAXHEALTH, 100), + (MANA, 100), + (MAX_MANA, 100), + (FLAGS, PLAYER_CONTROLLED), + (PACK_SLOT_1, POTION_GUID as u32), + (PACK_SLOT_1 + 1, (POTION_GUID >> 32) as u32), + ]; + fields.extend_from_slice(extra); + c.frame(vec![vec![created(ME, EntityKind::Player, &fields)]]); c.frame(vec![]); c.frame(vec![]); c.seen(&[]); @@ -300,18 +345,14 @@ fn form(form: u32) -> [(u16, u32); 1] { [(BYTES_1, form << 16)] } -/// Wherever the frame's snapshots are current, every census getter answers the same live as off -/// the snapshot, for every slot: at load, in each form, with the sword worn and short of mana. +/// Every census getter answers through the lent host for every slot, each leg the fixture means to +/// reach: at load, in each form, with the sword worn and short of mana. #[test] -fn every_action_getter_answers_the_same_live_as_off_the_snapshot() { +fn every_action_getter_reads_its_leg_live() { let mut c = client(); let agree = |c: &mut Client, why: &str| -> Vec { - let snapshot = c.answers(false); let live = c.answers(true); - assert_eq!(snapshot.len(), SLOTS.len() * 14 + 1, "{why}"); - let differ: Vec<(&String, &String)> = - snapshot.iter().zip(&live).filter(|(s, l)| s != l).collect(); - assert!(differ.is_empty(), "{why}: snapshot vs live: {differ:#?}"); + assert_eq!(live.len(), SLOTS.len() * 14 + 1, "{why}"); live }; let at_load = agree(&mut c, "at load"); @@ -347,9 +388,8 @@ fn every_action_getter_answers_the_same_live_as_off_the_snapshot() { } } -/// A store a packet moved after the frame's pushes reads as the object holds it, through the -/// host: the form byte for `IsCurrentAction`, the main hand for `IsEquippedAction`; the snapshot -/// still holds the push. +/// A store a packet moved reads as the object holds it, through the host: the form byte for +/// `IsCurrentAction`, the main hand for `IsEquippedAction`. #[test] fn the_object_getters_read_the_player_as_they_run() { let mut c = client(); @@ -358,8 +398,6 @@ fn the_object_getters_read_the_player_as_they_run() { let chunk = "return IsCurrentAction(2), IsEquippedAction(4)"; let live: (Option, Option) = c.eval(true, chunk); assert_eq!(live, (Some(1), Some(1))); - let snapshot: (Option, Option) = c.eval(false, chunk); - assert_eq!(snapshot, (None, None)); } /// Two power packets in one frame, the first leaving the player short of Frostbolt's 50 mana and @@ -373,7 +411,6 @@ fn a_usable_listener_reads_its_own_packets_power() { vec![values(ME, &[(MANA, 30)])], vec![values(ME, &[(MANA, 100)])], ]); - let usable = |l: &String| l.split(':').take(3).collect::>().join(":"); let seen: Vec = c .seen(&[ "ACTIONBAR_UPDATE_USABLE", @@ -381,7 +418,7 @@ fn a_usable_listener_reads_its_own_packets_power() { "UNIT_MANA", ]) .iter() - .map(usable) + .map(|l| usable(l)) .collect(); assert_eq!( seen, @@ -466,6 +503,470 @@ fn a_slot_changed_listener_reads_the_pair_its_recount_stored() { ); } +/// The usable pair a spy line carries: its event and `IsUsableAction(1)`. +fn usable(l: &str) -> String { + l.split(':').take(3).collect::>().join(":") +} + +/// `EditMacro`'s worker ends in the bar's usable cache refresh (`0x4f132e` into `0x4e5c00`), +/// inside the call: a pair that moved with no refresh signals `ACTIONBAR_UPDATE_USABLE` before the +/// call returns, so the chunk's next line has heard it, and no later frame signals it again. +#[test] +fn an_edit_macro_refreshes_the_usable_cache_inside_its_call() { + let mut c = client(); + c.eval::<()>(true, "CreateMacro('m', 1, '/say hi', 1)"); + c.write_store(&[(MANA, 10)]); + let heard: Vec = c.eval( + true, + "Seen = {} EditMacro(1, 'n') local s = Seen Seen = {} return s", + ); + let heard: Vec = heard + .iter() + .filter(|l| l.starts_with("ACTIONBAR_UPDATE_USABLE")) + .map(|l| usable(l)) + .collect(); + assert_eq!(heard, ["ACTIONBAR_UPDATE_USABLE:nil:1"], "inside the call"); + c.frame(vec![]); + assert!(c.seen(&["ACTIONBAR_UPDATE_USABLE"]).is_empty()); +} + +/// Two packets in one frame: the potion's stack count, whose watcher's `RaiseBagUpdate` +/// refreshes the bar's usable cache ahead of its `BAG_UPDATE` (`0x4f9370` → `0x4f9374`), then a +/// power packet. The run's refresh reads the pair a quiet write moved and signals at the run, +/// between the two packets' events. +#[test] +fn a_bag_updates_usable_refresh_signals_at_its_run() { + let mut c = client(); + c.eval::<()>( + false, + "local f = CreateFrame('Frame') f:RegisterEvent('BAG_UPDATE') \ + f:SetScript('OnEvent', function() table.insert(Seen, event) end)", + ); + c.write_store(&[(MANA, 10)]); + c.frame(vec![ + vec![values(POTION_GUID, &[(STACK_COUNT, 1)])], + vec![values(ME, &[(MANA, 100)])], + ]); + let seen: Vec = c + .seen(&["ACTIONBAR_UPDATE_USABLE", "BAG_UPDATE", "UNIT_MANA"]) + .iter() + .map(|l| usable(l)) + .collect(); + assert_eq!( + seen, + [ + "ACTIONBAR_UPDATE_USABLE:nil:1", + "BAG_UPDATE", + "ACTIONBAR_UPDATE_USABLE:1:nil", + "UNIT_MANA:1:nil", + ] + ); +} + +/// `PlaceAction`'s write stores the slot's pair inside the call (`0x4e62e0` → `0x4e58e0`, +/// `0x4e590a`), ahead of its `ACTIONBAR_SLOT_CHANGED` (`0x4e5998`): the listener reads the placed +/// spell lit, and the slot the pickup cleared grey. +#[test] +fn a_placed_slots_listener_reads_the_pair_its_write_stored() { + let mut c = client(); + let heard: Vec = c.eval( + true, + "Seen = {} PickupAction(1) PlaceAction(8) local s = Seen Seen = {} return s", + ); + let slots: Vec<&String> = heard + .iter() + .filter(|l| l.starts_with("ACTIONBAR_SLOT_CHANGED")) + .collect(); + assert_eq!( + slots, + [ + "ACTIONBAR_SLOT_CHANGED:1:nil:0", + "ACTIONBAR_SLOT_CHANGED:8:1:0" + ] + ); +} + +/// A ration the cache has no record of, on bar slot 8, three of them ours. +const RATION_GUID: u64 = 0x4000_0000_0000_00F2; +const RATION: u32 = 4540; +const RATION_DISPLAY: u32 = 6413; +const RATION_ICON: &str = "Interface\\Icons\\INV_Misc_Food_11"; + +/// Our arrival's slot pass counts the ration slot through the item cache with the bar's callback +/// (`0x5deb00` → `0x4e5d60` → `0x4e6d20`, `0x4e6d69`), which the record's answer runs inside its +/// packet (`0x55bf39` → `0x4e5b80` → `0x4e5c70`): the slot's `ACTIONBAR_SLOT_CHANGED` fires between +/// the packets around the answer, and every getter reads the slot's icon, consumable test and count +/// at its call (`0x4e6a50`, `0x4e5250`, `0x4e6c70`): the first packet's listener reads the cold +/// record, the question mark and no consumable test, with the count our arrival stored before the +/// rations reached the pack, and the last the answer's. +#[test] +fn a_bar_items_record_repaints_its_slot_at_the_answer_and_the_getters_read_it_live() { + let mut c = client_with(|world| { + crate::items::test_spawn_item( + world, + RATION_GUID, + ObjectFields::from_pairs(&[ + (OBJECT_TYPE, 0x3), + (3, RATION), + (6, ME as u32), + (7, (ME >> 32) as u32), + (STACK_COUNT, 3), + ]) + .into_created(benilla_protocol::messages::ObjectType::Item), + false, + ); + world + .resource_mut::() + .staged + .insert( + 7, + ActionButton { + slot: 7, + action: RATION, + kind: benilla_protocol::messages::ACTION_KIND_ITEM, + }, + ); + world.insert_resource(crate::entities::ItemDisplays::icons_for_tests( + benilla_formats::ItemDisplayCatalog::from_displays(HashMap::from([( + RATION_DISPLAY, + benilla_formats::ItemDisplay { + icon: Some(RATION_ICON.to_string()), + ..Default::default() + }, + )])), + )); + }); + c.write_store(&[ + (PACK_SLOT_1 + 2, RATION_GUID as u32), + (PACK_SLOT_1 + 3, (RATION_GUID >> 32) as u32), + ]); + c.eval::<()>( + false, + "local f = CreateFrame('Frame') f:RegisterEvent('UNIT_MANA') \ + f:RegisterEvent('ACTIONBAR_SLOT_CHANGED') \ + f:SetScript('OnEvent', function() \ + if event == 'ACTIONBAR_SLOT_CHANGED' and arg1 ~= 8 then return end \ + table.insert(Seen, 'RATION:' .. event .. ':' .. tostring(GetActionTexture(8)) .. ':' \ + .. tostring(IsConsumableAction(8)) .. ':' .. GetActionCount(8)) end)", + ); + c.seen(&[]); + // A cold record reads the resolver's question mark at the call; the arrival's count asked for + // it, and the getter, finding it pending, asks nothing more. + let icon: String = c.eval(true, "return GetActionTexture(8)"); + assert_eq!(icon, crate::ui_action::MISSING_ITEM_ICON); + let asked = crate::query_cache::queries(&c._sent) + .into_iter() + .filter(|q| matches!(q, ClientCommand::ItemQuery { entry, .. } if *entry == RATION)) + .count(); + assert_eq!(asked, 1); + // Tough rations: one on-use block whose charges -1 make the slot show its count. + let mut info = crate::items::test_template("Ration"); + info.display_info_id = RATION_DISPLAY; + info.spells = vec![benilla_protocol::messages::ItemSpellEntry { + index: 0, + spell_id: 433, + trigger: 0, + charges: -1, + cooldown_ms: -1, + category: 0, + category_cooldown_ms: -1, + }]; + c.frame(vec![ + vec![values(ME, &[(MANA, 90)])], + vec![SessionEvent::ItemTemplate { + entry: RATION, + info: Some(Box::new(info)), + }], + vec![values(ME, &[(MANA, 100)])], + ]); + let ration: Vec = c + .seen(&["RATION"]) + .into_iter() + .map(|l| l.trim_start_matches("RATION:").to_string()) + .collect(); + assert_eq!( + ration, + [ + format!("UNIT_MANA:{}:nil:0", crate::ui_action::MISSING_ITEM_ICON), + format!("ACTIONBAR_SLOT_CHANGED:{RATION_ICON}:1:3"), + format!("UNIT_MANA:{RATION_ICON}:1:3"), + ] + ); +} + +/// A bar slot holding [`RATION`], its record refused after our player's arrival asked it +/// (`0x4e6d20`), and `rations` of them in backpack slot 2 at the create, which the arrival's +/// recount stores (`0x4e5d90`); and a counter of the record's asks. +fn refused_ration(rations: u32) -> (Client, impl Fn(&Client) -> usize) { + let mut extra = Vec::new(); + if rations > 0 { + extra.extend([ + (PACK_SLOT_1 + 2, RATION_GUID as u32), + (PACK_SLOT_1 + 3, (RATION_GUID >> 32) as u32), + ]); + } + let mut c = client_created_with( + |world| { + crate::items::test_spawn_item( + world, + RATION_GUID, + ObjectFields::from_pairs(&[ + (OBJECT_TYPE, 0x3), + (3, RATION), + (6, ME as u32), + (7, (ME >> 32) as u32), + (STACK_COUNT, rations), + ]) + .into_created(benilla_protocol::messages::ObjectType::Item), + false, + ); + world + .resource_mut::() + .staged + .insert( + 7, + ActionButton { + slot: 7, + action: RATION, + kind: benilla_protocol::messages::ACTION_KIND_ITEM, + }, + ); + }, + &extra, + ); + c.frame(vec![vec![SessionEvent::ItemTemplate { + entry: RATION, + info: None, + }]]); + c.seen(&[]); + let asked = |c: &Client| { + crate::query_cache::queries(&c._sent) + .into_iter() + .filter(|q| matches!(q, ClientCommand::ItemQuery { entry, .. } if *entry == RATION)) + .count() + }; + asked(&c); + let count: i64 = c.eval(true, "return GetActionCount(8)"); + assert_eq!(count, i64::from(rations), "the arrival's stored count"); + (c, asked) +} + +/// The usable test's item lookup carries the bar's callback and its dedupe (`0x4e5050` → +/// `0x4e5a50` → `0x4e5ae0`, `0x4e5b30`), so a refused record it asks again answers through +/// `0x4e5b80` → `0x4e5c70`: after the refusal, a power packet's usable refresh (`0x604876` → +/// `0x4b31c0`) is the one lookup, and the record's answer signals the slot's +/// `ACTIONBAR_SLOT_CHANGED`. +#[test] +fn a_usable_refreshs_lookup_of_a_refused_record_repaints_its_slot_at_the_answer() { + let (mut c, asked) = refused_ration(3); + c.frame(vec![vec![values(ME, &[(MANA, 90)])]]); + assert_eq!(asked(&c), 1, "the refresh asks the refused record again"); + c.seen(&[]); + c.frame(vec![vec![SessionEvent::ItemTemplate { + entry: RATION, + info: Some(Box::new(crate::items::test_template("Ration"))), + }]]); + let slot: Vec = c + .seen(&["ACTIONBAR_SLOT_CHANGED"]) + .into_iter() + .filter(|l| l.starts_with("ACTIONBAR_SLOT_CHANGED:8:")) + .collect(); + assert_eq!(slot.len(), 1, "the slot repaints at the answer: {slot:?}"); +} + +/// The usable test asks nothing of an item slot whose stored count is 0: it returns at +/// `0x4e50ab`, ahead of both lookups (`0x4e50d0`, `0x4e50e7`), so a refresh leaves a refused +/// record refused. +#[test] +fn a_usable_refresh_asks_nothing_of_an_empty_item_slot() { + let (mut c, asked) = refused_ration(0); + c.frame(vec![vec![values(ME, &[(MANA, 90)])]]); + assert_eq!(asked(&c), 0); +} + +/// The active player's aura add and removal each notify the bar's slots that stand for the spell +/// (`0x612440`, `0x61237e` → `0x4e5de0`): a toggle's `ACTIONBAR_SLOT_CHANGED` fires inside each +/// aura packet, between its neighbours' events, after the add's line and ahead of the removal's +/// (`0x62b480`), and its listener's `GetActionTexture` reads that packet's aura (`0x4e6bbd`): the +/// active icon at the add, the spell's own at the removal. +#[test] +fn an_aura_packet_notifies_its_spells_slots_between_its_neighbours() { + let mut c = client_with(|world| { + world + .resource_mut::() + .spells + .insert(TOGGLE); + world + .resource_mut::() + .staged + .insert( + 7, + ActionButton { + slot: 7, + action: TOGGLE, + kind: benilla_protocol::messages::ACTION_KIND_SPELL, + }, + ); + }); + c.eval::<()>( + false, + "AURAADDEDSELFHELPFUL = 'You gain %s.' AURAREMOVEDSELF = '%s fades from you.' \ + local f = CreateFrame('Frame') f:RegisterEvent('UNIT_MANA') \ + f:RegisterEvent('ACTIONBAR_SLOT_CHANGED') f:RegisterEvent('CHAT_MSG_SPELL_PERIODIC_SELF_BUFFS') \ + f:RegisterEvent('CHAT_MSG_SPELL_AURA_GONE_SELF') \ + f:SetScript('OnEvent', function() \ + if event == 'ACTIONBAR_SLOT_CHANGED' and arg1 ~= 8 then return end \ + if event == 'UNIT_MANA' and arg1 ~= 'player' then return end \ + table.insert(Seen, 'TOGGLE:' .. event .. ':' .. tostring(GetActionTexture(8))) end)", + ); + c.seen(&[]); + c.frame(vec![ + vec![values(ME, &[(MANA, 90)])], + vec![values(ME, &[(AURA_0, TOGGLE), (AURA_FLAGS_0, 0xb)])], + vec![values(ME, &[(AURA_0, 0), (AURA_FLAGS_0, 0)])], + vec![values(ME, &[(MANA, 100)])], + ]); + let own = format!("Interface\\Icons\\Spell_{TOGGLE}"); + assert_eq!( + c.seen(&["TOGGLE"]), + [ + format!("TOGGLE:UNIT_MANA:{own}"), + format!("TOGGLE:CHAT_MSG_SPELL_PERIODIC_SELF_BUFFS:{TOGGLE_ACTIVE}"), + format!("TOGGLE:ACTIONBAR_SLOT_CHANGED:{TOGGLE_ACTIVE}"), + format!("TOGGLE:ACTIONBAR_SLOT_CHANGED:{own}"), + format!("TOGGLE:CHAT_MSG_SPELL_AURA_GONE_SELF:{own}"), + format!("TOGGLE:UNIT_MANA:{own}"), + ] + ); +} + +/// `GameTooltip:SetAction` runs the slot's cooldown query at the call (`0x5323a6` → `0x4e6ca0`), +/// so a hover inside the packet that armed a two-minute cooldown builds the remaining time and +/// answers 1 (`0x532597`, `0x5325a9`). +#[test] +fn set_action_reads_the_slots_cooldown_at_the_call() { + let mut c = client_with(|world| { + world + .resource_mut::() + .spells + .insert(FROSTBOLT_2); + world + .resource_mut::() + .staged + .insert( + 7, + ActionButton { + slot: 7, + action: FROSTBOLT_2, + kind: benilla_protocol::messages::ACTION_KIND_SPELL, + }, + ); + }); + crate::ui_script::test_ui::load_tooltip_template(c.app.world().non_send_resource::()); + c.eval::<()>( + false, + "local a = CreateFrame('Button', 'B') a:SetPoint('CENTER', 0, 0) a:SetWidth(10) \ + a:SetHeight(10) CreateFrame('GameTooltip', 'TT', nil, 'TestTooltipTemplate')", + ); + let hover = "TT:SetOwner(B, 'ANCHOR_RIGHT') return TT:SetAction(8)"; + assert_eq!(c.eval::>(true, hover), None, "nothing running"); + crate::net::handlers::dispatch( + c.app.world_mut(), + vec![SessionEvent::SpellCooldowns { + caster: ME, + cooldowns: vec![(FROSTBOLT_2, 120_000)], + }], + ); + assert_eq!( + c.eval::>(true, hover), + Some(1), + "live: the armed cooldown" + ); +} + +/// A `/reload` keeps the bar in the engine (`0xbc6980`, `0xbc6390`; `0x4e4f50` runs only at the +/// game entry), so the new interface reads it from its first file: an addon's file scope finds the +/// bar's words and icons, and the counts as the last recount stored them, a stack that moved with +/// no recount included; no slot signals. +#[test] +fn a_reloads_files_read_the_bar_it_left() { + use crate::local_state::test_env::{EnvGuard, ENV_LOCK}; + let _l = ENV_LOCK + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let tmp = std::env::temp_dir().join(format!("benilla-bar-reload-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&tmp); + let home = tmp.join("benilla-config"); + let dir = home.join("AddOns").join("BarProbe"); + std::fs::create_dir_all(&dir).expect("probe addon dir"); + std::fs::write( + dir.join("BarProbe.toc"), + "## Interface: 11200\nBarProbe.lua\n", + ) + .expect("probe toc"); + std::fs::write( + dir.join("BarProbe.lua"), + "BarProbe = { HasAction(1), HasAction(6), GetActionCount(7), GetActionTexture(1) } \ + BarProbeSlotSignals = 0 \ + local f = CreateFrame('Frame') f:RegisterEvent('ACTIONBAR_SLOT_CHANGED') \ + f:SetScript('OnEvent', function() BarProbeSlotSignals = BarProbeSlotSignals + 1 end)", + ) + .expect("probe lua"); + let _capture = EnvGuard::unset("WOW_CAPTURE"); + let _home = EnvGuard::set("BENILLA_HOME", home.to_str().expect("utf-8 temp path")); + + let mut c = client(); + let potions = c.app.world().resource::().0[&POTION_GUID]; + c.app + .world_mut() + .get_mut::(potions) + .expect("the potions") + .0 + .merge(ObjectFields::from_pairs(&[(STACK_COUNT, 5)])); + let world = c.app.world_mut(); + world.resource_mut::().0 = true; + crate::ui_script::run_pending_reload(world); + let probe: (Option, Option, i64, String, i64) = c.eval( + false, + "return BarProbe[1], BarProbe[2], BarProbe[3], BarProbe[4], BarProbeSlotSignals", + ); + assert_eq!( + probe, + ( + Some(1), + None, + 2, + format!("Interface\\Icons\\Spell_{FROSTBOLT}"), + 0 + ) + ); + drop(c); + let _ = std::fs::remove_dir_all(&tmp); +} + +/// Our create's arrival empties the reactive list and its registrar runs take the initial spells in +/// again in wire order (`0x5dea86`, `0x5dea96`-`0x5deab9` → `0x4b27b3`), so a refresh raises their +/// words in that order (`0x4b31d7`-`0x4b3226`): Overpower, listed first, before Revenge, whose id +/// is lower. +#[test] +fn the_arrival_lists_the_initial_reactive_spells_in_wire_order() { + let mut c = client(); + c.eval::<()>( + false, + "local f = CreateFrame('Frame') f:RegisterEvent('COMBAT_TEXT_UPDATE') \ + f:SetScript('OnEvent', function() \ + table.insert(Seen, event .. ':' .. arg1 .. ':' .. arg2) end)", + ); + c.frame(vec![vec![values(ME, &[(AURA_STATE, 1)])]]); + assert_eq!( + c.seen(&["COMBAT_TEXT_UPDATE"]), + [ + "COMBAT_TEXT_UPDATE:SPELL_ACTIVE:Spell 7384", + "COMBAT_TEXT_UPDATE:SPELL_ACTIVE:Spell 6572", + ] + ); +} + /// The worn walk resolves each item as of the drain's place, as the getter's `0x468460` finds the /// object at the call: a helm a later packet of the frame destroys is still worn to the listener /// of an earlier one. @@ -492,6 +993,190 @@ fn an_equipped_listener_finds_an_item_a_later_packet_destroys() { assert_eq!(seen, ["UNIT_MANA:1"]); } +/// `SMSG_ACTION_BUTTONS` only stages its words (`0x5e6680` into `0xc4c2b4`); our player's arrival +/// loads them into the bar and skips each spell word the player does not know (`0x5deaee` → +/// `0x60c740`, `0x5deaf5`). vmangos sends saved words with no such check +/// (`MasterPlayer.cpp:341`), so a slot saved with a rank the character lost stays empty: no +/// action, no icon, nothing in the bar, while the known words beside it load. +#[test] +fn an_arrival_leaves_a_saved_unknown_spells_slot_empty() { + let mut c = client_with(|world| { + let mut words: Vec = world + .resource::() + .staged + .values() + .copied() + .collect(); + words.push(ActionButton { + slot: 7, + action: FROSTBOLT_2, + kind: benilla_protocol::messages::ACTION_KIND_SPELL, + }); + crate::net::handlers::dispatch(world, vec![SessionEvent::ActionButtons { buttons: words }]); + assert!( + world + .resource::() + .buttons + .is_empty(), + "the packet only stages" + ); + }); + let chunk = "return HasAction(8), GetActionTexture(8), HasAction(1)"; + let read: (Option, Option, Option) = c.eval(true, chunk); + assert_eq!(read, (None, None, Some(1))); + let bar = c.app.world().resource::(); + assert!(!bar.buttons.contains_key(&7), "the bar holds no word there"); + assert_eq!(bar.buttons.len(), 6, "the known words loaded"); +} + +/// A macro slot's icon is its record's but where its bound spell is Attack or a ranged shot: +/// `0x4e6a50` runs both tests on the slot's spell through the record (`0x4e6ab2` → `0x4e59b0`, +/// `0x4e6acb` → `0x4e5a00`, each through `0x4e5a50` → `0x4e5ba0`) ahead of its kind arms, so a +/// macro bound to Attack shows the main hand's icon and one bound to Auto Shot the bow's. An item +/// slot runs them on its on-use spell (`0x4e5a50` → `0x4e5ae0`). +#[test] +fn a_macro_bound_to_an_attack_shows_its_weapons_icon() { + use crate::ui_macro::{Bound, BoundSpell}; + const BOW_GUID: u64 = 0x4000_0000_0000_00F3; + const BOW: u32 = 2504; + const RANGED: u16 = 486 + 2 * 17; + const SWORD_ICON: &str = "Interface\\Icons\\INV_Sword_04"; + const BOW_ICON: &str = "Interface\\Icons\\INV_Weapon_Bow_02"; + const QUIVER: u32 = 2101; + let mut c = client_with(|world| { + crate::items::test_spawn_item( + world, + BOW_GUID, + ObjectFields::from_pairs(&[(3, BOW), (14, 1)]), + false, + ); + let mut items = world.resource_mut::(); + for (entry, subclass, display) in [(SWORD, 7, 950), (BOW, 2, 951)] { + items.insert_template( + entry, + Some(benilla_protocol::messages::ItemInfo { + class: 2, + subclass, + display_info_id: display, + ..crate::items::test_template("Weapon") + }), + ); + } + // An item whose on-use spell is the ranged shot. + items.insert_template( + QUIVER, + Some(benilla_protocol::messages::ItemInfo { + display_info_id: 952, + use_spell: Some(benilla_protocol::messages::ItemUseSpell { + spell_id: AUTO_SHOT, + cooldown_ms: -1, + category: 0, + category_cooldown_ms: -1, + }), + ..crate::items::test_template("Quiver") + }), + ); + let display = |icon: &str| benilla_formats::ItemDisplay { + icon: Some(icon.to_string()), + ..Default::default() + }; + world.insert_resource(crate::entities::ItemDisplays::icons_for_tests( + benilla_formats::ItemDisplayCatalog::from_displays(HashMap::from([ + (950, display(SWORD_ICON)), + (951, display(BOW_ICON)), + (952, display("Interface\\Icons\\INV_Misc_Quiver_09")), + ])), + )); + }); + { + let world = c.app.world_mut(); + crate::ui_macro::bind_for_test( + &mut world.non_send_resource_mut::(), + &[ + (1, Bound::from(BoundSpell::Spell(ATTACK))), + (2, Bound::from(BoundSpell::Spell(AUTO_SHOT))), + (3, Bound::from(BoundSpell::Spell(FROSTBOLT))), + ], + ); + for (action, id) in [(9, 1), (10, 2), (11, 3)] { + crate::ui_action::hold_for_test( + world, + action, + benilla_protocol::messages::ACTION_KIND_MACRO, + id, + ); + } + crate::ui_action::hold_for_test( + world, + 12, + benilla_protocol::messages::ACTION_KIND_ITEM, + QUIVER, + ); + } + c.frame(vec![vec![values( + ME, + &[ + wield(true)[0], + wield(true)[1], + (RANGED, BOW_GUID as u32), + (RANGED + 1, (BOW_GUID >> 32) as u32), + ], + )]]); + let chunk = "return GetActionTexture(9), GetActionTexture(10), GetActionTexture(11)"; + assert_eq!( + c.eval::<(String, String, String)>(true, chunk), + ( + SWORD_ICON.to_string(), + BOW_ICON.to_string(), + "Interface\\Icons\\".to_string() + ), + "the weapons' icons, then the Frostbolt macro's own" + ); + assert_eq!( + c.eval::(true, "return GetActionTexture(12)"), + BOW_ICON, + "the item's on-use shot" + ); +} + +/// `SMSG_SUPERCEDED_SPELL` gives a bar macro that cast the old rank the new one in its record +/// (`0x5e6356` → `0x4e5e60`, `0x4e5ec4`), with no signal; `GetActionCooldown` resolves the slot +/// through that record at the call (`0x4e6ca0` → `0x4e5a50` → `0x4e5ba0`) and queries the new +/// rank's cooldown (`0x6e2ea0`). So a getter inside the packet that rewrote the record reads the +/// new rank's 10 s. +#[test] +fn a_superseded_macro_slots_cooldown_reads_the_new_rank_inside_its_packet() { + use crate::ui_macro::{Bound, BoundSpell}; + let mut c = client(); + { + let world = c.app.world_mut(); + crate::ui_macro::bind_for_test( + &mut world.non_send_resource_mut::(), + &[(1, Bound::from(BoundSpell::Spell(FROSTBOLT)))], + ); + world + .resource_mut::() + .spells + .insert(FROSTBOLT_2); + crate::ui_action::hold_for_test(world, 6, benilla_protocol::messages::ACTION_KIND_MACRO, 1); + } + c.frame(vec![vec![SessionEvent::SpellCooldowns { + caster: ME, + cooldowns: vec![(FROSTBOLT_2, 10_000)], + }]]); + c.frame(vec![]); + let chunk = "local _, d = GetActionCooldown(6) return d"; + assert_eq!(c.eval::(true, chunk), 0.0, "the macro casts rank 1"); + crate::net::handlers::dispatch( + c.app.world_mut(), + vec![SessionEvent::SpellSuperceded { + old_spell_id: FROSTBOLT, + new_spell_id: FROSTBOLT_2, + }], + ); + assert_eq!(c.eval::(true, chunk), 10.0, "live: the new rank's"); +} + /// The bar's getters' per-call cost with the host lent and off the snapshots: 10k calls of each. /// /// Run with `cargo nextest run -p benilla-app --lib action_getter_cost --run-ignored only @@ -537,7 +1222,6 @@ fn action_getter_cost() { }, ); } - slots.dirty = true; } c.frame(vec![]); let mut times = Vec::new(); diff --git a/crates/benilla-app/src/lanes/alert_live_tests.rs b/crates/benilla-app/src/lanes/alert_live_tests.rs new file mode 100644 index 000000000..b95076e7d --- /dev/null +++ b/crates/benilla-app/src/lanes/alert_live_tests.rs @@ -0,0 +1,276 @@ +//! The inventory alerts through the whole client: the recompute (`0x4c7ee0`) runs where its +//! watchers call it, inside the update packet's notify pass (the durability's `0x5d9920`, the +//! flags' `0x5d97aa`, a visible item's `0x5dee7a`), and at the world entry's set-up (`0x49097e` → +//! `0x4c6d30`), so `UPDATE_INVENTORY_ALERTS` fires between the packets around it, and +//! `GetInventoryAlertStatus` reads the statuses the last pass stored (`0xb71f60`). + +use benilla_protocol::field::{ + FIELD_PLAYER_INV_SLOT_HEAD, FIELD_PLAYER_VISIBLE_ITEM_1_CREATOR, FIELD_UNIT_HEALTH, + FIELD_UNIT_MAXHEALTH, +}; +use benilla_protocol::messages::{ChatMessage, ObjectType, CHAT_MSG_SYSTEM}; +use benilla_protocol::{EntityKind, ObjectFields, SessionEvent}; +use benilla_ui::script::UiScript; +use bevy::prelude::*; +use crossbeam_channel::Sender; + +use super::unit_view_tests::{created, values, wire_packets}; + +const ME: u64 = 0x7; +/// Another player in view. +const OTHER: u64 = 0x8; +/// Worn on the head, seat 0, the first alert region. +const HELM: (u64, u32) = (item(1), 7366); +/// In the backpack's first seat, 23: in no alert region. +const SPARE: (u64, u32) = (item(2), 2361); +/// In the main hand, seat 15, the ninth alert region. +const SWORD: (u64, u32) = (item(3), 25); + +/// `ITEM_FIELD_FLAGS`, the temporary enchantment's id (`ITEM_FIELD_ENCHANTMENT` slot 1), +/// `ITEM_FIELD_DURABILITY` and `_MAXDURABILITY`. +const FLAGS: u16 = 21; +const TEMP_ENCHANT: u16 = 25; +const DURABILITY: u16 = 46; +const MAX_DURABILITY: u16 = 47; + +const fn item(low: u64) -> u64 { + (benilla_protocol::guid::HIGH_ITEM as u64) << 48 | low +} + +/// The spy: each `UPDATE_INVENTORY_ALERTS` with the head's status as it fires, each system line +/// and each tutorial with the head's status as it shows, and `PLAYER_ENTERING_WORLD`. +const SPY: &str = r#"Seen = {} + local f = CreateFrame("Frame") + for _, e in ipairs({"UPDATE_INVENTORY_ALERTS", "CHAT_MSG_SYSTEM", "PLAYER_ENTERING_WORLD", + "TUTORIAL_TRIGGER"}) do + f:RegisterEvent(e) + end + f:SetScript("OnEvent", function() + if event == "UPDATE_INVENTORY_ALERTS" then + table.insert(Seen, "ALERTS:" .. GetInventoryAlertStatus(1)) + elseif event == "CHAT_MSG_SYSTEM" then + table.insert(Seen, arg1 .. ":" .. GetInventoryAlertStatus(1)) + elseif event == "TUTORIAL_TRIGGER" then + table.insert(Seen, "TUTORIAL:" .. arg1 .. ":" .. GetInventoryAlertStatus(1)) + else + table.insert(Seen, event) + end + end)"#; + +/// The whole client, headless, in the world with its frame run. +struct Client { + app: App, + inbound: Sender, +} + +impl Client { + /// One frame, with `packets` in the inbound channel, each one packet. + fn frame(&mut self, packets: Vec>) { + for ev in wire_packets(packets) { + self.inbound.send(ev).expect("the inbound channel"); + } + self.app.update(); + } + + /// What the spy heard since the last call. + fn seen(&mut self) -> Vec { + crate::script_calls::eval_in_vm(self.app.world(), "local s = Seen Seen = {} return s") + } +} + +/// One of our items, `durability` of 50. +fn item_create((guid, entry): (u64, u32), durability: u32) -> SessionEvent { + SessionEvent::ItemCreate { + guid, + container: false, + fields: ObjectFields::from_pairs(&[ + (2, 0x3), + (3, entry), + (6, ME as u32), + (8, ME as u32), + (DURABILITY, durability), + (MAX_DURABILITY, 50), + ]) + .into_created(ObjectType::Item), + } +} + +/// `guid` in flat seat `seat` of our array. +fn seat(seat: u16, guid: u64) -> [(u16, u32); 2] { + let lo = FIELD_PLAYER_INV_SLOT_HEAD + 2 * seat; + [(lo, guid as u32), (lo + 1, (guid >> 32) as u32)] +} + +fn system(text: &str) -> SessionEvent { + SessionEvent::Chat(ChatMessage { + chat_type: CHAT_MSG_SYSTEM, + language: 0, + sender_guid: 0, + target_guid: 0, + sender_name: None, + channel: None, + text: text.into(), + chat_tag: 0, + }) +} + +/// The client in the world as [`ME`], wearing [`HELM`] at `helm` durability and carrying +/// [`SPARE`], with [`OTHER`] in view; what the spy heard of the arrival. +fn client(helm: u32) -> (Client, Vec) { + let mut app = crate::game_plugins::schedule_tests::headless_client(); + app.insert_resource(bevy::ecs::error::DefaultErrorHandler( + bevy::ecs::error::ignore, + )); + let (tx, _sent) = crossbeam_channel::unbounded(); + app.insert_resource(crate::net::NetCommands(tx)); + let (inbound, rx) = crossbeam_channel::unbounded(); + app.insert_resource(crate::net::NetEvents::for_test(rx)); + app.update(); + let script = UiScript::new().expect("a VM"); + script.run(SPY).expect("the spy"); + app.insert_non_send_resource(script); + app.insert_resource(State::new(crate::client_state::ClientState::InWorld)); + benilla_world::world_point::init_world_point_resources(app.world_mut()); + app.world_mut().resource_mut::().0 = Some(ME); + { + let mut items = app.world_mut().resource_mut::(); + for (_, entry) in [HELM, SPARE, SWORD] { + items.insert_template(entry, Some(crate::items::test_template("Gear"))); + } + } + let mut c = Client { app, inbound }; + let mut me = vec![(FIELD_UNIT_HEALTH, 100), (FIELD_UNIT_MAXHEALTH, 100)]; + me.extend(seat(0, HELM.0)); + me.extend(seat(23, SPARE.0)); + me.extend(seat(15, SWORD.0)); + c.frame(vec![ + vec![item_create(HELM, helm)], + vec![item_create(SPARE, 50)], + vec![item_create(SWORD, 50)], + vec![created(ME, EntityKind::Player, &me)], + vec![created( + OTHER, + EntityKind::Player, + &[(FIELD_PLAYER_VISIBLE_ITEM_1_CREATOR + 2, HELM.1)], + )], + ]); + let arrival = c.seen(); + (c, arrival) +} + +/// The world entry's cascade sets the alerts up after its login events (`0x49096a`, then +/// `0x49097e` → `0x4c6d30` → `0x4c7ee0`): one recompute, over the gear we arrived in. +#[test] +fn the_world_entry_recomputes_after_entering_the_world() { + let (_, arrival) = client(0); + assert_eq!(arrival, ["PLAYER_ENTERING_WORLD", "ALERTS:4"]); +} + +/// A durability write runs its watcher's recompute inside its packet (`0x5d97c0` → +/// `0x5d9920`): its signal fires between the packets around it, and a listener of each reads the +/// statuses as of its own. +#[test] +fn a_durability_change_signals_between_its_neighbours() { + let (mut c, _) = client(40); + c.frame(vec![ + vec![system("before")], + vec![values(HELM.0, &[(DURABILITY, 0)])], + vec![system("after")], + ]); + assert_eq!(c.seen(), ["before:0", "ALERTS:4", "after:4"]); +} + +/// The getter reads the statuses the last pass stored, packet by packet: a break, a line, then +/// a repair in one frame read broken at the break and the line, whole at the repair. +#[test] +fn the_status_getter_reads_each_packets_pass() { + let (mut c, _) = client(40); + c.frame(vec![ + vec![values(HELM.0, &[(DURABILITY, 0)])], + vec![system("between")], + vec![values(HELM.0, &[(DURABILITY, 3)])], + vec![values(HELM.0, &[(DURABILITY, 40)])], + ]); + assert_eq!(c.seen(), ["ALERTS:4", "between:4", "ALERTS:3", "ALERTS:0"]); +} + +/// Every pass signals, a status moved or not (`0x4c8085` past the loop): the durability watcher +/// runs it for an item in no region (`0x5d97c0`), and a visible-item change runs it for any +/// player (`0x5dee7a`, ahead of `0x5dee82`'s test for us). A field with no recompute watcher, +/// `MAXDURABILITY`, or a flag bit other than the force-red one (`0x5d9722`), signals nothing. +#[test] +fn every_watched_pass_signals_and_nothing_else_does() { + let (mut c, _) = client(40); + c.frame(vec![vec![values(SPARE.0, &[(DURABILITY, 10)])]]); + assert_eq!(c.seen(), ["ALERTS:0"], "a backpack item's durability"); + c.frame(vec![vec![values( + OTHER, + &[(FIELD_PLAYER_VISIBLE_ITEM_1_CREATOR + 2, SPARE.1)], + )]]); + assert_eq!(c.seen(), ["ALERTS:0"], "another player's visible item"); + c.frame(vec![vec![values(HELM.0, &[(MAX_DURABILITY, 60)])]]); + assert_eq!(c.seen(), Vec::::new(), "the maximum alone"); + c.frame(vec![vec![values(HELM.0, &[(FLAGS, 0x1)])]]); + assert_eq!(c.seen(), Vec::::new(), "a flag bit but force-red"); + c.frame(vec![vec![values(HELM.0, &[(FLAGS, 0x11)])]]); + assert_eq!(c.seen(), ["ALERTS:4"], "the force-red bit"); +} + +/// The temporary-enchant arm (`0x4c8035`-`0x4c806d`) through the watchers: the enchantment's +/// write runs the recompute (`0x5d9b2f`), whose main hand reads 1 with more than 30 s left +/// (`0x5d9d00(1)`, `0x4c8060`). The time packet's setter (`0x5d9cc0`) runs no recompute, so the +/// status stays 1 past the 30 s mark until a watcher's next pass reads 2. +#[test] +fn a_temporary_enchant_reads_one_then_two_at_the_next_pass() { + let (mut c, _) = client(40); + let main_hand = |c: &mut Client| -> i64 { + crate::script_calls::eval_in_vm(c.app.world(), "return GetInventoryAlertStatus(9)") + }; + let time = |seconds: u32| SessionEvent::ItemEnchantTime { + item_guid: SWORD.0, + slot: 1, + seconds, + }; + c.frame(vec![ + vec![time(600)], + vec![values(SWORD.0, &[(TEMP_ENCHANT, 7)])], + ]); + assert_eq!(c.seen(), ["ALERTS:0"]); + assert_eq!(main_hand(&mut c), 1, "more than 30 s left"); + c.frame(vec![vec![time(20)]]); + assert_eq!( + c.seen(), + Vec::::new(), + "the time packet recomputes nothing" + ); + assert_eq!(main_hand(&mut c), 1, "as the last pass left it"); + c.frame(vec![vec![values(SWORD.0, &[(DURABILITY, 49)])]]); + assert_eq!(c.seen(), ["ALERTS:0"]); + assert_eq!(main_hand(&mut c), 2, "30 s or fewer left"); +} + +/// The pass fires its tutorials in its loop (`0x4b5390` with delay 0, `0x4c8002`), each region's +/// after its status is stored and ahead of the pass's signal (`0x4c8085`): Broken Items (36, +/// published 37) between the packets around the break, its listener reading the head broken. +#[test] +fn a_breaks_tutorial_fires_in_the_pass_ahead_of_its_signal() { + let (mut c, _) = client(40); + c.frame(vec![vec![SessionEvent::TutorialFlags(vec![0; 32])]]); + c.frame(vec![]); + c.seen(); + c.frame(vec![ + vec![system("before")], + vec![values(HELM.0, &[(DURABILITY, 0)])], + vec![system("after")], + ]); + assert_eq!( + c.seen(), + ["before:0", "TUTORIAL:37:4", "ALERTS:4", "after:4"] + ); + c.frame(vec![]); + assert_eq!( + c.seen(), + Vec::::new(), + "fired once, not again a frame late" + ); +} diff --git a/crates/benilla-app/src/lanes/arrival_live_tests.rs b/crates/benilla-app/src/lanes/arrival_live_tests.rs index 3bb4dc852..e19bb35c1 100644 --- a/crates/benilla-app/src/lanes/arrival_live_tests.rs +++ b/crates/benilla-app/src/lanes/arrival_live_tests.rs @@ -245,6 +245,8 @@ fn the_cascade_signals_the_lfg_types_twice_between_its_neighbours() { /// A player. const ALICE: u64 = 0x31; +/// Another, listed with [`ALICE`]. +const BOB: u64 = 0x32; /// The display latch tests a line after its sender's name (`0x49d77f` before `0x49db5c`): an /// uncached sender's name is asked at the packet, and the held line does not age, so however long @@ -333,51 +335,58 @@ fn the_latch_holds_a_defence_line_and_drops_a_named_emote() { ); } -/// The party's catch-up for a fresh VM fires after the arrival stamped at our create, as the -/// group list that follows the create signals after the login events. +/// A new VM's first frame signals each group list at its packet: the reference's interface is up +/// before the login goes out (`UI_Init` from `0x46c236`, the send at `0x46c272`), so no list lands +/// ahead of it, and the list handler signals inside itself (`0x5e6c66`) before the next packet runs +/// (`0x537ae5`). So after the arrival stamped at our create, each of two lists signals its own +/// `PARTY_MEMBERS_CHANGED`, ahead of a later packet's line. #[test] -fn a_fresh_vms_party_catch_up_fires_after_entering_the_world() { - use benilla_protocol::messages::{member_status, GroupLootInfo, GroupMemberEntry}; +fn a_new_vms_first_lists_signal_at_their_packets() { + use benilla_protocol::messages::{member_status, GroupMemberEntry}; let mut c = client( r#"Seen = {} local f = CreateFrame("Frame") - for _, e in ipairs({"PLAYER_ENTERING_WORLD", "PARTY_MEMBERS_CHANGED"}) do + for _, e in ipairs({"PLAYER_ENTERING_WORLD", "PARTY_MEMBERS_CHANGED", "CHAT_MSG_SYSTEM"}) do f:RegisterEvent(e) end - f:SetScript("OnEvent", function() table.insert(Seen, event) end)"#, + f:SetScript("OnEvent", function() + table.insert(Seen, event .. ":" .. GetNumPartyMembers()) + end)"#, ); - c.app - .world_mut() - .resource_mut::() - .insert_player(ALICE, "Alice".into(), None); - c.frame(vec![ - vec![me()], - vec![SessionEvent::GroupList { - group_type: 0, - own_flags: 0, - members: vec![GroupMemberEntry { - name: "Alice".into(), - guid: ALICE, + let list = |guids: &[u64]| SessionEvent::GroupList { + group_type: 0, + own_flags: 0, + members: guids + .iter() + .map(|&guid| GroupMemberEntry { + name: format!("M{guid}"), + guid, status: member_status::ONLINE, flags: 0, - }], - leader: ME, - loot: Some(GroupLootInfo { - method: 1, - master: 0, - threshold: 2, - }), - }], + }) + .collect(), + leader: ME, + loot: None, + }; + { + let mut names = c.app.world_mut().resource_mut::(); + names.insert_player(ALICE, "Alice".into(), None); + names.insert_player(BOB, "Bob".into(), None); + } + c.frame(vec![ + vec![me()], + vec![list(&[ALICE])], + vec![list(&[ALICE, BOB])], + vec![system_line("after")], ]); - let seen = c.seen(); assert_eq!( - seen.first().map(String::as_str), - Some("PLAYER_ENTERING_WORLD"), - "{seen:?}" - ); - assert!( - seen.iter().any(|e| e == "PARTY_MEMBERS_CHANGED"), - "{seen:?}" + c.seen(), + [ + "PLAYER_ENTERING_WORLD:0", + "PARTY_MEMBERS_CHANGED:1", + "PARTY_MEMBERS_CHANGED:2", + "CHAT_MSG_SYSTEM:2" + ] ); } @@ -615,6 +624,227 @@ fn a_worldport_latches_the_lines_of_the_next_frame() { ); } +/// A cross-map `SMSG_NEW_WORLD` in a frame, with `needs_ack` as the cross-map one carries it. +fn port() -> SessionEvent { + SessionEvent::Worldport { + map_id: 1, + position: [0.0; 3], + orientation: 0.0, + needs_ack: true, + } +} + +/// A system line on the wire. +fn system_line(text: &str) -> SessionEvent { + SessionEvent::Chat(ChatMessage { + chat_type: CHAT_MSG_SYSTEM, + language: 0, + sender_guid: 0, + target_guid: 0, + sender_name: None, + channel: None, + text: text.into(), + chat_tag: 0, + }) +} + +const LEAVE_SPY: &str = r#"Seen = {} + local f = CreateFrame("Frame") + for _, e in ipairs({"PLAYER_ENTERING_WORLD", "CHAT_MSG_SYSTEM", "PLAYER_LEAVING_WORLD", + "LOGOUT_CANCEL"}) do + f:RegisterEvent(e) + end + f:SetScript("OnEvent", function() + local line = event .. ":" .. tostring(arg1) + if event == "CHAT_MSG_SYSTEM" then line = line .. ":" .. tostring(UnitExists("player")) end + table.insert(Seen, line) + end)"#; + +/// The teardown timer `SMSG_NEW_WORLD` posts at no delay (`0x401bac`) runs at the next tick's +/// start, ahead of its packets (`core/loop`, "What one tick runs"), and its body is one unit +/// (`0x401bc0`): the connection leaves the world (`0x401bd4`, `LOGOUT_CANCEL` for a pending +/// request), the objects are destroyed (`0x401bf7`) and the local player's destructor sweeps +/// (`0x5dd543` → `0x490a9e`), so `PLAYER_LEAVING_WORLD` follows every event the worldport's own +/// tick raised, the lines of the packets on either side of it among them, all of which still read +/// the old world and its pending logout. +#[test] +fn a_worldports_teardown_runs_at_the_next_ticks_start() { + let mut c = client(LEAVE_SPY); + c.frame(vec![vec![me()]]); + assert_eq!(c.seen(), ["PLAYER_ENTERING_WORLD:nil"]); + crate::script_calls::with_hosted_vm(c.app.world_mut(), |vm| { + vm.expect("a VM").run("Logout()").expect("the verb runs") + }); + c.frame(vec![ + vec![system_line("before")], + vec![port()], + vec![system_line("after")], + ]); + assert_eq!( + c.seen(), + ["CHAT_MSG_SYSTEM:before:1", "CHAT_MSG_SYSTEM:after:1"], + "the port's own tick raised them, over the old world and its open logout" + ); + assert!( + c.app + .world() + .resource::() + .pending(), + "the request stands" + ); + c.frame(vec![vec![system_line("next")]]); + assert_eq!( + c.seen(), + ["LOGOUT_CANCEL:nil", "PLAYER_LEAVING_WORLD:nil"], + "the next tick's timer runs first, and its line waits for the next world entry" + ); + c.frame(vec![]); + assert_eq!(c.seen(), Vec::::new(), "once per port"); +} + +/// The leave-world sweep runs inside the object manager's walk at the local player's turn +/// (`0x467800` → `0x5dd543`), so an object created after the player is alive when +/// `PLAYER_LEAVING_WORLD` fires: the target still exists there, and is gone after the walk. +#[test] +fn a_worldports_leave_sees_the_target_created_after_the_player() { + const NPC: u64 = 0xF130_0000_0000_0042; + let mut c = client( + r#"Seen = {} + local f = CreateFrame("Frame") + f:RegisterEvent("PLAYER_LEAVING_WORLD") + f:SetScript("OnEvent", function() + table.insert(Seen, event .. ":" .. tostring(UnitExists("target"))) + end)"#, + ); + c.frame(vec![ + vec![me()], + vec![created( + NPC, + EntityKind::Unit, + &[(FIELD_UNIT_HEALTH, 50), (FIELD_UNIT_MAXHEALTH, 50)], + )], + ]); + let world = c.app.world_mut(); + let npc = world.resource::().0[&NPC]; + *world.resource_mut::() = crate::target::Selection { + target: Some(npc), + guid: Some(NPC), + ..Default::default() + }; + c.frame(vec![]); + c.seen(); + c.frame(vec![vec![port()]]); + assert_eq!(c.seen(), Vec::::new()); + c.frame(vec![]); + assert_eq!(c.seen(), ["PLAYER_LEAVING_WORLD:1"], "the target stands"); + assert!( + !c.app + .world() + .resource::() + .0 + .contains_key(&NPC), + "and goes with the walk" + ); +} + +/// A worldport alone in its frame: nothing fires in it, the leave fires once in the next. +#[test] +fn a_worldport_alone_leaves_in_the_next_frame() { + let mut c = client(LEAVE_SPY); + c.frame(vec![vec![me()]]); + assert_eq!(c.seen(), ["PLAYER_ENTERING_WORLD:nil"]); + c.frame(vec![vec![port()]]); + assert_eq!(c.seen(), Vec::::new()); + c.frame(vec![]); + assert_eq!(c.seen(), ["PLAYER_LEAVING_WORLD:nil"]); + c.frame(vec![]); + assert_eq!(c.seen(), Vec::::new()); +} + +const ROLL_SPY: &str = r#"Seen = {} + local f = CreateFrame("Frame") + for _, e in ipairs({"START_LOOT_ROLL", "CANCEL_LOOT_ROLL"}) do f:RegisterEvent(e) end + f:SetScript("OnEvent", function() + table.insert(Seen, event .. ":" .. tostring(arg1)) + end)"#; + +/// A group loot roll for an item the cache holds, so its frame opens in the frame it arrives. +fn roll_start() -> SessionEvent { + const ROLLED: u32 = 19_019; + SessionEvent::LootStartRoll(benilla_protocol::messages::LootStartRoll { + looted_target: 0xF130_0000_0000_0042, + item_slot: 0, + item_id: ROLLED, + random_property_id: 0, + suffix_factor: 0, + countdown_ms: 60_000, + }) +} + +/// The client with a roll open for the spy's frame. +fn client_with_open_roll() -> Client { + let mut c = client(ROLL_SPY); + c.app + .world_mut() + .resource_mut::() + .insert_template(19_019, Some(crate::items::test_template("Sulfuras"))); + c.frame(vec![vec![me()]]); + c.frame(vec![vec![roll_start()]]); + assert_eq!(c.seen(), ["START_LOOT_ROLL:1"]); + c +} + +/// The world load's body calls `CancelAllLootRolls` (`0x401c2c`), after the objects' walk and +/// before the map load: each open roll signals `CANCEL_LOOT_ROLL` and is freed, in the tick the +/// timer runs, and `PLAYER_LEAVING_WORLD` (the walk's) came before it. +#[test] +fn a_worldport_cancels_the_open_loot_rolls_in_the_next_frame() { + let mut c = client_with_open_roll(); + c.frame(vec![vec![port()]]); + assert_eq!( + c.seen(), + Vec::::new(), + "the port's own tick cancels nothing" + ); + assert!(c + .app + .world() + .resource::() + .holds(1)); + c.frame(vec![]); + assert_eq!( + c.seen(), + ["CANCEL_LOOT_ROLL:1"], + "once, in the timer's tick" + ); + assert!(!c + .app + .world() + .resource::() + .holds(1)); + c.frame(vec![]); + assert_eq!(c.seen(), Vec::::new(), "once per port"); +} + +/// A teleport inside the map (`MSG_MOVE_TELEPORT`) runs no world load, so the roll stands. +#[test] +fn a_same_map_teleport_leaves_the_loot_rolls() { + let mut c = client_with_open_roll(); + c.frame(vec![vec![SessionEvent::Teleport { + guid: ME, + counter: 1, + position: [1.0, 2.0, 3.0], + orientation: 0.0, + }]]); + c.frame(vec![]); + assert_eq!(c.seen(), Vec::::new()); + assert!(c + .app + .world() + .resource::() + .holds(1)); +} + /// The cascade's trainer reset zeroes the guid, the selection and the total (`0x4d73e0`), and not /// the expanded mask (`0xb73a24`): the VM's collapsed lines stay for the next list to reset. #[test] @@ -737,7 +967,7 @@ fn the_cascades_corpse_step_signals_the_range_latch_out() { ); c.app .world_mut() - .resource_mut::() + .resource_mut::() .latch_corpse_in_range_for_test(); c.frame(vec![vec![me()]]); c.frame(vec![]); diff --git a/crates/benilla-app/src/lanes/auction_live_tests.rs b/crates/benilla-app/src/lanes/auction_live_tests.rs index eecb439ca..a886ecdf5 100644 --- a/crates/benilla-app/src/lanes/auction_live_tests.rs +++ b/crates/benilla-app/src/lanes/auction_live_tests.rs @@ -168,8 +168,8 @@ fn boar_says(text: &str) -> SessionEvent { const NAME: &str = "return tostring((GetAuctionItemInfo('list', 1)))"; /// The page lands with silk's record out, so the VM's row holds no name; the record's answer -/// then fills it for a host-lent getter at the call, with no push between, while the VM's copy -/// still holds none until the page's tail runs. The throttle reads the house at the call too. +/// then fills it for a host-lent getter at the call, and the page's tail, which runs at the +/// answer's packet, fills the VM's copy there. The throttle reads the house at the call too. #[test] fn the_auction_getters_read_the_house_at_the_call() { let mut c = client(); @@ -177,12 +177,10 @@ fn the_auction_getters_read_the_house_at_the_call() { assert_eq!(c.eval::(true, NAME), "nil", "the record is out"); c.handle(vec![silk()]); assert_eq!(c.eval::(true, NAME), "Silk Cloth"); - assert_eq!(c.eval::(false, NAME), "nil", "the VM's copy waits"); - c.frame(vec![]); assert_eq!( c.eval::(false, NAME), "Silk Cloth", - "the tail's push" + "the tail's push at the answer's packet" ); const CAN: &str = "return CanSendAuctionQuery() == 1"; @@ -523,7 +521,8 @@ const DEPOSIT: &str = "return CalculateAuctionDeposit(120)"; /// `CalculateAuctionDeposit` and `GetAuctionSellItemInfo` on a sell slot item whose record the /// cache lacks answer the miss (`0x4ce2ca`, `0x4ce726`) and keep the callback `0x4ce2f0` with the /// item's guid (`0x4ce25e`, `0x4ce5e3`), one per call, which signals `NEW_AUCTION_UPDATE` at the -/// record's packet (`0x4ce2fa`); the getters then answer its price and the deposit on it. +/// record's packet (`0x4ce2fa`), their lookups finding the query the item's create sent in +/// flight (`0x5d8300`); the getters then answer its price and the deposit on it. #[test] fn a_sell_item_whose_record_lands_later_signals_the_new_auction_update() { let guid = item_guid(1); @@ -535,13 +534,9 @@ fn a_sell_item_whose_record_lands_later_signals_the_new_auction_update() { .into_iter() .filter(|s| s.starts_with("ItemQuery")) .collect(); - assert_eq!( - queries, - [format!( - "{:?}", - crate::net::ClientCommand::ItemQuery { entry: WOOL, guid } - )], - "one query in flight, with the item's guid" + assert!( + queries.is_empty(), + "the create's query is in flight: {queries:?}" ); c.frame(vec![vec![wool_record()]]); assert_eq!(c.eval::(true, "return Infos"), 2, "one per call"); diff --git a/crates/benilla-app/src/lanes/aura_view_tests.rs b/crates/benilla-app/src/lanes/aura_view_tests.rs index e0efa7e6b..4e72d0b5a 100644 --- a/crates/benilla-app/src/lanes/aura_view_tests.rs +++ b/crates/benilla-app/src/lanes/aura_view_tests.rs @@ -20,20 +20,11 @@ const APPLICATIONS: u16 = 113; /// A flag nibble with a shown bit (`& 0xe`) and the cancelable bit. const SHOWN: u32 = 0x9; -/// One frame: the packets, the unit and resolver feeds' pushes of the frame's state, then the -/// lanes' drain; what the aura spy saw. +/// One frame: the packets, each packet's lanes fired after its handlers, then the frame's drain; +/// what the aura spy saw. fn frame(app: &mut App, packets: Vec>) -> Vec { let world = app.world_mut(); - #[cfg(debug_assertions)] - { - use bevy::ecs::system::RunSystemOnce; - world - .run_system_once(crate::ui_unit::views::mark_frame_start) - .unwrap(); - } crate::net::handlers::dispatch(world, wire_packets(packets)); - crate::ui_unit::run_feed_units_once(world); - crate::ui_aura::run_feed_unit_guids_once(world); crate::lanes::fire_in_order(world); let s = world.non_send_resource_mut::(); let out = s.eval::>("return Auras").unwrap(); diff --git a/crates/benilla-app/src/lanes/bag_tests.rs b/crates/benilla-app/src/lanes/bag_tests.rs index 43f69a109..ec8d9b660 100644 --- a/crates/benilla-app/src/lanes/bag_tests.rs +++ b/crates/benilla-app/src/lanes/bag_tests.rs @@ -98,6 +98,10 @@ fn combo(n: u32) -> SessionEvent { /// the bag equipped, and a VM whose spy records the bag, lock, bank and money events with `arg1`. fn client() -> App { let mut app = crate::game_plugins::schedule_tests::headless_client_unrun(); + // In the world with the interface up, so the dispatch fires each packet's lanes. + app.insert_resource(bevy::prelude::State::new( + crate::client_state::ClientState::InWorld, + )); let world = app.world_mut(); let pairs: Vec<(u16, u32)> = seat(23, POTIONS) .into_iter() @@ -127,6 +131,7 @@ fn client() -> App { }), ); } + crate::ui_action::hold_for_test(world, 5, ACTION_KIND_ITEM, POTION); let mut script = UiScript::new().unwrap(); script.set_action( 5, @@ -602,12 +607,8 @@ fn a_bag_updates_listener_reads_the_seat_its_packet_left() { /// logout runs it: `SMSG_LOGOUT_COMPLETE` and the disconnect through the handler table, which /// free the objects, then the session's end, whose shutdown signals the event with the host lent. fn before_and_at_logout(app: &mut App, expr: &str) -> (String, String) { - use bevy::ecs::system::RunSystemOnce; use std::cell::RefCell; use std::rc::Rc; - app.world_mut() - .run_system_once(crate::ui_char::feed_char) - .unwrap(); let before: String = hosted_eval(app, &format!("return {expr}")); let seen: Rc>> = Rc::default(); let sink = seen.clone(); diff --git a/crates/benilla-app/src/lanes/bank_live_tests.rs b/crates/benilla-app/src/lanes/bank_live_tests.rs index 6904a4ac7..945fe10f7 100644 --- a/crates/benilla-app/src/lanes/bank_live_tests.rs +++ b/crates/benilla-app/src/lanes/bank_live_tests.rs @@ -135,23 +135,18 @@ fn the_bank_getters_read_the_player_at_the_call() { ); } -/// The open's `BANKFRAME_OPENED` sits on the bank lane at its handler's stamp, between the stamps -/// of the handlers before and after it. +/// The open's `BANKFRAME_OPENED` fires inside its packet's dispatch, with no frame after it: the +/// handler's signal runs every listener before the next packet's handler (`0x537ae5`, `0x703e50`). #[test] -fn the_open_is_stamped_at_its_handler() { +fn the_open_fires_inside_its_dispatch() { let mut c = client(); - let before = crate::lanes::stamp(); c.handle(vec![SessionEvent::ShowBank { banker: BANKER }]); - let after = crate::lanes::stamp(); - let stamped = c - .app - .world() - .resource::() - .stamped(); - assert_eq!(stamped.len(), 1); - let (at, event) = stamped[0]; - assert_eq!(event, crate::ui_bank::BankEvent::Opened); - assert!(before < at && at < after, "stamped inside the handler"); + let lane = c.app.world().resource::(); + assert!(lane.stamped().is_empty(), "nothing left on the lane"); + assert!( + c.seen().iter().any(|s| s == "BANKFRAME_OPENED:nil"), + "the open fired inside the dispatch" + ); } /// The open, a refusal's line and a bought slot's watch each fire at their packet's place around diff --git a/crates/benilla-app/src/lanes/book_live_tests.rs b/crates/benilla-app/src/lanes/book_live_tests.rs index c9297428b..973ed3055 100644 --- a/crates/benilla-app/src/lanes/book_live_tests.rs +++ b/crates/benilla-app/src/lanes/book_live_tests.rs @@ -568,3 +568,84 @@ fn the_respec_question_needs_its_trainer_in_range() { assert_eq!(c.seen(), ["CONFIRM_TALENT_WIPE:10000"]); assert_eq!(c.eval::>(true, dist), Some(1)); } + +/// The learn line's strings and a spy for its `CHAT_MSG_SYSTEM`, beside the family's. +fn hear_learn_lines(c: &mut Client) { + c.app + .world_mut() + .non_send_resource::() + .run( + r#" + ERR_LEARN_SPELL_S = "You have learned a new spell: %s." + local g = CreateFrame("Frame") + g:RegisterEvent("CHAT_MSG_SYSTEM") + g:SetScript("OnEvent", function() table.insert(Seen, event .. ":" .. arg1) end) + "#, + ) + .unwrap(); +} + +/// The registrar shows a learn's line after its form list's edge (`0x4b2904`) and ahead of the +/// book's signals (`0x4b29b7`, then `0x4b2b5a`); a rank-up's between its old rank's removal +/// (`0x4b2f5b` → `0x4b2f3f`) and its new rank's add (`0x4b2f68`). +#[test] +fn a_learns_line_falls_between_the_form_list_and_the_book() { + let mut c = client(); + hear_learn_lines(&mut c); + c.app + .world() + .resource::() + .lock() + .apply_flags(&[0u8; 8]); + c.frame(vec![vec![SessionEvent::SpellLearned { spell_id: BEAR }]]); + assert_eq!( + c.seen(), + [ + "UPDATE_SHAPESHIFT_FORMS:nil", + "CHAT_MSG_SYSTEM:You have learned a new spell: Bear Form.", + "SPELLS_CHANGED:nil", + "LEARNED_SPELL_IN_TAB:1", + "TUTORIAL_TRIGGER:40", + ] + ); + c.know(KINDLING_1); + c.frame(vec![vec![SessionEvent::SpellSuperceded { + old_spell_id: KINDLING_1, + new_spell_id: KINDLING_2, + }]]); + assert_eq!( + c.seen(), + [ + "SPELLS_CHANGED:nil", + "CHAT_MSG_SYSTEM:You have learned a new spell: Kindling (Rank 2).", + "SPELLS_CHANGED:nil", + "LEARNED_SPELL_IN_TAB:1", + ] + ); +} + +/// A rank-up reaches the registrar ahead of its player test (`0x5e6363`, then `0x5e6385`), so it +/// shows its line with no player held; a learn joins the initial list and shows none +/// (`0x5e61fb`). +#[test] +fn a_rank_up_shows_its_line_with_no_player_held() { + let mut c = client(); + hear_learn_lines(&mut c); + let world = c.app.world_mut(); + let me = world.resource::().0[&ME]; + world.entity_mut(me).remove::(); + c.know(KINDLING_1); + c.frame(vec![ + vec![SessionEvent::SpellLearned { + spell_id: FROSTBOLT, + }], + vec![SessionEvent::SpellSuperceded { + old_spell_id: KINDLING_1, + new_spell_id: KINDLING_2, + }], + ]); + assert_eq!( + c.seen(), + ["CHAT_MSG_SYSTEM:You have learned a new spell: Kindling (Rank 2)."] + ); +} diff --git a/crates/benilla-app/src/lanes/cast_live_tests.rs b/crates/benilla-app/src/lanes/cast_live_tests.rs index ba674824a..fcb8a9520 100644 --- a/crates/benilla-app/src/lanes/cast_live_tests.rs +++ b/crates/benilla-app/src/lanes/cast_live_tests.rs @@ -142,7 +142,7 @@ fn client() -> Client { .extend([HEAL]); { let mut slots = world.resource_mut::(); - slots.buttons.insert( + slots.staged.insert( 0, ActionButton { slot: 0, @@ -150,7 +150,6 @@ fn client() -> Client { kind: ACTION_KIND_SPELL, }, ); - slots.dirty = true; } let mut c = Client { app, inbound, sent }; c.frame(vec![vec![created( @@ -460,3 +459,297 @@ fn a_failed_results_gcd_clear_reads_the_targeting_word_still_up() { "{seen:?}" ); } + +/// A reagent the refusal below names, whose record the item cache lacks until its answer. +const SHARD: u32 = 6265; + +/// The reagent line's strings, and a spy on the lines, each `UI_ERROR_MESSAGE` as `LINE:`. +fn spy_lines(c: &mut Client) { + c.eval::<()>( + false, + r#"SPELL_FAILED_REAGENTS = "Missing reagent: %s" + ERR_SPELL_FAILED_REAGENTS = "%s" + local g = CreateFrame("Frame") + g:RegisterEvent("UI_ERROR_MESSAGE") + g:SetScript("OnEvent", function() table.insert(Seen, "LINE:" .. arg1) end)"#, + ); +} + +/// Our cast of `spell_id` refused for a missing reagent, its item word `arg`. +fn refuse_for_a_reagent(c: &mut Client, spell_id: u32, arg: Option) { + c.frame(vec![vec![SessionEvent::CastResult { + spell_id, + success: false, + reason: Some(0x5c), + arg, + }]]); +} + +/// [`client`] with [`spy_lines`]; then our cast refused for [`SHARD`], which the cache lacks: the +/// reporter's lookup asks for it and leaves past the line and its log line (`0x6e1ea4`, +/// `0x6e1eab`). +fn refused_for_a_reagent() -> Client { + let mut c = client(); + spy_lines(&mut c); + refuse_for_a_reagent(&mut c, HEAL, Some(SHARD)); + assert!( + c.seen(&["LINE"]).is_empty(), + "no line while the record is asked" + ); + c +} + +/// The answer for [`SHARD`]: its record, or the server's refusal. +fn shard_answer(name: Option<&str>) -> SessionEvent { + SessionEvent::ItemTemplate { + entry: SHARD, + info: name.map(|n| Box::new(crate::items::test_template(n))), + } +} + +/// The record's answer runs the refusal's callback (`ShowItemCastFailure 0x6e29b0`) inside its +/// packet (`ItemCacheReceive 0x55bdb0`): the line fires between the power packets around it. +#[test] +fn a_reagent_line_shows_at_its_records_answer() { + let mut c = refused_for_a_reagent(); + c.frame(vec![ + vec![values(ME, &[(MANA, 90)])], + vec![shard_answer(Some("Soul Shard"))], + vec![values(ME, &[(MANA, 80)])], + ]); + assert_eq!( + c.seen(&["UNIT_MANA", "LINE"]), + [ + "UNIT_MANA:nil:nil", + "LINE:Missing reagent: Soul Shard", + "UNIT_MANA:nil:nil", + ] + ); + c.frame(vec![]); + assert!(c.seen(&["LINE"]).is_empty(), "the callback ran once"); +} + +/// A refusal runs the callback too, whose lookup finds no record: `UNKNOWN` (`0x6e2a49`). +#[test] +fn a_refused_reagent_record_shows_unknown_at_its_answer() { + let mut c = refused_for_a_reagent(); + c.frame(vec![ + vec![values(ME, &[(MANA, 90)])], + vec![shard_answer(None)], + vec![values(ME, &[(MANA, 80)])], + ]); + assert_eq!( + c.seen(&["UNIT_MANA", "LINE"]), + [ + "UNIT_MANA:nil:nil", + "LINE:Missing reagent: UNKNOWN", + "UNIT_MANA:nil:nil", + ] + ); +} + +/// With no frame after them, the getters read through the host the cast state each packet left, +/// inside the call (`0x4e53a0`, `0x6e6e80`): Heal in flight after its start, popped after its +/// result, as the VM's copy holds it once the result's lanes fired; and `SpellStopCasting` finds +/// nothing to stop. +#[test] +fn the_cast_getters_read_each_packets_state_at_the_call() { + let mut c = client(); + cast_heal(&mut c); + let chunk = "return IsCurrentAction(1), SpellIsTargeting()"; + crate::net::handlers::dispatch( + c.app.world_mut(), + vec![SessionEvent::SpellStart { + caster: ME, + spell_id: HEAL, + cast_flags: 0, + cast_time_ms: 2500, + target: None, + ammo_display_id: None, + }], + ); + assert_eq!( + c.eval::<(Option, Option)>(true, chunk), + (Some(1), None) + ); + crate::net::handlers::dispatch( + c.app.world_mut(), + vec![SessionEvent::CastResult { + spell_id: HEAL, + success: true, + reason: None, + arg: None, + }], + ); + assert_eq!( + c.eval::<(Option, Option)>(true, chunk), + (None, None) + ); + assert_eq!( + c.eval::<(Option, Option)>(false, chunk), + (None, None), + "the VM's copy, given the live view at the result's lanes" + ); + c.press("Stopped = SpellStopCasting()"); + assert_eq!(c.eval::>(false, "return Stopped"), None); +} + +/// The targeting word and the auto-repeat key read at the call too (`0x6e6cd0`, `0x6e9fd0`), each +/// written with no push after it: the cursor up for Heal and Heal repeating. `SpellStopTargeting` +/// tests the word at the call and ends it inside it (`0x6e6e30` → `0x6e4900`). +#[test] +fn the_targeting_word_and_the_auto_repeat_key_read_at_the_call() { + let mut c = client(); + let world = c.app.world_mut(); + world.resource_mut::().enter( + HEAL, + crate::spell::CastCommit::Spell, + 0x0002, + ); + world.resource_mut::().0 = Some(HEAL); + let chunk = "return SpellIsTargeting(), IsAutoRepeatAction(1)"; + assert_eq!( + c.eval::<(Option, Option)>(true, chunk), + (Some(1), Some(1)) + ); + assert_eq!( + c.eval::<(Option, Option)>(false, chunk), + (None, None), + "the VM's copy" + ); + c.press("Stopped = SpellStopTargeting()"); + assert_eq!(c.eval::>(false, "return Stopped"), Some(1)); + assert!(!c + .app + .world() + .resource::() + .active()); +} + +/// A refusal of ours with no item word reads -1 (`0x6e736e`), whose ask no answer ever matches +/// (`0x55bdf7`, `0x55be5d`), and one with a word of 0 asks nothing (`0x55ba42`): neither shows a +/// line, now or at an answer, though Heal's reagent is cached and missing from our bags. +#[test] +fn a_reagent_refusal_with_no_item_word_shows_no_line() { + let mut c = client(); + let mut reagents = [(0, 0); 8]; + reagents[0] = (SHARD, 1); + c.app.insert_resource(crate::ui_action::Spells { + catalog: SpellCatalog::from_displays(HashMap::from([( + HEAL, + SpellDisplay { + id: HEAL, + name: "Heal".into(), + reagents, + ..Default::default() + }, + )])), + ..crate::ui_action::Spells::empty_for_tests() + }); + c.app + .world_mut() + .resource_mut::() + .insert_template(SHARD, Some(crate::items::test_template("Soul Shard"))); + spy_lines(&mut c); + for arg in [None, Some(0)] { + refuse_for_a_reagent(&mut c, HEAL, arg); + c.frame(vec![vec![shard_answer(Some("Soul Shard"))]]); + assert!(c.seen(&["LINE"]).is_empty(), "{arg:?}"); + } + assert!( + c.app + .world_mut() + .resource_mut::() + .take_callbacks(0) + .is_empty(), + "a word of 0 keeps no callback" + ); +} + +/// The reagent arm reads the item word alone, never the spell record (`0x6e1e7f`): a refusal of +/// a spell the catalog lacks shows its line at the record's answer under `0xd2`, which the +/// callback picks off the reason (`0x6e29fe`), and with the record cached under the default id +/// `0x2c`, as the reporter skips the record's chain (`0x6e1a7c`). +#[test] +fn a_reagent_line_shows_for_a_spell_with_no_record() { + const UNLISTED: u32 = 99_999; + let mut c = client(); + spy_lines(&mut c); + c.eval::<()>( + false, + r#"ERR_SPELL_FAILED_S = "S:%s" ERR_SPELL_FAILED_REAGENTS = "R:%s""#, + ); + refuse_for_a_reagent(&mut c, UNLISTED, Some(SHARD)); + assert!(c.seen(&["LINE"]).is_empty(), "the record is asked"); + c.frame(vec![vec![shard_answer(Some("Soul Shard"))]]); + assert_eq!(c.seen(&["LINE"]), ["LINE:R:Missing reagent: Soul Shard"]); + refuse_for_a_reagent(&mut c, UNLISTED, Some(SHARD)); + assert_eq!(c.seen(&["LINE"]), ["LINE:S:Missing reagent: Soul Shard"]); +} + +/// A listener's cast, then its failed result in the frame's next packet: `UNIT_MANA`'s listener +/// casts Heal at its packet, arming the GCD, so the result's report finds Heal in flight +/// (`0x6e1a00`), clears the GCD and fires its pair (`0x6e1d89` → `0x6e1630`), whose +/// `SPELL_UPDATE_COOLDOWN` reads it still in flight, then pops it (`0x6e2218`) for +/// `CURRENT_SPELL_CAST_CHANGED` and `SPELLCAST_FAILED`. +#[test] +fn a_listeners_cast_is_in_flight_for_the_next_packets_failure() { + let mut c = client(); + c.app.insert_resource(crate::ui_action::Spells { + catalog: SpellCatalog::from_displays(HashMap::from([( + HEAL, + SpellDisplay { + id: HEAL, + name: "Heal".into(), + icon: Some("Interface\\Icons\\Spell_Holy_Heal".into()), + start_recovery_category: 133, + start_recovery_ms: 1500, + ..Default::default() + }, + )])), + ..crate::ui_action::Spells::empty_for_tests() + }); + c.frame(vec![]); + c.seen(&[]); + c.eval::<()>( + false, + r#"local g = CreateFrame("Frame") + g:RegisterEvent("UNIT_MANA") + g:SetScript("OnEvent", function() + if arg1 == "player" and not Cast then + Cast = true + UseAction(1) + table.insert(Seen, "CAST") + end + end)"#, + ); + c.frame(vec![ + vec![values(ME, &[(MANA, 90)])], + vec![SessionEvent::CastResult { + spell_id: HEAL, + success: false, + reason: Some(0x0b), + arg: None, + }], + ]); + assert_eq!(c.casts(), [HEAL], "the listener's cast went out"); + let seen = c.seen(&[ + "CAST", + "SPELL_UPDATE_COOLDOWN", + "CURRENT_SPELL_CAST_CHANGED", + "SPELLCAST_FAILED", + ]); + // The send's own GCD pair (`0x6e58fb` → `0x4b31b0`) fires inside `UseAction` in the + // reference; here it waits on the lane behind the listener (#2202), so only the result's + // tail is held to the reference. + assert!(seen.iter().any(|s| s == "CAST"), "{seen:?}"); + assert_eq!( + seen[seen.len().saturating_sub(3)..], + [ + "SPELL_UPDATE_COOLDOWN:1:nil", + "CURRENT_SPELL_CAST_CHANGED:nil:nil", + "SPELLCAST_FAILED:nil:nil", + ], + "{seen:?}" + ); +} diff --git a/crates/benilla-app/src/lanes/chat_clock_live_tests.rs b/crates/benilla-app/src/lanes/chat_clock_live_tests.rs new file mode 100644 index 000000000..55e42977c --- /dev/null +++ b/crates/benilla-app/src/lanes/chat_clock_live_tests.rs @@ -0,0 +1,320 @@ +//! The small handler signals and the getters beside them, as a listener reads them: each event +//! fires inside the handler that raises it (`0x537ae5`, `0x703f50`), at its packet's place among a +//! chat line's of the packets around it, and each getter reads the live state at the call. + +use benilla_protocol::field::FIELD_UNIT_HEALTH; +use benilla_protocol::{EntityKind, SessionEvent}; +use benilla_ui::script::UiScript; +use bevy::prelude::*; +use crossbeam_channel::{Receiver, Sender}; + +use super::unit_view_tests::{created, wire_packets}; +use crate::net::ClientCommand; + +const ME: u64 = 0x7; + +/// The whole client, headless, in the world. +struct Client { + app: App, + inbound: Sender, + #[allow(dead_code)] + sent: Receiver, +} + +impl Client { + /// One frame of the client's, with `packets` in the inbound channel, each one packet. + fn frame(&mut self, packets: Vec>) { + for ev in wire_packets(packets) { + self.inbound.send(ev).expect("the inbound channel"); + } + self.app.update(); + } + + /// `chunk`'s answer through the lent host when `live`, else off the VM's copy alone. + fn eval(&mut self, live: bool, chunk: &str) -> T { + if live { + crate::script_calls::with_hosted_vm(self.app.world_mut(), |s| { + s.expect("a VM").eval::(chunk).expect("runs") + }) + } else { + crate::script_calls::eval_in_vm(self.app.world(), chunk) + } + } + + /// `packets` run through their handlers with no frame: the world as the handlers leave it. + fn handle(&mut self, packets: Vec) { + crate::net::handlers::dispatch(self.app.world_mut(), packets); + self.app.world_mut().flush(); + } + + /// What the spy heard since the last call. + fn seen(&mut self) -> Vec { + self.eval(false, "local s = Seen Seen = {} return s") + } +} + +/// The client in the world, and a spy whose line for each event it hears carries its name and +/// first two arguments. +fn client() -> Client { + let mut app = crate::game_plugins::schedule_tests::headless_client(); + app.insert_resource(bevy::ecs::error::DefaultErrorHandler( + bevy::ecs::error::ignore, + )); + let (tx, sent) = crossbeam_channel::unbounded(); + app.insert_resource(crate::net::NetCommands(tx)); + let (inbound, rx) = crossbeam_channel::unbounded(); + app.insert_resource(crate::net::NetEvents::for_test(rx)); + app.update(); + let script = UiScript::new().expect("a VM"); + script + .run( + r#" + Seen = {} + local f = CreateFrame("Frame") + for _, e in ipairs({"TIME_PLAYED_MSG", "PLAYER_SKINNED", "CHAT_MSG_MONSTER_SAY"}) do + f:RegisterEvent(e) + end + f:SetScript("OnEvent", function() + table.insert(Seen, event .. ":" .. tostring(arg1) .. ":" .. tostring(arg2)) + end) + "#, + ) + .unwrap(); + app.insert_non_send_resource(script); + app.insert_resource(State::new(crate::client_state::ClientState::InWorld)); + benilla_world::world_point::init_world_point_resources(app.world_mut()); + app.world_mut().resource_mut::().0 = Some(ME); + let mut c = Client { app, inbound, sent }; + c.frame(vec![vec![created( + ME, + EntityKind::Player, + &[(FIELD_UNIT_HEALTH, 100)], + )]]); + c.frame(vec![]); + c.seen(); + c +} + +/// A monster's line, which shows inside its own packet's handler on the chat lane. +fn boar_says(text: &str) -> SessionEvent { + SessionEvent::Chat(benilla_protocol::messages::ChatMessage { + chat_type: benilla_protocol::messages::CHAT_MSG_MONSTER_SAY, + language: 0, + sender_guid: 0xF130_0000_0045_0003, + target_guid: 0, + sender_name: Some("Boar".into()), + channel: None, + text: text.into(), + chat_tag: 0, + }) +} + +/// What the spy writes for a monster line `text`. +fn said(text: &str) -> String { + format!("CHAT_MSG_MONSTER_SAY:{text}:Boar") +} + +/// `SMSG_PLAYED_TIME` (`0x401850`) signals `TIME_PLAYED_MSG` inside itself (`0x4018df`) and +/// `SMSG_PLAYER_SKINNED` `PLAYER_SKINNED` (`0x5e7d40` → `0x48f412`), each at its packet's place +/// among the lines around it; two answers in one frame are two signals. +#[test] +fn the_played_time_and_the_skin_signal_at_their_packets() { + let mut c = client(); + c.frame(vec![ + vec![boar_says("a")], + vec![SessionEvent::PlayedTime { + total: 3_600, + level: 60, + }], + vec![boar_says("b")], + vec![SessionEvent::PlayerSkinned { free_repop: true }], + vec![boar_says("c")], + vec![SessionEvent::PlayedTime { + total: 3_601, + level: 61, + }], + vec![SessionEvent::PlayerSkinned { free_repop: false }], + ]); + assert_eq!( + c.seen(), + [ + said("a"), + "TIME_PLAYED_MSG:3600:60".into(), + said("b"), + "PLAYER_SKINNED:1:nil".into(), + said("c"), + "TIME_PLAYED_MSG:3601:61".into(), + "PLAYER_SKINNED:0:nil".into(), + ] + ); + c.frame(vec![]); + assert!(c.seen().is_empty(), "nothing fires after"); +} + +/// `SMSG_GAMETIME_SET` naming `hour:minute`, the date unset. +fn time_set(hour: i32, minute: i32) -> SessionEvent { + SessionEvent::GameTimeSet { + time: benilla_protocol::WowTime { + minute, + hour, + ..benilla_protocol::WowTime::UNSET + }, + } +} + +/// `GetGameTime` reads the clock object at the call (`0x515ee0`): each time message is read through +/// the host with no frame after it, where the VM's copy keeps the seed it was built with. +#[test] +fn the_game_clock_reads_at_the_call() { + let mut c = client(); + const READ: &str = "return GetGameTime()"; + c.handle(vec![time_set(10, 30)]); + assert_eq!(c.eval::<(i64, i64)>(true, READ), (10, 30)); + c.handle(vec![time_set(11, 45)]); + assert_eq!(c.eval::<(i64, i64)>(true, READ), (11, 45)); + assert_eq!( + c.eval::<(i64, i64)>(false, READ), + (-1, -1), + "the copy, seeded before any time" + ); +} + +/// A group member's `MSG_MINIMAP_PING` (`0x5e41bd` → `0x4ee330`) stores the point and signals +/// `MINIMAP_PING` with the pinger's token inside its handler, at its packet's place among the lines +/// around it; two pings in one frame are two signals. +#[test] +fn a_members_ping_signals_at_its_packet() { + let mut c = client(); + c.app + .world_mut() + .resource_mut::() + .active = true; + c.app + .world_mut() + .non_send_resource_mut::() + .run( + r#"local f = CreateFrame("Frame") f:RegisterEvent("MINIMAP_PING") + f:SetScript("OnEvent", function() table.insert(Seen, event .. ":" .. arg1) end)"#, + ) + .unwrap(); + c.frame(vec![]); + let ping = |x: f32| SessionEvent::MinimapPing { + guid: 0xDEAD, + x, + y: 0.0, + }; + c.frame(vec![ + vec![boar_says("a")], + vec![ping(10.0)], + vec![boar_says("b")], + vec![ping(20.0)], + ]); + assert_eq!( + c.seen(), + [ + said("a"), + "MINIMAP_PING:player".into(), + said("b"), + "MINIMAP_PING:player".into(), + ] + ); + assert_eq!( + c.app + .world() + .resource::() + .point(), + (20.0, 0.0) + ); +} + +/// Spy on `events` too, each heard as its name and first argument. +fn spy_on(c: &mut Client, events: &[&str]) { + let list: Vec = events.iter().map(|e| format!("{e:?}")).collect(); + c.app + .world_mut() + .non_send_resource_mut::() + .run(&format!( + r#"local f = CreateFrame("Frame") + for _, e in ipairs({{{}}}) do f:RegisterEvent(e) end + f:SetScript("OnEvent", function() table.insert(Seen, event .. ":" .. arg1) end)"#, + list.join(", ") + )) + .unwrap(); +} + +/// The world broadcasts print inside their handlers (`0x49de30`, `0x5e4a09`, `0x4019a0`), each +/// line at its packet's place among the lines around it: a defence message once per defence +/// channel joined (`0x49dd94`), the chat restriction and a transfer abort as system lines. +#[test] +fn the_world_broadcasts_print_at_their_packets() { + let mut c = client(); + spy_on(&mut c, &["CHAT_MSG_SYSTEM", "CHAT_MSG_CHANNEL"]); + c.app + .world_mut() + .non_send_resource_mut::() + .run(r#"ERR_CHAT_RESTRICTED = "restricted" TRANSFER_ABORT_MAX_PLAYERS = "full""#) + .unwrap(); + let world_defense = + benilla_formats::ChatChannelsCatalog::from_rows(vec![benilla_formats::ChatChannelRow { + id: 23, + flags: 0x1_0004, + pattern: "WorldDefense".into(), + shortcut: "WorldDefense".into(), + }]); + c.app.insert_resource(crate::ui_chat::ChannelState { + joined: vec![crate::ui_chat::edit::ChannelSlot::confirmed("WorldDefense", 23).into()], + channels: world_defense, + ..Default::default() + }); + c.frame(vec![ + vec![boar_says("a")], + vec![SessionEvent::DefenseMessage { + zone_id: 40, + text: "under attack".into(), + }], + vec![boar_says("b")], + vec![SessionEvent::ChatRestricted], + vec![boar_says("c")], + vec![SessionEvent::TransferAborted { reason: 1 }], + vec![boar_says("d")], + ]); + assert_eq!( + c.seen(), + [ + said("a"), + "CHAT_MSG_CHANNEL:under attack".into(), + said("b"), + "CHAT_MSG_SYSTEM:restricted".into(), + said("c"), + "CHAT_MSG_SYSTEM:full".into(), + said("d"), + ] + ); +} + +/// The channel lookups read the slot array at the call (`0x49be50`, `0x49bf30`): a VM built with +/// no copy of the slots answers them through the host at once, with no frame to seed it. +#[test] +fn the_channel_lookups_read_the_slots_at_the_call() { + let mut c = client(); + c.app.insert_resource(crate::ui_chat::ChannelState { + joined: vec![ + crate::ui_chat::edit::ChannelSlot::confirmed("General - Elwynn Forest", 1).into(), + crate::ui_chat::edit::ChannelSlot::confirmed("MyChan", 0).into(), + ], + ..Default::default() + }); + c.app + .insert_non_send_resource(UiScript::new().expect("a VM")); + const READ: &str = "local _, a = GetChannelName(2) return a, (GetChannelName('MyChan')), \ + table.getn({GetChannelList()})"; + assert_eq!( + c.eval::<(Option, i64, i64)>(true, READ), + (Some("MyChan".into()), 2, 4) + ); + assert_eq!( + c.eval::<(Option, i64, i64)>(false, READ), + (None, 0, 0), + "the copy holds none" + ); +} diff --git a/crates/benilla-app/src/lanes/close_parked_tests.rs b/crates/benilla-app/src/lanes/close_parked_tests.rs new file mode 100644 index 000000000..77fcd50db --- /dev/null +++ b/crates/benilla-app/src/lanes/close_parked_tests.rs @@ -0,0 +1,345 @@ +//! A close a packet handler runs, parked behind its window's lane, through the stock frames: the +//! engine half (the cell, the latch, the sends, the model) runs inside the handler, as the +//! reference's close core runs there, and only the signals wait for their place. The stock +//! `OnHide` then calls the window's close verb from the parked signal's listeners, which acts on +//! the session that close closed, never on the one a later open in the same frame began +//! ([`crate::ui_session::in_parked_close`]). + +use benilla_protocol::field::FIELD_UNIT_HEALTH; +use benilla_protocol::messages::{ + GossipOption, NpcTextBlock, QuestDetails, QuestGiverList, QuestListEntry, TradeStatus, +}; +use benilla_protocol::{EntityKind, SessionEvent}; +use benilla_ui::script::UiScript; +use bevy::prelude::*; +use crossbeam_channel::{Receiver, Sender}; + +use super::unit_view_tests::{created, wire_packets}; +use crate::net::ClientCommand; + +const ME: u64 = 0x7; +const NPC: u64 = 0xF130_0000_0000_0043; +const OTHER: u64 = 0xF130_0000_0000_0044; +const BOB: u64 = 0x9; +const CAROL: u64 = 0xA; +const MAILBOX: u64 = 0xF110_0000_0000_0B0C; + +/// The stock files every window here needs under it, in the production order with its own. +const KIT: &[&str] = &[ + r"Interface\FrameXML\GameTooltip.xml", + r"Interface\FrameXML\Cooldown.xml", + r"Interface\FrameXML\ItemButtonTemplate.xml", +]; + +/// The whole client, headless, in the world, with stock frames loaded. +struct Client { + app: App, + inbound: Sender, + sent: Receiver, +} + +impl Client { + /// One frame of the client's, with `packets` in the inbound channel, each one packet. + fn frame(&mut self, packets: Vec>) { + for ev in wire_packets(packets) { + self.inbound.send(ev).expect("the inbound channel"); + } + self.app.update(); + } + + /// `chunk`'s answer with the host lent. + fn eval(&mut self, chunk: &str) -> T { + crate::script_calls::with_hosted_vm(self.app.world_mut(), |s| { + s.expect("a VM").eval::(chunk).expect("runs") + }) + } + + /// What went out since the last call, the record queries left out. + fn sent(&mut self) -> Vec { + self.sent + .try_iter() + .map(|c| format!("{c:?}")) + .filter(|c| !c.contains("Query")) + .collect() + } +} + +/// The client in the world with the stock `files` loaded over [`KIT`], and `units` created beside +/// us. +fn client(files: &[&str], units: &[(u64, EntityKind)]) -> Client { + let mut app = crate::game_plugins::schedule_tests::headless_client(); + app.insert_resource(bevy::ecs::error::DefaultErrorHandler( + bevy::ecs::error::ignore, + )); + let (tx, sent) = crossbeam_channel::unbounded(); + app.insert_resource(crate::net::NetCommands(tx)); + let (inbound, rx) = crossbeam_channel::unbounded(); + app.insert_resource(crate::net::NetEvents::for_test(rx)); + app.update(); + let mut script = UiScript::new().expect("a VM"); + script.set_screen_size(1024.0, 768.0); + script.set_text_measurer(Box::new(crate::ui_script::FixedWidthFont(6.0))); + for f in crate::ui_script::test_ui::production_order(&[ + crate::ui_script::test_ui::GOSSIP_UI, + KIT, + files, + ]) { + crate::ui_script::test_ui::load_ui(&script, f); + } + app.insert_non_send_resource(script); + app.insert_resource(State::new(crate::client_state::ClientState::InWorld)); + benilla_world::world_point::init_world_point_resources(app.world_mut()); + app.world_mut().resource_mut::().0 = Some(ME); + let mut c = Client { app, inbound, sent }; + let mut packets = vec![vec![created( + ME, + EntityKind::Player, + &[(FIELD_UNIT_HEALTH, 100)], + )]]; + for &(guid, kind) in units { + packets.push(vec![created(guid, kind, &[(FIELD_UNIT_HEALTH, 100)])]); + } + c.frame(packets); + c.frame(vec![]); + c.sent(); + c +} + +fn visible(c: &mut Client, frame: &str) -> bool { + c.eval(&format!("return {frame}:IsVisible() == 1")) +} + +fn greeting(text_id: u32) -> SessionEvent { + SessionEvent::NpcGreeting { + text_id, + blocks: vec![NpcTextBlock { + probability: 1.0, + male: "Hello".into(), + female: "Hello".into(), + }], + } +} + +fn menu(npc: u64, text_id: u32) -> SessionEvent { + SessionEvent::GossipMenu { + npc, + text_id, + options: vec![GossipOption { + index: 0, + icon: 0, + coded: false, + message: "Browse".into(), + }], + quests: Vec::new(), + } +} + +/// A giver's greeting, then its detail in a later frame: the detail's open registers with no test +/// of the cell (`0x4930d0`), which closes the greeting through the teardown inside the handler +/// (`0x501130`), and the stock `QUEST_FINISHED` handler's `HideUIPanel` → `OnHide` → +/// `CloseQuest()` (`QuestFrame.lua:19`, `:293`) re-enters a teardown that finds its cell zero. The +/// detail's panel keeps its giver, so the Accept answers it. +#[test] +fn a_quest_detail_after_a_greeting_accepts_with_the_givers_guid() { + let _data = benilla_formats::wow_data_or_skip!(); + let mut c = client( + &[r"Interface\FrameXML\QuestFrame.xml"], + &[(NPC, EntityKind::Unit)], + ); + c.frame(vec![vec![SessionEvent::QuestGreeting(QuestGiverList { + npc: NPC, + greeting: "Well met.".into(), + emote_delay: 0, + emote: 0, + quests: vec![QuestListEntry { + quest_id: 51, + icon: 2, + level: 9, + title: "Kobolds".into(), + }], + })]]); + assert!(visible(&mut c, "QuestFrame")); + c.frame(vec![vec![SessionEvent::QuestDetail(QuestDetails { + npc: NPC, + quest_id: 51, + title: "Kobolds".into(), + details: "Clear the mine.".into(), + objectives: String::new(), + auto_finish: 0, + choices: Vec::new(), + rewards: Vec::new(), + money: 0, + reward_spell: 0, + })]]); + assert!(visible(&mut c, "QuestFrame"), "the detail panel is up"); + c.sent(); + let _: () = c.eval("AcceptQuest()"); + assert_eq!( + c.sent(), + [format!( + "{:?}", + ClientCommand::QuestgiverAccept { + npc: NPC, + quest: 51 + } + )] + ); +} + +/// A menu from a second NPC in a later frame: its register closes the first's menu inside the +/// handler (`0x4e1fa0`), whose `GOSSIP_CLOSED` hides the stock frame (`GossipFrame.lua:19`), and +/// `OnHide`'s `CloseGossip()` re-enters a core that finds its cell zero; the second menu stays, so +/// its option goes to the second NPC. +#[test] +fn a_second_npcs_menu_takes_the_option() { + let _data = benilla_formats::wow_data_or_skip!(); + let mut c = client( + &[r"Interface\FrameXML\GossipFrame.xml"], + &[(NPC, EntityKind::Unit), (OTHER, EntityKind::Unit)], + ); + c.frame(vec![vec![greeting(7)], vec![menu(NPC, 7)]]); + assert!(visible(&mut c, "GossipFrame")); + c.frame(vec![vec![menu(OTHER, 7)]]); + assert!(visible(&mut c, "GossipFrame"), "the second menu is up"); + c.sent(); + let _: () = c.eval("SelectGossipOption(1)"); + assert_eq!( + c.sent(), + [format!( + "{:?}", + ClientCommand::GossipSelectOption { + guid: OTHER, + option: 0, + code: None, + } + )] + ); +} + +/// A frame's `CANCELED` then a new request, over Bob's open trade, latched as the interaction +/// unless `latched` is false: the trade commands sent, and the `TRADE_CLOSED`s heard. +fn cancel_then_request(latched: bool) -> (Vec, i64) { + let mut c = client( + &[ + r"Interface\FrameXML\MoneyInputFrame.lua", + r"Interface\FrameXML\MoneyInputFrame.xml", + r"Interface\FrameXML\TradeFrame.xml", + ], + &[(BOB, EntityKind::Player), (CAROL, EntityKind::Player)], + ); + let status = |status| SessionEvent::TradeStatus { status }; + c.frame(vec![ + vec![status(TradeStatus::BeginTrade { partner: BOB })], + vec![status(TradeStatus::OpenWindow)], + ]); + assert!(visible(&mut c, "TradeFrame")); + let _: () = c.eval( + "Closes = 0 local f = CreateFrame('Frame') f:RegisterEvent('TRADE_CLOSED') \ + f:SetScript('OnEvent', function() Closes = Closes + 1 end)", + ); + if !latched { + c.app + .world_mut() + .resource_mut::() + .latch_for_test(OTHER); + } + c.sent(); + c.frame(vec![ + vec![status(TradeStatus::Canceled)], + vec![status(TradeStatus::BeginTrade { partner: CAROL })], + ]); + assert!(!visible(&mut c, "TradeFrame")); + let trade = c + .sent() + .into_iter() + .filter(|s| s.contains("Trade")) + .collect(); + (trade, c.eval("return Closes")) +} + +/// The status arm enters the close core `0x4bf4e0(0, 0)` with Bob latched: its release re-enters +/// the core (`0x493310` → `0x493365`) with the partner still set, whose own release finds the +/// latch zeroed (`0x49334b`); it clears the partner, signals `TRADE_CLOSED`, whose stock `OnHide` +/// calls `CloseTrade()` (`TradeFrame.lua:145`, `0x4bfdc0` → `0x4bf4e0`) and sends a cancel, then +/// sends its own (`0x4bf527`); the outer run signals again and sends the third. Every core call +/// sends (`0x4bf4fb`), all inside the handler, ahead of the next packet's `CMSG_BEGIN_TRADE` +/// (`0x4bf7ee`). +#[test] +fn a_latched_cancel_sends_three_cancels_before_the_next_begin() { + let _data = benilla_formats::wow_data_or_skip!(); + let (sent, closes) = cancel_then_request(true); + let cancel = format!("{:?}", ClientCommand::CancelTrade); + let begin = format!("{:?}", ClientCommand::BeginTrade); + assert_eq!(sent, [cancel.clone(), cancel.clone(), cancel, begin]); + assert_eq!(closes, 2); +} + +/// With another unit latched the release re-enters nothing: one `TRADE_CLOSED`, whose `OnHide`'s +/// `CloseTrade()` sends a cancel, and the core's own. +#[test] +fn an_unlatched_cancel_sends_two_cancels() { + let _data = benilla_formats::wow_data_or_skip!(); + let (sent, closes) = cancel_then_request(false); + let cancel = format!("{:?}", ClientCommand::CancelTrade); + let begin = format!("{:?}", ClientCommand::BeginTrade); + assert_eq!(sent, [cancel.clone(), cancel, begin]); + assert_eq!(closes, 1); +} + +/// The mailbox's close inside a later handler (a register's, `0x493310` → `0x4acd50`) runs its +/// tail there, the deferred refresh's query and its "no mail" stamp (`0x4acda8`, `0x4acdb1`), so +/// an arrival a later packet of the frame brings (`0x4ad620`) stamps over it: mail is waiting. The +/// stock mail window inherits the friends window's tabs, so this runs over the kit alone: what it +/// shows is the engine's. +#[test] +fn an_arrival_after_a_mailbox_close_in_one_frame_leaves_mail_waiting() { + let _data = benilla_formats::wow_data_or_skip!(); + let mut c = client( + &[], + &[(NPC, EntityKind::Unit), (MAILBOX, EntityKind::GameObject)], + ); + crate::ui_mail::open_mailbox(c.app.world_mut(), MAILBOX); + c.frame(vec![]); + assert_eq!( + c.app.world().resource::().mailbox, + Some(MAILBOX) + ); + c.app + .world_mut() + .resource_mut::() + .arm_refresh(); + c.frame(vec![ + vec![greeting(7)], + vec![menu(NPC, 7)], + vec![SessionEvent::ReceivedMail { seconds: 0.0 }], + ]); + assert_eq!( + c.app.world().resource::().mailbox, + None + ); + assert_eq!(c.eval::>("return HasNewMail()"), Some(1)); +} + +/// `SMSG_SHOW_BANK` from the banker whose window is open (`0x4f84d0(banker)`) closes it first, +/// with no test of the cell (`0x4f8507`), and opens it again; the stock `OnHide`'s +/// `CloseBankFrame()` (`BankFrame.xml:523`) re-enters the close of the session it hid and leaves +/// the new one open. +#[test] +fn a_bank_reopened_while_open_stays_open() { + const BANKER: u64 = NPC; + let _data = benilla_formats::wow_data_or_skip!(); + // The bag kit: the window's `OnHide` closes the bank's bags (`CloseBag`) before it calls + // `CloseBankFrame()`. + let mut c = client( + crate::ui_script::test_ui::BAG_UI, + &[(BANKER, EntityKind::Unit)], + ); + c.frame(vec![vec![SessionEvent::ShowBank { banker: BANKER }]]); + assert!(visible(&mut c, "BankFrame")); + c.frame(vec![vec![SessionEvent::ShowBank { banker: BANKER }]]); + assert_eq!( + c.app.world().resource::().banker, + Some(BANKER) + ); + assert!(visible(&mut c, "BankFrame")); +} diff --git a/crates/benilla-app/src/lanes/cooldown_live_tests.rs b/crates/benilla-app/src/lanes/cooldown_live_tests.rs index b52293cea..5c8bfd220 100644 --- a/crates/benilla-app/src/lanes/cooldown_live_tests.rs +++ b/crates/benilla-app/src/lanes/cooldown_live_tests.rs @@ -165,10 +165,9 @@ fn client() -> Client { (2, POTION, ACTION_KIND_ITEM), ] { slots - .buttons + .staged .insert(slot, ActionButton { slot, action, kind }); } - slots.dirty = true; } crate::items::test_spawn_item( world, @@ -264,11 +263,122 @@ fn an_item_cooldowns_listeners_read_its_packets_list() { ); } -/// The getters answer the same through the lent host as off the frame's snapshots wherever the -/// snapshots are current: every slot, cold and running. The book and the bags are read through -/// the host alone, so their lines are the live read's. +/// A cooldown query that missed its record left the callback `0x6e2f70` on the item cache +/// (`0x6e2efb`), and the record's answer runs it inside its handler (`0x55bdb0`): the query again, +/// and with the item's cooldown running the pair and the bags (`0x6e2f89`, `0x6e2f8e`), at the +/// answer's place. So with the answer first and a spell cooldown after it in one frame, the +/// record's flush fires first and reads Frost Nova cold. #[test] -fn every_cooldown_getter_answers_the_same_live_as_off_the_snapshot() { +fn a_cooldown_querys_record_flushes_at_its_answers_place() { + const HEARTHSTONE: u32 = 6948; + const HEARTH: u32 = 8690; + let mut c = client(); + let world = c.app.world_mut(); + { + let mut slots = world.resource_mut::(); + slots.buttons.insert( + 3, + ActionButton { + slot: 3, + action: HEARTHSTONE, + kind: ACTION_KIND_ITEM, + }, + ); + } + world + .resource_mut::() + .apply_wire_item_cooldown(HEARTHSTONE, HEARTH, std::time::Instant::now()); + c.frame(vec![]); + // The button's cooldown read (`ActionButton_UpdateCooldown`), whose query misses the record. + c.eval::<()>(true, "GetActionCooldown(4)"); + c.seen(&[]); + let mut record = crate::items::test_template("Hearthstone"); + record.use_spell = Some(benilla_protocol::messages::ItemUseSpell { + spell_id: HEARTH, + cooldown_ms: -1, + category: 0, + category_cooldown_ms: -1, + }); + c.frame(vec![ + vec![SessionEvent::ItemTemplate { + entry: HEARTHSTONE, + info: Some(Box::new(record)), + }], + vec![spell_cooldown(FROST_NOVA, 10_000)], + ]); + assert_eq!( + c.seen(&[ + "ACTIONBAR_UPDATE_COOLDOWN", + "SPELL_UPDATE_COOLDOWN", + "BAG_UPDATE_COOLDOWN" + ]), + [ + "ACTIONBAR_UPDATE_COOLDOWN:0:0:0:0:0:0", + "SPELL_UPDATE_COOLDOWN:0:0:0:0:0:0", + "BAG_UPDATE_COOLDOWN:0:0:0:0:0:0", + "ACTIONBAR_UPDATE_COOLDOWN:10:0:0:10:0:0", + "SPELL_UPDATE_COOLDOWN:10:0:0:10:0:0", + ] + ); +} + +/// `SMSG_PET_SPELLS` derives the macros that follow the pet's book after its book's sort and +/// ahead of `SetPetGuid` (`0x4bdadb` → `0x4b2fd0`, `0x4bdae0` → `0x4f0ce0`, `0x4bdaf0` → +/// `0x4bc7e0`): a `/cast` of the pet's spell that missed is still unbound to the sort's +/// `SPELLS_CHANGED`, and bound out of the pet's book to `SetPetGuid`'s `PET_BAR_UPDATE`, which +/// `GetActionAutocast` reads through the record's book (`0x4e6fcb`). +#[test] +fn a_pet_spell_list_binds_its_macros_between_its_sort_and_its_pet() { + use benilla_protocol::messages::{ + PetActionEntry, PetSpells, ACTION_KIND_MACRO, PET_ACT_ENABLED, + }; + const PET: u64 = 0x2A; + const SEDUCTION: u32 = 6358; + let mut c = client(); + let world = c.app.world_mut(); + world.insert_resource(spells_with(&[SEDUCTION])); + { + let mut script = world.non_send_resource_mut::(); + script.run(r#"SLASH_CAST1 = "/cast""#).unwrap(); + script.set_macros(benilla_ui::script::MacroState::from_scopes( + vec![benilla_ui::script::MacroView { + name: "Sed".into(), + body: format!("/cast Spell {SEDUCTION}"), + ..Default::default() + }], + Vec::new(), + )); + // The load's derivation, with no pet: a miss. + script.derive_macro_bindings(|_, _| true); + } + crate::ui_action::hold_for_test(world, 4, ACTION_KIND_MACRO, 1); + c.frame(vec![]); + c.eval::<()>( + false, + r#"local g = CreateFrame("Frame") + g:RegisterEvent("SPELLS_CHANGED") + g:RegisterEvent("PET_BAR_UPDATE") + g:SetScript("OnEvent", function() + table.insert(Seen, "PET:" .. event .. ":" .. tostring(GetActionAutocast(4))) + end)"#, + ); + c.seen(&[]); + let entry = PetActionEntry::from(SEDUCTION | (u32::from(PET_ACT_ENABLED) << 24)); + c.frame(vec![vec![SessionEvent::PetSpells(Box::new(PetSpells { + pet_guid: PET, + spells: vec![entry], + ..Default::default() + }))]]); + assert_eq!( + c.seen(&["PET"]), + ["PET:SPELLS_CHANGED:nil", "PET:PET_BAR_UPDATE:1"] + ); +} + +/// The getters answer through the lent host for every slot, the book and the bags, cold and +/// running. +#[test] +fn every_cooldown_getter_answers_live_cold_and_running() { let mut c = client(); let chunk = r#" local out = {} @@ -281,20 +391,8 @@ fn every_cooldown_getter_answers_the_same_live_as_off_the_snapshot() { note("bag 0 1", GetContainerItemCooldown(0, 1)) note("bag 0 2", GetContainerItemCooldown(0, 2)) return out"#; - let agree = |c: &mut Client, why: &str| { - let snapshot: Vec = c.eval(false, chunk); - let live: Vec = c.eval(true, chunk); - let unbooked = |lines: &[String]| -> Vec { - lines - .iter() - .filter(|l| !l.starts_with("spell ") && !l.starts_with("bag ")) - .cloned() - .collect() - }; - assert_eq!(unbooked(&snapshot), unbooked(&live), "{why}"); - live - }; - let cold = agree(&mut c, "all cold"); + let agree = |c: &mut Client| -> Vec { c.eval(true, chunk) }; + let cold = agree(&mut c); assert!(cold.iter().any(|l| l == "action 1 0,0,1"), "{cold:#?}"); assert!(cold.iter().any(|l| l == "action 4 0,0,0"), "{cold:#?}"); c.frame(vec![ @@ -304,7 +402,7 @@ fn every_cooldown_getter_answers_the_same_live_as_off_the_snapshot() { spell_id: POTION_SPELL, }], ]); - let running = agree(&mut c, "two running"); + let running = agree(&mut c); for prefix in ["action 1 ", "spell 1 ", "action 3 ", "bag 0 1 "] { let line = running .iter() @@ -453,31 +551,19 @@ fn the_pet_book_and_a_pet_bound_slot_read_the_pets_list_inside_their_packet() { .resource_mut::() .0 .insert(PET, pet); - { - let mut slots = world.resource_mut::(); - slots.buttons.insert( - 3, - ActionButton { - slot: 3, - action: 1, - kind: ACTION_KIND_MACRO, - }, - ); - slots.dirty = true; - } + crate::ui_action::hold_for_test(world, 4, ACTION_KIND_MACRO, 1); c.frame(vec![]); c.frame(vec![]); - c.app - .world_mut() - .resource_mut::() - .0 - .insert( + crate::ui_macro::bind_for_test( + &mut c.app.world_mut().non_send_resource_mut::(), + &[( 1, crate::ui_macro::Bound { spell: crate::ui_macro::BoundSpell::Spell(BITE), pet_book: true, }, - ); + )], + ); c.frame(vec![]); c.eval::<()>( false, @@ -502,3 +588,128 @@ fn the_pet_book_and_a_pet_bound_slot_read_the_pets_list_inside_their_packet() { // The book sorts Bite ahead of Growl. assert_eq!(c.seen(&["PET"]), ["PET:0:3:0", "PET:4:3:4"]); } + +/// A cross-map `SMSG_NEW_WORLD` in a frame, as the cross-map one carries `needs_ack`. +fn port() -> SessionEvent { + SessionEvent::Worldport { + map_id: 1, + position: [0.0; 3], + orientation: 0.0, + needs_ack: true, + } +} + +/// Frost Nova's and Blink's action slots and the potion's bag slot, as `GetActionCooldown` and +/// `GetContainerItemCooldown` read the lists through the lent host: the durations in seconds. +fn running(c: &mut Client) -> (f64, f64, f64) { + c.eval( + true, + "local _, a = GetActionCooldown(1) local _, b = GetActionCooldown(2) \ + local _, p = GetContainerItemCooldown(0, 1) return a, b, p", + ) +} + +/// The records both lists hold: the player's, then the pet's. +fn held(c: &Client) -> (usize, usize) { + let world = c.app.world(); + ( + world.resource::().record_count(), + world + .resource::() + .cooldowns + .record_count(), + ) +} + +/// Frost Nova on 10 s, the potion on the client's 30 s, and Blink on the pet's list. +fn running_lists() -> Client { + let mut c = client(); + c.frame(vec![ + vec![spell_cooldown(FROST_NOVA, 10_000)], + vec![SessionEvent::ItemCooldown { + item_guid: POTION_GUID, + spell_id: POTION_SPELL, + }], + ]); + let spells = spells(); + c.app + .world_mut() + .resource_mut::() + .cooldowns + .apply_spell_cooldowns( + [(BLINK, 15_000, spells.catalog.get(BLINK))], + &crate::spell::SpellModifiers::default(), + crate::spell::CategoryPad::Skip, + std::time::Instant::now(), + ); + // The pet record's flush fires with the frame's lanes. + c.frame(vec![]); + c.seen(&[]); + assert_eq!(running(&mut c), (10.0, 0.0, 30.0)); + assert_eq!( + held(&c), + (2, 1), + "Frost Nova's and the potion's, and Blink's" + ); + c +} + +/// The world load's body calls `ClearItemAndSpellCooldowns` (`0x401c17` → `0x6e9ad0`), in the tick +/// the timer runs: both history lists emptied and the item cooldowns freed, with no flush, so no +/// cooldown event fires. The server's `SMSG_INITIAL_SPELLS` after it then seeds only what it lists. +#[test] +fn a_worldport_empties_the_cooldowns_and_the_resend_seeds_only_what_it_lists() { + let mut c = running_lists(); + c.frame(vec![vec![port()]]); + assert_eq!(held(&c), (2, 1), "the port's own tick clears nothing"); + c.frame(vec![]); + // The potion goes with the objects, so its getter reads cold whatever its record does: the + // lists are read by their records. + assert_eq!( + held(&c), + (0, 0), + "the timer's tick empties both lists, the item cooldown with them" + ); + assert_eq!(running(&mut c), (0.0, 0.0, 0.0)); + assert_eq!( + c.seen(&[ + "ACTIONBAR_UPDATE_COOLDOWN", + "SPELL_UPDATE_COOLDOWN", + "BAG_UPDATE_COOLDOWN" + ]), + Vec::::new(), + "the clear signals nothing" + ); + c.frame(vec![vec![SessionEvent::SpellBook { + spell_ids: vec![FROST_NOVA, BLINK], + cooldowns: vec![benilla_protocol::messages::SpellCooldown { + spell_id: BLINK as u16, + item_id: 0, + category: 0, + spell_cd_ms: 20_000, + category_cd_ms: 0, + }], + }]]); + let (nova, blink, _) = running(&mut c); + assert_eq!( + (nova, blink, held(&c).0), + (0.0, 20.0, 1), + "Blink alone, as the resend lists it" + ); +} + +/// A teleport inside the map (`MSG_MOVE_TELEPORT`) runs no world load: both lists stand. +#[test] +fn a_same_map_teleport_leaves_the_cooldowns() { + let mut c = running_lists(); + let before = held(&c); + c.frame(vec![vec![SessionEvent::Teleport { + guid: ME, + counter: 1, + position: [1.0, 2.0, 3.0], + orientation: 0.0, + }]]); + c.frame(vec![]); + assert_eq!(running(&mut c), (10.0, 0.0, 30.0)); + assert_eq!(held(&c), before); +} diff --git a/crates/benilla-app/src/lanes/deactivate_live_tests.rs b/crates/benilla-app/src/lanes/deactivate_live_tests.rs new file mode 100644 index 000000000..c2126dec9 --- /dev/null +++ b/crates/benilla-app/src/lanes/deactivate_live_tests.rs @@ -0,0 +1,324 @@ +//! An item's deactivate through the whole client: the out-of-range list's release runs the item's +//! vtable slot 1 (`0x464920` → `[vtable+0x4]` at `0x46496f`, `CGItem_C::Deactivate 0x5d8660`), +//! whose head lets go of what still names the item inside the release's packet: the loot window +//! looting it (`0x5d869b`), the pending record's cast from it (`0x5d86c4`), the cursor holding it +//! (`0x5d86e9`) and the reader on it (`0x5d8713`). A line in the next packet reads what each left. + +use benilla_protocol::messages::loot_type; +use benilla_protocol::SessionEvent; +use benilla_ui::script::UiScript; + +use super::lock_live_tests::{client_with, spare, system, Client, SPARE}; +use crate::net::ClientCommand; + +/// The spy: each signal the legs raise, and at each system line whether the cursor holds an item +/// (`CursorHasItem`). +const SPY: &str = r#"Seen = {} + local f = CreateFrame("Frame") + for _, e in ipairs({"CHAT_MSG_SYSTEM", "ITEM_LOCK_CHANGED", "CURSOR_UPDATE", "LOOT_OPENED", + "LOOT_CLOSED", "ITEM_TEXT_CLOSED", "SPELLCAST_FAILED", "SPELLCAST_STOP"}) do + f:RegisterEvent(e) + end + f:SetScript("OnEvent", function() + if event == "CHAT_MSG_SYSTEM" then + table.insert(Seen, arg1 .. ":" .. tostring(CursorHasItem())) + else + table.insert(Seen, event) + end + end)"#; + +/// A use spell, for the pending record's cast. +const SPELL: u32 = 7_001; + +/// The release of [`SPARE`], then a line, in one frame. +fn release_then_line(c: &mut Client) { + c.frame(vec![ + vec![SessionEvent::ObjectsRemoved(vec![SPARE.0])], + vec![system("after")], + ]); +} + +/// The cursor leg (`0x5d86c9`-`0x5d86e9`): a held item released lets the cursor go as +/// `ClearCursor(1, 1)` does, its unlock first (`0x4951d9`), then `CURSOR_UPDATE`, inside the +/// release's packet; the item is unlocked. +#[test] +fn a_released_item_on_the_cursor_is_let_go_and_unlocked() { + let mut c = client_with(SPY); + crate::script_calls::with_hosted_vm(c.app.world_mut(), |s| { + s.expect("a VM") + .run("PickupContainerItem(0, 1)") + .expect("the pickup runs") + }); + { + let script = c.app.world().non_send_resource::(); + assert_eq!(script.cursor_item().map(|i| i.guid), Some(SPARE.0), "held"); + assert!(script.item_locked(SPARE.0), "the pickup's lock"); + } + c.seen(); + release_then_line(&mut c); + assert_eq!( + c.seen(), + ["ITEM_LOCK_CHANGED", "CURSOR_UPDATE", "after:nil"] + ); + let script = c.app.world().non_send_resource::(); + assert!(!script.item_locked(SPARE.0), "unlocked"); +} + +/// The loot leg (`0x5d867f`-`0x5d869b`): a window looting the released item closes as +/// `0x48f200(1, 0, 0)` does, with its `CMSG_LOOT_RELEASE`, an item source's two unlocks +/// (`0x48f2bd`, `0x4c1d36`) and `LOOT_CLOSED` (`0x4c1dac`), inside the release's packet. +#[test] +fn a_released_item_closes_the_window_looting_it() { + let mut c = client_with(SPY); + // `OpenItem` arms the latch with the item it opens (`0x5edcc0`), which admits its response. + c.app + .world_mut() + .resource_mut::() + .0 = Some(SPARE.0); + c.frame(vec![vec![SessionEvent::LootResponse { + guid: SPARE.0, + loot_type: loot_type::CORPSE, + gold: 5, + items: Vec::new(), + }]]); + assert_eq!( + c.app + .world() + .resource::() + .source(), + Some(SPARE.0), + "the window loots the item" + ); + c.seen(); + c.sent.try_iter().for_each(drop); + release_then_line(&mut c); + assert_eq!( + c.seen(), + [ + "ITEM_LOCK_CHANGED", + "ITEM_LOCK_CHANGED", + "LOOT_CLOSED", + "after:nil" + ] + ); + let sent: Vec = c.sent.try_iter().collect(); + assert!( + sent.iter() + .any(|s| matches!(s, ClientCommand::LootRelease { guid } if *guid == SPARE.0)), + "the release goes out: {sent:?}" + ); + assert_eq!( + c.app + .world() + .resource::() + .source(), + None + ); +} + +/// The reader leg (`0x5d86ee`-`0x5d8713`): a reader open on the released item closes as +/// `0x4e32e0` of a zero guid does: its latch release re-enters the core, which signals first +/// (`0x493310`), then the core's own `ITEM_TEXT_CLOSED`, inside the release's packet. +#[test] +fn a_released_item_closes_the_reader_on_it() { + let mut c = client_with(SPY); + let world = c.app.world_mut(); + world + .resource_mut::() + .open_letter(SPARE.0, 1); + // The open's tail registers the reader on the latch (`0x4e349a`). + crate::ui_session::register(world, SPARE.0); + c.seen(); + release_then_line(&mut c); + assert_eq!( + c.seen(), + ["ITEM_TEXT_CLOSED", "ITEM_TEXT_CLOSED", "after:nil"] + ); + let world = c.app.world(); + assert_eq!( + world + .resource::() + .object(), + None + ); + assert_eq!( + world.resource::().guid(), + None + ); +} + +/// The cast leg (`0x5d86a0`-`0x5d86c4`): a cast whose pending record's source is the released item +/// is cancelled as `CancelCast(1, 0, 0x1c)` does: the slot pops and `SPELLCAST_FAILED` fires for +/// our record, with no `CMSG_CANCEL_CAST`, inside the release's packet. +#[test] +fn a_released_item_cancels_the_cast_from_it() { + let mut c = client_with(SPY); + { + let mut pending = c + .app + .world_mut() + .resource_mut::(); + pending.push_cast( + SPELL, + Some(benilla_protocol::messages::ITEM_FLAG_PLAYERCAST), + Some(SPARE.0), + ); + pending.fill_record(); + pending.fill_record_spell(SPELL); + pending.fill_record_item(Some(SPARE.0)); + } + release_then_line(&mut c); + assert_eq!(c.seen(), ["SPELLCAST_FAILED", "after:nil"]); + assert_eq!( + c.app + .world() + .resource::() + .current(), + None, + "the slot popped" + ); + let sent: Vec = c.sent.try_iter().collect(); + assert!( + !sent + .iter() + .any(|s| matches!(s, ClientCommand::CancelCast { .. })), + "nothing sent: {sent:?}" + ); +} + +/// A disenchant window with a row left on the released item (`0x48f245`-`0x48f264`): the close +/// sweeps it inside the deactivate, the item still live, so the sweep's end finds contents +/// (`0x4c2228` → `0x4c2a8c`) and signals `LOOT_OPENED` (`0x4c2240`), the window kept, with no +/// release and no `LOOT_CLOSED`. +#[test] +fn a_released_disenchanted_item_sweeps_its_window_and_keeps_it() { + const ESSENCE: u32 = 10_938; + let mut c = client_with(SPY); + c.app + .world_mut() + .resource_mut::() + .0 = Some(SPARE.0); + c.app + .world_mut() + .resource_mut::() + .insert_template(ESSENCE, Some(crate::items::test_template("Essence"))); + c.frame(vec![vec![SessionEvent::LootResponse { + guid: SPARE.0, + loot_type: loot_type::DISENCHANTING, + gold: 0, + items: vec![benilla_protocol::messages::LootItem { + slot: 0, + item_id: ESSENCE, + count: 1, + display_info_id: 0, + random_property_id: 0, + slot_type: benilla_protocol::messages::slot_type::ALLOW_LOOT, + }], + }]]); + c.seen(); + c.sent.try_iter().for_each(drop); + release_then_line(&mut c); + assert_eq!(c.seen(), ["LOOT_OPENED", "after:nil"]); + let sent: Vec = c.sent.try_iter().collect(); + assert!( + matches!(sent[..], [ClientCommand::AutostoreLootItem { slot: 0 }]), + "the row's take alone: {sent:?}" + ); + assert_eq!( + c.app + .world() + .resource::() + .source(), + Some(SPARE.0), + "the window stays" + ); +} + +/// A destroy for a guid neither live nor released releases nothing (`0x464931`, `0x46493a`): a +/// reader on it stays open. +#[test] +fn a_destroy_of_an_unknown_guid_runs_no_deactivate() { + const GHOST: u64 = (benilla_protocol::guid::HIGH_ITEM as u64) << 48 | 0x99; + let mut c = client_with(SPY); + c.app + .world_mut() + .resource_mut::() + .open_letter(GHOST, 1); + c.frame(vec![ + vec![SessionEvent::ObjectDestroyed(GHOST)], + vec![system("after")], + ]); + assert_eq!(c.seen(), ["after:nil"]); + assert_eq!( + c.app + .world() + .resource::() + .object(), + Some(GHOST) + ); +} + +/// The record set-up's spy: each `BAG_UPDATE` with its bag (the set-up's `0x5d85e8` for our +/// item in the backpack), and each system line. +const SET_UP_SPY: &str = r#"Seen = {} + local f = CreateFrame("Frame") + f:RegisterEvent("BAG_UPDATE") + f:RegisterEvent("CHAT_MSG_SYSTEM") + f:SetScript("OnEvent", function() + if event == "BAG_UPDATE" then + table.insert(Seen, "BAG_UPDATE " .. arg1) + else + table.insert(Seen, arg1) + end + end)"#; + +/// [`SPARE`]'s record, answered. +fn spare_record() -> SessionEvent { + SessionEvent::ItemTemplate { + entry: SPARE.1, + info: Some(Box::new(crate::items::test_template("Spare"))), + } +} + +/// The record answered after a destroy and a new object under the guid, both before it: the +/// destroy's deactivate dropped the first object's set-up callback (`0x55c0c0` at `0x5d8733`), so +/// the answer sets up the new object once. +#[test] +fn a_destroy_before_the_record_leaves_the_next_object_one_set_up() { + let mut c = client_with(SET_UP_SPY); + c.frame(vec![ + vec![SessionEvent::ObjectDestroyed(SPARE.0)], + vec![spare()], + ]); + c.seen(); + c.frame(vec![vec![spare_record()], vec![system("after")]]); + assert_eq!(c.seen(), ["BAG_UPDATE 0", "after"]); +} + +/// The record answered after a release and the item's bring-back: the release dropped its +/// set-up callback, and the bring-back's slot 3 asked again (`0x5d8430` → `0x5d8300`), so the +/// answer sets it up once. +#[test] +fn a_release_before_the_record_and_a_bring_back_set_up_once() { + let mut c = client_with(SET_UP_SPY); + c.frame(vec![ + vec![SessionEvent::ObjectsRemoved(vec![SPARE.0])], + vec![spare()], + ]); + c.seen(); + c.frame(vec![vec![spare_record()], vec![system("after")]]); + assert_eq!(c.seen(), ["BAG_UPDATE 0", "after"]); +} + +/// A released item whose record landed while it was away sets up again as it comes back: its +/// slot 3 finds the record cached (`0x5d8430` → `0x5d8300` → `0x5d8440`), and the set-up's +/// `BAG_UPDATE` fires inside the bring-back's packet. +#[test] +fn a_released_item_brought_back_sets_up_off_its_cached_record() { + let mut c = client_with(SET_UP_SPY); + c.frame(vec![vec![SessionEvent::ObjectsRemoved(vec![SPARE.0])]]); + c.frame(vec![vec![spare_record()]]); + c.seen(); + c.frame(vec![vec![spare()], vec![system("after")]]); + assert_eq!(c.seen(), ["BAG_UPDATE 0", "after"]); +} diff --git a/crates/benilla-app/src/lanes/death_live_tests.rs b/crates/benilla-app/src/lanes/death_live_tests.rs new file mode 100644 index 000000000..adc169fbb --- /dev/null +++ b/crates/benilla-app/src/lanes/death_live_tests.rs @@ -0,0 +1,263 @@ +//! The death getters as a listener reads them, and the death signals at their packets. The +//! getters read the interface's death globals at the call (`GetCorpseRecoveryDelay` `0x48b5d0`); +//! the resurrect offer shows inside its packet or its caster's name answer (`0x5e7bc0`, +//! `0x5e7ca0` → `0x5ded50`), the revive's `PLAYER_ALIVE` inside the health watcher's run +//! (`0x6047ee` → `0x5fef70`), and the reclaim delay's range event inside its handler (`0x4962d0`). + +use benilla_protocol::SessionEvent; +use benilla_ui::script::UiScript; +use bevy::prelude::*; + +use super::unit_view_tests::{client, created, fall, frame, health, values}; + +/// [`client`]'s active player. +const ME: u64 = 0x7; +/// A fall's `UNIT_COMBAT` on our dead body, as [`client`]'s spy records it. +const FELL: &str = "UNIT_COMBAT:player:0"; +const PRIEST: u64 = 0x51; + +/// [`client`] with a spy on the death signals, each with what its listener reads: the offer's +/// name and timer, the corpse's delay. +fn death_client() -> App { + let mut app = client(); + app.world_mut() + .non_send_resource_mut::() + .run( + r#" + local f = CreateFrame("Frame") + for _, e in ipairs({"RESURRECT_REQUEST", "PLAYER_ALIVE", "CORPSE_IN_RANGE", + "CONFIRM_XP_LOSS"}) do + f:RegisterEvent(e) + end + f:SetScript("OnEvent", function() + if event == "RESURRECT_REQUEST" then + table.insert(Seen, event .. ":" .. arg1 .. ":" .. tostring(ResurrectHasTimer())) + elseif event == "CORPSE_IN_RANGE" then + table.insert(Seen, event .. ":" .. GetCorpseRecoveryDelay()) + else + table.insert(Seen, event) + end + end) + "#, + ) + .unwrap(); + app +} + +/// [`death_client`] after our death's packet, the frame's signals taken. +fn dead_client() -> App { + let mut app = death_client(); + frame(&mut app, vec![values(ME, &health(0))]); + app +} + +fn offer(name: &str) -> SessionEvent { + SessionEvent::ResurrectRequest { + caster: PRIEST, + name: name.into(), + sickness: false, + has_timer: true, + } +} + +/// With no frame after the reclaim delay's packet, `GetCorpseRecoveryDelay` reads the delay +/// through the host; the VM's copy, which nothing pushes, reads none. +#[test] +fn the_recovery_delay_reads_the_stores_at_the_call() { + let mut app = dead_client(); + crate::net::handlers::dispatch( + app.world_mut(), + vec![SessionEvent::CorpseReclaimDelay { delay_ms: 30_000 }], + ); + let chunk = "return GetCorpseRecoveryDelay()"; + let live: f64 = crate::script_calls::with_hosted_vm(app.world_mut(), |s| { + s.expect("a VM").eval(chunk).expect("runs") + }); + assert!((29.0..=30.0).contains(&live), "{live}"); + let copy: f64 = crate::script_calls::eval_in_vm(app.world(), chunk); + assert_eq!(copy, 0.0); +} + +/// An offer with its caster's name on the wire signals at its packet's place, between a fall's +/// `UNIT_COMBAT` on each side, its listener reading the offer's timer. +#[test] +fn resurrect_request_fires_between_neighbouring_packets_events() { + let mut app = dead_client(); + let seen = frame(&mut app, vec![fall(5), offer("Bob"), fall(5)]); + assert_eq!(seen, [FELL, "RESURRECT_REQUEST:Bob:1", FELL]); +} + +/// A player caster's offer waits on the name its packet asked (`0x5e7c82`): nothing at the offer, +/// then the show inside the name answer's packet. +#[test] +fn a_player_casters_offer_shows_at_its_name_answer() { + let mut app = dead_client(); + assert!(frame(&mut app, vec![offer("")]).is_empty()); + let named = SessionEvent::PlayerName { + guid: PRIEST, + name: "Ann".into(), + race: 1, + gender: 0, + class: 5, + }; + let seen = frame(&mut app, vec![fall(5), named, fall(5)]); + assert_eq!(seen, [FELL, "RESURRECT_REQUEST:Ann:1", FELL]); +} + +/// The revive's health rising above 0 runs the watcher's arm inside its packet: `PLAYER_ALIVE`, +/// then the bridge's `UNIT_HEALTH`, between the falls around it. +#[test] +fn player_alive_fires_at_the_revives_packet() { + let mut app = dead_client(); + let seen = frame(&mut app, vec![fall(5), values(ME, &health(1)), fall(5)]); + assert_eq!( + seen, + [ + FELL, + "PLAYER_ALIVE", + "UNIT_HEALTH:player:1", + "UNIT_COMBAT:player:1" + ] + ); +} + +/// A reclaim delay while the range latch is set signals the in-range event again at its packet, +/// its listener reading the new delay (`0x4962da`, `0x49630d`). +#[test] +fn a_reclaim_delay_in_range_signals_at_its_packet() { + let mut app = dead_client(); + app.world_mut() + .resource_mut::() + .latch_corpse_in_range_for_test(); + let delay = SessionEvent::CorpseReclaimDelay { delay_ms: 30_000 }; + let seen = frame(&mut app, vec![fall(5), delay, fall(5)]); + assert_eq!(seen.len(), 3, "{seen:?}"); + assert_eq!((seen[0].as_str(), seen[2].as_str()), (FELL, FELL)); + let read: f64 = seen[1] + .strip_prefix("CORPSE_IN_RANGE:") + .and_then(|d| d.parse().ok()) + .unwrap_or_else(|| panic!("{seen:?}")); + assert!((29.0..=30.0).contains(&read), "{read}"); +} + +/// A spirit healer's confirm signals `CONFIRM_XP_LOSS` at its packet's place for a ghost with the +/// healer in reach (`0x5df74a`, `0x5df7c1`, `0x5df837`), and nothing for the living. +#[test] +fn confirm_xp_loss_fires_at_its_packet_for_a_ghost_in_reach() { + use benilla_protocol::field::{FIELD_PLAYER_FLAGS, FIELD_UNIT_HEALTH, FIELD_UNIT_MAXHEALTH}; + const HEALER: u64 = 0xF130_0000_1772_0050; + let confirm = || SessionEvent::SpiritHealerConfirm { npc: HEALER }; + let mut app = death_client(); + let healer = created( + HEALER, + benilla_protocol::EntityKind::Unit, + &[(FIELD_UNIT_HEALTH, 100), (FIELD_UNIT_MAXHEALTH, 100)], + ); + frame(&mut app, vec![healer]); + let alive = "UNIT_COMBAT:player:100"; + assert_eq!( + frame(&mut app, vec![fall(5), confirm(), fall(5)]), + [alive, alive], + "alive: no question" + ); + frame( + &mut app, + vec![values( + ME, + &[(FIELD_UNIT_HEALTH, 1), (FIELD_PLAYER_FLAGS, 0x10)], + )], + ); + let ghost = "UNIT_COMBAT:player:1"; + assert_eq!( + frame(&mut app, vec![fall(5), confirm(), fall(5)]), + [ghost, "CONFIRM_XP_LOSS", ghost] + ); +} + +/// The ghost bit's edges run the corpse query inside their packet, behind the ghost state +/// (`0x5eeab4` → `0x5eeac1` → `0x491f50`): the set asks for the corpse; the clear resets the +/// cache and lowers the range latch, whose `CORPSE_OUT_OF_RANGE` signals behind `PLAYER_UNGHOST` +/// between the packets around it, and sends nothing (`0x491fa1`-`0x491fb0`), nor does the frame's +/// poll after it. +#[test] +fn the_ghost_bits_edges_ask_and_reset_the_corpse_at_their_packet() { + use crate::net::ClientCommand; + use benilla_protocol::field::{FIELD_PLAYER_FLAGS, FIELD_UNIT_HEALTH}; + let mut app = dead_client(); + let (tx, sent) = crossbeam_channel::unbounded(); + app.insert_resource(crate::net::NetCommands(tx)); + app.world_mut() + .resource_mut::() + .connected = true; + app.world_mut() + .non_send_resource_mut::() + .run( + r#" + local f = CreateFrame("Frame") + f:RegisterEvent("PLAYER_UNGHOST") + f:RegisterEvent("CORPSE_OUT_OF_RANGE") + f:SetScript("OnEvent", function() table.insert(Seen, event) end) + "#, + ) + .unwrap(); + let queries = || { + sent.try_iter() + .filter(|c| matches!(c, ClientCommand::CorpseQuery)) + .count() + }; + let poll = |app: &mut App| { + app.world_mut() + .run_system_cached(crate::death::poll_corpse) + .expect("the poll runs") + }; + + frame( + &mut app, + vec![values( + ME, + &[(FIELD_UNIT_HEALTH, 1), (FIELD_PLAYER_FLAGS, 0x10)], + )], + ); + assert_eq!(queries(), 1, "the release asks inside its packet"); + poll(&mut app); + assert_eq!(queries(), 0, "and the poll asks nothing more"); + + crate::net::handlers::dispatch( + app.world_mut(), + vec![SessionEvent::CorpseQuery { + found: true, + display_map: 0, + position: [1.0, 2.0, 3.0], + corpse_map: 0, + }], + ); + assert!( + app.world() + .resource::() + .corpse + .is_some(), + "control: a ghost's answer is stored" + ); + app.world_mut() + .resource_mut::() + .latch_corpse_in_range_for_test(); + + let ghost = "UNIT_COMBAT:player:1"; + assert_eq!( + frame( + &mut app, + vec![fall(5), values(ME, &[(FIELD_PLAYER_FLAGS, 0)]), fall(5)] + ), + [ghost, "PLAYER_UNGHOST", "CORPSE_OUT_OF_RANGE", ghost] + ); + assert!( + app.world() + .resource::() + .corpse + .is_none(), + "the cache reset at the packet" + ); + assert_eq!(queries(), 0, "the revive sends nothing"); + poll(&mut app); + assert_eq!(queries(), 0, "nor does the poll"); +} diff --git a/crates/benilla-app/src/lanes/dialog_live_tests.rs b/crates/benilla-app/src/lanes/dialog_live_tests.rs index 1b17b4adb..bac070188 100644 --- a/crates/benilla-app/src/lanes/dialog_live_tests.rs +++ b/crates/benilla-app/src/lanes/dialog_live_tests.rs @@ -15,7 +15,6 @@ use crossbeam_channel::{Receiver, Sender}; use super::unit_view_tests::{created, wire_packets}; use crate::net::ClientCommand; -use crate::ui_dialog_verbs::DialogSignal; const ME: u64 = 0x7; /// An innkeeper, a pet trainer and a talent trainer in one, standing on us. @@ -226,9 +225,9 @@ fn the_dialog_getters_read_the_world_through_the_host() { ); } -/// Each dialog's event goes on its lane at its handler, stamped there: a frame's packets fire in -/// their order across the lanes, the talent trainer's notice between them, and a boot's line -/// ahead of its stop (`0x5e4914`). +/// Each dialog's event fires inside its packet's dispatch, with no frame after it: a frame's +/// packets fire in their order across the lanes, the talent trainer's notice between them, and a +/// boot's line ahead of its stop (`0x5e4914`). #[test] fn the_dialog_events_fire_at_their_packets() { let mut c = client(); @@ -244,31 +243,20 @@ fn the_dialog_events_fire_at_their_packets() { }, SessionEvent::BinderConfirm { binder: NPC }, ]); - let dialogs = c + assert!(c .app .world_mut() .resource_mut::() - .take_stamped(); - let notices: Vec<_> = c - .app - .world_mut() - .resource_mut::() - .drain_stamped() - .collect(); - assert_eq!(dialogs.len(), 2); + .take_stamped() + .is_empty()); assert_eq!( - dialogs[0].1, - DialogSignal::Event("CONFIRM_SUMMON".into(), vec![]) - ); - assert_eq!( - dialogs[1].1, - DialogSignal::ConfirmBinder { leaf: None }, - "named by the area under the player" - ); - assert_eq!(notices.len(), 1); - assert!( - dialogs[0].0 < notices[0].0 && notices[0].0 < dialogs[1].0, - "each stamped at its handler" + c.seen(), + [ + "CONFIRM_SUMMON:nil", + "CONFIRM_TALENT_WIPE:100", + "CONFIRM_BINDER:your inn", + ], + "each inside its packet's dispatch, the binder named by the area under the player" ); c.frame(vec![ @@ -348,6 +336,99 @@ fn the_unlearn_question_drops_past_the_range_gate() { ); } +/// Walking away from an innkeeper, a pet trainer or a talent trainer with its question open closes +/// nothing: no engine path clears the latches (`0xc4d7c0`, `0xc4d7b0`, `0xc4d7a0`, written only +/// at `0x5dfe64`, `0x5dfc41`, `0x5dfa21`), and each poll tests the latched NPC's range at the +/// call (`0x5dff50`, `0x5dfd30`, `0x5dfb10`), so the stock `OnUpdate` hides the dialog +/// (`StaticPopup.lua:1297`, `1313`, `1329`). Out of range the Accept sends nothing; back in range +/// the poll holds again and the Accept answers the latched NPC (`0x5dfdc0`, `0x5dfba0`, `0x5df980` +/// with a zero guid). +#[test] +fn walking_away_keeps_the_service_latches_and_the_polls_test_the_range() { + use crate::net::ClientCommand as C; + let mut c = client(); + c.frame(vec![ + vec![SessionEvent::BinderConfirm { binder: NPC }], + vec![SessionEvent::PetUnlearnConfirm { + trainer: NPC, + cost: 0, + }], + vec![SessionEvent::TalentWipeConfirm { + trainer: NPC, + cost: 0, + }], + ]); + assert_eq!( + c.seen(), + [ + "CONFIRM_BINDER:your inn", + "CONFIRM_PET_UNLEARN:0", + "CONFIRM_TALENT_WIPE:0" + ] + ); + const POLLS: &str = + "return CheckBinderDist(), CheckPetUntrainerDist(), CheckTalentMasterDist()"; + type Polls = (Option, Option, Option); + assert_eq!(c.eval::(true, POLLS), (Some(1), Some(1), Some(1))); + let latched = |c: &Client| { + let w = c.app.world(); + ( + w.resource::().pending(), + w.resource::() + .pending(), + w.resource::() + .pending(), + ) + }; + let place = |c: &mut Client, x: f32| { + let npc = c.app.world().resource::().0[&NPC]; + c.app + .world_mut() + .get_mut::(npc) + .unwrap() + .translation + .x = x; + }; + let accept = |c: &mut Client| -> Vec { + let _: () = c.eval( + true, + "ConfirmBinder() ConfirmPetUnlearn() ConfirmTalentWipe()", + ); + c._sent + .try_iter() + .filter(|s| { + matches!( + s, + C::BinderActivate { .. } | C::PetUnlearn { .. } | C::TalentWipeConfirm { .. } + ) + }) + .map(|s| format!("{s:?}")) + .collect() + }; + + place(&mut c, 6.0); + c.frame(vec![]); + assert_eq!( + latched(&c), + (Some(NPC), Some(NPC), Some(NPC)), + "nothing closes" + ); + assert_eq!(c.eval::(true, POLLS), (None, None, None)); + assert!(accept(&mut c).is_empty(), "out of range, no Accept sends"); + + place(&mut c, 5.0); + c.frame(vec![]); + assert_eq!(c.eval::(true, POLLS), (Some(1), Some(1), Some(1))); + assert_eq!( + accept(&mut c), + [ + format!("{:?}", C::BinderActivate { binder: NPC }), + format!("{:?}", C::PetUnlearn { trainer: NPC }), + format!("{:?}", C::TalentWipeConfirm { trainer: NPC }), + ] + ); +} + /// A world-enter cascade and a `0x295` in one frame: the reset is the create's, ahead of the /// frame's later packets, so the rebuild stands (`0x4908c0` inside `0x5dea50`, then `0x4ca385`). #[test] diff --git a/crates/benilla-app/src/lanes/follow_live_tests.rs b/crates/benilla-app/src/lanes/follow_live_tests.rs new file mode 100644 index 000000000..d9177f73d --- /dev/null +++ b/crates/benilla-app/src/lanes/follow_live_tests.rs @@ -0,0 +1,550 @@ +//! The follow's ends at their packets. Each handler that ends an auto-move calls the canceller +//! `StopAutoMove` (`0x60fb60`), which signals `AUTOFOLLOW_END` for a follow first (`0x60fb84`), +//! inside the handler: the taxi flag's watcher (`0x5ff55a`), our own death (`0x605938`), our own +//! swing's report (`0x625a21`), the mover switch of a control update (`0x600742`), the mover's +//! release (`0x5fbc3b` → `0x6006c2`) and a near teleport (`0x60300e` → `0x60e9b5`). The follow's +//! arm reads the follow as the packets left it (`0x611130` → `0x60fb60`). + +use benilla_protocol::field::{FIELD_UNIT_FLAGS, FIELD_UNIT_HEALTH, FIELD_UNIT_MAXHEALTH}; +use benilla_protocol::messages::AttackerState; +use benilla_protocol::{EntityKind, SessionEvent}; +use benilla_ui::script::UiScript; +use bevy::prelude::*; + +use super::unit_view_tests::{client, created, fall, frame, health, values}; + +/// [`client`]'s active player and its target. +const ME: u64 = 0x7; +const WOLF: u64 = 0xF130_0000_0044_0001; +const BOAR: u64 = 0xF130_0000_0045_0002; +/// Another player, followed. +const LEADER: u64 = 0x52; + +/// [`client`] following [`LEADER`], with a spy on the follow's two events. +fn following() -> App { + let mut app = client(); + app.world_mut() + .non_send_resource_mut::() + .run( + r#" + local f = CreateFrame("Frame") + f:RegisterEvent("AUTOFOLLOW_BEGIN") + f:RegisterEvent("AUTOFOLLOW_END") + f:RegisterEvent("PLAYER_REGEN_DISABLED") + f:RegisterEvent("UNIT_AURA") + f:RegisterEvent("PLAYER_TARGET_CHANGED") + f:RegisterEvent("PLAYER_FARSIGHT_FOCUS_CHANGED") + f:RegisterEvent("PLAYER_DEAD") + f:SetScript("OnEvent", function() table.insert(Seen, event) end) + "#, + ) + .unwrap(); + let world = app.world_mut(); + assert!( + world.resource::().holds(ME), + "our create claims our own mover" + ); + world + .resource_mut::() + .start(LEADER, "Leader".into()); + app +} + +/// `seen` holds one `AUTOFOLLOW_END`, after the first fall's `UNIT_COMBAT` and before the second's. +fn ends_between_the_falls(seen: &[String]) { + let falls: Vec = (0..seen.len()) + .filter(|&i| seen[i].starts_with("UNIT_COMBAT:player:")) + .collect(); + let ends: Vec = (0..seen.len()) + .filter(|&i| seen[i] == "AUTOFOLLOW_END") + .collect(); + assert_eq!((falls.len(), ends.len()), (2, 1), "{seen:?}"); + assert!(falls[0] < ends[0] && ends[0] < falls[1], "{seen:?}"); +} + +/// Our swing at the wolf, as the server reports it. +fn our_swing() -> SessionEvent { + SessionEvent::AttackerState(AttackerState { + attacker: ME, + victim: WOLF, + hit_info: 2, + damage: 5, + victim_state: 1, + absorb: 0, + resist: 0, + blocked: 0, + melee_spell_id: 0, + school: 0, + }) +} + +/// The taxi flag rising on us ends the follow inside its update's notify pass (`0x5ff538`- +/// `0x5ff55a`). +#[test] +fn the_taxi_flag_ends_the_follow_at_its_packet() { + let mut app = following(); + let taxi = values( + ME, + &[(FIELD_UNIT_FLAGS, crate::player::UNIT_FLAG_TAXI_FLIGHT)], + ); + ends_between_the_falls(&frame(&mut app, vec![fall(5), taxi, fall(5)])); + assert_eq!( + app.world().resource::().guid, + None + ); +} + +/// The flags watcher's active-player arm runs first (`0x5ff5b4` → `0x5ff4e0`), the taxi stop last +/// in it, after the combat bit's `PLAYER_REGEN_DISABLED` (`0x5ff533`) and ahead of the watcher's +/// `UNIT_AURA` on bit 0x8000000 (`0x5ff7e2`): one flags write, three signals in that order. +#[test] +fn the_taxi_stop_signals_in_the_flags_watchers_order() { + let mut app = following(); + let flags = crate::player::UNIT_FLAG_TAXI_FLIGHT | 0x8_0000 | 0x0800_0000; + let seen = frame(&mut app, vec![values(ME, &[(FIELD_UNIT_FLAGS, flags)])]); + let ours: Vec<&str> = seen + .iter() + .map(String::as_str) + .filter(|e| !e.starts_with("UNIT_COMBAT") && !e.starts_with("UNIT_HEALTH")) + .collect(); + assert_eq!( + ours, + ["PLAYER_REGEN_DISABLED", "AUTOFOLLOW_END", "UNIT_AURA"], + "{seen:?}" + ); +} + +/// A near teleport of our mover ends the follow inside its packet (`0x602fb0` → `0x60e990(1, 0)` +/// at `0x60300e`), ahead of the move it queues. +#[test] +fn a_near_teleport_ends_the_follow_at_its_packet() { + let mut app = following(); + let teleport = SessionEvent::Teleport { + guid: ME, + counter: 1, + position: [1.0, 2.0, 3.0], + orientation: 0.0, + }; + ends_between_the_falls(&frame(&mut app, vec![fall(5), teleport, fall(5)])); +} + +/// The active mover's release ends its auto-move (`0x5fbc26`-`0x5fbc3b` → `0x6006b0` → +/// `0x6006c2`): a possessed boar destroyed under us. +#[test] +fn the_movers_release_ends_the_follow_at_its_packet() { + let mut app = following(); + let world = app.world_mut(); + let (tx, _rx) = crossbeam_channel::unbounded(); + let net = crate::net::NetCommands(tx); + world + .resource_mut::() + .claim(BOAR, &net); + let gone = SessionEvent::ObjectDestroyed(BOAR); + ends_between_the_falls(&frame(&mut app, vec![fall(5), gone, fall(5)])); + assert!(!app.world().resource::().holds(BOAR)); +} + +/// Our death ends the follow inside the health's packet, through the health watcher's input +/// tick (`0x60479c` → `0x5146d6`) ahead of `OnDied` (`0x6047a3`): `AUTOFOLLOW_END`, then our +/// death's target clear (`0x5e9a45`) signals `PLAYER_TARGET_CHANGED`, then `PLAYER_DEAD`. +#[test] +fn our_death_ends_the_follow_at_its_packet() { + let mut app = following(); + app.world_mut() + .resource_mut::() + .connected = true; + let died = values(ME, &health(0)); + let seen = frame(&mut app, vec![fall(5), died, fall(5)]); + ends_between_the_falls(&seen); + let ours: Vec<&str> = seen + .iter() + .map(String::as_str) + .filter(|e| ["AUTOFOLLOW_END", "PLAYER_TARGET_CHANGED", "PLAYER_DEAD"].contains(e)) + .collect(); + assert_eq!( + ours, + ["AUTOFOLLOW_END", "PLAYER_TARGET_CHANGED", "PLAYER_DEAD"], + "{seen:?}" + ); +} + +/// Our own swing's report ends the follow (`0x625a03`-`0x625a21`), inside its handler. +#[test] +fn our_swing_ends_the_follow_at_its_packet() { + let mut app = following(); + ends_between_the_falls(&frame(&mut app, vec![fall(5), our_swing(), fall(5)])); +} + +/// A control update that stops our mover zeroes the active mover (`0x5fa678`-`0x5fa696`), whose +/// switch ends the follow (`0x600731`-`0x600742`), inside its handler. +#[test] +fn losing_control_ends_the_follow_at_its_packet() { + let mut app = following(); + let lost = SessionEvent::ClientControl { + mover: ME, + allow_move: false, + }; + ends_between_the_falls(&frame(&mut app, vec![fall(5), lost, fall(5)])); +} + +/// A `FollowUnit` a listener calls between two packets reads the follow the first one ended: its +/// arm finds none to stop, so it signals `AUTOFOLLOW_BEGIN` alone (`0x611130` → `0x60fb70`). +#[test] +fn the_follows_arm_reads_the_follow_an_earlier_packet_ended() { + use crate::target::relations::fixture::{factions, player, store_of, HUMAN}; + let mut app = following(); + let human = |guid| -> Vec<(u16, u32)> { + store_of(&player(guid, HUMAN)) + .0 + .raw_fields() + .filter(|&(i, _)| i != 2) + .collect() + }; + let mut leader = human(LEADER); + leader.extend([(FIELD_UNIT_HEALTH, 100), (FIELD_UNIT_MAXHEALTH, 100)]); + let world = app.world_mut(); + world.insert_resource(factions()); + world + .resource_mut::() + .insert_player(LEADER, "Leader".into(), None); + frame( + &mut app, + vec![ + created(LEADER, EntityKind::Player, &leader), + values(ME, &human(ME)), + ], + ); + let world = app.world_mut(); + let index = world.resource::(); + let (me, them) = (index.0[&ME], index.0[&LEADER]); + world.entity_mut(me).insert(crate::net::ActiveMover); + *world.resource_mut::() = crate::target::Selection { + target: Some(them), + guid: Some(LEADER), + ..Default::default() + }; + world + .non_send_resource_mut::() + .run( + r#" + local f = CreateFrame("Frame") + f:RegisterEvent("UNIT_COMBAT") + f:SetScript("OnEvent", function() + if Arm then Arm = nil FollowUnit("target") end + end) + Arm = true + "#, + ) + .unwrap(); + let seen = frame(&mut app, vec![our_swing(), fall(5)]); + let follow: Vec<&str> = seen + .iter() + .map(String::as_str) + .filter(|e| e.starts_with("AUTOFOLLOW") || e.starts_with("UNIT_COMBAT:player:")) + .collect(); + assert_eq!( + follow, + [ + "AUTOFOLLOW_END", + "UNIT_COMBAT:player:100", + "AUTOFOLLOW_BEGIN" + ], + "{seen:?}" + ); + assert_eq!( + app.world().resource::().guid, + Some(LEADER) + ); +} + +/// [`following`] with autorun held and the frame's call store, the stop's forward release +/// (`0x60fc05` → `0x60e7f0`) to watch. +fn autorunning() -> App { + let mut app = following(); + let world = app.world_mut(); + world.init_resource::(); + world.init_resource::(); + let mut player = world.resource_mut::(); + player.active = true; + player.autorun_for_test(Some(true)); + app +} + +/// A stop that ends a follow owes its forward release: autorun clears inside the handler +/// (`0x514630` at `0x60e83f`), and the frame's steer applies it ahead of the controller's step, +/// which stops the move. A second stop finds no auto-move (`0x6103a0`) and owes nothing. +#[test] +fn the_stop_owes_its_autorun_release() { + let mut app = autorunning(); + frame(&mut app, vec![our_swing()]); + let world = app.world_mut(); + assert!(world + .resource::() + .owes_release()); + assert_eq!( + world.resource::().called(), + Some(false) + ); + crate::player::release_owed_for_test(world); + let mut player = world.resource_mut::(); + assert!(!player.autorun_for_test(None)); + player.autorun_for_test(Some(true)); + frame(&mut app, vec![our_swing()]); + let world = app.world_mut(); + assert!(!world + .resource::() + .owes_release()); + crate::player::release_owed_for_test(world); + assert!(world + .resource_mut::() + .autorun_for_test(None)); +} + +/// A `ToggleAutoRun` after the stop, before the frame's latch, reads the bit the stop cleared, so +/// it presses autorun on (`0x513de7`), as the stop's clear ran inside its handler (`0x514630`). +#[test] +fn a_toggle_after_the_stop_reads_autorun_clear() { + use bevy::ecs::system::RunSystemOnce; + let mut app = autorunning(); + app.world_mut() + .resource_mut::() + .open_for_test(); + let seen = frame(&mut app, vec![our_swing()]); + assert!(seen.iter().any(|e| e == "AUTOFOLLOW_END"), "{seen:?}"); + let world = app.world_mut(); + world + .run_system_once(|mut steps: crate::player::CommandSteps| { + steps.call(benilla_ui::script::BindingInput::Fire( + benilla_ui::script::FiredInput::ToggleAutoRun, + )) + }) + .unwrap(); + assert_eq!( + world.resource::().called(), + Some(true) + ); +} + +/// [`following`] with the boar's loot window open, its own events taken, and a spy on its close. +fn looting() -> App { + let mut app = following(); + let world = app.world_mut(); + world + .resource_mut::() + .open(BOAR, 1, 0, Vec::new()); + world.resource_mut::().0 = Some(BOAR); + world + .non_send_resource_mut::() + .run( + r#" + local f = CreateFrame("Frame") + f:RegisterEvent("LOOT_CLOSED") + f:SetScript("OnEvent", function() table.insert(Seen, event) end) + "#, + ) + .unwrap(); + frame(&mut app, vec![]); + app +} + +/// `seen`'s events between the two falls, in order. +fn past_the_falls(seen: &[String]) -> Vec<&str> { + let falls: Vec = (0..seen.len()) + .filter(|&i| seen[i].starts_with("UNIT_COMBAT:player:")) + .collect(); + seen[falls[0] + 1..falls[1]] + .iter() + .map(String::as_str) + .filter(|e| !e.starts_with("UNIT_HEALTH")) + .collect() +} + +/// A near teleport's movement guard (`0x60e990(1, 0)` at `0x60300e`) ends the follow, then closes +/// the active player's loot window as a movement start does (`0x60e9dd` → `0x48f200(1, 1, 0)`). +#[test] +fn a_near_teleport_closes_the_loot_window_after_the_follow() { + let mut app = looting(); + let teleport = SessionEvent::Teleport { + guid: ME, + counter: 1, + position: [1.0, 2.0, 3.0], + orientation: 0.0, + }; + let seen = frame(&mut app, vec![fall(5), teleport, fall(5)]); + ends_between_the_falls(&seen); + assert_eq!(past_the_falls(&seen), ["AUTOFOLLOW_END", "LOOT_CLOSED"]); +} + +/// A knockback runs the same guard ahead of its queue (`QueueKnockBack 0x602670`, `0x60267e`). +#[test] +fn a_knockback_ends_the_follow_and_closes_the_loot_window() { + let mut app = looting(); + let knock = SessionEvent::KnockBack { + guid: ME, + counter: 1, + launch: Default::default(), + }; + let seen = frame(&mut app, vec![fall(5), knock, fall(5)]); + ends_between_the_falls(&seen); + assert_eq!(past_the_falls(&seen), ["AUTOFOLLOW_END", "LOOT_CLOSED"]); +} + +/// The feign-death bit's rise on our mover runs its tick with `apply` clear (`0x6004f5`- +/// `0x600530`), whose teardown leg ends the follow, inside the update's notify pass. +#[test] +fn feign_death_ends_the_follow_at_its_packet() { + use benilla_protocol::field::FIELD_UNIT_DYNAMIC_FLAGS; + let mut app = following(); + let feign = values(ME, &[(FIELD_UNIT_DYNAMIC_FLAGS, 0x20)]); + ends_between_the_falls(&frame(&mut app, vec![fall(5), feign, fall(5)])); +} + +/// The stun bit's flip runs the active player's tick first in the flags watcher (`0x5ff501`): a +/// rooted mover that is now stunned may neither translate nor turn, so the follow ends there. +#[test] +fn a_stun_on_a_rooted_mover_ends_the_follow_at_its_packet() { + let mut app = following(); + let world = app.world_mut(); + world.init_resource::(); + world + .resource_mut::() + .root_for_test(); + let stun = values(ME, &[(FIELD_UNIT_FLAGS, crate::player::UNIT_FLAG_STUNNED)]); + ends_between_the_falls(&frame(&mut app, vec![fall(5), stun, fall(5)])); +} + +/// A server path on our mover. +fn monster_path() -> SessionEvent { + SessionEvent::MonsterMove { + guid: ME, + transport: None, + start: [0.0; 3], + spline_id: 1, + path: vec![[0.0; 3], [5.0, 0.0, 0.0]], + facing: benilla_protocol::messages::MonsterMoveFacing::None, + stop: false, + duration_ms: 1000, + flying: false, + run_mode: true, + } +} + +/// A server path on our mover runs its tick (`0x602053`), whose precondition the spline fails: +/// the follow ends inside the move's packet. +#[test] +fn a_monster_move_on_us_ends_the_follow_at_its_packet() { + let mut app = following(); + let path = monster_path(); + ends_between_the_falls(&frame(&mut app, vec![fall(5), path, fall(5)])); +} + +/// A rooted mover starts no server path (`0x6187c2`-`0x6187c7` returns 0 on the root bit), so +/// `0x601fee` skips the tick and the follow goes on. +#[test] +fn a_monster_move_on_a_rooted_mover_keeps_the_follow() { + let mut app = following(); + let world = app.world_mut(); + world.init_resource::(); + world + .resource_mut::() + .root_for_test(); + let seen = frame(&mut app, vec![monster_path()]); + assert!(!seen.iter().any(|e| e == "AUTOFOLLOW_END"), "{seen:?}"); + assert_eq!( + app.world().resource::().guid, + Some(LEADER) + ); +} + +/// Far sight on a held object stops the mover's auto-move inside the field watcher +/// (`0x5de0d0` → `0x5ee4a2`), ahead of its `PLAYER_FARSIGHT_FOCUS_CHANGED` (`0x5de167`). +#[test] +fn far_sight_ends_the_follow_ahead_of_its_focus_change() { + let mut app = following(); + let seen = frame(&mut app, vec![fall(5), far_sight(BOAR), fall(5)]); + assert_eq!( + past_the_falls(&seen), + ["AUTOFOLLOW_END", "PLAYER_FARSIGHT_FOCUS_CHANGED"], + "{seen:?}" + ); +} + +/// Our `PLAYER_FARSIGHT` set to `object`. +fn far_sight(object: u64) -> SessionEvent { + /// `PLAYER_FARSIGHT` (`+0x830` of the player section). + const FIELD_PLAYER_FARSIGHT: u16 = 712; + values( + ME, + &[ + (FIELD_PLAYER_FARSIGHT, object as u32), + (FIELD_PLAYER_FARSIGHT + 1, (object >> 32) as u32), + ], + ) +} + +/// Far sight on a unit we control takes the active mover (`0x5ee45d` → `0x5ee477`): the switch +/// stops the outgoing mover's auto-move (`0x600742`), and when the unit already is the mover it +/// switches nothing (`0x6006fb`) and runs no tick, so the follow goes on. `IsClientControlled` +/// (`0x5fa5f0`) is the unit's own bit, which the control update writes (`0x5fa636`) whoever holds +/// the mover. +#[test] +fn far_sight_on_a_unit_we_control_stops_only_the_mover_it_switches_from() { + let ends = |mover: u64, granted: Option, object: u64| { + let mut app = following(); + let (tx, _rx) = crossbeam_channel::unbounded(); + let net = crate::net::NetCommands(tx); + if let Some(unit) = granted { + let grant = SessionEvent::ClientControl { + mover: unit, + allow_move: true, + }; + frame(&mut app, vec![grant]); + } + let world = app.world_mut(); + world + .resource_mut::() + .claim(mover, &net); + // The grant's own switch may have ended it. + world + .resource_mut::() + .start(LEADER, "Leader".into()); + let seen = frame(&mut app, vec![far_sight(object)]); + seen.iter().filter(|e| *e == "AUTOFOLLOW_END").count() + }; + assert_eq!( + ends(BOAR, Some(BOAR), BOAR), + 0, + "the possessed boar already is the mover" + ); + assert_eq!(ends(ME, None, ME), 0, "our own body already is the mover"); + assert_eq!( + ends(BOAR, None, ME), + 1, + "our own body takes the mover from the boar" + ); + assert_eq!( + ends(WOLF, Some(BOAR), BOAR), + 1, + "a controlled boar takes it from the wolf" + ); + assert_eq!( + ends(ME, None, WOLF), + 1, + "an uncontrolled unit runs the tick" + ); +} + +/// The stun's tick reads the far-sight latch as the packets left it (`[mover+0x1c70] & 1`, +/// `0x514540`): far sight on our own body sets it at its packet and stops nothing (`0x6006fb`), so +/// a stun later in the same frame finds the view out and its tick tears the follow down, unrooted. +#[test] +fn a_stun_after_far_sight_in_one_frame_reads_the_latch_its_packet_set() { + let mut app = following(); + let stun = values(ME, &[(FIELD_UNIT_FLAGS, crate::player::UNIT_FLAG_STUNNED)]); + let seen = frame(&mut app, vec![far_sight(ME), stun]); + assert_eq!( + seen.iter().filter(|e| *e == "AUTOFOLLOW_END").count(), + 1, + "{seen:?}" + ); +} diff --git a/crates/benilla-app/src/lanes/gossip_live_tests.rs b/crates/benilla-app/src/lanes/gossip_live_tests.rs index 507c85807..fabd929ad 100644 --- a/crates/benilla-app/src/lanes/gossip_live_tests.rs +++ b/crates/benilla-app/src/lanes/gossip_live_tests.rs @@ -191,10 +191,10 @@ fn the_gossip_getters_read_the_world_at_the_call() { ); } -/// The draw's `GOSSIP_SHOW` sits on the gossip lane at the text's handler, between the stamps of -/// the handlers before and after it. +/// The draw's `GOSSIP_SHOW` fires inside the text's dispatch, with no frame after it: the +/// handler's signal runs every listener before the next packet's handler (`0x537ae5`, `0x703e50`). #[test] -fn the_show_is_stamped_at_its_handler() { +fn the_show_fires_inside_its_dispatch() { let mut c = client(); c.handle(vec![menu(7, "Browse")]); assert!(c @@ -203,18 +203,18 @@ fn the_show_is_stamped_at_its_handler() { .resource::() .stamped() .is_empty()); - let before = crate::lanes::stamp(); + c.seen(); c.handle(vec![greeting(7, "Hello")]); - let after = crate::lanes::stamp(); - let stamped = c + assert!(c .app .world() .resource::() - .stamped(); - assert_eq!(stamped.len(), 1); - let (at, event) = stamped[0]; - assert_eq!(event, crate::ui_gossip::GossipEvent::Show); - assert!(before < at && at < after, "stamped inside the handler"); + .stamped() + .is_empty()); + assert!( + c.seen().iter().any(|s| s == "GOSSIP_SHOW:nil"), + "the show fired inside the dispatch" + ); } /// A cached text shows at its message and a first visit at its text's arrival, each at its @@ -411,3 +411,28 @@ fn stock_gossip_frame_stays_visible_through_a_first_visit_submenu() { "an in-place repaint" ); } + +/// `SMSG_GOSSIP_COMPLETE` closes the menu inside its handler (`0x4e1fa0` with a zero guid), whose +/// release re-enters it (`0x4e1fc5` → `0x493310`): both `GOSSIP_CLOSED`s fire at the packet's +/// place, after an earlier packet's chat line and ahead of a later one's, though the gossip lane +/// holds nothing when the handler runs. +#[test] +fn a_server_close_fires_at_its_packet() { + let mut c = client(); + c.frame(vec![vec![greeting(7, "Hello")], vec![menu(7, "Browse")]]); + assert_eq!(c.seen(), ["GOSSIP_SHOW:nil"]); + c.frame(vec![ + vec![boar_says("a")], + vec![SessionEvent::GossipComplete], + vec![boar_says("b")], + ]); + assert_eq!( + c.seen(), + [ + "CHAT_MSG_MONSTER_SAY:a", + "GOSSIP_CLOSED:nil", + "GOSSIP_CLOSED:nil", + "CHAT_MSG_MONSTER_SAY:b", + ] + ); +} diff --git a/crates/benilla-app/src/lanes/group_live_tests.rs b/crates/benilla-app/src/lanes/group_live_tests.rs new file mode 100644 index 000000000..f0da81b8f --- /dev/null +++ b/crates/benilla-app/src/lanes/group_live_tests.rs @@ -0,0 +1,560 @@ +//! What a listener reads of the group and the pet, as its own packet left them. The group +//! handlers write the party slots and the raid rows themselves (`0x4e82d0`, `0x4e84a0`, the raid +//! writer `0x4ba5f0`) before they signal (`0x5e6c66`), a stats packet its member's record, and the +//! getters and the relation functions read those tables, the records and the objects at the call +//! (`0x5174d0`, `0x6062b0`-`0x60631c` through `0x4e7f70`), so no copy is pushed ahead of the drain. + +use benilla_protocol::field::{FIELD_UNIT_FLAGS, FIELD_UNIT_HEALTH, FIELD_UNIT_MAXHEALTH}; +use benilla_protocol::messages::{member_status, GroupMemberEntry, PartyMemberStatsInfo}; +use benilla_protocol::{EntityKind, SessionEvent}; +use benilla_ui::script::UiScript; +use bevy::prelude::*; + +use super::unit_view_tests::{client, created, fall, frame, values}; +use crate::target::relations::fixture::{factions, HUMAN, ORC, PC}; + +const ME: u64 = 0x7; +/// A player of the other faction, held. +const MATE: u64 = 0x22; +/// `UNIT_FIELD_FACTIONTEMPLATE`. +const TEMPLATE: u16 = 35; + +/// `SMSG_GROUP_LIST` for a party of us, leading, and [`MATE`]. +fn party_list() -> SessionEvent { + party_of(MATE) +} + +/// `SMSG_GROUP_LIST` for a party of us, leading, and `member`. +fn party_of(member: u64) -> SessionEvent { + SessionEvent::GroupList { + group_type: 0, + own_flags: 0, + members: vec![GroupMemberEntry { + name: String::new(), + guid: member, + status: member_status::ONLINE, + flags: 0, + }], + leader: ME, + loot: None, + } +} + +/// The relation a `PARTY_MEMBERS_CHANGED` listener reads off a list that seats an enemy-faction +/// player is the party's: the active player toward a party member is friendly (`0x6062b0`), which +/// the list's own party slots answer, not the slots of the frame before nor of a later list in +/// the same frame that seats another member, out of view, in the slot. +#[test] +fn a_group_list_listener_reads_the_roster_its_list_wrote() { + let mut app = client(); + app.insert_resource(factions()); + frame( + &mut app, + vec![ + values(ME, &[(TEMPLATE, HUMAN), (FIELD_UNIT_FLAGS, PC)]), + created( + MATE, + EntityKind::Player, + &[ + (TEMPLATE, ORC), + (FIELD_UNIT_FLAGS, PC), + (FIELD_UNIT_HEALTH, 100), + (FIELD_UNIT_MAXHEALTH, 100), + ], + ), + ], + ); + app.world_mut() + .non_send_resource_mut::() + .run( + r#" + local f = CreateFrame("Frame") + f:RegisterEvent("PARTY_MEMBERS_CHANGED") + f:SetScript("OnEvent", function() + table.insert(Seen, "reaction:" .. tostring(UnitReaction("player", "party1"))) + end) + "#, + ) + .unwrap(); + let seen = frame(&mut app, vec![party_list(), party_of(ALIA)]); + let seen: Vec<_> = seen.iter().filter(|s| s.starts_with("reaction:")).collect(); + let friendly = seen + .iter() + .take_while(|s| s.as_str() == "reaction:5") + .count(); + assert!( + friendly > 0, + "the first list's listeners, friendly: {seen:?}" + ); + assert!( + friendly < seen.len() + && seen[friendly..] + .iter() + .all(|s| s.as_str() == "reaction:nil"), + "then the second list's, whose member is out of view: {seen:?}" + ); +} + +/// Raid members out of view: the rows after [`MATE`]'s, two lists apart. +const ALIA: u64 = 0x31; +const BRAM: u64 = 0x32; +const CORA: u64 = 0x33; +const DUNN: u64 = 0x34; + +/// `SMSG_GROUP_LIST` for a raid of us, leading, [`MATE`] in our subgroup and `rest` in the next. +fn raid_list(rest: [u64; 2]) -> SessionEvent { + let entry = |guid: u64, subgroup: u8| GroupMemberEntry { + name: String::new(), + guid, + status: member_status::ONLINE, + flags: subgroup, + }; + SessionEvent::GroupList { + group_type: crate::ui_party::GROUPTYPE_RAID, + own_flags: 0, + members: vec![entry(MATE, 0), entry(rest[0], 1), entry(rest[1], 1)], + leader: ME, + loot: None, + } +} + +/// `SMSG_PARTY_MEMBER_STATS` for [`MATE`], its health alone. +fn mate_hp(cur: u16) -> SessionEvent { + SessionEvent::PartyMemberStats { + guid: MATE, + full: false, + info: Box::new(PartyMemberStatsInfo { + cur_hp: Some(cur), + ..Default::default() + }), + } +} + +/// A listener inside a member's stats packet reads `party1`'s health off the record that packet +/// wrote (`0x5e54c4` before `0x5e54fa`; `0x5174d0` reads the record for a member with no object, +/// `0x496400`) and `raid3` off the rows the list before it wrote (`0x4ba5f0`), the name by its +/// guid (`0x5171eb`): each token resolves at the call, with no copy pushed ahead of the drain. +#[test] +fn a_member_update_listener_reads_party1_and_raid3_as_its_packet_wrote_them() { + let mut app = client(); + { + let mut names = app.world_mut().resource_mut::(); + for (guid, name) in [ + (MATE, "Brisca"), + (ALIA, "Alia"), + (BRAM, "Bram"), + (CORA, "Cora"), + (DUNN, "Dunn"), + ] { + names.insert_player(guid, name.into(), None); + } + } + frame( + &mut app, + vec![ + raid_list([ALIA, BRAM]), + SessionEvent::PartyMemberStats { + guid: MATE, + full: true, + info: Box::new(PartyMemberStatsInfo { + status: Some(member_status::ONLINE), + cur_hp: Some(100), + max_hp: Some(100), + ..Default::default() + }), + }, + ], + ); + app.world_mut() + .non_send_resource_mut::() + .run( + r#" + local f = CreateFrame("Frame") + f:RegisterEvent("UNIT_HEALTH") + f:SetScript("OnEvent", function() + if arg1 == "party1" then + table.insert(Seen, UnitHealth("party1") .. ":" .. tostring(UnitName("raid3"))) + end + end) + "#, + ) + .unwrap(); + let seen = frame( + &mut app, + vec![mate_hp(40), raid_list([CORA, DUNN]), mate_hp(30)], + ); + let seen: Vec<_> = seen.iter().filter(|s| !s.starts_with("UNIT_")).collect(); + assert_eq!(seen, ["40:Bram", "30:Dunn"]); +} + +/// A member's `UNIT_HEALTH` names the tokens its own packet's roster gives it: `0x515e50` walks the +/// party slots and the raid rows at the signal (`0x515c50`, through `0x491920` and `0x491940`). +/// So [`MATE`], moved out of our subgroup by a list later in the frame, is `party1` and `raid1` at +/// the first stats packet; at the second, after a list that seats it third, `raid3` alone. +#[test] +fn a_member_health_event_names_the_tokens_its_packets_roster_gives() { + let mut app = client(); + let list = |rows: [(u64, u8); 3]| SessionEvent::GroupList { + group_type: crate::ui_party::GROUPTYPE_RAID, + own_flags: 0, + members: rows + .iter() + .map(|&(guid, subgroup)| GroupMemberEntry { + name: String::new(), + guid, + status: member_status::ONLINE, + flags: subgroup, + }) + .collect(), + leader: ME, + loot: None, + }; + frame( + &mut app, + vec![ + list([(MATE, 0), (ALIA, 1), (BRAM, 1)]), + SessionEvent::PartyMemberStats { + guid: MATE, + full: true, + info: Box::new(PartyMemberStatsInfo { + status: Some(member_status::ONLINE), + cur_hp: Some(100), + max_hp: Some(100), + ..Default::default() + }), + }, + ], + ); + let seen = frame( + &mut app, + vec![ + mate_hp(40), + list([(ALIA, 1), (BRAM, 1), (MATE, 1)]), + mate_hp(30), + ], + ); + assert_eq!( + seen, + [ + "UNIT_HEALTH:party1:40", + "UNIT_HEALTH:raid1:40", + "UNIT_HEALTH:raid3:30" + ] + ); +} + +/// Our pet, `UNIT_FIELD_SUMMON`'s, and the one that replaces it. +const PET: u64 = 0xF140_0000_0045_0002; +const PET2: u64 = 0xF140_0000_0045_0003; +/// `UNIT_FIELD_SUMMON`. +const SUMMON: u16 = 8; + +fn summons(guid: u64) -> [(u16, u32); 2] { + [(SUMMON, guid as u32), (SUMMON + 1, (guid >> 32) as u32)] +} + +/// A listener reads `"pet"` as its own packet left it: the token is our `UNIT_FIELD_SUMMON` at the +/// call (`0x515a5e`-`0x515a6e`) and the getter reads that object (`0x5174d0`). So a fall ahead of +/// the pet's update reads the pet before it, the update's own `UNIT_HEALTH` its health, and the +/// pet that replaces it later in the frame answers only after its summon. +#[test] +fn a_pet_update_listener_reads_pet_as_its_packet_left_it() { + let mut app = client(); + let pet = |guid: u64, hp: u32, max: u32| { + created( + guid, + EntityKind::Unit, + &[(FIELD_UNIT_HEALTH, hp), (FIELD_UNIT_MAXHEALTH, max)], + ) + }; + frame( + &mut app, + vec![values(ME, &summons(PET)), pet(PET, 100, 100)], + ); + app.world_mut() + .non_send_resource_mut::() + .run( + r#" + local f = CreateFrame("Frame") + f:RegisterEvent("UNIT_HEALTH") + f:RegisterEvent("UNIT_COMBAT") + f:SetScript("OnEvent", function() + if arg1 == "pet" or event == "UNIT_COMBAT" then + table.insert(Seen, "pet " .. event .. " " .. UnitHealth("pet") .. ":" + .. UnitHealthMax("pet")) + end + end) + "#, + ) + .unwrap(); + let seen = frame( + &mut app, + vec![ + fall(1), + values(PET, &[(FIELD_UNIT_HEALTH, 70)]), + values(ME, &summons(PET2)), + pet(PET2, 20, 40), + values(PET2, &[(FIELD_UNIT_HEALTH, 15)]), + ], + ); + let seen: Vec<_> = seen.iter().filter(|s| s.starts_with("pet ")).collect(); + assert_eq!( + seen, + [ + "pet UNIT_COMBAT 100:100", + "pet UNIT_HEALTH 70:100", + "pet UNIT_HEALTH 15:40" + ] + ); +} + +/// A getter's read of a member whose name the cache lacks asks the server inside the call, once +/// while the ask is pending: `UnitName` of a member with no object reads the cache by guid with a +/// callback (`0x5171eb`, `0x517290`), and the tooltip's name of a held one is `GetUnitName`'s +/// (`0x609210`, its player cache asked at `0x60925e`). The list asked each name it seated +/// (`0x4e8477`); a server's `SMSG_INVALIDATE_PLAYER` drops it again (`0x555600`). +#[test] +fn a_members_uncached_name_is_asked_once_by_the_getter() { + let mut app = client(); + let (tx, rx) = crossbeam_channel::unbounded(); + app.insert_resource(crate::net::NetCommands(tx)); + let asked = |rx: &crossbeam_channel::Receiver| { + rx.try_iter() + .filter(|c| matches!(c, crate::net::ClientCommand::NameQuery { guid } if *guid == MATE)) + .count() + }; + let forget = |app: &mut App| { + app.world_mut() + .resource_mut::() + .invalidate_player(MATE); + }; + frame(&mut app, vec![party_list()]); + assert_eq!(asked(&rx), 1, "the list's lookup"); + forget(&mut app); + let run = |app: &mut App, chunk: &str| { + crate::script_calls::with_hosted_vm(app.world_mut(), |s| { + s.expect("a VM").run(chunk).unwrap() + }) + }; + run(&mut app, r#"UnitName("party1") UnitName("party1")"#); + assert_eq!(asked(&rx), 1, "the member with no object, once"); + + frame( + &mut app, + vec![created( + MATE, + EntityKind::Player, + &[(FIELD_UNIT_HEALTH, 100), (FIELD_UNIT_MAXHEALTH, 100)], + )], + ); + let _ = asked(&rx); + forget(&mut app); + crate::ui_script::test_ui::load_tooltip_template(app.world().non_send_resource::()); + run( + &mut app, + r#" + Tip = CreateFrame("GameTooltip", "Tip", nil, "TestTooltipTemplate") + Tip:SetOwner(CreateFrame("Frame"), "ANCHOR_NONE") + Tip:SetUnit("party1") + Tip:SetUnit("party1") + "#, + ); + assert_eq!(asked(&rx), 1, "the held member's tooltip, once"); +} + +/// The unit tooltip finds the group record by guid for whatever token shows the unit (`0x52a02b`, +/// through `0x496400`): a raid member off our party slots reads its raid row's record, so an +/// offline one ends on `PLAYER_OFFLINE` (`0x52a6e2`-`0x52a72b`); off the roster the record a +/// member left behind is found by no row, and the tooltip reads none. +#[test] +fn the_tooltip_reads_a_raid_rows_record_and_none_off_the_roster() { + let mut app = client(); + let raid = |rows: &[(u64, u8)]| SessionEvent::GroupList { + group_type: crate::ui_party::GROUPTYPE_RAID, + own_flags: 0, + members: rows + .iter() + .map(|&(guid, subgroup)| GroupMemberEntry { + name: String::new(), + guid, + status: member_status::OFFLINE, + flags: subgroup, + }) + .collect(), + leader: ME, + loot: None, + }; + frame( + &mut app, + vec![ + raid(&[(MATE, 1), (ALIA, 1)]), + created( + MATE, + EntityKind::Player, + &[ + (FIELD_UNIT_HEALTH, 100), + (FIELD_UNIT_MAXHEALTH, 100), + (FIELD_UNIT_FLAGS, PC), + ], + ), + SessionEvent::PartyMemberStats { + guid: MATE, + full: true, + info: Box::new(PartyMemberStatsInfo { + status: Some(member_status::OFFLINE), + ..Default::default() + }), + }, + ], + ); + let world = app.world_mut(); + crate::ui_script::test_ui::load_tooltip_template(world.non_send_resource::()); + let lines = |app: &mut App| -> Vec { + crate::script_calls::with_hosted_vm(app.world_mut(), |s| { + s.expect("a VM") + .eval( + r#" + PLAYER_OFFLINE = "[OFFLINE]" + Tip = Tip or CreateFrame("GameTooltip", "Tip", nil, "TestTooltipTemplate") + Tip:SetOwner(CreateFrame("Frame"), "ANCHOR_NONE") + Tip:SetUnit("raid1") + local out = {} + for i = 2, 30 do + local line = getglobal("TipTextLeft" .. i) + if not line or not line:GetText() then break end + table.insert(out, line:GetText()) + end + return out + "#, + ) + .unwrap() + }) + }; + assert!( + lines(&mut app).iter().any(|l| l == "[OFFLINE]"), + "the raid row's record" + ); + // MATE leaves, and a late stats packet stores a record no row names: the held unit is shown + // as itself. + frame( + &mut app, + vec![ + raid(&[(ALIA, 1), (BRAM, 1)]), + SessionEvent::PartyMemberStats { + guid: MATE, + full: true, + info: Box::new(PartyMemberStatsInfo { + status: Some(member_status::OFFLINE), + ..Default::default() + }), + }, + ], + ); + *app.world_mut().resource_mut::() = crate::target::Selection { + target: app + .world() + .resource::() + .0 + .get(&MATE) + .copied(), + guid: Some(MATE), + ..Default::default() + }; + let off = crate::script_calls::with_hosted_vm(app.world_mut(), |s| { + s.expect("a VM") + .eval::>( + r#" + Tip:SetOwner(CreateFrame("Frame"), "ANCHOR_NONE") + Tip:SetUnit("target") + local out = {} + for i = 2, 30 do + local line = getglobal("TipTextLeft" .. i) + if not line or not line:GetText() then break end + table.insert(out, line:GetText()) + end + return out + "#, + ) + .unwrap() + }); + assert!( + app.world() + .resource::() + .stats + .contains_key(&MATE), + "the late record is stored" + ); + assert!( + !off.iter().any(|l| l == "[OFFLINE]"), + "off the roster: {off:?}" + ); +} + +/// [`MATE`]'s name answer. +fn mate_named() -> SessionEvent { + SessionEvent::PlayerName { + guid: MATE, + name: "Bob".into(), + race: 1, + class: 1, + gender: 0, + } +} + +/// The party with [`MATE`] in it, held as `held` says, its name not cached, a `UNIT_NAME_UPDATE` +/// listener noting the token and the name it reads, and `UnitName("party1")` run twice: the +/// events [`mate_named`] then signals. +fn name_update_after_unit_name(held: bool) -> Vec { + let mut app = client(); + frame(&mut app, vec![party_list()]); + if held { + frame( + &mut app, + vec![created( + MATE, + EntityKind::Player, + &[(FIELD_UNIT_HEALTH, 100), (FIELD_UNIT_MAXHEALTH, 100)], + )], + ); + } + app.world_mut() + .resource_mut::() + .invalidate_player(MATE); + crate::script_calls::with_hosted_vm(app.world_mut(), |s| { + s.expect("a VM").run( + r#" + local f = CreateFrame("Frame") + f:RegisterEvent("UNIT_NAME_UPDATE") + f:SetScript("OnEvent", function() + table.insert(Seen, event .. " " .. arg1 .. " " .. tostring(UnitName(arg1))) + end) + UnitName("party1") UnitName("party1") + Seen = {} + "#, + ) + }) + .expect("the listener and the reads"); + frame(&mut app, vec![mate_named()]) +} + +/// `UnitName` of a member it holds no unit for keeps its callback on the miss, once (`0x5171f1`, +/// `0x5171f5` with `0x517290`), and the found name signals `UNIT_NAME_UPDATE` to the tokens naming +/// the guid though no unit is held: `0x491a00` skips only the refresh without one (`0x491a23`), +/// never the signal (`0x491a3c`). So a raid frame's member out of view leaves "Unknown". +#[test] +fn a_unit_name_miss_signals_its_name_for_a_member_out_of_view() { + assert_eq!( + name_update_after_unit_name(false), + ["UNIT_NAME_UPDATE party1 Bob"] + ); +} + +/// The control: a held member's `UnitName` reads it through `GetUnitName` (`0x609210`), whose +/// callback is the unit's own (`0x5fb840`), so the answer signals once. +#[test] +fn a_held_members_name_answer_signals_once() { + assert_eq!( + name_update_after_unit_name(true), + ["UNIT_NAME_UPDATE party1 Bob"] + ); +} diff --git a/crates/benilla-app/src/lanes/group_view_tests.rs b/crates/benilla-app/src/lanes/group_view_tests.rs index b8dbf4633..b49942ca8 100644 --- a/crates/benilla-app/src/lanes/group_view_tests.rs +++ b/crates/benilla-app/src/lanes/group_view_tests.rs @@ -89,35 +89,27 @@ fn seat_party_targeting(app: &mut App, pet: u64, target: u64) { }); } -/// One frame: the packets, the unit, party, pet and chain feeds' pushes of the frame's state, -/// then the lanes' drain; what the spy saw. +/// One frame: the packets, each packet's lanes fired after its handlers, then the frame's drain; +/// what the spy saw. fn frame(app: &mut App, packets: Vec) -> Vec { - frame_after(app, |_| {}, packets) + run_frame(app, packets) } -/// [`frame`], with `before` run on the world between the frame-start snapshot and the packets. +/// [`frame`], with `inside` run inside the dispatch past the span's start and ahead of the +/// packets ([`super::unit_view_tests::inside_the_dispatch`]). fn frame_after( app: &mut App, - before: impl FnOnce(&mut World), + inside: impl FnOnce(&mut World) + Send + Sync + 'static, packets: Vec, ) -> Vec { + let events = super::unit_view_tests::inside_the_dispatch(app, inside, packets); + run_frame(app, events) +} + +/// `events` through the dispatch, then the frame's drain; what the spy saw. +fn run_frame(app: &mut App, events: Vec) -> Vec { let world = app.world_mut(); - #[cfg(debug_assertions)] - { - use bevy::ecs::system::RunSystemOnce; - world - .run_system_once(crate::ui_unit::views::mark_frame_start) - .unwrap(); - } - before(world); - crate::net::handlers::dispatch(world, packets); - crate::ui_unit::run_feed_units_once(world); - world - .run_system_cached(crate::ui_party::feed_party) - .expect("the party feed runs"); - world - .run_system_cached(crate::ui_pet::feed_pet_unit) - .expect("the pet feed runs"); + crate::net::handlers::dispatch(world, events); crate::lanes::fire_in_order(world); let s = world.non_send_resource_mut::(); let out = s.eval::>("return Seen").unwrap(); @@ -234,7 +226,7 @@ fn a_party_pet_replaced_mid_frame_reads_the_old_pet_before_the_swap() { .run(r#"function Look(event, unit) return UnitHealth("partypet1") end"#) .unwrap(); frame(&mut app, vec![]); - // The resolver's inputs as the feeds push them ahead of the drain: the frame's last pet. + // The resolver's stand-in as the frame left it: the frame's last pet. let seat_new_pet = |world: &mut World| { world .non_send_resource_mut::() @@ -269,8 +261,8 @@ fn a_party_pet_replaced_mid_frame_reads_the_old_pet_before_the_swap() { assert_eq!(seen, ["UNIT_COMBAT:player:10", "UNIT_COMBAT:player:20"]); } -/// A record written past the log fails the rewind's check against the frame-start snapshot: here -/// the member's maximum health, which no entry of the frame names. +/// A record written past the log fails the rewind's check against the span-start snapshot: here +/// the member's maximum health, which no entry of the span names. #[cfg(debug_assertions)] #[test] #[should_panic(expected = "a write the log missed")] @@ -288,9 +280,9 @@ fn a_record_write_the_log_missed_fails_the_rewind() { ); } -/// A record write after the lanes and before the next frame's snapshot needs no entry: the +/// A record write after the lanes and before the next span's snapshot needs no entry: the /// sandbox's (`/partytest off`, a sandboxed party call) runs in the drains of what the Lua asked, -/// past the lanes, and the next frame's rewind starts from the roster it left. +/// past the lanes, and the next span's rewind starts from the roster it left. #[test] fn a_record_write_between_frames_needs_no_entry() { let mut app = party_client(); @@ -1066,8 +1058,8 @@ fn each_listener_finds_the_member_its_own_list_seated_in_party1() { ); } -/// A roster cell written past the log fails the rewind's check against the frame-start snapshot: -/// here the leader cell, which no entry of the frame names. +/// A roster cell written past the log fails the rewind's check against the span-start snapshot: +/// here the leader cell, which no entry of the span names. #[cfg(debug_assertions)] #[test] #[should_panic(expected = "a write the log missed")] diff --git a/crates/benilla-app/src/lanes/guard_tests.rs b/crates/benilla-app/src/lanes/guard_tests.rs index 28efc6b70..2db497c2d 100644 --- a/crates/benilla-app/src/lanes/guard_tests.rs +++ b/crates/benilla-app/src/lanes/guard_tests.rs @@ -44,176 +44,152 @@ pub(super) enum Row { /// What still fires in the frame's system order rather than the packets', with what it is. A /// queue's row stays while any feed takes that queue; each goes when its producer moves onto a /// lane, and a row whose queue, feed or system is gone fails as stale. -pub(super) const NOT_YET_ON_A_LANE: &[(Row, &str, &str)] = &[ - ( - Row::Queue, - "::account_data::AccountData", - "the account-data sections a download replaced, whose readers (the binding sets, the \ - macros, the layout) run again off it; the chat setup's fires on its lane", - ), - ( - Row::Queue, - "::ui_action::errors::UiErrorKeys", - "the refusals the handlers push, which the action feed shows", - ), - ( - Row::Queue, - "::tutorial::Tutorials", - "the tutorial banks a handler fires", - ), - ( - Row::Queue, - "Messages", - "the tutorial events", - ), - ( - Row::Queue, - "::ui_action::errors::MountErrors", - "the mount refusals", - ), - ( - Row::Queue, - "::ui_action::errors::PetTameFailures", - "the pet-tame refusals", - ), - ( - Row::Queue, - "::ui_action::errors::UiErrorTexts", - "the wire's error texts", - ), - ( - Row::HostHeld, - "::minimap::ping::MinimapPing", - "the members' minimap pings, which `drive_minimap_ping` fires; our own `PingLocation`, \ - acting in its call, holds the ping in the host", - ), - ( - Row::Queue, - "::net::PlayedTimeAnswer", - "the played-time answer", - ), - ( - Row::Queue, - "::player::net::SkinnedFeed", - "the skinned state", - ), - ( - Row::Queue, - "::player::view_subject::FarSight", - "the far-sight machine a handler's Lua runs through the host's buff cancel; every feed \ - that lends the host reads it, and none fires from it", - ), - ( - Row::Queue, - "::creature_anim::gesture::GestureQueue", - "the gestures a chat line or a world click's greeting queues, which `drive_gestures` \ - plays; every feed that lends the host reads it, as the click's select queues the \ - greeting's in its call, and none fires from it", - ), - ( - Row::HostHeld, - "::ui_action::ActionSlots", - "the action slots, which `feed_actions` resolves; a handler's Lua writes them in its \ - call, through the host's bar verbs", - ), - ( - Row::HostHeld, - "::ui_logout::LogoutState", - "the logout state, which `feed_logout` fires from; the session verbs, acting in their \ - calls, hold it in the host", - ), - ( - Row::Queue, - "::ui_logout::SessionPosts", - "the exit and the cinematic stop a session verb posts, which nothing the script reads \ - waits on", - ), - ( - Row::Queue, - "::ui_quest_share::QuestShare", - "the quest share", - ), - ( - Row::Queue, - "::ui_quest::lines::QuestLines", - "the quest lines", - ), - ( - Row::HostHeld, - "::death::DeathNet", - "the death stores, which `feed_death` fires the offers and the corpse range from; the death verbs, acting in their calls, hold them in the host", - ), - ( - Row::HostHeld, - "::ui_craft::CraftOpen", - "the craft window's line, which `feed_craft` fires from; `CloseCraft`, acting in its call, holds it in the host", - ), - ( - Row::HostHeld, - "::ui_loot_roll::LootRolls", - "the open rolls, which `feed_loot_rolls` fires from; the votes, acting in their calls, hold them in the host", - ), - ( - Row::HostHeld, - "::ui_tradeskill::TradeSkillOpen", - "the profession window's line, which `feed_trade_skill` fires from; `CloseTradeSkill`, acting in its call, holds it in the host", - ), - ( - Row::Edge, - "::ui_action::state::fire_action_events", - "the usable cache's refresh `0x4e5c00` (`ACTIONBAR_UPDATE_USABLE`) of `EditMacro` \ - (`0x4f132e`) and `RaiseBagUpdate` (`0x4f9374`), which the reference runs in the call and \ - in the item watcher's run, one pass a frame over the bar's 120 slots diffed against the \ - cache", - ), -]; +pub(super) const NOT_YET_ON_A_LANE: &[(Row, &str, &str)] = &[( + Row::HostHeld, + "::items::Items", + "the record answers' callbacks still run off the frame's records rather than in the \ + answer's list (`ItemCacheReceive` `0x55bdb0`, `0x55bf12`-`0x55bf39`): the \ + dress-up's (`0x504ba0`) and the equipment display's (`0x5ed880`); and the combat log's \ + (`0x6294b0`) and the auction lists' (`0x4cca10`, `0x4ccc60`, `0x4cceb0`), which \ + `run_answer_tail` runs after the answer's list rather than in it", +)]; -/// The host-held queues a handler fills that are yet to be read for what their feeds fire, so -/// the list is the whole of that remaining work and must only shrink: the check finds a queue -/// the handlers and the host both hold, but not whether a feed fires off it what a packet -/// raised. Each goes once its feeds are read, to a [`Row::HostHeld`] row when one does, or named -/// quiet beside why when none does; a new one fails, and an entry whose queue the handlers or the -/// host no longer hold fails as stale. +/// The host-held queues a handler fills that no feed fires off, each named quiet beside why: the +/// check finds a queue the handlers and the host both hold, but not whether a feed fires off it +/// what a packet raised, so each is read for that before it goes here, and one a feed does fire +/// off is a [`Row::HostHeld`] row instead. A new one fails until it is read, and an entry whose +/// queue the handlers or the host no longer hold fails as stale. pub(super) const HOST_HELD_UNREAD: &[&str] = &[ + // Moved here from `NOT_YET_ON_A_LANE`, so neither list grew: the account-data sections, which + // the logout verb flushes inside its call (`0x5ab049` → `0x5afd30`), and quiet: each section's + // reader runs on its own lane at the settling's stamp, inside the packet that settled it + // (`0x5afaca`, `0x5afd19`), the bindings', the layout's, the macros' and the chat setup's. + "::account_data::AccountData", + // Quiet: StartAttack reads the stop word in its call (`0x5eccda`), the attack stop's handler + // clears it (`0x624e6b`), and no feed reads it. "::creature_anim::AttackStopInFlight", + // Quiet: the animations the handlers and the verbs ask for, which the model systems play; no + // getter reads a model's sequence. "::creature_anim::PlaySeq", + // Quiet: the gestures a chat line's firing and a world click's greeting queue, which + // `drive_gestures` plays as the speaker's animation (`0x60bb30` → `0x5fcd20`); no getter + // reads a model's gesture, and no feed fires off it. + "::creature_anim::gesture::GestureQueue", // Read through the host by the set block, and quiet: a member's answer rebuilds the tooltip // waiting on it through the build's own wait, read as the tick runs. "::item_names::ItemNames", - "::items::Items", + // Moved here from `NOT_YET_ON_A_LANE`, so neither list grew: read, and quiet. A member's ping + // stores the point at its packet and signals on the notice lane (`0x4ee330`), our own + // `PingLocation` holds it in the host in its call, and only a new VM's seed reads it. + "::minimap::ping::MinimapPing", + // Quiet: the object index, which the getters read through the host as they run; the feeds that + // read it push views (`READS_FRAME_FINAL`), and none fires off its change. "::net::GuidIndex", - // Read by the trainer's description getters through the host, and quiet. + // Quiet: `GetBindLocation` (`0x48dae3` → `0x5ed420`) and the `$z` token (`0x507f07` → + // `0x5ed420`) of the trainer's, the craft list's and the tooltips' descriptions read it through + // the host at the call; no feed fires off it. "::net::HomeBind", // Read through the host by the item requirement getters, and quiet: no feed fires off them. "::net::Proficiencies", + // Quiet: our own guid, which the login's handlers set and everything reads; the arrival's + // signals are the arrival lane's, and no feed fires off its change. "::net::SelfGuid", + // Written by the group handlers at their packets, read through the host by the relation + // getters (`0x4e7f70` inside `0x6061e0`), and quiet: no feed fires off it. + "::spell::group_relation::GroupRoster", // Read by the quest log getters through the host (`QuestClock`), and quiet: the time - // response's `QUEST_LOG_UPDATE` fires on the quest log lane. + // response's `QUEST_LOG_UPDATE` fires on the quest log lane, and `send_query_time`'s hourly + // resync is a timer. "::net::ServerWallClock", + // Read through the host by `GetGameTime` (`0x515ee0`), and quiet: no event signals the clock. "::net::game_time::ServerTime", // Read, and quiet: the control packet's handler and our own create's arrival signal its - // changes on the notice lane in place (`0x4958e0`), and the action bar's diff of it is - // `fire_action_events`'s edge row. + // changes on the notice lane in place (`0x4958e0`), with the usable refresh after them. "::player::state::OwnControlLost", // Read through the host by the world click's legs (who we drive, the gathering skills its // cursor forks on), and quiet: no feed fires off them. "::player::state::MoverLock", + // Read through the host by `HasFullControl` (`0x51a142`), and quiet: the update handler + // starts or ends far sight in place at the field's change (`0x5de0d0`) and starts it at its + // object's create (`0x5fbb1a`, `0x5d552d`), the clear's handler ends it (`0x5e441d`), the + // teardowns free it with our player, the buff cancel runs `UpdateFarSight` in its call + // (`0x6e70ad`), `PLAYER_FARSIGHT_FOCUS_CHANGED` is the field watch's, and no feed fires off it. + "::player::view_subject::FarSight", + // Read, and quiet: the follow's arm reads them in its call (`0x611130` → `0x60fb60`), and the + // handlers that end an auto-move signal its `AUTOFOLLOW_END` on the notice lane in place + // (`0x60fb84`). + "::player::approach::Approach", + "::player::follow::FollowState", + // Quiet: the autorun bit as the frame's calls leave it, read and written inside each call + // (`0x513de7`), which an auto-move's stop clears in place (`0x514630`). + "::player::press::CallAutorun", + // Quiet: the cast ladder's per-call state, which the cast result's, the loot response's and the + // go's handlers hold with the ladder and never write. A press holds the first and its call resumes it before it returns + // (`0x6e4efb`), each call sets and puts back the second, and the pet press applies the third + // in its call; no feed reads them. "::spell::cast_send::HeldForPick", "::spell::cast_send::ScriptCastPermit", "::spell::cast_send::unit_caster::UnitAttackOwed", + // Quiet: the cast in flight, which `SpellStopCasting` and the bar's tests read through the + // host, as of the drain's place, and the spell packets' events fire on the cast lane at their + // handlers. "::spell::inflight::ActiveChannel", "::spell::inflight::AutoRepeatActive", "::spell::inflight::PendingCast", "::spell::inflight::QueuedMeleeSpell", + // Quiet: read by the cost and `$`-token builds through the host at the call; the targeting + // feed pushes the input's word off it (`BUILT_OUTSIDE_THE_PACKETS_IN_THE_REFERENCE`), and none + // fires off it. "::spell::mods::SpellModifiers", + // Quiet: the units a select found the targeting cursor up for, which its writer binds at the + // select's place (`0x4935d5` → `0x6e5b40`): a handler's in its packet (the loot response's + // `0x48f3be`, the acquires' `0x6259fe` and `0x6e799c`, the go's deferred start's `0x5eccaa`), a + // call's before its next step; no feed reads it. "::spell::targeting::CursorPicks", + // Quiet: the targeting word, which `SpellIsTargeting` (`0x6e6cd0`) reads through the host; + // the feed publishes the world pick's words for the next frame's input, and no feed fires off + // it. "::spell::targeting::SpellTargeting", + // Quiet: every selection writer signals `PLAYER_TARGET_CHANGED` in place (`0x49389c`), and the + // getters' `"target"` reads it through the host (`0x515a86`); the feeds that read it push + // views. "::target::Selection", - "::ui_action::PlayerActions", + // Quiet: the world click's and `DropItemOnUnit`'s latches, read in their calls, which the + // learn, unlearn and supersede handlers write at their packet (`0x4b262c`, `0x5e9e49`, + // `0x4b2c83`); no feed fires off them. "::ui_action::LearnedAbilities", + // Read through the host by the bar's getters, and quiet: the bar's words, which our arrival's + // pass writes into the VM's copy (`0x5deb00`), the verbs and the spell packets' clears and + // replaces at their writes (`0x4e5d60`, `0x4e5db0`), and a new VM's seed copies; no feed fires + // off them. + "::ui_action::ActionSlots", + // Quiet: the reactive list, which the learn and supersede handlers' registrar leg grows at + // their packet (`0x4b27b3`-`0x4b27c7`) and our create's arrival empties and fills again + // (`0x5dea86`); the usable refreshes re-check it in their places, and no feed reads it. + "::ui_action::ReactiveSpells", + // Quiet: the bar's usable cache, which the game entry's handler zeroes (`0x48f5a4` → + // `0x4e4f50`) and the host's slot writes and refreshes store in place (`0x4e590a`, + // `0x4e5c00`); the getters read it at the call. + "::ui_action::state::ActionStateMemory", + // Quiet: the known spells and the book's lists, which the learn, unlearn and supersede handlers + // write at their packet beside the bar's clears and replaces, whose signals go on the notice + // lane there (`0x5ea253`, `0x5e6356`); the feeds that read it push views (`READS_FRAME_FINAL`), + // and none fires off it. + "::ui_action::PlayerActions", // Read through the host by the auction getters, and quiet: the hello's show, the lines, the // patches, the removals and the pages fire on the house lane at their handlers. "::ui_auction::AuctionOpen", + // Quiet: the craft and profession windows' open type and line, which an opener's cast + // toggles and signals inside its call (`0x4fc910`, `0x4f6000`), the closes zero in theirs, and + // the disconnect handlers (`ui_craft::on_session_end`, `ui_tradeskill::on_session_end`) clear + // without a signal; the profession and craft builds and getters read the line and the type + // through the host at their places. + "::ui_craft::CraftOpen", + "::ui_tradeskill::TradeSkillOpen", + // Quiet: the profession openers a cast intercepted (`0x6e4bd7`), which the call host toggles + // before the call returns and the disconnect handler (`ui_tradeskill::on_session_end`) + // empties; no feed reads it. + "::ui_tradeskill::TradeSkillOpens", // Read through the host by the bank getters, and quiet: its events fire on the bank lane at // their handlers, and `PurchaseSlot` and `CloseBankFrame` hold it in their calls. "::ui_bank::BankOpen", @@ -227,11 +203,15 @@ pub(super) const HOST_HELD_UNREAD: &[&str] = &[ "::ui_battlefield_score::BattlefieldScoreboard", "::ui_dialog_verbs::BattlefieldQueue", // Read through the host by `GetAreaSpiritHealerTime`, and quiet: the time packet's - // `AREA_SPIRIT_HEALER_IN_RANGE` goes on the notice lane. + // `AREA_SPIRIT_HEALER_IN_RANGE` goes on the notice lane, and `poll_area_spirit_healer` scans + // off it every frame, as the world frame's update does after the packets (`0x4818ca` → + // `0x4923b0`). "::ui_dialog_verbs::AreaSpiritHealer", // Moved here from `NOT_YET_ON_A_LANE`, so neither list grew: the dialogs' getters and verbs // read them through the host, and no feed fires off them, as their handlers' events go on the - // dialogs' lane. + // dialogs' lane. The duel's countdown is a timer ahead of the packets (`0x4d4930`, its + // `tick_countdown`), and the instance latch's writer is `track_instance_state`'s row in + // `BETWEEN_THE_DISPATCH_AND_THE_DRAIN`. "::ui_binder::BinderState", "::ui_dialog_verbs::InstanceBoot", "::ui_dialog_verbs::MeetingStone", @@ -246,17 +226,24 @@ pub(super) const HOST_HELD_UNREAD: &[&str] = &[ // Read through the host by the gossip getters, and quiet: the draw's `GOSSIP_SHOW` fires on the // gossip lane at its handler, and the gossip verbs hold it in their calls. "::ui_gossip::GossipState", + // Quiet: the reader's session, which the item-text getters read through the host and an + // item's deactivate closes in the object packet's handler (`0x5d8713`); `ITEM_TEXT_CLOSED` goes + // on the item-text lane at its place, and no feed fires off it. + "::ui_item_text::ItemTextOpen", + // Quiet: the loot session's auto-loot byte and latch, which the response's admit and the + // closes read in their handlers and calls; `LOOT_OPENED` and `LOOT_CLOSED` fire on the loot + // lane, and no feed fires off them. "::ui_loot::AutoLootByte", "::ui_loot::LootLatch", // Moved here from `NOT_YET_ON_A_LANE`, so neither list grew: the mail getters read them // through the host, and no feed fires off them, as the packets', the cores' and the record - // callbacks' events go on the mail lane at their handlers. + // callbacks' events go on the mail lane at their handlers. `step_pending_mail` steps the + // pending time in the world frame's update, as `0x4ade60` does after the packets. "::ui_mail::MailOpen", "::ui_mail::pending::MailPending", - // Read through the host by the stationery getters, and quiet: its rebuilds signal nothing. - "::ui_mail::stationery::UsableStationery", - // Read through the host by the merchant getters, and quiet: its events fire on the merchant - // lane at their handlers and callbacks. + // Moved here from `NOT_YET_ON_A_LANE`, so neither list grew: read through the host by the + // vendor's getters, and quiet. The list's handler triggers the Vendors tutorial on the + // tutorials lane at its packet (`0x4fad32`), and the window's events fire on the merchant lane. "::ui_merchant::MerchantOpen", // Moved here from `NOT_YET_ON_A_LANE`, so neither list grew: read, and quiet. A new pet's // `SMSG_PET_SPELLS` lowers it inside `SetPet` (`0x4bc8ce`), whose `PET_BAR_UPDATE` (`0x4bc90c`) @@ -265,6 +252,9 @@ pub(super) const HOST_HELD_UNREAD: &[&str] = &[ // the world entry's pet reset lowers it beside its own `PET_BAR_UPDATE`, which the reset's // change raises, not the latch. "::ui_pet::PetAttackLatch", + // Quiet: the registrar's cell and the charter records, which the registrar's and the charter's + // getters read through the host; the show, the close and the record callbacks fire on the + // charter lane at their handlers. "::ui_petition::GuildRegistrarState", "::ui_petition::PetitionRecords", // Read through the host by the charter getters, and quiet: its events fire on the charter lane @@ -272,9 +262,34 @@ pub(super) const HOST_HELD_UNREAD: &[&str] = &[ "::ui_petition::PetitionState", // Moved here from `NOT_YET_ON_A_LANE`, so neither list grew: the questgiver getters read its // cells through the host, and no feed fires off it, as its panels' events, lines and item - // callbacks go on the questgiver lane at their handlers. + // callbacks go on the questgiver lane at their handlers. `query_statuses` re-asks the givers' + // statuses off it after the dispatch, a send no script reads. "::ui_quest::QuestGiver", + // Quiet: the getters' and the verbs' `"npc"` reads the latch through the host as it runs + // (`0x515c00`), and the watchdog `watch_interaction_range` closes off it every frame, as + // `0x493230` does from the world frame's update, after the packets. `feed_interact_npc` + // copies it as `InteractNpc` right after the dispatch, for the frame's own readers: the + // facing chain and the portrait booth. "::ui_session::latch::InteractLatch", + // Moved here from `NOT_YET_ON_A_LANE`, so neither list grew: the session verbs read and write + // the logout bytes through the host in their calls, and quiet: the replies' handlers signal on + // the notice lane at their packets. + "::ui_logout::LogoutState", + // Quiet: what a session verb posts past its call, the exit `ForceQuit` posts (`0x48ab60` → + // `0x401560`), which `exit_on_logout_complete` takes in the drain, and the cinematic's stop + // (`0x48b970` → `0x48f050`), which the cinematic's chain takes at its head and fades at frame + // time; no feed fires off it. + "::ui_logout::SessionPosts", + // Quiet: the connection's state, which the session's handlers write and the death getters' + // body test reads through the host; no feed fires off it. + "::net::NetStatus", + // Moved here from `NOT_YET_ON_A_LANE`, so neither list grew: the death getters and + // `GetCorpseMapPosition` read the stores through the host and the death verbs hold them in + // their calls, and quiet: the offers and the + // corpse-range signals packets raise go on the dialogs' lane at their handlers, the revive's + // on the notice lane, and the corpse poll runs in the world frame's update, after the packets + // (`0x4818c5`). + "::death::DeathNet", // Read through the host by the taxi getters, and quiet: its events fire on the taxi lane at // their handlers. "::ui_taxi::TaxiState", @@ -290,170 +305,250 @@ pub(super) const HOST_HELD_UNREAD: &[&str] = &[ // Read, and quiet: `CheckTalentMasterDist` reads the latch through the host and the Accept // holds it; the question's `CONFIRM_TALENT_WIPE` fires on the notice lane. "::ui_talent_wipe::TalentWipeState", + // Moved here from `NOT_YET_ON_A_LANE`, so neither list grew: read through the host by the + // trainer's getters, and quiet. The list's open acknowledges its tutorial on the tutorials lane + // at its packet (`0x4d74ae`), and the window's events fire on the trainer lane. + "::ui_trainer::TrainerOpen", // Moved here from `NOT_YET_ON_A_LANE`, so neither list grew: the trade getters read it through // the host, and no feed fires off it, as its statuses' events go on the trade lane at their // handlers and the initiate's name callback. "::ui_trade::TradeSession", - "::ui_tradeskill::TradeSkillOpens", + // Read through the host by the map setter's landmark sources (`0x4a6819`), and quiet: the + // gossip handler's set re-selects the map on the landmark lane at its packet (`0x6dac93`), and + // the clears at its deadline and on arrival run in the minimap's update (`0x6d9411`, + // `0x6d9a4c`), past the frame's packets, on that lane. + "::poi_marker::PoiMarker", // Read through the host by the mail getters' letter bodies, whose `$` tokens expand off it - // (`0x506f70`), and quiet: its packets' signals fire on the world-state lane. + // (`0x506f70`), the readout's getters and the map setter's landmark sources, and quiet: its + // packets' signals fire on the world-state lane, and the defense channel's flip signals + // inside its notice (`0x49bdd6`). "::world_state::WorldStates", - // Read through the host by the trainer getters, and quiet: its events fire on the trainer - // lane at the list, the state pass's callers and the item callbacks. - "::ui_trainer::TrainerOpen", ]; /// The view pushes that read what a handler writes as the frame left it, not as each listener's -/// packet did: each VM-holding feed of the `UiFeed` phase with the state the handlers write that -/// it reads itself, past the call host's own reads. The reference's getters read the live object +/// packet did: each system that writes the VM, in any schedule and any set, with the state the +/// handlers write that it reads itself, past the call host's own reads. The reference's getters read the live object /// and caches at the listener's call (`UnitHealth` `0x5174d0`), and a handler runs whole before -/// the next (`0x537ae5`), so a listener reads its own packet's state; a push here hands a lane's -/// listener the frame's last. The list is the whole of that remaining work and only shrinks: a +/// the next (`0x537ae5`), so a listener reads its own packet's state; a push here hands a +/// listener inside the dispatch what the last push left, the frame before's. The list is the whole of that remaining work and only shrinks: a /// feed goes once a log versions what it reads ([`crate::ui_unit::views`]), a new one fails, and /// a row whose feed or inputs moved fails until it matches. #[rustfmt::skip] pub(super) const READS_FRAME_FINAL: &[(&str, &[&str])] = &[ - ("::player::net::feed_player_skinned", &["player::net::SkinnedFeed"]), - ("::death::feed_death", &["Transform", "death::DeathNet", "items::Countdowns", "items::Items", - "names::NameCache", "net::GuidIndex", "net::NetStatus", "net::ObjectStore", - "net::SelfGuid"]), - ("::minimap::ping::drive_minimap_ping", &["minimap::ping::MinimapPing", - "ui_party::GroupState"]), - ("::minimap::feed_game_time", &["net::game_time::ServerTime"]), + // The VM's copy of the item records, seated whole in a new VM and topped up with a record that + // lands outside an answer (a cache file's load), as the frame left the cache; an answer pushes + // its record at its packet, ahead of its callbacks (`0x55bdb0`), and a tooltip build reads the + // record and the player at the call (`0x5075f0` at `0x52da24`). A getter's miss is asked here, + // where the reference's lookup sends inside the call (`0x55ba30`). + ("::ui_items::feed::feed_item_stats", &["items::Items"]), + // The plates seated off the units as the frame left them, where the reference moves a plate's + // bar inside the packet, by its health watcher `0x7cc570` (registered by `0x7cc510`), and + // binds plates there too: `0x60f600`, called at `0x60706a` from `InvalidateNameDesc`, whose + // callers include `0x491a00`, `0x5ff800` and `0x604910`. + ("::vplates::drive_vplates", &["Transform", "names::NameCache", "net::GuidIndex", + "net::ObjectStore", "net::SelfGuid", "net::reputations::Reputations", + "player::camera::CameraControl", "spell::group_relation::GroupRoster", + "spell::targeting::SpellTargeting", "target::Selection", "ui_party::GroupState", + "video::Widescreen", "vplates::PlateFlashes", "vplates::VPlateMode"]), +]; + +/// The view pushes [`READS_FRAME_FINAL`]'s test finds whose build the reference too makes outside +/// every packet, held to their inputs the same way, with why: a hover's build that runs at a mouse +/// move (`0x7660d0`), the paint pass's repeat pick (`CSimpleTop::OnLayerUpdate` `0x765650`) or a +/// frame's own update in the frame pass, after the packets (`0x420d6a` after `0x420d55`), and whose +/// rebuilds inside a handler, if any, run there at their callbacks, so a listener fired inside the +/// dispatch reads what the last build left, as 1.12.1's does. They stay. +#[rustfmt::skip] +pub(super) const BUILT_OUTSIDE_THE_PACKETS_IN_THE_REFERENCE: &[(&str, &[&str], &str)] = &[ + // With `widescreen`, which seats the cursor-anchored plate on the interface's screen. + ("::ui_tooltip::drive_mouseover_tooltip", &["go_templates::GameObjectTemplates", + "names::NameCache", "net::GuidIndex", "net::ObjectStore", "net::SelfGuid", + "net::reputations::Reputations", "spell::group_relation::GroupRoster", + "ui_guild::GuildState", "video::Widescreen"], + "the WorldFrame's own update `0x481790` (its table's slot at `0x804420`), which picks and, \ + on a change of the mouseover alone (`0x482090` → `0x492e70` → `0x492890`), builds the \ + plate by kind; its rebuilds under the same hover run inside their packets: the unit's \ + (`0x4919d0`, from `0x491a00` and the flags watcher's `0x5ff7be`), the lock key's record \ + callback (`0x52ad10`) and the corpse owner's name callback (`0x52afe0`)"), ("::minimap::blips::drive_blip_tooltip", &["items::Countdowns", "names::NameCache", - "net::GuidIndex", "net::ObjectStore"]), - // The four tokens' snapshots read the stores as of the drain's place (`ui_unit::views`); the - // XP pair, the rest state, the combo points, the bar toggles and the worn display read the - // live store, and every snapshot its names, relations, selection and group, as the frame left - // them. - ("::ui_unit::feed_units", &["names::NameCache", "net::GuidIndex", "net::ObjectStore", - "net::SelfGuid", "net::reputations::Reputations", "target::Selection", - "ui_guild::GuildState", "ui_party::GroupState"]), - // The party and raid tokens read the members' stores, records and the roster's cells as of - // the drain's place (`ui_unit::views`), and the group getters read the cells through the host; - // the roster push is their no-host fallback, and every snapshot's names and relations read as - // the frame left them. - ("::ui_party::feed::feed_party", &["names::NameCache", "net::GuidIndex", "net::ObjectStore", - "net::SelfGuid", "net::reputations::Reputations", "ui_guild::GuildState", - "ui_party::GroupState"]), - ("::tutorial::feed_tutorials", &["items::Items", "net::ObjectStore"]), - ("::ui_logout::feed_logout", &["ui_logout::LogoutState"]), - // The engine's follow transitions, which a `FollowUnit` a handler's listener makes arms. - ("::ui_follow::feed_follow", &["player::follow::FollowState", "ui_follow::FollowFeed"]), - ("::ui_tooltip::drive_mouseover_tooltip", &["go_anim::GoAnim", - "go_templates::GameObjectTemplates", "items::Countdowns", "items::Items", - "names::NameCache", "net::GuidIndex", "net::ObjectStore", "net::SelfGuid", - "net::reputations::Reputations", "ui_action::PlayerActions", "ui_guild::GuildState"]), - ("::ui_tooltip::spell_feed::feed_spell_tooltips", &["items::Countdowns", "items::Items", - "net::GuidIndex", "net::HomeBind", "net::ObjectStore", "net::UnitSpeeds", - "net::motion::modes::UnitMoveModes", "net::motion::remote::RemoteMotion", - "net::reputations::Reputations", "spell::mods::SpellModifiers", - "ui_action::PlayerActions", "ui_pet::PetBar"]), - // The ammo getters' hits fire after the push that carries their record, whenever it runs. - ("::ui_char::feed_char", &["items::Countdowns", "items::Items", "names::NameCache", - "net::GuidIndex", "net::ObjectStore", "ui_char::AmmoRecordHits"]), - ("::ui_action::feed::feed_actions", &["items::Countdowns", "items::Items", "net::GuidIndex", - "net::ObjectStore", "ui_action::ActionSlots", "ui_action::PlayerActions", - "ui_action::errors::MountErrors", - "ui_action::errors::PetTameFailures", "ui_action::errors::UiErrorTexts"]), - ("::ui_action::state::feed_action_state", &["Transform", - "creature_anim::sheath::CommittedSheath", "items::Countdowns", "items::Items", - "names::NameCache", "net::GuidIndex", "net::ObjectStore", "net::SelfGuid", - "net::UnitSpeeds", "net::game_time::ServerTime", "net::motion::modes::UnitMoveModes", - "net::motion::remote::RemoteMotion", "net::reputations::Reputations", - "player::state::OwnControlLost", "player::state::StandPending", "spell::cooldowns::Cooldowns", - "spell::mods::SpellModifiers", "target::Selection", "ui_action::ActionSlots", - "ui_action::PlayerActions", "ui_action::state::ActionStateMemory", "ui_pet::PetBar"]), - // The ranged-slot item scales a ranged spell's range, read as the frame left it (#2217). - ("::spell::targeting::feed_targeting_to_vm", &["items::Items", "names::NameCache", + "net::GuidIndex", "net::ObjectStore"], + "the minimap's probe `0x4eb0c0`, its slot `0x3c`, which the hover pick calls at a mouse \ + move and at the paint pass's repeat pick (`0x7660d0`, from `0x765650`)"), + ("::minimap::feed_minimap_arrows", &["death::DeathNet", "net::GuidIndex", "net::ObjectStore", + "poi_marker::PoiMarker", "ui_party::GroupState"], + "the arrow half of the minimap's render (`0x4ec950`), which aims them by bearing"), + ("::player::camera::focus_on_look_edges", &["player::camera::CameraControl"], + "the mouse half of the freelook edges the frame's mouse made, which the input pass runs \ + ahead of its tick (`0x51491f` → `0x493070`, `0x493090`); a call's edge runs it inside"), + ("::spell::targeting::feed_targeting_to_input", &["items::Items", "names::NameCache", "net::GuidIndex", "net::ObjectStore", "net::UnitSpeeds", "net::motion::modes::UnitMoveModes", "net::motion::remote::RemoteMotion", "net::reputations::Reputations", - "spell::mods::SpellModifiers", "spell::targeting::SpellTargeting", "ui_party::GroupState"]), - // The resolver's guids, pushed before the drain and read with the host lent too: the - // mouseover, the group rows past a token's own, the pet records and every row of the field - // events' fan-out, which the `UNIT_HAPPINESS` gate reads. The aura getters walk each unit - // live, and the world entry's rebuild runs in its cascade (`0x490983`). - ("::ui_aura::feed_unit_guids", &["net::GuidIndex", "net::ObjectStore", "target::Selection", - "ui_party::GroupState"]), - // The pet book's sorts, which each pet spell list counts and the derivation follows - // (`0x4bdae0`): the frame's lists derive once, after the last. - ("::ui_macro::rebind_macro_spells", &["ui_action::ActionSlots", "ui_action::PlayerActions", - "ui_pet::PetBar"]), - ("::ui_macro::load_macros", &["ui_action::ActionSlots"]), - // The pet's snapshot reads its store as of the drain's place (`ui_unit::views`); its name - // reads as the frame left it. - ("::ui_pet::unit::feed_pet_unit", &["names::NameCache", "net::GuidIndex", "net::ObjectStore", - "net::SelfGuid", "ui_party::GroupState"]), - ("::ui_cast::feed_cast_reports", &["items::Countdowns", "items::Items", "net::GuidIndex", - "net::ObjectStore", "spell::inflight::AutoRepeatActive", "spell::inflight::PendingCast", - "spell::inflight::QueuedMeleeSpell", "spell::targeting::SpellTargeting", - "ui_action::cast_lines::CastFailRedisplays"]), - // The locks of the objects that went, forgotten as the frame left the index. - ("::ui_items::locks::forget_gone_item_locks", &["net::GuidIndex"]), - ("::ui_items::feed::feed_item_stats", &["items::Items", "net::HomeBind", "net::ObjectStore", - "spell::mods::SpellModifiers"]), - ("::ui_item_text::feed_item_text", &["go_templates::GameObjectTemplates", "items::Countdowns", - "items::Items", "names::NameCache", "net::GuidIndex", "net::ObjectStore", - "ui_item_text::ItemTextOpen", "ui_item_text::PageTexts", "ui_mail::MailOpen", - "world_state::WorldStates"]), - ("::ui_taxi::feed_on_taxi", &["net::ObjectStore"]), - // The getters' item callbacks, kept inside their calls, are spent as the frame left them. - ("::ui_tradeskill::feed_trade_skill", &["items::Countdowns", "items::Items", "net::GuidIndex", - "net::ObjectStore", "spell::cooldowns::Cooldowns", "ui_action::PlayerActions", - "ui_tradeskill::TradeSkillItemWaits", "ui_tradeskill::TradeSkillOpen"]), - // Beast Training reads the pet off its bar and its family off the creature record as the frame - // left them (#2217). - ("::ui_craft::feed_craft", &["items::Countdowns", "items::Items", "names::NameCache", - "net::GuidIndex", "net::ObjectStore", "spell::mods::SpellModifiers", - "ui_action::PlayerActions", "ui_craft::CraftItemWaits", "ui_craft::CraftOpen", - "ui_pet::PetBar"]), - ("::ui_loot_roll::feed_loot_rolls", &["items::Items", "names::NameCache", "net::SelfGuid", - "ui_loot_roll::LootRolls"]), - ("::ui_quest::lines::feed_quest_lines", &["items::Items", "ui_quest::lines::QuestLines", - "ui_quest_log::QuestLog"]), - ("::ui_quest_log::feed_quest_log", &["names::NameCache", "net::ObjectStore", - "ui_quest::lines::QuestLines", "ui_quest_log::QuestLog", "world_state::WorldStates"]), - ("::ui_quest_share::feed_quest_share", &["names::NameCache", "ui_quest_share::QuestShare"]), - ("::ui_chat::broadcast::feed_broadcasts", &["ui_chat::edit::ChannelState"]), - ("::ui_chat::channels::seed_channels", &["ui_chat::edit::ChannelState"]), - ("::ui_chat::feed::played_time_bridge", &["net::PlayedTimeAnswer"]), + "spell::group_relation::GroupRoster", "spell::mods::SpellModifiers", + "spell::targeting::SpellTargeting", "target::Selection", "ui_party::GroupState", + "ui_session::latch::InteractLatch"], + "the word as the frame began, for the input records' reads with no host to ask; a call's \ + reads go live through the host (`SpellIsTargeting` `0x6e6cd0`)"), + ("::ui_script::extract::tick_script", &["ui_script::UiScaleCvar", "video::Widescreen"], + "the frame pass's `OnUpdate` walk (`0x764330` → `0x765650`), its screen and scale"), + ("::ui_script::extract::paint_script", &["video::Widescreen"], + "the UI pass's paint, after the walk, which no getter reads"), + ("::ui_chat::channels::auto_join_zone_channels", &["net::ObjectStore", + "ui_chat::edit::ChannelState"], + "the zone text's update `0x494780`, whose walk (`0x494931`, gated on our taxi flag at \ + `0x494908`-`0x49491a`) the area poll runs in the idle pass after the packets \ + (`0x401ece` → `0x5db900` → `0x67e510` → `0x494780`), and `EndCinematic`'s (`0x48f1d0`), \ + in the frame pass; its runs inside a packet run there: the chat cache's load \ + (`0x499a22`) and the taxi flag's clear (`0x5ff56e`)"), +]; + +/// The systems that write the VM and push no view a getter reads of what a handler writes, by a +/// suffix of the system's name (beside [`NOT_YET_PLACED`]'s, whose firing is their work), with +/// what they do: an input's dispatch and the requests its calls queued, a timer or a poll that +/// signals in place, the CVar writes no call took, a session's end or the leave-world sweep's leg, +/// a save no script reads, a draw no getter reads, or the glue VM's frame, which no lane fires +/// into. The reference too does each outside every packet, so they stay; one that stops writing +/// the VM fails as stale. +#[rustfmt::skip] +pub(super) const WRITES_NO_VIEW: &[(&str, &str)] = &[ + ("::bindings::begin_dispatch", "the input pass's head: the binding calls Lua made, then the \ + frame's key records"), + ("::bindings::end_dispatch", "the input pass's tail: the stuck keys' release"), + ("::bindings::drain_binding_requests", "`SaveBindings`' files, written at the interface's \ + shutdown in the reference (`0x490bd0` → `0x4b65e0`)"), + ("::cursor::drive_displayed_cursor", "the cursor FrameXML set, and the world frame's hover \ + (`0x481790`)"), + ("::cvars::sync_cvars", "the CVar writes no call took into the mirror `GetCVar` reads (the \ + record's text, `0x488bf9`), and a new VM's seed: a packet's write reaches the mirror \ + inside its call, as `CVar::Set` runs inside its writer (`0x63df7d`), and every other is \ + made outside the packets (`every_cvar_write_reaches_the_mirror_before_a_packet`)"), + ("::cvars::sync_input_cvars", "the same writes, ahead of the world's mouse and the frame's \ + packets"), + ("::death::poll_corpse", "`CheckCorpseRange` (`0x492130`) every frame after the pick \ + (`0x4818c5`), signalling in place"), + ("::player::camera::apply_late_look_calls", "the look calls the frame's packets made, for \ + the input tick (`0x514840`)"), + ("::player::camera::latch_world_mouse", "the world's mouse buttons, the input's latch"), + ("::sound::ui::drain_ui_sounds", "`PlaySound`'s queued plays"), + ("::sound::zone::lua_music", "`PlayMusic` and `StopMusic`'s queued verbs"), + ("::target::click::act_on_arrival", "the verb an approach owed, at its stop (`0x60fa20`)"), + ("::target::click::act_on_interact", "a crate's `Interact`, the object's dispatcher"), + ("::ui_action::drain::attack_nearest_probe", "the melee probe's press"), + ("::ui_action::drain::drain_arrival_casts", "the cast a walk's arrival owed"), + ("::ui_action::drain::drain_click_casts", "the casts a crate's `Interact` queued"), + ("::ui_billing::poll_play_time", "the frame time's poll (`0x420d63`)"), + ("::ui_chat::away::movement_clears_afk", "the movement keys' AFK clear (`0x513d36`, \ + `0x514e23`, `0x514f0b`, `0x514fca`)"), + ("::ui_chat::channels::end_session_channels", "the session's end"), + ("::ui_chat::channels::end_session_channels_on_disconnect", "the session's end at a dead \ + socket"), + ("::ui_chat::idle::idle_handler", "the idle timer of `WorldFrame::Render` (`0x482ea0`)"), + ("::ui_chat::input::drain_chat_input", "the chat line's input"), + ("::ui_chat::settings::save_chat_looks", "the chat looks' save"), + ("::ui_dialog_verbs::drain_meeting_stone_joins", "the meeting stone's use, at its click"), + ("::ui_dialog_verbs::poll_area_spirit_healer", "the healer scan every frame (`0x4818ca` → \ + `0x4923b0`), signalling in place"), + ("::ui_dressup::compose_dressup", "the booth's frame: the try-on callbacks (`0x504ba0`) the \ + record answers owe, which `NOT_YET_ON_A_LANE`'s `Items` row counts, then the pane's look, \ + a draw"), + ("::ui_logout::leave_world", "the world load's first call (`0x401bd4`)"), + ("::ui_loot::close_loot_on_leave_world", "the sweep's loot leg (`0x490ab2`)"), + ("::ui_macro::save_dirty_macros", "the macros' save"), + ("::ui_mail::close_mail_on_leave_world", "the sweep's mail leg (`0x490b1b`)"), + ("::ui_models::sync_tiles", "the model panes' draw"), + ("::ui_script::glue_mgr::drive_glue_mgr", "the glue VM's `CGlueMgr::Idle` (`0x46b930`), \ + under the glue screens only"), + ("::ui_script::movie::upload_movie_pictures", "the movie's pictures, a draw"), + ("::ui_world_map::dev_map_jump", "a dev instrument's click"), + ("::video::drain_restart_gx", "the `RestartGx` asks no call took"), ]; /// The resources the handlers fill through a shared reference, which their declared access shows -/// as a read: the error keys a refusal pushes, the tutorial banks a watcher fires, the close -/// counts a window's core adds to and what a session verb posts. The lanes and the host's two -/// other sinks (the message sounds and the unit edits, which raise no event) are not queues here. -const FILLED_THROUGH_A_READ: &[&str] = &[ +/// as a read: the account data a download stores and what a session verb posts. One the call host +/// holds too is every hosted feed's read, so it is host-held, whichever handler fills it: a +/// [`Row::HostHeld`] row or a [`HOST_HELD_UNREAD`] entry. The lanes (the tutorials' and the ui errors' among them) and the host's two other sinks (the +/// message sounds and the unit edits, which raise no event) are not queues here. Each is named +/// by its path in the crate and matched whole ([`filled_through_a_read`]). +pub(super) const FILLED_THROUGH_A_READ: &[(&str, Fill)] = &[ // The account-data sections, which the download's handler stores through `&self`. - "::account_data::AccountData", - "::ui_action::errors::UiErrorKeys", - // The far-sight machine the call host's buff cancel runs (`0x6e70ad`). - "::player::view_subject::FarSight", - "::tutorial::Tutorials", - "::ui_logout::SessionPosts", + ("::account_data::AccountData", Fill::State), + // The far-sight machine the update handler starts and ends (`0x5de0d0`, `0x5fbb1a`, + // `0x5d552d`), the clear's handler ends (`0x5e441d`), the teardowns free and the call host's + // buff cancel runs (`0x6e70ad`). + ("::player::view_subject::FarSight", Fill::State), + // What a session verb posts, which the logout's and the cinematic's drains take. + ("::ui_logout::SessionPosts", Fill::Sink), // The gestures a chat line or a world click's greeting plays, which `drive_gestures` takes. - "::creature_anim::gesture::GestureQueue", + ("::creature_anim::gesture::GestureQueue", Fill::Sink), ]; +/// What a resource [`FILLED_THROUGH_A_READ`] holds is to the systems that reach it. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(super) enum Fill { + /// State its users read and write through `&self`: a read of it is a read. + State, + /// A sink its users push onto and a system of its own takes: a lane firing's access to it is + /// its own push, never a read of what a handler left. + Sink, +} + +/// Whether `n`, a type's full name, is a [`FILLED_THROUGH_A_READ`] entry, matched whole. +pub(super) fn filled_through_a_read(n: &str) -> Option { + FILLED_THROUGH_A_READ + .iter() + .find(|(e, _)| names_exactly(n, e)) + .map(|&(_, fill)| fill) +} + /// Every other resource a handler reads and does not write: state, tables and caches it -/// consults, none of them a queue a feed takes. A new one fails until it is placed here or in +/// consults, none of them a queue a feed takes. A system between the dispatch and the drain that +/// writes one has its row in `host_read_tests`'s lists, as a feed that rewrites what a handler +/// reads would hand it the frame before's. A new one fails until it is placed here or in /// [`FILLED_THROUGH_A_READ`]. The list is kept by hand: an entry a handler in fact fills through a /// shared reference leaves that queue out of [`handler_queues`], so a feed that takes it and fires /// in system order, or a system that pushes onto a lane off it at its own place, passes every -/// check here unseen. -const READ_ONLY_TO_HANDLERS: &[&str] = &[ +/// check here unseen. Each is named by its full path, the crate's own by its path in the crate, +/// and matched whole ([`names_exactly`]). +pub(super) const READ_ONLY_TO_HANDLERS: &[&str] = &[ + // `AreaPOI.dbc`, the landmark rows the gossip marker's re-select of the map reads + // (`0x6dac93` → `0x4a67a0`, its walk at `0x4a6819`). + "::area_poi::AreaPoiRes", + // The chat log files: the logging verbs open and close them through `&self` inside their + // call (`0x49fea2`), a file no handler reads back; the chat tee only appends to them. + "::ui_chat::logging::ChatLogFiles", + // The gossip marker, which the map setter's landmark sources read through the host + // (`0x4a6819`); `SMSG_GOSSIP_POI`'s handler and the minimap's clears write it through their + // own `ResMut` (`0x6dac10`, `0x6d9411`, `0x6d9a4c`). + "::poi_marker::PoiMarker", + // The language word pools, which a page's show rewrites it by (`0x4e3856`), loaded once at + // startup; the show reads the character's skill live (`0x4e3837` → `GetIndexedSpellSkill`). + "::ui_chat::language::ChatLanguages", // The usable stationery list, whose first paper the list parse gives a row with none - // (`0x4ad565`); the paper callback's handler writes it, through its own `ResMut`. + // (`0x4ad565`); the paper callback writes it in the item answer's list, through its own + // `ResMut`. "::ui_mail::stationery::UsableStationery", // `ItemBagFamily.dbc`, which the inventory refusal's handler names a bag's family by // (`0x5ede00`). "::ui_items::ItemBagFamilies", - // `AuctionHouse.dbc`, whose deposit rate the hello's show hands the VM. + // `AuctionHouse.dbc`, whose deposit rate the hello's show hands the VM, and which the host's + // mail getters read a row off. "::ui_auction::AuctionHouses", + // The corpse-range latch, which the reclaim delay's handler tests to signal again + // (`0x4962ec`); the corpse query's not-found handler and the corpse poll write it through + // their own `ResMut`. + "::death::DeathLatches", + // The connection's state, which the death getters' body test reads through the host; the + // socket's handlers write it through their own `ResMut`. + "::net::NetStatus", // The login pick, which names the character the account-data sections belong to. "::glue_session::roster::Roster", // `0xb4e314`, which the party snapshot reads; only the zone feed commits it. "::area::CommittedZone", + // The walk's committed zone, which the recruitment cascade's plan reads through the host + // (`0x49ead7`), and the slots; the walk's poll and the notice lane's taxi walk write them + // through their own `ResMut`. Both sit here only because the scan cannot see an exclusive + // handler's writes: the chat cache's read writes both inside its section's settle, in its + // packet (`0x499a22`). + "::ui_chat::channels::ZoneChannelWalk", "::ui_chat::edit::ChannelState", // The console's registry, which a `ConsoleExec` a listener makes reads. "::console::ConsoleCommands", @@ -465,120 +560,122 @@ const READ_ONLY_TO_HANDLERS: &[&str] = &[ // tooltip lines from. "::ui_unit::tooltip_facts::StudyTables", // The area names a trainer description's `$z` reads through the host. - "::QuestHeaderNamesRes", - "::HomeBind", + "::ui_quest_log::QuestHeaderNamesRes", + "::net::HomeBind", "::ui_trainer::TrainerOpen", "::ui_stable::StableSlotPrices", - "::AreaTableRes", + "::area::AreaTableRes", // The server clock the quest log getters read in the host. - "::ServerWallClock", + "::net::ServerWallClock", // The page materials the questgiver background getter reads in the host (`0x502230`). - "::PageMaterials", + "::ui_item_text::PageMaterials", // The world map's projections the battleground position getters read in the host, and the // stat columns' table the status handler reads (`0x4aa9c3`). - "::WorldMapUiData", - "::WorldStateUiRes", - "::DamageTextGates", - "::EnvDamageTable", - "::SpellVisuals", - "::Creatures", - "::ItemDisplays", + "::ui_world_map::WorldMapUiData", + "::world_state_ui::WorldStateUiRes", + "::combat_text::law::DamageTextGates", + "::creature_anim::env_damage::EnvDamageTable", + "::creature_anim::spell_visual::SpellVisuals", + "::entities::Creatures", + "::entities::equipment::ItemDisplays", // `ItemClass.dbc`, whose names the host's `GetItemInfo` reads. - "::ItemClasses", - "::GameObjectTemplates", - "::Enchants", - "::Items", - "::RandomProperties", - "::ChrClassTable", - "::ChrRaceTable", - "::RacePvpTeams", - "::MacroBoundSpells", - "::NameCache", - // The Video menus' lists the host's resolution and multisample verbs read (`0x48bc90`, `0x48c3e0`). - "::video::Widescreen", - "::view::MsaaFormats", - "::ServerTime", - "::GuidIndex", + "::ui_items::ItemClasses", + "::go_templates::GameObjectTemplates", + "::items::Enchants", + "::items::Items", + "::items::RandomProperties", + "::chr_classes::ChrClassTable", + "::chr_classes::ChrRaceTable", + "::chr_classes::RacePvpTeams", + "::names::NameCache", + // The Video menu's list the host's multisample verbs read (`0x48c3e0`). + "benilla_world::view::MsaaFormats", + // A capture run, which parks the camera the view verbs would move. + "::run_mode::CaptureMode", + "::net::game_time::ServerTime", + "::net::GuidIndex", // The bag cache the open-container handler numbers its `BAG_OPEN`s from. - "::BagCache", - "::NetCommands", - "::SelfGuid", - "::OwnControlLost", - "::Player", + "::item_watch::BagCache", + "::net::NetCommands", + "::net::SelfGuid", + "::player::state::OwnControlLost", + "::player::state::Player", // The request ladder's tests, which its status reads (`0x4bf793`, `0x4bf7a5`, `0x4bf7bc`). "::cinematic::Cinematic", "::ui_auction::AuctionOpen", "::ui_trade::BlockTrades", // Who we drive, which the loot response reads; our own create's arrival writes it. "::player::state::MoverLock", + // The active mover, which the handlers that end an auto-move test (`0x6103a0`); our own + // create's arrival claims it (`0x4958a0`). + "::net::MoverClaim", "::player::state::StandPending", // The page cache the host's page turns read. "::ui_item_text::PageTexts", // The streamed terrain the host's minimap ground cast traces. - "::terrain_stream::TerrainStreamer", - "::Assets", + "benilla_world::terrain_stream::TerrainStreamer", + "bevy_asset::assets::Assets", // The pet trainer's latch, which the host's `ConfirmPetUnlearn` reads. "::ui_dialog_verbs::PetUnlearnState", - "::BarUnitOutdoors", - "::PlayerOutdoors", - "::EmoteSounds", - "::ExplorationSounds", - "::ScriptCastPermit", - "::AutoSelfCast", - "::GroupRoster", - "::ActiveChannel", - "::SpellModifiers", - "::AssistAttack", - "::Hovered", - "::HoveredObject", - "::Factions", - "::CreatureTypes", - "::LastEnemy", - "::Selection", - "::TextFilter", - "::TextFilterSwitches", - "::PlayerActions", - "::SpellMechanics", - "::Spells", - "::CombatLogRanges", - "::LogPeriodicSpells", - "::GuildMemberNotify", - "::PetitionRecords", - "::ItemSubClasses", - "::LootConfig", - "::LootKneel", - "::MailOpen", - "::Stationery", + "::player::world_focus::BarUnitOutdoors", + "::player::world_focus::PlayerOutdoors", + "::sound::emote::EmoteSounds", + "::sound::zone::ExplorationSounds", + "::spell::cast_target::AutoSelfCast", + "::spell::group_relation::GroupRoster", + "::spell::inflight::ActiveChannel", + "::spell::mods::SpellModifiers", + "::target::AssistAttack", + "::target::Hovered", + "::target::HoveredObject", + "::target::ring::Factions", + "::target::scan::CreatureTypes", + "::target::scan::LastEnemy", + "::target::Selection", + "::text_filter::TextFilter", + "::text_filter::TextFilterSwitches", + "::ui_action::PlayerActions", + "::ui_action::SpellMechanics", + "::ui_action::Spells", + "::ui_chat::combat::CombatLogRanges", + "::ui_chat::combat::LogPeriodicSpells", + "::ui_guild::GuildMemberNotify", + "::ui_petition::PetitionRecords", + "::ui_items::ItemSubClasses", + // `showLootSpam`, which the roll handlers read as their lines compose (`0x61ba3a`, + // `0x61bafe`, `0x61c0b9`); a listener's `SetCVar` writes it inside its call. + "::ui_loot::LootConfig", + "::ui_loot::LootKneel", + "::ui_mail::MailOpen", + "::ui_mail::Stationery", // The tables and the world states the host's mail getters read a row off (`0x4aee11`, // `0x4af229`, `0x4aec87`, the body's `$` expansion `0x506f70`). - "::AuctionHouses", - "::MailTemplates", + "::ui_mail::MailTemplates", "::ui_mail::Packages", "::world_state::WorldStates", // The repair discounts and the taxi graph the host's merchant and taxi verbs consult. - "::RepairTables", - "::TaxiCatalogs", + "::ui_merchant::RepairTables", + "::ui_taxi::routing::TaxiCatalogs", // The bank's prices and the dialogs' states the host's bank, battleground, death, duel, // innkeeper and summon verbs consult. - "::BankPrices", + "::ui_bank::BankPrices", "::ui_battlefield::Battlefield", - "::MapCatalogRes", - "::BinderState", - "::BattlefieldQueue", - "::DuelState", - "::SummonState", + "benilla_assets::MapCatalogRes", + "::ui_binder::BinderState", + "::ui_dialog_verbs::BattlefieldQueue", + "::ui_duel::DuelState", + "::ui_summon::SummonState", // The dialogs' state the call host's getters read (`0x48b620`, `0x4ca570`, `0x495c90`). - "::InstanceBoot", - "::MeetingStone", - "::InstanceState", - "::UiClock", - "::InteractNpc", - "::SkillLines", + "::ui_dialog_verbs::InstanceBoot", + "::ui_dialog_verbs::MeetingStone", + "::ui_instance::InstanceState", + "::ui_script::UiClock", + "::ui_spellbook::SkillLines", // The talent catalog, which the host's talent getters read. "::ui_talent::Talents", - "::SpellFocus", - "::FrameStep", - "::CurrentMap", + "::ui_tradeskill::SpellFocus", + "benilla_world::frame_pace::FrameStep", + "benilla_world::world_map::CurrentMap", "bevy_time::time::Time", "bevy_time::time::Time", // The stores as of the drain's place, which the call host's token lookups read. @@ -588,7 +685,7 @@ const READ_ONLY_TO_HANDLERS: &[&str] = &[ "::ui_unit::LanguagesRes", "::ui_unit::DefaultLanguagesRes", // The area under the player, which the host's raid rows read for our own zone (`0xb4e314`). - "::CurrentArea", + "benilla_world::terrain_stream::queries::CurrentArea", // The interface clock's pair as the last tick left it, which the call host's buff timers // map each duration stamp through (`0x4e4450`); only the tick's copy and a new VM's seed // write it. @@ -602,25 +699,25 @@ const READ_ONLY_TO_HANDLERS: &[&str] = &[ // The proficiency masks the call host's requirement getters read (`0x5ea930`). "::net::Proficiencies", // `ItemSet.dbc` and the item-name cache the call host's set block reads (`0x52df5a`). - "::ItemSets", - "::ItemNames", + "::ui_items::ItemSets", + "::item_names::ItemNames", // What the world click's legs read in the call (`0x481f60`): the lock tables an object's - // open gates on, the cover and the inspector that refuse an arm, the look tuning and the - // frame's motion its drag test reads, `deselectOnClick`, and Shift for `SetAutoLoot`. + // open gates on, the cover and the inspector that refuse an arm, the frame's motion its drag + // test reads, and Shift for `SetAutoLoot`. "::go_templates::LockTypes", "::go_templates::Locks", // The gathering skills the world click's cursor forks on, read through the host. "::ui_action::LearnedAbilities", "::loading_screen::LoadingScreen", - "::player::camera::LookConfig", - "::target::ClickConfig", "::ui_script::InspectMode", "bevy_input::button_input::ButtonInput", "bevy_input::mouse::AccumulatedMouseMotion", + // The frame a quest-share line starts its bounded wait for a name at. + "bevy_diagnostic::frame_count_diagnostics_plugin::FrameCount", ]; /// Every lane's queue, by type: what a handler fills there fires in the packets' order. -fn lane_types() -> [TypeId; 38] { +pub(super) fn lane_types() -> [TypeId; 42] { [ // The views lane: what each packet changed in the stores. TypeId::of::(), @@ -638,13 +735,15 @@ fn lane_types() -> [TypeId; 38] { // The list rebuilds a learn, an unlearn or a pet's spells owe, stamped at their packets. TypeId::of::(), // The field callbacks' lane: the signals each callback's legs parked, stamped under its - // edge. + // edge, and the refused records' walks gone on behind their signals. TypeId::of::(), // The release lane: the signals each selection teardown parked, stamped under its release. TypeId::of::(), TypeId::of::(), // The item-text lane: the page-text packets' reads, stamped at their packets. TypeId::of::(), + // The rolls' lane: the roll packets' and their lookups' callbacks' signals and lines. + TypeId::of::(), // The cooldown lanes: the player's list and the pet's, which log their writes and flushes // at their places. TypeId::of::(), @@ -670,6 +769,7 @@ fn lane_types() -> [TypeId; 38] { TypeId::of::(), // The world-state lane: each packet's map and readout signals. TypeId::of::(), + TypeId::of::(), // The dialogs' lane: the service questions, the boot, the stone, the summon, the // lockouts, the duel and the ticket answers, at their packets. TypeId::of::(), @@ -694,89 +794,16 @@ fn lane_types() -> [TypeId; 38] { TypeId::of::(), // Our player's arrival, stamped at its create. TypeId::of::(), - ] -} - -/// [`lane_types`] by the lane that drains each: a queue is stripped only from its own lane's row, -/// so another lane's read of the same type shows as the state it is. -fn lane_queue_owners() -> [(&'static str, TypeId); 38] { - [ - ("unit views", TypeId::of::()), - ( - "field notices", - TypeId::of::(), - ), - ("item watchers", TypeId::of::()), - ("equip errors", TypeId::of::()), - ("loot", TypeId::of::()), - ("chat", TypeId::of::()), - ("cast reports", TypeId::of::()), - ( - "auction house", - TypeId::of::(), - ), - ("party", TypeId::of::()), - ("party", TypeId::of::()), - ( - "list rebuilds", - TypeId::of::(), - ), - ( - "field callbacks", - TypeId::of::(), - ), - ("releases", TypeId::of::()), - ("owed selects", TypeId::of::()), - ( - "item text", - TypeId::of::(), - ), - ("cooldowns", TypeId::of::()), - ("pet cooldowns", TypeId::of::()), - ("reputation", TypeId::of::()), - ( - "quest events", - TypeId::of::(), - ), - ("cast views", TypeId::of::()), - ("guild", TypeId::of::()), - ( - "battlefield", - TypeId::of::(), - ), - ("social", TypeId::of::()), - ("social", TypeId::of::()), - ("merchant", TypeId::of::()), - ("taxi", TypeId::of::()), - ( - "world states", - TypeId::of::(), - ), - ( - "dialogs", - TypeId::of::(), - ), - ("tabard", TypeId::of::()), - ("stable", TypeId::of::()), - ("charter", TypeId::of::()), - ("trainer", TypeId::of::()), - ("bank", TypeId::of::()), - ("gossip", TypeId::of::()), - ( - "quest giver", - TypeId::of::(), - ), - ("trade", TypeId::of::()), - ("mail", TypeId::of::()), - ( - "arrival", - TypeId::of::(), - ), + // The tutorials lane: each site's trigger, acknowledge and selection, and the flags' + // copy, stamped where it runs. + TypeId::of::(), + // The ui-error lane: each refusal and notice, stamped where its handler or verb shows it. + TypeId::of::(), ] } /// Whether `id` names a `Messages` buffer, which a reader takes from through a read. -fn is_messages(world: &World, id: ComponentId) -> bool { +pub(super) fn is_messages(world: &World, id: ComponentId) -> bool { name(world, id).contains("Messages<") } @@ -787,17 +814,21 @@ pub(super) fn name(world: &World, id: ComponentId) -> String { .map_or_else(|| "?".to_string(), |n| n.to_string()) } -fn ends_with_any(name: &str, rows: &[&str]) -> bool { +pub(super) fn ends_with_any(name: &str, rows: &[&str]) -> bool { rows.iter().any(|s| name.ends_with(s)) } -/// The queues the handlers fill, by id: each resource one writes, past the pure caches, and each -/// resource in [`FILLED_THROUGH_A_READ`] one reads. +/// The queues the handlers fill, by id: each resource one writes, past the pure caches, each +/// resource in [`FILLED_THROUGH_A_READ`] one reads, and, when one can queue a unit edit, what the +/// edits write as they apply after it ([`applied_by_the_unit_edits`]). fn handler_queues( world: &World, caches: &std::collections::HashSet, ) -> Vec { let handlers = world.resource::(); + let edits = world + .components() + .get_resource_id(TypeId::of::()); let mut out = BTreeSet::new(); for (_, access) in handlers.accesses() { let access = access.combined_access(); @@ -805,12 +836,25 @@ fn handler_queues( out.extend( access .resource_reads() - .filter(|id| ends_with_any(&name(world, *id), FILLED_THROUGH_A_READ)), + .filter(|id| filled_through_a_read(&name(world, *id)).is_some()), ); + if edits.is_some_and(|e| access.has_resource_read(e)) { + out.extend(applied_by_the_unit_edits(world)); + } } out.into_iter().collect() } +/// What the unit edits write as they apply ([`crate::creature_anim::applied_resources`]): a +/// handler's edits apply after it in the net drain, by an exclusive system whose writes Bevy's +/// access does not show, so each is a queue that handler fills. +fn applied_by_the_unit_edits(world: &World) -> Vec { + crate::creature_anim::applied_resources() + .into_iter() + .filter_map(|t| world.components().get_resource_id(t)) + .collect() +} + /// The call host's own state, which every system that lends it holds: what a call touches. fn call_host_access(world: &mut World) -> bevy::ecs::query::Access { use bevy::ecs::system::System; @@ -888,11 +932,10 @@ fn every_resource_a_handler_reads_is_a_known_queue_or_read_only() { eprintln!("skipped: this build carries no type names"); return; } + let read_only = |n: &str| READ_ONLY_TO_HANDLERS.iter().any(|e| names_exactly(n, e)); let unknown: Vec<&String> = reads .iter() - .filter(|n| { - !ends_with_any(n, FILLED_THROUGH_A_READ) && !ends_with_any(n, READ_ONLY_TO_HANDLERS) - }) + .filter(|n| filled_through_a_read(n).is_none() && !read_only(n)) .collect(); assert!( unknown.is_empty(), @@ -904,19 +947,33 @@ fn every_resource_a_handler_reads_is_a_known_queue_or_read_only() { .collect::>() .join("\n ") ); - let stale: Vec<&str> = READ_ONLY_TO_HANDLERS + let mut stale: Vec<&str> = READ_ONLY_TO_HANDLERS .iter() - .chain(FILLED_THROUGH_A_READ) - .filter(|s| !reads.iter().any(|n| n.ends_with(*s))) + .filter(|e| !reads.iter().any(|n| names_exactly(n, e))) .copied() .collect(); + stale.extend( + FILLED_THROUGH_A_READ + .iter() + .map(|&(s, _)| s) + .filter(|s| !reads.iter().any(|n| names_exactly(n, s))), + ); assert!(stale.is_empty(), "stale rows: {stale:?}"); } -/// The drain runs once a frame after every feed and before the tick, gated as the feeds of the -/// in-game interface are, and holds the lanes. +/// Whether `n`, a type's full name, is the type `entry` names: the crate's own by its path in the +/// crate (`::items::Items`), any other by its full name. Never a suffix, so a new type that shares +/// a listed one's short name is not taken for it. +fn names_exactly(n: &str, entry: &str) -> bool { + n == entry || n.strip_prefix("benilla_app") == Some(entry) +} + +/// The frame's drain, of what the feeds and the frame's systems push after the dispatch, runs once +/// a frame after every feed and before the tick, gated as the feeds of the in-game interface +/// are, and holds the lanes; the dispatch, whose flushes fire each packet's lanes, runs ahead of +/// every feed, so no feed's push lands between two packets. #[test] -fn the_drain_runs_after_the_feeds_and_before_the_tick() { +fn the_frames_drain_runs_after_the_feeds_and_before_the_tick() { let mut app = headless_client(); let mut lanes = app.world().resource::().names(); lanes.sort_unstable(); @@ -927,6 +984,7 @@ fn the_drain_runs_after_the_feeds_and_before_the_tick() { "auction house", "bank", "battlefield", + "binding arrivals", "cast reports", "cast views", "charter", @@ -941,8 +999,12 @@ fn the_drain_runs_after_the_feeds_and_before_the_tick() { "guild", "item text", "item watchers", + "landmarks", + "layout arrivals", "list rebuilds", "loot", + "loot rolls", + "macro arrivals", "mail", "merchant", "owed selects", @@ -958,6 +1020,8 @@ fn the_drain_runs_after_the_feeds_and_before_the_tick() { "taxi", "trade", "trainer", + "tutorials", + "ui errors", "unit views", "world states" ] @@ -1002,26 +1066,48 @@ fn the_drain_runs_after_the_feeds_and_before_the_tick() { late.is_empty(), "feeds not ordered ahead of the drain: {late:?}" ); + let (dispatch, _) = c + .systems + .iter() + .find(|(_, s)| s.name.ends_with("::net::apply::apply_net_updates")) + .expect("the dispatch is in Update"); + let mut next: HashMap<_, Vec<_>> = HashMap::new(); + for (a, b) in &c.dependencies { + next.entry(*a).or_default().push(*b); + } + let behind = |start| { + let mut seen = std::collections::HashSet::new(); + let mut stack = vec![start]; + while let Some(n) = stack.pop() { + for m in next.get(&n).into_iter().flatten() { + if seen.insert(*m) { + stack.push(*m); + } + } + } + seen + }; + let after_dispatch = behind(*dispatch); + let early: Vec<&str> = c + .systems + .iter() + .filter(|(k, s)| s.sets.iter().any(|set| set == "UiFeed") && !after_dispatch.contains(*k)) + .map(|(_, s)| s.name.as_str()) + .collect(); + assert!( + early.is_empty(), + "feeds not ordered behind the dispatch: {early:?}" + ); let tick = c .systems .iter() .find(|(_, s)| s.name.ends_with("::extract::tick_script")) .map(|(k, _)| *k) .expect("the tick"); - let mut after = std::collections::HashSet::new(); - let mut stack = vec![*drain]; - let mut next: HashMap<_, Vec<_>> = HashMap::new(); - for (a, b) in &c.dependencies { - next.entry(*a).or_default().push(*b); - } - while let Some(n) = stack.pop() { - for m in next.get(&n).into_iter().flatten() { - if after.insert(*m) { - stack.push(*m); - } - } - } - assert!(after.contains(&tick), "the drain runs before the tick"); + assert!( + behind(*drain).contains(&tick), + "the drain runs before the tick" + ); } /// The remaining work, whole. A queue the handlers fill ([`handler_queues`]) that a VM-holding @@ -1060,9 +1146,14 @@ fn every_handler_queue_a_feed_takes_is_on_a_lane_or_listed() { .iter() .filter(|&&id| Some(id) != vm && !lanes.contains(&id)) .filter(|&&id| !is_messages(world, id)) - .filter(|&&id| !ends_with_any(&self::name(world, id), FILLED_THROUGH_A_READ)) .filter(|&&id| host.has_resource_read(id)) - .filter(|id| filled_apart.contains(id)) + // A queue filled through a read is every handler's that holds the host, whichever + // fills it, so each the host reads is held; a written one is held once a handler + // apart from the host writes it. + .filter(|&&id| { + filled_apart.contains(&id) + || filled_through_a_read(&self::name(world, id)).is_some() + }) .map(|&id| self::name(world, id)) .collect(); for (key, system, _) in graph.systems.iter() { @@ -1087,9 +1178,10 @@ fn every_handler_queue_a_feed_takes_is_on_a_lane_or_listed() { continue; } let n = self::name(world, id); - let through_a_read = ends_with_any(&n, FILLED_THROUGH_A_READ); + let through_a_read = filled_through_a_read(&n).is_some(); let takes = if through_a_read { - access.has_resource_read(id) + // One the host holds too is every hosted feed's read: a host-held queue. + access.has_resource_read(id) && !host.has_resource_read(id) } else if is_messages(world, id) { // A reader, not a writer: the host's own messages are pushes. access.has_resource_read(id) @@ -1176,7 +1268,8 @@ fn every_handler_queue_a_feed_takes_is_on_a_lane_or_listed() { /// that pushes onto a lane off one pushes at the item's place, not its own: the field edges' /// `at`, and the aura watcher's calls'. A wrong entry lets a system that pushes at its own place, /// behind every packet of the frame, pass [`every_lane_push_off_a_handler_queue_keeps_its_place`]; -/// their readers that push are [`PLACED_OUTSIDE_THE_DISPATCH`]'s. +/// a reader that pushes after the dispatch fails +/// [`no_lane_push_off_a_placed_queue_follows_the_dispatch`]. fn placed_queues() -> [TypeId; 2] { [ TypeId::of::>(), @@ -1199,8 +1292,20 @@ const AT_THEIR_OWN_PLACE: &[(&str, &str)] = &[ ), ( "::ui_chat::channels::auto_join_zone_channels", - "world entry only arms the zone-channel walk, an engine turn that runs no Lua: its one \ - push is a walk's refusal into `UiErrorKeys`, which the action feed shows", + "world entry only arms the zone-channel walk, whose one push is a walk's refusal onto \ + the ui-error lane, made where the zone text's update walks, after the packets \ + (`0x401ece` → `0x494931`)", + ), + ( + "::player::controller::control", + "the mover's queue sends the root and unroot acks at its frame update (`0x616438`, \ + `0x6164a9`), and their input tick stops an auto-move there (`0x60e33d` → `0x60e347`)", + ), + ( + "::player::press::press_tick", + "the window deactivate runs the input tick outside every call (`0x514490` → \ + `0x5144b5`), its direction and pitch bits cleared (`0x5144a3`), whose pitch stop ends \ + the auto-move there (`0x60ddda` → `0x60e990`)", ), ( "::ui_chat::channels::end_session_channels_on_disconnect", @@ -1211,21 +1316,14 @@ const AT_THEIR_OWN_PLACE: &[(&str, &str)] = &[ /// The systems outside the phase that lend the call host and take a handler queue, firing off it /// in system order: remaining work, which only shrinks, by a suffix of the system's name. pub(super) const NOT_YET_PLACED: &[(&str, &str)] = &[( - "::ui_tradeskill::drain_trade_skill", - "the repeat craft's hook, which the reference runs inside the cast's go, its call to \ - `0x4fd7b0` (`0x6e81e7`), off the cast events", + "::ui_loot::drain_loot", + "the loot closes a precast end owes (`0x60d040` → `EndLootWindow` `0x48f200` at `0x60d10b`), \ + which the reference makes inside the packet that ends it: `HandleSpellGo` (`0x6e7fc5`), the \ + spell failures (`0x6e8dd7`, `0x6e8e8c`), the health watcher (`0x6047e7`) and \ + `OnMonsterMove` (`0x6020e8`); the unit edits owe them after the handler and the drain \ + closes them in its own phase, so `LOOT_CLOSED` fires behind the frame's packets", )]; -/// The systems that take a placed queue ([`placed_queues`]) after the dispatch and push onto a -/// lane, at the item's place or, from their commands, at their own, by a suffix of the system's -/// name: remaining work, which only shrinks. The order of those at the item's place holds today, -/// as the drain fires the whole frame by stamp after them; once -/// the dispatch fires each packet's lanes after its handlers, an item stamped at an earlier -/// packet and pushed after the dispatch fires behind every later packet's. The reference runs -/// each such consumer inside the update packet's notify pass (`0x465277` → `0x465330`), as -/// [`crate::field_callbacks`] runs the field edges' callbacks at the packet's end. -pub(super) const PLACED_OUTSIDE_THE_DISPATCH: &[(&str, &str)] = &[]; - /// The placed queues' readers that defer work to their commands and push nothing onto a lane /// from them, by a suffix of the system's name, with what the commands do. const DEFERS_NO_LANE_ITEM: &[(&str, &str)] = &[ @@ -1275,6 +1373,7 @@ fn lane_pushes_off_handler_queues() -> Option { } }; let placed: Vec = placed_queues().into_iter().filter_map(id).collect(); + let applied = applied_by_the_unit_edits(world); let graph = schedule.graph(); let mut pushes = BTreeSet::new(); let mut placed_pushes = BTreeSet::new(); @@ -1323,9 +1422,12 @@ fn lane_pushes_off_handler_queues() -> Option { continue; } let n = self::name(world, q); - // The host's own state is what a call touches, never a queue taken. - let takes = if ends_with_any(&n, FILLED_THROUGH_A_READ) { + // The host's own state is what a call touches, never a queue taken; what the + // unit edits owe is a queue whoever writes it takes, as no verb holds it. + let takes = if filled_through_a_read(&n).is_some() { access.has_resource_read(q) && !host.has_resource_read(q) + } else if applied.contains(&q) && !is_messages(world, q) { + access.has_resource_write(q) && !host.has_resource_write(q) } else if is_messages(world, q) { access.has_resource_read(q) && !access.has_resource_write(q) @@ -1393,12 +1495,15 @@ fn every_lane_push_off_a_handler_queue_keeps_its_place() { assert!(stale.is_empty(), "stale rows: {stale:?}"); } -/// Every system that takes a placed queue and pushes onto a lane outside the dispatch has its row -/// in [`PLACED_OUTSIDE_THE_DISPATCH`], found as -/// [`every_lane_push_off_a_handler_queue_keeps_its_place`] finds pushes, without its exemption -/// of the placed queues; a row whose system no longer does is stale. +/// No system takes a placed queue ([`placed_queues`]) after the dispatch and pushes onto a lane, +/// at the item's place or, from its commands, at its own, found as +/// [`every_lane_push_off_a_handler_queue_keeps_its_place`] finds pushes, without its exemption of +/// the placed queues: the dispatch fires each packet's lanes after its handlers, so an item +/// stamped at an earlier packet and pushed after the dispatch fires behind every later packet's. +/// The reference runs each such consumer inside the update packet's notify pass (`0x465277` → +/// `0x465330`), as [`crate::field_callbacks`] runs the field edges' callbacks at the packet's end. #[test] -fn every_lane_push_off_a_placed_queue_is_listed() { +fn no_lane_push_off_a_placed_queue_follows_the_dispatch() { let Some(LanePushes { mut placed, deferring, @@ -1420,27 +1525,38 @@ fn every_lane_push_off_a_placed_queue_is_listed() { .into_iter() .filter(|(system, _)| !ends_with_any(system, &quiet)), ); - let rows: Vec<&str> = PLACED_OUTSIDE_THE_DISPATCH - .iter() - .map(|(s, _)| *s) - .collect(); - let unlisted: Vec<&str> = placed - .iter() - .filter(|(system, _)| !ends_with_any(system, &rows)) - .map(|(_, line)| line.as_str()) - .collect(); + let lines: Vec<&str> = placed.iter().map(|(_, line)| line.as_str()).collect(); assert!( - unlisted.is_empty(), + lines.is_empty(), "these push onto a lane off a placed queue after the dispatch, or defer to commands that \ may: push from the handler's notify step instead, or give the system a row in \ - PLACED_OUTSIDE_THE_DISPATCH, or in DEFERS_NO_LANE_ITEM when its commands push none:\n {}", - unlisted.join("\n ") + DEFERS_NO_LANE_ITEM when its commands push none:\n {}", + lines.join("\n ") ); - let stale: Vec<&str> = rows +} + +/// Every exclusive firing declares its reads ([`super::LaneReads`]), and only an exclusive one: +/// Bevy reports an exclusive system's access as empty, and the drain's measured access +/// ([`super::Lanes::accesses`]) stands an exclusive firing's declared reads in for it. +#[test] +fn every_exclusive_firing_declares_its_reads() { + let app = headless_client(); + let lanes = app.world().resource::(); + let wrong: Vec = lanes + .names() .into_iter() - .filter(|s| !placed.iter().any(|(system, _)| system.ends_with(s))) + .zip(lanes.exclusive_reads()) + .filter_map( + |(lane, (exclusive, declared))| match (exclusive, declared) { + (true, false) => Some(format!("{lane:?} is exclusive and declares no reads")), + (false, true) => Some(format!( + "{lane:?} declares reads, but its firing is not exclusive" + )), + _ => None, + }, + ) .collect(); - assert!(stale.is_empty(), "stale rows: {stale:?}"); + assert!(wrong.is_empty(), "{}", wrong.join("\n")); } /// The drain is exclusive, so bevy lists its pairs with every system no declared order places @@ -1589,96 +1705,128 @@ pub(super) fn short_name(full: &str) -> String { } } +/// What the handlers write, as [`READS_FRAME_FINAL`] counts it: each component a handler writes, +/// and each resource one writes or fills through a shared reference ([`FILLED_THROUGH_A_READ`]), +/// whose access shows a read, so a feed that reads such a queue is held to it. +fn handler_written(world: &World) -> (BTreeSet, BTreeSet) { + use bevy::ecs::query::ComponentAccessKind; + let handlers = world.resource::(); + let mut components = BTreeSet::new(); + let mut resources = BTreeSet::new(); + for (_, access) in handlers.accesses() { + let access = access.combined_access(); + if let Ok(kinds) = access.try_iter_component_access() { + components.extend(kinds.filter_map(|k| match k { + ComponentAccessKind::Exclusive(id) => Some(id), + _ => None, + })); + } + resources.extend(access.resource_writes()); + resources.extend( + access + .resource_reads() + .filter(|id| filled_through_a_read(&name(world, *id)).is_some()), + ); + } + (components, resources) +} + /// Every view push that reads what a handler writes has its row, whose inputs are exactly the /// handler-written state it reads: each component a handler writes and each resource one writes, -/// past the VM, the message buffers and the lane queues. A feed's own reads are its declared -/// access less the call host's, entry by entry, as every feed that lends the host holds all of -/// the host's. +/// past the VM, the message buffers and the lane queues. A push is any system that writes the VM, +/// in any schedule and any set, the feeds of the `UiFeed` phase and those after the tick alike. +/// Its own reads are its declared access less the call host's, entry by entry, as every system +/// that lends the host holds all of the host's. #[test] fn every_view_push_of_what_a_handler_writes_is_listed() { - use bevy::ecs::query::{ComponentAccessKind, FilteredAccess}; - use bevy::ecs::schedule::NodeId; + use bevy::ecs::query::FilteredAccess; let mut app = headless_client(); - let (components, resources) = { - let handlers = app.world().resource::(); - let mut components = BTreeSet::new(); - let mut resources = BTreeSet::new(); - for (_, access) in handlers.accesses() { - let access = access.combined_access(); - if let Ok(kinds) = access.try_iter_component_access() { - components.extend(kinds.filter_map(|k| match k { - ComponentAccessKind::Exclusive(id) => Some(id), - _ => None, - })); - } - resources.extend(access.resource_writes()); - } - (components, resources) + let (components, resources) = handler_written(app.world()); + let host: Vec = { + use bevy::ecs::system::System; + let mut host = IntoSystem::into_system(|_: crate::script_calls::ScriptCallHost| {}); + System::initialize(&mut host, app.world_mut()) + .filtered_accesses() + .to_vec() }; - let (pushes, systems) = app.world_mut().schedule_scope(Update, |world, schedule| { - schedule.graph_mut().systems.initialize(world); - let vm = world - .components() - .get_resource_id(TypeId::of::()); - let host: Vec = { - use bevy::ecs::system::System; - let mut host = IntoSystem::into_system(|_: crate::script_calls::ScriptCallHost| {}); - System::initialize(&mut host, world) - .filtered_accesses() - .to_vec() - }; - let input = |id: ComponentId| { - let n = name(world, id); - (Some(id) != vm && !n.contains("Messages<")).then(|| short_name(&n)) - }; - let graph = schedule.graph(); - let mut pushes: HashMap> = HashMap::new(); - let mut systems = BTreeSet::new(); - for (key, system, _) in graph.systems.iter() { - let name = system.name().to_string(); - systems.insert(name.clone()); - if !in_feed(graph, NodeId::System(key)) || system.is_exclusive() { - continue; - } - let Some(with_access) = graph.systems.get(key) else { - continue; + let labels: Vec<_> = app + .world() + .resource::() + .iter() + .map(|(_, schedule)| schedule.label()) + .collect(); + let mut pushes: HashMap> = HashMap::new(); + let mut systems = BTreeSet::new(); + for label in labels { + app.world_mut().schedule_scope(label, |world, schedule| { + schedule.graph_mut().systems.initialize(world); + let vm = world + .components() + .get_resource_id(TypeId::of::()); + let input = |id: ComponentId| { + let n = name(world, id); + (Some(id) != vm && !n.contains("Messages<")).then(|| short_name(&n)) }; - if !vm.is_some_and(|vm| with_access.access.combined_access().has_resource_write(vm)) { - continue; - } - let mut own: Vec<&FilteredAccess> = - with_access.access.filtered_accesses().iter().collect(); - for h in &host { - if let Some(i) = own.iter().position(|o| *o == h) { - own.remove(i); + let graph = schedule.graph(); + for (key, system, _) in graph.systems.iter() { + let name = system.name().to_string(); + systems.insert(name.clone()); + if system.is_exclusive() { + continue; + } + let Some(with_access) = graph.systems.get(key) else { + continue; + }; + if !vm.is_some_and(|vm| with_access.access.combined_access().has_resource_write(vm)) + { + continue; + } + let mut own: Vec<&FilteredAccess> = + with_access.access.filtered_accesses().iter().collect(); + for h in &host { + if let Some(i) = own.iter().position(|o| *o == h) { + own.remove(i); + } + } + let mut inputs = BTreeSet::new(); + for access in own.iter().map(|o| o.access()) { + let read_c = components + .iter() + .filter(|&&id| access.has_component_read(id)); + let read_r = resources.iter().filter(|&&id| access.has_resource_read(id)); + inputs.extend(read_c.chain(read_r).filter_map(|&id| input(id))); + } + inputs.retain(|n| !QUEUES_NOT_VIEWS.contains(&n.as_str())); + if !inputs.is_empty() { + pushes.entry(short_name(&name)).or_default().extend(inputs); } } - let mut inputs = BTreeSet::new(); - for access in own.iter().map(|o| o.access()) { - let read_c = components - .iter() - .filter(|&&id| access.has_component_read(id)); - let read_r = resources.iter().filter(|&&id| access.has_resource_read(id)); - inputs.extend(read_c.chain(read_r).filter_map(|&id| input(id))); - } - inputs.retain(|n| !QUEUES_NOT_VIEWS.contains(&n.as_str())); - if !inputs.is_empty() { - pushes.insert(short_name(&name), inputs); - } - } - (pushes, systems) - }); + }); + } if !systems.iter().any(|n| n.contains("benilla_app::")) { eprintln!("skipped: this build carries no type names"); return; } let row = |system: &str| { + let built = BUILT_OUTSIDE_THE_PACKETS_IN_THE_REFERENCE + .iter() + .map(|(s, inputs, _)| (*s, *inputs)); READS_FRAME_FINAL .iter() + .copied() + .chain(built) .find(|(s, _)| format!("::{system}").ends_with(s)) }; + // A system [`NOT_YET_PLACED`] holds fires off a handler queue, which is its work. + let no_view = |system: &str| { + WRITES_NO_VIEW + .iter() + .chain(NOT_YET_PLACED) + .any(|(s, _)| format!("::{system}").ends_with(s)) + }; let mut wrong: Vec = pushes .iter() + .filter(|(system, _)| !no_view(system)) .filter(|(system, inputs)| { row(system).is_none_or(|(_, listed)| { listed @@ -1694,231 +1842,373 @@ fn every_view_push_of_what_a_handler_writes_is_listed() { }) .collect(); wrong.sort(); + let built = BUILT_OUTSIDE_THE_PACKETS_IN_THE_REFERENCE + .iter() + .map(|(s, inputs, _)| (*s, *inputs)); let stale: Vec<&str> = READS_FRAME_FINAL .iter() + .copied() + .chain(built) .filter(|(s, _)| { !pushes .keys() .any(|system| format!("::{system}").ends_with(s)) }) - .map(|(s, _)| *s) + .map(|(s, _)| s) + .chain(WRITES_NO_VIEW.iter().map(|(s, _)| *s).filter(|s| { + !pushes + .keys() + .any(|system| format!("::{system}").ends_with(s)) + })) .collect(); assert!( wrong.is_empty(), "these feeds push views off state a handler writes, read as the frame left it: version \ what they read through the views lane, or give each its row in READS_FRAME_FINAL as it \ - stands:\n {}", + stands, or in BUILT_OUTSIDE_THE_PACKETS_IN_THE_REFERENCE for a build the reference too \ + makes outside every packet, or in WRITES_NO_VIEW for a system that pushes no view:\n {}", wrong.join("\n ") ); assert!(stale.is_empty(), "stale rows: {stale:?}"); } -/// The lanes' own state that every firing of the drain reads as of its place, not as the frame left -/// it: the lane replays it packet by packet in stamp order among the others, so a firing between -/// two of its writes sees the first alone. A feed, which runs ahead of the drain, still reads it -/// as the frame left it, and its row says so. -const VERSIONED_FOR_THE_DRAIN: &[&str] = &["net::reputations::Reputations"]; - -/// The lane firings that read what a handler writes as the frame left it, by lane, beside -/// [`READS_FRAME_FINAL`]'s feeds: what a firing reads past the call host's own reads and its own -/// lane's queues ([`lane_queue_owners`]), the field watchers' callbacks among them (the notice lane's). A listener fired -/// there reads it as the frame's last packet left it, not as its own did (`0x537ae5`). The list -/// only shrinks: a read goes once a log versions it ([`crate::ui_unit::views`]), and a row that no -/// longer matches its firing fails. -#[rustfmt::skip] -pub(super) const LANE_READS_FRAME_FINAL: &[(&str, &[&str])] = &[ - // A packet's firing rebuilds the world map's landmarks and the readout's rows off the states, - // the gossip marker, our explored bits and the defense channel as the frame left them. - ("world states", &["net::ObjectStore", "poi_marker::PoiMarker", "ui_chat::edit::ChannelState", - "world_state::WorldStates"]), - // The chat setup's restore reads the channel rows its shortcuts and auto-joins come from as - // the frame left them, past the notices of the packets after the section's. - ("chat setup arrivals", &["ui_chat::edit::ChannelState"]), - // Our arrival's legs read and reset what later packets of its frame write, as the frame left - // it: the book the replay learns, the battlefield and stone it resets and asks again for, the - // death stores its death state reads and its corpse ask resets, the class family it sets, and - // the connection the clock resync asks through. - ("arrival", &["death::DeathNet", "net::NetStatus", "spell::mods::SpellModifiers", - "ui_action::PlayerActions", "ui_battlefield::Battlefield", - "ui_dialog_verbs::MeetingStone"]), - // The watchers' callbacks: the quest log's slots, the skill line's race and class and the - // bonus bar's form off our live descriptor, as the frame left them (#2217); the aura - // watcher's own store is the one its packet left, and the buff timers read the duration - // packet's stamps through the call host. The drunk line's name is read through the host. - // `SetPetGuid`'s trainer refresh reads the open trainer, and its `PET_UI_CLOSE` the new - // pet's object and ours, as the frame left them. - ("field notices", &["net::GuidIndex", "net::ObjectStore", "ui_trainer::TrainerOpen"]), - // The views lane reads the stores, records and roster cells it rewinds as of each packet, and - // the reputations as the reputation lane replays them; the names, the relations' stores, the - // selection and the guild as the frame left them (#2217). - // The roster's cells and records it rewinds and seats while it builds; the rest as the frame - // left it. - ("unit views", &["names::NameCache", "net::GuidIndex", "net::ObjectStore", "net::SelfGuid", - "target::Selection", "ui_guild::GuildState", "ui_party::GroupState"]), - // A landing's record expands its text's macros against the player's name and the world states - // as the frame left them, as the quest log's feed expands the held ones (#2217). - ("quest events", &["names::NameCache", "net::ObjectStore", "world_state::WorldStates"]), - ("cast reports", &["items::Countdowns", "items::Items", "net::GuidIndex", "net::ObjectStore", - "ui_action::cast_lines::CastFailRedisplays"]), - ("item watchers", &["items::Countdowns", "items::Items", "names::NameCache", "net::GuidIndex", - "net::ObjectStore", "ui_trade::TradeSession"]), - ("auction house", &["items::Items", "names::NameCache", "net::SelfGuid", - "ui_auction::AuctionOpen"]), - // The sweep's party and raid test (`0x4c2030`, `0x4c203d`), the pushes' owners and their - // names, the source's object and the records a copier and a push read, as the frame left them - // (#2217); the getters read the window each step's packet left through the host. - ("loot", &["items::Countdowns", "items::Items", "names::NameCache", "net::GuidIndex", - "net::ObjectStore", "ui_loot::AutoLootByte", "ui_loot::LootLatch", - "ui_loot::LootMoveStart", "ui_party::GroupState"]), - // The reader's open reads the object, its records and the text caches as the frame left them, - // past the answers still on its lane; its register closes whichever latched window holds the - // latch, reading that window's state as the frame left it. - ("item text", &["go_templates::GameObjectTemplates", "items::Countdowns", "items::Items", - "net::GuidIndex", "net::ObjectStore", "ui_auction::AuctionOpen", "ui_bank::BankOpen", - "ui_gossip::GossipState", "ui_item_text::ItemTextOpen", "ui_item_text::PageTexts", - "ui_mail::MailOpen", "ui_merchant::MerchantOpen", "ui_petition::GuildRegistrarState", - "ui_quest::QuestGiver", "ui_session::latch::InteractLatch", "ui_stable::StableOpen", - "ui_tabard::TabardOpen", "ui_taxi::TaxiState", "ui_trade::TradeSession", - "ui_trainer::TrainerOpen"]), - // A list's copy reads the stable, the creature cache and the pet as the frame left them; its - // listeners read the stable through the host (#2217). - ("stable", &["items::Countdowns", "names::NameCache", "net::GuidIndex", "net::ObjectStore", - "ui_pet::PetBar", "ui_stable::StableOpen"]), - // A list's and a pass's push read the books, the caches, the player and the window as the - // frame left them (#2217). - ("trainer", &["items::Items", "names::NameCache", "net::GuidIndex", "net::HomeBind", - "net::ObjectStore", "spell::mods::SpellModifiers", "ui_action::PlayerActions", - "ui_pet::PetBar", "ui_trainer::TrainerOpen"]), - // The open leg's placement reads the session, the objects and the records as the frame left - // them, past the statuses still on its lane (`0x4bf5f1`); its getters read through the host. - ("trade", &["items::Countdowns", "items::Items", "net::GuidIndex", "net::ObjectStore", - "ui_trade::TradeSession"]), - // A close's tail parked behind the lane reads the deferred refresh at its place (`0x4acda8`), - // past an arrival's arm by a later packet of the frame (`0x4ad642`). - ("mail", &["ui_mail::pending::MailPending"]), - ("chat", &["go_templates::GameObjectTemplates", "items::Items", "names::NameCache", - "net::GuidIndex", "net::ObjectStore", "net::SelfGuid", "ui_chat::edit::ChannelState", - "world_state::WorldStates"]), -]; - -/// Every lane firing's read of what a handler writes is listed in [`LANE_READS_FRAME_FINAL`], -/// found as [`every_view_push_of_what_a_handler_writes_is_listed`] finds a feed's; an exclusive -/// firing, which shows Bevy no access, by the reads it declares ([`super::LaneReads`]), and every -/// exclusive firing declares them. +/// The CVar mirror's two syncs are [`WRITES_NO_VIEW`]'s, not [`READS_FRAME_FINAL`]'s, on these +/// facts. The reference's `GetCVar` reads the one record (`0x488bd1`, `0x488bf9`) that `CVar::Set` +/// writes, running its callback inside the writer (`0x63df7d`). Here no handler holds the +/// registry but through the call host, whose appliers sync the VM's mirror inside the call that +/// writes it ([`crate::cvars::CvarSteps`]), and every other system of the frame that writes it +/// runs ahead of the input pass's sync or after the dispatch, so that sync carries the write in +/// before the next packet: a listener inside a packet reads every write made before it. A handler +/// that writes the registry itself, or a writer between the input sync and the dispatch, fails +/// here. The other schedules run outside `Update`, and an exclusive system shows no access. #[test] -fn every_lane_reads_of_what_a_handler_writes_is_listed() { - use bevy::ecs::query::{ComponentAccessKind, FilteredAccess}; +fn every_cvar_write_reaches_the_mirror_before_a_packet() { + use bevy::ecs::query::{FilteredAccess, FilteredAccessSet}; + use bevy::ecs::schedule::SystemKey; + use bevy::ecs::system::System; + use std::collections::HashSet; let mut app = headless_client(); - let (components, resources) = { - let handlers = app.world().resource::(); - let mut components = BTreeSet::new(); - let mut resources = BTreeSet::new(); - for (_, access) in handlers.accesses() { - let access = access.combined_access(); - if let Ok(kinds) = access.try_iter_component_access() { - components.extend(kinds.filter_map(|k| match k { - ComponentAccessKind::Exclusive(id) => Some(id), - _ => None, - })); - } - resources.extend(access.resource_writes()); - } - (components, resources) - }; - let world = app.world_mut(); - let vm = world - .components() - .get_resource_id(TypeId::of::()); - let host: Vec = { - use bevy::ecs::system::System; + let host = { let mut host = IntoSystem::into_system(|_: crate::script_calls::ScriptCallHost| {}); - System::initialize(&mut host, world) - .filtered_accesses() - .to_vec() + System::initialize(&mut host, app.world_mut()) }; - if !name(world, vm.expect("the VM's resource")).contains("benilla_ui") { - eprintln!("skipped: this build carries no type names"); - return; - } - let owners = lane_queue_owners(); - assert_eq!( - owners.map(|(_, t)| t).into_iter().collect::>(), - lane_types().into_iter().collect::>(), - "every lane queue has its owning lane" - ); - let lane_queues: Vec<(&str, String)> = owners - .iter() - .filter_map(|(lane, t)| Some((*lane, world.components().get_resource_id(*t)?))) - .map(|(lane, id)| (lane, short_name(&name(world, id)))) - .collect(); - let lanes = world.resource::(); - let mut found: Vec<(&str, BTreeSet)> = Vec::new(); - let mut undeclared = Vec::new(); - let firings = lanes - .names() - .into_iter() - .zip(lanes.accesses()) - .zip(lanes.exclusive_reads()); - for ((lane, access), (exclusive, declared)) in firings { - // An exclusive firing shows Bevy no access: the access its declared reads measure stands - // in ([`super::measure`]). - match (exclusive, declared) { - (true, false) => { - undeclared.push(format!("{lane:?} is exclusive and declares no reads")); - continue; - } - (false, true) => undeclared.push(format!( - "{lane:?} declares reads, but its firing is not exclusive" - )), - _ => {} - } + let registry = app + .world() + .components() + .get_resource_id(TypeId::of::()) + .expect("the client registers the CVar registry"); + // A write of the registry past the host a system lends, entry by entry, as one that lends the + // host holds all of the host's. + let past_the_host = |access: &FilteredAccessSet| { + let mut with_host = access.clone(); + with_host.extend(host.clone()); let mut own: Vec<&FilteredAccess> = access.filtered_accesses().iter().collect(); - // A firing that lends the host shows the host's access beside its own; an exclusive - // firing's declared reads are its own alone. - for h in host.iter().filter(|_| !exclusive) { - if let Some(i) = own.iter().position(|o| *o == h) { - own.remove(i); - } - } - let mut inputs = BTreeSet::new(); - for access in own.iter().map(|o| o.access()) { - let read_c = components - .iter() - .filter(|&&id| access.has_component_read(id)); - let read_r = resources.iter().filter(|&&id| access.has_resource_read(id)); - for &id in read_c.chain(read_r) { - let n = name(world, id); - if Some(id) != vm && !n.contains("Messages<") { - inputs.insert(short_name(&n)); + if with_host.combined_access() == access.combined_access() { + for h in host.filtered_accesses() { + if let Some(i) = own.iter().position(|o| *o == h) { + own.remove(i); } } } - inputs.retain(|n| { - !QUEUES_NOT_VIEWS.contains(&n.as_str()) - && !VERSIONED_FOR_THE_DRAIN.contains(&n.as_str()) - && !lane_queues.iter().any(|(l, q)| *l == lane && q == n) - }); - found.push((lane, inputs)); - } - assert!(undeclared.is_empty(), "{}", undeclared.join("\n")); - let wrong: Vec = found + own.iter().any(|o| o.access().has_resource_write(registry)) + }; + let handlers = app.world().resource::(); + // The control: the handlers that lend the host hold the registry through it. + assert!( + handlers + .accesses() + .iter() + .any(|(_, a)| a.combined_access().has_resource_write(registry)), + "no handler reaches the registry, even through the host: the scan below reads nothing" + ); + let handlers: Vec<&str> = handlers + .accesses() .iter() - .filter(|(lane, inputs)| { - let listed = LANE_READS_FRAME_FINAL.iter().find(|(l, _)| l == lane); - let listed: BTreeSet = listed - .map(|(_, i)| i.iter().map(|s| s.to_string()).collect()) - .unwrap_or_default(); - listed != *inputs - }) - .map(|(lane, inputs)| { - let inputs: Vec = inputs.iter().map(|i| format!("{i:?}")).collect(); - format!("({lane:?}, &[{}]),", inputs.join(", ")) - }) + .filter(|(_, a)| past_the_host(a)) + .map(|(n, _)| *n) .collect(); assert!( - wrong.is_empty(), - "these lanes' firings read state a handler writes as the frame left it: version it, or \ - give each its row in LANE_READS_FRAME_FINAL as it stands:\n {}", - wrong.join("\n ") + handlers.is_empty(), + "these handlers write the CVar registry past the call host, so a listener in the packet \ + reads the VM's mirror as the last sync left it: write it through the host, whose \ + appliers sync the mirror inside the write:\n {}", + handlers.join("\n ") + ); + let systems: Vec<(SystemKey, FilteredAccessSet)> = + app.world_mut().schedule_scope(Update, |world, schedule| { + schedule.graph_mut().systems.initialize(world); + let graph = schedule.graph(); + graph + .systems + .iter() + .filter(|(_, system, _)| !system.is_exclusive()) + .filter_map(|(k, _, _)| Some((k, graph.systems.get(k)?.access.clone()))) + .filter(|(_, access)| past_the_host(access)) + .collect() + }); + let c = census(&mut app, Update, SyncPoints::Declared); + if !type_names_available(&c) { + eprintln!("skipped: this build carries no type names"); + return; + } + let one = |suffix: &str| { + let mut hits = c.systems.iter().filter(|(_, s)| s.name.ends_with(suffix)); + match (hits.next(), hits.next()) { + (Some((k, _)), None) => *k, + _ => panic!("exactly one system named `…{suffix}` in Update"), + } + }; + let (sync, dispatch) = ( + one("::cvars::sync_input_cvars"), + one("::net::apply::apply_net_updates"), + ); + let mut prev: HashMap> = HashMap::new(); + for (a, b) in &c.dependencies { + prev.entry(*b).or_default().push(*a); + } + let ahead_of = |start: SystemKey| { + let mut seen = HashSet::new(); + let mut stack = vec![start]; + while let Some(n) = stack.pop() { + for m in prev.get(&n).into_iter().flatten() { + if seen.insert(*m) { + stack.push(*m); + } + } + } + seen + }; + // The control: the tip cursor's write at the world entry, a plain one after the dispatch. + assert!( + systems + .iter() + .any(|(k, _)| c.name(*k).ends_with("::game_tip::drive_game_tip")), + "the scan no longer sees `drive_game_tip`'s write of the registry" + ); + let before_sync = ahead_of(sync); + let between: Vec<&str> = systems + .iter() + .filter(|(k, _)| *k != sync && !before_sync.contains(k)) + .filter(|(k, _)| !ahead_of(*k).contains(&dispatch)) + .map(|(k, _)| c.name(*k)) + .collect(); + assert!( + between.is_empty(), + "these write the CVar registry outside any call and may run between the input pass's \ + sync and the dispatch, so the frame's packets read the VM's mirror without the write: \ + order each ahead of `sync_input_cvars` or after the dispatch:\n {}", + between.join("\n ") ); } + +/// The calls that queue an event on the VM's own lane for its next tick +/// ([`crate::ui_script::fire_scan::host_queue_writers`]), by a suffix of the calling function's +/// `path::fn` and the method it calls, with why. The tick fires that lane after the drain, behind +/// every packet's events, whichever system or lane the call ran in, so no call is exempt; where +/// the reference signals the event in place, inside the packet or the input that caused it, the +/// row is remaining work. A new call fails until it has its row, and a row whose call is gone +/// fails as stale. +pub(super) const QUEUED_FOR_THE_TICK: &[(&str, &str, &str)] = &[ + ( + "capture/fixtures.rs::seed_ui_fixture", + "set_world_map_explored", + "a capture's fixture, dev tooling outside any session: no packet raises it", + ), + ( + "ui_world_map.rs::feed_world_map", + "sync_world_map_to_player_zone", + "the first world enter's selection, queued for the next tick (the module's deviation), \ + where the zone updater selects (`0x4947ac` → `0x4a6650` → `0x4a67a0`) and signals in \ + place (`0x4a6ce4`)", + ), + ( + "ui_world_map.rs::install_world_loc_projector", + "set_world_loc_projector", + "installs benilla's own projection at a VM's first frame, whose first landmark list \ + queues `WORLD_MAP_UPDATE`; no reference fact, as the reference projects inside \ + `0x4a67a0`", + ), +]; + +/// Every call that queues an event on the VM's lane for its next tick has its row in +/// [`QUEUED_FOR_THE_TICK`], so a feed that raises off state it compares cannot hide behind the +/// tick. +#[test] +fn every_call_that_queues_for_the_tick_is_listed() { + let writers = crate::ui_script::fire_scan::host_queue_writers(); + let row = |w: &crate::ui_script::fire_scan::QueueWriter| { + QUEUED_FOR_THE_TICK + .iter() + .find(|(f, m, _)| w.writer.ends_with(&format!("/{f}")) && w.method == *m) + }; + let unlisted: Vec = writers + .iter() + .filter(|w| row(w).is_none()) + .map(|w| format!("{} calls {} at {}", w.writer, w.method, w.at)) + .collect(); + assert!( + unlisted.is_empty(), + "these queue an event for the VM's next tick, behind every packet's: signal it in place, \ + or give the call its row in QUEUED_FOR_THE_TICK:\n {}", + unlisted.join("\n ") + ); + let stale: Vec = QUEUED_FOR_THE_TICK + .iter() + .filter(|(f, m, _)| { + !writers + .iter() + .any(|w| w.writer.ends_with(&format!("/{f}")) && w.method == *m) + }) + .map(|(f, m, _)| format!("{f} {m}")) + .collect(); + assert!(stale.is_empty(), "stale rows: {stale:?}"); + let empty: Vec<&str> = QUEUED_FOR_THE_TICK + .iter() + .filter(|(_, _, why)| why.is_empty()) + .map(|(f, _, _)| *f) + .collect(); + assert!(empty.is_empty(), "rows with no reason: {empty:?}"); +} + +/// Each entry of the raise check's allow list ([`crate::ui_script::raise_origin::RAISES_AT_THEIR_OWN_PLACE`]) +/// names a function that exists and gives its reason; one that cites a guard list has that list's +/// row for it; and every call that queues for the tick has its entry, as each raises at its own +/// place in the frame. +#[test] +fn every_raise_origin_allowed_names_its_function_and_its_row() { + use crate::ui_script::raise_origin::{RAISES_AT_THEIR_OWN_PLACE, ROW_LISTS}; + let src = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src"); + let module = |file: &str| file.trim_end_matches(".rs").replace('/', "::"); + let queued: BTreeSet = QUEUED_FOR_THE_TICK + .iter() + .map(|(f, _, _)| { + let (file, func) = f.split_once("::").expect("a `file::fn` row"); + format!("{}::{func}", module(file)) + }) + .collect(); + let mut wrong = Vec::new(); + for a in RAISES_AT_THEIR_OWN_PLACE { + let (path, func) = a.frame.rsplit_once("::").expect("a `module::fn` frame"); + let dir = path.replace("::", "/"); + let found = [format!("{dir}.rs"), format!("{dir}/mod.rs")] + .iter() + .filter_map(|f| std::fs::read_to_string(src.join(f)).ok()) + .any(|code| { + code.contains(&format!("fn {func}(")) || code.contains(&format!("fn {func}<")) + }); + if !found { + wrong.push(format!("{}: no such function", a.frame)); + } + if a.why.trim().is_empty() { + wrong.push(format!("{}: no reason", a.frame)); + } + let Some((list, _)) = a.why.split_once(':').filter(|(l, _)| ROW_LISTS.contains(l)) else { + continue; + }; + let suffix = format!("::{}", a.frame); + let named = a.why.split('`').nth(1).filter(|n| n.starts_with("::")); + let has_row = match list { + "QUEUED_FOR_THE_TICK" => queued.contains(a.frame), + "AT_THEIR_OWN_PLACE" => AT_THEIR_OWN_PLACE.iter().any(|(s, _)| s.ends_with(&suffix)), + "NOT_YET_ON_A_LANE" => NOT_YET_ON_A_LANE + .iter() + .any(|(_, s, _)| named.map_or(s.ends_with(&suffix), |n| *s == n)), + _ => false, + }; + if !has_row { + wrong.push(format!("{}: {list} has no row for it", a.frame)); + } + } + for q in &queued { + if !RAISES_AT_THEIR_OWN_PLACE.iter().any(|a| a.frame == q) { + wrong.push(format!("{q}: queues for the tick and has no allow entry")); + } + } + assert!(wrong.is_empty(), "{}", wrong.join("\n")); +} + +/// The keys of `keys` named more than once, as `": "`. +pub(super) fn named_twice(list: &str, keys: impl IntoIterator) -> Vec { + let mut seen = BTreeSet::new(); + keys.into_iter() + .filter(|k| !seen.insert(k.clone())) + .map(|k| format!("{list}: {k}")) + .collect() +} + +/// No guard list names an entry twice and no row lists an input twice, as a stale check passes on +/// one copy while the other stays; and a system that writes the VM has one place among the lists +/// that classify it. +#[test] +fn no_guard_list_names_an_entry_twice() { + let keyed = |list: &[(&str, &str)]| list.iter().map(|(s, _)| s.to_string()).collect::>(); + let mut twice = Vec::new(); + twice.extend(named_twice( + "NOT_YET_ON_A_LANE", + NOT_YET_ON_A_LANE + .iter() + .map(|(row, s, _)| format!("{row:?} {s}")), + )); + for (list, names) in [ + ("HOST_HELD_UNREAD", HOST_HELD_UNREAD), + ("READ_ONLY_TO_HANDLERS", READ_ONLY_TO_HANDLERS), + ("QUEUES_NOT_VIEWS", QUEUES_NOT_VIEWS), + ] { + twice.extend(named_twice(list, names.iter().map(|s| s.to_string()))); + } + twice.extend(named_twice( + "FILLED_THROUGH_A_READ", + FILLED_THROUGH_A_READ.iter().map(|(s, _)| s.to_string()), + )); + for (list, rows) in [ + ("WRITES_NO_VIEW", WRITES_NO_VIEW), + ("AT_THEIR_OWN_PLACE", AT_THEIR_OWN_PLACE), + ("NOT_YET_PLACED", NOT_YET_PLACED), + ("DEFERS_NO_LANE_ITEM", DEFERS_NO_LANE_ITEM), + ] { + twice.extend(named_twice(list, keyed(rows))); + } + twice.extend(named_twice( + "READS_FRAME_FINAL", + READS_FRAME_FINAL.iter().map(|(s, _)| s.to_string()), + )); + for (s, inputs) in READS_FRAME_FINAL { + twice.extend(named_twice( + &format!("READS_FRAME_FINAL {s}"), + inputs.iter().map(|i| i.to_string()), + )); + } + twice.extend(named_twice( + "BUILT_OUTSIDE_THE_PACKETS_IN_THE_REFERENCE", + BUILT_OUTSIDE_THE_PACKETS_IN_THE_REFERENCE + .iter() + .map(|(s, _, _)| s.to_string()), + )); + for (s, inputs, _) in BUILT_OUTSIDE_THE_PACKETS_IN_THE_REFERENCE { + twice.extend(named_twice( + &format!("BUILT_OUTSIDE_THE_PACKETS_IN_THE_REFERENCE {s}"), + inputs.iter().map(|i| i.to_string()), + )); + } + twice.extend(named_twice( + "QUEUED_FOR_THE_TICK", + QUEUED_FOR_THE_TICK + .iter() + .map(|(site, call, _)| format!("{site} {call}")), + )); + // One place for a VM writer among the lists that classify it. + twice.extend(named_twice( + "the view lists", + READS_FRAME_FINAL + .iter() + .map(|(s, _)| s.to_string()) + .chain( + BUILT_OUTSIDE_THE_PACKETS_IN_THE_REFERENCE + .iter() + .map(|(s, _, _)| s.to_string()), + ) + .chain(keyed(WRITES_NO_VIEW)) + .chain(keyed(NOT_YET_PLACED)), + )); + assert!(twice.is_empty(), "named twice:\n {}", twice.join("\n ")); +} diff --git a/crates/benilla-app/src/lanes/guild_live_tests.rs b/crates/benilla-app/src/lanes/guild_live_tests.rs index 3457f45dd..7a2e795ec 100644 --- a/crates/benilla-app/src/lanes/guild_live_tests.rs +++ b/crates/benilla-app/src/lanes/guild_live_tests.rs @@ -560,3 +560,36 @@ fn last_online_answers_with_no_player_and_the_row_does_not() { ); assert_eq!(got, ["1", "1", "5", "12", "nil"]); } + +/// Each roster listener reads its own message's roster, and the friends the packets ahead of it +/// left: a friend list between the two rosters, which `GetNumFriends` reads at the call +/// (`0x5ad000`), counts none for the first and Ann for the second. +#[test] +fn each_roster_listener_reads_its_own_span() { + let on = guild_presence::ONLINE; + let mut c = named(); + let ann = super::unit_view_tests::one_friend(&mut c.app); + c.eval::<()>( + false, + r#"local g = CreateFrame("Frame") + g:RegisterEvent("GUILD_ROSTER_UPDATE") + g:SetScript("OnEvent", function() table.insert(Seen, "friends " .. GetNumFriends()) end)"#, + ); + c.frame(vec![ + vec![roster("one", vec![member(1, "Alder", 1, on)])], + vec![ann], + vec![roster( + "two", + vec![member(1, "Alder", 1, on), member(2, "Birch", 2, on)], + )], + ]); + assert_eq!( + c.seen(), + [ + "GUILD_ROSTER_UPDATE:nil:nil:1:Alder:one:Master", + "friends 0", + "GUILD_ROSTER_UPDATE:nil:nil:2:Birch:two:Master", + "friends 1", + ] + ); +} diff --git a/crates/benilla-app/src/lanes/host_read_tests.rs b/crates/benilla-app/src/lanes/host_read_tests.rs index a02fccad2..c62c1ecb7 100644 --- a/crates/benilla-app/src/lanes/host_read_tests.rs +++ b/crates/benilla-app/src/lanes/host_read_tests.rs @@ -1,29 +1,32 @@ -//! The readiness guard for firing each packet's lanes inside the net dispatch, after its handlers, -//! with the host lent: the reference's handler signals inside itself (`0x703e50`) and runs whole -//! before the next packet's (`0x537ae5`), so a listener reads the live state its packet left and -//! its sends go out in packet order. That move is right once five lists are empty, each the whole -//! of its remaining work and only shrinking; [`flip_readiness`] prints where they stand. +//! What a listener inside the net dispatch still reads or hears out of its packet's place. The +//! dispatch fires each packet's lanes after its handlers, with the host lent +//! ([`crate::lanes::flush`]), as the reference's handler signals inside itself (`0x703e50`) and +//! runs whole before the next packet's (`0x537ae5`), so a listener reads the live state its +//! packet left and its sends go out in packet order. Four lists hold what is left, each the whole +//! of its remaining work and only shrinking; [`what_the_flip_left`] prints where they stand. //! -//! - [`super::guard_tests::READS_FRAME_FINAL`], held here to its count: the feeds that push a -//! view of what a handler writes, which a getter reads in place of the live state. A family's -//! getters going live ([`crate::script_calls::live`]) drops its feed's row. +//! - [`super::guard_tests::READS_FRAME_FINAL`], held here to its count: the systems, in any +//! schedule or set, that push a view of what a handler writes, which a getter reads in place of +//! the live state, so a listener reads the push the last frame left. A family's getters going +//! live ([`crate::script_calls::live`]) drops its feed's row; a build the reference too makes +//! outside every packet is +//! [`super::guard_tests::BUILT_OUTSIDE_THE_PACKETS_IN_THE_REFERENCE`]'s, and a system that +//! writes the VM and pushes no view is [`super::guard_tests::WRITES_NO_VIEW`]'s; both stay. //! - [`BETWEEN_THE_DISPATCH_AND_THE_DRAIN`]: the systems after the dispatch and ahead of the drain -//! that write what the host's live reads read, or push a view the drain waits for, where the -//! reference writes inside a packet. A listener fired inside the dispatch would read each as the -//! frame before left it. The writers the reference too runs after the packets, and those no -//! listener can see, are [`AFTER_THE_PACKETS_IN_THE_REFERENCE`]'s, which stays. +//! that write what a call or a handler reads inside a packet (the host's live reads, the rest of +//! the call host's state, what the lanes' firings touch, and what the handlers read without +//! writing), where the reference +//! writes inside a packet: a listener reads each as the frame before left it. The writers the +//! reference too runs after the packets, and those no listener can see, are +//! [`AFTER_THE_PACKETS_IN_THE_REFERENCE`]'s, which stays. //! - [`super::guard_tests::NOT_YET_ON_A_LANE`]: what fires off a handler's queue or edge from a -//! feed, ahead of every lane. Once the lanes fire inside the dispatch, each such event moves -//! from ahead of every packet event of its frame to behind them all. +//! feed, behind every packet event of its frame. //! - [`super::guard_tests::NOT_YET_PLACED`]: the systems outside the phase that fire off a //! handler queue in system order. -//! - [`super::guard_tests::PLACED_OUTSIDE_THE_DISPATCH`]: the systems that push lane items off a -//! placed queue's field edges after the dispatch, at the edge's earlier stamp, which the -//! dispatch's own firing would already have passed, or at their own. //! -//! [`super::guard_tests::LANE_READS_FRAME_FINAL`] empties at the flip itself, which makes the -//! world a lane firing reads its packet's, and every entry of -//! [`super::guard_tests::HOST_HELD_UNREAD`] is read first, as quiet or as a row of its own. +//! Every entry of [`super::guard_tests::HOST_HELD_UNREAD`] is read first, as quiet or as a row of +//! its own. [`super::guard_tests::QUEUED_FOR_THE_TICK`] holds the calls that queue an event for +//! the VM's next tick, which fires behind every packet's events. use std::any::TypeId; use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; @@ -37,79 +40,63 @@ 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 = 34; -const FRAME_FINAL_INPUTS: usize = 181; +const FRAME_FINAL_FEEDS: usize = 2; +const FRAME_FINAL_INPUTS: usize = 15; /// 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 host's live -/// reads ([`crate::script_calls::live::LiveReads`]), by its name in the crate, and why: the -/// obstacles to the flip, each a write the reference makes inside a packet, or a view pushed in -/// its place. A listener fired inside the dispatch would read each of these as the frame before -/// left it. The writers the reference also runs after the packets are -/// [`AFTER_THE_PACKETS_IN_THE_REFERENCE`]'s, not these. `UiScript` -/// names a view the drain waits for ([`crate::ui_unit::field_events::FieldEventPushes`]); -/// `Commands` names a component a system filters out and may add with its commands, which -/// access does not show; `exclusive` a system whose access Bevy does not report. +/// (`fire_in_order`), by a suffix of the system's name, with what each writes of the state a +/// listener's call or a handler reads inside a packet, by its name in the crate, and why: the +/// host's live reads ([`crate::script_calls::live::LiveReads`]), the rest of the call host's +/// state, which its verbs read, what each lane's firing touches as it fires ([`super::LaneReads`]), +/// and what the handlers read without writing +/// ([`super::guard_tests::READ_ONLY_TO_HANDLERS`]), the lanes and the message buffers apart; a +/// read of what the handlers fill through a shared reference +/// ([`super::guard_tests::FILLED_THROUGH_A_READ`]) counts as the write it is. Each is a write +/// the reference makes inside a packet, or a view pushed in its place, which a listener fired +/// inside the dispatch reads as the frame before left it. The writers the reference also runs after the packets are +/// [`AFTER_THE_PACKETS_IN_THE_REFERENCE`]'s, not these. `Commands` names a component a system +/// filters out and may add with its commands, which access does not show; `exclusive` a system +/// whose access Bevy does not report. #[rustfmt::skip] const BETWEEN_THE_DISPATCH_AND_THE_DRAIN: &[(&str, &[&str], &str)] = &[ - ("::net::motion::remote::extrapolate_remote_units", &["Transform"], + ("::net::motion::remote::extrapolate_remote_units", &["Commands net::motion::spline::Spline", + "Transform", "net::motion::remote::RemoteMotion"], "the arrival snap `0x7c6420` (`0x618dfc`) is written inside the packet"), - ("::spell::group_relation::publish_group_roster", &["spell::group_relation::GroupRoster"], - "copies the group's roster, which the relation reads take, once the packets are in"), - ("::transport::compose_riders", &["Transform"], + ("::transport::compose_riders", &["Transform", "net::motion::remote::RemoteMotion"], "the arrival snap `0x7c6420` (`0x618dfc`) is written inside the packet"), - ("::ui_action::feed::feed_actions", &["ui_action::PlayerActions"], - "clears the bar's re-resolve flag; the known spells the book and the talents read are \ - the learn handlers' alone"), - ("::ui_action::state::feed_action_state", &["spell::cooldowns::Cooldowns", - "ui_action::state::ActionStateMemory"], - "keeps the frame's `GetTime` clock the cooldown reads map each start through, and \ - writes the list as it walks the slots"), - ("::ui_action::unlearn::clear_unlearned_slots", &["ui_action::PlayerActions"], - "drains the unlearned spells the bar clears; the known spells are the handlers' alone"), - ("::ui_char::feed_char", &["UiScript"], "a field event's listeners read its push"), - ("::ui_instance::track_instance_state", &["ui_instance::InstanceState"], - "latches the dungeon just left once the map the transfer lands on is known, which the \ - reference latches inside the map load and the packet (`0x464ff0`, `0x49e6ac`)"), - ("::ui_macro::rebind_macro_spells", &["ui_action::PlayerActions"], - "drains the superseded ranks the bar's macros take; the known spells are the handlers' \ - alone"), - ("::ui_party::feed::feed_party", &["UiScript"], "a field event's listeners read its push"), - ("::ui_pet::unit::feed_pet_unit", &["UiScript"], "a field event's listeners read its push"), - ("::ui_session::close_npc_session_out_of_range", - &["ui_binder::BinderState"], - "closes the bind question once the player leaves service range, which \ - `CheckBinderDist` reports; the reference tests the range at the call (`0x5dff50`)"), - ("::ui_session::close_npc_session_out_of_range", - &["ui_dialog_verbs::PetUnlearnState"], - "closes the unlearn question once the player leaves service range, which \ - `CheckPetUntrainerDist` reports; the reference tests the range at the call (`0x5dfd30`)"), - ("::ui_session::close_npc_session_out_of_range", - &["ui_talent_wipe::TalentWipeState"], - "closes the respec question once the player leaves service range, which \ - `CheckTalentMasterDist` reports; the reference tests the range at the call (`0x5df980`)"), - ("::ui_tooltip::spell_feed::feed_spell_tooltips", &["items::Items"], - "writes the item cache as it builds the spell tooltips"), - ("::ui_unit::feed_units", &["UiScript"], "a field event's listeners read its push"), + ("::ui_item_text::apply_reads", &["ui_item_text::ItemTextOpen"], + "a click's or a bag use's read, queued in its input or its call, which the reference \ + opens inside them (`0x5f58c0`, `0x4e32e0`), ahead of the packets (`0x420d23`)"), ]; /// The systems between the dispatch and the drain that write what the host's live reads read, /// as [`BETWEEN_THE_DISPATCH_AND_THE_DRAIN`]'s, but where the reference too runs them after the -/// packets, or where no listener can read them: they stay after the flip, and a listener fired -/// inside the dispatch reads them as the frame before left them, as 1.12.1's does. Same shape, +/// packets, or where no listener can read them: they stay, and a listener fired inside the +/// dispatch reads them as the frame before left them, as 1.12.1's does. Same shape, /// held to its systems' access by the same test. #[rustfmt::skip] const AFTER_THE_PACKETS_IN_THE_REFERENCE: &[(&str, &[&str], &str)] = &[ - ("::net::motion::facing::drive_display_facing", &["Transform"], + ("::net::motion::facing::drive_display_facing", &["Commands net::motion::remote::RemoteMotion", + "Commands net::motion::spline::Spline", "Transform"], "turns the units' models toward their facing; unit movement is \ frame time, which the reference runs after the packets (`0x420d63` after `0x420d55`)"), ("::net::motion::spline::ground_clamp_creatures", &["Transform"], "settles the creatures on the ground; unit movement is \ frame time, which the reference runs after the packets (`0x420d63` after `0x420d55`)"), - ("::net::motion::spline::sample_splines", &["Transform"], + ("::net::motion::remote::drain_pending_moves", &["Commands net::motion::spline::Spline", + "net::motion::remote::RemoteMotion"], + "fires the relayed moves queued past their arrival in the movement tick (event 5's \ + `0x616800` → `0x615b10` → `0x616620` → `0x615c30`), frame time, which the reference \ + runs after the packets (`0x420d63` after `0x420d55`)"), + ("::net::game_time::tick_game_time", &["net::game_time::ServerTime"], + "steps the game clock by the frame time, the category 5 handler `0x401ec0` → `0x6c5d50` \ + → `0x6435a0`, which the reference runs after the packets (`0x420d63` after \ + `0x420d55`)"), + ("::net::motion::spline::sample_splines", &["Commands net::motion::spline::Spline", + "Transform"], "moves the units along their splines; unit movement is \ frame time, which the reference runs after the packets (`0x420d63` after `0x420d55`)"), - ("::transport::ground_deck_riders", &["Transform"], + ("::transport::ground_deck_riders", &["Transform", "net::motion::remote::RemoteMotion"], "settles the riders on their decks; unit movement is \ frame time, which the reference runs after the packets (`0x420d63` after `0x420d55`)"), ("::transport::tick_transports", &["Transform"], @@ -123,12 +110,23 @@ const AFTER_THE_PACKETS_IN_THE_REFERENCE: &[(&str, &[&str], &str)] = &[ &["ui_pet::PetBar"], "drops the pet's cooldown log, run only while no in-game interface \ is up, so no listener exists; it goes with the log"), + ("::ui_cast::views::drop_cast_views", &["ui_cast::views::CastViews"], + "drops the cast views' log, run only while no in-game interface \ + is up, so no listener exists; it goes with the log"), + ("::ui_chat::language::load_language_words", &["ui_chat::language::ChatLanguages"], + "loads `LanguageWords.dbc` once, the first frame the install is open, ahead of every \ + world packet, as the reference loads it at startup (`StaticDBLoadAll` `0x53f8b0` → \ + `0x548990`, from `ClientDBInitialize` `0x53f4f0`): no listener reads the pools before \ + it"), ("::ui_mail::step_pending_mail", &["ui_mail::pending::MailPending"], "steps the pending-mail time in the world frame's update (its slot `0x38`, `0x4818d0` → \ `0x4ade60`), which the frame pass runs after the packets (`0x420d6a` after `0x420d55`)"), ("::ui_loot::drop_loot_steps", &["ui_loot::LootState"], "drops the loot lane's window signals, its pushes kept, run only while no in-game \ interface is up, so no listener exists"), + ("::ui_loot_roll::lane::drop_roll_events", &["ui_loot_roll::LootRolls"], + "drops the rolls' lane, run only while no in-game interface is up, so no listener \ + exists"), ("::ui_mail::lane::drop_mail_events", &["ui_mail::pending::MailPending"], "drops the mail lane, a parked close's tail with its query kept, run only while no \ in-game interface is up, so no listener exists"), @@ -138,11 +136,25 @@ const AFTER_THE_PACKETS_IN_THE_REFERENCE: &[(&str, &[&str], &str)] = &[ ("::ui_unit::views::drop_unit_views", &["ui_unit::views::UnitViews"], "drops the unit views' log, run only while no in-game interface \ is up, so no listener exists; it goes with the log"), + ("::net::send_query_time", &["net::QueryTimeAsks"], + "the clock's hourly resync, which writes only its own asks' bookkeeping, seated by the \ + world-enter cascade's ask (`0x4de45b`): no listener reads it"), + ("::poi_marker::expire_marker", &["poi_marker::PoiMarker"], + "clears the directions marker on arrival or at its deadline in the minimap's per-frame \ + update (`0x6d93a0`, its clears at `0x6d93fb` and `0x6d9a3a`), which the minimap frame's \ + draw runs (`0x4ebea0` → `0x4ec950`) in the frame pass, after the packets (`0x420d6a` \ + after `0x420d55`)"), + ("::ui_battlefield::drive_battlefield_leash", &["ui_battlefield::BattlefieldLeash"], + "the list's leash (`0x4aa090`), polled in the world frame's update (`0x4818d5`), which \ + the frame pass runs after the packets (`0x420d6a` after `0x420d55`)"), + ("::ui_chat::language::feed_default_language", &["ui_chat::frames::ChatWindows"], + "copies the faction tongue into the log files' composition (`route`'s tee), which no \ + listener reads: the stock `ChatFrame_OnEvent` holds its own `this.defaultLanguage`"), ]; /// The systems [`BETWEEN_THE_DISPATCH_AND_THE_DRAIN`] and [`AFTER_THE_PACKETS_IN_THE_REFERENCE`] -/// hold to, with what each writes of the host's live reads, by suffix; see the first's doc for the -/// kinds. +/// hold to, with what each writes of the state a call or a handler reads, by suffix; see the +/// first's doc for that state and the kinds. fn writers_between(app: &mut App) -> Option>> { let world = app.world_mut(); use bevy::ecs::system::System; @@ -157,6 +169,81 @@ fn writers_between(app: &mut App) -> Option>> .to_vec(); let mut read_resources = HashSet::new(); let mut read_components = HashSet::new(); + // What a listener inside the dispatch reads past the live families: every resource and + // component a call's verbs touch through the host, and what the handlers read without writing + // ([`super::guard_tests::READ_ONLY_TO_HANDLERS`]), each a read made inside a packet in the + // reference, and what the handlers fill through a shared reference, which a system writes + // through `&self`. The lanes and the message buffers are not state. + crate::net::handlers::measure(world); + let queues: HashSet = super::guard_tests::lane_types() + .into_iter() + .filter_map(|t| world.components().get_resource_id(t)) + .collect(); + let is_state = |world: &World, id: ComponentId| { + !queues.contains(&id) && !super::guard_tests::is_messages(world, id) + }; + // What the handlers and the host fill through a shared reference: a system's read of one is + // a write, which its access shows as a read. + let through_a_read = |world: &World, id: ComponentId| { + super::guard_tests::filled_through_a_read(&super::guard_tests::name(world, id)).is_some() + }; + let handlers = world.resource::(); + let mut handler_reads = HashSet::new(); + for (_, access) in handlers.accesses() { + let access = access.combined_access(); + handler_reads.extend( + access + .resource_reads() + .filter(|id| !access.has_resource_write(*id)), + ); + } + read_resources.extend(handler_reads.into_iter().filter(|id| is_state(world, *id))); + for fa in &host { + read_resources.extend( + fa.access() + .resource_reads_and_writes() + .filter(|id| is_state(world, *id)), + ); + if let Ok(kinds) = fa.access().try_iter_component_access() { + read_components.extend(kinds.map(|k| match k { + ComponentAccessKind::Archetypal(id) + | ComponentAccessKind::Shared(id) + | ComponentAccessKind::Exclusive(id) => id, + })); + } + } + // What each lane's firing touches as it fires, inside its packet in the reference: its + // declared access ([`super::LaneReads`] for an exclusive one), less the call host's it lends, + // counted above. + super::measure(world); + let lanes: Vec> = world + .resource::() + .accesses() + .into_iter() + .map(|set| set.filtered_accesses().to_vec()) + .collect(); + for set in &lanes { + let mut own: Vec<&FilteredAccess> = set.iter().collect(); + for h in &host { + if let Some(i) = own.iter().position(|o| *o == h) { + own.remove(i); + } + } + for fa in own { + read_resources.extend( + fa.access() + .resource_reads_and_writes() + .filter(|id| is_state(world, *id)), + ); + if let Ok(kinds) = fa.access().try_iter_component_access() { + read_components.extend(kinds.map(|k| match k { + ComponentAccessKind::Archetypal(id) + | ComponentAccessKind::Shared(id) + | ComponentAccessKind::Exclusive(id) => id, + })); + } + } + } for fa in &live { read_resources.extend(fa.access().resource_reads_and_writes()); if let Ok(kinds) = fa.access().try_iter_component_access() { @@ -237,9 +324,6 @@ fn writers_between(app: &mut App) -> Option>> if *exclusive { writes.insert("exclusive".to_string()); } - if info.sets.iter().any(|s| s == "FieldEventPushes") { - writes.insert("UiScript".to_string()); - } let mut own: Vec<&FilteredAccess> = access.iter().collect(); // A system that lends the host holds the host's access beside its own. if c.hosted.contains(k) { @@ -253,6 +337,7 @@ fn writers_between(app: &mut App) -> Option>> let a = fa.access(); writes.extend( a.resource_writes() + .chain(a.resource_reads().filter(|id| through_a_read(world, *id))) .filter(|id| read_resources.contains(id) && Some(*id) != vm) .map(name), ); @@ -295,9 +380,9 @@ fn rows_between( .chain(AFTER_THE_PACKETS_IN_THE_REFERENCE) } -/// Every system between the dispatch and the drain that writes what the host's live reads read -/// has its row, in one of the two lists, as it stands, and a row whose system no longer does is -/// stale. +/// Every system between the dispatch and the drain that writes what a call or a handler reads has +/// its row, in one of the two lists, as it stands, and a row whose system no longer does is stale: +/// a feed that rewrites once a frame what a listener's call reads inside its packet cannot hide. #[test] fn every_writer_between_the_dispatch_and_the_drain_is_listed() { let mut app = crate::game_plugins::schedule_tests::headless_client(); @@ -342,7 +427,7 @@ fn every_writer_between_the_dispatch_and_the_drain_is_listed() { .collect(); assert!( wrong.is_empty(), - "these run between the dispatch and the drain and write what the host's live reads read: \ + "these run between the dispatch and the drain and write what a call or a handler reads: \ move the write into its handler, or give each its row as it stands: in \ AFTER_THE_PACKETS_IN_THE_REFERENCE when the reference too writes it after the packets, \ else in BETWEEN_THE_DISPATCH_AND_THE_DRAIN:\n {}", @@ -370,14 +455,14 @@ fn the_frame_final_views_only_shrink() { ); } -/// Where the flip stands: every list's count, printed, failing nothing (`cargo test -/// flip_readiness -- --nocapture`). The flip needs the first five empty; the rest are context. +/// What the flip left: every list's count, printed, failing nothing (`cargo test +/// what_the_flip_left -- --nocapture`). The first four are the remaining work; the rest are +/// context. #[test] -fn flip_readiness() { +fn what_the_flip_left() { use super::guard_tests as g; let inputs: usize = g::READS_FRAME_FINAL.iter().map(|(_, i)| i.len()).sum(); - let lane_inputs: usize = g::LANE_READS_FRAME_FINAL.iter().map(|(_, i)| i.len()).sum(); - let needs = [ + let left = [ ( "READS_FRAME_FINAL", g::READS_FRAME_FINAL.len(), @@ -394,32 +479,37 @@ fn flip_readiness() { String::new(), ), ("NOT_YET_PLACED", g::NOT_YET_PLACED.len(), String::new()), - ( - "PLACED_OUTSIDE_THE_DISPATCH", - g::PLACED_OUTSIDE_THE_DISPATCH.len(), - String::new(), - ), ]; let context = [ ( - "HOST_HELD_UNREAD (to read; a quiet entry stays)", + "HOST_HELD_UNREAD (read, each quiet; stays)", g::HOST_HELD_UNREAD.len(), String::new(), ), - ( - "LANE_READS_FRAME_FINAL (empties at the flip)", - g::LANE_READS_FRAME_FINAL.len(), - format!(" ({lane_inputs} inputs)"), - ), ( "AFTER_THE_PACKETS_IN_THE_REFERENCE (stays)", AFTER_THE_PACKETS_IN_THE_REFERENCE.len(), String::new(), ), + ( + "BUILT_OUTSIDE_THE_PACKETS_IN_THE_REFERENCE (stays)", + g::BUILT_OUTSIDE_THE_PACKETS_IN_THE_REFERENCE.len(), + String::new(), + ), + ( + "WRITES_NO_VIEW (stays)", + g::WRITES_NO_VIEW.len(), + String::new(), + ), + ( + "QUEUED_FOR_THE_TICK (behind every packet)", + g::QUEUED_FOR_THE_TICK.len(), + String::new(), + ), ]; - let left: usize = needs.iter().map(|(_, n, _)| n).sum(); - let mut out = format!("flip readiness: {left} rows to empty\n"); - for (list, n, extra) in &needs { + let rows: usize = left.iter().map(|(_, n, _)| n).sum(); + let mut out = format!("after the flip: {rows} rows to empty\n"); + for (list, n, extra) in &left { out += &format!(" {n:>4} {list}{extra}\n"); } out += " context:\n"; @@ -428,3 +518,32 @@ fn flip_readiness() { } eprint!("{out}"); } + +/// No list here names a system twice, and no row lists an input twice. +#[test] +fn no_host_read_list_names_an_entry_twice() { + use super::guard_tests::named_twice; + let mut twice = Vec::new(); + for (list, rows) in [ + ( + "BETWEEN_THE_DISPATCH_AND_THE_DRAIN", + BETWEEN_THE_DISPATCH_AND_THE_DRAIN, + ), + ( + "AFTER_THE_PACKETS_IN_THE_REFERENCE", + AFTER_THE_PACKETS_IN_THE_REFERENCE, + ), + ] { + twice.extend(named_twice( + list, + rows.iter().map(|(s, _, _)| s.to_string()), + )); + for (s, inputs, _) in rows { + twice.extend(named_twice( + &format!("{list} {s}"), + inputs.iter().map(|i| i.to_string()), + )); + } + } + assert!(twice.is_empty(), "named twice:\n {}", twice.join("\n ")); +} diff --git a/crates/benilla-app/src/lanes/instance_live_tests.rs b/crates/benilla-app/src/lanes/instance_live_tests.rs new file mode 100644 index 000000000..9b1968686 --- /dev/null +++ b/crates/benilla-app/src/lanes/instance_live_tests.rs @@ -0,0 +1,105 @@ +//! The dungeon latch `CanShowResetInstances` reads (`0x495c90`), written where the reference +//! writes it: a world transfer's timer (`0x401bc0`, posted by `SMSG_NEW_WORLD` `0x401b00`) makes +//! the new object manager (`0x401c22`), whose creation latches the map left (`0x464ff0` → +//! `0x46500e` → `0x495d10`), at the next tick's start ahead of its packets. + +use benilla_protocol::SessionEvent; +use bevy::prelude::*; + +use super::unit_view_tests::client; + +/// Deadmines, a party dungeon, and the Eastern Kingdoms. +const DEADMINES: u32 = 36; +const AZEROTH: u32 = 0; + +fn port(map_id: u32, needs_ack: bool) -> SessionEvent { + SessionEvent::Worldport { + map_id, + position: [0.0; 3], + orientation: 0.0, + needs_ack, + } +} + +fn can_reset(app: &mut App) -> bool { + crate::script_calls::with_hosted_vm(app.world_mut(), |s| { + s.expect("a VM") + .eval::>("return CanShowResetInstances()") + .expect("runs") + }) == Some(1.0) +} + +/// A port out of a dungeon latches it at the port's load, the timer's manager leg, so a listener +/// of the next tick's packets reads the offer; the port's own frame, before its timer, does not. +#[test] +fn the_dungeon_latch_is_written_at_the_ports_load() { + let mut app = client(); + app.insert_resource(benilla_assets::MapCatalogRes( + benilla_formats::MapCatalog::from_rows([ + (AZEROTH, "Azeroth", 0), + (DEADMINES, "DeadminesInstance", 0), + ]) + .with_instance_types([(DEADMINES, 1)]), + )); + let world = app.world_mut(); + // In the dungeon, bound: the login's world load runs in place. + crate::net::handlers::dispatch( + world, + vec![ + port(DEADMINES, false), + SessionEvent::UpdateInstanceOwnership { owns: true }, + ], + ); + assert!(!can_reset(&mut app), "standing in the dungeon"); + // Out: the port posts its load, and its own frame still stands in the dungeon. + crate::net::handlers::dispatch(app.world_mut(), vec![port(AZEROTH, true)]); + assert!(!can_reset(&mut app), "the port's frame, ahead of its timer"); + app.world_mut().run_schedule(PreUpdate); + assert!( + can_reset(&mut app), + "the next tick's start made the new manager" + ); +} + +/// The world entry with the pick's map: `ClientInitializeGame` makes the manager for the +/// character list's map (`0x4015f3`), so a character logged out inside a dungeon and seated at its +/// exit by `SMSG_LOGIN_VERIFY_WORLD`, another map, has left it (`0x401e36`-`0x401ea4`). +#[test] +fn a_login_inside_a_dungeon_latches_it_at_the_world_entry() { + let mut app = client(); + app.insert_resource(benilla_assets::MapCatalogRes( + benilla_formats::MapCatalog::from_rows([ + (AZEROTH, "Azeroth", 0), + (DEADMINES, "DeadminesInstance", 0), + ]) + .with_instance_types([(DEADMINES, 1)]), + )); + const ME: u64 = 0x7; + let row = benilla_protocol::Character { + map: DEADMINES, + ..crate::glue_session::roster::test_character(ME, "Me") + }; + app.insert_resource(crate::glue_session::roster::Roster::with_pending_pick( + vec![row], + ME, + )); + crate::net::handlers::dispatch( + app.world_mut(), + vec![ + SessionEvent::Connected { + self_guid: ME, + name: "Me".into(), + billing: Default::default(), + tutorial_flags: None, + addon_info: None, + }, + SessionEvent::UpdateInstanceOwnership { owns: true }, + ], + ); + assert!( + !can_reset(&mut app), + "the world entry stands in the dungeon" + ); + crate::net::handlers::dispatch(app.world_mut(), vec![port(AZEROTH, false)]); + assert!(can_reset(&mut app), "seated at its exit, another map"); +} diff --git a/crates/benilla-app/src/lanes/item_live_tests.rs b/crates/benilla-app/src/lanes/item_live_tests.rs index 2ec4ad627..829d4d9f3 100644 --- a/crates/benilla-app/src/lanes/item_live_tests.rs +++ b/crates/benilla-app/src/lanes/item_live_tests.rs @@ -480,15 +480,19 @@ fn client(window: Window) -> Client { /// Wherever the frame's snapshots are current, every item getter answers the same off the cache /// and the objects as off the snapshot, across the bags, the bank, the worn slots, the trade and /// the mail: the fields the snapshots hold are the ones the live read derives -/// ([`crate::ui_items::live::LiveItem`]). The inspected slots have no snapshot pushed, and read +/// ([`crate::ui_items::live::LiveItem`]). The worn slots have no snapshot pushed in game, and the +/// test seats one ([`crate::ui_char::seat_doll_once`]). The inspected slots have none, and read /// the visible block live ([`crate::ui_inspect::InspectLive`]); nor have the bags, the trade or /// the mail ([`crate::ui_trade::TradeLive`], [`crate::ui_mail::MailLive`]), which read nothing off /// the VM alone. #[test] fn every_item_getter_answers_the_same_live_as_off_the_snapshot() { let mut c = client(Window::Trade); + // The doll's copy, which no feed pushes in game, seated for the host-less answer. + crate::ui_char::seat_doll_once(c.app.world_mut()); let (mut snapshot, mut live) = (c.answers(false), c.answers(true)); let mut c = client(Window::Mail); + crate::ui_char::seat_doll_once(c.app.world_mut()); snapshot.extend(c.answers(false)); live.extend(c.answers(true)); // The fixture shows what it means to on every surface. diff --git a/crates/benilla-app/src/lanes/item_tests.rs b/crates/benilla-app/src/lanes/item_tests.rs index 29dcebb23..ea63c3a80 100644 --- a/crates/benilla-app/src/lanes/item_tests.rs +++ b/crates/benilla-app/src/lanes/item_tests.rs @@ -65,6 +65,10 @@ fn item(guid: u64, entry: u32) -> SessionEvent { /// with `arg1`. fn client() -> App { let mut app = crate::game_plugins::schedule_tests::headless_client_unrun(); + // In the world with the interface up, so the dispatch fires each packet's lanes. + app.insert_resource(bevy::prelude::State::new( + crate::client_state::ClientState::InWorld, + )); let world = app.world_mut(); let seat = |n: u16, guid: u64| { let lo = FIELD_PLAYER_INV_SLOT_HEAD + 2 * n; @@ -90,6 +94,9 @@ fn client() -> App { .resource_mut::() .insert_template(entry, Some(crate::items::test_template(name))); } + for (action, entry) in [(3, HELM_ID), (5, POTION)] { + crate::ui_action::hold_for_test(world, action, ACTION_KIND_ITEM, entry); + } let mut script = UiScript::new().unwrap(); for (action, entry) in [(3, HELM_ID), (5, POTION)] { script.set_action( @@ -406,6 +413,7 @@ fn a_held_copier_ends_inside_its_packet_before_a_later_close() { fn linen_on_the_bar() -> App { let mut app = client(); let world = app.world_mut(); + crate::ui_action::hold_for_test(world, 7, ACTION_KIND_ITEM, LINEN); let mut script = world.non_send_resource_mut::(); script.set_unit_guids(&benilla_ui::script::UnitGuids { player: ME, diff --git a/crates/benilla-app/src/lanes/item_text_live_tests.rs b/crates/benilla-app/src/lanes/item_text_live_tests.rs new file mode 100644 index 000000000..6bc6bb58c --- /dev/null +++ b/crates/benilla-app/src/lanes/item_text_live_tests.rs @@ -0,0 +1,432 @@ +//! The reader's getters as a listener reads them, and its events at their packets. The getters read +//! the reader's cells and its object at the call (`0x4e38f0`-`0x4e3b10`); the open signals +//! `ITEM_TEXT_BEGIN` and the show `ITEM_TEXT_READY` inside the packet that runs them (the object's +//! page text `0x5f88c0`, a record's or a name's answer through `0x4e3280` or `0x4e32b0`), a page +//! turn inside its call, and a close a later packet makes waits behind what the lane still holds. + +use benilla_protocol::SessionEvent; +use benilla_ui::script::UiScript; +use bevy::prelude::*; + +use super::unit_view_tests::{client, fall, frame, values}; + +/// A fall's `UNIT_COMBAT`, as [`client`]'s spy records it. +const FELL: &str = "UNIT_COMBAT:player:100"; +/// "The Lay of Ameth'Aran", entry 17188, a GOOBER whose first page is 358. +const TABLET: u64 = 0xF110_0043_2400_0001; +/// A second tablet of the same template. +const OTHER_TABLET: u64 = 0xF110_0043_2400_0002; +const BANKER: u64 = 0xF130_0000_0B1E_0001; +const ME: u64 = 0x7; + +/// The tablets streamed, their template's first page 358 cached with 359 after it. +fn tablets(app: &mut App) { + let mut data = [0i32; 24]; + data[7] = 358; + let world = app.world_mut(); + world + .resource_mut::() + .insert(17188, 10, "The Lay of Ameth'Aran".into(), &data); + world + .resource_mut::() + .insert(358, "Page one.".into(), 359); + for guid in [TABLET, OTHER_TABLET] { + crate::items::test_spawn_object( + world, + guid, + crate::go_templates::test_typed_fields(17188, 10), + ); + } +} + +/// A spy on the reader's events and `extra`, each recorded by name; `ITEM_TEXT_READY` with the +/// text, the creator and the page its getters read as it fires, and with `close_on_hide` the +/// stock frame's `ITEM_TEXT_CLOSED` → `HideUIPanel` → OnHide → `CloseItemText()` +/// (`ItemTextFrame.lua:92`, `ItemTextFrame.xml:349`). +fn spy(app: &mut App, extra: &[&str], close_on_hide: bool) { + let list: Vec = ["ITEM_TEXT_BEGIN", "ITEM_TEXT_READY", "ITEM_TEXT_CLOSED"] + .iter() + .chain(extra) + .map(|e| format!("{e:?}")) + .collect(); + app.world_mut() + .non_send_resource_mut::() + .run(&format!( + r#" + local close = {close_on_hide} + local f = CreateFrame("Frame") + for _, e in ipairs({{{}}}) do f:RegisterEvent(e) end + f:SetScript("OnEvent", function() + if event == "ITEM_TEXT_READY" then + table.insert(Seen, event .. ":" .. ItemTextGetText() .. "/" + .. tostring(ItemTextGetCreator()) .. "/" .. ItemTextGetPage()) + else + table.insert(Seen, event) + end + if close and event == "ITEM_TEXT_CLOSED" then CloseItemText() end + end) + "#, + list.join(", ") + )) + .unwrap(); +} + +/// `chunk`'s answer through the lent host when `live`, else off the VM's copy alone. +fn eval(app: &mut App, live: bool, chunk: &str) -> T { + if live { + crate::script_calls::with_hosted_vm(app.world_mut(), |s| { + s.expect("a VM").eval::(chunk).expect("runs") + }) + } else { + crate::script_calls::eval_in_vm(app.world(), chunk) + } +} + +/// The reader as its getters read it. +const READ: &str = "return tostring(ItemTextGetItem()) .. '/' .. ItemTextGetText() .. '/' \ + .. ItemTextGetPage() .. '/' .. tostring(ItemTextHasNextPage())"; + +fn page_text(guid: u64) -> SessionEvent { + SessionEvent::GameObjectPageText { guid } +} + +fn reader(app: &App) -> Option { + app.world() + .resource::() + .object() +} + +/// The object's page text runs its open and its show inside its handler (`0x5f8915` → +/// `0x4e32e0`, `0x4e359b` → `0x4e35b0`): with no frame after it, the getters read the object's +/// name, the page the show wrote (`0xbc3fe8`), its number and the next page it stored +/// (`0x4e3723`), through the host; the VM's copy, which nothing pushes, holds none. +#[test] +fn the_reader_getters_read_the_session_at_the_call() { + let mut app = client(); + tablets(&mut app); + crate::net::handlers::dispatch(app.world_mut(), vec![page_text(TABLET)]); + assert_eq!( + eval::(&mut app, true, READ), + "The Lay of Ameth'Aran/Page one./1/1" + ); + assert_eq!(eval::(&mut app, false, READ), "nil//1/nil"); +} + +/// The open's `ITEM_TEXT_BEGIN` and the show's `ITEM_TEXT_READY` fire at the page text's place +/// between a fall's `UNIT_COMBAT` on each side, the show's listener reading its page. +#[test] +fn the_readers_events_fire_between_neighbouring_packets_events() { + let mut app = client(); + tablets(&mut app); + spy(&mut app, &[], false); + let seen = frame(&mut app, vec![fall(5), page_text(TABLET), fall(5)]); + assert_eq!( + seen, + [ + FELL, + "ITEM_TEXT_BEGIN", + "ITEM_TEXT_READY:Page one./nil/1", + FELL + ] + ); +} + +/// A tablet's page text, then a bank's open in the same frame: the bank's register closes the +/// reader first (`0x4930d0` → `0x493310` → `0x4e32e0(0, 0)`), so its `ITEM_TEXT_CLOSED` fires +/// ahead of `BANKFRAME_OPENED`, and the frame leaves the bank latched, the reader shut. +#[test] +fn a_one_frame_open_then_close_leaves_no_stale_state() { + let mut app = client(); + tablets(&mut app); + crate::items::test_spawn_object( + app.world_mut(), + BANKER, + benilla_protocol::ObjectFields::from_pairs(&[(2, 0x9)]), + ); + spy(&mut app, &["BANKFRAME_OPENED"], true); + let seen = frame( + &mut app, + vec![page_text(TABLET), SessionEvent::ShowBank { banker: BANKER }], + ); + let events: Vec<&str> = seen.iter().map(|e| e.split(':').next().unwrap()).collect(); + assert_eq!( + events, + [ + "ITEM_TEXT_BEGIN", + "ITEM_TEXT_READY", + "ITEM_TEXT_CLOSED", + "BANKFRAME_OPENED" + ] + ); + assert_eq!(reader(&app), None); + assert_eq!( + app.world() + .resource::() + .guid(), + Some(BANKER) + ); + assert_eq!( + app.world().resource::().banker, + Some(BANKER) + ); +} + +/// The close a later packet made fires behind the lane, while a third packet has opened another +/// tablet: the stock OnHide's `CloseItemText()` inside it closes the read it was signalled for, +/// already shut, and leaves the newer one open. +#[test] +fn a_parked_closes_nested_close_spares_the_newer_read() { + let mut app = client(); + tablets(&mut app); + crate::items::test_spawn_object( + app.world_mut(), + BANKER, + benilla_protocol::ObjectFields::from_pairs(&[(2, 0x9)]), + ); + spy(&mut app, &["BANKFRAME_OPENED", "BANKFRAME_CLOSED"], true); + let seen = frame( + &mut app, + vec![ + page_text(TABLET), + SessionEvent::ShowBank { banker: BANKER }, + page_text(OTHER_TABLET), + ], + ); + assert_eq!( + seen, + [ + "ITEM_TEXT_BEGIN", + "ITEM_TEXT_READY:Page one./nil/1", + "ITEM_TEXT_CLOSED", + "BANKFRAME_OPENED", + "BANKFRAME_CLOSED", + "ITEM_TEXT_BEGIN", + "ITEM_TEXT_READY:Page one./nil/1", + ] + ); + assert_eq!(reader(&app), Some(OTHER_TABLET)); + assert_eq!( + app.world() + .resource::() + .guid(), + Some(OTHER_TABLET) + ); +} + +/// `ItemTextNextPage()` moves to page 359 and shows it inside its call (`0x4e38b0` → +/// `0x4e35b0`), which finds it uncached and asks with the callback `0x4e3280` (`0x4e36ab`); the +/// page's answer shows it at its place, its listener reading page 2. +#[test] +fn a_turn_to_a_page_answered_later_shows_at_the_answer() { + let mut app = client(); + tablets(&mut app); + spy(&mut app, &[], false); + frame(&mut app, vec![page_text(TABLET)]); + let (tx, rx) = crossbeam_channel::unbounded(); + app.insert_resource(crate::net::NetCommands(tx)); + eval::<()>(&mut app, true, "ItemTextNextPage()"); + let asked: Vec = rx + .try_iter() + .filter_map(|c| match c { + crate::net::ClientCommand::PageTextQuery { page_id, .. } => Some(page_id), + _ => None, + }) + .collect(); + assert_eq!(asked, [359], "the show asks the page inside the call"); + assert!(eval::>(&mut app, false, "local s = Seen Seen = {} return s").is_empty()); + let page = SessionEvent::PageText { + page_id: 359, + text: "Page two.".into(), + next_page_id: 0, + }; + let seen = frame(&mut app, vec![fall(5), page, fall(5)]); + assert_eq!(seen, [FELL, "ITEM_TEXT_READY:Page two./nil/2", FELL]); +} + +/// A letter whose author the name cache lacks: its show signals `ITEM_TEXT_READY` with no creator, +/// whose `ItemTextGetCreator()` asks the name with the callback `0x4e32b0` (`0x4e39b9`); the +/// name's answer shows the letter again at its place, now with its author. A refusal shows +/// nothing. +#[test] +fn a_letters_missing_author_shows_at_the_names_answer() { + const LETTER: u64 = 0x4000_0000_0000_0009; + const AUTHOR: u64 = 0x42; + let mut app = client(); + let world = app.world_mut(); + world + .resource_mut::() + .insert_template(5_000, Some(crate::items::test_template("Letter"))); + world + .resource_mut::() + .bodies + .insert(77, "Dear you.".into()); + crate::items::test_spawn_item( + world, + LETTER, + benilla_protocol::ObjectFields::from_pairs(&[ + (2, 0x3), + (3, 5_000), + (8, ME as u32), + (10, AUTHOR as u32), + (11, 0), + ]), + false, + ); + spy(&mut app, &[], false); + let (tx, rx) = crossbeam_channel::unbounded(); + app.insert_resource(crate::net::NetCommands(tx)); + let names = |rx: &crossbeam_channel::Receiver| { + rx.try_iter() + .filter(|c| matches!(c, crate::net::ClientCommand::NameQuery { guid: AUTHOR })) + .count() + }; + crate::ui_item_text::read_letter_now(app.world_mut(), LETTER, 77); + assert_eq!( + eval::>(&mut app, false, "local s = Seen Seen = {} return s"), + ["ITEM_TEXT_BEGIN", "ITEM_TEXT_READY:Dear you./nil/1"] + ); + assert_eq!(names(&rx), 1, "the getter asks the author"); + let name = |name: &str| SessionEvent::PlayerName { + guid: AUTHOR, + name: name.into(), + race: 1, + gender: 0, + class: 1, + }; + let seen = frame(&mut app, vec![fall(5), name("Brisca"), fall(5)]); + assert_eq!(seen, [FELL, "ITEM_TEXT_READY:Dear you./Brisca/1", FELL]); + assert_eq!(names(&rx), 0); + // A second lookup that misses, then a refusal: nothing shows. + app.world_mut() + .resource_mut::() + .invalidate_player(AUTHOR); + assert!(eval::( + &mut app, + true, + "return ItemTextGetCreator() == nil" + )); + assert_eq!(names(&rx), 1); + assert!(frame(&mut app, vec![name("")]).is_empty()); +} + +/// A TEXT object read before its template lands keeps the reader's cell with no page to read +/// (`0x5f5900` reads 0, `0x4e341d`); the template's answer runs its handler's record callback, +/// which opens the reader again (`0x5f59d0` → `0x5f5a17`), so the book begins and shows at the +/// answer's place. +#[test] +fn a_text_objects_book_read_before_its_template_opens_when_it_lands() { + const PLAQUE: u64 = 0xF110_0000_4321_0001; + let mut app = client(); + let world = app.world_mut(); + world + .resource_mut::() + .insert(358, "Page one.".into(), 0); + crate::items::test_spawn_object( + world, + PLAQUE, + crate::go_templates::test_typed_fields(4321, 9), + ); + spy(&mut app, &[], false); + crate::ui_item_text::read_now(app.world_mut(), PLAQUE); + assert_eq!(reader(&app), Some(PLAQUE), "the cell stays with no page"); + assert!(frame(&mut app, vec![]).is_empty()); + let mut data = [0i32; 24]; + data[0] = 358; + let template = SessionEvent::GameObjectInfo { + entry: 4321, + type_id: 9, + display_id: 0, + name: "Plaque".into(), + data, + }; + let seen = frame(&mut app, vec![fall(5), template, fall(5)]); + assert_eq!( + seen, + [ + FELL, + "ITEM_TEXT_BEGIN", + "ITEM_TEXT_READY:Page one./nil/1", + FELL + ] + ); +} + +/// The reader's answers read the record their packet filed: each kind's cache handler runs ahead +/// of the reader's, whatever the plugin order, as the reference's receive files the record before +/// its callbacks run (`0x55bdb0`, `0x55f426`). +#[test] +fn the_caches_file_each_answer_ahead_of_the_readers_handler() { + use benilla_protocol::SessionEventKind as K; + let app = crate::game_plugins::schedule_tests::headless_client_unrun(); + let table = app + .world() + .resource::() + .census(); + for (kind, filer, reader) in [ + ( + K::MailItemText, + "ui_mail::net::on_mail_item_text", + "ui_item_text::net::on_item_text", + ), + ( + K::ItemTemplate, + "net::objects::on_item_answer", + "ui_item_text::net::on_item_template", + ), + ( + K::GameObjectInfo, + "net::objects::on_gameobject_info", + "ui_item_text::net::on_object_template", + ), + ( + K::PlayerName, + "names::net::on_player_name", + "ui_item_text::net::on_player_name", + ), + ] { + let order: Vec<&str> = table[&kind] + .iter() + .map(|name| name.trim_start_matches("benilla_app::")) + .collect(); + let at = |name: &str| order.iter().position(|n| *n == name); + assert!( + matches!((at(filer), at(reader)), (Some(f), Some(r)) if f < r), + "{kind:?}: {order:?}" + ); + } +} + +/// A page's show rewrites it to the player's skill as the show runs (`0x4e3837` → +/// `GetIndexedSpellSkill`, `0x4e3856`): a skill an earlier packet of the same frame raised to 300 +/// lets the tablet's page through whole, with no frame between, where a skill copied at the frame +/// would still scramble it. +#[test] +fn a_pages_show_reads_the_skill_its_frames_earlier_packet_wrote() { + use crate::ui_chat::test_speaker::{know, skill_fields}; + let mut app = client(); + tablets(&mut app); + let world = app.world_mut(); + // The tablets' template, its pages in language 1 (`data[8]`, `0x4e37fc`). + let mut data = [0i32; 24]; + data[7] = 358; + data[8] = 1; + world + .resource_mut::() + .insert(17188, 10, "The Lay of Ameth'Aran".into(), &data); + world + .resource_mut::() + .insert(358, "hello".into(), 0); + world.insert_resource(crate::ui_chat::ChatLanguages::for_test( + benilla_formats::LanguageWords::from_rows([(1, "kazum".to_string())]), + )); + know(world, 1); + frame(&mut app, vec![values(ME, &skill_fields(0))]); + crate::net::handlers::dispatch( + app.world_mut(), + vec![values(ME, &skill_fields(300)), page_text(TABLET)], + ); + assert_eq!( + eval::(&mut app, true, "return ItemTextGetText()"), + "hello" + ); +} diff --git a/crates/benilla-app/src/lanes/item_view_live_tests.rs b/crates/benilla-app/src/lanes/item_view_live_tests.rs new file mode 100644 index 000000000..c4b837916 --- /dev/null +++ b/crates/benilla-app/src/lanes/item_view_live_tests.rs @@ -0,0 +1,171 @@ +//! The item record as a getter reads it at the call, through the whole client: the tooltip build +//! expands each spell line's description at the build (`0x5075f0` at `0x52da24`), against the +//! active player as it stands, so a listener's build reads the player its own packet left; and +//! `GetBindLocation` reads the bind point at the call (`0x48dae3` → `0x5ed420`). + +use std::collections::HashMap; + +use benilla_formats::{SpellCatalog, SpellDisplay}; +use benilla_protocol::messages::{ChatMessage, ItemSpellEntry, CHAT_MSG_SYSTEM}; +use benilla_protocol::{EntityKind, SessionEvent}; +use benilla_ui::script::UiScript; +use bevy::prelude::*; +use crossbeam_channel::Sender; + +use super::unit_view_tests::{created, values, wire_packets}; + +const ME: u64 = 0x7; +/// The charm's record and the spell its use names, whose description branches on the caster's +/// gender (`$g`, `0x508214`). +const CHARM: u32 = 6_001; +const SPELL: u32 = 9_001; +/// `UNIT_FIELD_BYTES_0` of a human mage, and its gender byte's bit for female. +const BYTES_0: u16 = 36; +const HUMAN_MAGE: u32 = 1 | (8 << 8); +const FEMALE: u32 = 1 << 16; +/// The bind zone, named through `AreaTable`. +const GOLDSHIRE: u32 = 87; + +/// The spy: at each system line, the charm's use line as `SetHyperlink` builds it. +const SPY: &str = r#" + ITEM_SPELL_TRIGGER_ONUSE = "Use:" + Seen = {} + local a = CreateFrame("Button", "B"); a:SetPoint("CENTER", 0, 0); a:SetWidth(10); a:SetHeight(10) + CreateFrame("GameTooltip", "TT", nil, "TestTooltipTemplate") + local f = CreateFrame("Frame") + f:RegisterEvent("CHAT_MSG_SYSTEM") + f:SetScript("OnEvent", function() + TT:SetOwner(B, "ANCHOR_RIGHT"); TT:SetHyperlink("item:6001:0:0:0") + local line = "none" + for i = 1, TT:NumLines() do + local t = getglobal("TTTextLeft" .. i):GetText() + if t and string.find(t, "^Use:") then line = t end + end + table.insert(Seen, arg1 .. ":" .. line) + end) +"#; + +/// The whole client, headless, in the world with its frame run. +struct Client { + app: App, + inbound: Sender, +} + +impl Client { + /// One frame, with `packets` in the inbound channel, each one packet. + fn frame(&mut self, packets: Vec>) { + for ev in wire_packets(packets) { + self.inbound.send(ev).expect("the inbound channel"); + } + self.app.update(); + } + + /// What the spy heard since the last call. + fn seen(&mut self) -> Vec { + crate::script_calls::eval_in_vm(self.app.world(), "local s = Seen Seen = {} return s") + } +} + +fn system(text: &str) -> SessionEvent { + SessionEvent::Chat(ChatMessage { + chat_type: CHAT_MSG_SYSTEM, + language: 0, + sender_guid: 0, + target_guid: 0, + sender_name: None, + channel: None, + text: text.into(), + chat_tag: 0, + }) +} + +/// The client in the world as [`ME`], a male human mage, with the charm's record cached and a +/// VM whose spy builds its tooltip at each system line. +fn client() -> Client { + let mut app = crate::game_plugins::schedule_tests::headless_client(); + app.insert_resource(bevy::ecs::error::DefaultErrorHandler( + bevy::ecs::error::ignore, + )); + let (tx, _sent) = crossbeam_channel::unbounded(); + app.insert_resource(crate::net::NetCommands(tx)); + let (inbound, rx) = crossbeam_channel::unbounded(); + app.insert_resource(crate::net::NetEvents::for_test(rx)); + let spell = SpellDisplay { + id: SPELL, + name: "Charm".into(), + description: Some("Charms $ghis:her; foes.".into()), + ..Default::default() + }; + app.insert_resource(crate::ui_action::Spells { + catalog: SpellCatalog::from_displays(HashMap::from([(SPELL, spell)])), + ..crate::ui_action::Spells::empty_for_tests() + }); + app.insert_resource(crate::ui_quest_log::QuestHeaderNamesRes( + benilla_formats::QuestHeaderNames::from_zones([(GOLDSHIRE, "Goldshire")]), + )); + app.update(); + let script = UiScript::new().expect("a VM"); + crate::ui_script::test_ui::load_tooltip_template(&script); + script.run(SPY).expect("the spy"); + app.insert_non_send_resource(script); + app.insert_resource(State::new(crate::client_state::ClientState::InWorld)); + benilla_world::world_point::init_world_point_resources(app.world_mut()); + app.world_mut().resource_mut::().0 = Some(ME); + let mut t = crate::items::test_template("Charm of Gender"); + t.spells = vec![ItemSpellEntry { + index: 0, + spell_id: SPELL, + trigger: 0, + charges: 0, + cooldown_ms: -1, + category: 0, + category_cooldown_ms: -1, + }]; + app.world_mut() + .resource_mut::() + .insert_template(CHARM, Some(t)); + let mut c = Client { app, inbound }; + c.frame(vec![vec![created( + ME, + EntityKind::Player, + &[(BYTES_0, HUMAN_MAGE)], + )]]); + c.frame(vec![]); + c.seen(); + c +} + +/// Two writes of our gender byte in one frame, and a line after each: each line's tooltip build +/// expands the charm's use line against the player as the packets before it left it (`$g` reads +/// the caster at the build, `0x508214`), not as the frame's last packet left it. +#[test] +fn a_tooltip_between_two_player_writes_expands_against_the_first() { + let mut c = client(); + c.frame(vec![ + vec![values(ME, &[(BYTES_0, HUMAN_MAGE | FEMALE)])], + vec![system("first")], + vec![values(ME, &[(BYTES_0, HUMAN_MAGE)])], + vec![system("second")], + ]); + assert_eq!( + c.seen(), + [ + "first:Use: Charms her foes.", + "second:Use: Charms his foes." + ] + ); +} + +/// `GetBindLocation` reads the bind point at the call, through the lent host (`0x48dae3` → +/// `0x5ed420`): a bind stored since the last frame's feed answers at once. +#[test] +fn get_bind_location_reads_the_bind_point_at_the_call() { + let mut c = client(); + c.app.world_mut().resource_mut::().0 = Some(GOLDSHIRE); + let named = crate::script_calls::with_hosted_vm(c.app.world_mut(), |s| { + s.expect("a VM") + .eval::("return GetBindLocation()") + .expect("the chunk runs") + }); + assert_eq!(named, "Goldshire"); +} diff --git a/crates/benilla-app/src/lanes/lock_live_tests.rs b/crates/benilla-app/src/lanes/lock_live_tests.rs new file mode 100644 index 000000000..648aa46dc --- /dev/null +++ b/crates/benilla-app/src/lanes/lock_live_tests.rs @@ -0,0 +1,195 @@ +//! The item lock through the whole client: the lock is the item object's bit (`item+0x314` +//! bit 0), which only the constructor zeroes (`0x5d821f`, `0x5d823e`). A destroy frees the +//! object inside its handler (`0x4674a0` → `0x467521`), so a listener ahead of it reads the lock +//! and one behind a rebuild under the same guid reads none; a release leaves the bit set, as the +//! object waits in the released table (`0x464920`) and a block that brings it back reuses it +//! (`0x464530`). Neither the free nor the rebuild signals. + +use benilla_protocol::field::FIELD_PLAYER_INV_SLOT_HEAD; +use benilla_protocol::messages::{ChatMessage, ObjectType, CHAT_MSG_SYSTEM}; +use benilla_protocol::{EntityKind, ObjectFields, SessionEvent}; +use benilla_ui::script::UiScript; +use bevy::prelude::*; +use crossbeam_channel::{Receiver, Sender}; + +use crate::net::ClientCommand; + +use super::unit_view_tests::{created, wire_packets}; + +pub(super) const ME: u64 = 0x7; +/// In the backpack's first seat, 23: bag 0, slot 1. Its record is never asked, so no record +/// set-up runs its arrival's unlock (`0x5d85ab`). +pub(super) const SPARE: (u64, u32) = (item(2), 2361); + +const fn item(low: u64) -> u64 { + (benilla_protocol::guid::HIGH_ITEM as u64) << 48 | low +} + +/// The spy: each system line with the backpack's first slot's lock as `GetContainerItemInfo` +/// reads it at the call (`0x4f9752`), and each `ITEM_LOCK_CHANGED`. +const SPY: &str = r#"Seen = {} + local f = CreateFrame("Frame") + f:RegisterEvent("CHAT_MSG_SYSTEM") + f:RegisterEvent("ITEM_LOCK_CHANGED") + f:SetScript("OnEvent", function() + if event == "ITEM_LOCK_CHANGED" then + table.insert(Seen, "LOCK") + return + end + local _, _, locked = GetContainerItemInfo(0, 1) + table.insert(Seen, arg1 .. ":" .. tostring(locked)) + end)"#; + +/// The whole client, headless, in the world with its frame run. +pub(super) struct Client { + pub(super) app: App, + inbound: Sender, + /// What the client sent. + pub(super) sent: Receiver, +} + +impl Client { + /// One frame, with `packets` in the inbound channel, each one packet. + pub(super) fn frame(&mut self, packets: Vec>) { + for ev in wire_packets(packets) { + self.inbound.send(ev).expect("the inbound channel"); + } + self.app.update(); + } + + /// What the spy heard since the last call. + pub(super) fn seen(&mut self) -> Vec { + crate::script_calls::eval_in_vm(self.app.world(), "local s = Seen Seen = {} return s") + } +} + +/// Our item, created as a first create or a bring-back. +pub(super) fn spare() -> SessionEvent { + SessionEvent::ItemCreate { + guid: SPARE.0, + container: false, + fields: ObjectFields::from_pairs(&[ + (2, 0x3), + (3, SPARE.1), + (6, ME as u32), + (8, ME as u32), + (14, 1), + ]) + .into_created(ObjectType::Item), + } +} + +pub(super) fn system(text: &str) -> SessionEvent { + SessionEvent::Chat(ChatMessage { + chat_type: CHAT_MSG_SYSTEM, + language: 0, + sender_guid: 0, + target_guid: 0, + sender_name: None, + channel: None, + text: text.into(), + chat_tag: 0, + }) +} + +/// The client in the world as [`ME`], carrying [`SPARE`] locked in the backpack's first seat; the +/// spy emptied. +fn client() -> Client { + let mut c = client_with(SPY); + crate::script_calls::with_hosted_vm(c.app.world_mut(), |s| s.expect("a VM").lock_item(SPARE.0)); + c.frame(vec![]); + c.seen(); + c +} + +/// The client in the world as [`ME`], carrying [`SPARE`] in the backpack's first seat, its VM +/// running `spy`, whose `Seen` is emptied, and what it sent drained. +pub(super) fn client_with(spy: &str) -> Client { + let mut app = crate::game_plugins::schedule_tests::headless_client(); + app.insert_resource(bevy::ecs::error::DefaultErrorHandler( + bevy::ecs::error::ignore, + )); + let (tx, sent) = crossbeam_channel::unbounded(); + app.insert_resource(crate::net::NetCommands(tx)); + let (inbound, rx) = crossbeam_channel::unbounded(); + app.insert_resource(crate::net::NetEvents::for_test(rx)); + app.update(); + let script = UiScript::new().expect("a VM"); + script.run(spy).expect("the spy"); + app.insert_non_send_resource(script); + app.insert_resource(State::new(crate::client_state::ClientState::InWorld)); + benilla_world::world_point::init_world_point_resources(app.world_mut()); + app.world_mut().resource_mut::().0 = Some(ME); + let mut c = Client { app, inbound, sent }; + let seat = FIELD_PLAYER_INV_SLOT_HEAD + 2 * 23; + c.frame(vec![ + vec![spare()], + vec![created( + ME, + EntityKind::Player, + &[(seat, SPARE.0 as u32), (seat + 1, (SPARE.0 >> 32) as u32)], + )], + ]); + c.frame(vec![]); + c.seen(); + c.sent.try_iter().for_each(drop); + c +} + +/// A destroy of the locked item and a create of it again under the same guid, in one frame +/// between two lines: the line ahead of the destroy reads the old object's lock, and the line +/// behind the rebuild reads the new object unlocked, with no `ITEM_LOCK_CHANGED` for either. +#[test] +fn a_line_ahead_of_a_destroy_reads_the_lock_and_one_behind_the_rebuild_none() { + let mut c = client(); + c.frame(vec![ + vec![system("before")], + vec![SessionEvent::ObjectDestroyed(SPARE.0)], + vec![spare()], + vec![system("after")], + ]); + assert_eq!(c.seen(), ["before:1", "after:nil"]); +} + +/// The out-of-range list releases the locked item and a later block brings it back: the +/// object is the one that left, its bit still set, so the line behind it reads it locked. +#[test] +fn a_released_item_brought_back_keeps_its_lock() { + let mut c = client(); + c.frame(vec![ + vec![SessionEvent::ObjectsRemoved(vec![SPARE.0])], + vec![spare()], + vec![system("back")], + ]); + assert_eq!(c.seen(), ["back:1"]); + c.frame(vec![vec![system("later")]]); + assert_eq!(c.seen(), ["later:1"], "and keeps it past the frame"); +} + +/// A world load frees every object (`0x401bf7` → `0x467700` → `0x467800`): the item the new +/// world creates under the guid reads unlocked, with no `ITEM_LOCK_CHANGED`. +#[test] +fn a_world_load_frees_the_lock_with_its_item() { + let mut c = client(); + c.frame(vec![vec![SessionEvent::Worldport { + map_id: 1, + position: [0.0; 3], + orientation: 0.0, + needs_ack: false, + }]]); + c.frame(vec![]); + c.seen(); + let seat = FIELD_PLAYER_INV_SLOT_HEAD + 2 * 23; + c.frame(vec![ + vec![spare()], + vec![created( + ME, + EntityKind::Player, + &[(seat, SPARE.0 as u32), (seat + 1, (SPARE.0 >> 32) as u32)], + )], + vec![system("arrived")], + ]); + let heard = c.seen(); + assert_eq!(heard.last().map(String::as_str), Some("arrived:nil")); + assert!(!heard.iter().any(|l| l == "LOCK"), "no signal: {heard:?}"); +} diff --git a/crates/benilla-app/src/lanes/logout_live_tests.rs b/crates/benilla-app/src/lanes/logout_live_tests.rs new file mode 100644 index 000000000..1dc7f9a99 --- /dev/null +++ b/crates/benilla-app/src/lanes/logout_live_tests.rs @@ -0,0 +1,115 @@ +//! The logout replies' signals at their packets. `SMSG_LOGOUT_RESPONSE`'s handler signals +//! `PLAYER_CAMPING` or `PLAYER_QUITING` in place (`0x5aaef0`, `0x5aaf17`), and +//! `SMSG_LOGOUT_CANCEL_ACK`'s `LOGOUT_CANCEL` while a request is pending (`0x5aaf60`, `0x5aaf72`), +//! so each fires between the events of the packets around it. + +use benilla_protocol::SessionEvent; +use benilla_ui::script::UiScript; +use bevy::prelude::*; + +use super::unit_view_tests::{client, fall, frame}; + +/// A fall's `UNIT_COMBAT`, as [`client`]'s spy records it. +const FELL: &str = "UNIT_COMBAT:player:100"; + +/// [`client`] with the world handle seated, a write channel kept, and a spy on the logout +/// signals. +fn logout_client() -> (App, crossbeam_channel::Receiver) { + let mut app = client(); + let (tx, rx) = crossbeam_channel::unbounded(); + app.insert_resource(crate::net::NetCommands(tx)); + app.world_mut() + .resource_mut::() + .seat_world_handle_for_test(); + app.world_mut() + .non_send_resource_mut::() + .run( + r#" + local f = CreateFrame("Frame") + for _, e in ipairs({"PLAYER_CAMPING", "PLAYER_QUITING", "LOGOUT_CANCEL"}) do + f:RegisterEvent(e) + end + f:SetScript("OnEvent", function() table.insert(Seen, event) end) + "#, + ) + .unwrap(); + (app, rx) +} + +/// Run `chunk` with the host lent. +fn run(app: &mut App, chunk: &str) { + crate::script_calls::with_hosted_vm(app.world_mut(), |s| s.expect("a VM").run(chunk)) + .expect("runs"); +} + +/// The response's `PLAYER_CAMPING` fires at its packet's place, between a fall's `UNIT_COMBAT` on +/// each side. +#[test] +fn player_camping_fires_between_neighbouring_packets_events() { + let (mut app, _rx) = logout_client(); + run(&mut app, "Logout()"); + let response = SessionEvent::LogoutResponse { + reason: 0, + instant: false, + }; + let seen = frame(&mut app, vec![fall(5), response, fall(5)]); + assert_eq!(seen, [FELL, "PLAYER_CAMPING", FELL]); +} + +/// A quit's response signals `PLAYER_QUITING` at its packet, the quit byte its request stored +/// (`0x5ab053`) added to the id (`0x5aaf0c`). +#[test] +fn player_quiting_fires_at_its_packet() { + let (mut app, _rx) = logout_client(); + run(&mut app, "Quit()"); + let response = SessionEvent::LogoutResponse { + reason: 0, + instant: false, + }; + let seen = frame(&mut app, vec![fall(5), response, fall(5)]); + assert_eq!(seen, [FELL, "PLAYER_QUITING", FELL]); +} + +/// A cancel ack while a request is pending signals `LOGOUT_CANCEL` at its packet. +#[test] +fn logout_cancel_fires_at_the_acks_packet() { + let (mut app, _rx) = logout_client(); + run(&mut app, "Logout()"); + let seen = frame( + &mut app, + vec![fall(5), SessionEvent::LogoutCancelled, fall(5)], + ); + assert_eq!(seen, [FELL, "LOGOUT_CANCEL", FELL]); +} + +/// A `PLAYER_CAMPING` listener's `CancelLogout` runs before the next packet's handler (`0x537ae5`) +/// and clears the pending byte as it sends (`0x5aafc2`), so the cancel ack later in the frame +/// finds nothing pending (`0x5aaf60`) and signals no `LOGOUT_CANCEL`. +#[test] +fn a_campings_cancel_leaves_the_later_ack_silent() { + let (mut app, rx) = logout_client(); + app.world() + .non_send_resource::() + .run( + r#"local g = CreateFrame("Frame") + g:RegisterEvent("PLAYER_CAMPING") + g:SetScript("OnEvent", function() CancelLogout() end)"#, + ) + .unwrap(); + run(&mut app, "Logout()"); + let response = SessionEvent::LogoutResponse { + reason: 0, + instant: false, + }; + let seen = frame(&mut app, vec![response, SessionEvent::LogoutCancelled]); + assert_eq!(seen, ["PLAYER_CAMPING"]); + let sent: Vec<&str> = rx + .try_iter() + .filter_map(|c| match c { + crate::net::ClientCommand::Logout => Some("logout"), + crate::net::ClientCommand::LogoutCancel => Some("cancel"), + _ => None, + }) + .collect(); + assert_eq!(sent, ["logout", "cancel"]); +} diff --git a/crates/benilla-app/src/lanes/loot_live_tests.rs b/crates/benilla-app/src/lanes/loot_live_tests.rs index f51d71c36..18703ed01 100644 --- a/crates/benilla-app/src/lanes/loot_live_tests.rs +++ b/crates/benilla-app/src/lanes/loot_live_tests.rs @@ -317,16 +317,20 @@ fn a_candidates_name_signals_the_update_at_its_answer() { ); } -/// A window and the leave-world sweep's close with no frame between: the close shuts the session -/// at once and its `LOOT_CLOSED` waits behind the open on the lane, so the two fire in order and -/// leave the window shut, read through the host or after. +/// A window and the leave-world sweep's close with no frame between: the open fires inside its +/// dispatch, the close shuts the session at once and its `LOOT_CLOSED` fires at the frame's +/// drain, leaving the window shut, read through the host or after. #[test] fn a_one_frame_open_then_close_leaves_no_stale_state() { let mut c = client(); c.ask_loot(CORPSE); c.handle(vec![response(CORPSE, 0, &[LINEN])]); + assert_eq!( + c.seen(), + ["LOOT_OPENED:nil"], + "the open fires inside its dispatch" + ); crate::ui_script::sweep_test::sweep_in_place(&mut c.app); - assert!(c.seen().is_empty(), "nothing fired ahead of the open"); assert!( c.sent() .iter() @@ -336,7 +340,7 @@ fn a_one_frame_open_then_close_leaves_no_stale_state() { assert_eq!(c.app.world().resource::().source(), None); assert_eq!(c.app.world().resource::().0, None); c.frame(vec![]); - assert_eq!(c.seen(), ["LOOT_OPENED:nil", "LOOT_CLOSED:nil"]); + assert_eq!(c.seen(), ["LOOT_CLOSED:nil"]); assert_eq!(c.eval::(true, "return GetNumLootItems()"), 0); c.frame(vec![]); c.frame(vec![]); @@ -485,3 +489,100 @@ fn a_later_list_in_the_frame_does_not_show_through_to_an_earlier_step() { "Garrosh" ); } + +/// A response with the targeting cursor up hands its unit to the cast (`0x5ebc35` → `0x48f3be` → +/// `0x4935d5` → `0x6e5b40`), which binds it inside the packet, ahead of the open (`0x48f3cb`): the +/// cast goes out in the frame with no selection sent, its signals (`0x6e60cb`, the send's +/// `0x6e589d`) fire after the line before it and ahead of `LOOT_OPENED` and the line after, and a +/// listener of the window, as every call after it, reads the cursor down. +#[test] +fn a_response_with_the_cursor_up_binds_its_unit_at_the_packet() { + /// A living mark, which the pick-pocket's loot is from. + const MARK: u64 = 0xF130_0000_0000_00AD; + /// A spell the library does not know, so any unit binds under its `TARGET_FLAG_UNIT` word. + const HEAL: u32 = 2050; + let mut c = client(); + c.frame(vec![vec![created( + MARK, + EntityKind::Unit, + &[(FIELD_UNIT_HEALTH, 100)], + )]]); + c.frame(vec![]); + c.eval::<()>( + false, + r#" + local g = CreateFrame("Frame") + g:RegisterEvent("CURRENT_SPELL_CAST_CHANGED") + g:RegisterEvent("LOOT_OPENED") + g:SetScript("OnEvent", function() + if event == "LOOT_OPENED" then + table.insert(Seen, "targeting:" .. tostring(SpellIsTargeting())) + else + table.insert(Seen, event) + end + end) + "#, + ); + c.seen(); + c.sent(); + c.app + .world_mut() + .resource_mut::() + .enter(HEAL, crate::spell::CastCommit::Spell, 0x0002); + c.ask_loot(MARK); + c.frame(vec![ + vec![boar_says("a")], + vec![SessionEvent::LootResponse { + guid: MARK, + loot_type: loot_type::PICKPOCKETING, + gold: 0, + items: vec![row(0, LINEN, slot_type::ALLOW_LOOT)], + }], + vec![boar_says("b")], + ]); + assert_eq!( + c.seen(), + [ + "CHAT_MSG_MONSTER_SAY:a", + "CURRENT_SPELL_CAST_CHANGED", + "CURRENT_SPELL_CAST_CHANGED", + "LOOT_OPENED:nil", + "targeting:nil", + "CHAT_MSG_MONSTER_SAY:b", + ] + ); + let sent = c.sent(); + let casts: Vec<&String> = sent.iter().filter(|s| s.starts_with("CastSpell")).collect(); + assert_eq!( + casts, + [&format!( + "CastSpell {{ spell_id: {HEAL}, target: Some({MARK}) }}" + )], + "{sent:?}" + ); + assert!( + !sent.iter().any(|s| s.starts_with("SetSelection")), + "bound, not selected: {sent:?}" + ); + assert!(c.eval::(true, "return SpellIsTargeting() == nil")); +} + +/// A listener's close, then a removal in the same frame: `CloseLoot` at `LOOT_OPENED` runs before +/// the removal's handler (`0x537ae5`) and clears the latch, so the removal finds none +/// (`0x5ebedf`) and signals nothing. +#[test] +fn a_listeners_close_leaves_a_later_removal_unsignalled() { + let mut c = client(); + c.eval::<()>( + false, + r#"local g = CreateFrame("Frame") + g:RegisterEvent("LOOT_OPENED") + g:SetScript("OnEvent", function() CloseLoot() end)"#, + ); + c.ask_loot(CORPSE); + c.frame(vec![ + vec![response(CORPSE, 0, &[LINEN, WOOL])], + vec![SessionEvent::LootRemoved { slot: 1 }], + ]); + assert_eq!(c.seen(), ["LOOT_OPENED:nil", "LOOT_CLOSED:nil"]); +} diff --git a/crates/benilla-app/src/lanes/loot_roll_live_tests.rs b/crates/benilla-app/src/lanes/loot_roll_live_tests.rs new file mode 100644 index 000000000..14915cfd1 --- /dev/null +++ b/crates/benilla-app/src/lanes/loot_roll_live_tests.rs @@ -0,0 +1,136 @@ +//! The group loot rolls' getters as a listener reads them, and their signals at their packets. The +//! getters find the roll by id (`0x61b2e0`) and look its item up at the call (`0x4c3050`- +//! `0x4c3360`); `START_LOOT_ROLL` fires inside the start packet that finds its record cached +//! (`0x61b310` → `0x61b430`), and a result's line and `CANCEL_LOOT_ROLL` inside the result's +//! packet (`0x61b870` → `0x61b9e0`). + +use benilla_protocol::messages::{roll_vote, LootRollWon, LootStartRoll}; +use benilla_protocol::SessionEvent; +use benilla_ui::script::UiScript; +use bevy::prelude::*; + +use super::unit_view_tests::{client, fall, frame}; + +/// A fall's `UNIT_COMBAT`, as [`client`]'s spy records it. +const FELL: &str = "UNIT_COMBAT:player:100"; +const CORPSE: u64 = 0xF130_0000_0044_00AA; +const ROLLED: u32 = 17182; +const WINNER: u64 = 0x51; + +/// [`ROLLED`] cached as Sulfuras, [`WINNER`] named Bob, the won line's template in the strings, +/// and a spy on the roll events and the loot line, `START_LOOT_ROLL` with the name and the time +/// left its getters read as it fires. +fn rolls_client() -> App { + let mut app = client(); + let world = app.world_mut(); + world + .resource_mut::() + .insert_template(ROLLED, Some(crate::items::test_template("Sulfuras"))); + world + .resource_mut::() + .insert_player(WINNER, "Bob".into(), None); + world + .non_send_resource_mut::() + .run( + r#" + LOOT_ROLL_WON = "%s won: %s|Hitem:%d:%d:%d:%d|h[%s]|h%s" + local f = CreateFrame("Frame") + for _, e in ipairs({"START_LOOT_ROLL", "CANCEL_LOOT_ROLL", "CHAT_MSG_LOOT"}) do + f:RegisterEvent(e) + end + f:SetScript("OnEvent", function() + if event == "START_LOOT_ROLL" then + local _, name = GetLootRollItemInfo(arg1) + table.insert(Seen, event .. ":" .. arg1 .. ":" .. arg2 .. ":" + .. tostring(name)) + elseif event == "CHAT_MSG_LOOT" then + table.insert(Seen, event) + else + table.insert(Seen, event .. ":" .. arg1) + end + end) + "#, + ) + .unwrap(); + app +} + +fn start(slot: u32) -> SessionEvent { + SessionEvent::LootStartRoll(LootStartRoll { + looted_target: CORPSE, + item_slot: slot, + item_id: ROLLED, + random_property_id: 0, + suffix_factor: 0, + countdown_ms: 60_000, + }) +} + +fn won(slot: u32) -> SessionEvent { + SessionEvent::LootRollWon(LootRollWon { + looted_target: CORPSE, + item_slot: slot, + item_id: ROLLED, + random_property_id: 0, + suffix_factor: 0, + winner: WINNER, + roll_number: 84, + roll_type: roll_vote::NEED, + }) +} + +/// `chunk`'s answer through the lent host when `live`, else off the VM's copy alone. +fn eval(app: &mut App, live: bool, chunk: &str) -> T { + if live { + crate::script_calls::with_hosted_vm(app.world_mut(), |s| { + s.expect("a VM").eval::(chunk).expect("runs") + }) + } else { + crate::script_calls::eval_in_vm(app.world(), chunk) + } +} + +const READ: &str = "local _, name, _, quality = GetLootRollItemInfo(1) \ + return tostring(name) .. '/' .. quality .. '/' .. tostring(GetLootRollItemLink(1) ~= nil) \ + .. '/' .. tostring(GetLootRollTimeLeft(1) > 59000)"; + +/// With no frame after the start packet, the getters read the engine's roll and its record through +/// the host; the VM's copy, which nothing pushes, holds none. +#[test] +fn the_roll_getters_read_the_list_at_the_call() { + let mut app = rolls_client(); + crate::net::handlers::dispatch(app.world_mut(), vec![start(0)]); + assert_eq!(eval::(&mut app, true, READ), "Sulfuras/1/true/true"); + assert_eq!(eval::(&mut app, false, READ), "nil/1/false/false"); +} + +/// The start's `START_LOOT_ROLL` fires at its packet's place between a fall's `UNIT_COMBAT` on +/// each side, its listener reading the roll's item. +#[test] +fn start_loot_roll_fires_between_neighbouring_packets_events() { + let mut app = rolls_client(); + let seen = frame(&mut app, vec![fall(5), start(0), fall(5)]); + assert_eq!(seen, [FELL, "START_LOOT_ROLL:1:60000:Sulfuras", FELL]); +} + +/// A roll started and won in one frame: its start, then the win's line and cancel, each at its +/// packet's place; the frame leaves no roll listed, nothing on the lane, and no vote to send, and +/// the next frame signals nothing. +#[test] +fn a_roll_started_and_cancelled_in_one_frame_leaves_no_stale_state() { + let mut app = rolls_client(); + let seen = frame(&mut app, vec![start(0), fall(5), won(0)]); + assert_eq!( + seen[0].split(':').take(3).collect::>(), + ["START_LOOT_ROLL", "1", "60000"] + ); + assert_eq!(&seen[1..], [FELL, "CHAT_MSG_LOOT", "CANCEL_LOOT_ROLL:1"]); + let rolls = app.world().resource::(); + assert!(!rolls.holds(1)); + assert_eq!(eval::(&mut app, true, READ), "nil/1/false/false"); + let (tx, rx) = crossbeam_channel::unbounded(); + app.insert_resource(crate::net::NetCommands(tx)); + eval::<()>(&mut app, true, "RollOnLoot(1, 0)"); + assert!(rx.try_iter().next().is_none(), "no roll to vote on"); + assert!(frame(&mut app, vec![]).is_empty()); +} diff --git a/crates/benilla-app/src/lanes/mail_live_tests.rs b/crates/benilla-app/src/lanes/mail_live_tests.rs index 13f80f5b8..72b4cfab3 100644 --- a/crates/benilla-app/src/lanes/mail_live_tests.rs +++ b/crates/benilla-app/src/lanes/mail_live_tests.rs @@ -14,7 +14,7 @@ use crossbeam_channel::{Receiver, Sender}; use super::unit_view_tests::{created, wire_packets}; use crate::net::ClientCommand; -use crate::ui_mail::{MailEvent, MailLane, MailOpen, MailPending}; +use crate::ui_mail::{MailLane, MailOpen, MailPending}; const ME: u64 = 0x7; const BOB: u64 = 0x42; @@ -212,35 +212,28 @@ fn the_mail_getters_read_the_session_at_the_call() { ); } -/// The list's tail, a result's tail and the time reply's signal sit on the mail lane at their -/// handlers, between the stamps of the handlers before and after. +/// The list's tail, a result's tail and the time reply's signal each fire inside their packet's +/// dispatch, with no frame after them: a handler's signal runs every listener before the next +/// packet's handler (`0x537ae5`, `0x703e50`). #[test] -fn the_mail_events_are_stamped_at_their_handlers() { +fn the_mail_events_fire_inside_their_dispatch() { let mut c = client(); c.open_mailbox(); c.seen(); - let before = crate::lanes::stamp(); c.handle(vec![ list(vec![letter(1, "Hello", 0)]), sent_ok(), SessionEvent::NextMailTime { seconds: 0.0 }, ]); - let after = crate::lanes::stamp(); - let lane = c.app.world().resource::(); - let stamped = lane.stamped(); - assert!( - stamped.iter().all(|(at, _)| before < *at && *at < after), - "stamped inside the handlers" + assert!(c.app.world().resource::().stamped().is_empty()); + assert_eq!( + c.seen(), + [ + "MAIL_INBOX_UPDATE:nil", + "MAIL_FAILED:nil", + "UPDATE_PENDING_MAIL:nil" + ] ); - let events: Vec<&MailEvent> = stamped.into_iter().map(|(_, e)| e).collect(); - assert!( - matches!( - events[..], - [MailEvent::List, MailEvent::Result(_), MailEvent::Pending] - ), - "{events:?}" - ); - assert!(c.seen().is_empty(), "nothing fired in the handlers"); } /// Each mail event fires at its packet's place among a chat line's of the packets around it. The @@ -397,9 +390,10 @@ fn the_notice_callbacks_signal_at_their_answers() { ); } -/// The list's tail is on the lane when the mailbox is used and a bank opens over it, all with no -/// frame between: the open's show and the close's reset, signal and refresh wait behind the list, -/// so they fire whole at their place, the refresh's query with them, and leave the window shut. +/// A list, the mailbox used, and a bank opening over it, all with no frame between: the list's +/// tail fires inside its dispatch, the use shows the window in place, and the bank's handler +/// closes it, its reset and signal ahead of the bank's own; the close's refresh, its query and its +/// stamp, is the handler's own (`0x4acda8`), so it goes out there; the window is left shut. #[test] fn a_one_frame_open_then_close_leaves_no_stale_state() { let mut c = client(); @@ -410,10 +404,9 @@ fn a_one_frame_open_then_close_leaves_no_stale_state() { .arm_refresh(); c.open_mailbox(); c.handle(vec![SessionEvent::ShowBank { banker: BANKER }]); - assert!(c.seen().is_empty(), "nothing fired ahead of the list"); assert!( - !c.sent().iter().any(|s| s.starts_with("QueryNextMailTime")), - "the close's query waits with its signal" + c.sent().iter().any(|s| s.starts_with("QueryNextMailTime")), + "the close's query goes out inside the handler" ); assert_eq!(c.app.world().resource::().mailbox, None); c.frame(vec![]); @@ -431,7 +424,8 @@ fn a_one_frame_open_then_close_leaves_no_stale_state() { .iter() .filter(|s| s.starts_with("QueryNextMailTime")) .count(), - 1 + 0, + "the one query went out at the handler" ); // The rows outlive the close, and no verb finds a mailbox, through the host or the VM's copy. assert_eq!(c.eval::(true, "return GetInboxNumItems()"), 1); @@ -698,8 +692,9 @@ fn a_paper_picked_up_between_rebuilds_changes_nothing_until_the_next() { } /// Each `GetSendMailItem` call before the record answers keeps its own callback `0x4ae710` -/// (dedupe flag 0, `0x4ae5ea`), while the cache sends the one query in flight: two calls, one -/// query, two `MAIL_SEND_INFO_UPDATE` at the answer (`0x4ae71f`). +/// (dedupe flag 0, `0x4ae5ea`), while the cache holds the one query in flight, the item's create's +/// (`0x5d8300`): two calls, no query of theirs, two `MAIL_SEND_INFO_UPDATE` at the answer +/// (`0x4ae71f`). #[test] fn two_attachment_reads_before_the_answer_send_one_query_and_two_updates() { let mut c = client(); @@ -719,7 +714,7 @@ fn two_attachment_reads_before_the_answer_send_one_query_and_two_updates() { .into_iter() .filter(|s| s.starts_with("ItemQuery")) .count(); - assert_eq!(queries, 1, "one query in flight"); + assert_eq!(queries, 0, "the create's query is in flight"); c.frame(vec![vec![SessionEvent::ItemTemplate { entry: WOOL, info: Some(Box::new(crate::items::test_template("Wool Cloth"))), diff --git a/crates/benilla-app/src/lanes/merchant_live_tests.rs b/crates/benilla-app/src/lanes/merchant_live_tests.rs index 2a8f25a54..869e77770 100644 --- a/crates/benilla-app/src/lanes/merchant_live_tests.rs +++ b/crates/benilla-app/src/lanes/merchant_live_tests.rs @@ -247,20 +247,18 @@ fn the_merchant_events_fire_at_their_packets() { ); } -/// The list's `MERCHANT_SHOW` sits on the merchant lane at its handler's stamp, between the -/// stamps of the handlers before and after it. +/// The list's `MERCHANT_SHOW` fires inside its packet's dispatch, with no frame after it: the +/// handler's signal runs every listener before the next packet's handler (`0x537ae5`, `0x703e50`). #[test] -fn the_show_is_stamped_at_its_handler() { +fn the_show_fires_inside_its_dispatch() { let mut c = client(); - let before = crate::lanes::stamp(); c.handle(vec![list(vec![row(1, 159)])]); - let after = crate::lanes::stamp(); let lane = c.app.world().resource::(); - let stamped = lane.stamped(); - assert_eq!(stamped.len(), 1); - let (at, event) = stamped[0]; - assert_eq!(event, crate::ui_merchant::MerchantEvent::Show); - assert!(before < at && at < after, "stamped inside the handler"); + assert!(lane.stamped().is_empty(), "nothing left on the lane"); + assert!( + c.seen().iter().any(|s| s == "MERCHANT_SHOW:nil"), + "the show fired inside the dispatch" + ); } /// A row's missing record is asked by the getter's call with its callback, one wait per call @@ -307,6 +305,62 @@ fn a_records_answer_and_the_buyback_watch_signal_at_their_packets() { ); } +/// A refusal's `MERCHANT_UPDATE` fires inside its walk, while the dying node stands: a listener's +/// getter that asks the row again links its callback to the node and sends nothing. Raised by the +/// last callback, the walk ends there and the node's destroy frees it uncalled (`0x55be9c`, +/// `0x55bed2`); raised by one with a next, the walk reaches it, and its run with status 0 signals +/// again, whose re-ask is then the last's. A later call asks again. +#[test] +fn a_getter_inside_a_refusals_walk_asks_nothing() { + refusal_walk(false); + refusal_walk(true); +} + +/// [`a_getter_inside_a_refusals_walk_asks_nothing`], with a trade getter's wait after the row's +/// when `behind`. +fn refusal_walk(behind: bool) { + let mut c = client(); + c.handle(vec![list(vec![row(1, UNCACHED)])]); + c.frame(vec![]); + c.seen(); + c.eval::<()>( + true, + r#" + local f = CreateFrame("Frame") + f:RegisterEvent("MERCHANT_UPDATE") + f:SetScript("OnEvent", function() ReAsked = (GetMerchantItemInfo(1)) or "none" end) + GetMerchantItemInfo(1) + "#, + ); + assert_eq!(c.item_queries(), 1); + if behind { + c.app + .world() + .resource::() + .wait_for_trade_record(UNCACHED); + } + c.frame(vec![vec![SessionEvent::ItemTemplate { + entry: UNCACHED, + info: None, + }]]); + let updates: &[&str] = if behind { + &["MERCHANT_UPDATE:nil", "MERCHANT_UPDATE:nil"] + } else { + &["MERCHANT_UPDATE:nil"] + }; + assert_eq!(c.seen(), updates, "the re-ask's run signals when reached"); + assert_eq!(c.eval::(false, "return ReAsked"), "none"); + assert_eq!(c.item_queries(), 0, "nothing sent inside the walk"); + let waits = c + .app + .world_mut() + .resource_mut::() + .take_waiters(UNCACHED, crate::items::RecordCallback::Merchant); + assert_eq!(waits, 0, "nothing kept"); + c.eval::<()>(true, "GetMerchantItemInfo(1)"); + assert_eq!(c.item_queries(), 1, "a later call asks again"); +} + /// The item queries sent since the last call, as their bodies go out. fn query_bodies(c: &mut Client) -> Vec> { crate::query_cache::queries(&c.sent) @@ -559,3 +613,18 @@ fn a_repair_cost_reads_as_of_each_packet() { [i64::from(discounted), i64::from(full)] ); } + +/// A verb's `"npc"` is the interaction latch as the handlers leave it (`0x515c00`), with no frame +/// between: the list's handler latches the vendor (`0x4930d0`), and `TargetUnit("npc")` selects +/// it before any feed runs. +#[test] +fn a_verbs_npc_token_reads_the_latch_at_the_call() { + let mut c = client(); + c.handle(vec![list(vec![row(1, 159)])]); + c.eval::<()>(true, "TargetUnit('npc')"); + assert_eq!( + c.app.world().resource::().guid, + Some(VENDOR), + "the latch the list's handler set, read as the verb runs" + ); +} diff --git a/crates/benilla-app/src/lanes/packet_signal_tests.rs b/crates/benilla-app/src/lanes/packet_signal_tests.rs index 0cb3c7971..2e9bbd16a 100644 --- a/crates/benilla-app/src/lanes/packet_signal_tests.rs +++ b/crates/benilla-app/src/lanes/packet_signal_tests.rs @@ -252,6 +252,41 @@ fn a_game_objects_page_text_begins_at_its_packet() { ); } +/// A gossip menu's register closes the latched reader inside its handler (`0x4e26e0` → +/// `0x4930d0` → `0x493310` → `0x4e32e0(0, 0)`), so `ITEM_TEXT_CLOSED` (`0x4e33a2`) fires at the +/// menu's place among the frame's packets, though the reader's lane holds nothing then. +#[test] +fn a_register_at_a_packet_closes_the_reader_at_its_place() { + const NPC: u64 = 0xF130_0000_0000_0043; + let mut app = client(); + tablet(&mut app, true); + frame( + &mut app, + vec![SessionEvent::GameObjectPageText { guid: TABLET }], + ); + spy(&mut app, &["ITEM_TEXT_CLOSED"]); + let seen = frame( + &mut app, + vec![ + fall(5), + SessionEvent::GossipMenu { + npc: NPC, + text_id: 7, + options: Vec::new(), + quests: Vec::new(), + }, + fall(5), + ], + ); + assert_eq!(seen, [FELL, "ITEM_TEXT_CLOSED", FELL]); + assert_eq!( + app.world() + .resource::() + .object(), + None + ); +} + /// With the first page not cached the open asks for it and returns (`0x4e348b` → `0x4e35a0`); the /// page's answer runs the callback `0x4e3280`, which opens again (`0x4e32a5`), so /// `ITEM_TEXT_BEGIN` fires at the answer's place. @@ -277,36 +312,56 @@ fn an_uncached_page_begins_at_its_answer() { assert_eq!(seen, [FELL, "ITEM_TEXT_BEGIN", FELL]); } -/// The session's end drops the reads the item-text lane holds, as the other lanes' ends drop -/// theirs; so does a worldport's leave-world sweep in the same frame, which closes the reader -/// (`0x490abc` → `0x4e3240`) ahead of the lanes' drain. +/// The session's end drops the signals the item-text lane holds, as the other lanes' ends drop +/// theirs, and its shutdown's sweep closes the reader the packet opened; so does the leave-world +/// sweep (a `/reload`'s), which closes the reader (`0x490abc` → `0x4e3240`). The lane holds the +/// packet's `ITEM_TEXT_BEGIN` because the world's interface had not loaded at its dispatch, so no +/// flush fired it. #[test] -fn the_session_end_and_a_worldport_drop_the_item_text_lane() { +fn the_session_end_and_a_sweep_drop_the_item_text_lane() { let reader = |app: &App| { app.world() .resource::() .object() }; - let page_text = || vec![SessionEvent::GameObjectPageText { guid: TABLET }]; + let held = |app: &App| { + app.world() + .resource::() + .held() + }; + let page_text_held = |app: &mut App| { + let world = app.world_mut(); + world.insert_resource(crate::ui_script::PendingEntryUiLoad); + crate::net::handlers::dispatch( + world, + vec![SessionEvent::GameObjectPageText { guid: TABLET }], + ); + world.remove_resource::(); + }; let mut app = client(); tablet(&mut app, true); + page_text_held(&mut app); + assert_ne!(held(&app), 0, "the open's signals, unfired"); let world = app.world_mut(); - crate::net::handlers::dispatch(world, page_text()); + world + .resource_mut::() + .arm(); world.init_resource::(); world.run_schedule(OnExit(crate::client_state::ClientState::InWorld)); - crate::lanes::fire_in_order(world); + assert_eq!(held(&app), 0, "the session's end drops it"); + crate::lanes::fire_in_order(app.world_mut()); assert_eq!(reader(&app), None, "the session's end"); let mut app = client(); tablet(&mut app, true); spy(&mut app, &["ITEM_TEXT_BEGIN"]); + page_text_held(&mut app); let world = app.world_mut(); - crate::net::handlers::dispatch(world, page_text()); world .resource_mut::() .arm(); crate::ui_script::run_leave_world_sweep(world); - assert!(frame(&mut app, vec![]).is_empty(), "the worldport's sweep"); + assert!(frame(&mut app, vec![]).is_empty(), "the sweep drops it"); assert_eq!(reader(&app), None); } @@ -457,3 +512,215 @@ fn the_pets_happiness_signals_at_its_packet() { [FELL, "UNIT_HAPPINESS:pet", FELL, "UNIT_HAPPINESS:pet"] ); } + +/// `SMSG_CLEAR_FAR_SIGHT_IMMEDIATE` ends far sight inside its handler (`0x5e441d` → `0x5ee590`), +/// and `HasFullControl` reads the bit where it runs (`0x51a142`): with no frame after the packet +/// the getter answers 1 again through the host, where the VM's seat, which nothing pushes, holds +/// what it was. +#[test] +fn has_full_control_reads_the_far_sight_bit_at_the_call() { + /// The far-sight object, a unit the index holds. + const EYE: u64 = 0xF130_0000_0044_0001; + let mut app = client(); + app.world_mut() + .non_send_resource_mut::() + .set_player_control(true); + let live = |app: &mut App| { + crate::script_calls::with_hosted_vm(app.world_mut(), |s| { + s.expect("a VM") + .eval::>("return HasFullControl()") + .expect("runs") + }) + }; + assert_eq!(live(&mut app), Some(1)); + { + let world = app.world_mut(); + let net = crate::net::NetCommands(world.resource::().0.clone()); + world + .resource::() + .update(Some(EYE), |_| true, &net); + } + assert_eq!(live(&mut app), None, "far sight on refuses"); + crate::net::handlers::dispatch(app.world_mut(), vec![SessionEvent::FarSightCleared]); + assert_eq!(live(&mut app), Some(1), "the clear's handler ended it"); +} + +/// `PLAYER_FARSIGHT`, the guid's low word. +const FARSIGHT: u16 = 712; +/// [`client`]'s wolf, held. +const WOLF: u64 = 0xF130_0000_0044_0001; + +/// Our `PLAYER_FARSIGHT` set to `guid`. +fn far_sight_field(guid: u64) -> SessionEvent { + values( + ME, + &[(FARSIGHT, guid as u32), (FARSIGHT + 1, (guid >> 32) as u32)], + ) +} + +/// The `CMSG_FAR_SIGHT` sent since the last look, as engage booleans. +fn far_sight_votes(rx: &crossbeam_channel::Receiver) -> Vec { + rx.try_iter() + .filter_map(|c| match c { + crate::net::ClientCommand::FarSight { engage } => Some(engage), + _ => None, + }) + .collect() +} + +/// [`client`] in full control, its commands on the channel returned, with a spy on `event` that +/// records `HasFullControl()` as `":"`. +fn far_sight_client(event: &str) -> (App, crossbeam_channel::Receiver) { + let mut app = client(); + let (tx, rx) = crossbeam_channel::unbounded(); + app.insert_resource(crate::net::NetCommands(tx)); + let mut script = app.world_mut().non_send_resource_mut::(); + script.set_player_control(true); + script + .run(&format!( + r#" + local f = CreateFrame("Frame") + f:RegisterEvent("{event}") + f:SetScript("OnEvent", function() + table.insert(Seen, "{event}:" .. tostring(HasFullControl())) + end) + "# + )) + .unwrap(); + (app, rx) +} + +/// `PLAYER_FARSIGHT`'s change on our player (`0x5de0d0`) starts far sight on a held object +/// (`0x5de144` → `0x5ee270`), `CMSG_FAR_SIGHT` 1 out, then signals +/// `PLAYER_FARSIGHT_FOCUS_CHANGED` (`0x5de14e`), whose listener's `HasFullControl()` refuses on +/// the bit (`0x51a142`); the clear ends it (`0x5de15d` → `0x5ee590`), 0 out, ahead of its signal +/// (`0x5de167`). +#[test] +fn a_far_sight_change_starts_and_ends_at_its_packet_ahead_of_its_signal() { + let (mut app, rx) = far_sight_client("PLAYER_FARSIGHT_FOCUS_CHANGED"); + let seen = frame(&mut app, vec![far_sight_field(WOLF)]); + assert_eq!(seen, ["PLAYER_FARSIGHT_FOCUS_CHANGED:nil"]); + assert_eq!(far_sight_votes(&rx), [true]); + let seen = frame(&mut app, vec![far_sight_field(0)]); + assert_eq!(seen, ["PLAYER_FARSIGHT_FOCUS_CHANGED:1"]); + assert_eq!(far_sight_votes(&rx), [false]); +} + +/// A far-sight field naming an object not yet held starts nothing (`0x5de15d` → `0x5ee590`, far +/// sight off); the object's create does, a unit's `PostInit` (`0x5fbb1a` → `0x5ee270`): +/// `CMSG_FAR_SIGHT` 1 out inside its packet, and a listener later in the frame finds +/// `HasFullControl()` refusing on the bit (`0x51a142`). +#[test] +fn a_far_sight_objects_create_starts_far_sight_at_its_packet() { + /// Not yet streamed. + const EYE: u64 = 0xF130_0000_0046_0003; + let (mut app, rx) = far_sight_client("UNIT_COMBAT"); + frame(&mut app, vec![far_sight_field(EYE)]); + assert!(far_sight_votes(&rx).is_empty(), "no object, no start"); + let seen = frame(&mut app, vec![created(EYE, EntityKind::Unit, &[]), fall(5)]); + assert_eq!(far_sight_votes(&rx), [true], "the create starts it"); + assert_eq!( + seen.iter() + .filter(|s| s.starts_with("UNIT_COMBAT:") && !s.starts_with("UNIT_COMBAT:player")) + .collect::>(), + ["UNIT_COMBAT:nil"], + "{seen:?}" + ); +} + +/// A dynamic object's `OnCreate` (`0x5d5420`) starts far sight (`0x5d552d`) only for a far-sight +/// focus, its bytes' low byte 2 (`0x5d54a7`), that the active player cast (`0x5d54b6`), and only +/// when our `PLAYER_FARSIGHT` names it (`0x5d5520`). +#[test] +fn a_far_sight_focus_we_cast_starts_far_sight_at_its_create() { + /// The caster's guid (fields 6 and 7) and the bytes (field 8). + const CASTER: u16 = 6; + const BYTES: u16 = 8; + const OTHER: u64 = 0x52; + let focus = |guid: u64, caster: u64, bytes: u32| SessionEvent::ObjectCreate { + guid, + kind: EntityKind::DynamicObject, + display_id: None, + position: [0.0; 3], + orientation: 0.0, + scale: 1.0, + speeds: None, + mover: None, + transport_progress: None, + transport: None, + spline: None, + fields: benilla_protocol::ObjectFields::from_pairs(&[ + (2, 0x41), + (CASTER, caster as u32), + (CASTER + 1, (caster >> 32) as u32), + (BYTES, bytes), + ]) + .into_created(benilla_protocol::messages::ObjectType::DynamicObject), + }; + let starts = |caster: u64, bytes: u32, named: bool| { + const EYE: u64 = 0xF130_0000_0047_0004; + let (mut app, rx) = far_sight_client("UNIT_COMBAT"); + frame( + &mut app, + vec![far_sight_field(if named { EYE } else { EYE + 1 })], + ); + far_sight_votes(&rx); + frame(&mut app, vec![focus(EYE, caster, bytes)]); + far_sight_votes(&rx) == [true] + }; + assert!(starts(ME, 2, true), "our focus, named: the start"); + assert!(!starts(OTHER, 2, true), "another's focus"); + assert!(!starts(ME, 1, true), "an area spell's object"); + assert!(!starts(ME, 2, false), "a focus the field does not name"); +} + +/// Our player goes with every object at a world's end and at a cross-map load (`0x467800`), its +/// far-sight bit with it, and the next player's constructor zeroes it (`0x5dd33d`): a world left +/// far-sighted owes the next one no `CMSG_FAR_SIGHT` 0 at the clear packet (`0x5e441d` → +/// `0x5ee590`), and the next start sends its 1. +#[test] +fn a_world_left_far_sighted_starts_the_next_with_far_sight_off() { + let ends = [ + SessionEvent::LoggedOut, + SessionEvent::Disconnected { + reason: String::new(), + end: benilla_protocol::SessionEnd::Lost, + }, + SessionEvent::Worldport { + map_id: 1, + position: [0.0; 3], + orientation: 0.0, + needs_ack: false, + }, + ]; + for end in ends { + let label = format!("{end:?}"); + let (mut app, rx) = far_sight_client("UNIT_COMBAT"); + frame(&mut app, vec![far_sight_field(WOLF)]); + assert_eq!(far_sight_votes(&rx), [true], "{label}"); + frame(&mut app, vec![end]); + assert!( + far_sight_votes(&rx).is_empty(), + "{label}: the end sends nothing" + ); + // The next world: our player and the wolf again. + app.world_mut().resource_mut::().0 = Some(ME); + frame( + &mut app, + vec![ + created(ME, EntityKind::Player, &[]), + created(WOLF, EntityKind::Unit, &[]), + ], + ); + let world = app.world_mut(); + let me = world.resource::().0[&ME]; + world.entity_mut(me).insert(crate::net::SelfPlayer); + frame(&mut app, vec![SessionEvent::FarSightCleared]); + assert!( + far_sight_votes(&rx).is_empty(), + "{label}: the new player's far sight is off" + ); + frame(&mut app, vec![far_sight_field(WOLF)]); + assert_eq!(far_sight_votes(&rx), [true], "{label}: and starts again"); + } +} diff --git a/crates/benilla-app/src/lanes/petition_live_tests.rs b/crates/benilla-app/src/lanes/petition_live_tests.rs index bfa3a9947..a35924a0b 100644 --- a/crates/benilla-app/src/lanes/petition_live_tests.rs +++ b/crates/benilla-app/src/lanes/petition_live_tests.rs @@ -12,7 +12,7 @@ use benilla_protocol::SessionEvent; use benilla_ui::script::UiScript; use bevy::prelude::*; -use crate::ui_petition::{PetitionEvent, PetitionLane}; +use crate::ui_petition::PetitionLane; const ME: u64 = 0x10; const OWNER: u64 = 0xaa; @@ -23,6 +23,10 @@ const CHARTER: u64 = 0x4000_0000_0000_0099; /// each charter event. fn client() -> App { let mut app = crate::game_plugins::schedule_tests::headless_client_unrun(); + // In the world with the interface up, so the dispatch fires each packet's lanes. + app.insert_resource(bevy::prelude::State::new( + crate::client_state::ClientState::InWorld, + )); let (tx, _rx) = crossbeam_channel::unbounded(); app.insert_resource(crate::net::NetCommands(tx)); app.insert_resource(crate::net::SelfGuid(Some(ME))); @@ -57,23 +61,17 @@ fn eval(app: &mut App, live: bool, chunk: &st } } -/// `packets` through their handlers, each item they put on the charter lane stamped inside them, -/// none heard before the drain; then the drain, and what the spy heard. -fn handled(app: &mut App, packets: Vec) -> (Vec, Vec) { - let before = crate::lanes::stamp(); +/// `packets` through their handlers: each event the charter lane takes fires inside the dispatch, at +/// its packet's place, as a handler signals inside itself (`0x703e50`) ahead of the next packet's +/// (`0x537ae5`), so the drain finds nothing; what the spy heard. +fn handled(app: &mut App, packets: Vec) -> Vec { crate::net::handlers::dispatch(app.world_mut(), packets); app.world_mut().flush(); - let after = crate::lanes::stamp(); - let stamped = app.world().resource::().stamped(); assert!( - stamped.iter().all(|(at, _)| before < *at && *at < after), - "stamped inside the handler" + app.world().resource::().stamped().is_empty(), + "fired inside the dispatch" ); - let heard: Vec = eval(app, false, "return Seen"); - assert!(heard.is_empty(), "on the lane: {heard:?}"); - crate::lanes::fire_in_order(app.world_mut()); - let heard = eval(app, false, "local s = Seen Seen = {} return s"); - (stamped.into_iter().map(|(_, e)| e).collect(), heard) + eval(app, false, "local s = Seen Seen = {} return s") } fn offered() -> SessionEvent { @@ -146,32 +144,33 @@ fn the_getters_read_the_charter_through_the_host() { ); } -/// The show waits on the record's and the signer name's answers, and `PETITION_SHOW` sits on the -/// lane at the last one's handler; our signature's line and `PETITION_CLOSED`, and the turn-in's -/// `GUILD_REGISTRAR_CLOSED`, sit at theirs, and each fires there in the drain. +/// The show waits on the record's and the signer name's answers, and `PETITION_SHOW` fires inside +/// the last one's dispatch; our signature's chat line (the catalog sends the success ids to chat) +/// and `PETITION_CLOSED`, and the turn-in's +/// `GUILD_REGISTRAR_CLOSED`, inside theirs. #[test] -fn the_show_and_the_results_fire_on_the_lane_at_their_handlers() { +fn the_show_and_the_results_fire_inside_their_dispatch() { let mut app = client(); - assert_eq!(handled(&mut app, vec![offered()]), (vec![], vec![])); - assert_eq!(handled(&mut app, vec![record()]), (vec![], vec![])); - assert_eq!( - handled(&mut app, vec![signer_name()]), - (vec![PetitionEvent::Show], vec!["PETITION_SHOW".into()]) + eval::<()>( + &mut app, + false, + r#"ERR_PETITION_SIGNED = "Signed" + local g = CreateFrame("Frame") + g:RegisterEvent("CHAT_MSG_SYSTEM") + g:SetScript("OnEvent", function() table.insert(Seen, "line " .. arg1) end)"#, ); + assert!(handled(&mut app, vec![offered()]).is_empty()); + assert!(handled(&mut app, vec![record()]).is_empty()); + assert_eq!(handled(&mut app, vec![signer_name()]), ["PETITION_SHOW"]); let signed = SessionEvent::PetitionSignResults(PetitionSignResults { item: CHARTER, player: ME, result: petition_result::OK, }); - let (stamped, heard) = handled(&mut app, vec![signed]); - assert!( - matches!( - stamped.as_slice(), - [PetitionEvent::Line(_), PetitionEvent::Closed] - ), - "{stamped:?}" + assert_eq!( + handled(&mut app, vec![signed]), + ["line Signed", "PETITION_CLOSED"] ); - assert_eq!(heard, ["PETITION_CLOSED"]); assert_eq!( handled( &mut app, @@ -179,9 +178,6 @@ fn the_show_and_the_results_fire_on_the_lane_at_their_handlers() { result: petition_result::OK }] ), - ( - vec![PetitionEvent::RegistrarClosed], - vec!["GUILD_REGISTRAR_CLOSED".into()] - ) + ["GUILD_REGISTRAR_CLOSED"] ); } diff --git a/crates/benilla-app/src/lanes/plate_live_tests.rs b/crates/benilla-app/src/lanes/plate_live_tests.rs new file mode 100644 index 000000000..1ed694413 --- /dev/null +++ b/crates/benilla-app/src/lanes/plate_live_tests.rs @@ -0,0 +1,405 @@ +//! The world hover's plate rebuilt inside the packets. `GameTooltip` remembers the unit it shows +//! (`+0x368`, stored at `0x52a070`), and `RefreshTooltipForUnit` (`0x4919d0`) builds it again +//! over that guid from the unit's callbacks: `NotifyUnitNameUpdate` (`0x491a00`) from the name and +//! creature answers (`0x5fb875`, `0x6046d1`) and the entry and `PLAYER_BYTES_3` watchers, ahead of +//! its `UNIT_NAME_UPDATE`, and the unit-flags watcher on the skinnable bit (`0x5ff7be`). So the +//! rebuild runs at the callback's packet, between its neighbours' events, with no anchor script +//! and no `UPDATE_MOUSEOVER_UNIT`, which are the publisher's alone. + +use benilla_protocol::SessionEvent; +use benilla_ui::script::UiScript; +use bevy::prelude::*; + +use super::unit_view_tests::{client, frame, health, values}; + +/// The target [`client`] seats: a creature. +const WOLF: u64 = 0xF130_0000_0044_0001; +/// The template entry the wolf's descriptor names. +const WOLF_ENTRY: u32 = 299; +/// `OBJECT_FIELD_ENTRY`. +const OBJECT_ENTRY: u16 = 3; +/// `UNIT_FLAG_SKINNABLE`. +const SKINNABLE: u32 = 0x0400_0000; + +/// The wolf's answer packet. +fn wolf_named() -> SessionEvent { + SessionEvent::CreatureName { + entry: WOLF_ENTRY, + name: Some("Wolf".into()), + subname: None, + creature_type: Some(1), + pet_family: 0, + rank: 0, + type_flags: 0, + pet_spell_list: 0, + display_id: 0, + civilian: false, + racial_leader: false, + } +} + +/// The client with the wolf naming a template the cache lacks, and `GameTooltip` showing it as +/// `SetUnit("target")` builds it (`0x534a85` → `0x529fe0`). The spy notes each `UNIT_HEALTH` with +/// the plate's lines as its listener reads them, each `UNIT_NAME_UPDATE` likewise, each clear +/// (`OnTooltipCleared`, `0x530263`), each anchor script and each `UPDATE_MOUSEOVER_UNIT`. +fn plate_client() -> App { + let mut app = client(); + let world = app.world_mut(); + let entity = world.resource::().0[&WOLF]; + world + .get_mut::(entity) + .expect("a store") + .0 + .merge(benilla_protocol::ObjectFields::from_pairs(&[( + OBJECT_ENTRY, + WOLF_ENTRY, + )])); + crate::ui_script::test_ui::load_tooltip_template(world.non_send_resource::()); + crate::script_calls::with_hosted_vm(world, |s| { + s.expect("a VM").run( + r#" + UNIT_SKINNABLE = "Skinnable" + CreateFrame("GameTooltip", "GameTooltip", nil, "TestTooltipTemplate") + function Plate() + local t = {} + for i = 1, GameTooltip:NumLines() do + t[i] = getglobal("GameTooltipTextLeft" .. i):GetText() + end + return table.concat(t, " | ") + end + function Look(event, unit) return Plate() end + GameTooltip:SetScript("OnTooltipCleared", function() table.insert(Seen, "cleared") end) + GameTooltip:SetScript("OnTooltipSetDefaultAnchor", function() + table.insert(Seen, "anchor") + GameTooltip:SetOwner(UIParent, "ANCHOR_NONE") + end) + local f = CreateFrame("Frame") + f:RegisterEvent("UNIT_NAME_UPDATE") + f:RegisterEvent("UPDATE_MOUSEOVER_UNIT") + f:SetScript("OnEvent", function() + table.insert(Seen, event .. ":" .. tostring(arg1) .. ":" .. Plate()) + end) + GameTooltip:SetOwner(CreateFrame("Frame"), "ANCHOR_NONE") + GameTooltip:SetUnit("target") + Seen = {} + "#, + ) + }) + .expect("the plate shows the wolf"); + app +} + +/// The creature answer rebuilds the plate at its packet (`0x6046d1` → `0x491a27` → `0x4919f2`), +/// ahead of its `UNIT_NAME_UPDATE`, whose listener reads the new name, and between the health +/// packets around it; nothing re-anchors and no `UPDATE_MOUSEOVER_UNIT` fires. +#[test] +fn a_creature_answer_rebuilds_the_plate_at_its_packet() { + let mut app = plate_client(); + assert_eq!( + frame( + &mut app, + vec![ + values(WOLF, &health(70)), + wolf_named(), + values(WOLF, &health(40)), + ] + ), + [ + "UNIT_HEALTH:target:Unknown Being", + "cleared", + "UNIT_NAME_UPDATE:target:Wolf", + "UNIT_HEALTH:target:Wolf", + ] + ); +} + +/// The unit-flags watcher rebuilds on the skinnable bit alone (`0x5ff7a4`-`0x5ff7be`), with no +/// event: the `UNIT_SKINNABLE` line (`0x52a914`) is there for the next packet's listener. +#[test] +fn the_skinnable_bit_rebuilds_the_plate_at_its_packet() { + let mut app = plate_client(); + let flags = benilla_protocol::field::FIELD_UNIT_FLAGS; + assert_eq!( + frame( + &mut app, + vec![ + values(WOLF, &health(70)), + values(WOLF, &[(flags, SKINNABLE)]), + values(WOLF, &health(40)), + ] + ), + [ + "UNIT_HEALTH:target:Unknown Being", + "cleared", + "UNIT_HEALTH:target:Unknown Being | Skinnable", + ] + ); +} + +/// A plate that no longer shows the unit is not built again: a hide clears the remembered unit +/// (`0x530a6b` → `0x52ffe0` → `0x530050`, `0x5300ad`), which `0x4919dc` compares. A negative +/// control: the frame-time rebuild never reached a hidden plate either, so it passes without the +/// packet rebuilds and guards only against their overreach. +#[test] +fn a_hidden_plate_is_not_rebuilt() { + let mut app = plate_client(); + crate::script_calls::with_hosted_vm(app.world_mut(), |s| { + s.expect("a VM").run("GameTooltip:Hide() Seen = {}") + }) + .expect("hides"); + assert_eq!( + frame(&mut app, vec![wolf_named()]), + ["UNIT_NAME_UPDATE:target:"] + ); +} + +/// A dead player's corpse, its owner [`OWNER`]. +const CORPSE: u64 = 0xF000_0000_0000_0091; +/// The corpse's owner, whose name the cache lacks. +const OWNER: u64 = 0x91; +/// A locked door whose lock opens with the key [`KEY`]. +const DOOR: u64 = 0xF110_0000_0000_0092; +const DOOR_ENTRY: u32 = 5000; +const LOCK: u32 = 77; +/// Key to Searing Gorge, which the item cache lacks. +const KEY: u32 = 5396; + +/// `guid` created as `kind` with `pairs`. +fn object( + guid: u64, + kind: benilla_protocol::EntityKind, + as_type: benilla_protocol::messages::ObjectType, + pairs: &[(u16, u32)], +) -> SessionEvent { + SessionEvent::ObjectCreate { + guid, + kind, + display_id: None, + position: [0.0; 3], + orientation: 0.0, + scale: 1.0, + speeds: None, + mover: None, + transport_progress: None, + transport: None, + spline: None, + fields: benilla_protocol::ObjectFields::from_pairs(pairs).into_created(as_type), + } +} + +/// [`plate_client`] with the corpse and the locked door streamed, the door's record and lock +/// known, a `UIParent`, and the plates' strings. +fn world_client() -> App { + use benilla_protocol::messages::ObjectType; + use benilla_protocol::EntityKind; + let mut app = plate_client(); + let mut data = [0i32; 24]; + data[1] = LOCK as i32; + app.world_mut() + .resource_mut::() + .insert(DOOR_ENTRY, 0, "Gate".into(), &data); + let mut slots = [benilla_formats::LockSlot::default(); benilla_formats::MAX_LOCK_SLOTS]; + slots[0] = benilla_formats::LockSlot { + key_type: benilla_formats::LOCK_KEY_ITEM, + index: KEY, + skill: 0, + action: 1, + }; + app.world_mut().insert_resource(crate::go_templates::Locks( + benilla_formats::LockCatalog::from_rows([(LOCK, slots)]), + )); + frame( + &mut app, + vec![ + object( + CORPSE, + EntityKind::Corpse, + ObjectType::Corpse, + &[(2, 0x81), (6, OWNER as u32), (7, 0)], + ), + object( + DOOR, + EntityKind::GameObject, + ObjectType::GameObject, + &[(2, 0x21), (3, DOOR_ENTRY), (9, 0x2), (14, 1), (21, 0)], + ), + ], + ); + crate::script_calls::with_hosted_vm(app.world_mut(), |s| { + s.expect("a VM").run( + r#" + CreateFrame("Frame", "UIParent") + CORPSE_TOOLTIP = "Corpse of %s" + LOCKED = "Locked" + LOCKED_WITH_ITEM = "Requires %s" + "#, + ) + }) + .expect("seats"); + app +} + +/// This frame's pick, then the hover's drive, as the WorldFrame's update runs (`0x481790`); the +/// spy's notes reset. +fn hover(app: &mut App, pick: crate::target::Hovered, object: crate::target::HoveredObject) { + use bevy::ecs::system::RunSystemOnce; + let world = app.world_mut(); + *world.resource_mut::() = pick; + *world.resource_mut::() = object; + world + .run_system_once(crate::ui_tooltip::drive_mouseover_tooltip) + .expect("the drive runs"); + world + .non_send_resource::() + .run("Seen = {}") + .unwrap(); +} + +/// The corpse plate publishes at the hover with no line while the owner's name is not cached +/// (`0x52af7e`); the name's answer builds it again at its packet through the callback the lookup +/// registered (`0x52afe0` → `0x52aef0`), between the packets around it. +#[test] +fn a_corpse_owners_name_rebuilds_the_plate_at_its_packet() { + let mut app = world_client(); + let corpse = app.world().resource::().0[&CORPSE]; + hover( + &mut app, + crate::target::Hovered { + corpse: Some(corpse), + corpse_guid: Some(CORPSE), + distance: 2.0, + ..Default::default() + }, + crate::target::HoveredObject::default(), + ); + let named = SessionEvent::PlayerName { + guid: OWNER, + name: "Bob".into(), + race: 1, + class: 1, + gender: 0, + }; + assert_eq!( + frame( + &mut app, + vec![values(WOLF, &health(70)), named, values(WOLF, &health(40))] + ), + [ + "UNIT_HEALTH:target:", + "cleared", + "UNIT_HEALTH:target:Corpse of Bob", + ] + ); + // The drive under the same hover builds nothing more (`0x4820b5`). + hover( + &mut app, + crate::target::Hovered { + corpse: Some(corpse), + corpse_guid: Some(CORPSE), + distance: 2.0, + ..Default::default() + }, + crate::target::HoveredObject::default(), + ); + assert_eq!( + crate::script_calls::eval_in_vm::(app.world(), "return Plate()"), + "Corpse of Bob" + ); +} + +/// The door's plate leaves its key line out while the key's record is not cached (`0x52acab`); +/// the record's answer builds it again at its packet through the callback the lookup registered +/// (`0x52ad10` → `0x52aa20`), between the packets around it. +#[test] +fn a_lock_keys_record_rebuilds_the_plate_at_its_packet() { + let mut app = world_client(); + let door = app.world().resource::().0[&DOOR]; + hover( + &mut app, + crate::target::Hovered::default(), + crate::target::HoveredObject { + target: Some(door), + guid: Some(DOOR), + distance: 2.0, + }, + ); + let key = SessionEvent::ItemTemplate { + entry: KEY, + info: Some(Box::new(crate::items::test_template( + "Key to Searing Gorge", + ))), + }; + assert_eq!( + frame( + &mut app, + vec![values(WOLF, &health(70)), key, values(WOLF, &health(40))] + ), + [ + "UNIT_HEALTH:target:Gate | Locked", + "cleared", + "UNIT_HEALTH:target:Gate | Locked | Requires Key to Searing Gorge", + ] + ); +} + +/// A locked door whose record the cache lacks. +const BARE_DOOR: u64 = 0xF110_0000_0000_0093; +const BARE_ENTRY: u32 = 5001; + +/// A locked object whose record has not landed still shows the "Locked" line, which reads the +/// descriptor alone (`GAMEOBJECT_FLAGS` bit 1, `0x52aadc`-`0x52aaea`): no name line (`0x5f8100` +/// gives `""`, `0x5302a9`), and green (`0x52ab3d`), since the resolver finds no record +/// (`0x5f83d0` → `0x5f8418`). The record's answer builds nothing under the hover: its callback +/// (`0x5f78a0` → `0x5f7fb0`) reaches only the type handler. +#[test] +fn a_record_less_locked_object_shows_its_locked_line() { + use benilla_protocol::messages::ObjectType; + use benilla_protocol::EntityKind; + let mut app = world_client(); + frame( + &mut app, + vec![object( + BARE_DOOR, + EntityKind::GameObject, + ObjectType::GameObject, + &[(2, 0x21), (3, BARE_ENTRY), (9, 0x2), (14, 1), (21, 0)], + )], + ); + let door = app.world().resource::().0[&BARE_DOOR]; + hover( + &mut app, + crate::target::Hovered::default(), + crate::target::HoveredObject { + target: Some(door), + guid: Some(BARE_DOOR), + distance: 2.0, + }, + ); + let look = r#" + local r, g, b = GameTooltipTextLeft1:GetTextColor() + local function byte(c) return math.floor(c * 255 + 0.5) end + return Plate() .. " " .. byte(r) .. " " .. byte(g) .. " " .. byte(b) + "#; + assert_eq!( + crate::script_calls::eval_in_vm::(app.world(), look), + "Locked 64 192 64" + ); + let record = SessionEvent::GameObjectInfo { + entry: BARE_ENTRY, + type_id: 0, + display_id: 0, + name: "Gate".into(), + data: [0; 24], + }; + assert_eq!(frame(&mut app, vec![record]), Vec::::new()); + assert_eq!( + app.world() + .resource::() + .name(BARE_ENTRY), + Some("Gate") + ); + assert_eq!( + crate::script_calls::eval_in_vm::(app.world(), "return Plate()"), + "Locked" + ); +} diff --git a/crates/benilla-app/src/lanes/profession_live_tests.rs b/crates/benilla-app/src/lanes/profession_live_tests.rs new file mode 100644 index 000000000..b45d7f27d --- /dev/null +++ b/crates/benilla-app/src/lanes/profession_live_tests.rs @@ -0,0 +1,762 @@ +//! The profession windows open inside the cast that opens them. `TryCastSpell` (`0x6e4b60`) sends +//! nothing for a spell whose first effect is a profession's (`0x6e4bce`): it toggles the window +//! in place, `ToggleTradeSkill` (`0x4fc910` at `0x6e4c22`) or `ToggleCraftWindow` (`0x4f6000` at +//! `0x6e4c34`), whose build and `TRADE_SKILL_SHOW` or `CRAFT_SHOW` signal before the cast returns. +//! So a listener's cast shows the window between its packet's events and the next packet's, and a +//! chunk that opens and closes leaves the window shut. The book's builds and getters read the +//! player, the bags and the item cache as they stand at their call (`0x4fca20`, `0x4fdd40`, +//! `0x4ff7a2`), and the item answers run the lists' callbacks inside their handler +//! (`ItemCacheReceive` `0x55bdb0`: `0x4fdc30`, `0x4fc8e0`, `0x4f7710`). The craft window's do the +//! same (`0x4f60c0`, `0x4f6c10`, `0x4f6cb0`, `0x4f6fe6`, `0x4f74d0`, `0x4f78b0`, `0x4f7a90`). + +use benilla_formats::{ + SlaInfo, SpellDisplay, SPELL_ATTR_IS_TRADESKILL, SPELL_EFFECT_CREATE_ITEM, + SPELL_EFFECT_TRADE_SKILL, +}; +use benilla_ui::script::UiScript; +use bevy::prelude::*; + +use benilla_protocol::field::{FIELD_ITEM_STACK_COUNT, FIELD_PLAYER_INV_SLOT_HEAD}; +use benilla_protocol::messages::{ObjectType, FIELD_PLAYER_SKILL_INFO_1_1}; +use benilla_protocol::{EntityKind, ObjectFields, SessionEvent}; + +use super::unit_view_tests::{client, created, fall, frame, values, wire_packets}; +use crate::ui_craft::CraftOpen; +use crate::ui_tradeskill::{TradeSkillOpen, TradeSkillOpens}; + +/// [`client`]'s fall, as its spy records it. +const FELL: &str = "UNIT_COMBAT:player:100"; +const TAILORING: u32 = 197; +const ENCHANTING: u32 = 333; +/// The Tailoring opener, Bolt of Linen Cloth, the Enchanting opener, and a Minor Health enchant. +const TAILOR: u32 = 3908; +const BOLT: u32 = 2963; +/// Linen Bandage, a Tailoring-line recipe [`crafter`] knows of but has not learned. +const BANDAGE: u32 = 3275; +/// Linen Cloth, Bolt of Linen Cloth's reagent, not cached. +const LINEN: u32 = 2589; +/// [`client`]'s player. +const ME: u64 = 0x7; +const ENCHANT: u32 = 7411; +const MINOR_HEALTH: u32 = 7420; +/// Strange Dust, the enchant's reagent, not cached, and a Runed Copper Rod, its totem, cached. +const DUST: u32 = 10_940; +const ROD: u32 = 6_218; +/// Made-up labels: a Beast Training opener, its one row, the pet spell that row teaches, the pet +/// line that holds it, and a wolf for the pet bar. +const BEASTS: u32 = 90_001; +const BEAST_ROW: u32 = 90_002; +const PET_SPELL: u32 = 90_003; +const BEAST_TRAINING: u32 = 261; +const PET_LINE: u32 = 208; +const WOLF_FAMILY: u32 = 1; +const WOLF_ENTRY: u32 = 299; +const PET: u64 = 0xF140_0000_0000_0042; + +/// [`client`] knowing the Tailoring and Enchanting openers and one recipe of each, Bolt of Linen +/// Cloth's product cached, and the windows' events added to its spy. +fn crafter() -> App { + let mut app = client(); + let opener = |name: &str, misc: i32| SpellDisplay { + name: name.into(), + effects: [SPELL_EFFECT_TRADE_SKILL, 0, 0], + effect_misc_value: [misc, 0, 0], + ..Default::default() + }; + let mut reagents = [(0, 0); 8]; + reagents[0] = (LINEN, 2); + let bolt = SpellDisplay { + name: "Bolt of Linen Cloth".into(), + attributes: SPELL_ATTR_IS_TRADESKILL, + effects: [SPELL_EFFECT_CREATE_ITEM, 0, 0], + effect_item_type: [2996, 0, 0], + reagents, + ..Default::default() + }; + let bandage = SpellDisplay { + name: "Linen Bandage".into(), + attributes: SPELL_ATTR_IS_TRADESKILL, + ..Default::default() + }; + let mut dust = [(0, 0); 8]; + dust[0] = (DUST, 1); + let health = SpellDisplay { + name: "Enchant Chest - Minor Health".into(), + cast_ui: 3, + reagents: dust, + totems: [ROD, 0], + description: Some("Returns you to $z.".into()), + ..Default::default() + }; + // A Beast Training row: `LEARN_SPELL` aimed at the pet (`+0x148` 5). + let beast_row = SpellDisplay { + name: "Growl".into(), + cast_ui: 1, + effects: [benilla_formats::SPELL_EFFECT_LEARN_SPELL, 0, 0], + effect_implicit_target_a: [5, 0, 0], + effect_trigger_spell: [PET_SPELL, 0, 0], + ..Default::default() + }; + let pet_spell = SpellDisplay { + name: "Growl".into(), + spell_level: 4, + ..Default::default() + }; + let sla = |line| SlaInfo { + skill_id: line, + req_skill_value: 1, + forward_spell_id: 0, + trivial_low: 1, + trivial_high: 2, + }; + let world = app.world_mut(); + world.insert_resource(crate::ui_action::Spells { + catalog: benilla_formats::SpellCatalog::from_displays( + [ + (TAILOR, opener("Tailoring", 0)), + (BOLT, bolt), + (BANDAGE, bandage), + (ENCHANT, opener("Enchanting", 3)), + (MINOR_HEALTH, health), + (BEASTS, opener("Beast Training", 1)), + (BEAST_ROW, beast_row), + (PET_SPELL, pet_spell), + ] + .into(), + ), + ..crate::ui_action::Spells::empty_for_tests() + }); + world.insert_resource(crate::ui_spellbook::SkillLines { + catalog: benilla_formats::SkillLineCatalog::from_abilities([ + (TAILOR, sla(TAILORING)), + (BOLT, sla(TAILORING)), + (BANDAGE, sla(TAILORING)), + (ENCHANT, sla(ENCHANTING)), + (MINOR_HEALTH, sla(ENCHANTING)), + (BEASTS, sla(BEAST_TRAINING)), + (BEAST_ROW, sla(BEAST_TRAINING)), + ]) + .with_line_names([(TAILORING, "Tailoring"), (ENCHANTING, "Enchanting")]) + .with_line_abilities([( + PET_LINE, + PET_SPELL, + benilla_formats::LineAbility { + superseded_by: 0, + train_points: 5, + }, + )]), + }); + { + let mut actions = world.resource_mut::(); + actions + .spells + .extend([TAILOR, BOLT, ENCHANT, MINOR_HEALTH, BEASTS, BEAST_ROW]); + actions.profession_order.push(BOLT); + actions.craft_order.extend([MINOR_HEALTH, BEAST_ROW]); + } + let mut items = world.resource_mut::(); + items.insert_template( + 2996, + Some(crate::items::test_template("Bolt of Linen Cloth")), + ); + items.insert_template(ROD, Some(crate::items::test_template("Runed Copper Rod"))); + world + .non_send_resource::() + .run( + r#" + local f = CreateFrame("Frame") + for _, e in ipairs({"TRADE_SKILL_SHOW", "TRADE_SKILL_UPDATE", "TRADE_SKILL_CLOSE", + "CRAFT_SHOW", "CRAFT_UPDATE", "CRAFT_CLOSE"}) do + f:RegisterEvent(e) + end + f:SetScript("OnEvent", function() table.insert(Seen, event) end) + "#, + ) + .unwrap(); + app +} + +/// `chunk` with the host lent, and what the spy saw. +fn hosted(app: &mut App, chunk: &str) -> Vec { + crate::script_calls::with_hosted_vm(app.world_mut(), |s| { + s.expect("a VM").run(chunk).expect("the chunk runs") + }); + let s = app.world_mut().non_send_resource_mut::(); + let seen = s.eval::>("return Seen").unwrap(); + s.run("Seen = {}").unwrap(); + seen +} + +/// A fall's listener casts the Tailoring opener: the book builds and shows inside that cast, so +/// its `TRADE_SKILL_UPDATE` (`0x4fd164`) and `TRADE_SKILL_SHOW` (`0x4fc99f`) fire between the +/// first fall's event and the second's, and the line is open there. +#[test] +fn an_openers_show_fires_between_its_packets_neighbours() { + let mut app = crafter(); + app.world() + .non_send_resource::() + .run( + r#" + local f = CreateFrame("Frame") + f:RegisterEvent("UNIT_COMBAT") + f:SetScript("OnEvent", function() + if not Cast then Cast = true CastSpellByName("Tailoring") end + end) + "#, + ) + .unwrap(); + assert_eq!( + frame(&mut app, vec![fall(5), fall(6)]), + [FELL, "TRADE_SKILL_UPDATE", "TRADE_SKILL_SHOW", FELL] + ); + assert_eq!( + app.world().resource::().line, + Some(TAILORING) + ); +} + +/// A chunk that casts an opener and closes its window leaves both shut: each opener toggles and +/// signals in its cast (`0x4fc910`, `0x4f6000`), each close in its call (`0x4fc870`, `0x4f5fe0`), +/// so the engine, the VM and the opener queue agree once the chunk returns. +#[test] +fn a_chunk_that_opens_and_closes_leaves_no_window_open() { + let mut app = crafter(); + assert_eq!( + hosted( + &mut app, + r#"CastSpellByName("Tailoring") CloseTradeSkill() + CastSpellByName("Enchanting") CloseCraft()"# + ), + [ + "TRADE_SKILL_UPDATE", + "TRADE_SKILL_SHOW", + "TRADE_SKILL_CLOSE", + "CRAFT_UPDATE", + "CRAFT_SHOW", + "CRAFT_CLOSE", + ] + ); + let world = app.world(); + assert!(world.resource::().0.is_empty()); + assert_eq!(world.resource::().line, None); + assert_eq!(world.resource::().line, None); + let script = world.non_send_resource::(); + assert!(!script.trade_skill_open() && !script.craft_open()); +} + +/// The player's first skill slot holding Tailoring at `value` of 75 (`PLAYER_SKILL_INFO_1_1`). +fn tailoring(value: u32) -> SessionEvent { + values( + ME, + &[ + (FIELD_PLAYER_SKILL_INFO_1_1, TAILORING), + (FIELD_PLAYER_SKILL_INFO_1_1 + 1, (75 << 16) | value), + ], + ) +} + +/// `chunk` run with the host lent, its spy's record dropped. +fn quietly(app: &mut App, chunk: &str) { + hosted(app, chunk); +} + +/// A fall's listener reads `GetTradeSkillLine` at its call (`0x4fdd40` finds the slot at +/// `0x4fddb6` and reads its words): between a packet that raises the rank to 5 and one that raises +/// it to 6, it reads 5, its own place's rank, where the book's last build held another. +#[test] +fn the_line_getter_reads_the_rank_its_packet_left() { + let mut app = crafter(); + quietly(&mut app, r#"CastSpellByName("Tailoring")"#); + app.world() + .non_send_resource::() + .run( + r#" + local f = CreateFrame("Frame") + f:RegisterEvent("UNIT_COMBAT") + f:SetScript("OnEvent", function() + local _, rank, max = GetTradeSkillLine() + table.insert(Seen, "rank:" .. rank .. "/" .. max) + end) + "#, + ) + .unwrap(); + let seen = frame(&mut app, vec![tailoring(5), fall(5), tailoring(6)]); + let ranks: Vec<&String> = seen.iter().filter(|e| e.starts_with("rank:")).collect(); + assert_eq!(ranks, ["rank:5/75"], "{seen:?}"); +} + +/// A reagent's record answer runs the callback `GetTradeSkillReagentInfo`'s miss kept +/// (`0x4ff6cd` with `0x4fdc30`) inside its handler, whose rebuild signals `TRADE_SKILL_UPDATE` +/// (`0x4fdc3c` → `0x4fd164`) between the packets around it, and the getter then reads the record. +#[test] +fn a_reagents_record_answer_signals_the_update_at_its_packet() { + let mut app = crafter(); + quietly(&mut app, r#"CastSpellByName("Tailoring")"#); + let bolt_row = r#" + local row + for i = 1, GetNumTradeSkills() do + if GetTradeSkillInfo(i) == "Bolt of Linen Cloth" then row = i end + end + "#; + quietly( + &mut app, + &format!("{bolt_row} Missed = (GetTradeSkillReagentInfo(row, 1)) == nil"), + ); + assert!(app + .world() + .non_send_resource::() + .eval::("return Missed") + .unwrap()); + let answer = SessionEvent::ItemTemplate { + entry: LINEN, + info: Some(Box::new(crate::items::test_template("Linen Cloth"))), + }; + assert_eq!( + frame(&mut app, vec![fall(5), answer, fall(6)]), + [FELL, "TRADE_SKILL_UPDATE", FELL] + ); + let name = crate::script_calls::with_hosted_vm(app.world_mut(), |s| { + s.expect("a VM").eval::(&format!( + "{bolt_row} return (GetTradeSkillReagentInfo(row, 1))" + )) + }) + .unwrap(); + assert_eq!(name, "Linen Cloth"); +} + +/// A learn inside an open book rebuilds it with flag 1 at its packet (`0x5e9d79`), reading the +/// line's list as the learn left it (`0x5e9d72`) and banding the new recipe on the rank as it +/// stands there (`0x4fcc28`-`0x4fcc41`): with no Tailoring slot yet it reads `optimal`, though a +/// later packet of the frame raises the rank past its trivial mark. +#[test] +fn a_learn_inside_an_open_book_bands_its_recipe_at_its_packet() { + let mut app = crafter(); + quietly(&mut app, r#"CastSpellByName("Tailoring")"#); + app.world() + .non_send_resource::() + .run( + r#" + local f = CreateFrame("Frame") + f:RegisterEvent("TRADE_SKILL_UPDATE") + f:SetScript("OnEvent", function() + for i = 1, GetNumTradeSkills() do + local name, kind = GetTradeSkillInfo(i) + if name == "Linen Bandage" then table.insert(Seen, "band:" .. kind) end + end + end) + "#, + ) + .unwrap(); + let seen = frame( + &mut app, + vec![ + fall(5), + SessionEvent::SpellLearned { spell_id: BANDAGE }, + tailoring(5), + fall(6), + ], + ); + let bands: Vec<&String> = seen.iter().filter(|e| e.starts_with("band:")).collect(); + assert_eq!( + bands.first().map(|b| b.as_str()), + Some("band:optimal"), + "{seen:?}" + ); +} + +/// A build that finds no player (the lookup `0x468460` at `0x4fcb11`) has zeroed the full count +/// first (`0x4fca52`) and leaves past its signal (`0x4fcb1b` → `0x4fd170`): a reagent's answer +/// while our player is gone, as a world transfer leaves it, empties the book and signals nothing. +#[test] +fn a_build_with_no_player_empties_the_book_silently() { + let mut app = crafter(); + quietly(&mut app, r#"CastSpellByName("Tailoring")"#); + quietly( + &mut app, + r#"for i = 1, GetNumTradeSkills() do GetTradeSkillReagentInfo(i, 1) end"#, + ); + let me = app.world().resource::().0[&ME]; + app.world_mut() + .entity_mut(me) + .remove::(); + let answer = SessionEvent::ItemTemplate { + entry: LINEN, + info: Some(Box::new(crate::items::test_template("Linen Cloth"))), + }; + let seen = frame(&mut app, vec![fall(5), answer, fall(6)]); + assert!(!seen.iter().any(|e| e == "TRADE_SKILL_UPDATE"), "{seen:?}"); + let first = app + .world() + .non_send_resource::() + .eval::>("return (GetTradeSkillInfo(1))") + .unwrap(); + assert_eq!(first, None, "the rows are gone"); +} + +/// A `/reload` with a product's record in flight: the open's build kept the callback `0x4fc8e0` +/// in the item cache, which outlives the VM, so the record's answer rebuilds the book with flag 1 +/// into the new interface at its packet (`0x4fc8fb`, `0x4fc900`), which then lists it. +#[test] +fn a_products_record_answer_rebuilds_the_book_after_a_reload() { + let mut app = crafter(); + app.world_mut() + .resource_mut::() + .forget_templates(); + assert_eq!( + hosted(&mut app, r#"CastSpellByName("Tailoring")"#), + ["TRADE_SKILL_SHOW"], + "the pending build signals no update" + ); + // The reload: a new VM, seeded and entered as the load and the cascade do. + let mut script = UiScript::new().unwrap(); + crate::ui_tradeskill::seed_repeat(app.world(), &mut script); + script.reset_crafts_on_world_enter(); + script + .run( + r#" + Seen = {} + local f = CreateFrame("Frame") + for _, e in ipairs({"UNIT_COMBAT", "TRADE_SKILL_UPDATE"}) do f:RegisterEvent(e) end + f:SetScript("OnEvent", function() table.insert(Seen, event) end) + "#, + ) + .unwrap(); + app.world_mut().insert_non_send_resource(script); + let answer = SessionEvent::ItemTemplate { + entry: 2996, + info: Some(Box::new(crate::items::test_template("Bolt of Linen Cloth"))), + }; + assert_eq!( + frame(&mut app, vec![fall(5), answer, fall(6)]), + ["UNIT_COMBAT", "TRADE_SKILL_UPDATE", "UNIT_COMBAT"] + ); + let rows = app + .world() + .non_send_resource::() + .eval::("return GetNumTradeSkills()") + .unwrap(); + assert!(rows > 0, "{rows}"); +} + +/// A fall's listener that records `expr`'s answer at its call as `tag:answer`. +fn listen(app: &mut App, tag: &str, expr: &str) { + app.world() + .non_send_resource::() + .run(&format!( + r#" + local f = CreateFrame("Frame") + f:RegisterEvent("UNIT_COMBAT") + f:SetScript("OnEvent", function() + table.insert(Seen, "{tag}:" .. tostring({expr})) + end) + "# + )) + .unwrap(); +} + +/// What `seen` recorded under `tag`. +fn tagged<'a>(seen: &'a [String], tag: &str) -> Vec<&'a str> { + seen.iter() + .map(String::as_str) + .filter(|e| e.strip_prefix(tag).is_some_and(|r| r.starts_with(':'))) + .collect() +} + +/// The player's first skill slot holding Enchanting at `value` of 75. +fn enchanting(value: u32) -> SessionEvent { + values( + ME, + &[ + (FIELD_PLAYER_SKILL_INFO_1_1, ENCHANTING), + (FIELD_PLAYER_SKILL_INFO_1_1 + 1, (75 << 16) | value), + ], + ) +} + +/// `expr`'s answer as a string, read with the host lent. +fn read(app: &mut App, expr: &str) -> String { + crate::script_calls::with_hosted_vm(app.world_mut(), |s| { + s.expect("a VM") + .eval::(&format!("return tostring({expr})")) + }) + .unwrap() +} + +/// `packets` through their handlers, each one packet, with no frame: the world as they leave it. +fn handle(app: &mut App, packets: Vec>) { + crate::net::handlers::dispatch(app.world_mut(), wire_packets(packets)); +} + +/// `GetCraftName` reads the player's effect slot of the open type at its call (`0x4f6c3b` → +/// `0x5ea360`): a learn of the Enchanting opener writes slot 3 inside its handler (`0x5e9e1c`- +/// `0x5e9e36`), and the next call reads its name, with no frame between to push it. +#[test] +fn the_craft_name_reads_the_effect_slot_at_its_call() { + let mut app = crafter(); + quietly(&mut app, r#"CastSpellByName("Enchanting")"#); + assert_eq!(read(&mut app, "GetCraftName()"), "nil"); + handle( + &mut app, + vec![vec![SessionEvent::SpellLearned { spell_id: ENCHANT }]], + ); + assert_eq!(read(&mut app, "GetCraftName()"), "Enchanting"); +} + +/// `GetCraftDisplaySkillLine` finds its slot and reads its words at the call (`0x4f6d52`, +/// `0x4f6d99`, `0x4f6e08`): between a packet that raises Enchanting to 5 and one that raises it to +/// 6, it reads 5, where the open's build held none. +#[test] +fn the_display_line_reads_the_rank_its_packet_left() { + let mut app = crafter(); + quietly(&mut app, r#"CastSpellByName("Enchanting")"#); + listen( + &mut app, + "rank", + "(function() local n, r, m = GetCraftDisplaySkillLine() return n .. r .. '/' .. m end)()", + ); + let seen = frame(&mut app, vec![enchanting(5), fall(5), enchanting(6)]); + assert_eq!(tagged(&seen, "rank"), ["rank:Enchanting5/75"], "{seen:?}"); +} + +/// An item of `entry` at `guid`, `stack` of it, ours. +fn item(guid: u64, entry: u32, stack: u32) -> SessionEvent { + SessionEvent::ItemCreate { + guid, + container: false, + fields: ObjectFields::from_pairs(&[ + (2, 0x3), + (3, entry), + (6, ME as u32), + (8, ME as u32), + (FIELD_ITEM_STACK_COUNT, stack), + ]) + .into_created(ObjectType::Item), + } +} + +/// `GetCraftReagentInfo` counts the reagent in the bags at its call (`0x4f76b2` → `0x622130`) and +/// `GetCraftSpellFocus` asks whether they hold the totem at its call (`0x4f7a3c` → `0x622270`): +/// a fall ahead of the packets that bring both reads none, one behind them both, where the open's +/// build counted none. +#[test] +fn the_craft_counts_read_the_bags_their_packet_left() { + const DUST_ITEM: u64 = 0x4000_0000_0000_0001; + const ROD_ITEM: u64 = 0x4000_0000_0000_0002; + let mut app = crafter(); + quietly(&mut app, r#"CastSpellByName("Enchanting")"#); + listen( + &mut app, + "count", + "(function() local _, _, _, have = GetCraftReagentInfo(1, 1) \ + local _, tool = GetCraftSpellFocus(1) return have .. '/' .. tostring(tool) end)()", + ); + // The first two backpack slots (`PLAYER_FIELD_PACK_SLOT_1`, inventory slots 23 and 24). + let seat = |slot: u16, guid: u64| { + let field = FIELD_PLAYER_INV_SLOT_HEAD + 2 * slot; + [(field, guid as u32), (field + 1, (guid >> 32) as u32)] + }; + let seen = frame( + &mut app, + vec![ + fall(5), + item(DUST_ITEM, DUST, 2), + item(ROD_ITEM, ROD, 1), + values(ME, &[seat(23, DUST_ITEM), seat(24, ROD_ITEM)].concat()), + fall(6), + ], + ); + assert_eq!( + tagged(&seen, "count"), + ["count:0/nil", "count:2/1"], + "{seen:?}" + ); +} + +/// `GetCraftInfo`'s cost and level read the pet bar's unit at the call (`0xb714a0` at `0x4f6fe6`, +/// `0x468460` at `0x4f7010`): before the packet that brings the wolf, 0 and 0; after its handler, +/// with no frame or rebuild between, its line's training points (`+0x38`, `0x4f704b`) and the +/// taught spell's level (`0x60c840`). +#[test] +fn the_craft_cost_reads_the_pet_at_its_call() { + let mut app = crafter(); + { + let world = app.world_mut(); + world.insert_resource(crate::ui_pet_stats::PetFamilyTables { + families: benilla_formats::CreatureFamilies::from_skill_lines([( + WOLF_FAMILY, + [PET_LINE, 0], + )]), + foods: Default::default(), + }); + world + .resource_mut::() + .insert_creature( + WOLF_ENTRY, + Some(crate::names::CreatureRecord { + name: "Wolf".into(), + subname: None, + creature_type: 1, + pet_family: WOLF_FAMILY, + rank: 0, + type_flags: 0, + pet_spell_list: 0, + civilian: false, + racial_leader: false, + display_id: 0, + }), + ); + world + .resource_mut::() + .spells + .pet_guid = PET; + } + quietly(&mut app, r#"CastSpellByName("Beast Training")"#); + let cost = + "(function() local _, _, _, _, _, tp, l = GetCraftInfo(1) return tp .. '/' .. l end)()"; + assert_eq!(read(&mut app, cost), "0/0"); + handle( + &mut app, + vec![vec![created(PET, EntityKind::Unit, &[(3, WOLF_ENTRY)])]], + ); + assert_eq!(read(&mut app, cost), "5/4"); +} + +/// `GetCraftDescription` expands the row's text at its call (`0x4f7b53` → `0x5075f0`), whose `$z` +/// reads the bind point there (`0x5ed420` at `0x507f07`) and the `HOME_INN` template from the VM's +/// strings without one (`0x507f3a`): the inn before the bind point's packet, the area after its +/// handler, with no frame between; a rewrite of the template reaches the next call. +#[test] +fn the_craft_description_reads_the_bind_point_at_its_call() { + let mut app = crafter(); + app.insert_resource(crate::ui_quest_log::QuestHeaderNamesRes( + benilla_formats::QuestHeaderNames::from_zones([(12, "Elwynn Forest")]), + )); + app.world() + .non_send_resource::() + .run("HOME_INN = 'your inn'") + .unwrap(); + quietly(&mut app, r#"CastSpellByName("Enchanting")"#); + let desc = "GetCraftDescription(1)"; + assert_eq!(read(&mut app, desc), "Returns you to your inn."); + quietly(&mut app, "HOME_INN = 'the inn'"); + assert_eq!(read(&mut app, desc), "Returns you to the inn."); + handle(&mut app, vec![vec![SessionEvent::BindPoint { area: 12 }]]); + assert_eq!(read(&mut app, desc), "Returns you to Elwynn Forest."); +} + +/// `SMSG_PET_SPELLS` rebuilds the open craft list inside its handler (`0x4bdafa` → `0x4f60c0`), +/// whose build bands each row on the skill as it stands there (`0x4f620e` → `0x5ea520`, +/// `0x4f6215`-`0x4f6267`) and signals `CRAFT_UPDATE` at its tail (`0x4f661a`): between the falls +/// around it, its listener reads the band the rank before it gives, not the open's. +#[test] +fn a_pet_book_rebuilds_the_craft_list_at_its_packet() { + let mut app = crafter(); + quietly(&mut app, r#"CastSpellByName("Enchanting")"#); + app.world() + .non_send_resource::() + .run( + r#" + local f = CreateFrame("Frame") + f:RegisterEvent("CRAFT_UPDATE") + f:SetScript("OnEvent", function() + local _, _, kind = GetCraftInfo(1) + table.insert(Seen, "kind:" .. kind) + end) + "#, + ) + .unwrap(); + let seen = frame( + &mut app, + vec![ + fall(5), + enchanting(5), + SessionEvent::PetSpells(Box::default()), + fall(6), + ], + ); + let craft: Vec<&String> = seen + .iter() + .filter(|e| *e == FELL || e.starts_with("CRAFT") || e.starts_with("kind:")) + .collect(); + assert_eq!( + craft, + [FELL, "CRAFT_UPDATE", "kind:trivial", FELL], + "{seen:?}" + ); +} + +/// A craft build that finds no player (the lookup `0x468460` at `0x4f60ff`) has zeroed the counts +/// first (`0x4f60d1`-`0x4f60dd`) and leaves past its signal (`0x4f6109` → `0x4f661f`): a reagent's +/// answer while our player is gone runs the callback `0x4f7710` (`0x4f771a`), which empties the +/// list and signals nothing. +#[test] +fn a_craft_build_with_no_player_empties_the_list_silently() { + let mut app = crafter(); + quietly(&mut app, r#"CastSpellByName("Enchanting")"#); + quietly(&mut app, "GetCraftReagentInfo(1, 1)"); + let me = app.world().resource::().0[&ME]; + app.world_mut() + .entity_mut(me) + .remove::(); + let answer = SessionEvent::ItemTemplate { + entry: DUST, + info: Some(Box::new(crate::items::test_template("Strange Dust"))), + }; + let seen = frame(&mut app, vec![fall(5), answer, fall(6)]); + assert!(!seen.iter().any(|e| e == "CRAFT_UPDATE"), "{seen:?}"); + let script = app.world().non_send_resource::(); + assert_eq!(script.eval::("return GetNumCrafts()").unwrap(), 0); + assert_eq!( + script + .eval::>("return (GetCraftInfo(1))") + .unwrap(), + None, + "the rows are gone" + ); +} + +/// With our player in place, the same answer's callback rebuilds the list at its packet and +/// signals `CRAFT_UPDATE` between the falls around it (`0x4f771a` → `0x4f661a`), and the getter +/// then reads the record. +#[test] +fn a_craft_reagents_record_answer_signals_the_update_at_its_packet() { + let mut app = crafter(); + quietly(&mut app, r#"CastSpellByName("Enchanting")"#); + quietly(&mut app, "GetCraftReagentInfo(1, 1)"); + let answer = SessionEvent::ItemTemplate { + entry: DUST, + info: Some(Box::new(crate::items::test_template("Strange Dust"))), + }; + assert_eq!( + frame(&mut app, vec![fall(5), answer, fall(6)]), + [FELL, "CRAFT_UPDATE", FELL] + ); + let name = crate::script_calls::with_hosted_vm(app.world_mut(), |s| { + s.expect("a VM") + .eval::("return (GetCraftReagentInfo(1, 1))") + }) + .unwrap(); + assert_eq!(name, "Strange Dust"); +} + +/// Another player's visible item rebuilds both open lists (`0x5e2810` → `0x5dee30`: `0x4fca20(0)` +/// at `0x5dee70`, `0x4f60c0` at `0x5dee75`), ahead of its test for the active player +/// (`0x5dee82`), so each window's update fires at that player's packet. +#[test] +fn another_players_visible_item_rebuilds_the_open_lists() { + const OTHER: u64 = 0x9; + let mut app = crafter(); + quietly( + &mut app, + r#"CastSpellByName("Tailoring") CastSpellByName("Enchanting")"#, + ); + let entry = benilla_protocol::field::FIELD_PLAYER_VISIBLE_ITEM_1_CREATOR + 2; + frame( + &mut app, + vec![created(OTHER, EntityKind::Player, &[(entry, 2996)])], + ); + assert_eq!( + frame(&mut app, vec![values(OTHER, &[(entry, 2589)])]), + ["TRADE_SKILL_UPDATE", "CRAFT_UPDATE"] + ); +} diff --git a/crates/benilla-app/src/lanes/quest_log_live_tests.rs b/crates/benilla-app/src/lanes/quest_log_live_tests.rs index 021480863..d9c93fd35 100644 --- a/crates/benilla-app/src/lanes/quest_log_live_tests.rs +++ b/crates/benilla-app/src/lanes/quest_log_live_tests.rs @@ -14,7 +14,7 @@ use benilla_protocol::messages::{ QuestDetails, QuestGiverList, QuestListEntry, QuestRequestItems, QuestRewardItem, }; use benilla_protocol::{EntityKind, ObjectFields, SessionEvent}; -use benilla_ui::script::{QuestPanel, UiScript}; +use benilla_ui::script::UiScript; use bevy::prelude::*; use crossbeam_channel::{Receiver, Sender}; @@ -300,8 +300,8 @@ fn a_lines_count_is_the_slots_at_the_call() { ); assert_eq!( c.eval::(false, line), - "Timber Wolf slain: 3/3|monster|1", - "with no host the copy answers" + "... slain: 3/3|monster|1", + "with no host the copies answer, and the VM holds no creature name" ); } @@ -383,6 +383,111 @@ fn the_logs_events_fire_at_their_packets_places() { ); } +/// The client with quest 52 in slot 1, selected, whose text reads world state 2000 and the +/// player's name, and a listener that notes `GetQuestLogQuestText` at each `QUEST_LOG_UPDATE`. +fn holding_a_macro_quest() -> Client { + let mut c = client(); + let mut t = crate::ui_quest::test_template(52, "Hold the Line", 0); + t.details = "Hold for $2000w waves, $N.".into(); + t.objectives_text = "$2000W left.".into(); + let world = c.app.world_mut(); + world + .resource_mut::() + .insert_template(t); + world + .resource_mut::() + .insert_player(ME, "Tri".into(), None); + c.frame(vec![vec![SessionEvent::ObjectValues { + guid: ME, + fields: ObjectFields::from_pairs(&[(FIELD_PLAYER_QUEST_LOG_1_1 + 3, 52)]), + }]]); + c.frame(vec![]); + c.eval::<()>( + false, + r#"for i = 1, GetNumQuestLogEntries() do + if GetQuestLogTitle(i) == "Hold the Line" then SelectQuestLogEntry(i) end + end + Texts = {} + local g = CreateFrame("Frame") + g:RegisterEvent("QUEST_LOG_UPDATE") + g:SetScript("OnEvent", function() + local d, o = GetQuestLogQuestText() + table.insert(Texts, tostring(d) .. "|" .. tostring(o)) + end)"#, + ); + c.seen(); + c +} + +fn texts_seen(c: &mut Client) -> Vec { + c.eval(false, "local t = Texts Texts = {} return t") +} + +fn world_state(value: u32) -> SessionEvent { + SessionEvent::WorldStates { + scope: None, + states: vec![(2000, value)], + } +} + +/// `GetQuestLogQuestText` expands its text's `$` macros at the call (`0x4dff89`, `0x4dffae` → +/// `0x506f70`): a listener fired at a packet, with the packets after it not yet in, reads the +/// world state and the name as its packet left them, not as a push before it did. +#[test] +fn a_quest_log_listener_reads_its_packets_quest_text() { + let mut c = holding_a_macro_quest(); + for value in [3, 7] { + let world = c.app.world_mut(); + crate::net::handlers::dispatch(world, vec![world_state(value)]); + crate::net::handlers::dispatch(world, sync()); + crate::lanes::fire_in_order(world); + assert_eq!( + texts_seen(&mut c), + [format!("Hold for {value} waves, Tri.|{value} left.")] + ); + } + let world = c.app.world_mut(); + world + .resource_mut::() + .insert_player(ME, "Tria".into(), None); + crate::net::handlers::dispatch(world, sync()); + crate::lanes::fire_in_order(world); + assert_eq!(texts_seen(&mut c), ["Hold for 7 waves, Tria.|7 left."]); +} + +/// The quest-slot watcher's accept line shows inside the update packet that filled the slot +/// (`0x5ddd80`, `0x5dde66`), at its place: a later packet of the same frame that empties the slot +/// again takes nothing back. The line's listener reads the log as it stood when the slot's watcher +/// ran, ahead of the log's own watcher on the same block (`0x4de430`), so without the quest. +#[test] +fn the_accept_line_shows_at_the_packet_that_fills_the_slot() { + let mut c = client(); + c.app + .world_mut() + .resource_mut::() + .insert_template(crate::ui_quest::test_template(51, "Kobolds", 0)); + c.eval::<()>( + false, + r#"ERR_QUEST_ACCEPTED_S = "Quest accepted: %s" + Lines = {} + local g = CreateFrame("Frame") + g:RegisterEvent("CHAT_MSG_SYSTEM") + g:SetScript("OnEvent", function() + local _, n = GetNumQuestLogEntries() + table.insert(Lines, arg1 .. "|" .. n) + end)"#, + ); + let slot = |quest: u32| { + vec![SessionEvent::ObjectValues { + guid: ME, + fields: ObjectFields::from_pairs(&[(FIELD_PLAYER_QUEST_LOG_1_1 + 3, quest)]), + }] + }; + c.frame(vec![slot(51), slot(0)]); + let lines: Vec = c.eval(false, "local l = Lines Lines = {} return l"); + assert_eq!(lines, ["Quest accepted: Kobolds|1"]); +} + /// The client with a second quest in slot 1 whose record is not cached, so the rebuild awaits it, /// and a listener that notes the log's row count at each `QUEST_LOG_UPDATE`. fn awaiting_a_record() -> Client { @@ -616,9 +721,9 @@ fn the_giver_getters_read_the_panel_cells_at_the_call() { ); } -/// A panel's event sits on the questgiver lane at its handler's place and fires there, and a -/// refusal's close in the same frame runs behind it: `QUEST_DETAIL`, the line, then -/// `QUEST_FINISHED` (`0x5dbd50`, `0x5dbca0`, `0x501217`). +/// A panel's event fires inside its packet's dispatch, and a refusal's close in a later packet +/// runs behind it: `QUEST_DETAIL`, the line, then `QUEST_FINISHED` (`0x5dbd50`, `0x5dbca0`, +/// `0x501217`). #[test] fn a_panel_and_its_refusal_fire_on_the_lane_at_their_packets() { let mut c = client(); @@ -633,32 +738,19 @@ fn a_panel_and_its_refusal_fire_on_the_lane_at_their_packets() { f:SetScript("OnEvent", function() table.insert(Seen, event) end) "#, ); - let before = crate::lanes::stamp(); crate::net::handlers::dispatch(c.app.world_mut(), vec![detail()]); - let after = crate::lanes::stamp(); - let stamped = c + assert!(c .app .world() .resource::() - .stamped(); - assert!( - matches!( - stamped.as_slice(), - [(at, crate::ui_quest::QuestGiverEvent::Panel(QuestPanel::Detail, GIVER))] - if before < *at && *at < after - ), - "stamped inside the handler: {stamped:?}" - ); + .stamped() + .is_empty()); + assert_eq!(c.seen(), ["QUEST_DETAIL"], "inside the panel's dispatch"); crate::net::handlers::dispatch( c.app.world_mut(), vec![SessionEvent::QuestGiverInvalid { reason: 13 }], ); - assert!(c.seen().is_empty(), "nothing fires ahead of the drain"); - crate::lanes::fire_in_order(c.app.world_mut()); - assert_eq!( - c.seen(), - ["QUEST_DETAIL", "CHAT_MSG_SYSTEM", "QUEST_FINISHED"] - ); + assert_eq!(c.seen(), ["CHAT_MSG_SYSTEM", "QUEST_FINISHED"]); } /// A panel's event fires once per panel, and the giver's name, which the frame looks up with a diff --git a/crates/benilla-app/src/lanes/record_callback_tests.rs b/crates/benilla-app/src/lanes/record_callback_tests.rs new file mode 100644 index 000000000..1400ec84c --- /dev/null +++ b/crates/benilla-app/src/lanes/record_callback_tests.rs @@ -0,0 +1,432 @@ +//! What an item record's answer runs, at its packet's place. `SMSG_ITEM_QUERY_SINGLE_RESPONSE`'s +//! handler (`0x555140`) calls `ItemCacheReceive` (`0x55bdb0`), which stores the record +//! (`0x55bef6`, `0x55befb`) and then runs every callback the lookups that missed it registered +//! (`0x55bf12`-`0x55bf39`), inside the handler: the equip callbacks (`0x5e17a0`, `0x5e1020`) send +//! there, ahead of a later packet's, and the quest log's (`0x4e0830`) and the tooltips' +//! (`0x52e530`, `0x52f820`) fire and rebuild between the frame's neighbouring packets. + +use benilla_protocol::field::{FIELD_ITEM_STACK_COUNT, FIELD_PLAYER_INV_SLOT_HEAD}; +use benilla_protocol::messages::ObjectType; +use benilla_protocol::{ObjectFields, SessionEvent}; +use benilla_ui::script::UiScript; +use bevy::prelude::*; +use crossbeam_channel::Receiver; + +use super::unit_view_tests::{client, fall, frame, values}; +use crate::net::ClientCommand; + +/// [`client`]'s player. +const ME: u64 = 0x7; +/// A fall's `UNIT_COMBAT`, as [`client`]'s spy records it. +const FELL: &str = "UNIT_COMBAT:player:100"; +/// Our item in backpack slot 1, whose record the cache has not seen. +const HELM: u64 = (benilla_protocol::guid::HIGH_ITEM as u64) << 48 | 0x31; +const HELM_ENTRY: u32 = 4_242; +/// The duel flag's guid of our own challenge, which the request's handler accepts at once +/// (`0x4d4a12`). +const ARBITER: u64 = 0xF110_0000_0000_0055; + +/// [`client`] with our helm in backpack slot 1 and its record in flight, cursor control, and the +/// sends kept. +fn holding_client() -> (App, Receiver) { + let mut app = client(); + let (tx, rx) = crossbeam_channel::unbounded(); + app.insert_resource(crate::net::NetCommands(tx)); + let helm = SessionEvent::ItemCreate { + guid: HELM, + container: false, + fields: ObjectFields::from_pairs(&[ + (2, 0x3), + (3, HELM_ENTRY), + (6, ME as u32), + (8, ME as u32), + (FIELD_ITEM_STACK_COUNT, 1), + ]) + .into_created(ObjectType::Item), + }; + let seat = FIELD_PLAYER_INV_SLOT_HEAD + 2 * 23; + frame( + &mut app, + vec![ + helm, + values(ME, &[(seat, HELM as u32), (seat + 1, (HELM >> 32) as u32)]), + ], + ); + app.world_mut() + .non_send_resource_mut::() + .set_player_control(true); + (app, rx) +} + +/// `chunk` with the host lent. +fn hosted(app: &mut App, chunk: &str) { + crate::script_calls::with_hosted_vm(app.world_mut(), |s| { + s.expect("a VM").run(chunk).expect("the chunk runs") + }); +} + +/// The helm's record: plain, no bind on equip, so the replay sends. +fn helm_record() -> SessionEvent { + let mut t = crate::items::test_template("Plain Helm"); + (t.class, t.inventory_type) = (4, 1); + SessionEvent::ItemTemplate { + entry: HELM_ENTRY, + info: Some(Box::new(t)), + } +} + +/// A duel request we made, whose handler sends `CMSG_DUEL_ACCEPTED` at once. +fn our_duel() -> SessionEvent { + SessionEvent::DuelRequested { + arbiter: ARBITER, + challenger: ME, + } +} + +/// The equip and move sends among `sent`, and the duel's accept, in order. +fn equips_and_duels(sent: &Receiver) -> Vec<&'static str> { + sent.try_iter() + .filter_map(|c| match c { + ClientCommand::AutoEquipItem { .. } => Some("AutoEquipItem"), + ClientCommand::SwapInvItem { .. } | ClientCommand::SwapItem { .. } => Some("Swap"), + ClientCommand::DuelAccepted { .. } => Some("DuelAccepted"), + _ => None, + }) + .collect() +} + +/// `AutoEquipCursorItem` on a helm whose record is not cached asks it with the callback +/// `0x5e17a0` (`0x5e1603`); the answer runs the call again inside its handler (`0x5e182b`), whose +/// send (`0x5e1757`) goes out ahead of the next packet's handler's. +#[test] +fn an_equip_replay_sends_before_a_later_packets_handler_send() { + let (mut app, sent) = holding_client(); + hosted(&mut app, "PickupContainerItem(0, 1) AutoEquipCursorItem()"); + assert!( + sent.try_iter().any(|c| matches!( + c, + ClientCommand::ItemQuery { + entry: HELM_ENTRY, + .. + } + )), + "the record is asked" + ); + frame(&mut app, vec![helm_record(), our_duel()]); + assert_eq!(equips_and_duels(&sent), ["AutoEquipItem", "DuelAccepted"]); +} + +/// The replay's clear signals at its packet's place: its `CURSOR_UPDATE` fires between the +/// falls of the packets around the answer, the cursor read empty there and held before it. +#[test] +fn an_equip_replays_signals_fire_at_its_packets_place() { + let (mut app, _sent) = holding_client(); + hosted(&mut app, "PickupContainerItem(0, 1) AutoEquipCursorItem()"); + app.world_mut() + .non_send_resource_mut::() + .run( + r#" + local f = CreateFrame("Frame") + f:RegisterEvent("CURSOR_UPDATE") + f:RegisterEvent("UNIT_COMBAT") + f:SetScript("OnEvent", function() + table.insert(Seen, event .. (CursorHasItem() and " held" or " empty")) + end) + "#, + ) + .unwrap(); + let seen = frame(&mut app, vec![fall(5), helm_record(), fall(6)]); + assert_eq!( + seen, + [ + FELL, + "UNIT_COMBAT held", + "CURSOR_UPDATE empty", + FELL, + "UNIT_COMBAT empty", + ] + ); +} + +/// A swap onto the doll parked on the helm's record (`0x5e0dbe`, the callback `0x5e1020`) +/// replays inside the answer's handler (`0x5e10c2`): its move goes out ahead of the next +/// packet's send, and the parked element is freed (`0x5e10cf`). +#[test] +fn a_parked_swap_sends_before_a_later_packets_handler_send() { + use bevy::ecs::system::RunSystemOnce; + let (mut app, sent) = holding_client(); + let mv = benilla_ui::script::ContainerMove { + src_bag: 0, + src_slot: 1, + dst_bag: benilla_ui::script::EQUIPMENT_BAG, + dst_slot: 1, + count: None, + }; + app.world_mut() + .run_system_once( + move |mut gate: crate::ui_bind_confirm::BindGate, + items: Res, + net: Res| { + gate.park_swap(&mv, HELM_ENTRY, &items, &net); + }, + ) + .unwrap(); + frame(&mut app, vec![helm_record(), our_duel()]); + assert_eq!(equips_and_duels(&sent), ["Swap", "DuelAccepted"]); + assert_eq!( + app.world() + .resource::() + .live(), + 0, + "the replay freed the parked move" + ); +} + +/// A leaderboard read that missed an objective's item registered the callback `0x4e0830` +/// (`0x4e05e0`); the record's answer signals `QUEST_LOG_UPDATE` (`0x4e083a`) at its packet's +/// place, between the falls of the packets around it. +#[test] +fn a_quest_log_update_off_an_item_answer_fires_between_its_neighbours() { + use crate::ui_quest_log::fixture::{quest, seat}; + const PELT: u32 = 900; + let mut app = client(); + { + let mut s = app.world_mut().non_send_resource_mut::(); + let mut pelts = quest(50, "Pelts", 1); + pelts.record.objectives[0] = benilla_ui::script::QuestObjectiveView { + item_id: PELT, + item_count: 5, + ..Default::default() + }; + seat(&mut s, &[pelts]); + s.run( + r#" + local f = CreateFrame("Frame") + f:RegisterEvent("QUEST_LOG_UPDATE") + f:SetScript("OnEvent", function() table.insert(Seen, event) end) + "#, + ) + .unwrap(); + } + // Our quest log's first slot holds the quest, as the getter reads it at the call. + let slot = benilla_protocol::field::FIELD_PLAYER_QUEST_LOG_1_1; + frame(&mut app, vec![values(ME, &[(slot, 50)])]); + // The read, with the host lent, misses the pelt's record and registers the callback. + let kind: String = crate::script_calls::with_hosted_vm(app.world_mut(), |s| { + let s = s.expect("a VM"); + let kind = s + .eval("local _, kind = GetQuestLogLeaderBoard(1, 2) return kind") + .expect("the chunk runs"); + s.run("Seen = {}").expect("the chunk runs"); + kind + }); + assert_eq!(kind, "item"); + let answer = SessionEvent::ItemTemplate { + entry: PELT, + info: Some(Box::new(crate::items::test_template("Wolf Pelt"))), + }; + assert_eq!( + frame(&mut app, vec![fall(5), answer, fall(6)]), + [FELL, "QUEST_LOG_UPDATE", FELL] + ); +} + +/// A shown spell tooltip whose reagent's record the build missed counts it and keeps the +/// callback `0x52f820` with the tooltip as its cookie (`0x52f3f4`, `0x52f3ff`); the answer builds +/// the spell again at its packet's place (`0x52f862`), so a listener of the packet before reads +/// the tooltip as it stood and one of the packet after reads the reagent's line. +#[test] +fn a_spell_tooltip_rebuilds_at_its_reagents_answer() { + use benilla_formats::{SpellCatalog, SpellDisplay}; + const FROSTBOLT: u32 = 116; + /// Arcane Powder. + const POWDER: u32 = 17020; + let mut app = client(); + let mut reagents = [(0, 0); 8]; + reagents[0] = (POWDER, 1); + let frostbolt = SpellDisplay { + id: FROSTBOLT, + name: "Frostbolt".into(), + reagents, + ..Default::default() + }; + app.insert_resource(crate::ui_action::Spells { + catalog: SpellCatalog::from_displays(std::collections::HashMap::from([( + FROSTBOLT, frostbolt, + )])), + ..crate::ui_action::Spells::empty_for_tests() + }); + app.insert_resource(crate::ui_spellbook::SkillLines { + catalog: benilla_formats::SkillLineCatalog::from_spell_lines([]), + }); + app.world_mut() + .resource_mut::() + .spells + .insert(FROSTBOLT); + crate::ui_script::test_ui::load_tooltip_template(app.world().non_send_resource::()); + app.world_mut() + .non_send_resource_mut::() + .run( + r#" + SPELL_REAGENTS = "Reagents: " + local a = CreateFrame("Button", "B"); a:SetPoint("CENTER", 0, 0) + a:SetWidth(10); a:SetHeight(10) + CreateFrame("GameTooltip", "TT", nil, "TestTooltipTemplate") + local f = CreateFrame("Frame") + f:RegisterEvent("UNIT_COMBAT") + f:SetScript("OnEvent", function() + table.insert(Seen, "lines " .. TT:NumLines()) + end) + "#, + ) + .unwrap(); + hosted( + &mut app, + r#"TT:SetOwner(B, "ANCHOR_RIGHT"); TT:SetSpell(1, "spell")"#, + ); + let answer = SessionEvent::ItemTemplate { + entry: POWDER, + info: Some(Box::new(crate::items::test_template("Arcane Powder"))), + }; + assert_eq!( + frame(&mut app, vec![fall(5), answer, fall(6)]), + [FELL, "lines 1", FELL, "lines 2"] + ); +} + +/// Two swaps parked on one record (`0x5e0dbe`) replay in table order inside the answer's handler +/// (`0x5e1087`-`0x5e10ed`): each `SwapItem` sends in its body (`0x5e0fdb`) ahead of its clear +/// (`0x5e0fe7`), so the second's send waits on no signal of the first's, and both go out ahead +/// of the next packet's. +#[test] +fn two_parked_swaps_on_one_record_both_send_before_a_later_packets_handler_send() { + use bevy::ecs::system::RunSystemOnce; + let (mut app, sent) = holding_client(); + let to = |dst_slot: u32| benilla_ui::script::ContainerMove { + src_bag: 0, + src_slot: 1, + dst_bag: benilla_ui::script::EQUIPMENT_BAG, + dst_slot, + count: None, + }; + let moves = [to(1), to(1)]; + // The helm held, so the first replay's clear signals `CURSOR_UPDATE` ahead of the second. + hosted(&mut app, "PickupContainerItem(0, 1)"); + app.world_mut() + .run_system_once( + move |mut gate: crate::ui_bind_confirm::BindGate, + items: Res, + net: Res| { + for mv in &moves { + gate.park_swap(mv, HELM_ENTRY, &items, &net); + } + }, + ) + .unwrap(); + frame(&mut app, vec![helm_record(), our_duel()]); + assert_eq!(equips_and_duels(&sent), ["Swap", "Swap", "DuelAccepted"]); +} + +/// A refusal destroys the record's node (`0x55bed2`), so an equip on that entry looks it up +/// afresh: it waits and asks again, its callback held for the next answer, never run at once on +/// a record that is not there. +#[test] +fn an_equip_on_a_refused_record_asks_again_and_waits() { + let (mut app, sent) = holding_client(); + hosted(&mut app, "PickupContainerItem(0, 1) AutoEquipCursorItem()"); + let refusal = SessionEvent::ItemTemplate { + entry: HELM_ENTRY, + info: None, + }; + frame(&mut app, vec![refusal]); + sent.try_iter().for_each(drop); + hosted(&mut app, "AutoEquipCursorItem()"); + let asked = sent.try_iter().any(|c| { + matches!( + c, + ClientCommand::ItemQuery { + entry: HELM_ENTRY, + .. + } + ) + }); + assert!(asked, "the record is asked again"); + assert_eq!( + app.world_mut() + .resource_mut::() + .take_waiters(HELM_ENTRY, crate::items::RecordCallback::AutoEquip), + 1, + "the callback waits for the next answer" + ); +} + +/// A record the cache holds ahead of the VM's copy, as a cache file's load lands one outside an +/// answer, is found by the lookup inside the call (`0x5e1603`, `0x5e0db1`): `AutoEquipCursorItem` +/// sends in its body (`0x5e1757`) and a place's `SwapItem` in its (`0x5e0fdb`), before the call +/// returns, with nothing asked or parked for a later replay. +#[test] +fn an_equip_on_a_record_the_cache_holds_sends_inside_the_call() { + for (chunk, send) in [ + ( + "PickupContainerItem(0, 1) AutoEquipCursorItem()", + "AutoEquipItem", + ), + ("PickupContainerItem(0, 1) PickupInventoryItem(1)", "Swap"), + ] { + let (mut app, sent) = holding_client(); + let mut t = crate::items::test_template("Plain Helm"); + (t.class, t.inventory_type) = (4, 1); + app.world_mut() + .resource_mut::() + .insert_template(HELM_ENTRY, Some(t)); + sent.try_iter().for_each(drop); + hosted(&mut app, chunk); + let sent: Vec = sent.try_iter().collect(); + assert!( + !sent + .iter() + .any(|c| matches!(c, ClientCommand::ItemQuery { .. })), + "{chunk}: nothing asked" + ); + let (tx, rx) = crossbeam_channel::unbounded(); + sent.into_iter().for_each(|c| tx.send(c).unwrap()); + assert_eq!(equips_and_duels(&rx), [send], "{chunk}"); + assert_eq!( + app.world() + .resource::() + .live(), + 0, + "{chunk}: nothing parked" + ); + } +} + +/// A bind-on-equip record's answer replays `AutoEquipCursorItem` inside its handler, which asks +/// the question (`0x5e163b`, `0x5e16c6`): `AUTOEQUIP_BIND_CONFIRM` fires at the answer's place, +/// between the falls of the packets around it, and nothing is sent. +#[test] +fn a_bind_on_equip_replay_asks_at_its_answers_place() { + let (mut app, sent) = holding_client(); + hosted(&mut app, "PickupContainerItem(0, 1) AutoEquipCursorItem()"); + app.world_mut() + .non_send_resource_mut::() + .run( + r#" + local f = CreateFrame("Frame") + f:RegisterEvent("AUTOEQUIP_BIND_CONFIRM") + f:SetScript("OnEvent", function() table.insert(Seen, event .. " " .. arg1) end) + "#, + ) + .unwrap(); + let mut t = crate::items::test_template("Bound Helm"); + (t.class, t.inventory_type, t.bonding) = (4, 1, benilla_ui::script::BIND_WHEN_EQUIPPED); + let answer = SessionEvent::ItemTemplate { + entry: HELM_ENTRY, + info: Some(Box::new(t)), + }; + assert_eq!( + frame(&mut app, vec![fall(5), answer, fall(6)]), + [FELL, "AUTOEQUIP_BIND_CONFIRM 0", FELL] + ); + assert!(equips_and_duels(&sent).is_empty(), "nothing sent"); +} diff --git a/crates/benilla-app/src/lanes/reputation_live_tests.rs b/crates/benilla-app/src/lanes/reputation_live_tests.rs index 28f88ebf0..6193eba71 100644 --- a/crates/benilla-app/src/lanes/reputation_live_tests.rs +++ b/crates/benilla-app/src/lanes/reputation_live_tests.rs @@ -456,3 +456,32 @@ fn the_chat_listeners_read_the_standing_their_line_follows() { "each line reads its message's standing, the rank line after the increase" ); } + +/// Each standing listener reads its own message's standing, and the friends the packets ahead of +/// it left: a friend list between the two messages, which `GetNumFriends` reads at the call +/// (`0x5ad000`), counts none for the first and Ann for the second. +#[test] +fn each_standing_listener_reads_its_own_span() { + let mut c = client(); + let ann = super::unit_view_tests::one_friend(&mut c.app); + c.eval::<()>( + false, + r#"local g = CreateFrame("Frame") + g:RegisterEvent("UPDATE_FACTION") + g:SetScript("OnEvent", function() table.insert(Seen, "friends " .. GetNumFriends()) end)"#, + ); + c.frame(vec![ + vec![delta(STORMWIND.1, 100)], + vec![ann], + vec![delta(STORMWIND.1, 5100)], + ]); + assert_eq!( + c.seen(), + [ + "2 4100/5/nil nil/0", + "friends 0", + "2 9100/6/nil nil/0", + "friends 1" + ] + ); +} diff --git a/crates/benilla-app/src/lanes/requirement_live_tests.rs b/crates/benilla-app/src/lanes/requirement_live_tests.rs index f73f09141..ec048f9ca 100644 --- a/crates/benilla-app/src/lanes/requirement_live_tests.rs +++ b/crates/benilla-app/src/lanes/requirement_live_tests.rs @@ -22,6 +22,8 @@ const LOCKBOX_ENTRY: u32 = 4632; const LOCK_ID: u32 = 7; /// A recipe, the craft it teaches, and an item with a required level. const RECIPE_ENTRY: u32 = 2406; +/// The recipe's use spell, a learn (`Effect[0]` 36) whose trigger spell is the craft. +const LEARN: u32 = 2540; const TAUGHT: u32 = 2541; const AXE_ENTRY: u32 = 1311; /// A crafted item whose maker the name cache lacks, and a charter whose record it lacks. @@ -58,9 +60,9 @@ fn item(entry: u32, extra: &[(u16, u32)]) -> ObjectFields { } /// The client with us in the world, a level-10 human warrior carrying the lockbox, the key, the -/// crafted bar and the charter in backpack slots 1 to 4 and their records cached, the VM's copy -/// pushed as a level-60 player who knows nothing and opens nothing, and the VM's item records and -/// the lock row seated. +/// crafted bar and the charter in backpack slots 1 to 4, their records, the recipe's and the axe's +/// cached, the VM's copy pushed as a level-60 player who knows nothing and opens nothing, and the +/// VM's item records and the lock row seated. fn client() -> (App, Receiver) { let mut app = crate::game_plugins::schedule_tests::headless_client_unrun(); let (tx, rx) = crossbeam_channel::unbounded(); @@ -100,25 +102,63 @@ fn client() -> (App, Receiver) { item(CHARTER_ENTRY, &[(ITEM_ENCHANT_0, PETITION_ID)]), false, ); - // The records the item cache holds, as the bags read them. + // The recipe's learn spell, which its record's view names the craft through. + let mut spells = crate::ui_action::Spells::empty_for_tests(); + spells.catalog = + benilla_formats::SpellCatalog::from_displays(std::collections::HashMap::from([( + LEARN, + benilla_formats::SpellDisplay { + id: LEARN, + effects: [36, 0, 0], + effect_trigger_spell: [TAUGHT, 0, 0], + ..Default::default() + }, + )])); + world.insert_resource(spells); + // The records the item cache holds, which the bags and a build with the host lent read. let mut items = world.resource_mut::(); - for (entry, name, flags) in [ - (LOCKBOX_ENTRY, "Lockbox", 0), - (KEY_ENTRY, "Key", 0), - (CRAFTED_ENTRY, "Bar", 0), + let record = crate::items::test_template; + for (entry, t) in [ + ( + LOCKBOX_ENTRY, + benilla_protocol::messages::ItemInfo { + lock_id: LOCK_ID, + ..record("Lockbox") + }, + ), + (KEY_ENTRY, record("Key")), + (CRAFTED_ENTRY, record("Bar")), ( CHARTER_ENTRY, - "Charter", - benilla_protocol::messages::ITEM_FLAG_CHARTER, + benilla_protocol::messages::ItemInfo { + flags: benilla_protocol::messages::ITEM_FLAG_CHARTER, + ..record("Charter") + }, + ), + ( + RECIPE_ENTRY, + benilla_protocol::messages::ItemInfo { + spells: vec![benilla_protocol::messages::ItemSpellEntry { + index: 0, + spell_id: LEARN, + trigger: 0, + charges: 0, + cooldown_ms: -1, + category: 0, + category_cooldown_ms: -1, + }], + ..record("Recipe") + }, + ), + ( + AXE_ENTRY, + benilla_protocol::messages::ItemInfo { + required_level: 20, + ..record("Axe") + }, ), ] { - items.insert_template( - entry, - Some(benilla_protocol::messages::ItemInfo { - flags, - ..crate::items::test_template(name) - }), - ); + items.insert_template(entry, Some(t)); } let mut script = world.non_send_resource_mut::(); crate::ui_script::test_ui::load_tooltip_template(&script); @@ -333,6 +373,13 @@ fn set_client() -> (App, Receiver) { }, )])); world.insert_resource(spells); + world.resource_mut::().insert_template( + MARK, + Some(benilla_protocol::messages::ItemInfo { + item_set: SET, + ..crate::items::test_template("Defias Mark") + }), + ); let mut script = world.non_send_resource_mut::(); script.set_item_template( MARK, diff --git a/crates/benilla-app/src/lanes/selection_live_tests.rs b/crates/benilla-app/src/lanes/selection_live_tests.rs index ac2c7649f..ed935fb6b 100644 --- a/crates/benilla-app/src/lanes/selection_live_tests.rs +++ b/crates/benilla-app/src/lanes/selection_live_tests.rs @@ -49,6 +49,8 @@ fn a_hosted_getter_reads_the_live_target_and_npc() { const READ: &str = r#"return UnitHealth("target"), UnitHealth("npc"), UnitIsUnit("target", "npc") and 1 or 0"#; assert_eq!(hosted::<(u32, u32, u8)>(&mut app, READ), (100, 0, 0)); + // The VM's copies of the tokens, which no feed pushes in game, seated on the wolf. + crate::ui_unit::seat_tokens_once(app.world_mut()); // The boar selected and latched, the VM told nothing. select(&mut app, Some(BOAR)); app.world_mut() @@ -233,9 +235,8 @@ fn a_reconnect_does_not_reseat_the_lost_target() { } /// Nothing selected and the VM told so, with a spy on the selection's change and the boar's line: -/// each heard event, the change and the window with the target they read, `UnitHealth("target")`. -/// The line's listener is not asked: a lane's firing reads the world the frame left until each -/// packet's lanes fire inside the dispatch. +/// each heard event, the change and the window with the target they read, `UnitHealth("target")`, +/// and the line by its name alone. fn unselected_with_a_spy(app: &mut App) { select(app, None); frame(app, vec![]); @@ -379,6 +380,8 @@ fn a_dead_units_loot_close_signals_its_deselect_at_the_packet() { .resource_mut::() .open(BOAR, 1, 0, Vec::new()); world.resource_mut::().0 = Some(BOAR); + // The open stands in for its response's packet, whose event fires with it. + assert_eq!(frame(&mut app, vec![]), ["LOOT_OPENED:0"]); let release = SessionEvent::LootReleaseResponse { guid: BOAR, result: 1, diff --git a/crates/benilla-app/src/lanes/social_live_tests.rs b/crates/benilla-app/src/lanes/social_live_tests.rs index ea4d11b8c..95f8f001e 100644 --- a/crates/benilla-app/src/lanes/social_live_tests.rs +++ b/crates/benilla-app/src/lanes/social_live_tests.rs @@ -261,3 +261,29 @@ fn the_who_answer_routes_by_the_flag_its_stamp_finds() { assert_eq!(seen[1], "CHAT_MSG_SYSTEM:1 player total"); assert_eq!(seen[2], "FRIENDLIST_UPDATE", "behind"); } + +/// A listener reads the friend list as the packets ahead of it left it, before the next packet's +/// handler rewrites it (`0x537ae5`; `GetNumFriends` reads the list at the call, `0x5ad000`): the +/// time response's `QUEST_LOG_UPDATE` ahead of a list of two counts Ann alone. +#[test] +fn a_listener_counts_the_friends_its_packet_left() { + let mut c = client(); + let _: () = c.eval( + false, + r#"local g = CreateFrame("Frame") + g:RegisterEvent("QUEST_LOG_UPDATE") + g:SetScript("OnEvent", function() table.insert(Seen, "count " .. GetNumFriends()) end)"#, + ); + c.frame(vec![ + SessionEvent::ServerUnixTime { + unix_time: 1_000_000, + }, + SessionEvent::FriendList { + friends: vec![online(ANN, 10), online(BOB, 20)], + }, + ]); + assert_eq!( + c.seen(), + ["QUEST_LOG_UPDATE", "count 1", "FRIENDLIST_UPDATE"] + ); +} diff --git a/crates/benilla-app/src/lanes/spell_slot_live_tests.rs b/crates/benilla-app/src/lanes/spell_slot_live_tests.rs new file mode 100644 index 000000000..bbf47414f --- /dev/null +++ b/crates/benilla-app/src/lanes/spell_slot_live_tests.rs @@ -0,0 +1,395 @@ +//! The bar's legs of the spell packets, at their packet. An unlearn clears every slot standing for +//! its spell inside its handler (`UnlearnSpell 0x5e9fe0` → `ClearSpellSlots 0x4e5e20` at +//! `0x5ea253`), and a supersede clears and sets each spell slot of the old rank before its book +//! pair (`0x5e6356` → `ReplaceActionSpell 0x4e5e60`), each write sending and signalling +//! `ACTIONBAR_SLOT_CHANGED` there (`0x4e58e0`). The learn latches are written at the learn +//! (`0x4b262c`). + +use std::collections::HashMap; + +use benilla_formats::{SpellCatalog, SpellDisplay}; +use benilla_protocol::messages::{ActionButton, ACTION_KIND_SPELL}; +use benilla_protocol::{EntityKind, SessionEvent}; +use benilla_ui::script::UiScript; +use bevy::prelude::*; +use crossbeam_channel::{Receiver, Sender}; + +use super::unit_view_tests::{created, fall, wire_packets}; +use crate::net::ClientCommand; + +const ME: u64 = 0x7; +const FIREBALL: u32 = 133; +/// Frostbolt's first two ranks. +const FROSTBOLT_1: u32 = 116; +const FROSTBOLT_2: u32 = 205; +/// Skinning's first rank, whose `Effect[0]` is `SPELL_EFFECT_SKINNING`. +const SKINNING: u32 = 8613; + +/// What the spy records of every event it hears. +const EVENTS: &[&str] = &["ACTIONBAR_SLOT_CHANGED", "SPELLS_CHANGED", "UNIT_COMBAT"]; + +struct Client { + app: App, + inbound: Sender, + sent: Receiver, +} + +impl Client { + /// One whole frame of the client's, with `packets` in the inbound channel, each one packet. + fn frame(&mut self, packets: Vec>) -> Vec { + for ev in wire_packets(packets) { + self.inbound.send(ev).expect("the inbound channel"); + } + self.app.update(); + self.seen() + } + + /// What the spy heard since the last call. + fn seen(&mut self) -> Vec { + let script = self.app.world().non_send_resource::(); + let seen: Vec = script.eval("local s = Seen Seen = {} return s").unwrap(); + seen + } + + /// The bar's sends since the last call, as `(slot, word)`. + fn sends(&self) -> Vec<(u8, u32)> { + self.sent + .try_iter() + .filter_map(|c| match c { + ClientCommand::SetActionButton { button, packed } => Some((button, packed)), + _ => None, + }) + .collect() + } +} + +fn spells() -> crate::ui_action::Spells { + let row = |id: u32, effect: u32| { + let mut d = SpellDisplay { + id, + name: format!("Spell {id}"), + icon: Some(format!("Interface\\Icons\\Spell_{id}")), + ..Default::default() + }; + d.effects[0] = effect; + (id, d) + }; + crate::ui_action::Spells { + catalog: SpellCatalog::from_displays(HashMap::from([ + row(FIREBALL, 0), + row(FROSTBOLT_1, 0), + row(FROSTBOLT_2, 0), + row(SKINNING, benilla_formats::SPELL_EFFECT_SKINNING), + ])), + ..crate::ui_action::Spells::empty_for_tests() + } +} + +/// The client in the world as [`ME`], knowing Fireball and Frostbolt's first rank, with Fireball +/// in slot 1 and Frostbolt in slot 2, shown; a spy whose line for each [`EVENTS`] carries what a +/// listener reads of slots 1 and 2 as it fires. +fn client() -> Client { + let mut app = crate::game_plugins::schedule_tests::headless_client(); + app.insert_resource(bevy::ecs::error::DefaultErrorHandler( + bevy::ecs::error::ignore, + )); + let (tx, sent) = crossbeam_channel::unbounded(); + app.insert_resource(crate::net::NetCommands(tx)); + let (inbound, rx) = crossbeam_channel::unbounded(); + app.insert_resource(crate::net::NetEvents::for_test(rx)); + app.update(); + app.insert_resource(spells()); + let script = UiScript::new().expect("a VM"); + let list: Vec = EVENTS.iter().map(|e| format!("{e:?}")).collect(); + script + .run(&format!( + r#" + Seen = {{}} + local f = CreateFrame("Frame") + for _, e in ipairs({{{}}}) do f:RegisterEvent(e) end + local function slot(s) return tostring(GetActionTexture(s)) end + f:SetScript("OnEvent", function() + if event == "UNIT_COMBAT" then table.insert(Seen, event) return end + table.insert(Seen, event .. ":" .. tostring(arg1) .. ":" .. slot(1) .. ":" + .. slot(2)) + end) + "#, + list.join(", ") + )) + .unwrap(); + app.insert_non_send_resource(script); + app.insert_resource(State::new(crate::client_state::ClientState::InWorld)); + benilla_world::world_point::init_world_point_resources(app.world_mut()); + let world = app.world_mut(); + world.resource_mut::().0 = Some(ME); + world + .resource_mut::() + .spells + .extend([FIREBALL, FROSTBOLT_1]); + { + let mut slots = world.resource_mut::(); + for (slot, action) in [(0, FIREBALL), (1, FROSTBOLT_1)] { + slots.staged.insert( + slot, + ActionButton { + slot, + action, + kind: ACTION_KIND_SPELL, + }, + ); + } + } + let mut c = Client { app, inbound, sent }; + c.frame(vec![vec![created(ME, EntityKind::Player, &[])]]); + c.frame(vec![]); + c.seen(); + c.sends(); + c +} + +fn removed(spell_id: u32) -> SessionEvent { + SessionEvent::SpellRemoved { spell_id } +} + +fn superceded(old_spell_id: u32, new_spell_id: u32) -> SessionEvent { + SessionEvent::SpellSuperceded { + old_spell_id, + new_spell_id, + } +} + +/// The icon a listener reads for `spell`'s slot. +fn icon(spell: u32) -> String { + format!("Interface\\Icons\\Spell_{spell}") +} + +/// With no frame after the unlearn, the bar holds no Fireball: the slot is cleared and sent as 0 +/// inside the handler, and the VM shows it cleared, so a listener reads it so at the packet. +#[test] +fn a_listener_inside_an_unlearns_packet_reads_the_slot_cleared() { + let mut c = client(); + assert!(c + .app + .world() + .resource::() + .buttons + .contains_key(&0)); + crate::net::handlers::dispatch(c.app.world_mut(), vec![removed(FIREBALL)]); + assert!(!c + .app + .world() + .resource::() + .buttons + .contains_key(&0)); + assert_eq!(c.sends(), [(0, 0)], "the clear's send, at the packet"); + crate::lanes::fire_in_order(c.app.world_mut()); + let seen = c.seen(); + assert_eq!( + seen.last().map(String::as_str), + Some(format!("ACTIONBAR_SLOT_CHANGED:1:nil:{}", icon(FROSTBOLT_1)).as_str()), + "{seen:?}" + ); +} + +/// A supersede clears and sets Frostbolt's slot, each with its send and its signal, ahead of the +/// book pair's `SPELLS_CHANGED`; the set's listener reads the new rank on the bar. The feed after +/// the packets adds nothing. +#[test] +fn a_supersedes_listener_reads_the_new_rank_on_the_bar() { + let mut c = client(); + let seen = c.frame(vec![vec![superceded(FROSTBOLT_1, FROSTBOLT_2)]]); + let on_bar = format!("{}:{}", icon(FIREBALL), icon(FROSTBOLT_2)); + assert_eq!(seen.len(), 4, "{seen:?}"); + assert!(seen[0].starts_with("ACTIONBAR_SLOT_CHANGED:2:"), "{seen:?}"); + assert_eq!( + seen[1..], + [ + format!("ACTIONBAR_SLOT_CHANGED:2:{on_bar}"), + format!("SPELLS_CHANGED:nil:{on_bar}"), + format!("SPELLS_CHANGED:nil:{on_bar}"), + ] + ); + assert_eq!( + c.sends(), + [(1, 0), (1, FROSTBOLT_2)], + "two packets, clear then set" + ); + let slots = c.app.world().resource::(); + assert_eq!(slots.buttons[&1].action, FROSTBOLT_2); + assert!(c.frame(vec![]).is_empty()); +} + +/// The unlearn's `ACTIONBAR_SLOT_CHANGED` fires at its packet's place, after its book's +/// `SPELLS_CHANGED` and between a fall's `UNIT_COMBAT` on each side; the identity feed signals the +/// slot no second time. +#[test] +fn actionbar_slot_changed_fires_between_neighbouring_packets_events() { + let mut c = client(); + let seen = c.frame(vec![vec![fall(5)], vec![removed(FIREBALL)], vec![fall(5)]]); + let after = format!("nil:{}", icon(FROSTBOLT_1)); + assert_eq!( + seen, + [ + "UNIT_COMBAT".to_string(), + format!("SPELLS_CHANGED:nil:{after}"), + format!("ACTIONBAR_SLOT_CHANGED:1:{after}"), + "UNIT_COMBAT".to_string(), + ] + ); + assert!(c.frame(vec![]).is_empty()); +} + +/// The registrar latches Skinning at the learn's packet (`0x4b262c`), so a call inside that packet +/// reads it, and the unlearn clears it at its own (`0x4b2c8b`). +#[test] +fn a_learned_abilitys_latch_reads_at_the_learn_packet() { + let mut c = client(); + let latch = |c: &Client| { + c.app + .world() + .resource::() + .skinning + }; + crate::net::handlers::dispatch( + c.app.world_mut(), + vec![SessionEvent::SpellLearned { spell_id: SKINNING }], + ); + assert_eq!(latch(&c), Some(SKINNING)); + crate::net::handlers::dispatch(c.app.world_mut(), vec![removed(SKINNING)]); + assert_eq!(latch(&c), None); +} + +/// The next login in the same run, as B: `logout` runs the session's end first, else the session +/// dropped with no logout. Then B's login, B's book, which knows only Frostbolt's second rank, and +/// B's bar, in vmangos's order (`Player.cpp:19253`, `:19256`). A's bar held the first rank, which +/// A knew. Returns the bar's sends and B's staged words. +fn next_login(logout: bool) -> (Vec<(u8, u32)>, Vec, ActionButton) { + use benilla_formats::{SkillLineCatalog, SlaInfo}; + let mut c = client(); + // A's bar as A's login brought it. + let a_bar: Vec = { + let slots = c.app.world().resource::(); + slots.buttons.values().copied().collect() + }; + crate::net::handlers::dispatch( + c.app.world_mut(), + vec![SessionEvent::ActionButtons { buttons: a_bar }], + ); + let ability = |forward_spell_id| SlaInfo { + skill_id: 6, + req_skill_value: 0, + forward_spell_id, + trivial_low: 0, + trivial_high: 0, + }; + c.app.insert_resource(crate::ui_spellbook::SkillLines { + catalog: SkillLineCatalog::from_abilities([ + (FROSTBOLT_1, ability(FROSTBOLT_2)), + (FROSTBOLT_2, ability(0)), + ]), + }); + if logout { + c.app + .world_mut() + .run_schedule(OnExit(crate::client_state::ClientState::InWorld)); + } + let b_bar = ActionButton { + slot: 5, + action: FIREBALL, + kind: ACTION_KIND_SPELL, + }; + crate::net::handlers::dispatch( + c.app.world_mut(), + vec![ + SessionEvent::Connected { + self_guid: 0x8, + name: "Bee".into(), + billing: Default::default(), + tutorial_flags: None, + addon_info: None, + }, + SessionEvent::SpellBook { + spell_ids: vec![FIREBALL, FROSTBOLT_2], + cooldowns: Vec::new(), + }, + SessionEvent::ActionButtons { + buttons: vec![b_bar], + }, + ], + ); + let slots = c.app.world().resource::(); + assert!(slots.buttons.is_empty(), "B's bar waits for B's arrival"); + let bar = slots.staged.values().copied().collect(); + (c.sends(), bar, b_bar) +} + +/// A worldport resends the book ahead of the bar (vmangos `MovementHandler.cpp:112` → +/// `Player.cpp:19253`, `:19256`). The book's rank pass reaches only a staging that waits for our +/// player's arrival, so it never sends the last staging, which the arrival loaded and the bar may +/// have moved on from; the worldport's own bar packet gets the pass. +#[test] +fn a_worldports_book_leaves_the_loaded_staging_alone() { + use benilla_formats::{SkillLineCatalog, SlaInfo}; + let mut c = client(); + // This login's bar packet, then the arrival that loads it. + let bar: Vec = { + let slots = c.app.world().resource::(); + slots.buttons.values().copied().collect() + }; + crate::net::handlers::dispatch( + c.app.world_mut(), + vec![SessionEvent::ActionButtons { + buttons: bar.clone(), + }], + ); + c.app + .world_mut() + .run_system_cached(crate::ui_action::recount::arrival_slot_pass) + .expect("the arrival's slot pass runs"); + c.sends(); + // Frostbolt's second rank trained, which supersedes the first in the book. + let ability = |forward_spell_id| SlaInfo { + skill_id: 6, + req_skill_value: 0, + forward_spell_id, + trivial_low: 0, + trivial_high: 0, + }; + c.app.insert_resource(crate::ui_spellbook::SkillLines { + catalog: SkillLineCatalog::from_abilities([ + (FROSTBOLT_1, ability(FROSTBOLT_2)), + (FROSTBOLT_2, ability(0)), + ]), + }); + crate::net::handlers::dispatch( + c.app.world_mut(), + vec![SessionEvent::SpellBook { + spell_ids: vec![FIREBALL, FROSTBOLT_2], + cooldowns: Vec::new(), + }], + ); + assert_eq!(c.sends(), [], "the book's pass waits for the bar"); + crate::net::handlers::dispatch( + c.app.world_mut(), + vec![SessionEvent::ActionButtons { buttons: bar }], + ); + assert_eq!(c.sends(), [(1, FROSTBOLT_2)], "the bar's pass moves it"); +} + +/// A relog in the same run: the game entry empties A's bar (`0x48f5a4` → `0x4e4f50`) and the +/// book's rank pass waits for B's bar, so neither moves or sends A's slots. +#[test] +fn a_relogs_rank_pass_never_reaches_the_last_characters_bar() { + let (sent, bar, b_bar) = next_login(true); + assert_eq!(sent, [], "nothing for A's slots"); + assert_eq!(bar, [b_bar]); +} + +/// The session dropped with no logout, so no session end ran: the game entry alone empties A's +/// bar. +#[test] +fn a_login_after_a_dropped_session_never_reaches_the_last_characters_bar() { + let (sent, bar, b_bar) = next_login(false); + assert_eq!(sent, [], "nothing for A's slots"); + assert_eq!(bar, [b_bar]); +} diff --git a/crates/benilla-app/src/lanes/stable_live_tests.rs b/crates/benilla-app/src/lanes/stable_live_tests.rs index aa1cf3de5..44affa6af 100644 --- a/crates/benilla-app/src/lanes/stable_live_tests.rs +++ b/crates/benilla-app/src/lanes/stable_live_tests.rs @@ -12,7 +12,7 @@ use bevy::prelude::*; use crossbeam_channel::Receiver; use crate::net::ClientCommand; -use crate::ui_stable::{StableEvent, StableLane, StableOpen}; +use crate::ui_stable::{StableLane, StableOpen}; const ME: u64 = 0x10; const MASTER: u64 = 0xF130_0000_4500_0001; @@ -22,6 +22,10 @@ const BOAR: u32 = 1_126; /// event and message line. fn client() -> (App, Receiver) { let mut app = crate::game_plugins::schedule_tests::headless_client_unrun(); + // In the world with the interface up, so the dispatch fires each packet's lanes. + app.insert_resource(bevy::prelude::State::new( + crate::client_state::ClientState::InWorld, + )); let (tx, rx) = crossbeam_channel::unbounded(); app.insert_resource(crate::net::NetCommands(tx)); app.insert_resource(crate::net::SelfGuid(Some(ME))); @@ -68,23 +72,17 @@ fn boar() -> StabledPet { } } -/// `packets` through their handlers, each item they put on the stable lane stamped inside them, -/// none heard before the drain; then the drain, and what the spy heard. -fn handled(app: &mut App, packets: Vec) -> (Vec, Vec) { - let before = crate::lanes::stamp(); +/// `packets` through their handlers: each event the stable lane takes fires inside the dispatch, at +/// its packet's place, as a handler signals inside itself (`0x703e50`) ahead of the next packet's +/// (`0x537ae5`), so the drain finds nothing; what the spy heard. +fn handled(app: &mut App, packets: Vec) -> Vec { crate::net::handlers::dispatch(app.world_mut(), packets); app.world_mut().flush(); - let after = crate::lanes::stamp(); - let stamped = app.world().resource::().stamped(); assert!( - stamped.iter().all(|(at, _)| before < *at && *at < after), - "stamped inside the handler" + app.world().resource::().stamped().is_empty(), + "fired inside the dispatch" ); - let heard: Vec = eval(app, false, "return Seen"); - assert!(heard.is_empty(), "on the lane: {heard:?}"); - crate::lanes::fire_in_order(app.world_mut()); - let heard = eval(app, false, "local s = Seen Seen = {} return s"); - (stamped.into_iter().map(|(_, e)| e).collect(), heard) + eval(app, false, "local s = Seen Seen = {} return s") } /// With the host lent the getters read the records as the world holds them, where the VM's copy @@ -120,36 +118,24 @@ fn the_getters_read_the_stable_through_the_host() { ); } -/// The list's `PET_STABLE_SHOW`, the money refusal's line and code 11's `PET_STABLE_UPDATE` sit -/// on the stable lane at their handler's place, and fire there in the drain. +/// The list's `PET_STABLE_SHOW`, the money refusal's line and code 11's `PET_STABLE_UPDATE` fire +/// inside their packet's dispatch. #[test] -fn the_list_and_the_results_fire_on_the_lane_at_their_handlers() { +fn the_list_and_the_results_fire_inside_their_dispatch() { let (mut app, _rx) = client(); let list = SessionEvent::ListStabledPets { npc: MASTER, num_stable_slots: 1, pets: vec![boar()], }; - assert_eq!( - handled(&mut app, vec![list]), - (vec![StableEvent::Show], vec!["PET_STABLE_SHOW:nil".into()]) - ); + assert_eq!(handled(&mut app, vec![list]), ["PET_STABLE_SHOW:nil"]); let refused = SessionEvent::StableResult { result: stable_result::ERR_MONEY, }; - assert_eq!( - handled(&mut app, vec![refused]), - ( - vec![StableEvent::Line("ERR_NOT_ENOUGH_MONEY")], - vec!["UI_ERROR_MESSAGE:poor".into()] - ) - ); + assert_eq!(handled(&mut app, vec![refused]), ["UI_ERROR_MESSAGE:poor"]); assert_eq!( handled(&mut app, vec![SessionEvent::StableResult { result: 11 }]), - ( - vec![StableEvent::Update], - vec!["PET_STABLE_UPDATE:nil".into()] - ) + ["PET_STABLE_UPDATE:nil"] ); } @@ -172,7 +158,7 @@ fn answer(found: bool) -> SessionEvent { /// Each `GetStablePetInfo` call that misses the record keeps the callback `0x4cb3b0` (flag 0), /// the cache asking once, owned by the active player; the answer runs each one, which signals -/// `PET_STABLE_UPDATE` on the lane at its handler (`0x4cb3bf`), and a held record keeps none. +/// `PET_STABLE_UPDATE` inside its handler (`0x4cb3bf`), and a held record keeps none. #[test] fn a_missed_record_signals_the_update_once_per_call_when_it_lands() { let (mut app, rx) = client(); @@ -194,18 +180,12 @@ fn a_missed_record_signals_the_update_once_per_call_when_it_lands() { ); assert_eq!( handled(&mut app, vec![answer(true)]), - ( - vec![StableEvent::Update, StableEvent::Update], - vec![ - "PET_STABLE_UPDATE:nil".into(), - "PET_STABLE_UPDATE:nil".into() - ] - ) + ["PET_STABLE_UPDATE:nil", "PET_STABLE_UPDATE:nil"] ); eval::<()>(&mut app, true, "GetStablePetInfo(1)"); assert_eq!( handled(&mut app, vec![answer(true)]), - (vec![], vec![]), + Vec::::new(), "a held record keeps no callback" ); } diff --git a/crates/benilla-app/src/lanes/stat_live_tests.rs b/crates/benilla-app/src/lanes/stat_live_tests.rs index e95a7c00d..e2c65193d 100644 --- a/crates/benilla-app/src/lanes/stat_live_tests.rs +++ b/crates/benilla-app/src/lanes/stat_live_tests.rs @@ -406,21 +406,38 @@ fn client() -> Client { c.frame(vec![]); c.frame(vec![]); c.eval::<()>(false, "Seen = {}"); - // The purse's VM copy, which no feed pushes: `GetMoney` reads the coinage through the host. - crate::script_calls::with_hosted_vm(c.app.world_mut(), |s| s.expect("a VM").set_money(123_456)); + // The VM's copies of the purse, the experience, the rest and the play-time bits, which no + // feed pushes: their getters read the descriptor through the host. + crate::script_calls::with_hosted_vm(c.app.world_mut(), |s| { + let s = s.expect("a VM"); + s.set_money(123_456); + s.set_player_xp(4_200, 9_000); + s.set_rest_state(1, 1_500, true); + s.set_play_time(true, false); + }); c } /// Wherever the frame's snapshots are current, every census getter answers the same off the live -/// object as off the snapshot, for us (buffed by items and auras, debuffed), a creature, our pet -/// and us through a `target` hop: the fields the snapshots hold are the ones the live read takes -/// ([`crate::ui_char::StatsObject`]). +/// object as off the snapshot, for us (buffed by items and auras, debuffed), a creature and us +/// through a `target` hop: the fields the snapshots hold are the ones the live read takes +/// ([`crate::ui_char::StatsObject`]). Our pet has no snapshot, and reads live. #[test] fn every_stat_getter_answers_the_same_live_as_off_the_snapshot() { let mut c = client(); + // The four tokens' copies and the doll's, which no feed pushes in game, seated for the + // host-less answer. + crate::ui_unit::seat_tokens_once(c.app.world_mut()); + crate::ui_char::seat_doll_once(c.app.world_mut()); let snapshot = c.answers(false); let live = c.answers(true); - assert_eq!(snapshot, live, "snapshot vs live"); + let unseated = |l: &String| l.starts_with("pet "); + let differ: Vec<(&String, &String)> = snapshot + .iter() + .zip(&live) + .filter(|(s, l)| !unseated(s) && s != l) + .collect(); + assert!(differ.is_empty(), "snapshot vs live: {differ:?}"); // The fixture reaches every gate: our buffs and gear, the creature's and the pet's own arms. for line in [ "player UnitStat 5 -3,0,2,-9", diff --git a/crates/benilla-app/src/lanes/tabard_live_tests.rs b/crates/benilla-app/src/lanes/tabard_live_tests.rs index d0d5101c4..f53608dfa 100644 --- a/crates/benilla-app/src/lanes/tabard_live_tests.rs +++ b/crates/benilla-app/src/lanes/tabard_live_tests.rs @@ -7,7 +7,7 @@ use benilla_protocol::SessionEvent; use benilla_ui::script::{TabardHost, UiScript, UnitState}; use bevy::prelude::*; -use crate::ui_tabard::{TabardEvent, TabardLane, TabardOpen}; +use crate::ui_tabard::{TabardLane, TabardOpen}; const VENDOR: u64 = 0xF130_0000_0000_0042; /// `PLAYER_GUILDID`, absolute. @@ -17,6 +17,10 @@ const GUILD_ID: u16 = 191; /// record is: its spy notes each designer event and message line. fn client() -> App { let mut app = crate::game_plugins::schedule_tests::headless_client_unrun(); + // In the world with the interface up, so the dispatch fires each packet's lanes. + app.insert_resource(bevy::prelude::State::new( + crate::client_state::ClientState::InWorld, + )); let (tx, _rx) = crossbeam_channel::unbounded(); app.insert_resource(crate::net::NetCommands(tx)); let world = app.world_mut(); @@ -89,42 +93,25 @@ fn can_save_reads_the_record_and_the_latch_through_the_host() { } /// The activate's `OPEN_TABARD_FRAME` and the failed save reply's line and `TABARD_SAVE_PENDING` -/// sit on the tabard lane at their handler's place, and fire there in the drain. +/// fire inside their packet's dispatch, as a handler signals inside itself (`0x703e50`) ahead of +/// the next packet's (`0x537ae5`). #[test] -fn the_open_and_the_reply_fire_on_the_lane_at_their_handlers() { +fn the_open_and_the_reply_fire_inside_their_dispatch() { let mut app = client(); let handled = |app: &mut App, ev: SessionEvent| { - let before = crate::lanes::stamp(); crate::net::handlers::dispatch(app.world_mut(), vec![ev]); app.world_mut().flush(); - let after = crate::lanes::stamp(); - let stamped = app.world().resource::().stamped(); assert!( - stamped.iter().all(|(at, _)| before < *at && *at < after), - "stamped inside the handler" + app.world().resource::().stamped().is_empty(), + "fired inside the dispatch" ); - let heard: Vec = eval(app, false, "return Seen"); - assert!(heard.is_empty(), "on the lane: {heard:?}"); - crate::lanes::fire_in_order(app.world_mut()); - let heard: Vec = eval(app, false, "local s = Seen Seen = {} return s"); - ( - stamped.into_iter().map(|(_, e)| e).collect::>(), - heard, - ) + eval::>(app, false, "local s = Seen Seen = {} return s") }; - let (items, heard) = handled(&mut app, SessionEvent::TabardVendorActivate(VENDOR)); - assert_eq!(items, [TabardEvent::Open]); + let heard = handled(&mut app, SessionEvent::TabardVendorActivate(VENDOR)); assert_eq!(heard, ["OPEN_TABARD_FRAME:nil"]); assert_eq!(app.world().resource::().npc(), Some(VENDOR)); - let (items, heard) = handled(&mut app, SessionEvent::SaveGuildEmblemResult(3)); - assert_eq!( - items, - [ - TabardEvent::Line("ERR_GUILDEMBLEM_NOTGUILDMASTER"), - TabardEvent::SavePending - ] - ); + let heard = handled(&mut app, SessionEvent::SaveGuildEmblemResult(3)); assert_eq!( heard, ["UI_ERROR_MESSAGE:not master", "TABARD_SAVE_PENDING:nil"] @@ -163,7 +150,7 @@ fn a_close_after_the_open_ends_the_preview_the_open_started() { crate::ui_session::register(app.world_mut(), 0xF130_0000_0000_0043); app.world_mut().flush(); assert_eq!(app.world().resource::().npc(), None, "closed"); - assert_eq!(preview(&app), None, "nothing has fired yet"); + assert_eq!(preview(&app), None, "the close ended the open's preview"); crate::lanes::fire_in_order(app.world_mut()); let order: Vec = eval(&mut app, false, "return Order"); assert_eq!(order, ["OPEN_TABARD_FRAME", "CLOSE_TABARD_FRAME"]); diff --git a/crates/benilla-app/src/lanes/taxi_live_tests.rs b/crates/benilla-app/src/lanes/taxi_live_tests.rs index 903eccfce..e51623b5f 100644 --- a/crates/benilla-app/src/lanes/taxi_live_tests.rs +++ b/crates/benilla-app/src/lanes/taxi_live_tests.rs @@ -208,24 +208,23 @@ fn the_taxi_events_fire_at_their_packets() { ); } -/// The open's `TAXIMAP_OPENED` sits on the taxi lane at its handler's stamp; a map that builds no -/// slot signals nothing and leaves no cell (`0x4dba40`, `0x4dbab0`). +/// The open's `TAXIMAP_OPENED` fires inside its packet's dispatch, with no frame after it; a map +/// that builds no slot signals nothing and leaves no cell (`0x4dba40`, `0x4dbab0`). #[test] -fn the_open_is_stamped_at_its_handler() { +fn the_open_fires_inside_its_dispatch() { let data = benilla_formats::wow_data_or_skip!(); let mut c = client(&data); - let before = crate::lanes::stamp(); c.handle(vec![shown()]); - let after = crate::lanes::stamp(); - let stamped = c + assert!(c .app .world() .resource::() - .stamped(); - assert_eq!(stamped.len(), 1); - let (at, event) = stamped[0]; - assert_eq!(event, crate::ui_taxi::TaxiEvent::Opened); - assert!(before < at && at < after, "stamped inside the handler"); + .stamped() + .is_empty()); + assert!( + c.seen().iter().any(|s| s == "TAXIMAP_OPENED:nil"), + "the open fired inside the dispatch" + ); c.frame(vec![]); crate::ui_taxi::close_core(c.app.world_mut()); c.seen(); diff --git a/crates/benilla-app/src/lanes/tests.rs b/crates/benilla-app/src/lanes/tests.rs index 4eba76404..259c77470 100644 --- a/crates/benilla-app/src/lanes/tests.rs +++ b/crates/benilla-app/src/lanes/tests.rs @@ -519,15 +519,12 @@ fn cast_stops(_: In, mut reports: ResMut App { - let mut app = client(|app| { + client(|app| { app.add_plugins(crate::ui_cast::UiCastPlugin); handlers(app); - }); - app.world_mut() - .init_resource::(); - app + }) } /// A cast's report fires inside its packet's handler (`SPELLCAST_STOP` from `SMSG_CAST_RESULT`, @@ -660,7 +657,8 @@ fn the_roster_events_fire_at_their_packet() { } /// The session's end drops what the cast and house lanes hold, as the chat lane's end drops its -/// lines: the Lua state they were readied for is replaced. +/// lines: the Lua state they were readied for is replaced. They hold it here because the world's +/// UI has not loaded yet, so no flush fires them. #[test] fn the_session_end_drops_the_cast_and_house_lanes() { let mut app = cast_client(|app| { @@ -676,9 +674,29 @@ fn the_session_end_drops_the_cast_and_house_lanes() { world .resource_mut::() .bar(crate::ui_cast::CastBarEdge::Stop); + world.insert_resource(crate::ui_script::PendingEntryUiLoad); crate::net::handlers::dispatch(world, vec![outbid()]); + assert!(heard(&mut app).is_empty(), "held while the UI loads"); + let world = app.world_mut(); world.run_schedule(OnExit(crate::client_state::ClientState::InWorld)); assert!(world.resource::().is_empty()); fire_frame(world); assert!(heard(&mut app).is_empty(), "nothing left to fire"); } + +/// A firing's own pushes are what moves its drain: a stamp another thread takes meanwhile, as a +/// test beside it does on its own world, nests under nothing it fires. +#[test] +fn another_threads_stamp_is_no_push_of_the_firing() { + let at = crate::lanes::stamp(); + let ((), moved) = crate::lanes::firing(at, || { + std::thread::spawn(crate::lanes::stamp) + .join() + .expect("stamps"); + }); + assert!(!moved, "another thread's stamp"); + let ((), moved) = crate::lanes::firing(at, || { + crate::lanes::stamp(); + }); + assert!(moved, "the firing's own push"); +} diff --git a/crates/benilla-app/src/lanes/token_live_tests.rs b/crates/benilla-app/src/lanes/token_live_tests.rs index 1c567df8f..27376bfe9 100644 --- a/crates/benilla-app/src/lanes/token_live_tests.rs +++ b/crates/benilla-app/src/lanes/token_live_tests.rs @@ -2,9 +2,9 @@ //! lent host: the active player's object (`0x51598d`), our pet off our `UNIT_FIELD_CHARM` else //! `UNIT_FIELD_SUMMON` (`0x515a5e`-`0x515a6e`), a group member's pet off the member's descriptor //! (`0x4e8204`, `0x491993`), the mouseover's object (`0x515bd2`), and each `target` hop off the -//! held unit's `UNIT_FIELD_TARGET` (`0x515a1c`-`0x515a25`). The live answer and the frame's -//! snapshot agree on every token form wherever the snapshot is current, and a listener resolves a -//! chain as its own packet left it. +//! held unit's `UNIT_FIELD_TARGET` (`0x515a1c`-`0x515a25`). A listener resolves a chain, and the +//! verbs that take a token resolve it, as its own packet left them, with no copy pushed ahead of +//! the drain. use benilla_protocol::field::{FIELD_UNIT_HEALTH, FIELD_UNIT_MAXHEALTH}; use benilla_protocol::messages::{member_status, GroupMemberEntry, PartyMemberStatsInfo}; @@ -26,6 +26,11 @@ const MATE: u64 = 0x22; const MATE_PET: u64 = 0xF140_0000_0046_0003; /// A raid member out of view, and the pet its record names. const FAR: u64 = 0x23; +/// A member who joins mid-frame, out of view. +const NEW: u64 = 0x24; +/// `AreaTable.dbc` zones: one on our map, 0, and one on an instance's, 36. +const ELWYNN: u16 = 12; +const DEADMINES: u16 = 1581; const FAR_PET: u64 = 0xF140_0000_0048_0005; /// A creature beside the wolf. const BOAR: u64 = 0xF130_0000_0047_0004; @@ -96,7 +101,7 @@ const GETTERS: &str = " struct Client { app: App, inbound: Sender, - _sent: Receiver, + sent: Receiver, } impl Client { @@ -165,6 +170,26 @@ fn summons(guid: u64) -> [(u16, u32); 2] { [(SUMMON, guid as u32), (SUMMON + 1, (guid >> 32) as u32)] } +/// `SMSG_GROUP_LIST` for a raid of us, leading, and `members` in our subgroup, in that order: the +/// party slots and the raid rows. +fn raid_of(members: &[u64]) -> SessionEvent { + SessionEvent::GroupList { + group_type: crate::ui_party::GROUPTYPE_RAID, + own_flags: 0, + members: members + .iter() + .map(|&guid| GroupMemberEntry { + name: if guid == MATE { "Mate" } else { "Far" }.into(), + guid, + status: member_status::ONLINE, + flags: 0, + }) + .collect(), + leader: ME, + loot: None, + } +} + /// The client in the world as [`ME`] (90 health, some XP) with [`PET`] (70), in a raid with /// [`MATE`] (60, in view, with [`MATE_PET`], 50) and [`FAR`] (out of view, its record naming /// [`FAR_PET`]), all one subgroup; [`WOLF`] (80) selected and hovered. The chains: the wolf targets @@ -235,25 +260,8 @@ fn client() -> Client { ); } crate::ui_unit::TestNames::english().insert(&mut app); - let mut c = Client { - app, - inbound, - _sent: sent, - }; - let roster = SessionEvent::GroupList { - group_type: crate::ui_party::GROUPTYPE_RAID, - own_flags: 0, - members: [("Mate", MATE), ("Far", FAR)] - .map(|(name, guid)| GroupMemberEntry { - name: name.into(), - guid, - status: member_status::ONLINE, - flags: 0, - }) - .into(), - leader: ME, - loot: None, - }; + let mut c = Client { app, inbound, sent }; + let roster = raid_of(&[MATE, FAR]); let far = SessionEvent::PartyMemberStats { guid: FAR, full: true, @@ -302,32 +310,21 @@ fn client() -> Client { c.frame(vec![]); c.frame(vec![]); c.eval::<()>(false, "Seen = {} PetSeen = {} DeepSeen = {}"); + // The VM's copy of our experience, which no feed pushes: `UnitXP` reads it through the host. + crate::script_calls::with_hosted_vm(c.app.world_mut(), |s| { + s.expect("a VM").set_player_xp(1234, 0) + }); c } -/// Wherever the frame's snapshots are current, every token form names the same unit live as off -/// the snapshot: what the live resolver reads of the objects is what the snapshot's build read. -/// A chain whose end no token pushes has no snapshot: with no host lent it reads nobody. +/// Every token form names its unit live, as the resolver reads the objects and the group rows +/// inside the call (`0x515970`): each base, a hop off each, the chains, a member out of view and +/// the pet its record names, our own raid row and its pet, and nobody. #[test] -fn every_token_form_names_the_same_unit_live_as_off_the_snapshot() { +fn every_token_form_names_its_unit_live() { let mut c = client(); - let snapshot = c.answers(false); let live = c.answers(true); - assert_eq!(snapshot.len(), TOKENS.len()); - let unpushed_chain = |line: &str| { - let (token, row) = line.split_once(' ').expect("a token and its row"); - let chain = matches!( - benilla_ui::script::parse_unit_token(token), - benilla_ui::script::UnitTokenParse::Unit { hops, .. } if hops > 0 - ); - chain && row == "nil,0,0,nil,nil,nil,nil,nil,nil,nil" - }; - let differ: Vec<(&String, &String)> = snapshot - .iter() - .zip(&live) - .filter(|(s, l)| s != l && !unpushed_chain(s)) - .collect(); - assert!(differ.is_empty(), "snapshot vs live: {differ:#?}"); + assert_eq!(live.len(), TOKENS.len()); // The fixture reaches every leg: each base, a hop off each, a three-hop chain, a member out // of view and the pet its record names, our own raid row and its pet, and nobody. for line in [ @@ -518,6 +515,216 @@ fn a_chunk_that_targets_resolves_the_new_targets_target() { assert_eq!(wolf, 80, "we target the wolf"); } +/// Two group lists in one frame, the second swapping the party's slots: each list's +/// `PARTY_MEMBERS_CHANGED` listener trades with `party1` as its own list wrote the slots, as +/// `InitiateTrade` resolves its token inside the call (`0x48a120` → `0x515970`), not the frame's +/// last. +#[test] +fn a_listeners_trade_goes_to_party1_as_its_own_list_left_it() { + let mut c = client(); + c.eval::<()>( + true, + r#"local f = CreateFrame("Frame") + f:RegisterEvent("PARTY_MEMBERS_CHANGED") + f:SetScript("OnEvent", function() InitiateTrade("party1") end)"#, + ); + c.sent.try_iter().for_each(drop); + c.frame(vec![ + vec![raid_of(&[MATE, FAR])], + vec![raid_of(&[FAR, MATE])], + ]); + let mut traded: Vec = c + .sent + .try_iter() + .filter_map(|cmd| match cmd { + ClientCommand::InitiateTrade { target } => Some(target), + _ => None, + }) + .collect(); + traded.dedup(); + assert_eq!(traded, [MATE, FAR]); +} + +/// Two group lists in one frame, the second dropping [`FAR`], who is out of view: the first list's +/// listener finds `party2` friendly and cooperative through the verbs' group fallback, which tests +/// the slots at the call (`0x516961`-`0x516a1d`, `0x516aa1`-`0x516b5c` → `0x491900` → `0x4e80a0`), +/// and the second's `party2` names nobody. +#[test] +fn a_listeners_friend_test_reads_its_own_lists_slots() { + let mut c = client(); + c.eval::<()>( + true, + r#"Friends = {} + local f = CreateFrame("Frame") + f:RegisterEvent("PARTY_MEMBERS_CHANGED") + f:SetScript("OnEvent", function() + table.insert(Friends, tostring(UnitIsFriend("player", "party2")) .. "," + .. tostring(UnitCanCooperate("party2", "player"))) + end)"#, + ); + c.frame(vec![vec![raid_of(&[MATE, FAR])], vec![raid_of(&[MATE])]]); + let mut seen: Vec = c.eval(false, "return Friends"); + seen.dedup(); + assert_eq!(seen, ["1,1", "nil,nil"]); +} + +/// The world map's inputs for the map position tests: our map 0, the two zones' `AreaTable` rows, +/// and a projection that reads a position on map 0 as its thousandths and any other map as off +/// the displayed one (`0x4a7437`); and a spy noting `GetPlayerMapPosition(token)` at each of +/// `token`'s `UNIT_HEALTH`s. +fn map_spy(c: &mut Client, token: &str) { + let row = |map_id| benilla_formats::AreaTableRow { + map_id, + zone_id: 0, + explore_flag: 0, + flags: 0, + faction_group_mask: 0, + exploration_level: -1, + name: String::new(), + }; + c.app.insert_resource(crate::area::AreaTableRes( + benilla_formats::AreaTableCatalog::from_rows(vec![ + (u32::from(ELWYNN), row(0)), + (u32::from(DEADMINES), row(36)), + ]), + )); + c.app + .insert_resource(benilla_world::world_map::CurrentMap(0)); + let script = &mut *c.app.world_mut().non_send_resource_mut::(); + script.set_world_loc_projector(Box::new(|_, map, x, y| { + (map == 0).then_some((x / 1000.0, y / 1000.0)) + })); + c.eval::<()>( + true, + &format!( + r#"Maps = {{}} + local f = CreateFrame("Frame") + f:RegisterEvent("UNIT_HEALTH") + f:SetScript("OnEvent", function() + if arg1 == "{token}" then + local x, y = GetPlayerMapPosition(arg1) + table.insert(Maps, string.format("%.1f,%.1f", x, y)) + end + end)"# + ), + ); +} + +/// `SMSG_PARTY_MEMBER_STATS` for `guid`, online, at `hp` health in `zone` at `at`. +fn member_at(guid: u64, hp: u16, zone: u16, at: (i16, i16)) -> SessionEvent { + member_with(member_status::ONLINE, guid, hp, zone, at) +} + +/// [`member_at`] with the record's status byte `status`. +fn member_with(status: u8, guid: u64, hp: u16, zone: u16, at: (i16, i16)) -> SessionEvent { + SessionEvent::PartyMemberStats { + guid, + full: true, + info: Box::new(PartyMemberStatsInfo { + status: Some(status), + cur_hp: Some(hp), + max_hp: Some(100), + zone: Some(zone), + position: Some(at), + ..Default::default() + }), + } +} + +/// A member who joins and moves inside one frame: each stats packet's listener reads `party3`'s +/// map position off the record that packet wrote, as `0x4a7870` reads the record at the call +/// (`0x4a78fd`, its position words at `0x4a7929` and `0x4a792d`), not the frame before's, which +/// held no such member. +#[test] +fn a_member_who_joins_mid_frame_reads_its_packets_map_position() { + let mut c = client(); + map_spy(&mut c, "party3"); + c.frame(vec![ + vec![raid_of(&[MATE, FAR, NEW])], + vec![member_at(NEW, 50, ELWYNN, (100, 200))], + vec![member_at(NEW, 40, ELWYNN, (300, 400))], + ]); + let seen: Vec = c.eval(false, "return Maps"); + assert_eq!(seen, ["0.1,0.2", "0.3,0.4"]); +} + +/// A member in an instance whose position falls inside our map's rect reads (0, 0): `0x4a7870` +/// projects a record under the map its zone's `AreaTable` row names (`0x4a790c`-`0x4a7934`), which +/// is not the displayed one (`0x4a7437`), never under ours. +#[test] +fn a_member_in_an_instance_reads_no_map_position() { + let mut c = client(); + map_spy(&mut c, "party2"); + c.frame(vec![ + vec![member_at(FAR, 20, ELWYNN, (100, 200))], + vec![member_at(FAR, 10, DEADMINES, (100, 200))], + ]); + let seen: Vec = c.eval(false, "return Maps"); + assert_eq!(seen, ["0.1,0.2", "0.0,0.0"]); +} + +/// A member whose record's status has bit 0x20 reads (0, 0), and the same record without it reads +/// its position: `0x4a7870` leaves a record with that bit (`0x4a7906`) unread. +#[test] +fn a_member_whose_status_has_bit_0x20_reads_no_map_position() { + let mut c = client(); + map_spy(&mut c, "party2"); + c.frame(vec![ + vec![member_with( + member_status::ONLINE | 0x20, + FAR, + 20, + ELWYNN, + (100, 200), + )], + vec![member_at(FAR, 10, ELWYNN, (100, 200))], + ]); + let seen: Vec = c.eval(false, "return Maps"); + assert_eq!(seen, ["0.0,0.0", "0.1,0.2"]); +} + +/// A member in view reads its object's position under our map whatever its record's zone: +/// `0x4a7870` takes a held player object first (`0x4a78ae`, typemask 0x10) and projects it under +/// the active player's map (`0x4a78e2` → `0x5ea700`), never reaching the record (`0x4a78fd`). +#[test] +fn a_member_in_view_reads_its_objects_map_position() { + let mut c = client(); + map_spy(&mut c, "party1"); + let mate = c.app.world().resource::().0[&MATE]; + c.app + .world_mut() + .entity_mut(mate) + .insert(Transform::from_translation( + benilla_assets::coords::wow_to_bevy([500.0, 600.0, 0.0]), + )); + c.frame(vec![vec![member_at(MATE, 20, DEADMINES, (100, 200))]]); + let seen: Vec = c.eval(false, "return Maps"); + assert_eq!(seen, ["0.5,0.6"]); +} + +/// A member in view whose stats packet's listener reads its map position, destroyed by a later +/// packet of the frame: the listener runs before the destroy's handler (`0x537ae5`), so +/// `0x4a7870` still finds the object at the call (`0x4a78ae`) and reads its position +/// (`0x4a78c1`). +#[test] +fn a_member_destroyed_later_in_the_frame_reads_its_objects_map_position() { + let mut c = client(); + map_spy(&mut c, "party1"); + let mate = c.app.world().resource::().0[&MATE]; + c.app + .world_mut() + .entity_mut(mate) + .insert(Transform::from_translation( + benilla_assets::coords::wow_to_bevy([500.0, 600.0, 0.0]), + )); + c.frame(vec![ + vec![member_at(MATE, 20, DEADMINES, (100, 200))], + vec![SessionEvent::ObjectDestroyed(MATE)], + ]); + let seen: Vec = c.eval(false, "return Maps"); + assert_eq!(seen, ["0.5,0.6"]); +} + /// The resolver's per-call cost with the host lent and off the snapshots: 10k calls of a getter /// that reads nothing but the guid (`UnitInParty`, `0x516290`), and of `UnitHealth`, for `target` /// and `targettarget`. diff --git a/crates/benilla-app/src/lanes/tooltip_live_tests.rs b/crates/benilla-app/src/lanes/tooltip_live_tests.rs new file mode 100644 index 000000000..1036dd6cf --- /dev/null +++ b/crates/benilla-app/src/lanes/tooltip_live_tests.rs @@ -0,0 +1,232 @@ +//! The spell tooltip as a listener builds it. The builder reads the player and the talent +//! modifier tables at the setter's call (`0x52e610`) and keeps nothing; the modifier handler +//! stores its cell and then runs the trainer's state pass (`0x6e99b4` → `0x6e99bb` for the flat +//! table, `0x6e9998` → `0x6e999f` for the percent one), whose `TRAINER_UPDATE` a listener hears +//! with the cell already stored. + +use std::collections::HashMap; + +use benilla_formats::{SpellCatalog, SpellDisplay}; +use benilla_protocol::messages::{trainer_spell_state, TrainerSpell}; +use benilla_protocol::{EntityKind, SessionEvent}; +use benilla_ui::script::{KeyedArg, SpellTooltipView, TooltipText, UiScript}; +use bevy::prelude::*; + +use super::unit_view_tests::created; + +const ME: u64 = 0x10; +const TRAINER: u64 = 0xF130_0000_4500_0002; +/// A mage spell (family 3) on family-flag bit 5, costing 100 mana. +const FROSTBOLT: u32 = 116; +const FROST_BIT: u8 = 5; +/// `UNIT_FIELD_BYTES_0` of a human mage. +const BYTES_0: u16 = 36; +const HUMAN_MAGE: u32 = 1 | (8 << 8); + +/// The listener: at each `TRAINER_UPDATE`, the book's first spell's cost line as `SetSpell` builds +/// it. +const LISTENER: &str = r#" + MANA_COST = "%d Mana" + SPELL_REAGENTS = "Reagents: " + Costs = {} + local a = CreateFrame("Button", "B"); a:SetPoint("CENTER", 0, 0); a:SetWidth(10); a:SetHeight(10) + CreateFrame("GameTooltip", "TT", nil, "TestTooltipTemplate") + local f = CreateFrame("Frame") + f:RegisterEvent("TRAINER_UPDATE") + f:SetScript("OnEvent", function() + TT:SetOwner(B, "ANCHOR_RIGHT"); TT:SetSpell(1, "spell") + table.insert(Costs, tostring(TTTextLeft2:GetText())) + end) +"#; + +/// The client in the world as a mage knowing Frostbolt, at a trainer, and a VM whose listener +/// notes each `TRAINER_UPDATE`'s cost line. +fn client() -> App { + let mut app = crate::game_plugins::schedule_tests::headless_client_unrun(); + // In the world with the interface up, so the dispatch fires each packet's lanes. + app.insert_resource(bevy::prelude::State::new( + crate::client_state::ClientState::InWorld, + )); + let (tx, _rx) = crossbeam_channel::unbounded(); + app.insert_resource(crate::net::NetCommands(tx)); + let frostbolt = SpellDisplay { + id: FROSTBOLT, + name: "Frostbolt".into(), + spell_family: 3, + spell_family_flags: 1 << FROST_BIT, + mana_cost: 100, + ..Default::default() + }; + app.insert_resource(crate::ui_action::Spells { + catalog: SpellCatalog::from_displays(HashMap::from([(FROSTBOLT, frostbolt)])), + ..crate::ui_action::Spells::empty_for_tests() + }); + app.insert_resource(crate::ui_spellbook::SkillLines { + catalog: benilla_formats::SkillLineCatalog::from_spell_lines([]), + }); + let world = app.world_mut(); + world.resource_mut::().0 = Some(ME); + world.resource_mut::().asked = TRAINER; + world + .resource_mut::() + .spells + .insert(FROSTBOLT); + let script = UiScript::new().expect("a VM"); + crate::ui_script::test_ui::load_tooltip_template(&script); + script.run(LISTENER).unwrap(); + world.insert_non_send_resource(script); + crate::net::handlers::dispatch( + world, + vec![ + created(ME, EntityKind::Player, &[(BYTES_0, HUMAN_MAGE)]), + SessionEvent::ObjectUpdateEnd, + ], + ); + world.flush(); + let me = world.resource::().0[&ME]; + world.entity_mut(me).insert(crate::net::SelfPlayer); + // The class's family, which the modifier gates read (`0x6e6b30`). + world + .resource_mut::() + .set_class_family(3); + let list = SessionEvent::TrainerList { + trainer: TRAINER, + trainer_type: 0, + services: vec![TrainerSpell { + spell: FROSTBOLT, + state: trainer_spell_state::GREEN, + cost: 10, + can_learn_primary_prof: false, + is_primary_prof_first_rank: false, + req_level: 1, + req_skill: 0, + req_skill_value: 0, + req_spells: [0; 3], + }], + greeting: String::new(), + }; + handled(&mut app, vec![list]); + app +} + +/// `packets` through their handlers, then the drain; the cost lines the listener read. +fn handled(app: &mut App, packets: Vec) -> Vec { + crate::net::handlers::dispatch(app.world_mut(), packets); + app.world_mut().flush(); + crate::lanes::fire_in_order(app.world_mut()); + crate::script_calls::eval_in_vm(app.world(), "local c = Costs Costs = {} return c") +} + +/// The modifier packet stores its cell and signals `TRAINER_UPDATE` behind it: the listener's +/// `SetSpell` builds the cost with the new cell, where the VM's copy holds the view pushed before +/// the packet. +#[test] +fn a_listeners_set_spell_reads_the_modifier_its_packet_stored() { + let mut app = client(); + // What the view held before this packet, as a push ahead of it left it. + let before = SpellTooltipView { + name: "Frostbolt".into(), + cost: Some(TooltipText::keyed("MANA_COST", vec![KeyedArg::D(100)])), + ..Default::default() + }; + app.world_mut() + .non_send_resource_mut::() + .set_spell_tooltip(FROSTBOLT, before); + let modifier = SessionEvent::SpellModifier { + flat: true, + mask_bit: FROST_BIT, + op: crate::spell::OP_COST, + value: -40, + }; + assert_eq!(handled(&mut app, vec![modifier]), ["60 Mana"]); +} + +/// `"mouseover"` resolves to the published guid (`0x515970`) and its getters read that unit at the +/// call, as `"target"`'s do: a raid mark a packet sets on the hovered unit reads with the host lent +/// (`GetRaidTargetIndex`, by guid, `0x4bb4f1`), where the hover's push keeps what its build read. +#[test] +fn the_mouseover_getters_read_the_hovered_unit_at_the_call() { + use super::unit_view_tests::{client, frame}; + use bevy::ecs::system::RunSystemOnce; + /// The harness's target. + const WOLF: u64 = 0xF130_0000_0044_0001; + let mut app = client(); + let world = app.world_mut(); + let wolf = world.resource::().0[&WOLF]; + *world.resource_mut::() = crate::target::Hovered { + target: Some(wolf), + guid: Some(WOLF), + distance: 2.0, + ..Default::default() + }; + world + .run_system_once(crate::ui_tooltip::drive_mouseover_tooltip) + .unwrap(); + frame( + &mut app, + vec![SessionEvent::RaidTargetSet { + icon: 2, + guid: WOLF, + }], + ); + let read = r#"return GetRaidTargetIndex("mouseover")"#; + let live: Option = + crate::script_calls::with_hosted_vm(app.world_mut(), |s| s.expect("a VM").eval(read)) + .expect("the chunk runs"); + let pushed: Option = crate::script_calls::eval_in_vm(app.world(), read); + assert_eq!((live, pushed), (Some(3), None)); +} + +/// A reagent the item cache misses at the build is asked with the tooltip as its cookie and +/// counted (`0x52f3f4`, `0x52f3ff`); its answer builds the spell again from the kept id +/// (`0x52f820` → `0x52e610`), so the shown tooltip gains the line with no new hover. +#[test] +fn a_reagents_answer_rebuilds_the_shown_spell_tooltip() { + /// Arcane Powder. + const POWDER: u32 = 17020; + let mut app = client(); + let mut reagents = [(0, 0); 8]; + reagents[0] = (POWDER, 1); + let frostbolt = SpellDisplay { + id: FROSTBOLT, + name: "Frostbolt".into(), + reagents, + ..Default::default() + }; + app.world_mut() + .resource_mut::() + .catalog = SpellCatalog::from_displays(HashMap::from([(FROSTBOLT, frostbolt)])); + let lines = r#" + local t = {} + for i = 1, TT:NumLines() do t[i] = getglobal("TTTextLeft" .. i):GetText() end + return table.concat(t, " | ") + "#; + let hosted = |app: &mut App, chunk: &str| -> String { + crate::script_calls::with_hosted_vm(app.world_mut(), |s| s.expect("a VM").eval(chunk)) + .expect("the chunk runs") + }; + hosted( + &mut app, + r#"TT:SetOwner(B, "ANCHOR_RIGHT"); TT:SetSpell(1, "spell"); return """#, + ); + assert_eq!(hosted(&mut app, lines), "Frostbolt", "the name unknown"); + // The record lands, in the app's cache and the VM's copy. + app.world_mut() + .resource_mut::() + .insert_template(POWDER, Some(crate::items::test_template("Arcane Powder"))); + app.world_mut() + .non_send_resource_mut::() + .set_item_template( + POWDER, + benilla_ui::script::ItemTemplateView { + name: "Arcane Powder".into(), + ..Default::default() + }, + ); + crate::script_calls::with_hosted_vm(app.world_mut(), |s| s.expect("a VM").tick(0.01)); + assert_eq!( + hosted(&mut app, lines), + "Frostbolt | Reagents: |cffff2020Arcane Powder|r", + "none carried, so red" + ); +} diff --git a/crates/benilla-app/src/lanes/trade_live_tests.rs b/crates/benilla-app/src/lanes/trade_live_tests.rs index bf64bdf82..a646ca080 100644 --- a/crates/benilla-app/src/lanes/trade_live_tests.rs +++ b/crates/benilla-app/src/lanes/trade_live_tests.rs @@ -12,7 +12,7 @@ use bevy::prelude::*; use crossbeam_channel::Sender; use super::unit_view_tests::{created, wire_packets}; -use crate::ui_trade::{TradeEvent, TradeLane, TradeSession}; +use crate::ui_trade::{TradeLane, TradeSession}; const ME: u64 = 0x7; const BOB: u64 = 0x9; @@ -183,38 +183,30 @@ fn the_trade_getters_read_the_session_at_the_call() { ); } -/// The open's `TRADE_SHOW`, the accept's `TRADE_ACCEPT_UPDATE` and the offer's compare sit on the -/// trade lane at their handlers, between the stamps of the handlers before and after. +/// The open's `TRADE_SHOW`, the accept's `TRADE_ACCEPT_UPDATE` and the offer's compare each fire +/// inside their packet's dispatch, with no frame after them: a handler's signal runs every +/// listener before the next packet's handler (`0x537ae5`, `0x703e50`). #[test] -fn the_trade_events_are_stamped_at_their_handlers() { +fn the_trade_events_fire_inside_their_dispatch() { let mut c = client(); c.handle(vec![status(TradeStatus::BeginTrade { partner: BOB })]); - let before = crate::lanes::stamp(); + c.seen(); c.handle(vec![ status(TradeStatus::OpenWindow), status(TradeStatus::Accept), bobs(true, 500), ]); - let after = crate::lanes::stamp(); - let stamped = c.app.world().resource::().stamped(); - assert!( - stamped.iter().all(|(at, _)| before < *at && *at < after), - "stamped inside the handlers" - ); + assert!(c.app.world().resource::().stamped().is_empty()); assert_eq!( - stamped.into_iter().map(|(_, e)| e).collect::>(), + c.seen(), [ - TradeEvent::Show { - partner: BOB, - purse: None - }, - TradeEvent::Accept(false, true), - TradeEvent::Accept(false, false), - TradeEvent::TargetItem(0), - TradeEvent::TargetMoney, + "TRADE_SHOW:nil", + "TRADE_ACCEPT_UPDATE:0", + "TRADE_ACCEPT_UPDATE:0", + "TRADE_TARGET_ITEM_CHANGED:1", + "TRADE_MONEY_CHANGED:nil", ] ); - assert!(c.seen().is_empty(), "nothing fired in the handlers"); } /// Each trade event fires at its packet's place among a chat line's of the packets around it. @@ -245,3 +237,60 @@ fn the_trade_events_fire_at_their_packets() { ] ); } + +/// An `[OpenWindow][Canceled]` frame: the open's `TRADE_SHOW` runs its listeners before the +/// cancel's handler (`0x537ae5`), so they read the trade open, Bob latched as its unit +/// (`UnitExists("NPC")`), and the cancel's close half runs after them. +#[test] +fn a_shows_listener_reads_the_trade_its_packet_opened() { + let mut c = client(); + let _: () = c.eval( + false, + r#"local g = CreateFrame("Frame") + g:RegisterEvent("TRADE_SHOW") + g:SetScript("OnEvent", function() + table.insert(Seen, "npc " .. tostring(UnitExists("NPC"))) + end)"#, + ); + c.handle(vec![status(TradeStatus::BeginTrade { partner: BOB })]); + c.frame(vec![ + vec![status(TradeStatus::OpenWindow)], + vec![status(TradeStatus::Canceled)], + ]); + assert_eq!(c.seen(), ["TRADE_SHOW:nil", "npc 1"]); +} + +/// A close behind another lane's earlier item: a monster's line, then the cancel of a trade an +/// earlier frame opened. The line's listeners run at its packet (`0x537ae5`), so they read Bob +/// still latched as the trade's unit, ahead of the cancel's handler and its `TRADE_CLOSED`, which +/// the core signals twice with Bob latched (`0x493365`). +#[test] +fn a_close_fires_behind_another_lanes_earlier_line() { + let mut c = client(); + let _: () = c.eval( + false, + r#"local g = CreateFrame("Frame") + g:RegisterEvent("CHAT_MSG_MONSTER_SAY") + g:RegisterEvent("TRADE_CLOSED") + g:SetScript("OnEvent", function() + if event == "TRADE_CLOSED" then table.insert(Seen, event) + else table.insert(Seen, "npc " .. tostring(UnitExists("NPC"))) end + end)"#, + ); + c.handle(vec![status(TradeStatus::BeginTrade { partner: BOB })]); + c.frame(vec![vec![status(TradeStatus::OpenWindow)]]); + c.seen(); + c.frame(vec![ + vec![boar_says("a")], + vec![status(TradeStatus::Canceled)], + ]); + assert_eq!( + c.seen(), + [ + "CHAT_MSG_MONSTER_SAY:a", + "npc 1", + "TRADE_CLOSED", + "TRADE_CLOSED" + ] + ); +} diff --git a/crates/benilla-app/src/lanes/trainer_live_tests.rs b/crates/benilla-app/src/lanes/trainer_live_tests.rs index 36687fdef..422b55805 100644 --- a/crates/benilla-app/src/lanes/trainer_live_tests.rs +++ b/crates/benilla-app/src/lanes/trainer_live_tests.rs @@ -14,7 +14,7 @@ use bevy::prelude::*; use std::collections::HashMap; use super::unit_view_tests::{created, values}; -use crate::ui_trainer::{TrainerEvent, TrainerLane, TrainerOpen}; +use crate::ui_trainer::{TrainerLane, TrainerOpen}; const ME: u64 = 0x10; const TRAINER: u64 = 0xF130_0000_4500_0001; @@ -65,6 +65,10 @@ const SPY: &str = r#" /// holds what the lane last pushed: its spy notes each trainer event. fn client() -> App { let mut app = crate::game_plugins::schedule_tests::headless_client_unrun(); + // In the world with the interface up, so the dispatch fires each packet's lanes. + app.insert_resource(bevy::prelude::State::new( + crate::client_state::ClientState::InWorld, + )); let (tx, _rx) = crossbeam_channel::unbounded(); app.insert_resource(crate::net::NetCommands(tx)); app.insert_resource(crate::ui_action::Spells { @@ -104,23 +108,17 @@ fn eval(app: &mut App, live: bool, chunk: &st } } -/// `packets` through their handlers, each item they put on the trainer lane stamped inside them, -/// none heard before the drain; then the drain, and what the spy heard. -fn handled(app: &mut App, packets: Vec) -> (Vec, Vec) { - let before = crate::lanes::stamp(); +/// `packets` through their handlers: each event the trainer lane takes fires inside the dispatch, at +/// its packet's place, as a handler signals inside itself (`0x703e50`) ahead of the next packet's +/// (`0x537ae5`), so the drain finds nothing; what the spy heard. +fn handled(app: &mut App, packets: Vec) -> Vec { crate::net::handlers::dispatch(app.world_mut(), packets); app.world_mut().flush(); - let after = crate::lanes::stamp(); - let stamped = app.world().resource::().stamped(); assert!( - stamped.iter().all(|(at, _)| before < *at && *at < after), - "stamped inside the handler" + app.world().resource::().stamped().is_empty(), + "fired inside the dispatch" ); - let heard: Vec = eval(app, false, "return Seen"); - assert!(heard.is_empty(), "on the lane: {heard:?}"); - crate::lanes::fire_in_order(app.world_mut()); - let heard = eval(app, false, "local s = Seen Seen = {} return s"); - (stamped.into_iter().map(|(_, e)| e).collect(), heard) + eval(app, false, "local s = Seen Seen = {} return s") } fn list() -> SessionEvent { @@ -147,10 +145,7 @@ fn list() -> SessionEvent { #[test] fn the_ability_getter_reads_the_book_through_the_host() { let mut app = client(); - assert_eq!( - handled(&mut app, vec![list()]), - (vec![TrainerEvent::Show], vec!["TRAINER_SHOW".into()]) - ); + assert_eq!(handled(&mut app, vec![list()]), ["TRAINER_SHOW"]); // Row 1 is the group's header. let read = "local name, met = GetTrainerServiceAbilityReq(2, 1) return name, met"; let unmet = (Some("Smelt Copper".to_string()), None); @@ -178,20 +173,14 @@ fn the_ability_getter_reads_the_book_through_the_host() { ); } -/// The list's `TRAINER_SHOW` and the passes' `TRAINER_UPDATE`s sit on the trainer lane at their -/// handler's place, and fire there in the drain: the coinage's, a learned spell's, and a product -/// record's whose lookup the icon getter's call missed, which keeps one callback per call. +/// The list's `TRAINER_SHOW` and the passes' `TRAINER_UPDATE`s fire inside their packet's +/// dispatch: the coinage's, a learned spell's, and a product record's whose lookup the icon +/// getter's call missed, which keeps one callback per call. #[test] -fn the_list_and_the_passes_fire_on_the_lane_at_their_handlers() { +fn the_list_and_the_passes_fire_inside_their_dispatch() { let mut app = client(); - let show = (vec![TrainerEvent::Show], vec!["TRAINER_SHOW".to_string()]); - assert_eq!(handled(&mut app, vec![list()]), show); - let update = |n: usize| { - ( - vec![TrainerEvent::Update; n], - vec!["TRAINER_UPDATE".to_string(); n], - ) - }; + assert_eq!(handled(&mut app, vec![list()]), ["TRAINER_SHOW"]); + let update = |n: usize| vec!["TRAINER_UPDATE".to_string(); n]; let money = values(ME, &[(FIELD_PLAYER_FIELD_COINAGE, 200)]); let money = vec![money, SessionEvent::ObjectUpdateEnd]; assert_eq!(handled(&mut app, money), update(1)); diff --git a/crates/benilla-app/src/lanes/tutorial_live_tests.rs b/crates/benilla-app/src/lanes/tutorial_live_tests.rs new file mode 100644 index 000000000..9b19ebe32 --- /dev/null +++ b/crates/benilla-app/src/lanes/tutorial_live_tests.rs @@ -0,0 +1,312 @@ +//! The tutorials at their places. Each trigger site fires inside the handler or the input that +//! raises it (`0x4b5390`, the callers in benilla-re's `tables/tutorial_triggers.tsv`): the +//! battleground status's (`0x4aa91d`, `0x4aaa93`), the vendor list's (`0x4fad32`), the dynamic +//! flags watcher's Looting (`0x60049b`) and the item-received function's, after its line +//! (`0x491cdd`, then `0x491cec`). So a tutorial raised by a packet fires between the neighbouring +//! packets' events, and its fire-once test reads the bank as the listeners before it left it. +//! `TutorialsEnabled` reads the acknowledged bank at its call (`0x4b5960`). + +use benilla_protocol::field::{FIELD_UNIT_DYNAMIC_FLAGS, FIELD_UNIT_HEALTH, FIELD_UNIT_NPC_FLAGS}; +use benilla_protocol::messages::{BattlefieldStatus, ItemPushResult, VendorItem}; +use benilla_protocol::{EntityKind, SessionEvent}; +use benilla_ui::script::UiScript; +use bevy::prelude::*; +use crossbeam_channel::{Receiver, Sender}; + +use super::unit_view_tests::{created, values, wire_packets}; +use crate::net::ClientCommand; + +const ME: u64 = 0x7; +const VENDOR: u64 = 0xF130_0000_0000_0043; +const MOB: u64 = 0xF130_0000_0000_0051; +const WSG: u32 = 489; +const LINEN: u32 = 2589; +/// `TUTORIAL_TRIGGER`'s published ids, each the 0-based id plus one. +const BATTLEGROUND_QUEUE: &str = "TUTORIAL_TRIGGER:48"; +const VENDORS: &str = "TUTORIAL_TRIGGER:20"; +const LOOTING: &str = "TUTORIAL_TRIGGER:7"; +const BACKPACK: &str = "TUTORIAL_TRIGGER:8"; + +/// The whole client, headless, in the world with its frame run. +struct Client { + app: App, + inbound: Sender, + sent: Receiver, +} + +impl Client { + /// One frame of the client's, with `packets` in the inbound channel, each one packet. + fn frame(&mut self, packets: Vec>) { + for ev in wire_packets(packets) { + self.inbound.send(ev).expect("the inbound channel"); + } + self.app.update(); + } + + /// `chunk`'s answer through the lent host when `live`, else off the VM's copies alone. + fn eval(&mut self, live: bool, chunk: &str) -> T { + if live { + crate::script_calls::with_hosted_vm(self.app.world_mut(), |s| { + s.expect("a VM").eval::(chunk).expect("runs") + }) + } else { + crate::script_calls::eval_in_vm(self.app.world(), chunk) + } + } + + /// The tutorial flags sent since the last call. + fn flags_sent(&mut self) -> Vec { + self.sent + .try_iter() + .filter_map(|c| match c { + ClientCommand::TutorialFlag { id } => Some(id), + _ => None, + }) + .collect() + } + + /// What the spy heard since the last call. + fn seen(&mut self) -> Vec { + self.eval(false, "local s = Seen Seen = {} return s") + } +} + +const SPY: &str = r#" + Seen = {} + LOOT_ITEM_PUSHED_SELF = "You receive item: %s." + local f = CreateFrame("Frame") + for _, e in ipairs({"TUTORIAL_TRIGGER", "UPDATE_BATTLEFIELD_STATUS", "MERCHANT_SHOW", + "CHAT_MSG_MONSTER_SAY", "CHAT_MSG_LOOT"}) do + f:RegisterEvent(e) + end + f:SetScript("OnEvent", function() + if event == "CHAT_MSG_LOOT" then + table.insert(Seen, event) + else + table.insert(Seen, event .. ":" .. tostring(arg1)) + end + -- The Show Tutorials option unticked (`UIOptionsFrame.lua:324`). + if event == "CHAT_MSG_MONSTER_SAY" and arg1 == "clear" then + ClearTutorials() + end + end) +"#; + +/// The client in the world, a vendor and a mob beside it, the tutorial banks clear, and a spy +/// whose line for each event carries its name and first argument. +fn client() -> Client { + let mut app = crate::game_plugins::schedule_tests::headless_client(); + app.insert_resource(bevy::ecs::error::DefaultErrorHandler( + bevy::ecs::error::ignore, + )); + let (tx, sent) = crossbeam_channel::unbounded(); + app.insert_resource(crate::net::NetCommands(tx)); + let (inbound, rx) = crossbeam_channel::unbounded(); + app.insert_resource(crate::net::NetEvents::for_test(rx)); + app.update(); + let script = UiScript::new().expect("a VM"); + script.run(SPY).unwrap(); + app.insert_non_send_resource(script); + app.insert_resource(State::new(crate::client_state::ClientState::InWorld)); + benilla_world::world_point::init_world_point_resources(app.world_mut()); + app.world_mut().resource_mut::().0 = Some(ME); + let mut c = Client { app, inbound, sent }; + c.frame(vec![vec![ + created(ME, EntityKind::Player, &[(FIELD_UNIT_HEALTH, 100)]), + created(VENDOR, EntityKind::Unit, &[(FIELD_UNIT_NPC_FLAGS, 0x80)]), + created(MOB, EntityKind::Unit, &[(FIELD_UNIT_HEALTH, 0)]), + ]]); + c.frame(vec![vec![SessionEvent::TutorialFlags(vec![0; 32])]]); + c.frame(vec![]); + c.seen(); + c +} + +fn queued(slot: u32) -> SessionEvent { + SessionEvent::BattlefieldStatus(BattlefieldStatus { + slot, + map_id: WSG, + bracket: 1, + instance_id: 3, + status: 1, + time_ms: None, + in_progress: None, + queued: Some((30_000, 0)), + }) +} + +/// A monster's line, which shows inside its own packet's handler on the chat lane. +fn boar_says(text: &str) -> SessionEvent { + SessionEvent::Chat(benilla_protocol::messages::ChatMessage { + chat_type: benilla_protocol::messages::CHAT_MSG_MONSTER_SAY, + language: 0, + sender_guid: 0xF130_0000_0045_0003, + target_guid: 0, + sender_name: Some("Boar".into()), + channel: None, + text: text.into(), + chat_tag: 0, + }) +} + +fn vendor_list() -> SessionEvent { + SessionEvent::VendorInventory { + vendor: VENDOR, + items: vec![VendorItem { + slot: 1, + entry: 159, + display_id: 0, + current_count: 5, + price: 25, + max_durability: 0, + buy_count: 1, + }], + } +} + +/// The battleground status's tutorial (`0x4aaa93`) fires inside its handler, ahead of its own +/// `UPDATE_BATTLEFIELD_STATUS` (`0x4aab05`) and between the lines of the packets around it. +#[test] +fn a_tutorial_raised_by_a_packet_fires_between_its_neighbours_events() { + let mut c = client(); + c.frame(vec![ + vec![boar_says("a")], + vec![queued(0)], + vec![boar_says("b")], + ]); + assert_eq!( + c.seen(), + [ + "CHAT_MSG_MONSTER_SAY:a", + BATTLEGROUND_QUEUE, + "UPDATE_BATTLEFIELD_STATUS:nil", + "CHAT_MSG_MONSTER_SAY:b", + ] + ); +} + +/// The vendor list's handler triggers Vendors (`0x4fad32`) ahead of its `MERCHANT_SHOW` +/// (`0x4fad92`), between the neighbouring packets' lines; a later list fires none, its bit set. +#[test] +fn the_vendor_tutorial_fires_at_the_lists_handler() { + let mut c = client(); + c.frame(vec![ + vec![boar_says("a")], + vec![vendor_list()], + vec![boar_says("b")], + ]); + assert_eq!( + c.seen(), + [ + "CHAT_MSG_MONSTER_SAY:a", + VENDORS, + "MERCHANT_SHOW:nil", + "CHAT_MSG_MONSTER_SAY:b", + ] + ); + c.frame(vec![vec![vendor_list()]]); + assert_eq!(c.seen(), ["MERCHANT_SHOW:nil"], "fire-once"); +} + +/// A unit's lootable bit rising triggers Looting inside the update's notify pass +/// (`0x600440`, `0x60049b`), at its packet's place. +#[test] +fn the_looting_tutorial_fires_at_the_dynamic_flags_watchers_place() { + let mut c = client(); + c.frame(vec![ + vec![boar_says("a")], + vec![values(MOB, &[(FIELD_UNIT_DYNAMIC_FLAGS, 0x1)])], + vec![boar_says("b")], + ]); + assert_eq!( + c.seen(), + ["CHAT_MSG_MONSTER_SAY:a", LOOTING, "CHAT_MSG_MONSTER_SAY:b"] + ); +} + +/// Our own push with its record held fires its line, then Backpack (`0x491cdd`, `0x491cec`), +/// ahead of the next packet's line. +#[test] +fn an_item_push_fires_its_tutorials_after_its_line() { + let mut c = client(); + c.app + .world_mut() + .resource_mut::() + .insert_template(LINEN, Some(crate::items::test_template("Linen Cloth"))); + let push = SessionEvent::ItemPushResult(ItemPushResult { + player_guid: ME, + from_npc: true, + created: false, + show_in_chat: true, + bag_slot: 255, + item_slot: 23, + item_entry: LINEN, + suffix_factor: 0, + random_property_id: 0, + count: 1, + }); + c.frame(vec![vec![push], vec![boar_says("b")]]); + assert_eq!( + c.seen(), + ["CHAT_MSG_LOOT", BACKPACK, "CHAT_MSG_MONSTER_SAY:b"] + ); +} + +/// The Show Tutorials option unticked in a listener, `ClearTutorials()` (`0x4b55c0`), sets every +/// bit before a later packet of the same frame triggers, so that trigger fires nothing +/// (`0x4b53c8`). +#[test] +fn tutorials_turned_off_by_an_earlier_listener_stop_the_next_trigger() { + let mut c = client(); + c.frame(vec![vec![boar_says("clear")], vec![queued(0)]]); + assert_eq!( + c.seen(), + [ + "CHAT_MSG_MONSTER_SAY:clear", + "UPDATE_BATTLEFIELD_STATUS:nil" + ] + ); + assert!(c.eval::(true, "return TutorialsEnabled() == nil")); +} + +/// `TutorialsEnabled` reads the acknowledged bank at the call through the host, with nothing +/// pushed: a fresh VM (a `/reload`'s) reads it as it stands, and a clear in the chunk reads nil on +/// the next line. +#[test] +fn tutorials_enabled_reads_the_bank_at_the_call() { + let mut c = client(); + assert_eq!(c.eval::(true, "return TutorialsEnabled()"), 1); + assert!( + c.eval::(false, "return TutorialsEnabled() == nil"), + "no copy pushed to the VM" + ); + c.app + .insert_non_send_resource(UiScript::new().expect("a fresh VM")); + assert_eq!(c.eval::(true, "return TutorialsEnabled()"), 1); + assert!(c.eval::(true, "ClearTutorials() return TutorialsEnabled() == nil")); +} + +/// `SetTrainer` (`0x4d7440`) on a new trainer acknowledges Learning Talents (`0x0c`) for our own +/// guid and Trainers (`0x0d`) for another (`0x4d7492`-`0x4d74ae`), its flag sent at the list's +/// place; a re-list from the open trainer acknowledges nothing (`0x4d7459`). +#[test] +fn a_trainer_list_acknowledges_its_tutorial_by_whose_it_is() { + for (trainer, want) in [(VENDOR, 0x0d), (ME, 0x0c)] { + let mut c = client(); + c.flags_sent(); + let list = || SessionEvent::TrainerList { + trainer, + trainer_type: 0, + services: Vec::new(), + greeting: String::new(), + }; + c.app + .world_mut() + .resource_mut::() + .asked = trainer; + c.frame(vec![vec![list()]]); + assert_eq!(c.flags_sent(), [want], "trainer {trainer:#x}"); + c.frame(vec![vec![list()]]); + assert!(c.flags_sent().is_empty(), "the open trainer's re-list"); + } +} diff --git a/crates/benilla-app/src/lanes/ui_error_live_tests.rs b/crates/benilla-app/src/lanes/ui_error_live_tests.rs new file mode 100644 index 000000000..a01bd9293 --- /dev/null +++ b/crates/benilla-app/src/lanes/ui_error_live_tests.rs @@ -0,0 +1,437 @@ +//! The UI error line at its handlers' places. `DisplayError` (`0x496720`) and the sink +//! `0x4945b0` signal inside whatever calls them, so a refusal or a notice a packet raises fires +//! between the neighbouring packets' events, in its handler's order against the handler's other +//! signals: the ticket answer's line ahead of its `UPDATE_TICKET` (`0x5e4504`, `0x5e4527`), the +//! mount result's (`0x5ec6f3`), the tame failure's (`0x6e6ab4`), the notification's and the area +//! trigger's (`0x401828`, `0x48f921`), the guild invite's after its popup (`0x5e6f53`, +//! `0x5e6f65`), a guild event's ahead of its roster update (`0x5e745f`-`0x5e74c4`), a disband's +//! ahead of the party's end (`0x5e688b`, `0x5e6898`), and a ready check's ahead of its popup +//! (`0x4ba51e`, `0x4ba53a`). + +use benilla_protocol::field::FIELD_UNIT_HEALTH; +use benilla_protocol::messages::{member_status, GroupMemberEntry}; +use benilla_protocol::{EntityKind, SessionEvent}; +use benilla_ui::script::UiScript; +use bevy::prelude::*; +use crossbeam_channel::Sender; + +use super::unit_view_tests::{created, wire_packets}; + +const ME: u64 = 0x7; +const MATE: u64 = 0x22; + +/// The whole client, headless, in the world with its frame run. +struct Client { + app: App, + inbound: Sender, +} + +impl Client { + /// One frame of the client's, with `packets` in the inbound channel, each one packet. + fn frame(&mut self, packets: Vec>) { + for ev in wire_packets(packets) { + self.inbound.send(ev).expect("the inbound channel"); + } + self.app.update(); + } + + /// What the spy heard since the last call. + fn seen(&mut self) -> Vec { + crate::script_calls::eval_in_vm(self.app.world(), "local s = Seen Seen = {} return s") + } +} + +const SPY: &str = r#" + Seen = {} + ERR_TICKET_DB_ERROR = "Ticket database error" + ERR_MOUNT_TOOFARAWAY = "Too far away" + ERR_TAME_FAILED = "%s." + PETTAME_TOOHIGHLEVEL = "Creature is too high level for you to tame" + ERR_INVITED_TO_GUILD_SS = "%s invites you to join %s" + ERR_GROUP_DISBANDED = "Your group has been disbanded." + ERR_GUILD_JOIN_S = "%s has joined the guild." + ERR_RAID_LEADER_READY_CHECK_START_S = "%s has initiated a ready check." + local f = CreateFrame("Frame") + for _, e in ipairs({"UI_ERROR_MESSAGE", "UI_INFO_MESSAGE", "CHAT_MSG_SYSTEM", + "CHAT_MSG_MONSTER_SAY", "UPDATE_TICKET", "GUILD_INVITE_REQUEST", + "PARTY_MEMBERS_CHANGED", "GUILD_ROSTER_UPDATE", "READY_CHECK"}) do + f:RegisterEvent(e) + end + local bare = {UPDATE_TICKET = 1, PARTY_MEMBERS_CHANGED = 1, GUILD_ROSTER_UPDATE = 1, + READY_CHECK = 1} + f:SetScript("OnEvent", function() + if bare[event] then + table.insert(Seen, event) + else + table.insert(Seen, event .. ":" .. tostring(arg1)) + end + end) +"#; + +/// The client in the world with our player held, and a spy whose line for each event carries its +/// name and first argument. +fn client() -> Client { + let mut app = crate::game_plugins::schedule_tests::headless_client(); + app.insert_resource(bevy::ecs::error::DefaultErrorHandler( + bevy::ecs::error::ignore, + )); + let (tx, _sent) = crossbeam_channel::unbounded(); + app.insert_resource(crate::net::NetCommands(tx)); + let (inbound, rx) = crossbeam_channel::unbounded(); + app.insert_resource(crate::net::NetEvents::for_test(rx)); + app.update(); + let script = UiScript::new().expect("a VM"); + script.run(SPY).unwrap(); + app.insert_non_send_resource(script); + app.insert_resource(State::new(crate::client_state::ClientState::InWorld)); + benilla_world::world_point::init_world_point_resources(app.world_mut()); + app.world_mut().resource_mut::().0 = Some(ME); + let mut c = Client { app, inbound }; + c.frame(vec![vec![created( + ME, + EntityKind::Player, + &[(FIELD_UNIT_HEALTH, 100)], + )]]); + c.frame(vec![]); + c.seen(); + c +} + +/// A monster's line, which shows inside its own packet's handler on the chat lane. +fn boar_says(text: &str) -> SessionEvent { + SessionEvent::Chat(benilla_protocol::messages::ChatMessage { + chat_type: benilla_protocol::messages::CHAT_MSG_MONSTER_SAY, + language: 0, + sender_guid: 0xF130_0000_0045_0003, + target_guid: 0, + sender_name: Some("Boar".into()), + channel: None, + text: text.into(), + chat_tag: 0, + }) +} + +/// `packet` between two of the boar's lines, in one frame: what the spy heard. +fn between(c: &mut Client, packet: SessionEvent) -> Vec { + c.frame(vec![ + vec![boar_says("a")], + vec![packet], + vec![boar_says("b")], + ]); + c.seen() +} + +/// A refusal by key: the ticket answer's status 0 shows `ERR_TICKET_DB_ERROR` (`0x5e4504`), then +/// signals `UPDATE_TICKET` (`0x5e4527`), both between the neighbours' lines. +#[test] +fn a_refusal_fires_between_its_neighbours_events_in_its_handlers_order() { + let mut c = client(); + let ticket = SessionEvent::GmTicket { + status: 0, + ticket: None, + }; + assert_eq!( + between(&mut c, ticket), + [ + "CHAT_MSG_MONSTER_SAY:a", + "UI_ERROR_MESSAGE:Ticket database error", + "UPDATE_TICKET", + "CHAT_MSG_MONSTER_SAY:b", + ] + ); +} + +/// The mount result's line (`0x5ec6f3`) fires at its packet's place. +#[test] +fn a_mount_refusal_fires_at_its_packet() { + let mut c = client(); + let refused = SessionEvent::MountResult { + mount: true, + code: 1, + }; + assert_eq!( + between(&mut c, refused), + [ + "CHAT_MSG_MONSTER_SAY:a", + "UI_ERROR_MESSAGE:Too far away", + "CHAT_MSG_MONSTER_SAY:b", + ] + ); +} + +/// The tame failure's line (`0x6e6ab4`), its reason's string in `%s`, fires at its packet's +/// place. +#[test] +fn a_tame_failure_fires_at_its_packet() { + let mut c = client(); + assert_eq!( + between(&mut c, SessionEvent::PetTameFailure { reason: 9 }), + [ + "CHAT_MSG_MONSTER_SAY:a", + "UI_ERROR_MESSAGE:Creature is too high level for you to tame.", + "CHAT_MSG_MONSTER_SAY:b", + ] + ); +} + +/// A notification's red line and an area trigger's yellow one (`0x401828`, `0x48f921`) fire at +/// their packets' places. +#[test] +fn the_wires_texts_fire_at_their_packets() { + let mut c = client(); + c.frame(vec![ + vec![boar_says("a")], + vec![SessionEvent::Notification { + text: "GM mode is ON".into(), + }], + vec![boar_says("b")], + vec![SessionEvent::AreaTriggerMessage { + text: "You must be level 58.".into(), + }], + vec![boar_says("c")], + ]); + assert_eq!( + c.seen(), + [ + "CHAT_MSG_MONSTER_SAY:a", + "UI_ERROR_MESSAGE:GM mode is ON", + "CHAT_MSG_MONSTER_SAY:b", + "UI_INFO_MESSAGE:You must be level 58.", + "CHAT_MSG_MONSTER_SAY:c", + ] + ); +} + +/// The guild invite shows its popup (`0x5e6f53`), then its chat line (`0x5e6f65`). +#[test] +fn a_guild_invite_shows_its_line_after_its_popup() { + let mut c = client(); + let invite = SessionEvent::GuildInvite { + inviter: "Dorn".into(), + guild: "Ironforge Guard".into(), + }; + assert_eq!( + between(&mut c, invite), + [ + "CHAT_MSG_MONSTER_SAY:a", + "GUILD_INVITE_REQUEST:Dorn", + "CHAT_MSG_SYSTEM:Dorn invites you to join Ironforge Guard", + "CHAT_MSG_MONSTER_SAY:b", + ] + ); +} + +/// A disband with a party slot held shows its line (`0x5e688b`), then ends the party +/// (`0x5e6898`), whose `PARTY_MEMBERS_CHANGED` follows it. +#[test] +fn a_disband_shows_its_line_ahead_of_the_partys_end() { + let mut c = client(); + grouped(&mut c, ME); + let seen = between(&mut c, SessionEvent::GroupDestroyed); + assert_eq!( + seen.first().map(String::as_str), + Some("CHAT_MSG_MONSTER_SAY:a") + ); + assert_eq!( + seen.get(1).map(String::as_str), + Some("CHAT_MSG_SYSTEM:Your group has been disbanded."), + "{seen:?}" + ); + assert_eq!( + seen.get(2).map(String::as_str), + Some("PARTY_MEMBERS_CHANGED"), + "{seen:?}" + ); + assert_eq!( + seen.last().map(String::as_str), + Some("CHAT_MSG_MONSTER_SAY:b"), + "{seen:?}" + ); +} + +/// A party of us and Dorn, [`MATE`], led by `leader`, the spy emptied. +fn grouped(c: &mut Client, leader: u64) { + c.frame(vec![vec![SessionEvent::GroupList { + group_type: 0, + own_flags: 0, + members: vec![GroupMemberEntry { + name: "Dorn".into(), + guid: MATE, + status: member_status::ONLINE, + flags: 0, + }], + leader, + loot: None, + }]]); + c.frame(vec![]); + c.seen(); +} + +/// A guild event's arm shows its line (`0x5e745f`-`0x5e74b7`), then the roster update every arm +/// but the sign-on pair's ends in (`0x5e74c4`). +#[test] +fn a_guild_event_shows_its_line_ahead_of_its_roster_update() { + let mut c = client(); + let joined = SessionEvent::GuildEvent(benilla_protocol::messages::GuildEventNotice { + event: benilla_protocol::messages::guild_event::JOINED, + params: vec!["Brisca".into()], + guid: None, + }); + assert_eq!( + between(&mut c, joined), + [ + "CHAT_MSG_MONSTER_SAY:a", + "CHAT_MSG_SYSTEM:Brisca has joined the guild.", + "GUILD_ROSTER_UPDATE", + "CHAT_MSG_MONSTER_SAY:b", + ] + ); +} + +/// A ready check another leads shows the leader's line (`0x4ba51e`) when the name cache holds the +/// leader (`0x4ba50f`, no callback), then `READY_CHECK` (`0x4ba53a`); with the name still to +/// come the line is skipped and `READY_CHECK` fires all the same (`0x4ba514`-`0x4ba53a`). +#[test] +fn a_ready_check_shows_its_line_ahead_of_its_popup() { + let mut c = client(); + grouped(&mut c, MATE); + assert_eq!( + between(&mut c, SessionEvent::ReadyCheckRequest), + [ + "CHAT_MSG_MONSTER_SAY:a", + "READY_CHECK", + "CHAT_MSG_MONSTER_SAY:b", + ], + "the leader's name is not cached" + ); + c.frame(vec![vec![SessionEvent::PlayerName { + guid: MATE, + name: "Dorn".into(), + race: 1, + gender: 0, + class: 1, + }]]); + c.seen(); + assert_eq!( + between(&mut c, SessionEvent::ReadyCheckRequest), + [ + "CHAT_MSG_MONSTER_SAY:a", + "CHAT_MSG_SYSTEM:Dorn has initiated a ready check.", + "READY_CHECK", + "CHAT_MSG_MONSTER_SAY:b", + ] + ); +} + +/// The ready check's lines print inside the handler that composes them (`0x49a870`), between the +/// neighbouring packets' events: a member's not-ready answer prints `RAID_MEMBER_NOT_READY` for +/// them (`0x4ba48a`), and with nobody left pending the close runs the timeout worker at once +/// (`0x4ba4d9` → `0x4bb310`), whose summary follows (`0x4bb49a`). +#[test] +fn a_ready_check_answer_prints_its_lines_at_its_packet() { + let mut c = client(); + c.frame(vec![vec![SessionEvent::GroupList { + group_type: crate::ui_party::GROUPTYPE_RAID, + own_flags: 0, + members: vec![GroupMemberEntry { + name: "Dorn".into(), + guid: MATE, + status: member_status::ONLINE, + flags: 0, + }], + leader: ME, + loot: None, + }]]); + c.frame(vec![]); + crate::script_calls::with_hosted_vm(c.app.world_mut(), |s| { + s.expect("a VM") + .run( + r#"RAID_MEMBER_NOT_READY = "%s is not ready" + READY_CHECK_NO_AFK = "No players are away" + DoReadyCheck()"#, + ) + .expect("the check starts") + }); + c.seen(); + let answer = SessionEvent::ReadyCheckAnswer { + guid: MATE, + ready: 0, + }; + assert_eq!( + between(&mut c, answer), + [ + "CHAT_MSG_MONSTER_SAY:a", + "CHAT_MSG_SYSTEM:Dorn is not ready", + "CHAT_MSG_SYSTEM:No players are away", + "CHAT_MSG_MONSTER_SAY:b", + ] + ); + c.frame(vec![]); + assert_eq!(c.seen(), Vec::::new(), "once"); +} + +/// A world session that ends before the world is entered releases what it held behind its entry +/// load (`net::apply`'s `InboundHold`), its notice's line among them, with no world left to clear +/// it; the next session's start drops it, so that session's interface never shows it. +#[test] +fn a_session_that_ends_before_the_world_leaves_no_line_for_the_next() { + let mut app = crate::game_plugins::schedule_tests::headless_client(); + app.insert_resource(bevy::ecs::error::DefaultErrorHandler( + bevy::ecs::error::ignore, + )); + let (tx, _sent) = crossbeam_channel::unbounded(); + app.insert_resource(crate::net::NetCommands(tx)); + let (inbound, rx) = crossbeam_channel::unbounded(); + app.insert_resource(crate::net::NetEvents::for_test(rx)); + app.update(); + let connected = || SessionEvent::Connected { + self_guid: ME, + name: "Me".into(), + billing: Default::default(), + tutorial_flags: None, + addon_info: None, + }; + for ev in [ + connected(), + SessionEvent::Notification { + text: "stale".into(), + }, + SessionEvent::Disconnected { + reason: "lost".into(), + end: benilla_protocol::SessionEnd::Lost, + }, + ] { + inbound.send(ev).unwrap(); + } + app.update(); + app.update(); + assert_eq!( + app.world() + .resource::() + .texts() + .len(), + 1, + "the released notice is queued, with no world to clear it" + ); + + inbound.send(connected()).unwrap(); + app.update(); + assert!( + app.world() + .resource::() + .texts() + .is_empty(), + "the next session's start drops it" + ); + // The next session's interface up: its lane fires nothing of the last session's. + let script = UiScript::new().expect("a VM"); + script.run(SPY).unwrap(); + app.insert_non_send_resource(script); + crate::ui_action::fire_ui_error_lane(app.world_mut()); + let seen: Vec = + crate::script_calls::eval_in_vm(app.world(), "local s = Seen Seen = {} return s"); + assert!( + seen.is_empty(), + "no stale line in the next session: {seen:?}" + ); +} diff --git a/crates/benilla-app/src/lanes/unit_feed_live_tests.rs b/crates/benilla-app/src/lanes/unit_feed_live_tests.rs index 42bdbd655..aee74cd28 100644 --- a/crates/benilla-app/src/lanes/unit_feed_live_tests.rs +++ b/crates/benilla-app/src/lanes/unit_feed_live_tests.rs @@ -279,6 +279,66 @@ fn the_language_getters_read_the_player_at_the_call() { assert_eq!(c.eval::(true, default), "Orcish", "the race now"); } +/// `PLAYER_FIELD_BYTES`, the combo points in byte 1 and the bar toggles in byte 2, and +/// `PLAYER_FIELD_COMBO_TARGET`, a guid pair. +const FIELD_BYTES: u16 = 1222; +const COMBO_TARGET: u16 = 714; + +/// The active player's combo pair, bar toggles and faction masks are read off its object as the +/// call runs (`GetComboPoints` `0x51a1c3`-`0x51a234`, `GetActionBarToggles` `0x4e768c`, +/// `GetZonePVPInfo` `0x48d5d6`-`0x48d613`): what a handler wrote shows to the hosted getter with no +/// frame between, and the VM's copy, which no feed pushes, stays as it was across the frame. +#[test] +fn the_player_scalars_read_as_written() { + let mut c = client(); + crate::script_calls::with_hosted_vm(c.app.world_mut(), |s| { + let s = s.expect("a VM"); + s.set_realm_pvp(true); + // An Alliance zone: friendly to the Human template (friend mask 2), hostile to the Orc + // one (enemy mask 10). + s.set_zone_texts(benilla_ui::script::ZoneTexts { + pvp_zone: Some(benilla_ui::script::ZonePvp { + faction_group_mask: 2, + faction_name: "Alliance".into(), + ..Default::default() + }), + ..Default::default() + }); + }); + let chunk = "return GetComboPoints(), (GetZonePVPInfo()), GetActionBarToggles()"; + type Scalars = ( + i64, + Option, + Option, + Option, + Option, + Option, + ); + let human = (0, Some("friendly".to_string()), None, None, None, None); + assert_eq!(c.eval::(true, chunk), human); + // A rogue (class 4, `UNIT_FIELD_BYTES_0` byte 1) of the Orc template, three points banked on + // the wolf, the target, and the second and third bars on. + c.write( + ME, + &[ + (BYTES_0, 1 | 4 << 8), + (TEMPLATE, ORC), + (FIELD_BYTES, 0b0110 << 16 | 3 << 8), + (COMBO_TARGET, WOLF as u32), + (COMBO_TARGET + 1, (WOLF >> 32) as u32), + ], + ); + let written = (3, Some("hostile".to_string()), None, Some(1), Some(1), None); + assert_eq!(c.eval::(true, chunk), written); + c.frame(vec![]); + assert_eq!(c.eval::(true, chunk), written); + assert_eq!( + c.eval::(false, chunk), + (0, None, None, None, None, None), + "no feed pushes the scalars: the VM's copies hold nothing" + ); +} + /// `SMSG_SPELL_COOLDOWN` for us on [`PLAIN`], a packet of the cooldown lane's. fn cooldown() -> Vec { vec![SessionEvent::SpellCooldowns { diff --git a/crates/benilla-app/src/lanes/unit_live_tests.rs b/crates/benilla-app/src/lanes/unit_live_tests.rs index 9e7dc3ff4..46f157c20 100644 --- a/crates/benilla-app/src/lanes/unit_live_tests.rs +++ b/crates/benilla-app/src/lanes/unit_live_tests.rs @@ -212,8 +212,10 @@ fn client() -> Client { } /// Wherever the frame's snapshots are current, every getter answers the same off the live object -/// as off the snapshot, for every token: the object's fields the snapshot holds are the ones it -/// reads ([`crate::ui_unit::unit_object`]), with nothing a token's own build changes after. +/// as off the snapshot: the object's fields the snapshot holds are the ones it reads +/// ([`crate::ui_unit::unit_object`]), with nothing a token's own build changes after. The group's +/// and the pet's tokens have no snapshot, nor has the roster, whose leader cell +/// `UnitIsPartyLeader` reads at the call (`0x516210`), and every token names its unit live. #[test] fn every_getter_answers_the_same_live_as_off_the_snapshot() { let mut c = client(); @@ -224,24 +226,39 @@ fn every_getter_answers_the_same_live_as_off_the_snapshot() { vec![values(PET, &[(FIELD_UNIT_HEALTH, 35)])], vec![values(ME, &[(FIELD_UNIT_HEALTH, 20)])], ]); + // The four tokens' copies, which no feed pushes in game, seated for the host-less answer. + crate::ui_unit::seat_tokens_once(c.app.world_mut()); let snapshot = c.answers(false); let live = c.answers(true); assert_eq!(snapshot.len(), TOKENS.len() * GETTERS.len()); for token in TOKENS { assert!( - snapshot - .iter() + live.iter() .any(|l| l.starts_with(&format!("{token} UnitExists true,1"))), - "{token} names a unit: {snapshot:?}" + "{token} names a unit: {live:?}" ); } - let differ: Vec<(&String, &String)> = - snapshot.iter().zip(&live).filter(|(s, l)| s != l).collect(); + let seated = |line: &str| { + ["player ", "target ", "targettarget "] + .iter() + .any(|t| line.starts_with(t)) + }; + assert!( + live.iter().any(|l| l == "player UnitIsPartyLeader true,1"), + "we lead, read off the roster: {live:?}" + ); + let roster = |line: &str| line.contains(" UnitIsPartyLeader "); + let differ: Vec<(&String, &String)> = snapshot + .iter() + .zip(&live) + .filter(|(s, l)| seated(s) && !roster(s) && s != l) + .collect(); assert!(differ.is_empty(), "snapshot vs live: {differ:?}"); } /// A store a packet moved after the frame's pushes reads as the object holds it, through the host, -/// for the token's own unit and through a `target` hop; the snapshot still holds the push. +/// for the token's own unit and through a `target` hop; with no host lent, the VM holds no copy of +/// the four tokens, which no feed pushes. #[test] fn a_getter_reads_the_object_as_it_runs() { let mut c = client(); @@ -253,7 +270,7 @@ fn a_getter_reads_the_object_as_it_runs() { }); assert_eq!(live, (15, 5, 5)); let snapshot: (i64, i64, i64) = crate::script_calls::eval_in_vm(c.app.world(), chunk); - assert_eq!(snapshot, (80, 90, 90)); + assert_eq!(snapshot, (0, 0, 0)); } /// `UnitOnTaxi` tests bit 20 of the resolved object's flags as it runs (`0x517a80`-`0x517a8c`): a diff --git a/crates/benilla-app/src/lanes/unit_view_tests.rs b/crates/benilla-app/src/lanes/unit_view_tests.rs index b8aad43d3..a4b3fe8b6 100644 --- a/crates/benilla-app/src/lanes/unit_view_tests.rs +++ b/crates/benilla-app/src/lanes/unit_view_tests.rs @@ -29,6 +29,7 @@ fn wire(events: impl IntoIterator) -> Vec { let block = matches!( ev, SessionEvent::ObjectCreate { .. } + | SessionEvent::ItemCreate { .. } | SessionEvent::ObjectValues { .. } | SessionEvent::ObjectsRemoved(_) ); @@ -46,6 +47,7 @@ pub(super) fn wire_packets(packets: Vec>) -> Vec matches!( ev, SessionEvent::ObjectCreate { .. } + | SessionEvent::ItemCreate { .. } | SessionEvent::ObjectValues { .. } | SessionEvent::ObjectsRemoved(_) ) @@ -128,6 +130,8 @@ pub(super) fn client() -> App { let mut app = crate::game_plugins::schedule_tests::headless_client_unrun(); let (tx, _rx) = crossbeam_channel::unbounded(); app.insert_resource(crate::net::NetCommands(tx)); + // In the world with the interface up, so the dispatch fires each packet's lanes. + app.insert_resource(State::new(crate::client_state::ClientState::InWorld)); let world = app.world_mut(); world.resource_mut::().0 = Some(ME); let script = UiScript::new().unwrap(); @@ -198,29 +202,63 @@ pub(super) fn seat(app: &mut App, tot: u64) { }); } -/// One frame: the packets through the handler table, the unit feed's push of the frame's state, -/// then the lanes' drain; what the spy saw. +/// One frame: the packets through the handler table, each packet's lanes fired after its +/// handlers, then the frame's drain; what the spy saw. pub(super) fn frame(app: &mut App, packets: Vec) -> Vec { - frame_after(app, |_| {}, packets) + run_frame(app, wire(packets)) } -/// [`frame`], with `before` run on the world between the frame-start snapshot and the packets. +/// [`frame`], with `inside` run inside the dispatch past the span's start and ahead of the +/// packets, as a handler of an earlier packet would run it ([`inside_the_dispatch`]). pub(super) fn frame_after( app: &mut App, - before: impl FnOnce(&mut World), + inside: impl FnOnce(&mut World) + Send + Sync + 'static, packets: Vec, ) -> Vec { - let world = app.world_mut(); - #[cfg(debug_assertions)] + let events = inside_the_dispatch(app, inside, wire(packets)); + run_frame(app, events) +} + +/// A test's step on the world. +type Step = Box; + +/// What a test runs inside the dispatch, as a packet's handler. +#[derive(Resource, Default)] +struct Inside(Option); + +/// The test's step, run as the handler of the packet [`inside_the_dispatch`] puts first. +fn run_inside(In(_): In, world: &mut World) { + if let Some(step) = world + .get_resource_mut::() + .and_then(|mut i| i.0.take()) { - use bevy::ecs::system::RunSystemOnce; - world - .run_system_once(crate::ui_unit::views::mark_frame_start) - .unwrap(); + step(world); } - before(world); - crate::net::handlers::dispatch(world, wire(packets)); - crate::ui_unit::run_feed_units_once(world); +} + +/// `events` behind a `SMSG_PONG`, a packet no handler of the client takes, whose handler here runs +/// `step`: a write a handler makes past the span's start, which the dispatch takes at its first +/// packet ([`crate::lanes::span_starts`]). +pub(super) fn inside_the_dispatch( + app: &mut App, + step: impl FnOnce(&mut World) + Send + Sync + 'static, + events: Vec, +) -> Vec { + use crate::net::handlers::NetHandlerApp; + if !app.world().contains_resource::() { + app.init_resource::() + .net_handler(benilla_protocol::SessionEventKind::Pong, run_inside); + } + app.world_mut().resource_mut::().0 = Some(Box::new(step)); + std::iter::once(SessionEvent::Pong { sequence: 0 }) + .chain(events) + .collect() +} + +/// `events` through the dispatch, then the frame's drain; what the spy saw. +fn run_frame(app: &mut App, events: Vec) -> Vec { + let world = app.world_mut(); + crate::net::handlers::dispatch(world, events); crate::lanes::fire_in_order(world); let s = world.non_send_resource_mut::(); let out = s.eval::>("return Seen").unwrap(); @@ -244,6 +282,37 @@ fn each_unit_health_listener_reads_its_own_packets_target_health() { ); } +/// The unit tooltip watches the health of the unit it shows on the object itself (`0x52a0a8` +/// registers `0x529560`), so a values block re-seats the plate's bar inside its packet's notify +/// pass, with no token pushed: the target's plate follows each packet's health. +#[test] +fn a_unit_tooltips_bar_follows_its_units_health_at_each_packet() { + let mut app = client(); + let world = app.world_mut(); + crate::ui_script::test_ui::load_tooltip_template(world.non_send_resource::()); + crate::script_calls::with_hosted_vm(world, |s| { + s.expect("a VM").run( + r#" + Tip = CreateFrame("GameTooltip", "Tip", nil, "TestTooltipTemplate") + local bar = CreateFrame("StatusBar", "TipStatusBar", Tip) + bar:SetWidth(100) bar:SetHeight(8) + Bars = {} + bar:SetScript("OnValueChanged", function() table.insert(Bars, arg1) end) + Tip:SetOwner(CreateFrame("Frame"), "ANCHOR_NONE") + Tip:SetUnit("target") + "#, + ) + }) + .expect("the plate shows the target"); + frame( + &mut app, + vec![values(WOLF, &health(70)), values(WOLF, &health(40))], + ); + let bars: Vec = crate::script_calls::eval_in_vm(app.world(), "return Bars"); + // Each seat sets the range, re-firing the held value, then the packet's (`0x529560`). + assert_eq!(bars, [100.0, 100.0, 70.0, 70.0, 40.0]); +} + /// A combat-log `UNIT_COMBAT` raised ahead of the update packet that writes the hit reads the /// health before it: the combat-log handler runs whole first (`0x624f83`), and the health write /// comes in the later packet. @@ -270,23 +339,18 @@ fn each_unit_mana_listener_reads_its_own_packets_mana() { ); } -/// The lane's own count of the builds it made, the views it pushed and the stores it checked at -/// its end, read and reset. -fn lane_counts(app: &mut App) -> (usize, usize, usize) { +/// The lane's own count of the stores it checked at its end, read and reset. +fn lane_checks(app: &mut App) -> usize { let mut views = app .world_mut() .resource_mut::(); - let counts = (views.builds, views.pushes, views.checked); - views.builds = 0; - views.pushes = 0; - views.checked = 0; - counts + std::mem::take(&mut views.checked) } -/// The replay ends on the live stores: a frame of moved dwords, a re-create that clears a field, -/// the target's target released out of range and brought back by a create, each with an event -/// between, ends with every rewound store equal to the live one (the `debug_assert` in the -/// lane's end) and none left rewound, so the stores read live again once the drain is done. +/// The replay ends on the live stores: moved dwords, a re-create that clears a field, the +/// target's target released out of range and brought back by a create, each with an event +/// between, end each flush with every rewound store equal to the live one (the `debug_assert` in +/// the lane's end) and none left rewound, so the stores read live again between packets. #[test] fn the_replay_ends_on_the_live_stores() { let mut app = client(); @@ -296,7 +360,7 @@ fn the_replay_ends_on_the_live_stores() { .non_send_resource_mut::() .run(r#"function Look(event, unit) return UnitHealth("targettarget") end"#) .unwrap(); - lane_counts(&mut app); + lane_checks(&mut app); let seen = frame( &mut app, vec![ @@ -327,9 +391,9 @@ fn the_replay_ends_on_the_live_stores() { "the target's target as each packet left it: gone between its release and its create" ); assert_eq!( - lane_counts(&mut app).2, - 2, - "the boar and we were rewound and checked" + lane_checks(&mut app), + 5, + "each flush checks its own span: the boar's four, then ours" ); let views = app.world().resource::(); assert!( @@ -338,17 +402,17 @@ fn the_replay_ends_on_the_live_stores() { ); } -/// Two packets with no event between them are one gap: the drain applies both and builds the -/// views once. A fall ahead of the first reads the frame's start, one between the second and the -/// third reads after the second, and the last packet's views are the feed's own, built by none. +/// Two packets with no event between them are one gap: the flush after the second applies both. +/// A fall ahead of the first reads the stores as they were, one between the second and the third +/// reads after the second, and the last reads the live stores. #[test] -fn two_packets_with_no_event_between_make_one_build() { +fn two_packets_with_no_event_between_are_one_gap() { let mut app = client(); app.world_mut() .non_send_resource_mut::() .run(r#"function Look(event, unit) return UnitHealth("targettarget") end"#) .unwrap(); - lane_counts(&mut app); + lane_checks(&mut app); let seen = frame( &mut app, vec![ @@ -368,29 +432,10 @@ fn two_packets_with_no_event_between_make_one_build() { "UNIT_COMBAT:player:50" ] ); - assert_eq!( - lane_counts(&mut app).0, - 2, - "the frame's start and the one gap" - ); } -/// A frame whose events all follow its last write needs no older view than the feed's push: -/// the lane builds and pushes nothing. -#[test] -fn a_frame_whose_events_follow_every_write_pushes_no_old_view() { - let mut app = client(); - lane_counts(&mut app); - assert_eq!( - frame(&mut app, vec![values(WOLF, &health(70)), fall(1)]), - ["UNIT_HEALTH:target:70", "UNIT_COMBAT:player:100"] - ); - let (builds, pushes, _) = lane_counts(&mut app); - assert_eq!((builds, pushes), (0, 0)); -} - -/// A store written past the log fails the rewind's check against the frame-start snapshot: here -/// the target's `MAXHEALTH`, a field no entry of the frame names. +/// A store written past the log fails the rewind's check against the span-start snapshot: here +/// the target's `MAXHEALTH`, a field no entry of the span names. #[cfg(debug_assertions)] #[test] #[should_panic(expected = "a write the log missed")] @@ -415,7 +460,7 @@ fn a_write_the_log_missed_fails_the_rewind() { #[test] fn a_worldport_is_logged_as_the_stores_it_takes() { let mut app = client(); - lane_counts(&mut app); + lane_checks(&mut app); app.world_mut() .resource_mut::() .starts_checked = 0; @@ -444,8 +489,7 @@ struct Stuck(Option); fn fire_stuck(In(_): In) {} /// A drain that stops before the views lane has replayed its entries leaves no rewound store -/// behind: the next frame's feed reads the live store, and the next drain puts the feed's views -/// back, so the target reads the health its last packet wrote. +/// behind, so the target reads, through the host, the health its last packet wrote. #[test] fn a_drain_that_stops_early_leaves_no_rewound_store() { use crate::lanes::LaneApp; @@ -466,42 +510,13 @@ fn a_drain_that_stops_early_leaves_no_rewound_store() { assert!(!views.holds(WOLF), "the stop left nothing rewound"); app.world_mut().resource_mut::().0 = None; assert_eq!(frame(&mut app, vec![]), ["UNIT_HEALTH:target:70"]); - let health = app - .world_mut() - .non_send_resource_mut::() - .eval::("return UnitHealth('target')") - .unwrap(); + let health = crate::script_calls::with_hosted_vm(app.world_mut(), |s| { + s.expect("a VM").eval::("return UnitHealth('target')") + }) + .unwrap(); assert_eq!(health, 70.0); } -/// Updates to units no view reads, between events, build nothing: the lane rewinds only a unit a -/// token can name, and a gap whose entries name none is no build. -#[test] -fn updates_to_units_no_view_reads_build_nothing() { - const FAR: [u64; 3] = [ - 0xF130_0000_0050_0001, - 0xF130_0000_0050_0002, - 0xF130_0000_0050_0003, - ]; - let mut app = client(); - let mob = |hp: u32| [(FIELD_UNIT_HEALTH, hp), (FIELD_UNIT_MAXHEALTH, 100)]; - frame( - &mut app, - FAR.iter() - .map(|&g| created(g, EntityKind::Unit, &mob(100))) - .collect(), - ); - lane_counts(&mut app); - let mut packets = vec![fall(1)]; - for (i, &g) in FAR.iter().enumerate() { - packets.push(values(g, &health(90 - i as u32))); - packets.push(fall(1)); - } - frame(&mut app, packets); - let (builds, pushes, _) = lane_counts(&mut app); - assert_eq!((builds, pushes), (0, 0)); -} - /// Our own death signals `PLAYER_DEAD` inside its packet (`0x6046f0` at `0x6047a3`, then /// `0x6058ae` → `0x6251cc` → `0x495850`), after the packets before it ran whole: it fires after /// the combat line an earlier packet of the frame queued, and `UnitHealth("player")` reads the @@ -534,9 +549,6 @@ fn player_dead_reads_its_packets_health_after_an_earlier_packets_line() { /// line (`0x62c160`) and ends in `SignalDeathState` (`0x6251cc` → `0x495850`). #[test] fn our_deaths_list_signals_before_its_line_and_player_dead_after() { - #[cfg(debug_assertions)] - use bevy::ecs::system::RunSystemOnce; - let mut app = client(); app.world_mut() .resource_mut::() @@ -557,13 +569,8 @@ fn our_deaths_list_signals_before_its_line_and_player_dead_after() { ) .unwrap(); let world = app.world_mut(); - #[cfg(debug_assertions)] - world - .run_system_once(crate::ui_unit::views::mark_frame_start) - .unwrap(); // The packet's end writes the line among the death's legs. crate::net::handlers::dispatch(world, wire([values(ME, &health(0))])); - crate::ui_unit::run_feed_units_once(world); crate::lanes::fire_in_order(world); let seen = world .non_send_resource::() @@ -580,10 +587,8 @@ fn our_deaths_list_signals_before_its_line_and_player_dead_after() { /// The death line's listener runs where the health watcher wrote it, inside its update packet /// (`0x465277` → `0x6046f0` → `0x605860` → `0x62c160`), before the next packet's handler runs /// (`0x537ae5`): its `SendChatMessage` goes out ahead of the name query the next packet's create -/// asks in its handler (`0x5dec12` → `0x609210`). The lanes fire after the whole dispatch until -/// they fire inside it, so the query goes first today. +/// asks in its handler (`0x5dec12` → `0x609210`). #[test] -#[ignore = "the lanes fire inside the dispatch only from the flip on"] fn a_death_lines_listener_sends_ahead_of_the_next_packets_handler() { const STRANGER: u64 = 0x31; let mut app = client(); @@ -702,3 +707,207 @@ fn a_descriptor_level_change_alone_signals_no_level_up() { "{seen:?}" ); } + +/// A friend list of one, Ann, her name cached: a lever no log rewinds, since `GetNumFriends` reads +/// the list at the call (`0x5ad000`), so the count a listener reads names the packets ahead of it. +pub(super) fn one_friend(app: &mut App) -> SessionEvent { + const ANN: u64 = 0x61; + app.world_mut() + .resource_mut::() + .insert_player(ANN, "Ann".into(), None); + SessionEvent::FriendList { + friends: vec![benilla_protocol::messages::FriendEntry { + guid: ANN, + status: benilla_protocol::messages::friend_status::ONLINE, + area: 0, + level: 10, + class: 1, + }], + } +} + +/// A say's listener runs at its packet, before the next packet's handler (`0x537ae5`): its +/// `SendChatMessage` goes out ahead of the name query the next packet's player create asks in its +/// handler (`0x5dec12` → `0x609210`). +#[test] +fn a_says_listener_sends_ahead_of_the_next_packets_query() { + const SPEAKER: u64 = 0x32; + const STRANGER: u64 = 0x31; + let mut app = client(); + let (tx, sent) = crossbeam_channel::unbounded(); + app.insert_resource(crate::net::NetCommands(tx)); + let world = app.world_mut(); + world.resource_mut::().connected = true; + world + .resource_mut::() + .insert_player(SPEAKER, "Ann".into(), None); + world + .non_send_resource::() + .run( + r#"local d = CreateFrame("Frame") + d:RegisterEvent("CHAT_MSG_SAY") + d:SetScript("OnEvent", function() SendChatMessage("hello", "SAY") end)"#, + ) + .unwrap(); + let say = SessionEvent::Chat(benilla_protocol::messages::ChatMessage { + chat_type: benilla_protocol::messages::CHAT_MSG_SAY, + language: 0, + sender_guid: SPEAKER, + target_guid: 0, + sender_name: None, + channel: None, + text: "hi".into(), + chat_tag: 0, + }); + crate::net::handlers::dispatch( + world, + wire_packets(vec![ + vec![say], + vec![created( + STRANGER, + EntityKind::Player, + &[(FIELD_UNIT_HEALTH, 100)], + )], + ]), + ); + crate::lanes::fire_in_order(world); + let order: Vec<&str> = sent + .try_iter() + .filter_map(|c| match c { + crate::net::ClientCommand::Chat { .. } => Some("chat"), + crate::net::ClientCommand::NameQuery { guid: STRANGER } => Some("name query"), + _ => None, + }) + .collect(); + assert_eq!(order, ["chat", "name query"]); +} + +/// Each flush rewinds the views to its own span's start: two target health packets with a friend +/// list between, each `UNIT_HEALTH` listener reading its packet's health and the friends the +/// packets ahead of it left ([`one_friend`]), and each raising flush checking the wolf's store. +#[test] +fn each_flush_rewinds_to_its_own_spans_start() { + let mut app = client(); + let ann = one_friend(&mut app); + app.world_mut() + .non_send_resource_mut::() + .run(r#"function Look(event, unit) return UnitHealth(unit) .. "/" .. GetNumFriends() end"#) + .unwrap(); + lane_checks(&mut app); + assert_eq!( + frame( + &mut app, + vec![values(WOLF, &health(70)), ann, values(WOLF, &health(40))] + ), + ["UNIT_HEALTH:target:70/0", "UNIT_HEALTH:target:40/1"] + ); + assert_eq!(lane_checks(&mut app), 2, "the wolf, once a raising flush"); +} + +/// A held line ages once a frame, not once a flush: its age pass is a frame begin +/// ([`crate::ui_chat::ChatLog::begin_frame`]). A stranger's say waits on his name through a frame +/// of more raising packets than its tries, each fall's listener counting the friends the packets +/// ahead of it left ([`one_friend`]), and shows at the name's answer in the next frame. +#[test] +fn a_held_line_ages_by_frames_not_by_flushes() { + const STRANGER: u64 = 0x31; + let mut app = client(); + let ann = one_friend(&mut app); + app.world_mut() + .non_send_resource_mut::() + .run( + r#"function Look(event, unit) return GetNumFriends() end + local s = CreateFrame("Frame") + s:RegisterEvent("CHAT_MSG_SAY") + s:SetScript("OnEvent", function() table.insert(Seen, "SAY:" .. arg2) end)"#, + ) + .unwrap(); + let say = SessionEvent::Chat(benilla_protocol::messages::ChatMessage { + chat_type: benilla_protocol::messages::CHAT_MSG_SAY, + language: 0, + sender_guid: STRANGER, + target_guid: 0, + sender_name: None, + channel: None, + text: "hi".into(), + chat_tag: 0, + }); + let mut packets = vec![say, fall(1), ann]; + packets.extend((0..crate::ui_chat::NAME_MAX_TRIES).map(|_| fall(1))); + let seen = frame(&mut app, packets); + assert_eq!(seen.len(), usize::from(crate::ui_chat::NAME_MAX_TRIES) + 1); + assert_eq!(seen[0], "UNIT_COMBAT:player:0"); + assert!( + seen[1..].iter().all(|s| s == "UNIT_COMBAT:player:1"), + "the line still waits: {seen:?}" + ); + let name = SessionEvent::PlayerName { + guid: STRANGER, + name: "Zed".into(), + race: 1, + gender: 0, + class: 1, + }; + assert_eq!(frame(&mut app, vec![name]), ["SAY:Zed"]); +} + +/// The dispatch's cost a packet, with each packet's flush and with the frame's one drain alone (the +/// world's interface not up until the drain, so no flush runs): the target's health, which raises +/// `UNIT_HEALTH`; a unit no token names, whose notices fire and signal nothing; and its scale, +/// which queues nothing, so no flush runs. +/// +/// Run with `cargo nextest run -p benilla-app --lib flush_cost --run-ignored only --no-capture`. +#[test] +#[ignore = "a timing, not a check"] +fn flush_cost() { + const PACKETS: u32 = 200; + let mut app = client(); + app.world_mut() + .non_send_resource_mut::() + .run("function Look() return 0 end") + .unwrap(); + let kinds: [(&str, u64, u16); 3] = [ + ("raising", WOLF, FIELD_UNIT_HEALTH), + ("no token's notices", BOAR, FIELD_UNIT_HEALTH), + ("non-raising", BOAR, 4), + ]; + for (what, guid, field) in kinds { + for flush in [true, false] { + let mut times = Vec::new(); + let mut counts = (0, 0); + for round in 0..30u32 { + let packets = wire( + (0..PACKETS).map(|n| values(guid, &[(field, 1 + (round * PACKETS + n) % 99)])), + ); + let world = app.world_mut(); + if !flush { + world.insert_resource(crate::ui_script::PendingEntryUiLoad); + } + let (f0, k0) = crate::lanes::tally(); + let at = std::time::Instant::now(); + crate::net::handlers::dispatch(world, packets); + world.remove_resource::(); + crate::lanes::fire_in_order(world); + times.push(at.elapsed().as_secs_f64() * 1e9 / f64::from(PACKETS)); + let (f1, k1) = crate::lanes::tally(); + counts = (f1 - f0, k1 - k0); + world + .non_send_resource_mut::() + .run("Seen = {}") + .unwrap(); + } + times.sort_by(f64::total_cmp); + eprintln!( + "{what}, {}: {:.0} ns a packet; a frame of {PACKETS}: flushes={} fired={}", + if flush { + "each packet's flush" + } else { + "the drain alone" + }, + times[times.len() / 2], + counts.0, + counts.1 + ); + } + } +} diff --git a/crates/benilla-app/src/lanes/world_map_live_tests.rs b/crates/benilla-app/src/lanes/world_map_live_tests.rs new file mode 100644 index 000000000..85de02fa0 --- /dev/null +++ b/crates/benilla-app/src/lanes/world_map_live_tests.rs @@ -0,0 +1,300 @@ +//! The world map's getters read the state their listener's packet left, at the call, where the +//! reference reads it: the setter `0x4a67a0` reads the active player's explored bytes and the +//! landmark sources as it builds (`0x4a6bf4`, `0x4a6819`), and `GetCorpseMapPosition` reads the +//! corpse cache (`0x4a86df` → `0x4a7960` → `0x492090`). Each packet's handler runs whole before the +//! next (`0x537ae5`), so a listener in one packet of a frame reads that packet's state, not the +//! frame's last. + +use benilla_protocol::{EntityKind, SessionEvent}; +use benilla_ui::script::{UiScript, WorldMapContinentView, WorldMapOverlayView, WorldMapZoneView}; +use benilla_world::map_proj::ZoneRect; +use bevy::prelude::*; +use crossbeam_channel::Sender; + +use super::unit_view_tests::{created, values, wire_packets}; + +const ME: u64 = 0x7; +/// `PLAYER_FIELD_BYTES`, whose byte 1 is the combo count (`0x5ddff0`): the packet whose +/// `PLAYER_COMBO_POINTS` listener reads the map. +const PLAYER_FIELD_BYTES: u16 = 188 + 0x1028 / 4; +/// `PLAYER_FLAGS`, and its ghost bit (`[player+0xe68]+8`, bit 4). +const PLAYER_FLAGS: u16 = 188 + 0x8 / 4; +const GHOST: u32 = 0x10; +/// `PLAYER_EXPLORED_ZONES_1`, the first dword of the explored bytes (`188 + 0xe6c / 4`). +const EXPLORED_1: u16 = 188 + 0xe6c / 4; +/// Elwynn Forest, the one zone, and Northshire Valley inside it, explored by bit 125 (word 3, bit +/// 29), which reveals the zone's overlay and gates its landmark. +const ELWYNN: u32 = 12; +const NORTHSHIRE: u32 = 9; +const NORTHSHIRE_BIT: u32 = 125; +/// The zone's rect, 1000 yards a side from the origin. +const RECT: ZoneRect = ZoneRect { + left: 1000.0, + right: 0.0, + top: 1000.0, + bottom: 0.0, +}; + +/// The whole client, headless, in the world with its frame run. +struct Client { + app: App, + inbound: Sender, +} + +impl Client { + /// One frame of the client's, with `packets` in the inbound channel, each one packet. + fn frame(&mut self, packets: Vec>) { + for ev in wire_packets(packets) { + self.inbound.send(ev).expect("the inbound channel"); + } + self.app.update(); + } + + /// What the combo listener heard, emptied. + fn seen(&mut self) -> Vec { + crate::script_calls::with_hosted_vm(self.app.world_mut(), |s| { + let s = s.expect("a VM"); + let seen = s.eval::>("return Seen").expect("the spy"); + s.run("Seen = {}").expect("the reset"); + seen + }) + } +} + +/// The client with a map of one continent and one zone, Elwynn, whose overlay and whose one +/// `AreaPOI` row, a zone-level landmark in Northshire, wait on bit 125; and a VM whose +/// `PLAYER_COMBO_POINTS` listener selects Elwynn and notes the overlays, the landmarks and the +/// corpse's position it reads. +fn client() -> Client { + let mut app = crate::game_plugins::schedule_tests::headless_client(); + app.insert_resource(bevy::ecs::error::DefaultErrorHandler( + bevy::ecs::error::ignore, + )); + let (tx, _sent) = crossbeam_channel::unbounded(); + app.insert_resource(crate::net::NetCommands(tx)); + let (inbound, rx) = crossbeam_channel::unbounded(); + app.insert_resource(crate::net::NetEvents::for_test(rx)); + app.update(); + let mut script = UiScript::new().expect("a VM"); + script.set_world_map_catalog(vec![WorldMapContinentView { + name: "Eastern Kingdoms".into(), + map_file: "Azeroth".into(), + zones: vec![WorldMapZoneView { + name: "Elwynn Forest".into(), + area_id: ELWYNN, + map_file: "Elwynn".into(), + loc_rect: (RECT.left, RECT.right, RECT.top, RECT.bottom), + overlays: vec![WorldMapOverlayView { + texture: "Interface\\WorldMap\\Elwynn\\NORTHSHIREVALLEY".into(), + width: 200, + height: 176, + explore_bits: vec![NORTHSHIRE_BIT], + ..Default::default() + }], + }], + ..Default::default() + }]); + script + .run( + r#" + Seen = {} + local f = CreateFrame("Frame") + f:RegisterEvent("PLAYER_COMBO_POINTS") + f:SetScript("OnEvent", function() + SetMapZoom(1, 1) + local x, y = GetCorpseMapPosition() + table.insert(Seen, string.format("%d/%d %.3f,%.3f", + GetNumMapOverlays(), GetNumMapLandmarks(), x, y)) + end) + "#, + ) + .expect("the spy"); + app.insert_non_send_resource(script); + app.insert_resource(State::new(crate::client_state::ClientState::InWorld)); + benilla_world::world_point::init_world_point_resources(app.world_mut()); + app.world_mut().resource_mut::().0 = Some(ME); + app.insert_resource(crate::ui_world_map::WorldMapUiData::one_zone_for_test( + 0, ELWYNN, RECT, + )); + app.insert_resource(benilla_world::world_map::CurrentMap(0)); + let area = |explore_flag, exploration_level| benilla_formats::AreaTableRow { + map_id: 0, + zone_id: 0, + explore_flag, + flags: 0, + faction_group_mask: 0, + exploration_level, + name: String::new(), + }; + app.insert_resource(crate::area::AreaTableRes( + benilla_formats::AreaTableCatalog::from_rows(vec![ + (ELWYNN, area(0, -1)), + (NORTHSHIRE, area(NORTHSHIRE_BIT, 0)), + ]), + )); + app.insert_resource(crate::area_poi::AreaPoiRes( + benilla_formats::AreaPoiCatalog::from_rows(vec![( + 1, + benilla_formats::AreaPoi { + importance: 0, + icon: 6, + faction_id: 0, + pos: [500.0, 500.0, 0.0], + continent_id: 0, + // Zone level. + flags: 0x04, + area_id: NORTHSHIRE, + name: "Northshire Abbey".into(), + description: String::new(), + world_state_id: 0, + }, + )]), + )); + let mut c = Client { app, inbound }; + // A frame with no player: the map's projection goes in, and whatever reads the bytes reads + // none. + c.frame(vec![]); + c +} + +/// A packet that sets our combo count to `n`, whose listener reads the map. +fn combo(n: u32) -> Vec { + vec![values(ME, &[(PLAYER_FIELD_BYTES, n << 8)])] +} + +/// `MSG_CORPSE_QUERY`'s found answer, our corpse at `(x, y)` on map 0. +fn corpse_at(x: f32, y: f32) -> Vec { + vec![SessionEvent::CorpseQuery { + found: true, + display_map: 0, + position: [x, y, 0.0], + corpse_map: 0, + }] +} + +/// The not-found answer, which resets the cache. +fn no_corpse() -> Vec { + vec![SessionEvent::CorpseQuery { + found: false, + display_map: -1, + position: [0.0; 3], + corpse_map: 0, + }] +} + +/// Our first create carries Northshire explored, which no watcher signals (a first create runs no +/// notify pass); a later packet's listener selects the map, whose setter reads the bytes at its +/// run (`0x4a6bf4`): the overlay and the landmark they gate show, though a packet after it clears +/// the bit. +#[test] +fn a_selection_reads_the_explored_bytes_its_packet_left() { + let mut c = client(); + c.frame(vec![ + vec![created( + ME, + EntityKind::Player, + &[(EXPLORED_1 + 3, 1 << (NORTHSHIRE_BIT % 32))], + )], + combo(2), + vec![values(ME, &[(EXPLORED_1 + 3, 0)])], + ]); + assert_eq!(c.seen(), ["1/1 0.000,0.000"]); +} + +/// The world-state init's setter run (`0x48fa0d` → `0x4a6cdf`) reads the explored bytes as it +/// builds (`0x4a6bf4`): after our create, whose bits no watcher signals, the init's +/// `WORLD_MAP_UPDATE` listener on the map already shown reads the overlay and the landmark the +/// bits reveal. +#[test] +fn a_world_state_rebuild_reads_the_bytes_its_packet_left() { + let mut c = client(); + crate::script_calls::with_hosted_vm(c.app.world_mut(), |s| { + s.expect("a VM") + .run( + r#" + SetMapZoom(1, 1) + local f = CreateFrame("Frame") + f:RegisterEvent("WORLD_MAP_UPDATE") + f:SetScript("OnEvent", function() + table.insert(Seen, "update " .. GetNumMapOverlays() .. "/" .. GetNumMapLandmarks()) + end) + "#, + ) + .expect("the listener") + }); + c.seen(); + c.frame(vec![ + vec![created( + ME, + EntityKind::Player, + &[(EXPLORED_1 + 3, 1 << (NORTHSHIRE_BIT % 32))], + )], + vec![SessionEvent::WorldStates { + scope: Some((0, ELWYNN)), + states: Vec::new(), + }], + ]); + assert_eq!( + c.seen().first().map(String::as_str), + Some("update 1/1"), + "the init's run reads the bytes" + ); +} + +/// Where `(x, y)` lands on Elwynn, the zone the listener selects. +fn on_elwynn(x: f32, y: f32) -> String { + let (u, v) = crate::ui_world_map::project_on_displayed( + &crate::ui_world_map::WorldMapUiData::one_zone_for_test(0, ELWYNN, RECT), + (1, 1, None), + 0, + x, + y, + ) + .expect("on the zone"); + format!("0/0 {u:.3},{v:.3}") +} + +/// The corpse's position is read at the call: a listener between two answers of a frame reads +/// the first's, projected onto the zone it selected, where the frame before held another. We are +/// a ghost, the one state the answer is stored for (`0x48f766`-`0x48f779`). +#[test] +fn the_corpse_position_reads_its_packets_answer() { + let mut c = client(); + c.frame(vec![ + vec![created(ME, EntityKind::Player, &[(PLAYER_FLAGS, GHOST)])], + corpse_at(250.0, 750.0), + ]); + c.frame(vec![corpse_at(600.0, 300.0), combo(2), no_corpse()]); + assert_eq!(c.seen(), [on_elwynn(600.0, 300.0)]); + c.frame(vec![combo(0)]); + assert_eq!( + c.seen(), + ["0/0 0.000,0.000"], + "the reset cache reads nothing" + ); +} + +/// A found answer that reaches a living player resets the cache, as any answer but a ghost's +/// does (`0x48f766`-`0x48f779` → `0x48f7e3`): the corpse the cache held goes, and a listener +/// after the answer reads 0, 0. +#[test] +fn a_found_answer_for_the_living_clears_the_corpse() { + let mut c = client(); + c.frame(vec![vec![created(ME, EntityKind::Player, &[])]]); + c.app + .world_mut() + .resource_mut::() + .corpse = Some(crate::death::CorpsePoint { + display_map: 0, + position: [250.0, 750.0, 0.0], + corpse_map: 0, + }); + c.frame(vec![combo(2)]); + assert_eq!( + c.seen(), + [on_elwynn(250.0, 750.0)], + "control: the cache shows" + ); + c.frame(vec![corpse_at(600.0, 300.0), combo(0)]); + assert_eq!(c.seen(), ["0/0 0.000,0.000"]); +} diff --git a/crates/benilla-app/src/lanes/world_map_update_tests.rs b/crates/benilla-app/src/lanes/world_map_update_tests.rs new file mode 100644 index 000000000..f345d4a61 --- /dev/null +++ b/crates/benilla-app/src/lanes/world_map_update_tests.rs @@ -0,0 +1,400 @@ +//! `WORLD_MAP_UPDATE` from the explored bytes' watcher and the gossip marker. The active player's +//! `PLAYER_EXPLORED_ZONES` carries a mirror watcher (`0x4a6430` arms `0x4a6460` on section 4, +//! `+0xe6c`, 0x100 bytes), whose run in the update packet's notify pass (`0x465330`) calls the map +//! setter (`0x4a6477` → `0x4a67a0`): the overlays follow the bytes it reads, and it signals +//! (`0x4a6ce4`), whole before a later packet's events and after an earlier one's (`0x5384d0`). +//! The marker's set in `SMSG_GOSSIP_POI`'s handler (`0x6dac93`) and its clears in the minimap's +//! update (`0x6d9411`, `0x6d9a4c`) call the same setter where they run. + +use benilla_protocol::messages::ObjectType; +use benilla_protocol::{ObjectFields, SessionEvent}; +use benilla_ui::script::{UiScript, WorldMapContinentView, WorldMapOverlayView, WorldMapZoneView}; +use bevy::prelude::*; + +const ME: u64 = 0x7; +/// `PLAYER_FIELD_BYTES`, whose byte 1 is the combo count (`0x5ddff0`), the neighbour each golden +/// interleaves with. +const PLAYER_FIELD_BYTES: u16 = 188 + 0x1028 / 4; +/// `PLAYER_EXPLORED_ZONES_1`, the first dword of the watched range (`188 + 0xe6c / 4`). +const EXPLORED_1: u16 = 188 + 0xe6c / 4; +/// The dword just below the range, which no watcher covers. +const BELOW_EXPLORED: u16 = EXPLORED_1 - 1; + +fn values(pairs: &[(u16, u32)]) -> Vec { + vec![ + SessionEvent::ObjectValues { + guid: ME, + fields: ObjectFields::from_pairs(pairs), + }, + SessionEvent::ObjectUpdateEnd, + ] +} + +fn combo(n: u32) -> Vec { + values(&[(PLAYER_FIELD_BYTES, n << 8)]) +} + +/// Northshire Valley's `AreaBit` 125 as an update: word 3, bit 29. +fn northshire() -> Vec { + values(&[(EXPLORED_1 + 3, 1 << 29)]) +} + +/// Bit 126 beside it, which the fixture's zone carries no overlay for. +fn northshire_and_other() -> Vec { + values(&[(EXPLORED_1 + 3, 1 << 29 | 1 << 30)]) +} + +/// The client in the world as [`ME`], with a map of one zone that shows an overlay once bit 125 is +/// explored, selected, and a VM whose spy records `WORLD_MAP_UPDATE` with the overlays a handler +/// counts through the getter, and the combo event. +fn client() -> App { + let mut app = crate::game_plugins::schedule_tests::headless_client_unrun(); + // In the world with the interface up, so the dispatch fires each packet's lanes. + app.insert_resource(bevy::prelude::State::new( + crate::client_state::ClientState::InWorld, + )); + let world = app.world_mut(); + let me = world + .spawn(( + crate::net::Guid(ME), + crate::net::SelfPlayer, + crate::net::ObjectStore(ObjectFields::from_pairs(&[]).into_created(ObjectType::Player)), + )) + .id(); + world + .resource_mut::() + .0 + .insert(ME, me); + world.resource_mut::().0 = Some(ME); + let mut script = UiScript::new().unwrap(); + script.set_world_map_catalog(vec![WorldMapContinentView { + name: "Eastern Kingdoms".into(), + map_file: "Azeroth".into(), + zones: vec![WorldMapZoneView { + name: "Elwynn Forest".into(), + area_id: 12, + map_file: "Elwynn".into(), + overlays: vec![WorldMapOverlayView { + texture: "Interface\\WorldMap\\Elwynn\\NORTHSHIREVALLEY".into(), + width: 200, + height: 176, + explore_bits: vec![125], + ..Default::default() + }], + ..Default::default() + }], + ..Default::default() + }]); + script.tick(0.01); + script + .run( + r#" + SetMapZoom(1, 1) + Heard = {} + local f = CreateFrame("Frame") + f:RegisterEvent("WORLD_MAP_UPDATE") + f:RegisterEvent("PLAYER_COMBO_POINTS") + f:SetScript("OnEvent", function() + if event == "WORLD_MAP_UPDATE" then + table.insert(Heard, event .. ":" .. GetNumMapOverlays()) + else + table.insert(Heard, event) + end + end) + "#, + ) + .unwrap(); + world.insert_non_send_resource(script); + app +} + +/// One frame: the packets through the handler table, then the lanes' drain; what the spy heard. +fn frame(app: &mut App, packets: impl IntoIterator>) -> Vec { + let world = app.world_mut(); + crate::net::handlers::dispatch(world, packets.into_iter().flatten().collect()); + crate::lanes::fire_in_order(world); + let s = world.non_send_resource_mut::(); + let out = s.eval::>("return Heard").unwrap(); + s.run("Heard = {}").unwrap(); + out +} + +/// The watcher signals inside the update that moved the bytes: between the neighbouring packets' +/// events, in either order. +#[test] +fn an_explored_update_signals_the_map_between_its_neighbours() { + let mut app = client(); + assert_eq!( + frame(&mut app, [combo(2), northshire(), combo(0)]), + [ + "PLAYER_COMBO_POINTS", + "WORLD_MAP_UPDATE:1", + "PLAYER_COMBO_POINTS" + ] + ); + assert_eq!( + frame(&mut app, [northshire_and_other(), combo(2)]), + ["WORLD_MAP_UPDATE:1", "PLAYER_COMBO_POINTS"], + "a second update is a second signal, ahead of the packet after it" + ); +} + +/// A handler reads the bits its packet wrote through the map's getters: no overlay before, the +/// revealed zone's after, none again when a later update clears the bit. +#[test] +fn a_listener_reads_the_newly_explored_zone_through_the_getters() { + let mut app = client(); + assert_eq!( + app.world() + .non_send_resource::() + .eval::("return GetNumMapOverlays()") + .unwrap(), + 0, + "control: nothing explored yet" + ); + assert_eq!( + frame(&mut app, [northshire()]), + ["WORLD_MAP_UPDATE:1"], + "the handler counted the overlay the packet revealed" + ); + assert_eq!( + frame(&mut app, [values(&[(EXPLORED_1 + 3, 0)])]), + ["WORLD_MAP_UPDATE:0"] + ); +} + +/// An update that moves no byte of the range fires nothing: one beside it, and one that writes the +/// bytes the player already has. +#[test] +fn an_update_that_moves_no_explored_byte_fires_nothing() { + let mut app = client(); + assert_eq!( + frame(&mut app, [northshire()]), + ["WORLD_MAP_UPDATE:1"], + "control: the watcher is armed" + ); + assert_eq!( + frame( + &mut app, + [ + values(&[(BELOW_EXPLORED, 5)]), + northshire(), + values(&[(EXPLORED_1 + 3, 1 << 29), (BELOW_EXPLORED, 6)]), + ] + ), + Vec::::new() + ); +} + +/// The guard's directions at `pos`, as `SMSG_GOSSIP_POI` carries them. +fn directions(pos: [f32; 2]) -> Vec { + vec![SessionEvent::GossipPoi( + benilla_protocol::messages::GossipPoi { + flags: 99, + pos, + icon: 6, + data: 0, + name: "Stormwind Warrior Trainer".into(), + }, + )] +} + +/// Where the marker drops, far from where we stand. +const MARKER: [f32; 2] = [50.0, 50.0]; + +/// [`client`] with the map data the landmark sources read, a projection that puts a world point +/// at its own UV, and a second spy that counts the landmarks on `WORLD_MAP_UPDATE`. +fn landmark_client() -> App { + let mut app = client(); + let world = app.world_mut(); + world.insert_resource(benilla_world::world_map::CurrentMap(0)); + world.init_resource::(); + let start = std::time::Instant::now(); + let mut clock = Time::::new(start); + clock.update_with_instant(start); + world.insert_resource(clock); + world.insert_resource(ClockStart(start)); + world.insert_resource(crate::area::AreaTableRes( + benilla_formats::AreaTableCatalog::from_rows(Vec::new()), + )); + let mut script = world.non_send_resource_mut::(); + script.set_world_loc_projector(Box::new(|_, _, x, y| Some((x, y)))); + script.tick(0.01); + script + .run( + r#" + local f = CreateFrame("Frame") + f:RegisterEvent("WORLD_MAP_UPDATE") + f:SetScript("OnEvent", function() + table.insert(Heard, "landmarks:" .. GetNumMapLandmarks()) + end) + Heard = {} + "#, + ) + .unwrap(); + app +} + +/// The hand-driven clock's start. +#[derive(Resource)] +struct ClockStart(std::time::Instant); + +/// The real clock `secs` past its start. +fn clock_at(app: &mut App, secs: u64) { + let start = app.world().resource::().0; + app.world_mut() + .resource_mut::>() + .update_with_instant(start + std::time::Duration::from_secs(secs)); +} + +fn marker_held(app: &App) -> bool { + app.world() + .resource::() + .poi + .is_some() +} + +/// [`frame`] with the minimap's update between the packets and the drain, as the frame runs it: +/// the marker's clears (`crate::poi_marker::expire_marker`). +fn frame_with_minimap( + app: &mut App, + packets: impl IntoIterator>, +) -> Vec { + let world = app.world_mut(); + crate::net::handlers::dispatch(world, packets.into_iter().flatten().collect()); + world + .run_system_cached(crate::poi_marker::expire_marker) + .unwrap(); + crate::lanes::fire_in_order(world); + let s = world.non_send_resource_mut::(); + let out = s.eval::>("return Heard").unwrap(); + s.run("Heard = {}").unwrap(); + out +} + +/// The marker's set re-selects the shown map inside its handler (`0x4e28aa` → `0x6dac10` → +/// `0x6dac93`): `WORLD_MAP_UPDATE` falls between the neighbouring packets' events, its listeners +/// reading the marker in the landmark list, and a second set signals again. +#[test] +fn the_gossip_marker_signals_the_map_between_its_neighbours() { + let mut app = landmark_client(); + assert_eq!( + frame_with_minimap(&mut app, [combo(2), directions(MARKER), combo(0)]), + [ + "PLAYER_COMBO_POINTS", + "WORLD_MAP_UPDATE:0", + "landmarks:1", + "PLAYER_COMBO_POINTS" + ] + ); + assert_eq!( + frame_with_minimap(&mut app, [directions(MARKER), combo(2)]), + ["WORLD_MAP_UPDATE:0", "landmarks:1", "PLAYER_COMBO_POINTS"], + "the same directions again are a second set, which signals whether or not the list moved" + ); +} + +/// Arriving within 10 yards clears the marker in the minimap's update (`0x6d9a08`-`0x6d9a4c`), +/// whose re-select signals in that frame, after its packets' events, its listeners reading the +/// list without the marker; the next frame's packets come after it. +#[test] +fn arriving_at_the_marker_signals_the_map_in_its_frame() { + let mut app = landmark_client(); + frame_with_minimap(&mut app, [directions(MARKER)]); + app.world_mut().resource_mut::().pos = + benilla_assets::coords::wow_to_bevy([MARKER[0] + 3.0, MARKER[1], 0.0]); + assert_eq!( + frame_with_minimap(&mut app, [combo(2)]), + ["PLAYER_COMBO_POINTS", "WORLD_MAP_UPDATE:0", "landmarks:0"] + ); + assert_eq!( + frame_with_minimap(&mut app, [combo(0)]), + ["PLAYER_COMBO_POINTS"], + "the clear signalled once" + ); +} + +/// The deadline, 480 seconds past the set (`0x6dac7e`), clears the marker in the minimap's update +/// and re-selects the map (`0x6d93d0`-`0x6d9411`): one signal in that frame, after its packets' +/// events, the player never having moved. +#[test] +fn the_deadline_signals_the_map_in_its_frame() { + let mut app = landmark_client(); + frame_with_minimap(&mut app, [directions(MARKER)]); + clock_at(&mut app, 479); + assert_eq!( + frame_with_minimap(&mut app, [combo(2)]), + ["PLAYER_COMBO_POINTS"], + "control: a second short of the deadline" + ); + clock_at(&mut app, 480); + assert_eq!( + frame_with_minimap(&mut app, [combo(0)]), + ["PLAYER_COMBO_POINTS", "WORLD_MAP_UPDATE:0", "landmarks:0"] + ); + assert!(!marker_held(&app)); + assert_eq!( + frame_with_minimap(&mut app, [combo(2)]), + ["PLAYER_COMBO_POINTS"], + "the deadline fired once" + ); +} + +/// A `/reload` runs the world-enter cascade (`0x490168` → `0x4908c0`), whose minimap leg +/// (`0x49096f` → `0x4ed9d0` → `0x6d8e10`) zeroes the marker's record (`0x6d8fb0`) with no +/// signal and leaves its deadline: at the deadline the update still clears and re-selects the +/// map, one late `WORLD_MAP_UPDATE`. +#[test] +fn a_reload_drops_the_marker_and_its_deadline_still_signals() { + let mut app = landmark_client(); + frame_with_minimap(&mut app, [directions(MARKER)]); + assert!(marker_held(&app), "control: the marker is set"); + app.world_mut() + .resource_mut::() + .push(crate::ui_world_enter::Entry::Reload); + let heard = frame_with_minimap(&mut app, []); + assert!( + !heard.iter().any(|e| e.starts_with("WORLD_MAP_UPDATE")), + "the cascade's clear signals nothing: {heard:?}" + ); + assert!(!marker_held(&app), "the cascade zeroed the record"); + assert_eq!( + frame_with_minimap(&mut app, [combo(2)]), + ["PLAYER_COMBO_POINTS"] + ); + clock_at(&mut app, 480); + assert_eq!( + frame_with_minimap(&mut app, [combo(0)]), + ["PLAYER_COMBO_POINTS", "WORLD_MAP_UPDATE:0", "landmarks:0"], + "the kept deadline re-selects the map" + ); +} + +/// Arrival is tested only in an update whose player position or map moved since the cached one +/// (`0x6d9419`-`0x6d9459`, `0x6d95c4` → `0x6d9a58`): a marker dropped within 10 yards of a player +/// standing still stays, and the first step clears it. +#[test] +fn arrival_waits_for_an_update_that_moved() { + let mut app = landmark_client(); + let here = [MARKER[0] + 3.0, MARKER[1]]; + app.world_mut().resource_mut::().pos = + benilla_assets::coords::wow_to_bevy([here[0], here[1], 0.0]); + frame_with_minimap(&mut app, [combo(2)]); + assert_eq!( + frame_with_minimap(&mut app, [directions(MARKER)]), + ["WORLD_MAP_UPDATE:0", "landmarks:1"], + "set beside a player standing still: no arrival" + ); + assert_eq!( + frame_with_minimap(&mut app, [combo(0)]), + ["PLAYER_COMBO_POINTS"] + ); + assert!(marker_held(&app)); + app.world_mut().resource_mut::().pos = + benilla_assets::coords::wow_to_bevy([here[0] - 1.0, here[1], 0.0]); + assert_eq!( + frame_with_minimap(&mut app, [combo(2)]), + ["PLAYER_COMBO_POINTS", "WORLD_MAP_UPDATE:0", "landmarks:0"], + "the step is an arrival" + ); +} diff --git a/crates/benilla-app/src/lanes/world_state_live_tests.rs b/crates/benilla-app/src/lanes/world_state_live_tests.rs new file mode 100644 index 000000000..85ff3a81a --- /dev/null +++ b/crates/benilla-app/src/lanes/world_state_live_tests.rs @@ -0,0 +1,143 @@ +//! The world-state readout's rows are read at the call (`0x4c5a70`), and the zone-defense flag that +//! admits its `Type` 1 rows moves inside the channel notice that confirms or frees the defense +//! slot (`0x49bbbf`, `0x49bc41` → `0x49bd50`), which signals `UPDATE_WORLD_STATES` there +//! (`0x49bdd6`): the confirm's ahead of its `CHAT_MSG_CHANNEL_NOTICE` (`0x49c0c2` before +//! `0x49c5b0`), the free's after it (`0x49c5c2`). A listener reads the flag its own notice left, +//! not the frame's last. + +use benilla_protocol::messages::{channel_notice, ChannelNoticeTail}; +use benilla_protocol::SessionEvent; +use benilla_ui::script::UiScript; +use bevy::prelude::*; +use crossbeam_channel::Sender; + +use super::unit_view_tests::wire_packets; + +/// Eastern Plaguelands, the scope of the init. +const EPL: u32 = 139; +const DEFENSE: &str = "LocalDefense - Eastern Plaguelands"; + +/// The whole client, headless, in the world with its frame run. +struct Client { + app: App, + inbound: Sender, +} + +impl Client { + fn frame(&mut self, packets: Vec>) { + for ev in wire_packets(packets) { + self.inbound.send(ev).expect("the inbound channel"); + } + self.app.update(); + } + + fn heard(&mut self) -> Vec { + crate::script_calls::with_hosted_vm(self.app.world_mut(), |s| { + let s = s.expect("a VM"); + let heard = s.eval::>("return Heard").expect("the spy"); + s.run("Heard = {}").expect("the reset"); + heard + }) + } +} + +/// The client with two readout rows for Eastern Plaguelands, one always up and one up only with +/// the defense channel joined, our join of that channel sent (its slot pending), and a VM whose +/// listeners note the rows they read on `UPDATE_WORLD_STATES` and on each channel notice. +fn client() -> Client { + let mut app = crate::game_plugins::schedule_tests::headless_client(); + app.insert_resource(bevy::ecs::error::DefaultErrorHandler( + bevy::ecs::error::ignore, + )); + let (tx, _sent) = crossbeam_channel::unbounded(); + app.insert_resource(crate::net::NetCommands(tx)); + let (inbound, rx) = crossbeam_channel::unbounded(); + app.insert_resource(crate::net::NetEvents::for_test(rx)); + app.update(); + let script = UiScript::new().expect("a VM"); + script + .run( + r#" + Heard = {} + local f = CreateFrame("Frame") + f:RegisterEvent("UPDATE_WORLD_STATES") + f:RegisterEvent("CHAT_MSG_CHANNEL_NOTICE") + f:SetScript("OnEvent", function() + local tag = event == "UPDATE_WORLD_STATES" and "readout" or arg1 + table.insert(Heard, tag .. ":" .. GetNumWorldStateUI()) + end) + "#, + ) + .expect("the spy"); + app.insert_non_send_resource(script); + app.insert_resource(State::new(crate::client_state::ClientState::InWorld)); + benilla_world::world_point::init_world_point_resources(app.world_mut()); + let row = |ui_type| benilla_formats::WorldStateUiRow { + map_id: 0, + area_id: EPL, + icon: String::new(), + text: String::new(), + tooltip: String::new(), + state_variable: 0, + ui_type, + dynamic_icon: String::new(), + dynamic_tooltip: String::new(), + extended_ui: String::new(), + extended_ui_state: [0; 3], + }; + app.insert_resource(crate::world_state_ui::WorldStateUiRes( + benilla_formats::WorldStateUiCatalog::from_rows(vec![(1, row(0)), (2, row(1))]), + )); + let mut channels = crate::ui_chat::ChannelState { + channels: benilla_formats::ChatChannelsCatalog::from_rows(vec![ + benilla_formats::ChatChannelRow { + id: 22, + flags: 0x1_0003, + pattern: "LocalDefense - %s".into(), + shortcut: "LocalDefense".into(), + }, + ]), + zone_mask: Some(0), + ..Default::default() + }; + channels.claim_slot(DEFENSE, 22); + app.insert_resource(channels); + let mut c = Client { app, inbound }; + c.frame(vec![vec![SessionEvent::WorldStates { + scope: Some((0, EPL)), + states: Vec::new(), + }]]); + c.frame(vec![]); + c +} + +fn notice(byte: u8, tail: ChannelNoticeTail) -> Vec { + vec![SessionEvent::ChannelNotify { + notice: byte, + channel: DEFENSE.into(), + tail, + }] +} + +/// The join's confirm sets the flag and signals the readout ahead of its own notice, both reading +/// the defense row; the leave's notice in the same frame still reads it, and its free clears the +/// flag and signals after it, reading the row gone. +#[test] +fn the_defense_flag_moves_and_signals_inside_its_notice() { + let mut c = client(); + assert_eq!(c.heard(), ["readout:1"], "control: the init's signal"); + c.frame(vec![ + notice( + channel_notice::YOU_JOINED, + ChannelNoticeTail::YouJoined { + flags: 0, + instance: 0, + }, + ), + notice(channel_notice::YOU_LEFT, ChannelNoticeTail::Empty), + ]); + assert_eq!( + c.heard(), + ["readout:2", "YOU_JOINED:2", "YOU_LEFT:2", "readout:1"] + ); +} diff --git a/crates/benilla-app/src/lanes/worn_live_tests.rs b/crates/benilla-app/src/lanes/worn_live_tests.rs new file mode 100644 index 000000000..67dd46bb5 --- /dev/null +++ b/crates/benilla-app/src/lanes/worn_live_tests.rs @@ -0,0 +1,269 @@ +//! The worn slots through the whole client: the slot getters look the item up in the player's +//! list as they run (`GetItemInSlot` `0x6228a0`; `GetInventoryItemLink` at `0x4c8cd3`), and +//! `GetWeaponEnchantInfo` its weapons and their deadlines (`0x4c97ca`, `0x5d9d00`), so a +//! listener reads the doll its own packet left: an equip's `UNIT_INVENTORY_CHANGED` reads the +//! item its packet seated, and a line between two writes reads the first. + +use benilla_protocol::field::{FIELD_PLAYER_INV_SLOT_HEAD, FIELD_PLAYER_VISIBLE_ITEM_1_CREATOR}; +use benilla_protocol::messages::{ChatMessage, ObjectType, CHAT_MSG_SYSTEM}; +use benilla_protocol::{EntityKind, ObjectFields, SessionEvent}; +use benilla_ui::script::UiScript; +use bevy::prelude::*; +use crossbeam_channel::Sender; + +use super::unit_view_tests::{created, values, wire_packets}; + +const ME: u64 = 0x7; +/// Worn on the head, seat 0, at the start. +const HELM: (u64, u32) = (item(1), 7366); +/// In the backpack's first seat, 23, at the start. +const SPARE: (u64, u32) = (item(2), 2361); +/// In the main hand, seat 15, with a temporary enchantment of five charges. +const SWORD: (u64, u32) = (item(3), 25); +/// In the first bank bag slot at the start, and the bag that takes its place. +const BAG: (u64, u32) = (item(4), 4500); +const OTHER_BAG: (u64, u32) = (item(5), 4501); + +/// `ITEM_FIELD_ENCHANTMENT` slot 1, the temporary one: its id and its charges. +const TEMP_ENCHANT: u16 = 25; +const TEMP_CHARGES: u16 = 27; +/// `ITEM_FIELD_STACK_COUNT`. +const STACK: u16 = 14; +/// `PLAYER_FIELD_BANK_BAG_SLOT_1`. +const BANK_BAG_1: u16 = 612; +/// `PLAYER_VISIBLE_ITEM_1_0`, the head's shown entry. +const VISIBLE_HEAD: u16 = FIELD_PLAYER_VISIBLE_ITEM_1_CREATOR + 2; + +const fn item(low: u64) -> u64 { + (benilla_protocol::guid::HIGH_ITEM as u64) << 48 | low +} + +/// The spy: each `UNIT_INVENTORY_CHANGED` with the head's entry as it fires, and each system +/// line with the main hand's temporary charges and the bank bag's entry as it shows. +const SPY: &str = r#"Seen = {} + local function entry(slot) + local _, _, id = string.find(GetInventoryItemLink("player", slot) or "", "item:(%d+)") + return id or "none" + end + local f = CreateFrame("Frame") + f:RegisterEvent("UNIT_INVENTORY_CHANGED") + f:RegisterEvent("CHAT_MSG_SYSTEM") + f:SetScript("OnEvent", function() + if event == "UNIT_INVENTORY_CHANGED" then + table.insert(Seen, "INV:" .. entry(1)) + else + local _, _, charges = GetWeaponEnchantInfo() + table.insert(Seen, arg1 .. ":" .. tostring(charges) .. ":" .. entry(64)) + end + end)"#; + +/// The whole client, headless, in the world with its frame run. +struct Client { + app: App, + inbound: Sender, +} + +impl Client { + /// One frame, with `packets` in the inbound channel, each one packet. + fn frame(&mut self, packets: Vec>) { + for ev in wire_packets(packets) { + self.inbound.send(ev).expect("the inbound channel"); + } + self.app.update(); + } + + /// What the spy heard since the last call. + fn seen(&mut self) -> Vec { + crate::script_calls::eval_in_vm(self.app.world(), "local s = Seen Seen = {} return s") + } +} + +/// One of our items, with `extra` fields. +fn item_create((guid, entry): (u64, u32), container: bool, extra: &[(u16, u32)]) -> SessionEvent { + let mut pairs = vec![ + (2, if container { 0x7 } else { 0x3 }), + (3, entry), + (6, ME as u32), + (8, ME as u32), + (STACK, 1), + ]; + pairs.extend_from_slice(extra); + SessionEvent::ItemCreate { + guid, + container, + fields: ObjectFields::from_pairs(&pairs).into_created(if container { + ObjectType::Container + } else { + ObjectType::Item + }), + } +} + +/// `guid` in flat seat `seat` of our array. +fn seat(seat: u16, guid: u64) -> [(u16, u32); 2] { + let lo = FIELD_PLAYER_INV_SLOT_HEAD + 2 * seat; + [(lo, guid as u32), (lo + 1, (guid >> 32) as u32)] +} + +fn system(text: &str) -> SessionEvent { + SessionEvent::Chat(ChatMessage { + chat_type: CHAT_MSG_SYSTEM, + language: 0, + sender_guid: 0, + target_guid: 0, + sender_name: None, + channel: None, + text: text.into(), + chat_tag: 0, + }) +} + +/// The client in the world as [`ME`], wearing [`HELM`] and [`SWORD`], carrying [`SPARE`], with +/// [`BAG`] in the first bank bag slot and a banker open; the spy emptied. +fn client() -> Client { + let mut app = crate::game_plugins::schedule_tests::headless_client(); + app.insert_resource(bevy::ecs::error::DefaultErrorHandler( + bevy::ecs::error::ignore, + )); + let (tx, _sent) = crossbeam_channel::unbounded(); + app.insert_resource(crate::net::NetCommands(tx)); + let (inbound, rx) = crossbeam_channel::unbounded(); + app.insert_resource(crate::net::NetEvents::for_test(rx)); + app.update(); + let script = UiScript::new().expect("a VM"); + script.run(SPY).expect("the spy"); + app.insert_non_send_resource(script); + app.insert_resource(State::new(crate::client_state::ClientState::InWorld)); + benilla_world::world_point::init_world_point_resources(app.world_mut()); + app.world_mut().resource_mut::().0 = Some(ME); + { + let mut items = app.world_mut().resource_mut::(); + for (_, entry) in [HELM, SPARE, SWORD, BAG, OTHER_BAG] { + items.insert_template(entry, Some(crate::items::test_template("Gear"))); + } + } + let mut c = Client { app, inbound }; + let mut me = vec![(VISIBLE_HEAD, HELM.1)]; + me.extend(seat(0, HELM.0)); + me.extend(seat(23, SPARE.0)); + me.extend(seat(15, SWORD.0)); + me.extend([ + (BANK_BAG_1, BAG.0 as u32), + (BANK_BAG_1 + 1, (BAG.0 >> 32) as u32), + ]); + c.frame(vec![ + vec![item_create(HELM, false, &[])], + vec![item_create(SPARE, false, &[])], + vec![item_create( + SWORD, + false, + &[(TEMP_ENCHANT, 7), (TEMP_CHARGES, 5)], + )], + vec![item_create(BAG, true, &[])], + vec![item_create(OTHER_BAG, true, &[])], + vec![created(ME, EntityKind::Player, &me)], + ]); + // The banker's cell in the VM, which the open writes beside it (`0x4f850e`), for the bank + // bags' gate (`0x6228ad`). + crate::script_calls::with_hosted_vm(c.app.world_mut(), |s| { + s.expect("a VM") + .set_bank(Some(benilla_ui::script::BankState::default())) + }); + c.frame(vec![]); + c.seen(); + c +} + +/// A swap of the head and the backpack seat and its swap back in one frame, each packet seating +/// the item and showing its entry as an equip's does: each packet's visible-item watch signals +/// `UNIT_INVENTORY_CHANGED` there, and its listener reads the head its own packet seated, not the +/// frame's last. +#[test] +fn an_equips_listener_reads_the_item_its_packet_seated() { + let mut c = client(); + let wear = |head: (u64, u32), spare: (u64, u32)| -> Vec<(u16, u32)> { + let mut pairs = vec![(VISIBLE_HEAD, head.1)]; + pairs.extend(seat(0, head.0)); + pairs.extend(seat(23, spare.0)); + pairs + }; + c.frame(vec![ + vec![values(ME, &wear(SPARE, HELM))], + vec![values(ME, &wear(HELM, SPARE))], + ]); + let heard: Vec = c.seen(); + assert_eq!( + heard, + [format!("INV:{}", SPARE.1), format!("INV:{}", HELM.1)] + ); +} + +/// Two writes of the main hand's temporary charges and of the first bank bag slot, and a line +/// after each, in one frame: each line reads `GetWeaponEnchantInfo`'s charges and the bank bag's +/// item as the packets before it left them (`0x4c97ca`, `0x4c8cd3`). +#[test] +fn a_line_between_two_writes_reads_the_first() { + let mut c = client(); + let bank_bag = |guid: u64| { + [ + (BANK_BAG_1, guid as u32), + (BANK_BAG_1 + 1, (guid >> 32) as u32), + ] + }; + c.frame(vec![ + vec![values(SWORD.0, &[(TEMP_CHARGES, 3)])], + vec![values(ME, &bank_bag(OTHER_BAG.0))], + vec![system("between")], + vec![values(SWORD.0, &[(TEMP_CHARGES, 1)])], + vec![values(ME, &bank_bag(BAG.0))], + vec![system("after")], + ]); + let lines: Vec = c + .seen() + .into_iter() + .filter(|l| !l.starts_with("INV:")) + .collect(); + assert_eq!( + lines, + [ + format!("between:3:{}", OTHER_BAG.1), + format!("after:1:{}", BAG.1) + ] + ); +} + +/// The second spy: each system line with the main hand's temporary enchantment's time left, long +/// past five minutes or short of it. +const LEFT_SPY: &str = r#"Left = {} + local f = CreateFrame("Frame") + f:RegisterEvent("CHAT_MSG_SYSTEM") + f:SetScript("OnEvent", function() + local _, left = GetWeaponEnchantInfo() + local span = left and (left > 300000 and "long" or "short") or "none" + table.insert(Left, arg1 .. ":" .. span) + end)"#; + +/// Two enchant-time updates of the main hand in one frame, and a line after each: each line reads +/// `GetWeaponEnchantInfo`'s time left as the packets before it set the deadline (`0x5d9cc0` in its +/// packet, read at the call by `0x5d9d00`), not as the frame's last left it. +#[test] +fn a_line_between_two_enchant_times_reads_the_first() { + let mut c = client(); + crate::script_calls::with_hosted_vm(c.app.world_mut(), |s| { + s.expect("a VM").run(LEFT_SPY).expect("the spy") + }); + let time = |seconds| SessionEvent::ItemEnchantTime { + item_guid: SWORD.0, + slot: 1, + seconds, + }; + c.frame(vec![ + vec![time(600)], + vec![system("between")], + vec![time(60)], + vec![system("after")], + ]); + let lines: Vec = + crate::script_calls::eval_in_vm(c.app.world(), "local s = Left Left = {} return s"); + assert_eq!(lines, ["between:long", "after:short"]); +} diff --git a/crates/benilla-app/src/lib.rs b/crates/benilla-app/src/lib.rs index 4008d945c..8f297d2e1 100644 --- a/crates/benilla-app/src/lib.rs +++ b/crates/benilla-app/src/lib.rs @@ -136,7 +136,6 @@ mod ui_craft; mod ui_dialog_verbs; mod ui_dressup; mod ui_duel; -mod ui_follow; mod ui_gamma; mod ui_gm_ticket; mod ui_gossip; diff --git a/crates/benilla-app/src/minimap/mod.rs b/crates/benilla-app/src/minimap/mod.rs index c23d52ebb..b26b87031 100644 --- a/crates/benilla-app/src/minimap/mod.rs +++ b/crates/benilla-app/src/minimap/mod.rs @@ -11,13 +11,11 @@ //! - North up: screen up is world +X, screen left world +Y. pub(crate) mod blips; -/// Where a party member is, shared with the world map so the two surfaces never disagree. -pub(crate) use blips::party_member_pos; mod composite; mod interior; /// The minimap ping, engine-owned and pinned to a world point. mod ping; -pub(crate) use ping::{MinimapPing, MinimapSteps}; +pub(crate) use ping::{MemberPing, MinimapPing, MinimapSteps}; use std::collections::HashMap; @@ -156,7 +154,10 @@ pub(crate) struct MinimapZoom { /// The app's mirror of the two zoom CVars, each on its own field: the record's integer as the /// reference's raw copy takes it into the zoom cell (`0x6d9013`), unclamped. -pub(crate) fn on_cvar(ev: On, mut zoom: ResMut) { +pub(crate) fn on_cvar( + ev: &crate::cvars::CvarChanged, + mut zoom: bevy::prelude::Mut<'_, MinimapZoom>, +) { match ev.key().as_str() { "minimapzoom" => zoom.outdoor = zoom_index(&ev.new), "minimapinsidezoom" => zoom.inside = zoom_index(&ev.new), @@ -964,25 +965,6 @@ fn feed_minimap_player_facing(mut hosted_vm: crate::script_calls::HostedVm, play }) } -/// Push the game clock `GetGameTime()` answers when its hour or minute changes, the API's own -/// resolution: the clock's fields as they stand (`0x515ee0`), -1, -1 while it is unset. -fn feed_game_time( - mut hosted_vm: crate::script_calls::HostedVm, - time: Res, - mut last: Local>>, -) { - hosted_vm.run(|script| { - let Some(script) = script else { return }; - let last = last.get(script); - let now = (time.0.hour(), time.0.minute()); - if *last == Some(now) { - return; - } - *last = Some(now); - script.set_game_time(now.0, now.1); - }) -} - /// The app half of the `` widget. The zone label feed is `crate::area`'s: the reference /// fires `MINIMAP_ZONE_CHANGED` from the same area-update pass as the `ZONE_CHANGED` family /// (`0x494970` beside `0x494780`). @@ -997,7 +979,6 @@ impl Plugin for MinimapPlugin { app.net_handler(K::Connected, clear_quest_blip_on_world_entry) .net_handler(K::Worldport, clear_quest_blip_on_world_entry); } - app.add_observer(on_cvar); app.init_resource::() .init_resource::() .init_resource::() @@ -1036,26 +1017,18 @@ impl Plugin for MinimapPlugin { .after(crate::ui_chat::ChatDrain) .after(crate::ui_party::drain_party) .after(crate::poi_marker::expire_marker) - .after(crate::poi_marker::clear_on_world_entry) + .after(crate::lanes::UiLanes) .after(feed_minimap_art) .before(crate::ui_script::UiPaint), // After the tick that can set the art, before the emit that draws with it. feed_minimap_art .in_set(crate::ui_script::UiDrain) .before(UiQuadAppend), - // Before the script tick, after the indoor push the radius reads. Gated on the - // in-game UI: a member's ping in the login burst has no player to land on - // (`0x4ee341`), so it is dropped, not signalled to the glue VM. - ping::drive_minimap_ping + // Before the script tick, after the indoor push the radius reads. + ping::feed_minimap_player .after(feed_minimap_inside) .in_set(crate::ui_script::UiFeed) .run_if(crate::ui_script::ingame_ui_up), - ping::drop_inbound_pings - .after(ping::drive_minimap_ping) - .in_set(crate::ui_script::UiFeed) - .run_if(not(crate::ui_script::ingame_ui_up)), - // Before the script tick, so GameTimeFrame reads this frame's minute. - feed_game_time.in_set(crate::ui_script::UiFeed), // In the feed, off the hover the last walk left; after the world drive only so // the two VM writers keep one order. blips::drive_blip_tooltip diff --git a/crates/benilla-app/src/minimap/ping.rs b/crates/benilla-app/src/minimap/ping.rs index 28088c4f5..1c52db979 100644 --- a/crates/benilla-app/src/minimap/ping.rs +++ b/crates/benilla-app/src/minimap/ping.rs @@ -7,16 +7,17 @@ //! //! - In: the stock `Minimap_OnClick` calls `Minimap:PingLocation(dx, dy)`; the VM turns it into a //! world point against the frame's own size and the zoom diameter. A group member's -//! `MSG_MINIMAP_PING` (raw world floats) applies through [`drive_minimap_ping`]. +//! `MSG_MINIMAP_PING` (raw world floats) applies at its packet ([`on_minimap_ping`]), its +//! `MINIMAP_PING` on the notice lane. //! - Out: our own ping goes on the wire when grouped (relayed to the rest of the group only, //! `GroupHandler.cpp:384-391`), inside its call ([`MinimapSteps`]). //! //! The reference keeps the world point in two statics nothing clears (`0xbc787c`/`0xbc7880`), -//! across a `ReloadUI` too, so [`MinimapPing`] keeps the process's copy for each new VM. The stock -//! `Minimap.lua` owns everything visible: it shows the `MiniMapPing` `` -//! (`Interface\MiniMap\Ping\MinimapPing.mdx`, rendered by `crate::ui_models`), holds it 5 s and -//! fades it 0.5 s (`MINIMAPPING_TIMER`, `MINIMAPPING_FADE_TIMER`). `WorldMapPing` is the same model -//! on the world map. +//! across a `ReloadUI` too, so [`MinimapPing`] keeps the process's copy, which a new VM is seeded +//! with as it is built. The stock `Minimap.lua` owns everything visible: it shows the +//! `MiniMapPing` `` (`Interface\MiniMap\Ping\MinimapPing.mdx`, rendered by +//! `crate::ui_models`), holds it 5 s and fades it 0.5 s (`MINIMAPPING_TIMER`, +//! `MINIMAPPING_FADE_TIMER`). `WorldMapPing` is the same model on the world map. //! //! Reaching a ping does not clear it: the reference's 10-yd `d² < 100` auto-clear belongs to the //! `SMSG_GOSSIP_POI` marker (`0x6d99aa`–`0x6d9a4c`). @@ -28,73 +29,106 @@ use benilla_assets::coords::{bevy_to_wow, wow_to_bevy}; use crate::net::{ClientCommand, Guid, NetCommands, SelfPlayer}; use crate::player::Player; -/// The process's copy of the ping statics, and the members' pings not yet applied to a VM. +/// The process's copy of the ping statics, which a new VM inherits. #[derive(Resource, Default)] pub(crate) struct MinimapPing { - /// The last ping's WoW `(x, y)`, which a new VM inherits; the statics start at zero. + /// The last ping's WoW `(x, y)`; the statics start at zero. world: (f32, f32), - /// Group members' pings since the last [`drive_minimap_ping`], with each sender's guid. - inbound: Vec<((f32, f32), u64)>, } impl MinimapPing { - /// A group member's ping, stored now and applied to the VM by the next [`drive_minimap_ping`]. - pub(crate) fn seat(&mut self, world: (f32, f32), sender: u64) { - self.world = world; - self.inbound.push((world, sender)); + /// The stored point, a new VM's seed. + pub(crate) fn point(&self) -> (f32, f32) { + self.world + } + + /// `sender`'s ping at the world point `at` (`0x4ee330`): the point stored (`0x4ee366`, + /// `0x4ee373`), and the signal that follows, its token resolved against `group` as it stands, + /// `me` our own guid. + pub(crate) fn member( + &mut self, + at: (f32, f32), + sender: u64, + me: Option, + group: Option<&crate::ui_party::GroupState>, + ) -> MemberPing { + self.world = at; + MemberPing { + token: PingToken::of(sender, me, group), + x: at.0.to_bits(), + y: at.1.to_bits(), + } } } -/// Push the player's position, seat a new VM's stored ping, and apply the members' pings, each -/// signalling `MINIMAP_PING` with its sender's unit token. Runs before the script tick. -pub(super) fn drive_minimap_ping( - // The ping, which the host's `PingLocation` writes too: taken before the VM runs. - mut hosted: crate::script_calls::disjoint::Pair< - ResMut<'static, MinimapPing>, - crate::script_calls::HostedVm<'static, 'static>, - >, +/// The pinger's unit token (`0x4ee330`): ourselves, else the sender's party slot (`party%d`, +/// `0x4ee412`), else its raid row (`raid%d`, `0x4ee41b`), each 1-based, the party scan first; a +/// sender in neither leaves `player`, the buffer's first text (`0x4ee379`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum PingToken { + Player, + Party(u8), + Raid(u8), +} + +impl PingToken { + /// The token `sender` resolves to against `group` as it stands, `me` our own guid. + fn of(sender: u64, me: Option, group: Option<&crate::ui_party::GroupState>) -> Self { + if Some(sender) == me { + return Self::Player; + } + let Some(group) = group else { + return Self::Player; + }; + if let Some(i) = group.party_slots().position(|m| m.guid == sender) { + Self::Party(i as u8 + 1) + } else if let Some(i) = group.raid_rows().position(|g| g == sender) { + Self::Raid(i as u8 + 1) + } else { + Self::Player + } + } + + fn text(self) -> String { + match self { + Self::Player => "player".to_string(), + Self::Party(n) => format!("party{n}"), + Self::Raid(n) => format!("raid{n}"), + } + } +} + +/// A group member's ping as the notice lane carries it: the token its packet resolved and the +/// world point, the floats by their bits so the notice compares exactly. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct MemberPing { + token: PingToken, + x: u32, + y: u32, +} + +impl MemberPing { + /// `MINIMAP_PING` with the token and the point's offset from the player (`0x4ee48d`), and the + /// VM's statics storing the point; nothing with no player position pushed (`0x4ee35e`). + pub(crate) fn fire(self, script: &mut benilla_ui::script::UiScript) { + let world = (f32::from_bits(self.x), f32::from_bits(self.y)); + script.apply_minimap_ping(world, &self.token.text()); + } +} + +/// Push the active player's position the ping methods read at the call (`0x4eecdf`, `0x4ef021`): +/// the player object's own, which unit movement writes in frame time. Runs before the script tick. +pub(super) fn feed_minimap_player( + mut hosted_vm: crate::script_calls::HostedVm, player: Res, - group: Res, - self_q: Query<&Guid, With>, - mut seated: Local>, ) { - let (stored, inbound) = { - let mut ping = hosted.p0(); - (ping.world, std::mem::take(&mut ping.inbound)) - }; - hosted.p1().run(|script| { + hosted_vm.run(|script| { let Some(script) = script else { return }; let wow = bevy_to_wow(player.pos); script.set_minimap_player(player.active.then_some((wow[0], wow[1]))); - let seated = seated.get(script); - if !*seated { - script.set_minimap_ping_point(stored); - *seated = true; - } - // The token (`0x4ee330`): ourselves, else the sender's party slot (`party%d`, `0x4ee412`), - // else its raid row (`raid%d`, `0x4ee41b`), the party scan first; a sender in neither - // leaves `player`. - let self_guid = self_q.iter().next().map(|g| g.0); - for (world, sender) in inbound { - let token = if Some(sender) == self_guid { - "player".to_string() - } else if let Some(i) = group.party_slots().position(|m| m.guid == sender) { - format!("party{}", i + 1) - } else if let Some(i) = group.raid_rows().position(|g| g == sender) { - format!("raid{}", i + 1) - } else { - "player".to_string() - }; - script.apply_minimap_ping(world, &token); - } }) } -/// No in-game UI: a member's ping has no player object to land on, so it applies nowhere. -pub(super) fn drop_inbound_pings(mut ping: ResMut) { - ping.inbound.clear(); -} - /// Our own `PingLocation` inside its call ([`benilla_ui::script::MinimapCall`]). #[derive(bevy::ecs::system::SystemParam)] pub(crate) struct MinimapSteps<'w> { @@ -145,10 +179,26 @@ pub(super) fn register(app: &mut App) { ); } -/// A group member's ping: raw world floats, stored now and announced by the next drive. -fn on_minimap_ping(In(ev): In, mut ping: ResMut) { - if let benilla_protocol::SessionEvent::MinimapPing { guid, x, y } = ev { - ping.seat((x, y), guid); +/// A group member's ping (`0x5e4185` → `0x5e41bd` → `0x4ee330`), with the active player held +/// (`0x4ee341`-`0x4ee35e`): the point stored (`0x4ee366`, `0x4ee373`), the pinger's token +/// resolved against the group as the packet finds it ([`MinimapPing::member`]), and `MINIMAP_PING` +/// on the notice lane at the packet's place. Absent in a harness without the notice lane. +fn on_minimap_ping( + In(ev): In, + mut ping: ResMut, + me: Query<&Guid, With>, + group: Option>, + lane: Option>, +) { + let benilla_protocol::SessionEvent::MinimapPing { guid, x, y } = ev else { + return; + }; + let Some(me) = me.iter().next().map(|g| g.0) else { + return; + }; + let signal = ping.member((x, y), guid, Some(me), group.as_deref()); + if let Some(mut lane) = lane { + lane.write(crate::field_watch::FieldNotice::MinimapPing(signal)); } } @@ -157,8 +207,8 @@ mod tests { use super::*; use benilla_ui::script::UiScript; - /// The drive over a VM with a Minimap and a `MINIMAP_PING` listener, the player at WoW - /// (100, 200) and in a group. + /// The player-position push over a VM with a Minimap and a `MINIMAP_PING` listener, the player + /// at WoW (100, 200), in a group or not; the ping's handler and the notice lane beside it. fn ping_app(in_group: bool) -> (App, crossbeam_channel::Receiver) { let mut app = App::new(); let (tx, rx) = crossbeam_channel::unbounded(); @@ -173,7 +223,9 @@ mod tests { .insert_resource(group) .insert_resource(player) .init_resource::() - .add_systems(Update, drive_minimap_ping); + .init_resource::() + .add_systems(Update, feed_minimap_player); + register(&mut app); let mut script = UiScript::new().unwrap(); script.keep_calls(); script @@ -193,15 +245,49 @@ mod tests { app.world_mut().non_send_resource_mut::() } - /// A member's ping applies to the VM with its token at the next drive, and an unknown - /// sender's leaves `player` (`0x4ee330`); the getter answers it at once. + /// `sender`'s ping through its handler, then each notice it wrote fired on the VM. + fn pinged(app: &mut App, sender: u64, point: (f32, f32)) { + crate::net::handlers::dispatch( + app.world_mut(), + vec![benilla_protocol::SessionEvent::MinimapPing { + guid: sender, + x: point.0, + y: point.1, + }], + ); + let notices: Vec<_> = app + .world_mut() + .resource_mut::() + .drain() + .collect(); + let mut s = script(app); + for notice in notices { + match notice { + crate::field_watch::FieldNotice::MinimapPing(p) => p.fire(&mut s), + other => panic!("{other:?}"), + } + } + } + + /// A member's ping stores the point and signals with its token at its packet, an unknown + /// sender's leaving `player` (`0x4ee330`); the getter answers it at once. With no player + /// object the handler stores and signals nothing (`0x4ee35e`). #[test] fn a_members_ping_signals_with_its_token_and_seats_the_statics() { let (mut app, _rx) = ping_app(true); - app.world_mut() - .resource_mut::() - .seat((100.0, 200.0 - 50.0), 0xDEAD); app.update(); + pinged(&mut app, 0xDEAD, (100.0, 200.0 - 50.0)); + assert_eq!(app.world().resource::().point(), (0.0, 0.0)); + assert!(script(&mut app) + .eval::>("return seen[1]") + .unwrap() + .is_none()); + app.world_mut().spawn((Guid(0x10), SelfPlayer)); + pinged(&mut app, 0xDEAD, (100.0, 200.0 - 50.0)); + assert_eq!( + app.world().resource::().point(), + (100.0, 150.0) + ); let s = script(&mut app); assert_eq!(s.eval::("return seen[1]").unwrap(), "player"); let (x, y) = s.eval::<(f64, f64)>("return m:GetPingPosition()").unwrap(); @@ -234,6 +320,7 @@ mod tests { group.members = vec![member(0xB1, 1), member(0xA1, 0), member(0xB2, 1)]; group.rebuild_raid(ME); } + app.update(); for (sender, want) in [ (0xA1, "party1"), (0xB2, "raid3"), @@ -241,10 +328,7 @@ mod tests { (ME, "player"), (0xDEAD, "player"), ] { - app.world_mut() - .resource_mut::() - .seat((100.0, 150.0), sender); - app.update(); + pinged(&mut app, sender, (100.0, 150.0)); let s = script(&mut app); assert_eq!( s.eval::("return seen[table.getn(seen)]").unwrap(), @@ -255,9 +339,9 @@ mod tests { } /// Our own ping goes on the wire when grouped and only then, and becomes the process's copy, - /// which a new VM inherits as the reference's statics outlive a `ReloadUI`. + /// which a new VM is seeded with as the reference's statics outlive a `ReloadUI`. #[test] - fn our_ping_is_sent_when_grouped_and_outlives_the_vm() { + fn our_ping_is_sent_when_grouped_and_becomes_the_process_copy() { for grouped in [true, false] { let (mut app, rx) = ping_app(grouped); app.update(); @@ -275,22 +359,8 @@ mod tests { if let Some(ClientCommand::MinimapPing { x, y }) = sent.first() { assert!((x - want.0).abs() < 1e-3 && (y - want.1).abs() < 1e-3); } - - // A fresh VM: the drive seats the stored point before its first tick. - let fresh = UiScript::new().unwrap(); - fresh - .run(r#"m = CreateFrame("Minimap", "Minimap")"#) - .unwrap(); - app.insert_non_send_resource(fresh); - app.update(); - let (x, _) = script(&mut app) - .eval::<(f64, f64)>("return m:GetPingPosition()") - .unwrap(); - assert!(x.abs() < 1e-6, "the inherited point, due north: {x}"); - let (_, y) = script(&mut app) - .eval::<(f64, f64)>("return m:GetPingPosition()") - .unwrap(); - assert!((y - 0.5).abs() < 1e-6, "{y}"); + let (x, y) = app.world().resource::().point(); + assert!((x - want.0).abs() < 1e-3 && (y - want.1).abs() < 1e-3); } } diff --git a/crates/benilla-app/src/nameplates.rs b/crates/benilla-app/src/nameplates.rs index 31c9de239..89421d792 100644 --- a/crates/benilla-app/src/nameplates.rs +++ b/crates/benilla-app/src/nameplates.rs @@ -775,7 +775,10 @@ pub(crate) struct NameplatesPlugin; struct NameAnchorTrace(bool); /// The overhead-name rows' change callback: the name trio, the guild line and the rank prefix. -pub(crate) fn on_cvar(ev: On, mut names: ResMut) { +pub(crate) fn on_cvar( + ev: &crate::cvars::CvarChanged, + mut names: bevy::prelude::Mut<'_, NameConfig>, +) { match ev.key().as_str() { "unitnameplayer" => names.player = ev.flag(), "unitnamenpc" => names.npc = ev.flag(), @@ -788,7 +791,6 @@ pub(crate) fn on_cvar(ev: On, mut names: ResMut, /// No negative entry: the server answers for a live pet or says nothing. pets: QueryCache, - /// Bumped by every landed answer, a refusal that took a record away and the pet-rename - /// eviction, never by an ask: the gated feeds re-run when it moves. - generation: u64, - /// The creature entries in the order their records landed, for a reader that keeps its own - /// place ([`Self::creatures_landed_since`]); a `u32` a landing, never trimmed. - creature_landings: Vec, + /// The callbacks a player-name lookup that missed registered (`0x55f080`), by the guid it + /// asked for, each once: the dedupe flag (`0x52af55`). Locked, so a build's lookup registers + /// through a shared read. + player_waits: std::sync::Mutex>, +} + +/// A callback a player-name lookup registers on its miss, which the answer runs. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum NameCallback { + /// The corpse plate's owner (`0x52af77` with `CGTooltip::OnCorpseOwnerName` `0x52afe0`). + CorpsePlate, + /// `UnitName` on a guid it holds no unit for, once the party pet record misses too + /// (`0x5171d7`-`0x5171f5`), with `0x517290`: on a found name, `NotifyUnitNameUpdate` + /// (`0x491a00`) over the guid, held or not. + UnitName, } /// One cached creature template head. @@ -169,6 +178,36 @@ impl NameCache { self.resolve_unit(guid_val, objects.store(guid_val), ask) } + /// A lookup of `guid`'s name that missed registered `callback`, once (`0x55f080` with the + /// dedupe flag). + pub(crate) fn wait_for_player(&self, guid: u64, callback: NameCallback) { + let mut waits = self + .player_waits + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + if !waits.contains(&(guid, callback)) { + waits.push((guid, callback)); + } + } + + /// The answer for `guid` landed, or refused it: the callbacks waiting on it, in the order they + /// asked, spent either way. + pub(crate) fn take_player_waits(&mut self, guid: u64) -> Vec { + let waits = self + .player_waits + .get_mut() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let mut taken = Vec::new(); + waits.retain(|&(g, cb)| { + let hit = g == guid; + if hit { + taken.push(cb); + } + !hit + }); + taken + } + /// The player-name cache by guid, whatever the guid is: the reference's `0x55f080` on /// `0xc0e228`, which names a chat speaker (`0x49d560`), the summoner (`GetSummonConfirmSummoner`, `0x48b6a0`) /// and every roster, mail, auction and petition guid the server sends as a player's. A guid @@ -290,28 +329,26 @@ impl NameCache { Some(t) => self.player_traits.insert(guid, t), None => self.player_traits.remove(&guid), }; - // A refusal redisplays only a name it took away: the status-0 callback `0x5fb840` does - // nothing (`0x5fb84b`). - let moved = if name.is_empty() { - self.players.refuse(guid) == Refused::Record + if name.is_empty() { + self.players.refuse(guid); } else { self.players.insert(guid, name); - true - }; - if moved { - self.generation = self.generation.wrapping_add(1); } } /// The reference's world-session wipe (`0x555740`; `0x5557ad call 0x560400` for the player /// cache): every `DBCache` whose persistence byte `[cache+0x39]` is 0 is cleared, which is /// `'WNAM'` (player names, ctor `0x554cd0`), `'WGLD'`, `'WPNM'` (pet names) and `'WPTN'`. - /// Called at world entry, before the login seeds our own name. + /// Called at world entry, before the login seeds our own name. The player cache's nodes go + /// with their callbacks, none of them run (`0x560400`), so no wait outlives the session. pub(crate) fn clear_world_session(&mut self) { self.players.clear(); self.player_traits.clear(); self.pets.clear(); - self.generation = self.generation.wrapping_add(1); + self.player_waits + .get_mut() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clear(); } /// The creature-template store, the one [`crate::wdb`] saves. @@ -323,11 +360,6 @@ impl NameCache { &mut self.creatures } - /// The landed-answer counter. - pub(crate) fn generation(&self) -> u64 { - self.generation - } - /// `(race, class, gender)` for a player guid the name query has answered for. pub(crate) fn player_traits(&self, guid: u64) -> Option<(u8, u8, u8)> { self.player_traits.get(&guid).copied() @@ -336,55 +368,30 @@ impl NameCache { /// Record a pet-name answer, keyed by pet number. pub(crate) fn insert_pet(&mut self, pet_number: u32, name: String) { self.pets.insert(pet_number, name); - self.generation = self.generation.wrapping_add(1); } /// Forget a pet's name and its in-flight mark so the next resolve asks again: a rename /// arrives only as a bumped `UNIT_FIELD_PET_NAME_TIMESTAMP`, never as the name. pub(crate) fn forget_pet(&mut self, pet_number: u32) { self.pets.evict(pet_number); - self.generation = self.generation.wrapping_add(1); } /// Record a creature-name answer; `None` is a refusal (an entry the server flagged unknown). - /// A refusal redisplays only a record it took away: the status-0 callback `0x604660` finds - /// no record and sets nothing (`0x60469c`). pub(crate) fn insert_creature(&mut self, entry: u32, record: Option) { - let moved = match record { - Some(record) => { - self.creatures.insert(entry, record); - self.creature_landings.push(entry); - true + match record { + Some(record) => self.creatures.insert(entry, record), + None => { + self.creatures.refuse(entry); } - None => self.creatures.refuse(entry) == Refused::Record, - }; - if moved { - self.generation = self.generation.wrapping_add(1); } } - /// The creature entries that landed after a reader's place `seen`, and its new place. - pub(crate) fn creatures_landed_since(&self, seen: usize) -> (&[u32], usize) { - let landed = self.creature_landings.get(seen..).unwrap_or_default(); - (landed, self.creature_landings.len()) - } - - /// Every cached creature's entry and name. - pub(crate) fn creature_names(&self) -> impl Iterator { - self.creatures.iter().map(|(&e, r)| (e, r.name.as_str())) - } - /// Whether the server refused the player's name, an empty name answered for the guid, and /// nothing has asked for it since. pub(crate) fn player_answered_unknown(&self, guid: u64) -> bool { self.players.answered_unknown(guid) } - /// Whether the server refused `entry` and nothing has asked for it since. - pub(crate) fn creature_answered_unknown(&self, entry: u32) -> bool { - self.creatures.answered_unknown(entry) - } - /// The cached subname, the title line under a creature's name. pub(crate) fn creature_subname(&self, entry: u32) -> Option<&str> { self.creatures.get(entry)?.subname.as_deref() @@ -418,7 +425,6 @@ impl NameCache { pub(crate) fn invalidate_player(&mut self, guid: u64) { self.players.evict(guid); self.player_traits.remove(&guid); - self.generation = self.generation.wrapping_add(1); } } @@ -427,7 +433,7 @@ pub(crate) mod net { use benilla_protocol::{SessionEvent, SessionEventKind}; use bevy::prelude::*; - use super::{CreatureRecord, NameCache}; + use super::{CreatureRecord, NameCache, NameCallback}; use crate::field_watch::{id, FieldNotice, NoticeLane}; use crate::net::{GuidIndex, NetHandlerApp, ObjectStore}; @@ -477,10 +483,10 @@ pub(crate) mod net { } /// The name callback `0x5fb840` of a unit the answer names: for a found name (`0x5fb84b`) of a - /// held unit (`0x5fb86a`), `UNIT_NAME_UPDATE` through `0x491a00`; and the chat's `0x49ccc0`, - /// which shows the lines that waited on the name, and the trade initiate's `0x5d4080`. The - /// callbacks are the lookups that missed, so an answer for a name the cache already holds runs - /// none. + /// held unit (`0x5fb86a`), `UNIT_NAME_UPDATE` through `0x491a00`; the chat's `0x49ccc0`, + /// which shows the lines that waited on the name, and the trade initiate's `0x5d4080`; and the + /// waits a lookup registered ([`NameCallback`]). The callbacks are the lookups that missed, so + /// an answer for a name the cache already holds runs none. fn on_player_name( In(ev): In, mut names: ResMut, @@ -507,6 +513,7 @@ pub(crate) mod net { // A guid already cached has no lookup waiting, so no callback runs. let waited = names.players.get(guid).is_none(); let found = !name.is_empty() && waited; + let callbacks = names.take_player_waits(guid); player_name(guid, name, race, class, gender, &mut names); if waited { battlefield.answered(guid, &names); @@ -522,10 +529,23 @@ pub(crate) mod net { } } if found && units.holds(guid) { - notices.write(FieldNotice::Signal { - guid, - id: id::UNIT_NAME_UPDATE, - }); + notices.write_batch(name_update(guid)); + } + // The lookups' own callbacks, in the order they asked, each for a found name only. + for callback in callbacks.into_iter().filter(|_| found) { + match callback { + // `0x52affc`. + NameCallback::CorpsePlate => notices.write(FieldNotice::CorpsePlate), + // `0x51729a` → `0x491a00`: the refresh for a unit held (`0x491a23`), the + // signal to every token naming the guid whatever (`0x491a3c`). + NameCallback::UnitName if units.holds(guid) => { + notices.write_batch(name_update(guid)); + } + NameCallback::UnitName => notices.write(FieldNotice::Signal { + guid, + id: id::UNIT_NAME_UPDATE, + }), + } } } } @@ -543,10 +563,7 @@ pub(crate) mod net { pet_name(pet_number, name, &mut names); if found && pet_number != 0 { for guid in units.matching(|s| s.0.unit_pet_number() == pet_number) { - notices.write(FieldNotice::Signal { - guid, - id: id::UNIT_NAME_UPDATE, - }); + notices.write_batch(name_update(guid)); } } } @@ -592,21 +609,28 @@ pub(crate) mod net { ); if found { for guid in units.matching(|s| s.0.object_entry() == Some(entry)) { - notices.write_batch([ - FieldNotice::Signal { - guid, - id: id::UNIT_NAME_UPDATE, - }, - FieldNotice::Signal { - guid, - id: id::UNIT_CLASSIFICATION_CHANGED, - }, - ]); + notices.write_batch(name_update(guid)); + notices.write(FieldNotice::Signal { + guid, + id: id::UNIT_CLASSIFICATION_CHANGED, + }); } } } } + /// `NotifyUnitNameUpdate` (`0x491a00`) on a held unit: the tooltip's refresh (`0x491a27`), + /// then `UNIT_NAME_UPDATE` (`0x491a3c`). + fn name_update(guid: u64) -> [FieldNotice; 2] { + [ + FieldNotice::TooltipUnit { guid }, + FieldNotice::Signal { + guid, + id: id::UNIT_NAME_UPDATE, + }, + ] + } + fn on_invalidate_player(In(ev): In, mut names: ResMut) { if let SessionEvent::InvalidatePlayer { guid } = ev { invalidate_player(guid, &mut names); @@ -752,6 +776,11 @@ pub(crate) mod net { FieldNotice::Signal { guid, id } } + /// `0x4919d0` on `guid`, the tooltip's refresh ahead of its name signal. + fn tooltip(guid: u64) -> FieldNotice { + FieldNotice::TooltipUnit { guid } + } + fn creature(entry: u32, name: Option<&str>) -> SessionEvent { SessionEvent::CreatureName { entry, @@ -779,10 +808,13 @@ pub(crate) mod net { assert_eq!( notices(&mut app), [ + tooltip(WOLF_B), signal(WOLF_B, 183), signal(WOLF_B, 187), + tooltip(WOLF_A), signal(WOLF_A, 183), signal(WOLF_A, 187), + tooltip(PET), signal(PET, 183), signal(PET, 187) ] @@ -815,7 +847,7 @@ pub(crate) mod net { app.world_mut() .run_system_once_with(on_player_name, player(PLAYER, "Brisca")) .unwrap(); - assert_eq!(notices(&mut app), [signal(PLAYER, 183)]); + assert_eq!(notices(&mut app), [tooltip(PLAYER), signal(PLAYER, 183)]); app.world_mut() .run_system_once_with(on_player_name, player(PLAYER, "Brisca")) .unwrap(); @@ -839,7 +871,7 @@ pub(crate) mod net { }, ) .unwrap(); - assert_eq!(notices(&mut app), [signal(PET, 183)]); + assert_eq!(notices(&mut app), [tooltip(PET), signal(PET, 183)]); app.world_mut() .run_system_once_with( on_pet_name, @@ -869,42 +901,6 @@ mod tests { (NetCommands(tx), rx) } - /// An ask must not move the counter, or an outstanding query would hold every gated feed open. - #[test] - fn the_generation_counts_landings_never_asks() { - let (cmds, _rx) = commands(); - let mut cache = NameCache::default(); - let g0 = cache.generation(); - - let player = compose(0, 0, 7); - assert_eq!(cache.resolve_unit(player, None, Ask::New(&cmds)), None); - assert_eq!( - cache.generation(), - g0, - "the miss asked, and asking is not a landing" - ); - - cache.insert_player(player, "Benilla".into(), None); - let landed = cache.generation(); - assert_ne!(g0, landed, "the answer landing is the edge"); - - assert_eq!( - cache.resolve_unit(player, None, Ask::New(&cmds)), - Some("Benilla") - ); - assert_eq!(cache.generation(), landed, "a cache hit moves nothing"); - - cache.insert_pet(137, "Voidwalker".into()); - let pet = cache.generation(); - assert_ne!(landed, pet); - cache.forget_pet(137); - assert_ne!( - pet, - cache.generation(), - "the rename eviction is a landing-shaped edge" - ); - } - /// A summoned pet asks `CMSG_PET_NAME_QUERY` by the pet number in its guid; its entry slot /// names no creature template. #[test] @@ -972,9 +968,15 @@ mod tests { cache.insert_player(0x11, "Moamtester".into(), Some((1, 2, 0))); cache.insert_pet(7, "Rex".into()); cache.insert_creature(69, Some(record("Stable Master"))); + cache.wait_for_player(0x22, NameCallback::UnitName); cache.clear_world_session(); + assert!( + cache.take_player_waits(0x22).is_empty(), + "the waits went with the cache" + ); + assert_eq!(cache.resolve_unit(0x11, None, Ask::Read), None); assert_eq!(cache.player_traits(0x11), None); assert!( @@ -1008,12 +1010,7 @@ mod tests { ); assert!(matches!(rx.try_recv(), Err(TryRecvError::Empty)), "no ask"); - let before = cache.generation(); cache.invalidate_player(0x11); - assert!( - cache.generation() != before, - "an eviction is a landed change" - ); assert_eq!( cache.player_traits(0x11), None, @@ -1079,17 +1076,11 @@ mod tests { rx.try_recv(), Ok(ClientCommand::NameQuery { guid }) if guid == g )); - let before = cache.generation(); cache.insert_player(g, String::new(), None); // server: unknown guid assert!( cache.players.answered_unknown(g), "the waiters read unknown" ); - assert_eq!( - cache.generation(), - before, - "nothing redisplays: `0x5fb840` ignores status 0" - ); assert_eq!(cache.resolve_unit(g, None, Ask::New(&cmds)), None); assert!( matches!(rx.try_recv(), Err(TryRecvError::Empty)), @@ -1153,21 +1144,17 @@ mod tests { #[test] fn a_refusal_nobody_asked_for_marks_nothing() { let mut cache = NameCache::default(); - let before = cache.generation(); cache.insert_creature(4321, None); assert!(!cache.creatures.answered_unknown(4321)); - assert_eq!(cache.generation(), before); } - /// `0x556f35` frees a valid node too, and what the readers showed changes. + /// `0x556f35` frees a valid node too. #[test] - fn a_refusal_of_a_held_record_takes_it_away_and_redisplays() { + fn a_refusal_of_a_held_record_takes_it_away() { let mut cache = NameCache::default(); cache.insert_creature(55, Some(record("Kobold"))); - let before = cache.generation(); cache.insert_creature(55, None); assert!(cache.creature_record(55).is_none()); - assert_ne!(cache.generation(), before); } #[test] diff --git a/crates/benilla-app/src/net.rs b/crates/benilla-app/src/net.rs index 6b1fec351..146a454c1 100644 --- a/crates/benilla-app/src/net.rs +++ b/crates/benilla-app/src/net.rs @@ -26,11 +26,17 @@ pub(crate) mod io; pub(crate) mod motion; mod objects; #[cfg(test)] +pub(crate) use objects::answer_item; +pub(crate) use objects::continue_refusal_walk; +#[cfg(test)] pub(crate) use objects::wire; pub(crate) use objects::Listed; pub(crate) use objects::{release_unheld, ReleasePending}; mod reputations; mod session; +#[cfg(test)] +pub(crate) use session::fire_worldport_timer; +pub(crate) use session::{world_ported, PendingWorldports, WorldportTimer}; mod world; pub(crate) use reputations::Reputations; @@ -38,7 +44,7 @@ pub(crate) use reputations::Reputations; pub(crate) use apply::apply_net_updates; #[cfg(test)] pub(crate) use game_time::GameTime; -pub(crate) use game_time::{clock_tick, ServerTime}; +pub(crate) use game_time::{clock_tick, GameTimeLive, ServerTime}; pub(crate) use handlers::NetHandlerApp; pub(crate) use io::LoginRequest; @@ -94,7 +100,6 @@ impl Plugin for NetPlugin { .init_resource::() .init_resource::() .init_resource::() - .init_resource::() .init_resource::() .init_resource::() .init_resource::() @@ -434,6 +439,13 @@ pub(crate) struct Embodied; #[derive(Component)] pub(crate) struct ActiveMover; +/// `IsClientControlled` (`0x5fa5f0`): bit 0x400 of the unit's `+0xc58`, which the control update +/// sets or clears on its unit (`0x5fa62a`, `0x5fa631`, stored at `0x5fa636`) and only the +/// constructor clears besides (`0x5fae7a`), so it outlives a release. Our own character's is read +/// off [`crate::player::OwnControlLost`], which the same update writes beside it. +#[derive(Component, Clone, Copy, Debug, Default)] +pub(crate) struct ClientControlled; + /// The active-mover global (`0xc4da98`/`0xc4da9c`) as the claims read it: the guid the last /// `SetActiveMover` (`0x6006e0`) stored, or none. A claim of the guid it holds returns at once /// (`0x6006ee`-`0x6006fb` → `0x600852`), so `CMSG_SET_ACTIVE_MOVER` goes out only on a change. @@ -461,6 +473,16 @@ impl MoverClaim { true } + /// The guid the global names. + pub(crate) fn get(&self) -> Option { + self.0 + } + + /// Whether the global names `guid` (`0x6103a0`'s first test). + pub(crate) fn holds(&self, guid: u64) -> bool { + self.0 == Some(guid) + } + /// The unit `guid` gone or stopped: the global is zeroed when it names it. pub(crate) fn forget(&mut self, guid: u64) { if self.0 == Some(guid) { @@ -851,11 +873,6 @@ pub(crate) fn send_query_time( #[derive(Resource, Default)] pub(crate) struct HomeBind(pub(crate) Option); -/// The undelivered `/played` answer (`SMSG_PLAYED_TIME`): total seconds and seconds this level. -/// One slot: the server sends one reply per request. -#[derive(Resource, Default)] -pub(crate) struct PlayedTimeAnswer(pub(crate) Option<(u32, u32)>); - /// Equip proficiencies (`SMSG_SET_PROFICIENCY`): item class (2 weapon, 4 armor) to a subclass /// bitmask, the client's `0xc4d4a0[class]` store. #[derive(Resource, Default)] diff --git a/crates/benilla-app/src/net/apply.rs b/crates/benilla-app/src/net/apply.rs index 57ffb46a7..9264ce07b 100644 --- a/crates/benilla-app/src/net/apply.rs +++ b/crates/benilla-app/src/net/apply.rs @@ -21,17 +21,33 @@ mod world_enter_tests; /// load ([`InboundHold`]). pub(crate) fn apply_net_updates(world: &mut World) { let events: Vec = world.resource::().0.try_iter().collect(); - // `drn`: where the frame's packets land, against the input records' `prs` and `snd` lines. - if !events.is_empty() && benilla_assets::trace::enabled_for("drn") { - benilla_assets::trace::line("drn", &format!("events={}", events.len())); - } + let arrived = events.len(); let mut hold = world.remove_resource::().unwrap_or_default(); let mut out = hold.release(world); for ev in events { hold.admit(ev, &mut out); } world.insert_resource(hold); + // `drn`: where the frame's packets land, against the input records' `prs` and `snd` lines; + // then, behind what they sent, the flushes the dispatch fired, their lane firings and its time. + let traced = !out.is_empty() && benilla_assets::trace::enabled_for("drn"); + if traced { + benilla_assets::trace::line("drn", &format!("events={arrived} packets={}", out.len())); + } + let before = traced.then(|| (crate::lanes::tally(), std::time::Instant::now())); super::handlers::dispatch(world, out); + if let Some(((flushes, fired), at)) = before { + let (f, k) = crate::lanes::tally(); + benilla_assets::trace::line( + "drn", + &format!( + "done flushes={} fired={} us={}", + f - flushes, + k - fired, + at.elapsed().as_micros() + ), + ); + } } /// The world session's inbound events behind its entry load. The reference sends the login only diff --git a/crates/benilla-app/src/net/game_time.rs b/crates/benilla-app/src/net/game_time.rs index 79bcae07e..704db770e 100644 --- a/crates/benilla-app/src/net/game_time.rs +++ b/crates/benilla-app/src/net/game_time.rs @@ -452,6 +452,23 @@ fn format_time(time: &WowTime) -> String { #[derive(Resource, Default)] pub(crate) struct ServerTime(pub(crate) GameTime); +/// The game clock as `GetGameTime` reads it at the call (`0x515ee0`): its hour and minute as they +/// stand, so a listener reads what its packet's time message left. Absent in a harness without the +/// clock. +#[derive(bevy::ecs::system::SystemParam)] +pub(crate) struct GameTimeLive<'w> { + clock: Option>, +} + +impl crate::script_calls::live::LiveFamily for GameTimeLive<'_> { + fn answer(&mut self, ask: &mut benilla_ui::script::live::LiveAsk<'_>) -> bool { + ask.answer(|_: &benilla_ui::script::GameTimeQuery| { + let clock = &self.clock.as_deref()?.0; + Some((clock.hour(), clock.minute())) + }) + } +} + /// The clock's per-frame systems. In the net stage, after the drain that may have set the clock: /// the lighting resolve runs after it and reads this frame's clock. The frame advance runs only /// in the world: the reference registers it with `ClientInitializeGame` at world entry diff --git a/crates/benilla-app/src/net/handlers.rs b/crates/benilla-app/src/net/handlers.rs index f4f0f4a90..5015d55d9 100644 --- a/crates/benilla-app/src/net/handlers.rs +++ b/crates/benilla-app/src/net/handlers.rs @@ -174,56 +174,85 @@ pub(crate) fn measure(world: &mut World) { }); } -/// What runs around the packets of a dispatch: `begin` once ahead of the first, and `end` after -/// each, with a stamp taken ahead of its handlers, so a state the packet moved can be logged -/// ahead of what the packet raised ([`crate::lanes`]). -#[derive(Clone, Copy)] -struct PacketHook { - begin: fn(&mut World), - end: fn(&mut World, crate::lanes::Stamp), -} +/// What runs after each packet of a dispatch, its handlers done, with a stamp taken ahead of +/// them, so a state the packet moved can be logged ahead of what the packet raised +/// ([`crate::lanes`]). A log's start is read where the span of packets begins +/// ([`crate::lanes::LaneApp::add_span_start`]). +type PacketEnd = fn(&mut World, crate::lanes::Stamp); -/// Every [`PacketHook`], in registration order. +/// Every [`PacketEnd`], in registration order. #[derive(Resource, Default, Clone)] -struct PacketHooks(Vec); +struct PacketEnds(Vec); -/// Register a [`PacketHook`]. -pub(crate) fn add_packet_hook( - app: &mut App, - begin: fn(&mut World), - end: fn(&mut World, crate::lanes::Stamp), -) { +/// Register a [`PacketEnd`]. +pub(crate) fn add_packet_end(app: &mut App, end: PacketEnd) { app.world_mut() - .get_resource_or_init::() + .get_resource_or_init::() .0 - .push(PacketHook { begin, end }); + .push(end); } -/// One drain's dispatch in wire order, each handler's commands applied before the next event. +/// One drain's dispatch in wire order, each handler's commands applied before the next event, +/// and each packet's lanes fired once its handlers are done ([`crate::lanes::flush`]): the +/// reference's poll runs each packet's handler whole before the next (`0x5384d0`, `0x537ae5`), +/// and what a handler signals runs every listener before the signal returns (`0x703e50`). What +/// the input records and the last tick stamped fires first, as the window input runs ahead of the +/// packets (`0x420d23`, `0x420d55`); the span's starts follow, and each packet's ends after its +/// handlers. pub(crate) fn dispatch(world: &mut World, events: Vec) { + if events.is_empty() { + return; + } let handlers = world.remove_resource::().unwrap_or_default(); - let hooks = world - .get_resource::() - .filter(|_| !events.is_empty()) + let ends = world + .get_resource::() .cloned() .unwrap_or_default(); - for hook in &hooks.0 { - (hook.begin)(world); + if !crate::lanes::flush(world) { + crate::lanes::span_starts(world); } - for ev in events { - if hooks.0.is_empty() { + crate::lanes::at_packets(|| { + for ev in events { + let last = ends_its_packet(&ev); + let at = (!ends.0.is_empty()).then(crate::lanes::stamp); handlers.run(world, ev); - continue; + if let Some(at) = at { + for end in &ends.0 { + end(world, at); + } + } + if last { + crate::lanes::flush(world); + } } - let at = crate::lanes::stamp(); - handlers.run(world, ev); - for hook in &hooks.0 { - (hook.end)(world, at); - } - } + }); world.insert_resource(handlers); } +/// Whether `ev` is the last event its packet decodes to (`benilla_protocol::decode`): an update +/// packet's blocks run until its [`SessionEvent::ObjectUpdateEnd`], as its handler writes every +/// block before its notify pass (`0x46520e`, `0x465222`, `0x465277`), a `MSG_MOVE_SET_*_SPEED` +/// decodes to its pose, the one [`benilla_protocol::messages::RelayVerb::Pose`] move, then its +/// speed, and a saved store's answer sends its bytes ahead of its record +/// ([`crate::net::io::inbound`]). +pub(crate) fn ends_its_packet(ev: &SessionEvent) -> bool { + !matches!( + ev, + SessionEvent::SavedAnswer { .. } + | SessionEvent::ObjectCreate { .. } + | SessionEvent::ItemCreate { .. } + | SessionEvent::ObjectValues { .. } + | SessionEvent::ObjectsRemoved(_) + | SessionEvent::ObjectsNear(_) + | SessionEvent::ObjectMove { .. } + | SessionEvent::ObjectNotify { .. } + | SessionEvent::UnitMove { + verb: benilla_protocol::messages::RelayVerb::Pose, + .. + } + ) +} + #[cfg(test)] mod tests { use super::*; @@ -464,6 +493,77 @@ mod tests { ); } + /// Each packet's last event alone ends it: an update packet's blocks run to its + /// `ObjectUpdateEnd`, and a speed change's pose to its speed (`benilla_protocol::decode`), so + /// the dispatch fires the lanes between packets, never between one packet's events. + #[test] + fn only_a_packets_last_event_ends_it() { + use benilla_protocol::messages::{opcode, parse_server}; + let hex = |s: &str| -> Vec { + s.as_bytes() + .chunks(2) + .map(|h| u8::from_str_radix(std::str::from_utf8(h).unwrap(), 16).unwrap()) + .collect() + }; + // Two values blocks, the first a first-pass guid's, which leaves its notify place. + let update = hex("020000000000814260010800000013000000\ + 0001aa010800000012000000"); + let mut speed = hex("012a"); + speed.extend([0; 28]); + speed.extend(7.0f32.to_le_bytes()); + for (op, body) in [ + (opcode::SMSG_UPDATE_OBJECT, update), + (opcode::MSG_MOVE_SET_RUN_SPEED, speed), + (opcode::SMSG_LOGOUT_COMPLETE, Vec::new()), + ] { + let events = benilla_protocol::decode(parse_server(op, &body).unwrap()); + let ends: Vec = events.iter().map(ends_its_packet).collect(); + let mut want = vec![false; ends.len().saturating_sub(1)]; + want.push(true); + assert_eq!(ends, want, "{op:#06x}: {events:?}"); + } + } + + fn raises_in_a_handler(_: In, world: &mut World) { + let mut ui = world.non_send_resource_mut::(); + ui.fire_event("PLAYER_MONEY", Vec::new()); + } + + fn raises_at_a_packets_end(world: &mut World, _: crate::lanes::Stamp) { + let mut ui = world.non_send_resource_mut::(); + ui.fire_event("PLAYER_MONEY", Vec::new()); + } + + /// One packet's dispatch, a pong, in each frame. + fn dispatch_a_pong(world: &mut World) { + dispatch(world, vec![SessionEvent::Pong { sequence: 0 }]); + } + + /// The raise check armed over a frame that dispatches a pong. + fn armed() -> App { + let mut app = App::new(); + crate::ui_script::raise_origin::arm_each_frame(&mut app); + app.insert_non_send_resource(benilla_ui::script::UiScript::new().expect("a VM")) + .add_systems(Update, dispatch_a_pong); + app + } + + /// A handler's raise inside the dispatch passes, its packet's own (`0x703e50`); a packet end's, + /// which runs in the dispatch outside every handler and lane firing, fails. + #[test] + #[cfg_attr(not(debug_assertions), ignore = "the check compiles out")] + fn a_handlers_raise_passes_and_a_packet_ends_fails() { + let mut handled = armed(); + handled.net_handler(SessionEventKind::Pong, raises_in_a_handler); + handled.update(); + let mut ended = armed(); + add_packet_end(&mut ended, raises_at_a_packets_end); + let failed = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| ended.update())) + .expect_err("the packet end's raise passed"); + let message = failed.downcast_ref::().cloned().unwrap_or_default(); + assert!(message.contains("`PLAYER_MONEY`"), "{message}"); + } + /// `//` comments out, so a variant named in prose does not count as an arm. fn regex_lite_strip_comments(s: &str) -> String { s.lines() diff --git a/crates/benilla-app/src/net/io/fake.rs b/crates/benilla-app/src/net/io/fake.rs index 3977a4523..db401b7f6 100644 --- a/crates/benilla-app/src/net/io/fake.rs +++ b/crates/benilla-app/src/net/io/fake.rs @@ -681,13 +681,18 @@ pub(crate) fn world(listener: TcpListener, keys: Receiver) -> World { let Some(key) = last else { return; }; - // Held and counted before the client can see the session open, so a drop never misses - // it and `open` never reads behind the client's authentication. + // Held, counted and logged before the client can see the session open, so a drop never + // misses it and neither `open` nor `authentications` reads behind its authentication. if let Ok(link) = s.try_clone() { link_log.lock().unwrap().push(link); } let sessions = Arc::clone(&sessions); sessions.fetch_add(1, Ordering::SeqCst); + let index = { + let mut all = session_log.lock().unwrap(); + all.push(Vec::new()); + all.len() - 1 + }; let mut crypto = HeaderCrypto::from_session_key(key); let reply = addon_reply.lock().unwrap().clone(); if let Some((body, false)) = &reply { @@ -723,11 +728,6 @@ pub(crate) fn world(listener: TcpListener, keys: Receiver) -> World { let refuse_flag = Arc::clone(&refuse_flag); let refuse_wait = Arc::clone(&refuse_wait); let trailing = Arc::clone(&trailing); - let index = { - let mut all = session_log.lock().unwrap(); - all.push(Vec::new()); - all.len() - 1 - }; thread::spawn(move || { while let Some(packet) = recv_packet(&mut s, Some(&mut crypto)) { let op = u16::from_le_bytes([packet[2], packet[3]]); diff --git a/crates/benilla-app/src/net/objects.rs b/crates/benilla-app/src/net/objects.rs index c4c9b369d..3e8151c26 100644 --- a/crates/benilla-app/src/net/objects.rs +++ b/crates/benilla-app/src/net/objects.rs @@ -28,6 +28,7 @@ use super::{ }; mod arrival; +mod item_deactivate; mod update; pub(crate) use update::{release_unheld, Listed, ReleasePending, Released}; @@ -51,9 +52,7 @@ fn gameobject_anim_event( pub(super) fn register(app: &mut App) { use SessionEventKind as K; update::register(app); - app.net_handler(K::ItemTemplate, on_item) - // Next, so the stationery rebuild reads the record the cache now holds. - .net_handler(K::ItemTemplate, on_paper_record) + app.net_handler(K::ItemTemplate, on_item_answer) .net_handler(K::ItemTime, on_item) .net_handler(K::ItemEnchantTime, on_item) .net_handler(K::MoveTimeSkipped, on_move_time_skipped) @@ -84,6 +83,7 @@ pub(crate) struct Scene<'w, 's> { remote: Query<'w, 's, &'static mut RemoteMotion>, modes: Query<'w, 's, &'static mut UnitMoveModes>, xp_awarded: Query<'w, 's, (), With>, + client_controlled: Query<'w, 's, (), With>, riders: Query<'w, 's, &'static mut crate::transport::TransportRider>, /// A transport's clock, which only a new object's create sets (`0x5f7080`). anchors: Query<'w, 's, &'static crate::transport::TransportAnchor>, @@ -126,6 +126,13 @@ pub(crate) struct Scene<'w, 's> { house: Option>, // The loot window's rows and the pushes that wait on an item's record. loot: Option>, + /// What an item's deactivate lets go of besides the window above (`0x5d8660`): the loot + /// latch, the pending record's cast and the reader. + loot_latch: Option>, + item_cast: crate::spell::ItemCastLeg<'w>, + item_text: crate::ui_item_text::ItemTextLeg<'w>, + // The group loot rolls and their lines that wait on an item's record. + loot_rolls: crate::ui_loot_roll::RollRecordAnswers<'w>, // The vendor window's row and buy-back callbacks. merchant: crate::ui_merchant::MerchantRecordAnswers<'w>, // The state pass the trainer's watches and item callbacks run (`0x4d7d40`). @@ -134,6 +141,9 @@ pub(crate) struct Scene<'w, 's> { quest_giver: Option>, // The quest log's leaderboard's object waits' `QUEST_LOG_UPDATE`. quest_log: Option>, + /// The quest chat lines waiting on a record, and the notices an elite accept's tutorial + /// fires on ([`crate::ui_quest::lines`]). + quest_lines: Option>, // The mail rows' and notices' callbacks' `MAIL_INBOX_UPDATE`. mail: Option>, pass: ResMut<'w, update::UpdatePass>, @@ -155,12 +165,25 @@ pub(crate) struct Scene<'w, 's> { place: crate::ui_party::net::SnapshotPlace<'w, 's>, /// The active mover, which its unit's release and destroy zero. mover: Option>, + /// The far-sight machine the field's change starts or ends (`0x5de0d0`) and an arrival + /// starts, and whose latch the stun's tick reads (`0x514540`). + far_sight: Option>, + /// The active mover's auto-move, which its release and the watchers' stops end. + follow: Option>, + approach: Option>, + /// Autorun as the frame's calls leave it, which an auto-move's stop clears. + call_autorun: Option>, + /// Our own control, which our arrival restores and `IsClientControlled` reads for our + /// character (`0x5fa5f0`). + own_control_lost: Option>, /// Who we drive and whether we may, which our own arrival gives back. mover_lock: Option>, /// The area spirit healer the ghost flag's clear empties (`0x5dea20` → `0x4921c0`), and the /// aura cancel it runs. spirit: Option>, aura: crate::ui_aura::AuraGate<'w>, + /// The corpse-range latch the ghost bit's corpse query lowers (`0x5eeac1` → `0x491f7b`). + death_latches: Option>, } /// The item watchers' reads of the scene ([`crate::item_watch::Watch`]). @@ -183,148 +206,334 @@ fn item_watch<'a, 'w, 's>( } } -/// `SMSG_ITEM_QUERY_SINGLE_RESPONSE`'s stationery callbacks (`0x4acbf0`), a record or a refusal, -/// registered right after [`on_item`] so the rebuild they may run (`0x4acbf8`) reads the record -/// [`on_item`] just cached ([`crate::ui_mail::StationeryRebuild::answered`]). -fn on_paper_record( - In(ev): In, +/// A paper row's callback (`0x4acbf0`) on the answer for `entry`, a record or a refusal: it +/// counts one down, the last rebuilding the list off the record now cached (`0x4acbf8`). +fn paper_answered( + In(entry): In, paper: Option, items: Res, ) { - if let (SessionEvent::ItemTemplate { entry, .. }, Some(mut paper)) = (ev, paper) { + if let Some(mut paper) = paper { paper.answered(entry, &items); } } -/// Items past their create block: `SMSG_ITEM_QUERY_SINGLE_RESPONSE`, whose refusal the next -/// create or entry change of that entry asks again; and the lifetime and enchant countdowns, -/// written into the item's own [`crate::items::Countdowns`]. -fn on_item(In(ev): In, mut sc: Scene) { - match ev { - SessionEvent::ItemTemplate { entry, info } => { - let info = info.map(|b| *b); - debug!("net: item template {entry} → {info:?}"); - let answered = info.is_some(); - sc.items.insert_template(entry, info); - // The callbacks the lookups that missed registered, in the order they asked - // (`0x55ba30`, the dedupe flag 0): each item's set-up (`0x5d8390`) and entry change's - // (`0x5d96b0`), the loot window's rows (`0x4c2ac0`) and pushes (`0x491ee0`), the trade - // getters' (`0x4c0340`), the ammo getters' (`0x4c84f0`), the parked swaps' - // (`0x5e1020`) and auto-equips' (`0x5e17a0`), the vendor rows' (`0x4fada0`, - // `0x4fb570`), the trainer rows' (`0x4d9140`, `0x4d9db0`), the questgiver rows' - // (`0x5018c0`), the mail rows' and notices' (`0x4af0a0`, `0x4ad010`), the mail - // attachment's (`0x4ae710`) and the auction notices' lines (`0x4cd190`). - let callbacks = sc.items.take_callbacks(entry); - for callback in callbacks { - use crate::items::RecordCallback as Cb; - match callback { - // A refusal finishes no set-up (its found byte is clear, `0x5d83b8`) and runs - // no entry change (`0x5d96bb`). - Cb::SetUp(_) | Cb::Entry(_) if !answered => {} - Cb::SetUp(guid) => { - let run = item_watch(&sc.index, &sc.stores, &sc.self_guid, &sc.items) - .set_up_run(guid, entry, &sc.bag_cache); - if run.notice.is_some() { - replay_enchant_times( - &mut sc.items, - &mut sc.countdowns, - &sc.index, - guid, - ); - } - sc.item_lane.push(run); - } - Cb::Entry(guid) => { - let run = item_watch(&sc.index, &sc.stores, &sc.self_guid, &sc.items) - .entry_run(guid, entry, &sc.bag_cache); - sc.item_lane.push(run); - } - // A refusal releases a row ([`crate::ui_loot`]'s deviation). - Cb::LootRow => { - if let Some(loot) = sc.loot.as_mut() { - loot.row_answered(&sc.items); - } - } - Cb::Push => { - if let Some(loot) = sc.loot.as_mut() { - loot.push_answered(&sc.items, entry); - } - } - // The trade and the ammo getters' callbacks run for a ready record only - // (`0x4c0343`, `0x4c84f6`). - Cb::Trade if answered => sc.item_lane.push(crate::item_watch::Run { - notice: Some(crate::item_watch::ItemNotice::TradeRecord { entry }), - ..Default::default() - }), - Cb::Ammo if answered => { - sc.field_notices - .write(crate::field_watch::FieldNotice::Player { - id: crate::field_watch::id::UNIT_INVENTORY_CHANGED, - }) - } - Cb::Trade | Cb::Ammo => {} - // The equip callbacks run with the VM, after the feeds push the answer - // ([`crate::ui_bind_confirm::replay_equip_records`]). - Cb::Swap | Cb::AutoEquip => sc.items.run_with_vm(entry, callback, answered), - // The vendor's run for a record and a refusal alike (`0x4fb0f0`, `0x4fb570`). - Cb::Merchant => sc.merchant.row_answered(), - Cb::Buyback => sc.merchant.buyback_answered(), - // The trainer getters' run the state pass for a ready record only (`0x4d9146`, - // `0x4d9db6`). - Cb::Trainer if answered => sc.trainer.owed(), - Cb::Trainer => {} - // `QUEST_ITEM_UPDATE` for a ready record only (`0x5018d6`, `0x5018f5`, - // `0x501903`), whatever the window shows then. - Cb::Quest if answered => { - if let Some(lane) = sc.quest_giver.as_mut() { - lane.push(crate::ui_quest::QuestGiverEvent::ItemUpdate); - } - } - Cb::Quest => {} - // `MAIL_INBOX_UPDATE` for a ready record only (`0x4af0a6`, `0x4ad016`); the - // notice's subject reads the record as its row resolves. - Cb::Mail if answered => { - if let Some(lane) = sc.mail.as_mut() { - lane.push(crate::ui_mail::MailEvent::InboxUpdate); - } - } - Cb::Mail => {} - // An auction notice's line, shown with the name or, for a refusal, dropped - // (`0x4cd190`). - Cb::AuctionMessage => { - if let (Some(auction), Some(house)) = - (sc.auction.as_mut(), sc.house.as_mut()) - { - crate::ui_auction::message_answered(auction, house, &sc.items, entry); - } - } - // `MAIL_SEND_INFO_UPDATE` for a ready record only (`0x4ae716`, `0x4ae71f`). - Cb::SendMail if answered => { - if let Some(lane) = sc.mail.as_mut() { - lane.push(crate::ui_mail::MailEvent::SendInfoUpdate); - } - } - Cb::SendMail => {} - // `NEW_AUCTION_UPDATE` for a ready record only (`0x4ce2f6`-`0x4ce2ff`). - Cb::AuctionSellItem if answered => { - if let Some(house) = sc.house.as_mut() { - crate::ui_auction::sell_item_answered(house); - } - } - Cb::AuctionSellItem => {} +/// `SMSG_ITEM_QUERY_SINGLE_RESPONSE` as `ItemCacheReceive` (`0x55bdb0`, from the handler +/// `0x555140`) runs it: the record stored, or the refusal taken, and the VM's copy with it +/// ([`crate::ui_items::feed::push_answered_record`]), then every callback the lookups that missed +/// registered, in the order they asked (`0x55ba30` links each at the head with the dedupe flag 0, +/// and `0x55bf12`-`0x55bf39` walk from the tail), each in place: what a callback signals fires at +/// this packet's place among the frame's other packets, and what it sends goes out ahead of a +/// later packet's. A refusal walks the callbacks its own add as [`crate::items::Items`]'s walk says, +/// and is asked again by the next create or entry change of that entry. +fn on_item_answer(In(ev): In, world: &mut World) { + let SessionEvent::ItemTemplate { entry, info } = ev else { + return; + }; + let info = info.map(|b| *b); + debug!("net: item template {entry} → {info:?}"); + let answered = info.is_some(); + let Some(mut items) = world.get_resource_mut::() else { + return; + }; + items.insert_template(entry, info); + let callbacks = items.take_callbacks(entry); + run_answer_step(world, crate::ui_items::feed::push_answered_record, entry); + if answered { + for callback in callbacks { + run_callback(world, entry, callback, true); + } + run_answer_step(world, run_answer_tail, entry); + } else { + walk_refusal(world, entry, callbacks, true); + } +} + +/// The record answer for `entry` run as its handler runs it ([`on_item_answer`]), for a test with +/// no net stack: `info` stored, or refused, and its callbacks walked. +#[cfg(test)] +pub(crate) fn answer_item( + world: &mut World, + entry: u32, + info: Option, +) { + on_item_answer( + In(SessionEvent::ItemTemplate { + entry, + info: info.map(Box::new), + }), + world, + ); +} + +/// A refusal's walk of `list` for `entry`, and with `tail` the callbacks run after the list; when +/// a listener of what it signalled may add to it, the walk goes on behind those signals +/// ([`continue_refusal_walk`]). +fn walk_refusal( + world: &mut World, + entry: u32, + list: Vec, + tail: bool, +) { + let Some(items) = world.get_resource::() else { + return; + }; + items.begin_refusal_walk(entry, list); + let from = items.walk_began(); + while let Some(callback) = world.resource::().next_walk_step() { + run_callback(world, entry, callback, false); + } + if tail { + run_answer_step(world, run_answer_tail, entry); + } + if let (true, Some(from)) = (world.resource::().end_refusal_walk(), from) { + crate::field_callbacks::walk_on(world, entry, from); + } +} + +/// The walk of `entry` that began at `from`, gone on behind its signals: what their listeners +/// added, walked with status 0 in the order added. +pub(crate) fn continue_refusal_walk(world: &mut World, entry: u32, from: crate::lanes::Mark) { + let Some(items) = world.get_resource::() else { + return; + }; + let list = items.take_walk_tail(entry, from); + if !list.is_empty() { + walk_refusal(world, entry, list, false); + } +} + +/// One callback of an answer's list, for a record (`answered`) or a refusal. +fn run_callback( + world: &mut World, + entry: u32, + callback: crate::items::RecordCallback, + answered: bool, +) { + { + use crate::items::RecordCallback as Cb; + match callback { + // The equip callbacks run with the VM, their sends inside them. + Cb::Swap | Cb::AutoEquip => { + crate::ui_bind_confirm::replay_at_answer(world, entry, callback, answered) + } + Cb::ItemCooldown => { + run_answer_step(world, crate::spell::net::item_cooldown_answered, entry) + } + // The query again for a found record only (`0x6e2f78`). + Cb::CooldownQuery if answered => { + run_answer_step(world, crate::spell::net::cooldown_query_answered, entry) + } + Cb::CooldownQuery => {} + Cb::Stationery => run_answer_step(world, paper_answered, entry), + // `ShowItemCastFailure 0x6e29b0`, for a record and a refusal alike: the line again, + // on the cast lane here. + Cb::CastFailure { spell, reason } => { + if let Some(mut reports) = world.get_resource_mut::() { + reports.redisplay(spell, reason, entry); } } - // The combat log's callback for its held lines (`0x6294b0`), which writes each one - // whose item the cache now holds. - if let Some(chat) = &sc.chat { - chat.answer_landed(crate::ui_chat::Answer::Item(entry)); + // `QUEST_LOG_UPDATE` for a ready record only (`0x4e0838`), held and parked here. + Cb::QuestLog if answered => crate::ui_items::feed::quest_log_answered(world), + // The tooltips' rebuilds for a found record only (`0x52e551`, `0x52f826`). + Cb::Tooltip if answered => crate::ui_items::feed::tooltips_answered(world, entry), + Cb::QuestLog | Cb::Tooltip => {} + // The profession and craft lists' rebuilds, for a found record only. + Cb::TradeSkill | Cb::TradeSkillBuild | Cb::Craft => { + if answered { + crate::ui_tradeskill::record_answered(world, callback); + } } - // The auction lists' callbacks (`0x4cc9bf`, `0x4ccbff`, `0x4cce4f`), a record or a - // refusal: a page that now waits on nothing runs its tail. - if let (Some(auction), Some(house)) = (sc.auction.as_mut(), sc.house.as_mut()) { - crate::ui_auction::record_answered(auction, house, &sc.items, entry); + _ => run_answer_step(world, run_record_callback, (entry, callback, answered)), + } + } +} + +/// Run one step of an answer's callbacks as a one-shot, its unit edits applied as it returns; a +/// harness without its state runs nothing. +fn run_answer_step( + world: &mut World, + step: impl IntoSystem, (), M> + 'static, + input: T, +) { + if let Err(err) = world.run_system_cached_with(step, input) { + debug!("net: an item answer's callback did not run: {err}"); + } + crate::creature_anim::apply_unit_edits(world); +} + +/// One callback an item lookup registered, for the answer of `entry`, a record (`answered`) or a +/// refusal: each item's set-up (`0x5d8390`) and entry change's (`0x5d96b0`), the loot window's rows +/// (`0x4c2ac0`) and pushes (`0x491ee0`), the trade getters' (`0x4c0340`), the ammo getters' +/// (`0x4c84f0`), the vendor rows' (`0x4fada0`, `0x4fb570`), the trainer rows' (`0x4d9140`, +/// `0x4d9db0`), the questgiver rows' (`0x5018c0`), the turn-in's reward lines' (`0x5dc7b0`), the +/// mail rows' and notices' (`0x4af0a0`, `0x4ad010`), the mail attachment's (`0x4ae710`) and the +/// auction notices' lines (`0x4cd190`). The equip callbacks are the VM's +/// ([`crate::ui_bind_confirm::replay_at_answer`]). +fn run_record_callback( + In((entry, callback, answered)): In<(u32, crate::items::RecordCallback, bool)>, + mut sc: Scene, +) { + use crate::items::RecordCallback as Cb; + match callback { + // A refusal finishes no set-up (its found byte is clear, `0x5d83b8`) and runs + // no entry change (`0x5d96bb`). + Cb::SetUp(_) | Cb::Entry(_) if !answered => {} + Cb::SetUp(guid) => { + let run = item_watch(&sc.index, &sc.stores, &sc.self_guid, &sc.items).set_up_run( + guid, + entry, + &sc.bag_cache, + ); + if run.notice.is_some() { + replay_enchant_times( + &mut sc.items, + &mut sc.countdowns, + &sc.index, + &mut sc.view_log, + guid, + ); + // Its entry sorts ahead of its own notice and behind the set-ups before it. + sc.view_log.close(); + } + sc.item_lane.push(run); + } + Cb::Entry(guid) => { + let run = item_watch(&sc.index, &sc.stores, &sc.self_guid, &sc.items).entry_run( + guid, + entry, + &sc.bag_cache, + ); + sc.item_lane.push(run); + } + // A refusal releases a row ([`crate::ui_loot`]'s deviation). + Cb::LootRow => { + if let Some(loot) = sc.loot.as_mut() { + loot.row_answered(&sc.items); } } + Cb::Push => { + if let Some(loot) = sc.loot.as_mut() { + loot.push_answered(&sc.items, entry); + } + } + // The trade and the ammo getters' callbacks run for a ready record only + // (`0x4c0343`, `0x4c84f6`). + Cb::Trade if answered => sc.item_lane.push(crate::item_watch::Run { + notice: Some(crate::item_watch::ItemNotice::TradeRecord { entry }), + ..Default::default() + }), + Cb::Ammo if answered => sc + .field_notices + .write(crate::field_watch::FieldNotice::Player { + id: crate::field_watch::id::UNIT_INVENTORY_CHANGED, + }), + Cb::Trade | Cb::Ammo => {} + // The bar's recount of the entry, for a ready record only (`0x4e5b86` → `0x4e5c70`). + Cb::ActionSlots if answered => sc.item_lane.push(crate::item_watch::Run { + notice: Some(crate::item_watch::ItemNotice::ActionRecord { entry }), + ..Default::default() + }), + Cb::ActionSlots => {} + // The game object plate's rebuild, for a found record only (`0x52ad2f`). + Cb::LockKey if answered => sc.item_lane.push(crate::item_watch::Run { + notice: Some(crate::item_watch::ItemNotice::LockKeyRecord), + ..Default::default() + }), + Cb::LockKey => {} + Cb::Swap + | Cb::AutoEquip + | Cb::ItemCooldown + | Cb::CooldownQuery + | Cb::Stationery + | Cb::CastFailure { .. } + | Cb::QuestLog + | Cb::Tooltip + | Cb::TradeSkill + | Cb::TradeSkillBuild + | Cb::Craft => {} + // The vendor's run for a record and a refusal alike (`0x4fb0f0`, `0x4fb570`). + Cb::Merchant => sc.merchant.row_answered(), + Cb::Buyback => sc.merchant.buyback_answered(), + // The trainer getters' run the state pass for a ready record only (`0x4d9146`, + // `0x4d9db6`). + Cb::Trainer if answered => sc.trainer.owed(), + Cb::Trainer => {} + // `QUEST_ITEM_UPDATE` for a ready record only (`0x5018d6`, `0x5018f5`, + // `0x501903`), whatever the window shows then. + Cb::Quest if answered => { + if let Some(lane) = sc.quest_giver.as_mut() { + lane.push(crate::ui_quest::QuestGiverEvent::ItemUpdate); + } + } + Cb::Quest => {} + // The turn-in's reward line, shown with a ready record (`0x5dc7b0`). + Cb::QuestReward => { + if let (Some(lines), Some(lane)) = (sc.quest_lines.as_mut(), sc.quest_giver.as_mut()) { + lines.item_answered(entry, &sc.items, lane); + } + } + // `MAIL_INBOX_UPDATE` for a ready record only (`0x4af0a6`, `0x4ad016`); the + // notice's subject reads the record as its row resolves. + Cb::Mail if answered => { + if let Some(lane) = sc.mail.as_mut() { + lane.push(crate::ui_mail::MailEvent::InboxUpdate); + } + } + Cb::Mail => {} + // An auction notice's line, shown with the name or, for a refusal, dropped + // (`0x4cd190`). + Cb::AuctionMessage => { + if let (Some(auction), Some(house)) = (sc.auction.as_mut(), sc.house.as_mut()) { + crate::ui_auction::message_answered(auction, house, &sc.items, entry); + } + } + // `MAIL_SEND_INFO_UPDATE` for a ready record only (`0x4ae716`, `0x4ae71f`). + Cb::SendMail if answered => { + if let Some(lane) = sc.mail.as_mut() { + lane.push(crate::ui_mail::MailEvent::SendInfoUpdate); + } + } + Cb::SendMail => {} + // `NEW_AUCTION_UPDATE` for a ready record only (`0x4ce2f6`-`0x4ce2ff`). + Cb::AuctionSellItem if answered => { + if let Some(house) = sc.house.as_mut() { + crate::ui_auction::sell_item_answered(house); + } + } + Cb::AuctionSellItem => {} + // A roll's or its line's, for a record and a refusal alike: the start's opens the roll + // (`0x61b460` → `0x61b430`), a line's goes on to its name or is shown (`0x61c4b0`, + // `0x61bd50`, `0x61b7d0`). + Cb::LootRoll(wait) => sc.loot_rolls.item_answered( + wait, + answered, + &sc.items, + &sc.names, + &sc.net, + sc.self_guid.0, + ), + } +} + +/// The answer's callbacks registered outside the lookups' list, run after it. +fn run_answer_tail(In(entry): In, mut sc: Scene) { + // The combat log's callback for its held lines (`0x6294b0`), which writes each one + // whose item the cache now holds. + if let Some(chat) = &sc.chat { + chat.answer_landed(crate::ui_chat::Answer::Item(entry)); + } + // The auction lists' callbacks (`0x4cc9bf`, `0x4ccbff`, `0x4cce4f`), a record or a + // refusal: a page that now waits on nothing runs its tail. + if let (Some(auction), Some(house)) = (sc.auction.as_mut(), sc.house.as_mut()) { + crate::ui_auction::record_answered(auction, house, &sc.items, entry); + } +} + +/// Items past their create block: the lifetime and enchant countdowns, written into the item's +/// own [`crate::items::Countdowns`]. +fn on_item(In(ev): In, mut sc: Scene) { + match ev { // `0x5e4f30`'s two arms share the item lookup (`0x468460`, `TYPEMASK_ITEM`) and differ on // a miss. SessionEvent::ItemTime { item_guid, seconds } => { @@ -333,6 +542,7 @@ fn on_item(In(ev): In, mut sc: Scene) { match sc.index.0.get(&item_guid).copied() { Some(e) if sc.countdowns.contains(e) => { if let Ok(mut c) = sc.countdowns.get_mut(e) { + sc.view_log.countdowns(item_guid, Some(c.clone())); c.set_lifetime(seconds); } debug!("item duration: item {item_guid:#x} → {seconds}s"); @@ -347,6 +557,7 @@ fn on_item(In(ev): In, mut sc: Scene) { } => match sc.index.0.get(&item_guid).copied() { Some(e) if sc.countdowns.contains(e) => { if let Ok(mut c) = sc.countdowns.get_mut(e) { + sc.view_log.countdowns(item_guid, Some(c.clone())); if c.set_enchant(slot, seconds) { debug!("enchant timer: item {item_guid:#x} slot {slot} → {seconds}s"); } else { @@ -364,6 +575,7 @@ fn on_item(In(ev): In, mut sc: Scene) { }, _ => {} } + sc.view_log.close(); } /// `CGItem_C::ApplyRecord`'s replay (`0x5ebde0` at `0x5d85b7`): the enchant times queued on the @@ -375,12 +587,16 @@ fn replay_enchant_times( items: &mut Items, countdowns: &mut Query<&mut crate::items::Countdowns>, index: &GuidIndex, + view_log: &mut crate::ui_unit::views::ViewLog, guid: u64, ) { let queued = items.take_enchant_times(guid); let Some(mut cells) = index.0.get(&guid).and_then(|&e| countdowns.get_mut(e).ok()) else { return; }; + if !queued.is_empty() { + view_log.countdowns(guid, Some(cells.clone())); + } for (slot, seconds) in queued { if !cells.set_enchant(slot, seconds) { debug!("enchant timer: queued slot {slot} for {guid:#x} is past the seventh — refused"); @@ -480,6 +696,24 @@ fn on_monster_move(In(ev): In, mut sc: Scene) { &mut sc.transforms, &mut sc.riders, ); + // A path started on the active mover runs its input tick (`0x6187a0` → `0x602053`), whose + // precondition the server's spline fails (`0x5144e0`): the teardown leg stops the auto-move + // (`0x5146d6`). A stop starts no path, and nor does a rooted mover: the start returns 0 on + // the root bit `0x1000` (`0x6187c2`-`0x6187c7`), so `0x601fee` skips the tick. + let mover_rooted = sc + .player + .as_deref() + .is_some_and(crate::player::Player::rooted); + if !stop && !mover_rooted { + update::stop_auto_move( + sc.mover.as_deref(), + sc.follow.as_deref_mut(), + sc.approach.as_deref_mut(), + sc.call_autorun.as_deref_mut(), + &mut sc.field_notices, + guid, + ); + } } } @@ -503,7 +737,7 @@ fn on_gameobject_info(In(ev): In, mut sc: Scene) { // The leaderboard's callback `0x4e0800` signals for a landed record (`0x4e081a`). if sc.go_templates.take_quest_wait(entry) { if let Some(log) = sc.quest_log.as_mut() { - log.ready(crate::ui_quest_log::QuestEvent::ObjectNamed); + log.ready(crate::ui_quest_log::QuestEvent::Named); } } } @@ -1628,7 +1862,11 @@ mod tests { ); assert_eq!( drain(world), - crate::field_watch::guild_tag(ME), + [ + &crate::field_watch::guild_tag(ME)[..], + &[crate::field_watch::FieldNotice::RecruitmentCascade], + ] + .concat(), "a first create runs no notify pass, only a player's own `PostInit`" ); super::super::handlers::dispatch( @@ -1729,8 +1967,12 @@ mod tests { super::super::handlers::dispatch(world, super::wire(vec![create(ME, &mate)])); assert_eq!( drain(world), - crate::field_watch::guild_tag(ME), - "our own create: the guild tag alone" + [ + &crate::field_watch::guild_tag(ME)[..], + &[FieldNotice::RecruitmentCascade], + ] + .concat(), + "our own create: the guild tag, then the recruitment cascade (`0x5dec1e`)" ); } diff --git a/crates/benilla-app/src/net/objects/arrival.rs b/crates/benilla-app/src/net/objects/arrival.rs index 52a19cc9e..364e9775d 100644 --- a/crates/benilla-app/src/net/objects/arrival.rs +++ b/crates/benilla-app/src/net/objects/arrival.rs @@ -15,19 +15,33 @@ use crate::net::ClientCommand; /// What the arrival writes past the streamed world; each absent in a harness without it. #[derive(SystemParam)] pub(super) struct Arrival<'w> { - own_control: Option>, actions: Option>, + spells: Option>, + reactive: Option>, lane: Option>, stable: Option>, } /// The arrival's writes, in its order, and its item on the arrival lane, at the create's place. pub(super) fn arrive(sc: &mut Scene, arrival: &mut Arrival, guid: u64) { + // `ResetSpellBook 0x4b23a0` empties the reactive list (`0x5dea86`), and each initial spell's + // `LearnSpell` runs the registrar, whose leg takes it in again in wire order + // (`0x5dea96`-`0x5deab9`). + if let (Some(actions), Some(spells), Some(reactive)) = ( + arrival.actions.as_deref(), + arrival.spells.as_deref(), + arrival.reactive.as_mut(), + ) { + reactive.0.reset(); + for &spell_id in &actions.initial { + reactive.0.learned(spell_id, &spells.catalog); + } + } // `0x5deb49`: the manager's `+0xc8` gates the restore, the claim and the cascade; its // constructor (`0x4650e7`) is its only store, so it is clear at every create. let control_gained = crate::player::regain_control_on_arrival( sc.mover_lock.as_deref_mut(), - arrival.own_control.as_deref_mut(), + sc.own_control_lost.as_deref_mut(), ); // `0x4958a0` (`0x5deb5b`) claims our own mover through `SetActiveMover` (`0x6006e0`), which // sends `CMSG_SET_ACTIVE_MOVER` only when the mover changes ([`crate::net::MoverClaim`]). diff --git a/crates/benilla-app/src/net/objects/item_deactivate.rs b/crates/benilla-app/src/net/objects/item_deactivate.rs new file mode 100644 index 000000000..f90ec58a5 --- /dev/null +++ b/crates/benilla-app/src/net/objects/item_deactivate.rs @@ -0,0 +1,40 @@ +//! `CGItem_C::Deactivate`'s head, which a release and a destroy run on every item and bag +//! (`0x464920` → `[vtable+0x4]` at `0x46496f`): what still names the item lets it go, inside the +//! object packet's handler. Its interface tail is the item lane's run ([`crate::item_watch`]). + +use super::Scene; + +/// `CGItem_C::Deactivate`'s head (`0x5d8660`, slot 1 of the item's vtable `0x80ada8` and the +/// bag's `0x80ac88`): what still names `item` lets it go, in its order, each signalling at the +/// packet's place ahead of the tail. The loot window looting it (`[0xb71b48]`, `0x5d867f`) closes +/// with its release (`0x48f200(1, 0, 0)` at `0x5d869b`); the pending record's cast from it +/// (`0x6e3d40` at `0x5d86ab`) is cancelled (`0x6e4940(1, 0, 0x1c)` at `0x5d86c4`); the cursor +/// holding it (`0x494c60` at `0x5d86d4`) lets it go (`0x495190(1, 1)` at `0x5d86e9`); the +/// reader on it (`[0xbc3fa0]`, `0x5d86f3`) closes (`0x4e32e0` of a zero guid at `0x5d8713`); and +/// a record not yet arrived (`+0x314` bit 1 clear, `0x5d8718`) drops this item's set-up callback +/// `0x5d8390` from its entry's pending record (`0x55c0c0` at `0x5d8733`), so the next object +/// under the guid sets up off its own request alone. The callback waits only until its record +/// lands, which is the bit, so the wait's presence stands for it. The owner's pending count it +/// lowers (`0x5d875d`) has no reader here. +pub(super) fn head(sc: &mut Scene, item: u64) { + if let (Some(loot), Some(latch)) = (sc.loot.as_deref_mut(), sc.loot_latch.as_deref_mut()) { + if loot.source() == Some(item) { + crate::ui_loot::end_loot_window_on_its_item(loot, latch, &sc.net); + } + } + let player = sc.self_guid.0.and_then(|me| sc.index.0.get(&me).copied()); + sc.item_cast.run(item, &sc.net, player); + sc.item_lane + .push(crate::item_watch::Run::clearing_cursor(item)); + sc.item_text.run(item); + let entry = sc + .index + .0 + .get(&item) + .and_then(|&e| sc.stores.get(e).ok()) + .and_then(|s| s.0.object_entry()); + if let Some(entry) = entry { + sc.items + .cancel_wait(entry, crate::items::RecordCallback::SetUp(item)); + } +} diff --git a/crates/benilla-app/src/net/objects/update.rs b/crates/benilla-app/src/net/objects/update.rs index d9048c315..b7a6df3cb 100644 --- a/crates/benilla-app/src/net/objects/update.rs +++ b/crates/benilla-app/src/net/objects/update.rs @@ -148,6 +148,8 @@ enum Body { /// Bit 3 of the unit's `+0xc58`, which only the constructor clears (`0x5fae7a`): the /// object a block brings back is the one that left. xp_awarded: bool, + /// Bit 0x400 of the same word ([`crate::net::ClientControlled`]). + client_controlled: bool, /// A unit's resolved records, which its slot 3 compares (`0x5fbe28`). display: Option, /// A transport's clock, which reactivation leaves (`0x464530` constructs nothing). @@ -188,11 +190,11 @@ impl Released { } /// A new object of type `type_id` frees the oldest released one of that type (`0x466e55`, - /// the head of the list). - fn free_oldest(&mut self, type_id: u8) { - if let Some(guid) = self.reuse.get_mut(&type_id).and_then(VecDeque::pop_front) { - self.objects.remove(&guid); - } + /// the head of the list); the guid it freed. + fn free_oldest(&mut self, type_id: u8) -> Option { + let guid = self.reuse.get_mut(&type_id).and_then(VecDeque::pop_front)?; + self.objects.remove(&guid); + Some(guid) } /// Frees every released object, as leaving the world does (`0x467700`). @@ -292,16 +294,23 @@ fn on_object_create(In(ev): In, mut sc: Scene) { }), ) => { let moved = write_fields(&mut store, fields.clone()); - let (pose, modes, xp_awarded, display, kept_anchor) = match body { + let (pose, modes, (xp_awarded, controlled), display, kept_anchor) = match body { Body::World { pose, modes, xp_awarded, + client_controlled, display, anchor, .. - } => (Some(pose), modes, xp_awarded, display, anchor), - Body::Item { .. } => (None, None, false, None, None), + } => ( + Some(pose), + modes, + (xp_awarded, client_controlled), + display, + anchor, + ), + Body::Item { .. } => (None, None, (false, false), None, None), }; // Only a unit takes the block's movement (`0x46638c`); any other type keeps its pose. let unit = matches!(kind, EntityKind::Unit | EntityKind::Player); @@ -322,6 +331,9 @@ fn on_object_create(In(ev): In, mut sc: Scene) { if xp_awarded { sc.commands.entity(e).insert(XpAwarded); } + if controlled { + sc.commands.entity(e).insert(crate::net::ClientControlled); + } if let Some(display) = display { sc.commands.entity(e).insert(display); } @@ -364,7 +376,19 @@ fn on_object_create(In(ev): In, mut sc: Scene) { /// allocated apart and frees nothing (`0x466e0c`). fn allocate(sc: &mut Scene, guid: u64, ty: ObjectType) { if sc.self_guid.0 != Some(guid) { - sc.released.free_oldest(type_id(ty)); + if let Some(freed) = sc.released.free_oldest(type_id(ty)) { + free_item(sc, freed); + } + } +} + +/// An object freed here: an item's lock goes with it, at this place among the packet's runs +/// ([`crate::item_watch::Freed`]). +fn free_item(sc: &mut Scene, object: u64) { + if guid::is_item(object) { + sc.item_lane.push(crate::item_watch::Run::freeing( + crate::item_watch::Freed::Items(vec![object]), + )); } } @@ -398,6 +422,7 @@ fn on_item_create(In(ev): In, mut sc: Scene) { ) => { let moved = write_fields(&mut store, fields); sc.view_log.replaced(guid, None); + sc.view_log.countdowns(guid, None); let e = crate::items::spawn_item(&mut sc.commands, &mut sc.index, guid, store, container); if let Body::Item { countdowns, .. } = body { @@ -409,6 +434,7 @@ fn on_item_create(In(ev): In, mut sc: Scene) { (None, None) => { allocate(&mut sc, guid, item_type(container)); sc.view_log.replaced(guid, None); + sc.view_log.countdowns(guid, None); crate::items::spawn_item(&mut sc.commands, &mut sc.index, guid, fields, container); sc.pass.unshown.insert(guid); Vec::new() @@ -446,7 +472,7 @@ fn write_logged( /// A held object leaving the live table: the store it takes, logged for any unit, as one a token /// names now or named earlier in the frame (the target's target before it changed) reads it in /// the frame's earlier listeners, and for any item, as a weapon the active player wore earlier in -/// the frame reads to the stat getters there. +/// the frame reads to the stat getters there, with the item's countdown cells. fn log_destroy(sc: &mut Scene, guid: u64) { let Some(&e) = sc.index.0.get(&guid) else { return; @@ -455,6 +481,9 @@ fn log_destroy(sc: &mut Scene, guid: u64) { if before.is_some() { sc.view_log.replaced(guid, before); } + if let Ok(cells) = sc.countdowns.get(e) { + sc.view_log.countdowns(guid, Some(cells.clone())); + } } /// A values block (`0x467160`): written into a held object, or one it brings back; a guid the @@ -600,6 +629,7 @@ fn respawn(sc: &mut Scene, guid: u64, body: Body, store: ObjectFields, pose: Opt let e = crate::items::spawn_item(&mut sc.commands, &mut sc.index, guid, store, container); sc.commands.entity(e).insert(countdowns); + sc.view_log.countdowns(guid, None); } Body::World { kind, @@ -610,6 +640,7 @@ fn respawn(sc: &mut Scene, guid: u64, body: Body, store: ObjectFields, pose: Opt modes, rider, xp_awarded, + client_controlled, display, anchor, } => { @@ -638,6 +669,9 @@ fn respawn(sc: &mut Scene, guid: u64, body: Body, store: ObjectFields, pose: Opt if xp_awarded { entity.insert(XpAwarded); } + if client_controlled { + entity.insert(crate::net::ClientControlled); + } if let Some(display) = display { entity.insert(display); } @@ -753,15 +787,18 @@ fn on_object_destroyed(In(ev): In, mut sc: Scene, script: Option, mut sc: Scene, script: Option) { + if benilla_protocol::guid::is_item(guid) { + super::item_deactivate::head(sc, guid); + } let gone = item_watch(&sc.index, &sc.stores, &sc.self_guid, &sc.items).destroyed_run(guid); sc.item_lane.push(gone.unwrap_or_default()); let held = |g: u64| sc.index.0.get(&g).and_then(|e| sc.stores.get(*e).ok()); @@ -826,12 +868,127 @@ fn deactivate(sc: &mut Scene, guid: u64, script: Option<&UiScript>) { || crate::target::raid_member_or_pet(group, guid, me, &held), ); } + // `0x5fbc26`-`0x5fbc3b`: the active mover's release stops its auto-move + // (`ReleaseActiveMover 0x6006b0` → `0x6006c2`); the global goes with the unit ([`release`]). + // The later `0x5fbcd7` finds no active mover left. + stop_auto_move( + sc.mover.as_deref(), + sc.follow.as_deref_mut(), + sc.approach.as_deref_mut(), + sc.call_autorun.as_deref_mut(), + &mut sc.field_notices, + guid, + ); // The release's `PARTY_MEMBER_DISABLE` for a party slot's player (`0x5e9b78`). if held(guid).is_some_and(|s| s.0.created_as() == Some(ObjectType::Player)) { sc.group.member_object(guid, false); } } +/// Whether the mover's input tick takes its teardown leg (`0x5146c1`-`0x5146ce`): it may neither +/// translate (`0x514560`) nor turn (`0x5145b0`), off its health, the far-sight latch as the packet +/// leaves it (`[mover+0x1c70] & 1`, `0x514540`, past the active-player test `0x514537`), the root +/// and the stun its new flags hold ([`crate::player::MoverInput`]). +fn tick_tears_down(sc: &Scene, fields: &ObjectFields) -> bool { + let driving_own_body = sc + .mover_lock + .as_deref() + .is_none_or(|l| l.foreign_mover.is_none()); + let input = crate::player::MoverInput { + dead: fields.unit_is_dead(), + view_is_out: crate::player::view_is_out( + driving_own_body, + sc.far_sight + .as_deref() + .is_some_and(crate::player::FarSight::on), + ), + }; + let rooted = sc + .player + .as_deref() + .is_some_and(crate::player::Player::rooted); + let stunned = fields.unit_flags() & crate::player::UNIT_FLAG_STUNNED != 0; + input.torn_down(rooted, stunned) +} + +/// `StopAutoMove` (`0x60fb60`) on `guid`, a no-op unless it is the active mover +/// ([`crate::player::AutoMoveStop`]): the scene's claim, auto-move and notice lane. +pub(super) fn stop_auto_move( + mover: Option<&crate::net::MoverClaim>, + follow: Option<&mut crate::player::FollowState>, + approach: Option<&mut crate::player::Approach>, + autorun: Option<&mut crate::player::CallAutorun>, + lane: &mut crate::field_watch::NoticeLane, + guid: u64, +) { + if mover.is_some_and(|m| m.holds(guid)) { + crate::player::end_auto_move(follow, approach, autorun, Some(lane)); + } +} + +/// `StartFarSight` (`0x5ee270`) on our player `me`, whose `PLAYER_FARSIGHT` names `object`, held: +/// the update while far sight is off. A start (`0x5ee39c` on, past the unresolved return) stops +/// the auto-move: a unit we control takes the active mover (`0x5ee45d` → `0x5ee477`), whose switch +/// stops the outgoing one's (`0x600742`) and is a no-op when it already holds it (`0x6006fb`); the +/// switch itself is possession's control update's. Any other object runs the mover's tick +/// (`0x5ee4a2`), which the view's going out tears down. +fn start_far_sight(sc: &mut Scene, me: u64, object: u64) { + let started = match sc.far_sight.as_deref() { + Some(far_sight) => { + let was_on = far_sight.on(); + let index = &sc.index; + far_sight.start(Some(object), |g| index.0.contains_key(&g), &sc.net); + !was_on + } + // A harness without the machine: the start's stop. + None => true, + }; + if !started { + return; + } + let active = sc.mover.as_deref().and_then(crate::net::MoverClaim::get); + // `IsClientControlled` (`0x5fa5f0`): our own control, or the unit's own bit. + let controlled = if object == me { + !sc.own_control_lost.as_deref().is_some_and(|l| l.0) + } else { + sc.client_controlled.contains(sc.index.0[&object]) + }; + let stops = if controlled { + active.filter(|&m| m != object) + } else { + Some(me) + }; + if let Some(mover) = stops { + stop_auto_move( + sc.mover.as_deref(), + sc.follow.as_deref_mut(), + sc.approach.as_deref_mut(), + sc.call_autorun.as_deref_mut(), + &mut sc.field_notices, + mover, + ); + } +} + +/// The far-sight arrival of a new object: a unit's `PostInit` (`0x5fbb1a`) and a dynamic object's +/// `OnCreate` (`0x5d552d`) look up the active player (`0x468460`, as a player) and, when its +/// `PLAYER_FARSIGHT` (`[player+0xe68]+0x830`) names the new object, start far sight on it +/// ([`start_far_sight`]). +fn far_sight_arrives(sc: &mut Scene, guid: u64) { + let Some(me) = sc.self_guid.0 else { + return; + }; + let field = sc + .index + .0 + .get(&me) + .and_then(|&e| sc.stores.get(e).ok()) + .and_then(|s| s.0.player_farsight()); + if field == Some(guid) { + start_far_sight(sc, me, guid); + } +} + /// `0x464920` past the deactivate: the object leaves the live table for the released one, its /// fields and what it stood as kept, and its model fades out ([`super::tear_down`]). fn release(sc: &mut Scene, guid: u64) { @@ -869,6 +1026,7 @@ fn release(sc: &mut Scene, guid: u64) { local_orientation: r.local_orientation, }), xp_awarded: sc.xp_awarded.contains(e), + client_controlled: sc.client_controlled.contains(e), display: sc.held_displays.get(e).ok().copied(), anchor: sc.anchors.get(e).ok().copied(), } @@ -1110,6 +1268,48 @@ fn notify(sc: &mut Scene, guid: u64, block: Notified, bridged: bool) { crate::field_watch::Step::Notice(crate::field_watch::FieldNotice::TrainerPass) => { sc.trainer.owed() } + // A watcher's stop of the mover's auto-move, its `AUTOFOLLOW_END` at this place. + crate::field_watch::Step::Notice(crate::field_watch::FieldNotice::AutoMoveStop) => { + stop_auto_move( + sc.mover.as_deref(), + sc.follow.as_deref_mut(), + sc.approach.as_deref_mut(), + sc.call_autorun.as_deref_mut(), + &mut sc.field_notices, + guid, + ); + } + // The stun's tick (`0x5ff501` → `0x514640`): its teardown leg (`0x5146d6`). + crate::field_watch::Step::Notice(crate::field_watch::FieldNotice::InputTick) => { + if sc + .stores + .get(e) + .is_ok_and(|store| tick_tears_down(sc, &store.0)) + { + stop_auto_move( + sc.mover.as_deref(), + sc.follow.as_deref_mut(), + sc.approach.as_deref_mut(), + sc.call_autorun.as_deref_mut(), + &mut sc.field_notices, + guid, + ); + } + } + // The far-sight field's change (`0x5de0d0`): on a held object the start + // (`0x5de144` → `0x5ee270`, [`start_far_sight`]); else the end (`0x5de15d` → + // `0x5ee590`). + crate::field_watch::Step::Notice(crate::field_watch::FieldNotice::FarSight { + object, + }) => { + let field = (object != 0).then_some(object); + if field.is_some_and(|g| sc.index.0.contains_key(&g)) { + start_far_sight(sc, guid, object); + } else if let Some(far_sight) = sc.far_sight.as_deref() { + let index = &sc.index; + far_sight.end(field, |g| index.0.contains_key(&g), &sc.net); + } + } // The ghost flag's clear (`0x5dea20`): `SetAreaSpiritHealer(0, 0)` runs at the packet, // a pending wave's `CMSG_CANCEL_AURA` going out here and its event on the lane ahead // of the `PLAYER_UNGHOST` that follows. @@ -1120,7 +1320,8 @@ fn notify(sc: &mut Scene, guid: u64, block: Notified, bridged: bool) { continue; }; if spirit.set_healer(None).cancel_aura { - let player = Some((e, fields.player_farsight())); + let farsight = sc.stores.get(e).ok().and_then(|s| s.0.player_farsight()); + let player = Some((e, farsight)); let held = |guid: u64| sc.index.0.contains_key(&guid); let spell = crate::ui_dialog_verbs::AREA_SPIRIT_HEALER_AURA; if sc.aura.cancel_at_packet(player, held, spell) { @@ -1131,6 +1332,43 @@ fn notify(sc: &mut Scene, guid: u64, block: Notified, bridged: bool) { } } } + // The ghost bit's corpse query (`0x5eeac1` → `0x491f50`), at its place: the cache reset, + // the range latch's `CORPSE_OUT_OF_RANGE` on the lane behind `PLAYER_UNGHOST`, and a + // ghost's `MSG_CORPSE_QUERY` sent here, as the bit stands after this packet. + crate::field_watch::Step::Notice(crate::field_watch::FieldNotice::QueryCorpse) => { + let was_in = crate::death::reset_corpse( + Some(&mut sc.death_net), + sc.death_latches.as_deref_mut(), + ); + if was_in { + sc.field_notices + .write(crate::field_watch::FieldNotice::Global { + id: crate::field_watch::id::CORPSE_OUT_OF_RANGE, + }); + } + let ghost = sc.stores.get(e).is_ok_and(|s| s.0.player_is_ghost()); + crate::death::ask_corpse(ghost, &sc.net); + } + // The quest-slot watcher's accept line (`0x5dde4f`-`0x5dde7d`), at its place. + crate::field_watch::Step::Notice(crate::field_watch::FieldNotice::QuestAccepted { + quest_id, + }) => { + if let (Some(quest_log), Some(lane), Some(lines)) = ( + sc.quest_log.as_deref(), + sc.quest_giver.as_deref_mut(), + sc.quest_lines.as_deref_mut(), + ) { + crate::ui_quest::lines::Raise { + quest_log, + items: &sc.items, + commands: &sc.net, + lane, + notices: &mut sc.field_notices, + lines, + } + .line(crate::ui_quest::QuestLine::Accepted(quest_id)); + } + } crate::field_watch::Step::Notice(n) => sc.field_notices.write(n), crate::field_watch::Step::Item(run) => sc.item_lane.push(run), } @@ -1144,7 +1382,8 @@ fn notify(sc: &mut Scene, guid: u64, block: Notified, bridged: bool) { .edges() .any(|(index, _, _)| index == benilla_protocol::field::FIELD_PLAYER_FIELD_COINAGE) { - if let (Some(trade), Some(purse)) = (sc.trade.as_mut(), fields.player_money()) { + let purse = sc.stores.get(e).ok().and_then(|s| s.0.player_money()); + if let (Some(trade), Some(purse)) = (sc.trade.as_mut(), purse) { crate::ui_trade::trim_offer_to_purse(trade, purse, &sc.net); } } @@ -1178,11 +1417,14 @@ fn mirror_guild(sc: &mut Scene) { /// The create hook of an object not yet shown (the table `0x465e78`), which alone asks the /// object's record: an item's record set-up (`0x5d8400` → `0x5d8300`); a unit's `PostInit` -/// (`0x5fb880`), whose display resolve asks a creature's record (`0x60afb0`, at `0x60b15b`); a -/// player's (`0x5debe0`), its name (`0x5dec12` → `0x609210`) and guild tag (`0x5dec19`) ahead of another -/// player's party record (`0x5dec5f`, the active player skipped at `0x5dec48`-`0x5dec5b`), and for -/// the active player its arrival last (`0x5dec7b`, [`super::arrival`]); a game object's template -/// (`0x5f7c40`, at `0x5f7d81`), whose lockId decides use-vs-cast. +/// (`0x5fb880`), whose display resolve asks a creature's record (`0x60afb0`, at `0x60b15b`) and +/// which starts far sight late, ahead of its tail (`0x60c520`, `0x606fe0`, `0x607710`, +/// `0x5ff130`, `0x612a30`; [`far_sight_arrives`]); a player's (`0x5debe0`), the unit's +/// first (`0x5dec09`), then its name (`0x5dec12` → `0x609210`) and guild tag (`0x5dec19`) ahead of +/// another player's party record (`0x5dec5f`, the active player skipped at `0x5dec48`-`0x5dec5b`), +/// and for the active player its arrival last (`0x5dec7b`, [`super::arrival`]); a game object's +/// template (`0x5f7c40`, at `0x5f7d81`), whose lockId decides use-vs-cast; a dynamic object's +/// `OnCreate` (`0x5d5420`), a far-sight focus's arrival. fn create_hook( sc: &mut Scene, guid: u64, @@ -1200,31 +1442,7 @@ fn create_hook( return; }; match kind { - Created::Item => { - // The record, set up at once when cached, for our item in the world, and its signal - // for the owner of any item. - let run = item_watch(&sc.index, &sc.stores, &sc.self_guid, &sc.items).created_run( - guid, - &fields, - &sc.bag_cache, - ); - // The set-up asks for the record of every item, whoever's, with the callback - // `0x5d8390` (`0x5d8300` into `0x55ba30`): the readers of a held item only read it. - if let Some(entry) = fields.object_entry() { - if sc - .items - .template(entry, guid, Ask::Event(&sc.net)) - .is_none() - { - sc.items - .wait(entry, crate::items::RecordCallback::SetUp(guid)); - } - } - if let Some(crate::item_watch::ItemNotice::Record { guid, .. }) = run.notice { - super::replay_enchant_times(&mut sc.items, &mut sc.countdowns, &sc.index, guid); - } - sc.item_lane.push(run); - } + Created::Item => request_item_record(sc, guid, &fields), Created::World(EntityKind::Player) => { // Our own create runs the world-enter cascade (`0x5deb60` → `0x4908c0`), whose bag // watcher set-up zeroes and rescans the bag cache (`0x49098d` → `0x4f8cc0`). @@ -1240,9 +1458,18 @@ fn create_hook( sc.bag_cache.seat(&fields, &lookup); } resolve_display_records(sc, guid, &fields); + // The unit's `PostInit` (`0x5dec09` → `0x5fb880`): its far-sight arrival, ahead of + // its tail (`0x60c520`, `0x606fe0`, `0x607710`, `0x5ff130`, `0x612a30`). + far_sight_arrives(sc, guid); sc.names.lookup_fields(guid, &fields, &sc.net); sc.field_notices .write_batch(crate::field_watch::guild_tag(guid)); + // Then the recruitment cascade (`0x5dec1e`), for our create alone (the deviation in + // `crate::ui_chat`'s recruitment). + if sc.self_guid.0 == Some(guid) { + sc.field_notices + .write(crate::field_watch::FieldNotice::RecruitmentCascade); + } // `0x5dec35` → `0x4e85d0` mode 1: a party slot's `PARTY_MEMBER_ENABLE`. sc.group.member_object(guid, true); if sc.self_guid.0 != Some(guid) { @@ -1254,6 +1481,18 @@ fn create_hook( Created::World(EntityKind::Unit) => { resolve_display_records(sc, guid, &fields); sc.names.lookup_fields(guid, &fields, &sc.net); + far_sight_arrives(sc, guid); + } + // `OnCreate` (`0x5d5420`): a far-sight focus (the bytes' low byte 2, `0x5d54a7`) that + // the active player cast (`0x5d54b6`) is the far-sight arrival's. + Created::World(EntityKind::DynamicObject) => { + let focus = fields.dynamicobject_bytes().is_some_and(|b| b & 0xff == 2); + let ours = fields + .dynamicobject_caster() + .is_some_and(|caster| sc.self_guid.0 == Some(caster)); + if focus && ours { + far_sight_arrives(sc, guid); + } } Created::World(EntityKind::GameObject) => { sc.go_templates.request_at_create(guid, &fields, &sc.net) @@ -1266,7 +1505,9 @@ fn create_hook( /// when its records changed while it was away (`0x5fbe28` → `0x60abe0`); a player's `PostUpdate` /// (`0x5dec90`) runs the unit's, then compares its party record (`0x5decb7`), with no /// active-player gate, as the active player is never released; a game object's (`0x5f7ed0`) asks -/// its template when it holds none (`+0x214`, `0x558560` at `0x5f7f31`). +/// its template when it holds none (`+0x214`, `0x558560` at `0x5f7f31`); an item's and a bag's +/// (`0x5d8430` → `0x5d8300`) request their record as their create did, set up at once when +/// cached ([`request_item_record`]). fn reactivated_end(sc: &mut Scene, guid: u64, script: Option<&UiScript>) { let Some(e) = sc.index.0.get(&guid).copied() else { return; @@ -1283,10 +1524,44 @@ fn reactivated_end(sc: &mut Scene, guid: u64, script: Option<&UiScript>) { compare_party_record(sc, guid, &fields, script); } Some(ObjectType::GameObject) => sc.go_templates.request_at_create(guid, &fields, &sc.net), + Some(ObjectType::Item | ObjectType::Container) => request_item_record(sc, guid, &fields), _ => {} } } +/// `CGItem_C::RequestRecord` (`0x5d8300`), an item's create hook (`0x5d8400`) and its slot 3 +/// (`EndReactivation 0x5d8430`): the record, set up at once when cached (`0x5d834a` → +/// `0x5d8440`), for our item in the world, and its signal for the owner of any item; a miss asks +/// for it with the callback `0x5d8390` (`0x5d833f` → `0x55ba30`), whoever's the item. The readers +/// of a held item only read it. +fn request_item_record(sc: &mut Scene, guid: u64, fields: &ObjectFields) { + let run = item_watch(&sc.index, &sc.stores, &sc.self_guid, &sc.items).created_run( + guid, + fields, + &sc.bag_cache, + ); + if let Some(entry) = fields.object_entry() { + if sc + .items + .template(entry, guid, Ask::Event(&sc.net)) + .is_none() + { + sc.items + .wait(entry, crate::items::RecordCallback::SetUp(guid)); + } + } + if let Some(crate::item_watch::ItemNotice::Record { guid, .. }) = run.notice { + super::replay_enchant_times( + &mut sc.items, + &mut sc.countdowns, + &sc.index, + &mut sc.view_log, + guid, + ); + } + sc.item_lane.push(run); +} + /// `CGUnit_C::ResolveDisplayRecords` from the unit's `PostInit` (`0x5fb88b` → `0x60afb0`): the /// records held off the display row ([`HeldDisplay`]); its creature ask is the create hook's /// ([`NameCache::lookup_fields`]). diff --git a/crates/benilla-app/src/net/reputations.rs b/crates/benilla-app/src/net/reputations.rs index b760b6a10..a42f011c8 100644 --- a/crates/benilla-app/src/net/reputations.rs +++ b/crates/benilla-app/src/net/reputations.rs @@ -11,7 +11,7 @@ //! answer on the call's next line. //! //! Each message's writes are logged with their stamp, and the reputation lane rewinds the store to -//! the frame's start and replays them packet by packet ([`log`]), so a listener's getters read +//! the span's start and replays them packet by packet ([`log`]), so a listener's getters read //! the standings its own packet left. use std::sync::atomic::{AtomicI32, AtomicU8, Ordering}; @@ -78,7 +78,7 @@ pub(crate) struct Reputations { slots: Arc, /// The forced table, shared as the slots are: the relation snapshot's reads see the replay. forced: Arc>>, - /// The frame's writes and the pane's list operations each message made, for the lane to replay + /// The span's writes and the pane's list operations each message made, for the lane to replay /// ([`log`]). log: ReputationLog, } @@ -115,6 +115,7 @@ impl Reputations { } /// Every slot's `(flags, standing)`, slot 0 first. + #[cfg(test)] pub(crate) fn slots(&self) -> impl Iterator + '_ { (0..FACTION_LIST_LEN).map(|i| self.slot(i)) } @@ -247,7 +248,7 @@ impl Reputations { None } - /// The drain's end, however it ended: the store as the frame left it. + /// The drain's end, however it ended: the store as the span left it. pub(crate) fn end_replay(&mut self) { for write in self.log.finish() { self.apply(write); @@ -286,10 +287,10 @@ impl Reputations { mod tests { use super::*; - /// The lane's replay: the store rewound to the frame's start, each write applied at its place - /// ahead of the operation stamped after it, and the frame's last state once it ends. + /// The lane's replay: the store rewound to the span's start, each write applied at its place + /// ahead of the operation stamped after it, and the span's last state once it ends. #[test] - fn the_replay_walks_the_frames_writes_between_its_operations() { + fn the_replay_walks_the_spans_writes_between_its_operations() { let mut store = Reputations::default(); store.set_standing(3, 100); store.list_op(ReputationListOp::Rebuild); @@ -306,7 +307,7 @@ mod tests { assert_eq!( (store.standing(3), store.flags(3)), (0, 0), - "the frame's start" + "the span's start" ); assert_eq!( store.replay(until).map(|(_, op)| op), @@ -330,7 +331,7 @@ mod tests { assert!(store.lane_head().is_none()); } - /// A drain that stops early leaves the store as the frame wrote it, and its operations for the + /// A drain that stops early leaves the store as the span wrote it, and its operations for the /// next drain; a verb's write during the replay lands in place and is not logged. #[test] fn a_drain_that_stops_early_leaves_the_final_store_and_a_verbs_write_stands() { @@ -390,7 +391,7 @@ mod tests { let clone = store.clone(); assert_eq!(clone.forced_rank(72), Some(7)); assert!(store.rewind()); - assert_eq!(clone.forced_rank(72), None, "the frame's start"); + assert_eq!(clone.forced_rank(72), None, "the span's start"); store.replay(Until::all()); assert_eq!(clone.forced_rank(72), Some(7)); store.end_replay(); diff --git a/crates/benilla-app/src/net/reputations/log.rs b/crates/benilla-app/src/net/reputations/log.rs index dfb954805..b4b677c09 100644 --- a/crates/benilla-app/src/net/reputations/log.rs +++ b/crates/benilla-app/src/net/reputations/log.rs @@ -1,12 +1,12 @@ //! The reputation store as each packet left it. In the reference each reputation message's handler //! writes the slots, edits the pane's list and signals `UPDATE_FACTION` inside itself (`0x4d56f6`, //! `0x4d5699`, `0x4d5984`), and the getters read the slots at their calls (`0x4d65ac`, `0x4d65ea`), so a -//! listener reads its own packet's standings. Here every handler of the frame writes the store -//! before any listener runs, so each write is logged with its stamp, as is each list operation -//! the message made ([`ReputationListOp`]); the lane (`ui_reputation`) rewinds the store to the -//! frame's start and replays the log in stamp order among the other lanes, applying each list -//! operation at its place. A write made during the drain, a verb's flag write, lands at its own -//! place and is not logged. +//! listener reads its own packet's standings. Here the lanes fire once a packet's handlers are +//! done, over the span of packets since they last fired, so each write is logged with its stamp, +//! as is each list operation the message made ([`ReputationListOp`]); the lane (`ui_reputation`) +//! rewinds the store to the span's start and replays the log in stamp order among the other lanes, +//! applying each list operation at its place. A write made during the drain, a verb's flag write, +//! lands at its own place and is not logged. use std::collections::VecDeque; @@ -42,7 +42,7 @@ enum Entry { Op(ReputationListOp), } -/// The store's log of the frame's writes and list operations. +/// The store's log of the span's writes and list operations. #[derive(Default)] pub(super) struct ReputationLog { /// The tables before the log's first write. @@ -120,7 +120,7 @@ impl ReputationLog { } /// The drain's end, however it ended: the writes it did not replay, for the caller to apply, - /// so the store stands as the frame left it; its operations wait for the next drain, as every + /// so the store stands as the span left it; its operations wait for the next drain, as every /// lane's unfired items do, and the next write opens a new log. pub(super) fn finish(&mut self) -> Vec { if !self.replaying { diff --git a/crates/benilla-app/src/net/session.rs b/crates/benilla-app/src/net/session.rs index 6597fc8c7..39b3c6499 100644 --- a/crates/benilla-app/src/net/session.rs +++ b/crates/benilla-app/src/net/session.rs @@ -29,6 +29,27 @@ use benilla_world::frame_pace::FrameStep; /// Registers the session handlers. pub(super) fn register(app: &mut App) { use SessionEventKind as K; + // The posted world load's legs run at the frame's start in the executor's order, after a + // `/reload` the last frame asked for, which the reference ran inside its call. + app.init_resource::() + .configure_sets( + PreUpdate, + ( + WorldportTimer::Connection.after(crate::ui_script::run_pending_reload), + WorldportTimer::Sweep, + WorldportTimer::Objects, + WorldportTimer::Cooldowns, + WorldportTimer::Manager, + WorldportTimer::Rolls, + ) + .chain(), + ) + .add_systems( + PreUpdate, + world_load_timer + .in_set(WorldportTimer::Objects) + .run_if(|pending: Res| pending.is_posted()), + ); app.net_handler(K::LoginStage, on_login_edge) .net_handler(K::WorldAuthenticated, on_login_edge) .net_handler(K::RosterFailed, on_login_edge) @@ -70,7 +91,6 @@ pub(super) fn register(app: &mut App) { #[derive(SystemParam)] pub(crate) struct Edges<'w> { teleports: MessageWriter<'w, TeleportMessage>, - worldports: MessageWriter<'w, WorldportMessage>, char_lists: MessageWriter<'w, CharListMessage>, realm_lists: MessageWriter<'w, RealmListMessage>, char_actions: MessageWriter<'w, CharActionResultMessage>, @@ -111,9 +131,35 @@ pub(crate) struct Bridge<'w, 's> { dropped: ResMut<'w, DroppedOpcodes>, net: Res<'w, NetCommands>, stores: Query<'w, 's, &'static mut ObjectStore>, + /// The item countdown cells a teardown takes with their items, for the views' log. + countdowns: Query<'w, 's, &'static crate::items::Countdowns>, transports: Query<'w, 's, &'static crate::transport::Transport>, /// The active mover, which the world entry zeroes and the teardowns free with its unit. mover: Option>, + /// Our player's far-sight latch, which the teardowns free with it. + far_sight: Option>, + /// The item lane, where the teardowns' free takes every item's lock with its object. + item_lane: Option>, +} + +impl Bridge<'_, '_> { + /// Every object freed (`0x467700` → `0x467800`), our own player too: the active mover it + /// names is zeroed unless its unit is still held (`0x5fb650`), its far-sight latch goes + /// with it ([`crate::player::FarSight::free`]), and every item's lock with its item + /// ([`crate::item_watch::Freed::All`]). + fn objects_freed(&mut self) { + if let Some(mover) = self.mover.as_deref_mut() { + mover.forget_unless_held(&self.index); + } + if let Some(far_sight) = self.far_sight.as_deref() { + far_sight.free(); + } + if let Some(lane) = self.item_lane.as_deref_mut() { + lane.push(crate::item_watch::Run::freeing( + crate::item_watch::Freed::All, + )); + } + } } fn on_login_edge(In(ev): In, mut e: Edges) { @@ -229,9 +275,7 @@ fn on_logged_out( ); // The teardown destroys every object (`0x402011` → `0x467700`), the mover's unit with it // (`0x5fb650`). - if let Some(mover) = b.mover.as_deref_mut() { - mover.forget_unless_held(&b.index); - } + b.objects_freed(); // The reference zeroes the forced table's count and the 64 slots only in teardown // `0x4d5360` (`0x4d5419`, `0x4d541f`), whose one caller is `ShutdownGame 0x491180` // (`0x4911dc`), never on a worldport. The session's end stands in for that shutdown: the @@ -301,53 +345,92 @@ fn on_disconnected( &mut e.transfer, &mut e.disconnects, ); - if let Some(mover) = b.mover.as_deref_mut() { - mover.forget_unless_held(&b.index); - } + b.objects_freed(); } } -/// The world left at once: the stores the teardown takes, logged for the views a listener reads +/// The world left at once: the stores and countdown cells the teardown takes, logged for the views a listener reads /// ([`crate::ui_unit::views::ViewLog::torn_down`]). fn log_teardown(view_log: Option>, b: &Bridge) { if let Some(mut log) = view_log { - log.torn_down(&b.index, |e| b.stores.get(e).ok()); + log.torn_down( + &b.index, + |e| b.stores.get(e).ok(), + |e| b.countdowns.get(e).ok(), + ); } } -/// Teleport, knockback and client control, forwarded unjudged to the controller, which applies -/// and answers them. -fn on_mover_edge(In(ev): In, mut e: Edges, b: Bridge) { +/// Teleport and knockback, forwarded unjudged to the controller, which applies and answers them. +/// A near teleport runs the movement guard first inside the packet (`OnForcedTeleport 0x602fb0` +/// → `0x60e990(1, 0)` at `0x60300e`, [`MoveInput`]), before the move is queued (`0x603029`); the +/// echo's own stop (`0x60e3b1`) finds none left. +fn on_mover_edge( + In(ev): In, + mut e: Edges, + self_guid: Res, + mut moved: MoveInput, +) { match ev { SessionEvent::Teleport { guid, counter, position, orientation, - } => teleport( - guid, - counter, - position, - orientation, - &b.self_guid, - &mut e.teleports, - ), + } => { + moved.stop(guid, self_guid.0); + teleport( + guid, + counter, + position, + orientation, + &self_guid, + &mut e.teleports, + ); + } + // `QueueKnockBack 0x602670` runs the same guard first (`0x60267e`), ahead of the queue + // (`0x617a30`). SessionEvent::KnockBack { guid, counter, launch, - } => knock_back(guid, counter, launch, &b.self_guid, &mut e.knockbacks), + } => { + moved.stop(guid, self_guid.0); + knock_back(guid, counter, launch, &self_guid, &mut e.knockbacks); + } _ => {} } } +/// The movement guard `CGUnit_C::OnMoveInput(1, 0)` (`0x60e990`) where a forced move's handler runs +/// it on its unit: the active mover's auto-move stops (`0x60e99d`-`0x60e9b5`), the follow's +/// `AUTOFOLLOW_END` on the notice lane, then the active player's loot window closes as on a +/// movement start (`0x60e9c1`-`0x60e9dd`). +#[derive(bevy::ecs::system::SystemParam)] +struct MoveInput<'w, 's> { + auto_move: crate::player::AutoMoveStop<'w>, + lane: Option>, + loot: crate::ui_loot::MoveStartClose<'w, 's>, +} + +impl MoveInput<'_, '_> { + fn stop(&mut self, guid: u64, me: Option) { + self.auto_move.stop(guid, self.lane.as_deref_mut()); + if me == Some(guid) { + self.loot.close(); + } + } +} + /// What [`on_client_control`] holds beside the host: the cast its fall cancels, our guid, the flag, -/// and the notice lane its signals go on (absent in a harness without the unit feed). +/// the notice lane its signals go on (absent in a harness without the unit feed), and the +/// outgoing mover's auto-move. type ControlSet = ( crate::spell::SelfCancel<'static>, Res<'static, SelfGuid>, ResMut<'static, crate::player::OwnControlLost>, Option>, + crate::player::AutoMoveStop<'static>, ); /// `SMSG_CLIENT_CONTROL_UPDATE` (`0x5fa6b1` → `SetPlayerControl 0x4958e0`), its movement judged by @@ -355,20 +438,38 @@ type ControlSet = ( /// (`0x4958ea`); its fall drops the cursor's payload and the cast (`0x4958e8`-`0x495901` → /// `0x495920`), and the change signals on the notice lane at this packet's place, then runs the /// usable refresh (`0x4958f7`/`0x49590b`, `0x4958fc`/`0x495910`). A store that changes nothing does -/// nothing (`0x4958e6`). +/// nothing (`0x4958e6`). Ahead of it the unit's control moves the active mover (`0x5fa600`): a +/// grant claims the unit (`0x5fa696`) and a stop of the mover zeroes it (`0x5fa678`-`0x5fa696`), +/// and the switch ends the outgoing mover's auto-move first (`SetActiveMover`, `0x600731`- +/// `0x600742`), its `AUTOFOLLOW_END` on the notice lane ahead of the flag's signal. fn on_client_control( In(ev): In, mut e: Edges, // The flag and our guid are the host's too, so they sit in the set it shares with the cast. mut vm: crate::script_calls::VmWith, + // The unit whose `IsClientControlled` bit the update writes. + mut units: (Option>, Commands), ) { let SessionEvent::ClientControl { mover, allow_move } = ev else { return; }; e.client_control .write(ClientControlMessage { mover, allow_move }); + // `0x5fa62a`/`0x5fa631`: the unit's own bit first (`0x5fa636`). + if let Some(&unit) = units.0.as_deref().and_then(|i| i.0.get(&mover)) { + let mut unit = units.1.entity(unit); + if allow_move { + unit.insert(super::ClientControlled); + } else { + unit.remove::(); + } + } { - let (_, self_guid, mut own, _) = vm.own(); + let (_, self_guid, mut own, mut lane, mut stop) = vm.own(); + let switches = stop.mover().is_some_and(|m| (m == mover) != allow_move); + if switches { + stop.stop_mover(lane.as_deref_mut()); + } if self_guid.0 != Some(mover) || own.0 == !allow_move { return; } @@ -377,7 +478,7 @@ fn on_client_control( if !allow_move { crate::spell::drop_hold(&mut vm, |(mut cancel, ..)| cancel.abort_cast()); } - if let (.., Some(mut lane)) = vm.own() { + if let (_, _, _, Some(mut lane), _) = vm.own() { use crate::field_watch::FieldNotice; lane.write(FieldNotice::PlayerControl { in_control: allow_move, @@ -386,48 +487,144 @@ fn on_client_control( } } -fn on_worldport( - In(ev): In, - mut e: Edges, - mut b: Bridge, - mut group: ResMut, - script: Option>, - mut released: ResMut, - view_log: Option>, - player: Option>, - selection: Option>, - place: crate::ui_party::net::SnapshotPlace, - transforms: Query<&Transform>, -) { - if let SessionEvent::Worldport { - map_id, - position, - orientation, - needs_ack, - } = ev - { +/// A `SMSG_NEW_WORLD`'s destination, held for its timer. +#[derive(Clone, Copy, Debug)] +struct Destination { + map_id: u32, + position: [f32; 3], + orientation: f32, +} + +/// The world loads posted and not yet run: `SMSG_NEW_WORLD` (`0x401b00`) reads its destination +/// into globals and posts the executor `0x401bc0` as a timer at no delay (`0x401ba5`-`0x401bae`), +/// which the next tick runs ahead of its packets (`0x420d0c`, `0x420d55`). Beside them, the maps +/// whose objects' leg has run, each owed its new object manager (`0x401c22`). +#[derive(Resource, Default)] +pub(crate) struct PendingWorldports { + posted: Vec, + /// How many loads the objects' leg has run, which the legs after it test ([`world_ported`]). + ported: u32, + /// The maps of the loads whose objects' leg has run, owed their new manager. + loaded: Vec, +} + +impl PendingWorldports { + /// Whether a timer is posted, for the connection's leave to run only then. + pub(crate) fn is_posted(&self) -> bool { + !self.posted.is_empty() + } + + /// Whether a load's objects are gone and its new manager not yet made, for the manager's leg + /// ([`WorldportTimer::Manager`]) to run only then. + pub(crate) fn has_loaded(&self) -> bool { + !self.loaded.is_empty() + } + + /// The maps of the loads whose objects are gone, in their order, taken by the manager's leg. + pub(crate) fn take_loaded(&mut self) -> Vec { + std::mem::take(&mut self.loaded) + } + + /// A load posted, as `SMSG_NEW_WORLD` posts it, for a harness with no objects' leg. + #[cfg(test)] + pub(crate) fn post_for_test(&mut self) { + self.posted.push(Destination { + map_id: 1, + position: [0.0; 3], + orientation: 0.0, + }); + } + + /// The posted loads taken, as the objects' leg takes them. + #[cfg(test)] + pub(crate) fn take_for_test(&mut self) { + self.posted.clear(); + } +} + +/// The executor `0x401bc0`'s body, one unit at the next tick's start, in the order of its calls: +/// the connection leaves the world (`0x401bd4` → `0x5aae70(0)`, `LOGOUT_CANCEL` for a pending +/// request), then the movement and missiles go (`0x401bde`, `0x401bf2`), then the object manager +/// is destroyed (`0x401bf7`), whose walk (`0x467800`) frees the objects in creation order and +/// reaches the local player's destructor and its leave-world sweep (`0x5dd543`) at the player's +/// turn; then the cooldowns are freed (`0x401c17`), the new object manager made (`0x401c22`) and +/// the open loot rolls cancelled (`0x401c2c`), ahead of the map load. The sets order those legs in `PreUpdate`. +/// +/// The sweep runs ahead of the objects' leg, so what was created after the player (the target, a +/// pet, an NPC) is alive when `PLAYER_LEAVING_WORLD` fires, as in the reference. What remains: the +/// objects created before the player (its items, say) are gone by then in the reference, and +/// benilla keeps no creation order, so they are alive there too. +#[derive(SystemSet, Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub(crate) enum WorldportTimer { + /// `0x401bd4`: `crate::ui_logout::leave_world`. + Connection, + /// `0x5dd543`: `crate::ui_script::sweep_on_worldport`, for a load posted. + Sweep, + /// `0x401bf7`'s walk of the objects: [`world_load_timer`]. + Objects, + /// `0x401c17`: `ClearItemAndSpellCooldowns`, for a load the objects' leg ran. + Cooldowns, + /// `0x401c22`: the new object manager for the map loaded (`ClntObjMgrCreate` `0x464ff0`), whose + /// map-change latch (`0x46500e`) is `crate::ui_instance`'s, for each map the objects' leg ran + /// ([`PendingWorldports::take_loaded`]). + Manager, + /// `0x401c2c`: `CancelAllLootRolls`, for a load the objects' leg ran; the map load + /// (`0x401c5c`) follows. + Rolls, +} + +/// What the world load needs from the bridge. +#[derive(SystemParam)] +pub(crate) struct WorldLoad<'w, 's> { + transfer: ResMut<'w, PendingTransfer>, + worldports: MessageWriter<'w, WorldportMessage>, + b: Bridge<'w, 's>, + group: ResMut<'w, crate::ui_party::GroupState>, + script: Option>, + released: ResMut<'w, super::objects::Released>, + view_log: Option>, + player: Option>, + selection: Option>, + place: crate::ui_party::net::SnapshotPlace<'w, 's>, + transforms: Query<'w, 's, &'static Transform>, +} + +impl WorldLoad<'_, '_> { + /// The objects' destruction (`0x467700` → `0x467800`) and the destination handed to the app. + fn objects_destroyed(&mut self, dest: Destination, needs_ack: bool) { + let Destination { + map_id, + position, + orientation, + } = dest; + let b = &mut self.b; // Every streamed roster member is about to be freed, and each one's destructor runs the // roster hook (`0x5dd6a0` → `0x4e85d0` mode 0). - let before = view_log.as_ref().map(|_| group.stats.clone()); + let before = self.view_log.as_ref().map(|_| self.group.stats.clone()); crate::ui_party::net::roster_deactivated( - &mut group, + &mut self.group, &b.index, &b.stores, - &place, - &|e| transforms.get(e).ok().copied(), + &self.place, + &|e| self.transforms.get(e).ok().copied(), &b.names, - script.as_deref(), + self.script.as_deref(), &b.net, ); - let mut view_log = view_log; - if let (Some(log), Some(before)) = (view_log.as_deref_mut(), before) { - log.records(&before, &group.stats); + if let (Some(log), Some(before)) = (self.view_log.as_deref_mut(), before) { + log.records(&before, &self.group.stats); + } + if let Some(log) = self.view_log.as_deref_mut() { + log.torn_down( + &b.index, + |e| b.stores.get(e).ok(), + |e| b.countdowns.get(e).ok(), + ); } - log_teardown(view_log, &b); // The transfer frees every object with no release (`0x467700` → `0x467800`): the selection // keeps its guid, its object gone, until the arrival's `SelectTarget(0)` (`0x490927`) // clears it (the unit feed's world-enter turn). - if let Some(mut selection) = selection { + if let Some(selection) = self.selection.as_deref_mut() { selection.target = None; selection.lit = None; } @@ -438,21 +635,74 @@ fn on_worldport( needs_ack, &mut b.commands, &mut b.index, - &mut e.transfer, + &mut self.transfer, &b.transports, - player.as_ref().and_then(|p| p.ride_entity()), - &mut e.worldports, + self.player.as_ref().and_then(|p| p.ride_entity()), + &mut self.worldports, ); // The world load destroys every object (`0x401bf7` → `0x467700` → `0x467800`), our own // player too, whose destructor zeroes the active mover it names (`0x5fb650`). - if let Some(mover) = b.mover.as_deref_mut() { - mover.forget_unless_held(&b.index); - } + b.objects_freed(); // Loading a new world frees the released objects with the live ones (`0x467700`). - released.clear(); + self.released.clear(); } } +/// `SMSG_NEW_WORLD` (`0x401b00`) only posts the load: its body runs as a timer at the next tick's +/// start ([`WorldportTimer`], [`world_load_timer`]), so what the port's own tick raised still sees +/// the old world and an open logout request. `SMSG_LOGIN_VERIFY_WORLD` for another map +/// (`0x401de0` → `0x401ea4`) calls the executor in place, with no ack owed. +fn on_worldport( + In(ev): In, + mut pending: ResMut, + mut load: WorldLoad, +) { + if let SessionEvent::Worldport { + map_id, + position, + orientation, + needs_ack, + } = ev + { + let dest = Destination { + map_id, + position, + orientation, + }; + if needs_ack { + pending.posted.push(dest); + } else { + load.objects_destroyed(dest, false); + } + } +} + +/// The posted world loads' objects leg once, for a test that dispatches a port and reads what the +/// timer does. +#[cfg(test)] +pub(crate) fn fire_worldport_timer(world: &mut World) { + use bevy::ecs::system::RunSystemOnce; + world + .run_system_once(world_load_timer) + .expect("the world load runs"); + world.flush(); +} + +/// The posted world loads' objects leg, at the frame's start ([`WorldportTimer::Objects`]). +fn world_load_timer(mut pending: ResMut, mut load: WorldLoad) { + for dest in std::mem::take(&mut pending.posted) { + pending.loaded.push(dest.map_id); + load.objects_destroyed(dest, true); + pending.ported = pending.ported.wrapping_add(1); + } +} + +/// Whether the objects' leg ran a load since this condition last looked, for the legs after it: +/// the leg takes the posted loads, so [`PendingWorldports::is_posted`] is spent by then. +pub(crate) fn world_ported(pending: Res, mut seen: Local) -> bool { + std::mem::replace(&mut *seen, pending.ported) != pending.ported +} + /// The handler `0x401900` reaches `0x495920` on both of its arms (`0x40194c`), ahead of the /// loading screen: the cursor's payload and the cast are dropped. fn on_transfer_pending( @@ -1461,7 +1711,7 @@ mod worldport_tests { needs_ack: true, }], ); - world.flush(); + fire_worldport_timer(world); let alive = |world: &World, guid: u64, e: Entity| { world.resource::().0.contains_key(&guid) && world.get_entity(e).is_ok() }; @@ -1501,7 +1751,7 @@ mod worldport_tests { needs_ack: true, }], ); - world.flush(); + fire_worldport_timer(world); let fresh = std::time::Instant::now(); let create = SessionEvent::ObjectCreate { guid: RIDDEN, diff --git a/crates/benilla-app/src/net/world.rs b/crates/benilla-app/src/net/world.rs index a766abc0f..37ef1278d 100644 --- a/crates/benilla-app/src/net/world.rs +++ b/crates/benilla-app/src/net/world.rs @@ -41,7 +41,7 @@ fn on_world_states( // The handler's tail signals the map, then the readout (`0x48f9f6`-`0x48fa17`), for an // init and an update alike. if let Some(mut lane) = lane { - lane.push(crate::world_state::WorldStateSignal::Packet); + lane.push(); } } } diff --git a/crates/benilla-app/src/npc_text.rs b/crates/benilla-app/src/npc_text.rs index 65f1ea3ee..f415fee6e 100644 --- a/crates/benilla-app/src/npc_text.rs +++ b/crates/benilla-app/src/npc_text.rs @@ -197,8 +197,19 @@ pub(crate) fn player_identity( unit_names: UnitNames<'_>, ) -> Option { let (store, guid) = self_q.iter().next()?; + player_subject(guid.0, store, names, unit_names) +} + +/// The self player `guid` as a macro [`Subject`] off `store`, its descriptor as the caller reads +/// it, once its name is known. +pub(crate) fn player_subject( + guid: u64, + store: &ObjectStore, + names: &NameCache, + unit_names: UnitNames<'_>, +) -> Option { Some(Subject { - name: names.resolve_player(guid.0, Ask::Read)?.to_string(), + name: names.resolve_player(guid, Ask::Read)?.to_string(), race: race_word(unit_names, store.0.unit_race().unwrap_or(0)), class: class_word(unit_names, store.0.unit_class().unwrap_or(0)), gender: store.0.unit_gender().unwrap_or(0), diff --git a/crates/benilla-app/src/perf/journal.rs b/crates/benilla-app/src/perf/journal.rs index e99b81817..129959717 100644 --- a/crates/benilla-app/src/perf/journal.rs +++ b/crates/benilla-app/src/perf/journal.rs @@ -61,7 +61,10 @@ const JOURNAL_HEADER: &str = "t,x,y,z,mean_ms,p95_ms,streamed,entities,cpu_ms,ma gpu_other\n"; /// The `fpsJournal` change callback: a flag, int-parsed and `!= 0`. -pub(crate) fn on_cvar(ev: On, mut journal: ResMut) { +pub(crate) fn on_cvar( + ev: &crate::cvars::CvarChanged, + mut journal: bevy::prelude::Mut<'_, FpsJournalSetting>, +) { if ev.is("fpsJournal") { journal.0 = ev.flag(); } @@ -75,7 +78,6 @@ impl Plugin for FpsJournalPlugin { // zones, registered in every build. app.add_plugins(RenderDiagnosticsPlugin) .init_resource::() - .add_observer(on_cvar) .insert_resource(FpsJournal { env_path: std::env::var("WOW_FPS_JOURNAL") .ok() diff --git a/crates/benilla-app/src/perf/mod.rs b/crates/benilla-app/src/perf/mod.rs index 6f9bfb58b..d70a02c7d 100644 --- a/crates/benilla-app/src/perf/mod.rs +++ b/crates/benilla-app/src/perf/mod.rs @@ -57,7 +57,6 @@ pub(crate) use gpu::{GpuMsShared, WgpuCensusShared}; pub(crate) use hud::PerfHud; pub(crate) use journal::FpsJournalPlugin; pub use journal::FpsJournalTags; -#[cfg(test)] pub(crate) use journal::{on_cvar, FpsJournalSetting}; #[cfg(feature = "dev")] pub(crate) use main_split::MainThreadSplit; diff --git a/crates/benilla-app/src/player.rs b/crates/benilla-app/src/player.rs index ce64fa678..d03b62980 100644 --- a/crates/benilla-app/src/player.rs +++ b/crates/benilla-app/src/player.rs @@ -95,21 +95,31 @@ use controller::control; pub(crate) use controller::LookSample; // The private camera and `state` items are re-imported for the modules beside this one, which // name them `super::X`. -pub(crate) use camera::{head_height, CameraControl, CameraPivot, LookConfig, PressGesture}; +pub(crate) use camera::{ + head_height, CameraControl, CameraPivot, LookConfig, LookLive, LookSteps, Looked, PressGesture, +}; use camera::{model_pivot_height, run_look_session, FlyCam, LookButton}; -use camera_zoom::{apply_zoom_scroll, CAM_DIST_DEFAULT}; +use camera_zoom::{glide_zoom, CAM_DIST_DEFAULT}; // `/follow`: chat sends the request, `crate::target` resolves the subject into the state, and // `follow` owns the motion. +#[cfg(test)] +pub(crate) use follow::release_owed_for_test; pub(crate) use follow::{FollowRequest, FollowState}; // Click to Move: `crate::target`'s dispatchers start it and run the verb it owes on arrival. -#[cfg(test)] pub(crate) use approach::on_cvar as approach_on_cvar; pub(crate) use approach::{ - can_auto_interact, cancel_move_action_on_ui_shutdown, Approach, ApproachVerb, AutoMove, - Refused, Subject, RANGE_STOP_FRACTION, TALK_STOP, + can_auto_interact, cancel_move_action_on_ui_shutdown, end_auto_move, stop_auto_move, Approach, + ApproachVerb, AutoMove, AutoMoveStop, Refused, Subject, RANGE_STOP_FRACTION, TALK_STOP, }; /// `SetStandState` run inside a script call. -pub(crate) use posture::{stand_up_for_attack, stand_up_refused, StandSetter}; +pub(crate) use posture::{stand_up_for_attack, stand_up_refused, SheathToggle, StandSetter}; +pub(crate) use press::{CallAutorun, Called, CommandSteps, TickLegs}; +pub(crate) use state::{ + view_is_out, MoverInput, MoverLock, OwnControlLost, Player, PlayerCapsule, StandPending, + CAPSULE_HEIGHT, CAPSULE_RADIUS, CREATURE_STEP_UP_HEIGHT, DEFAULT_COLLISION_HEIGHT, + FEATHER_TERMINAL_VELOCITY, GRAVITY, HOVER_CLIMB_RATE, HOVER_HEIGHT, SETTLE_TIMEOUT, + STEP_UP_HEIGHT, TERMINAL_VELOCITY, +}; 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, @@ -117,11 +127,6 @@ use state::{ TURN_RATE_MOVING, WALK_RATIO, WATER_WALK_PITCH_FLOOR, WEDGE_MIN_FALL, WEDGE_STALL_RATIO, WEDGE_STILL_FRAMES, }; -pub(crate) use state::{ - MoverLock, OwnControlLost, Player, PlayerCapsule, StandPending, CAPSULE_HEIGHT, CAPSULE_RADIUS, - CREATURE_STEP_UP_HEIGHT, DEFAULT_COLLISION_HEIGHT, FEATHER_TERMINAL_VELOCITY, GRAVITY, - HOVER_CLIMB_RATE, HOVER_HEIGHT, SETTLE_TIMEOUT, STEP_UP_HEIGHT, TERMINAL_VELOCITY, -}; /// The swim boundary `0.75·h`, also the wade ceiling, for the creature swim marker and the /// footstep splash, which have no `Player`. pub(crate) use swim::{may_swim, swim_enter_depth}; @@ -326,14 +331,14 @@ impl Plugin for PlayerPlugin { .after(WorldFocusSet) .in_set(crate::vm_pass::VmPass::Member), ); - app.add_observer(camera::on_cvar); - app.add_observer(camera_dynamics::on_cvar); app.init_resource::(); app.init_resource::(); app.init_resource::(); app.init_resource::(); 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. @@ -470,6 +475,7 @@ impl Plugin for PlayerPlugin { Update, ( controller::sample_look, + camera::focus_on_look_edges, press::press_commands, press::press_tick, ) diff --git a/crates/benilla-app/src/player/approach.rs b/crates/benilla-app/src/player/approach.rs index eb92c4bf3..3105ef4f2 100644 --- a/crates/benilla-app/src/player/approach.rs +++ b/crates/benilla-app/src/player/approach.rs @@ -1,11 +1,12 @@ //! Click to Move's walks (`AutoInteract`, "Toggles auto-move to interact target"). With the option //! on, a right-click on an NPC, a body to loot or skin, or a GameObject beyond the verb's reach //! walks the player there and the verb runs on arrival; a right-click on the ground walks to the -//! point (mode 4), one on the sky walks that way until stopped (mode 8), and an attack on an enemy +//! point (mode 4, the click-to-move walk), one on the sky walks that way until stopped (mode 8), and an attack on an enemy //! out of melee walks to where it stood (mode 10). It is [`super::follow`]'s auto-move: one cell //! holds either (mode `0xc4d888`, guid `0xc4d980`), so arming one ends the other (`0x611130` calls //! the canceller `0x60fb60` first), the same input cancels both, and nothing goes on the wire but -//! the movement; an attack on an enemy already in melee only turns to face it (mode 2). +//! the movement; an attack on an enemy already in melee only turns to face it (mode 2, the facing +//! turn). use std::f32::consts::{FRAC_PI_2, PI}; @@ -77,6 +78,9 @@ pub(crate) struct Approach { goal: Option, /// The pending cells `0x60f940` fills (`0xc4da28`, `0xc4da78`, `0xc4d950`, `0xc4da20`). pub(crate) arrived: Option<(ApproachVerb, u64)>, + /// A walk's arm ended a follow, whose `AUTOFOLLOW_END` (`0x611130` → `0x60fb84`) the + /// dispatcher that armed it signals as it returns ([`AutoMove::signal_follow_end`]). + owes_follow_end: bool, } /// What a walk heads for, by its mode in `0xc4d888`. @@ -84,14 +88,14 @@ pub(crate) struct Approach { enum Toward { /// Modes 5-7 and 9: the object's live position. Object { verb: ApproachVerb, guid: u64 }, - /// Mode 4. - Ground(Anchor), + /// Mode 4, the click-to-move walk: a right-click on the ground (`0x6102b0`). + ClickToMove(Anchor), /// Mode 10. Melee(Anchor), /// Mode 8: a facing (`0xc4d9a8`), with no stop. Sky(f32), - /// Mode 2: a facing, turned to and done. - Face(f32), + /// Mode 2, the facing turn: an attack on an enemy in melee turns to it and is done (`0x6100a0`). + FacingTurn(f32), } /// A point fixed at the arm (`0xc4d890`), held in the frame of the transport the player stands on @@ -154,15 +158,14 @@ impl Approach { self.goal.as_ref().map(|g| g.stop) } - #[cfg(test)] - pub(crate) fn facing(&self) -> bool { + /// Mode 2, the facing turn (`0x6100a0`). + pub(crate) fn facing_turn(&self) -> bool { self.goal .as_ref() - .is_some_and(|g| matches!(g.toward, Toward::Face(_))) + .is_some_and(|g| matches!(g.toward, Toward::FacingTurn(_))) } } -/// `CanAutoInteract` (`0x60f900`): alive, driving our own body, and the option on. /// The canceller `0x60fb60(0, 1)` as the UI shutdown's `/reload` guard calls it (`0x490c1b`): a /// follow or a walk in flight ends and the mover stops (`0x60fc05`-`0x60fc18`, the mode reset /// `0x60fc30`). `true` when it ended a follow, mode 3, which owes `AUTOFOLLOW_END` (`0x60fb84`). @@ -174,6 +177,133 @@ pub(crate) fn cancel_move_action_on_ui_shutdown( follow.stop() } +/// The canceller `CGUnit_C::StopAutoMove` (`0x60fb60`) where a packet's handler calls it on a unit: +/// the taxi flag's rise (`0x5ff55a`), a death (`0x605938`), our own swing's report (`0x625a21`), +/// a mover switch (`0x600742`), the mover's release (`0x5fbc3b` → `0x6006c2`) and a near +/// teleport (`0x60300e` → `0x60e9b5`). It acts only on the active mover with an auto-move in +/// flight (`IsAutoMoving 0x6103a0`, the early-out `0x60fb70`); past that it is [`end_auto_move`]. +/// The handlers whose scene holds the mover's claim call that directly. +#[derive(SystemParam)] +pub(crate) struct AutoMoveStop<'w> { + /// The active mover `0xc4da98`. Each absent in a harness without the mover's state, which + /// stops nothing. + claim: Option>, + follow: Option>, + approach: Option>, + autorun: Option>, +} + +impl AutoMoveStop<'_> { + /// `StopAutoMove` on `guid`, a no-op unless `guid` is the active mover; `true` if it ended an + /// auto-move. + pub(crate) fn stop( + &mut self, + guid: u64, + lane: Option<&mut crate::field_watch::NoticeLane>, + ) -> bool { + self.claim.as_deref().is_some_and(|c| c.holds(guid)) && self.end(lane) + } + + /// [`Self::stop`] unless the auto-move is mode 2, the facing turn: the swing report's gate + /// `IsAutoMovingInModes` with the mode mask 4, bit 2 (`0x625a0e`-`0x625a19`). + pub(crate) fn stop_unless_facing_turn( + &mut self, + guid: u64, + lane: Option<&mut crate::field_watch::NoticeLane>, + ) -> bool { + let facing = self.approach.as_deref().is_some_and(Approach::facing_turn); + !facing && self.stop(guid, lane) + } + + /// The active mover `0xc4da98`. + pub(crate) fn mover(&self) -> Option { + self.claim.as_deref().and_then(crate::net::MoverClaim::get) + } + + /// `StopAutoMove` on the active mover, whoever it is: a mover switch's stop of the outgoing one + /// (`0x600731`-`0x600742`); `None` names no mover, which stops nothing. + pub(crate) fn stop_mover(&mut self, lane: Option<&mut crate::field_watch::NoticeLane>) -> bool { + self.mover().is_some() && self.end(lane) + } + + fn end(&mut self, lane: Option<&mut crate::field_watch::NoticeLane>) -> bool { + end_auto_move( + self.follow.as_deref_mut(), + self.approach.as_deref_mut(), + self.autorun.as_deref_mut(), + lane, + ) + } +} + +/// The canceller past its gate (`0x60fb76` on), with its release: a follow signals +/// `AUTOFOLLOW_END` first, on the notice lane at the caller's place ([`super::follow::end`]), and +/// the mode returns to 12 (`0x60fc30`), so a walk ends too; `true` if either ended. +/// +/// The release lets go of the move, turn and pitch commands (`0x60fc05`-`0x60fc18`). For modes 3 +/// to 10, whose row's first byte is set (`0x860a58`, filled at `0x60e5b2`-`0x60e65c`), the forward +/// release `0x60e7f0` queues a move stop (`MoveStop 0x60dc90`) and clears autorun (`0x514630`) +/// while the input owns the mover (`0x5144e0`), and where it fails (a death, far sight, a server +/// spline) the tick clears autorun itself (`0x514748`), after the signal either way. Here a +/// follow's clear runs on the notice lane right behind its `AUTOFOLLOW_END`, a walk's in place +/// ([`super::press::CallAutorun::clear`]), so a call after the stop reads the bit clear, and the +/// frame's steer applies it ([`FollowState::owe_release`]) ahead of the controller, whose step +/// sends the stop, as the reference's mover update sends the one it queued. The `face` leg (`0x60fb92`-`0x60fbe8`) turns no unit: it keeps the target's +/// heading at `0xc4d8c4` for the camera (`0x60e8f0`; its readers `0x510904` and `0x510ef6`, through +/// `0x611660`) and presses command 0x800000, which the release lets go of in the same call +/// (`0x60fc10`). The canceller itself sends nothing. +pub(crate) fn end_auto_move( + follow: Option<&mut FollowState>, + approach: Option<&mut Approach>, + autorun: Option<&mut super::press::CallAutorun>, + lane: Option<&mut crate::field_watch::NoticeLane>, +) -> bool { + // Mode 2, the facing turn, has no forward release. + let (walked, faced) = approach.map_or((false, false), |a| { + let ended = (a.active(), a.facing_turn()); + a.stop(); + ended + }); + let Some(follow) = follow else { + return walked; + }; + let mut lane = lane; + let followed = super::follow::end(follow, lane.as_deref_mut()); + if followed || (walked && !faced) { + follow.owe_release(); + // `AUTOFOLLOW_END` goes out before the release clears autorun (`0x60fb84`, then `0x60fc08` + // → `0x60e83f`), so a follow's clear waits on the lane behind it; a walk signals nothing + // and clears in place. + match (followed, lane) { + (true, Some(lane)) => lane.write(crate::field_watch::FieldNotice::AutorunClear), + _ => { + if let Some(autorun) = autorun { + autorun.clear(); + } + } + } + } + walked || followed +} + +/// [`AutoMoveStop::stop`] on `guid` from a handler's world, its signal on the notice lane at the +/// place it runs. +pub(crate) fn stop_auto_move(world: &mut World, guid: u64) { + if let Err(e) = world.run_system_cached_with(stop_auto_move_of, guid) { + // A harness without the mover's claim stops nothing. + debug!("auto-move: the stop did not run: {e}"); + } +} + +fn stop_auto_move_of( + In(guid): In, + mut stop: AutoMoveStop, + mut lane: Option>, +) { + stop.stop(guid, lane.as_deref_mut()); +} + +/// `CanAutoInteract` (`0x60f900`): alive, driving our own body, and the option on. pub(crate) fn can_auto_interact( enabled: bool, me: Option<&ObjectStore>, @@ -198,6 +328,16 @@ pub(crate) struct AutoMove<'w, 's> { } impl AutoMove<'_, '_> { + /// The `AUTOFOLLOW_END` a walk's arm owes, signalled on `script`, in the call or the click + /// that armed it. + pub(crate) fn signal_follow_end(&mut self, script: Option<&mut benilla_ui::script::UiScript>) { + if std::mem::take(&mut self.approach.owes_follow_end) { + if let Some(script) = script { + script.fire_event("AUTOFOLLOW_END", vec![]); + } + } + } + pub(crate) fn can_auto_interact(&self) -> bool { can_auto_interact( self.approach.enabled, @@ -247,7 +387,7 @@ impl AutoMove<'_, '_> { return false; } let anchor = self.anchor(at); - self.arm(Toward::Ground(anchor), at, GROUND_STOP, stand) + self.arm(Toward::ClickToMove(anchor), at, GROUND_STOP, stand) .is_ok() } @@ -303,7 +443,7 @@ impl AutoMove<'_, '_> { } let delta = at - self.player.pos; let facing = follow::bearing_to(Vec3::new(delta.x, 0.0, delta.z)); - self.arm(Toward::Face(facing), at, 0.0, stand).is_ok() + self.arm(Toward::FacingTurn(facing), at, 0.0, stand).is_ok() } /// Deviation: the reference converts back through the transport the player stands on each @@ -332,7 +472,10 @@ impl AutoMove<'_, '_> { .me .single() .is_ok_and(|(_, s)| s.0.unit_stand_state() == 0); - self.follow.stop(); + // The canceller first (`0x61113e` → `0x60fb60(0, 0)`), whose follow leg owes `END`. + if self.follow.stop() { + self.approach.owes_follow_end = true; + } self.approach.stop(); if toward.leashed() && self.player.pos.distance_squared(at) >= LEASH_SQ { return Err(Refused::TooFar); @@ -463,7 +606,7 @@ pub(super) fn steer_approach( } Some(tf.translation) } - Toward::Ground(anchor) | Toward::Melee(anchor) => match anchor.frame { + Toward::ClickToMove(anchor) | Toward::Melee(anchor) => match anchor.frame { None => Some(anchor.at), Some(frame) => { let Ok((tf, ..)) = targets.get(frame) else { @@ -474,7 +617,7 @@ pub(super) fn steer_approach( Some(tf.transform_point(anchor.at)) } }, - Toward::Sky(_) | Toward::Face(_) => None, + Toward::Sky(_) | Toward::FacingTurn(_) => None, }; let delta = target.map(|t| t - player.pos); let d2 = delta.map(|d| goal_distance_sq(toward, goal.stop, d, speed, player.swimming)); @@ -495,7 +638,7 @@ pub(super) fn steer_approach( } } let bearing = match (toward, delta) { - (Toward::Sky(facing) | Toward::Face(facing), _) => facing, + (Toward::Sky(facing) | Toward::FacingTurn(facing), _) => facing, (_, Some(d)) => follow::bearing_to(Vec3::new(d.x, 0.0, d.z)), (_, None) => player.face_yaw, }; @@ -504,14 +647,14 @@ pub(super) fn steer_approach( if turning { let rate = *goal.turn_rate.get_or_insert_with(|| turn_rate(remaining)); player.face_yaw = follow::steer(player.face_yaw, bearing, rate, time.delta_secs()); - } else if let Toward::Face(_) = toward { + } else if let Toward::FacingTurn(_) = toward { // `0x6108c3`: the facing walk ends once lined up, never holding forward. approach.goal = None; return; } else { goal.aligned = true; } - if let Toward::Face(_) = toward { + if let Toward::FacingTurn(_) = toward { return; } if let (Some(d2), Some(delta)) = (d2, delta) { @@ -548,14 +691,17 @@ pub(super) fn steer_approach( player.auto_forward = hold; } -pub(crate) fn on_cvar(ev: On, mut approach: ResMut) { +pub(crate) fn on_cvar( + ev: &crate::cvars::CvarChanged, + mut approach: bevy::prelude::Mut<'_, Approach>, +) { if ev.is("AutoInteract") { approach.enabled = ev.flag(); } } pub(super) fn plugin(app: &mut App) { - app.init_resource::().add_observer(on_cvar); + app.init_resource::(); } #[cfg(test)] @@ -592,11 +738,11 @@ mod tests { #[test] fn the_ground_stop_scales_with_speed_and_the_melee_stop_does_not() { assert_eq!( - arrive_distance(Toward::Ground(POINT), GROUND_STOP, 7.0), + arrive_distance(Toward::ClickToMove(POINT), GROUND_STOP, 7.0), 0.5 ); assert_eq!( - arrive_distance(Toward::Ground(POINT), GROUND_STOP, 14.0), + arrive_distance(Toward::ClickToMove(POINT), GROUND_STOP, 14.0), 1.0 ); assert_eq!(arrive_distance(Toward::Melee(POINT), 1.9, 14.0), 1.9); @@ -648,7 +794,7 @@ mod tests { .init_resource::>() .init_resource::() .init_resource::() - .init_resource::() + .init_resource::() .insert_resource(MoveSpeed { value: 7.0, env_override: false, diff --git a/crates/benilla-app/src/player/camera.rs b/crates/benilla-app/src/player/camera.rs index 6f2d224ce..bf74c040d 100644 --- a/crates/benilla-app/src/player/camera.rs +++ b/crates/benilla-app/src/player/camera.rs @@ -5,7 +5,7 @@ use bevy::ecs::entity::EntityHashSet; use bevy::input::mouse::AccumulatedMouseMotion; use bevy::mesh::MeshTag; use bevy::prelude::*; -use bevy::window::{CursorGrabMode, CursorOptions, PrimaryWindow}; +use bevy::window::{CursorGrabMode, CursorOptions}; use super::camera_channel::{Arm, SmoothChannel}; use super::camera_dynamics::{DynamicsInput, HeadBob, SmartPivot, TerrainTilt}; @@ -72,10 +72,10 @@ pub(crate) const MOUSE_SPEED_RANGE: std::ops::RangeInclusive = 0.5..=1.5; /// The camera rows' change callback: the look, zoom and follow knobs. pub(crate) fn on_cvar( - ev: On, - mut look: ResMut, - mut zoom: ResMut, - mut follow: ResMut, + ev: &crate::cvars::CvarChanged, + mut look: bevy::prelude::Mut<'_, LookConfig>, + mut zoom: bevy::prelude::Mut<'_, ZoomLimit>, + mut follow: bevy::prelude::Mut<'_, FollowConfig>, ) { let v = ev.num(); match ev.key().as_str() { @@ -574,10 +574,9 @@ pub(crate) struct CameraControl { /// The arm's length from the head after world collision: pulled in instantly, eased back out, /// and kept apart from `distance` so the chosen zoom survives an obstruction. pub(super) collision_distance: f32, + /// The look session's button, `Some` while the camera is in freelook: the reference's + /// `[cam+0x90] & 1` (set `0x50fe41`, cleared `0x50fddd`), for a left orbit as for the rest. pub(super) look: Option, - /// Mouse-look is on: the reference's `[cam+0x90] & 1` (set `0x50fe41`, cleared `0x50fddd`). - /// Written by [`run_look_session`], read the same frame for `cameraTerrainTilt`'s hand-off. - pub(super) freelook: bool, /// The mouse buttons the world owns this frame, latched by [`latch_world_mouse`]. pub(crate) world_mouse: WorldMouse, /// `ToggleMouseMove` entered mouselook with no mouse bit (`0x50f910` → `0x50f930`): the @@ -589,6 +588,12 @@ pub(crate) struct CameraControl { pub(super) cursor_stash: Option, /// A look session is running with the OS cursor handed back: the window is unfocused. pub(super) cursor_released: bool, + /// A call left freelook inside it (`0x50fdd0`) while the session held the OS cursor: the look + /// session gives it back and restores it, the one part left at the frame ([`LookSteps`]). + pub(super) cursor_return: bool, + /// The freelook edges the look session made outside any call, in order, true for an entry: + /// their mouse-focus half waits for [`focus_on_look_edges`], right after it. + pub(super) world_edges: Vec, /// The self-avatar's alpha from the camera-to-pivot distance, 1 in third person to 0 in first /// (`self_model_fade_alpha`); applied by [`apply_self_model_fade`]. pub(super) self_fade_alpha: f32, @@ -654,30 +659,40 @@ pub(super) enum LookButton { Left, } -impl LookButton { - fn button(self) -> MouseButton { - match self { - LookButton::Right => MouseButton::Right, - LookButton::Left => MouseButton::Left, +/// The primary bits as the frame's look session reads them off their store +/// ([`crate::bindings::BindingsState`]), by [`LookButton`]: TurnOrAction, then CameraOrSelectOrMove. +#[derive(Clone, Copy, Debug, Default)] +pub(super) struct Primaries { + /// Held now, which holds the channel's session. + held: [bool; 2], + /// Rose this frame in a call that entered nothing inside it, one with no host lent. + rose: [bool; 2], +} + +impl Primaries { + pub(super) fn of(binds: &crate::bindings::BindingsState) -> Self { + use crate::bindings::Input; + let bits = [Input::TurnOrAction, Input::CameraOrSelectOrMove]; + Self { + held: bits.map(|i| binds.pressed(i)), + rose: bits.map(|i| binds.just_pressed(i) && !binds.settled(i)), } } } -/// The mouse buttons the world owns, latched at the press, and the two channels they drive. 1.12 -/// reads the `TurnOrAction` and `CameraOrSelectOrMove` bindings, which a press a UI frame captured -/// never dispatches: no mouse bit in `[InputControl+0x4]`, no look session, no [`FollowState`]. -/// The world's down sets the bit and that button's up clears it, so a frame appearing under the -/// locked cursor cannot steal it. `MouselookStart` sets the TurnOrAction bit with no button. +/// The look session's share of the calls that move the primary bits. The bits themselves are +/// `[InputControl+4] & 3` in [`crate::bindings::BindingsState`], one store whoever sets them: the +/// mouse commands' Starts and Stops, `MouselookStart`'s TurnOrAction bit (`0x515090(1, 1, …)` at +/// `0x514231`), the right button's release in freelook. A press a UI frame captured runs no +/// binding: no bit, no look session, no [`FollowState`]. #[derive(Default)] pub(crate) struct WorldMouse { - /// Held by the world right now, indexed by [`LookButton`]. - held: [bool; 2], - /// Took its down edge from the world this frame, same index. - down: [bool; 2], - /// `MouselookStart` holds the TurnOrAction channel (`0x515090(1, 1, …)` at `0x514231`). - scripted: bool, - /// This frame's `MouselookStart` raised the channel. - scripted_rise: bool, + /// A first primary press a call with no host lent made, which the next look session enters + /// freelook on (`0x51491f`): one made inside its call entered there ([`LookSteps`]). + owed: Option, + /// The latch ran and the controller has not yet read [`Self::late_rise`]: a rise a call makes + /// now is the packets' handlers', after the look session. + late_window: bool, /// A `MouselookStart` after the frame's look session raised it: the controller hands the /// body off for it ([`Self::late_rise`]). late_rise: bool, @@ -687,62 +702,12 @@ pub(crate) struct WorldMouse { /// `0x50f940` stores as the camera's sticky bit when the release ends mouselook; `None` with /// no release call. release_sticky: Option, + /// A bound mouse command's stop inside its call: whether it cleared a held bit, which the + /// release call its verb makes next reads (`0x514b7d`) ([`LookSteps::bound`]). + release_changed: Option, } impl WorldMouse { - pub(super) fn held(&self, b: LookButton) -> bool { - self.held[b as usize] - } - - pub(super) fn down(&self, b: LookButton) -> bool { - self.down[b as usize] - } - - /// The TurnOrAction channel, `[InputControl+4] & 1`: the world's right button, or a - /// `MouselookStart` with none. - pub(super) fn turn(&self) -> bool { - self.held(LookButton::Right) || self.scripted - } - - /// The channel `b`'s look session runs on: TurnOrAction for right, the left button's own. - pub(super) fn channel(&self, b: LookButton) -> bool { - match b { - LookButton::Right => self.turn(), - LookButton::Left => self.held(LookButton::Left), - } - } - - /// Both channels held: the both-button run (`0x514da0` nets `0x1` and `0x2` as forward). - pub(super) fn both(&self) -> bool { - self.turn() && self.held(LookButton::Left) - } - - /// A channel rose this frame, by a press or a `MouselookStart`: with [`Self::both`], the - /// transition into the both-button run (`0x514a73`, in the set helper both reach). - pub(super) fn rose(&self) -> bool { - self.down(LookButton::Left) || self.down(LookButton::Right) || self.scripted_rise - } - - /// The left button held by the world, then a `MouselookStart` made after the frame's look - /// session, as a packet's handler makes one: the call that completes both mouse bits. - #[cfg(test)] - pub(crate) fn late_mouselook_start_over_a_left_drag(&mut self) { - self.held[LookButton::Left as usize] = true; - self.call_late(benilla_ui::script::LookCall::Mouselook(true)); - } - - /// The right button, as the world holds it, for a test of who owns a press. - #[cfg(test)] - pub(crate) fn holds_right(&self) -> bool { - self.held(LookButton::Right) - } - - /// The left button, as the world holds it, for a test of who owns a press. - #[cfg(test)] - pub(crate) fn held_left(&self) -> bool { - self.held(LookButton::Left) - } - /// A `MouselookStart` made after this frame's look session raised the channel, as a packet's /// handler makes one: the session saw no rise, so the controller hands the body off for it, /// as the reference's press handler does inside the call (`0x514924`-`0x514966`). @@ -750,172 +715,393 @@ impl WorldMouse { self.late_rise } - /// What the calls since the last look session hand it, taken: the `ToggleMouseMove` count and - /// the last release's sticky argument. A call made after a session reaches the next one. - fn take_session_edges(&mut self) -> (u32, Option) { + /// The controller has read [`Self::late_rise`]: a rise a call makes from here on, the frame + /// pass's, is the next frame's. + pub(super) fn close_late_window(&mut self) { + self.late_window = false; + } + + /// What the calls since the last look session hand it, taken: the `ToggleMouseMove` count, the + /// last release's sticky argument, and the entry a call with no host owes. A call made after + /// a session reaches the next one. + fn take_session_edges(&mut self) -> (u32, Option, Option) { ( std::mem::take(&mut self.toggles), self.release_sticky.take(), + self.owed.take(), ) } - /// Latch this frame; `world_press` says whether a down edge belongs to the world. A held bit - /// rides to its release, including a cover's emptying of the button planes. - fn update( - &mut self, - buttons: &ButtonInput, - world_press: impl Fn(MouseButton) -> bool, - ) { - self.scripted_rise = false; + /// The frame's latch: a rise from here on is this frame's. + fn frame_start(&mut self) { self.late_rise = false; - for b in [LookButton::Right, LookButton::Left] { - let i = b as usize; - self.down[i] = world_press(b.button()) && buttons.just_pressed(b.button()); - self.held[i] = (self.held[i] || self.down[i]) && buttons.pressed(b.button()); - } + self.late_window = true; } - /// The release of every command (`0x5144c0` → `0x514b70(-1, …)`): both mouse bits, held or - /// scripted, so the look session ends at its next run. + /// The release of every command (`0x5144c0` → `0x514b70(-1, …)`): the session's accumulators, + /// with the bits' own release ([`crate::bindings::BindingsState::release_primaries`]). pub(crate) fn release_all(&mut self) { - self.mouselook(false); - self.held = [false; 2]; + self.owed = None; + self.release_sticky = Some(false); } - /// Whether the TurnOrAction channel is held, by the right button or a `MouselookStart`. + /// `MouselookStart` as the VM's call lands with no host lent, for a test. #[cfg(test)] - pub(crate) fn turn_held(&self) -> bool { - self.turn() + pub(crate) fn mouselook_for_test(&mut self, binds: &mut crate::bindings::BindingsState) { + self.call(benilla_ui::script::LookCall::Mouselook(true), binds); } - /// `MouselookStart` as the VM's call lands, for a test. + /// A look call made after the frame's look session, as a packet's handler makes one. #[cfg(test)] - pub(crate) fn mouselook_for_test(&mut self) { - self.mouselook(true); - } - - /// `MouselookStart` (`on`) or `MouselookStop`: one bit, whoever set it, so a stop also ends - /// a right drag in flight, whose release then clears nothing. - fn mouselook(&mut self, on: bool) { - if on { - self.scripted_rise |= !self.turn(); - self.scripted = true; - } else { - self.scripted = false; - self.held[LookButton::Right as usize] = false; - // `0x515090(1, 0, now, 0)`: the release hands 0. - self.release_sticky = Some(false); - } + pub(crate) fn late_call_for_test( + &mut self, + call: benilla_ui::script::LookCall, + binds: &mut crate::bindings::BindingsState, + ) { + self.call_late(call, binds); } /// One look-session call made after the frame's look session, in call order. - fn call_late(&mut self, call: benilla_ui::script::LookCall) { - let rises = call == benilla_ui::script::LookCall::Mouselook(true) && !self.turn(); - self.call(call); - self.late_rise |= rises; + fn call_late( + &mut self, + call: benilla_ui::script::LookCall, + binds: &mut crate::bindings::BindingsState, + ) { + self.late_rise |= self.call(call, binds); } - /// One look-session call from the VM, in call order. - fn call(&mut self, call: benilla_ui::script::LookCall) { - use benilla_ui::script::LookCall; + /// One look-session call from the VM that no host applied, in call order, after this frame's + /// latch: `MouselookStart` or `MouselookStop` moves the TurnOrAction bit, a start that set the + /// first primary bit owes the session its entry (`0x51491f`), and a stop hands the release + /// its 0 (`0x515090(1, 0, now, 0)`). Whether a start raised the bit. + fn call( + &mut self, + call: benilla_ui::script::LookCall, + binds: &mut crate::bindings::BindingsState, + ) -> bool { + use crate::bindings::Input; + use benilla_ui::script::{BindingInput, HeldInput, LookCall}; match call { - LookCall::Mouselook(on) => self.mouselook(on), - LookCall::ToggleMouseMove => self.toggles += 1, - LookCall::MouseRelease { sticky } => self.release_sticky = Some(sticky), + LookCall::Mouselook(on) => { + let first = !binds.primary_held(); + let was = binds.pressed(Input::TurnOrAction); + binds.apply_unhosted(if on { + BindingInput::Start(HeldInput::TurnOrAction) + } else { + BindingInput::Stop(HeldInput::TurnOrAction) + }); + if on && first { + self.owed = Some(LookButton::Right); + } + if !on && was { + self.release_sticky = Some(false); + } + on && !was + } + LookCall::ToggleMouseMove => { + self.toggles += 1; + false + } + LookCall::MouseRelease { sticky } => { + self.release_sticky = Some(sticky); + false + } } } } -/// Decide once per frame which mouse buttons the world owns: a press in the viewport off the UI, -/// or any press while a look session owns the cursor (a chord's second button). Its own system, -/// first of the world's mouse input ([`super::WorldMouse`]), ahead of the look session and of -/// `/follow`'s both-button cancel ([`super::follow::steer_follow`]) in the frame time. +/// The look-session calls inside their verbs ([`benilla_ui::script::ScriptCall::Look`]), on the +/// world mouse and the camera's freelook; absent in a harness without the rig. +#[derive(bevy::ecs::system::SystemParam)] +pub(crate) struct LookSteps<'w> { + rig: Option>, + /// The primary bits' store, which `MouselookStart` and `MouselookStop` move, a press must find + /// clear to enter freelook and a release must leave clear to leave it. + binds: Option>, + /// The click a toggle's leave disarms. + arm: Option>, + /// The dev inspector, which owns the left button while armed. + inspect: Option>, +} + +/// The look's state as of the getter's place: the camera's freelook, which blanks the world's +/// pick ([`benilla_ui::script::FreelookQuery`]), and the TurnOrAction bit `IsMouselooking` tests +/// ([`benilla_ui::script::MouselookingQuery`]). +#[derive(bevy::ecs::system::SystemParam)] +pub(crate) struct LookLive<'w> { + /// Absent in a harness without the rig, where the pick stands. + rig: Option>, + /// The primary bits' one store; absent in a harness without it, where the VM's own record of + /// the commands answers. + binds: Option>, +} + +impl crate::script_calls::live::LiveFamily for LookLive<'_> { + fn answer(&mut self, ask: &mut benilla_ui::script::live::LiveAsk<'_>) -> bool { + ask.answer(|_: &benilla_ui::script::FreelookQuery| Some(self.rig.as_deref()?.is_looking())) + || ask.answer(|_: &benilla_ui::script::MouselookingQuery| { + Some( + self.binds + .as_deref()? + .pressed(crate::bindings::Input::TurnOrAction), + ) + }) + } +} + +/// What a look call did inside it ([`LookSteps::call`]). +#[derive(Clone, Copy, Debug, Default)] +pub(crate) struct Looked { + /// The TurnOrAction channel moved. + pub(crate) changed: bool, + /// The camera entered freelook (`0x50fe30` → `0x493070`): the world frame turns the plates' + /// mouse off (`0x483e9a` → `0x60f830`) and clears the published mouseover (`0x483ec3`). + pub(crate) entered: bool, + /// The camera left freelook (`0x50fdd0` → `0x493090`): the plates' mouse comes back + /// (`0x483e70` → `0x60f830`). + pub(crate) left: bool, +} + +impl LookSteps<'_> { + /// Apply `call` inside its verb: the channel, then the freelook it enters or leaves there. + /// `MouselookStart`'s press enters it as the first primary (`0x514840` → `0x51491f` → + /// `0x50f930`), `ToggleMouseMove` flips it (`0x50f910`), and a release that leaves no mouse + /// bit held leaves it with its sticky argument (`0x514c48` → `0x50f940`). The session takes + /// the OS cursor at the frame ([`sync_look_focus`]). + pub(crate) fn call(&mut self, call: benilla_ui::script::LookCall) -> Looked { + use benilla_ui::script::{BindingInput, HeldInput, LookCall}; + let (Some(rig), Some(binds)) = (self.rig.as_deref_mut(), self.binds.as_deref_mut()) else { + return Looked::default(); + }; + let mut looked = Looked::default(); + match call { + // One bit, whoever set it: a stop also ends a right drag in flight, whose release then + // clears nothing (`0x514240` → `0x515090(1, 0, …)`). + LookCall::Mouselook(on) => { + let first = !binds.primary_held(); + let was = binds.pressed(crate::bindings::Input::TurnOrAction); + binds.call(if on { + BindingInput::Start(HeldInput::TurnOrAction) + } else { + BindingInput::Stop(HeldInput::TurnOrAction) + }); + looked.changed = was != on; + // A rise a packet's handler makes, after the look session, is the controller's + // hand-off ([`WorldMouse::late_rise`]). + if looked.changed && on && rig.world_mouse.late_window { + rig.world_mouse.late_rise = true; + } + if looked.changed && on && first { + looked.entered = rig.press_in_place(LookButton::Right); + } else if looked.changed && !on && !binds.primary_held() { + looked.left = rig.leave_in_place(false); + } + } + LookCall::ToggleMouseMove => { + if rig.look.is_some() { + if let Some(arm) = self.arm.as_deref_mut() { + arm.disarm(); + } + looked.left = rig.leave_in_place(false); + } else { + looked.entered = rig.enter_in_place(LookButton::Left); + rig.toggled = true; + } + } + // A release that cleared a held bit and left none held leaves (`0x514b7d`, + // `0x514c35` → `0x514c48`); one that cleared none, as under a toggled freelook with + // no press, does nothing. + LookCall::MouseRelease { sticky } => { + let changed = rig.world_mouse.release_changed.take().unwrap_or(true); + if changed && !binds.primary_held() { + looked.left = rig.leave_in_place(sticky); + } + if changed && !looked.left { + rig.world_mouse.release_sticky = Some(sticky); + } + } + } + looked + } + + /// The primary bits a binding call finds before its bit moves, which [`Self::bound`] reads + /// after it. + pub(crate) fn bits_before(&self, input: benilla_ui::script::BindingInput) -> PrimaryBits { + use benilla_ui::script::BindingInput::{Start, Stop}; + let Some(binds) = self.binds.as_deref() else { + return PrimaryBits::default(); + }; + let this = match input { + Start(held) | Stop(held) => mouse_command(held), + _ => None, + }; + PrimaryBits { + any: binds.primary_held(), + this: this.is_some_and(|i| binds.pressed(i)), + } + } + + /// A bound mouse command inside its call, its bit moved, as `before` found the bits. A + /// `TurnOrActionStart` or `CameraOrSelectOrMoveStart` that set the first primary bit enters + /// freelook on its button (`0x514840` → `0x51491f` → `0x50f930`), unless the camera is in it + /// already (`0x50fe3b`); while the dev inspector is armed, the left button is its own. A stop + /// records whether it cleared a held bit, for the release call its verb makes next. + pub(crate) fn bound( + &mut self, + input: benilla_ui::script::BindingInput, + before: PrimaryBits, + ) -> Looked { + use benilla_ui::script::BindingInput::{Start, Stop}; + let inspecting = self.inspect.as_deref().is_some_and(|i| i.enabled); + let Some(rig) = self.rig.as_deref_mut() else { + return Looked::default(); + }; + match input { + Start(held) if !before.any => { + let button = match mouse_command(held) { + Some(crate::bindings::Input::TurnOrAction) => LookButton::Right, + Some(_) if !inspecting => LookButton::Left, + _ => return Looked::default(), + }; + Looked { + entered: rig.press_in_place(button), + ..Default::default() + } + } + Stop(held) if mouse_command(held).is_some() => { + rig.world_mouse.release_changed = Some(before.this); + Looked::default() + } + _ => Looked::default(), + } + } +} + +/// What a binding call finds of the primary bits before its own moves ([`LookSteps::bits_before`]). +#[derive(Clone, Copy, Debug, Default)] +pub(crate) struct PrimaryBits { + /// A primary bit is held, so a press is not the first. + any: bool, + /// The call's own mouse command bit is held, so its stop clears one. + this: bool, +} + +/// The mouse command a held input is, if it is one. +fn mouse_command(held: benilla_ui::script::HeldInput) -> Option { + use benilla_ui::script::HeldInput; + match held { + HeldInput::TurnOrAction => Some(crate::bindings::Input::TurnOrAction), + HeldInput::CameraOrSelectOrMove => Some(crate::bindings::Input::CameraOrSelectOrMove), + _ => None, + } +} + +impl CameraControl { + /// The first primary's press inside its call (`0x51491f`): freelook entered on `button` + /// ([`Self::enter_in_place`]), or a toggled one, which holds no bit, made that bit's, as the + /// session hands it at the frame ([`run_look_session`]). Whether it entered. + fn press_in_place(&mut self, button: LookButton) -> bool { + if self.toggled && self.look.is_some() { + self.toggled = false; + self.look = Some(button); + return false; + } + self.enter_in_place(button) + } + + /// `0x50fe30` inside a call: the mode bit, the session on `button`, the cursor hidden and the + /// device relative; the OS grab is owed to the look session, which takes it once focused. + /// Whether it entered: in freelook already, it does nothing (`0x50fe3b`). + fn enter_in_place(&mut self, button: LookButton) -> bool { + if self.look.is_some() { + return false; + } + self.look = Some(button); + self.cursor_released = true; + true + } + + /// `0x50f940(sticky)` → `0x50fdd0` inside a call: freelook left, a toggle's with it, and the + /// sticky bit kept (`0x50f958`, `0x50f95d`); a held OS cursor goes back at the look session. + /// Whether it left: out of freelook, the mode bit's test skips the leave (`0x50fddb`) and the + /// sticky bit is still written. + fn leave_in_place(&mut self, sticky: bool) -> bool { + self.follow.sticky = sticky; + if self.look.is_none() { + return false; + } + self.look = None; + self.toggled = false; + self.world_mouse.release_sticky = None; + if std::mem::take(&mut self.cursor_released) { + self.cursor_stash = None; + } else { + self.cursor_return = true; + } + true + } +} + +/// The frame's latch of the world's mouse input, first of it, ahead of the look session and of +/// `/follow`'s both-button cancel ([`super::follow::steer_follow`]) in the frame time: the look +/// calls made with no host lent since the last latch, and the cover's release of both primary +/// bits, each on their store ([`crate::bindings::BindingsState`]). A button's release moves a bit +/// only through its binding's up-half, as the world frame's release slot runs it +/// ([`crate::bindings`]). pub(crate) fn latch_world_mouse( - buttons: Res>, - // The raw flag: a press on a nameplate is the plate's, so dragging from a plate never turns the - // camera, as in 1.12. `0x7662c0` hands a mouse-down to one frame (capture at `0x7663e9`), and - // `CBindings::ExecuteBinding` (`0x4b7990`) runs only from `CGWorldFrame` handlers; the release - // goes to the plate's click slot (`0x7792d0` → `0x7cb910` → `0x4949f0`). Entering freelook - // disables plate input (`0x60f830`, from `0x483e80`) for a world drag across one. A plate's - // ground-targeting veto (`+0x3c`, `0x7cba30`) arrives through `PointerOverUi` - // (`UiScript::set_nameplate_hit_test_veto`). The wheel still zooms over a plate. - pointer_over_ui: Res, - // A press the UI consumed with nothing hovered, the layout drag's or a right press that - // dropped a payload: no frame saw it, the world's included (`0x766353`, `0x766370`). - press_consumed: Option>, - // Who each of the frame's press records went to, as the world frame's binding read it. - presses: Option>, - mut rig: ResMut, - cameras: Query<&Camera, With>, - window: Single<&Window, With>, - mut hosted_vm: crate::script_calls::HostedVm, + // With the rig and the primary bits, which the calls move inside them: written between the Lua + // the latch runs, never while the host is lent. + mut vm: crate::script_calls::VmWith<( + ResMut<'static, CameraControl>, + ResMut<'static, crate::bindings::BindingsState>, + )>, cover: Option>, ) { - hosted_vm.run(|mut script| { - let calls = script - .as_mut() - .map(|s| s.take_look_calls()) - .unwrap_or_default(); - let Ok(camera) = cameras.single() else { - return; - }; - // A press's owner is its record's, as its binding read it, so the latch and the binding - // agree; a press no record made (a test's plane) reads the frame's hover. - let over_ui = pointer_over_ui.0 || press_consumed.is_some_and(|c| c.0); - let looking = rig.look.is_some(); - let in_viewport = cursor_in_viewport(&window, camera); - let world_press = |b: MouseButton| { - let over = presses - .as_ref() - .and_then(|p| p.over_ui(b)) - .unwrap_or(over_ui); - looking || (in_viewport && !over) - }; - let wm = &mut rig.world_mouse; - wm.update(&buttons, world_press); - // The script's calls, made since the last latch, before this frame's release. + let (mut script, set) = vm.parts(); + let calls = script + .as_mut() + .map(|s| s.take_look_calls()) + .unwrap_or_default(); + { + let (mut rig, mut binds) = set.p0(); + rig.world_mouse.frame_start(); + // The script's calls made with no host lent since the last latch, before this frame's + // release; a lent host applied the rest inside their calls ([`LookSteps`]). for call in calls { - wm.call(call); - } - // The right button's release ends a scripted channel too, wherever its press went: in - // freelook every button event goes to the `WorldFrame` (`0x492b50`), whose TURNORACTION up - // runs `TurnOrActionStop` (`0x514160`), `0x515090(1, 0, …)`. - // The command's own bit goes with it: a release whose press a frame took ran no binding - // here, and a bit left held would kill every later click. - if buttons.just_released(MouseButton::Right) { - wm.scripted = false; - if let Some(script) = script.as_deref_mut() { - script.release_turn_or_action(); - } + rig.world_mouse.call(call, &mut binds); } // The world enter behind the cover clears the whole word (`0x5144c0` → `0x514b70(-1, …)`), // the commands' primary bits with it. A window deactivate clears none of it (`0x5144a3 // and eax,0xfffff00f` keeps the low bits): the session outlives the focus, and only the // OS cursor goes back ([`sync_look_focus`]). - if cover.is_some_and(|c| c.covering()) { - wm.scripted = false; - if let Some(script) = script.as_deref_mut() { - script.release_mouse_commands(); - } + if cover.as_ref().is_some_and(|c| c.covering()) { + binds.release_primaries(); + rig.world_mouse.release_all(); } - // `IsMouselooking` (`0x514270`) reads `[InputControl+4] & 1`, the TurnOrAction channel. - if let Some(script) = script { - script.set_turn_or_action_held(rig.world_mouse.turn()); - } - }) + } + let Some(script) = script else { + return; + }; + if cover.is_some_and(|c| c.covering()) { + script.release_mouse_commands(); + } } -/// The look calls the handlers of the frame's packets made, after the input's latch -/// ([`latch_world_mouse`]) and before the frame time's controller: the reference's press and +/// The look calls the handlers of the frame's packets made with no host lent, after the input's +/// latch ([`latch_world_mouse`]) and before the frame time's controller; a lent host applied the +/// rest inside their calls ([`LookSteps::call`]): the reference's press and /// release handlers move the input control inside the call (`MouselookStart` `0x514210` → /// `0x515090` → `0x514840`), so a packet's handler's call holds the channel for the input tick of /// the same tick (category 5), and the next mouse message turns. The frame pass's `OnUpdate` /// runs after that tick, so its calls wait for the next frame's latch. pub(crate) fn apply_late_look_calls( - mut rig: ResMut, - mut hosted_vm: crate::script_calls::HostedVm, + // With the rig and the primary bits, which the calls move inside them; the drain runs no Lua. + mut vm: crate::script_calls::VmWith<( + ResMut<'static, CameraControl>, + ResMut<'static, crate::bindings::BindingsState>, + )>, ) { - hosted_vm.run(|script| { + vm.turn(|script, (mut rig, mut binds)| { let Some(script) = script else { return; }; @@ -924,12 +1110,38 @@ pub(crate) fn apply_late_look_calls( return; } for call in calls { - rig.world_mouse.call_late(call); + rig.world_mouse.call_late(call, &mut binds); } - script.set_turn_or_action_held(rig.world_mouse.turn()); }) } +/// The mouse-focus half of the freelook edges the look session made outside any call +/// ([`run_look_session`]), right after it and ahead of the tick, as the reference's entry runs it +/// before its tick (`0x51491f`, then `0x5151a0`): an entry's `SetMouseFocus` of the world frame +/// (`0x493070` → `0x493085`), a leave's hover re-pick (`0x493090` → `0x4930a0`). An edge a call +/// made ran its half inside the call ([`crate::script_calls`]); the plates' mouse and the +/// mouseover follow the look on their own. +pub(crate) fn focus_on_look_edges( + mut vm: crate::script_calls::VmWith>, +) { + let edges = std::mem::take(&mut vm.own().world_edges); + if edges.is_empty() { + return; + } + vm.run(|script| { + let Some(script) = script else { + return; + }; + for entered in edges { + if entered { + script.focus_world_frame(); + } else { + script.repick_hover(); + } + } + }); +} + #[derive(Component)] // `pub(crate)` for the scripted camera park's query; `FlyCam::park` is its one lever. pub(crate) struct FlyCam { @@ -962,14 +1174,13 @@ pub(crate) struct CameraPivot { /// The mouse-look session: start, stop and hand-off between the buttons, cursor grab and restore, /// the look rotation, and the travel of the click the mouse commands armed /// ([`crate::target::ClickArm`]), which their release judges. Orbit and select are independent: -/// each primary press engages its session at once. A session lasts while its -/// [`WorldMouse::channel`] is held, so a `MouselookStart` runs the right button's session. +/// each primary press engages its session at once. A session lasts while its primary bit is held +/// ([`Primaries`]), so a `MouselookStart` runs the right button's session. /// Returns whether a mouse motion reached the body's hand-off this frame: the motion handler /// `0x514400` hands the camera's facing and pitch on (`0x5103e0`) for each motion while the mouse /// turns the body (`0x51446f`), before the body gates of `0x5145e0`, which are the caller's. pub(super) fn run_look_session( mouse_motion: &AccumulatedMouseMotion, - both_buttons: bool, rig: &mut CameraControl, cam: &mut FlyCam, face_yaw: &mut f32, @@ -984,15 +1195,31 @@ pub(super) fn run_look_session( dynamics: &DynamicsInput, // The primary window has the OS focus. focused: bool, + // The primary bits off their store, which hold the session's channel and raise its entry. + primaries: Primaries, + // `[InputControl+4]` holds a bit ([`super::input::word_held`]). + word_held: bool, ) -> bool { + let holds = |b: LookButton| primaries.held[b as usize]; // The mouse moves the view only through a held cursor: motion while unfocused, or on the frame // that takes the cursor back, is the pointer travelling in another app. + // A call left freelook inside it: the OS cursor it held goes back where the look began. + if std::mem::take(&mut rig.cursor_return) { + release_cursor(cursor_opts); + if let Some(pos) = rig.cursor_stash.take() { + window.set_cursor_position(Some(pos)); + } + } let motion = if sync_look_focus(rig, focused, window, cursor_opts) { mouse_motion.delta } else { Vec2::ZERO }; - let (toggles, release_sticky) = rig.world_mouse.take_session_edges(); + // The motion handler returns on an empty command word (`0x51440c`), ahead of the click's + // travel, the camera's turn (`0x514446`, the one caller of `0x50fee0`) and the hand-off: a + // `ToggleMouseMove` with nothing held hides the cursor, and the mouse turns nothing. + let motion = if word_held { motion } else { Vec2::ZERO }; + let (toggles, release_sticky, owed) = rig.world_mouse.take_session_edges(); // The armed click accumulates the rotation the press asked for, charged before the pitch // clamp: the reference accumulates raw motion, so a drag pinned at the pitch limit still spends // budget. @@ -1010,9 +1237,11 @@ pub(super) fn run_look_session( rig.toggled = false; rig.follow.sticky = false; disengage_look(rig, window, cursor_opts); + rig.world_edges.push(false); } else { engage_look(rig, LookButton::Left, focused, window, cursor_opts); rig.toggled = true; + rig.world_edges.push(true); } } @@ -1023,20 +1252,20 @@ pub(super) fn run_look_session( // that ends mouselook (`0x514b70` → `0x50f940`), so the session becomes that channel's. let held = [LookButton::Right, LookButton::Left] .into_iter() - .find(|&b| rig.world_mouse.channel(b)); + .find(|&b| holds(b)); if let Some(b) = held { rig.toggled = false; rig.look = Some(b); } } else if let Some(active) = rig.look { - if !rig.world_mouse.channel(active) { + if !holds(active) { // Hand off to the other channel if it is held, as the reference keeps turning; a // button the UI holds never fired its binding. let other = match active { LookButton::Right => LookButton::Left, LookButton::Left => LookButton::Right, }; - if rig.world_mouse.channel(other) { + if holds(other) { rig.look = Some(other); } else { // The last mouse bit's release, `0x514b70` → `0x50f940(extra)` (`0x514c48`): the @@ -1044,27 +1273,33 @@ pub(super) fn run_look_session( // bit (`0x50f958`/`0x50f95d`). A release no binding ran hands 0. rig.follow.sticky = release_sticky.unwrap_or(false); disengage_look(rig, window, cursor_opts); + rig.world_edges.push(false); } } } else { - // `WorldMouse` has already dropped a press over the UI, the dev overlay or outside the - // viewport. Right-drag turns. - if rig.world_mouse.down(LookButton::Right) { - engage_look(rig, LookButton::Right, focused, window, cursor_opts); - } else if rig.world_mouse.turn() { - // `MouselookStart` with no button: the channel's rise enters the same freelook - // (`0x514840` → `0x51491f`). - engage_look(rig, LookButton::Right, focused, window, cursor_opts); - } else if rig.world_mouse.down(LookButton::Left) && !inspect_enabled { - // Left-drag orbits, engaged on the press like right (`0x51491f`), a cursor-payload - // world drop included. While the inspector is armed, left belongs to it. - engage_look(rig, LookButton::Left, focused, window, cursor_opts); + // Only the first primary press enters freelook (`0x51490a` → `0x51491f`), and one made + // inside its call entered there ([`LookSteps`]): here a call's with no host lent, the + // rise of a bit still held, the TurnOrAction bit's first (`0x51490c` tests `al,0x3`). + // A bit held across a leave enters nothing. Left orbits; while the inspector is armed, + // left belongs to it. + let first = |b: LookButton| { + let other = 1 - b as usize; + primaries.rose[b as usize] && !(primaries.held[other] && !primaries.rose[other]) + }; + let entry = owed + .filter(|&b| holds(b)) + .or_else(|| first(LookButton::Right).then_some(LookButton::Right)) + .or_else(|| (first(LookButton::Left) && !inspect_enabled).then_some(LookButton::Left)) + .filter(|&b| holds(b)); + if let Some(b) = entry { + engage_look(rig, b, focused, window, cursor_opts); + rig.world_edges.push(true); } } // Look rotation; a right-drag also turns the character. let mut handed = false; - if let Some(active) = rig.look { + if rig.look.is_some() { let delta = motion; let d_yaw = -delta.x * yaw_rate; cam.yaw += d_yaw; @@ -1087,14 +1322,13 @@ pub(super) fn run_look_session( ) { cam.pitch = (cam.pitch + d_pitch).clamp(-CAM_PITCH_LIMIT, CAM_PITCH_LIMIT); } - if active == LookButton::Right || both_buttons { + // The hand-off to the body behind the TurnOrAction bit (`0x5145fa`), which a both-button + // run holds too. + if holds(LookButton::Right) { *face_yaw = cam.yaw; handed = motion != Vec2::ZERO; } } - // Freelook is right-held mouse-look or a both-button run, which steers like it; a left-drag - // orbit is not. This test and the `face_yaw` sync above must stay alike. - rig.freelook = rig.look == Some(LookButton::Right) || (rig.look.is_some() && both_buttons); handed } @@ -1173,6 +1407,18 @@ fn sync_look_focus( } } +impl CameraControl { + /// The ground lean's hand-off to the pitch (`0x50d500` push, `0x50d520` pop): every freelook + /// entry pushes (`0x50fe72`, `0x50fe79`) and every leave pops (`0x50fde6`, `0x50fded`), a + /// left orbit's as a right drag's. + pub(super) fn hand_off_ground_pitch(&mut self, cam: &mut FlyCam) { + let handed = self.terrain_tilt.hand_off(self.look.is_some()); + if handed != 0.0 { + cam.pitch = (cam.pitch + handed).clamp(-CAM_PITCH_LIMIT, CAM_PITCH_LIMIT); + } + } +} + /// Seat the camera on whatever it orbits: our own body, or the far-sight subject `PLAYER_FARSIGHT` /// names (Mind Vision, Sentry Totem, Mind Control), substituting the orbit centre, sweep origin and /// pivot target before [`seat_camera`]. Both of the controller's seat paths call it, as far sight @@ -1260,13 +1506,10 @@ pub(super) fn seat_on_subject( &dynamics.options, dt, ); - // The mouse-look hand-off (`0x50d500` push, `0x50d520` pop), after the channel steps; the - // reference fires it from the input handler, at most one frame of channel motion apart (a - // fortieth of a degree at `cameraGroundSmoothSpeed`). - let handed = rig.terrain_tilt.hand_off(rig.freelook); - if handed != 0.0 { - cam.pitch = (cam.pitch + handed).clamp(-CAM_PITCH_LIMIT, CAM_PITCH_LIMIT); - } + // The mouse-look hand-off, after the channel steps; the reference fires it from the input + // handler, at most one frame of channel motion apart (a fortieth of a degree at + // `cameraGroundSmoothSpeed`). + rig.hand_off_ground_pitch(cam); // `cameraBobbing`: the session runs whatever the CVar says and only its output is gated. It // reads the zoom, not the collided arm, as the reference's first conjunct is `[cam+0xec]`: a @@ -1625,21 +1868,6 @@ fn apply_self_fade_to_descendants( } } -/// True if the OS pointer is over the world camera's viewport (the whole window when it has none). -fn cursor_in_viewport(window: &Window, camera: &Camera) -> bool { - let Some(cursor) = window.physical_cursor_position() else { - return false; - }; - match &camera.viewport { - Some(vp) => { - let min = vp.physical_position.as_vec2(); - let max = min + vp.physical_size.as_vec2(); - cursor.x >= min.x && cursor.y >= min.y && cursor.x < max.x && cursor.y < max.y - } - None => true, - } -} - /// Free-fly (pre-connect or detached): WASD in the camera basis, Space/C up and down, Ctrl 5×. /// [`super::control`] parks the mover first, so the wire never extrapolates a phantom walk. pub(super) fn fly_free( @@ -2188,20 +2416,22 @@ mod tests { assert_eq!(pitched, plain, "neither cancelled nor restarted"); } - /// A right-click the UI took (a Who-list row) sets no mouse bit in the camera's command word, - /// so it cannot arm Smart's `Turn` row, an immediate return; pinned from the latch to the row. + /// A right-click the UI took (a Who-list row) runs no binding, so it sets no mouse bit in the + /// camera's command word and cannot arm Smart's `Turn` row, an immediate return; pinned from + /// the bit to the row. #[test] fn a_press_the_ui_ate_never_reaches_the_camera_command_word() { let word = |world_press: bool| { - let mut rig = CameraControl::default(); - let mut buttons = ButtonInput::::default(); - buttons.press(MouseButton::Right); - rig.world_mouse.update(&buttons, |_| world_press); + let mut binds = crate::bindings::BindingsState::default(); + if world_press { + binds.apply_unhosted(benilla_ui::script::BindingInput::Start( + benilla_ui::script::HeldInput::TurnOrAction, + )); + } super::super::input::look_input( - &crate::bindings::BindingsState::default(), + &binds, &super::super::Player::default(), &super::super::MoverLock::default(), - &rig, ) .follow_command }; @@ -2229,54 +2459,6 @@ mod tests { assert_eq!(FollowStyle::Smart.row(FollowState::Turn), (0.0, 1.0)); } - /// A button is claimed at its down edge and held to its own release, so the UI arriving under - /// the locked cursor cannot drop it; a chord's second button joins the held gesture. - #[test] - fn the_world_holds_a_button_from_its_press_to_its_release() { - let mut rig = CameraControl::default(); - let mut buttons = ButtonInput::::default(); - - // Pressed over a UI row: never claimed, and no amount of later frames claims it. - buttons.press(MouseButton::Right); - rig.world_mouse.update(&buttons, |_| false); - assert!(!rig.world_mouse.held(LookButton::Right)); - buttons.clear(); - rig.world_mouse.update(&buttons, |_| true); - assert!( - !rig.world_mouse.held(LookButton::Right), - "a press the UI ate is never handed back mid-hold" - ); - buttons.release(MouseButton::Right); - buttons.clear(); - - // Pressed in the world: claimed, and it survives the UI arriving under the locked cursor. - buttons.press(MouseButton::Right); - rig.world_mouse.update(&buttons, |_| true); - assert!(rig.world_mouse.down(LookButton::Right)); - buttons.clear(); - rig.world_mouse.update(&buttons, |_| false); - assert!(rig.world_mouse.held(LookButton::Right)); - assert!( - !rig.world_mouse.down(LookButton::Right), - "the edge is one frame" - ); - - // The chord's second button joins the gesture the world already holds… - buttons.press(MouseButton::Left); - rig.world_mouse.update(&buttons, |_| true); - assert!( - rig.world_mouse.both(), - "both primaries = the both-button run" - ); - - // …and the release ends it, including a cover's synthetic one (emptied button planes). - buttons = ButtonInput::::default(); - rig.world_mouse.update(&buttons, |_| false); - assert!(!rig.world_mouse.both()); - assert!(!rig.world_mouse.held(LookButton::Right)); - assert!(!rig.world_mouse.held(LookButton::Left)); - } - /// The classifier (`0x510960`) reads the camera's command word, not the character's velocity, /// and its priority order decides when several states hold. #[test] diff --git a/crates/benilla-app/src/player/camera/mouselook_tests.rs b/crates/benilla-app/src/player/camera/mouselook_tests.rs index b743add53..f5c38cea1 100644 --- a/crates/benilla-app/src/player/camera/mouselook_tests.rs +++ b/crates/benilla-app/src/player/camera/mouselook_tests.rs @@ -1,9 +1,12 @@ //! `MouselookStart`/`MouselookStop` against the look session: the latch and the session run as the //! frame runs them, with the VM's calls in between. -use benilla_ui::script::UiScript; +use benilla_ui::script::{BindingInput, HeldInput, UiScript}; use bevy::ecs::system::RunSystemOnce; use bevy::math::DVec2; +use bevy::window::PrimaryWindow; + +use crate::bindings::{BindingsState, Input}; use super::super::camera_dynamics::{CameraOptions, SubjectState}; use super::*; @@ -24,12 +27,13 @@ fn look_frame( cam: Single<&mut FlyCam>, window: Single<(&mut Window, &mut CursorOptions), With>, mut hand: ResMut, + binds: Option>, ) { let (mut window, mut opts) = window.into_inner(); let focused = window.focused; let mut cam = cam.into_inner(); let hand = &mut *hand; - let both = rig.world_mouse.both(); + let primaries = binds.as_deref().map(Primaries::of).unwrap_or_default(); let dynamics = DynamicsInput { options: CameraOptions::default(), smooth_style: FollowStyle::default(), @@ -40,7 +44,6 @@ fn look_frame( }; hand.handed = run_look_session( &motion, - both, &mut rig, &mut cam, &mut hand.face_yaw, @@ -51,6 +54,10 @@ fn look_frame( LookConfig::default(), &dynamics, focused, + primaries, + binds + .as_deref() + .is_some_and(|b| super::super::input::command_word(b) != 0), ); } @@ -73,17 +80,39 @@ fn world(over_ui: bool) -> World { let mut window = Window::default(); window.set_physical_cursor_position(Some(DVec2::new(100.0, 100.0))); world.spawn((window, CursorOptions::default(), PrimaryWindow)); - world.insert_non_send_resource(UiScript::new().unwrap()); + // The interface: the `WorldFrame` under everything and, `over_ui`, a frame under the cursor. + let mut script = UiScript::new().unwrap(); + script.set_screen_size(1024.0, 768.0); + script + .run(r#"WorldFrame = CreateFrame("WorldFrame", "WorldFrame") WorldFrame:SetAllPoints()"#) + .unwrap(); + if over_ui { + script + .run( + r#"F = CreateFrame("Frame", "F") + F:SetPoint("BOTTOMLEFT", 50, 50) F:SetWidth(100) F:SetHeight(100) F:EnableMouse(true)"#, + ) + .unwrap(); + } + script.resolve(); + script.mouse_move(AT.0, AT.1); + world.insert_non_send_resource(script); + world.init_resource::(); world } +/// The cursor in the interface's units. +const AT: (f32, f32) = (100.0, 100.0); + /// One frame with the mouse moved by `dx` pixels: the latch, then the session, then the input /// planes age as bevy's do. fn frame(world: &mut World, dx: f32) { world.resource_mut::().delta = Vec2::new(dx, 0.0); world.run_system_once(latch_world_mouse).unwrap(); world.run_system_once(look_frame).unwrap(); + world.run_system_once(focus_on_look_edges).unwrap(); world.resource_mut::>().clear(); + world.resource_mut::().next_frame_for_test(); } /// The OS gives the window focus or takes it. @@ -120,12 +149,28 @@ fn looking(world: &World) -> bool { world.resource::().is_looking() } -fn is_mouselooking(world: &World) -> bool { - world - .non_send_resource::() - .eval::>("return IsMouselooking()") - .unwrap() - == Some(1) +/// `f` on the VM with the look's live reads lent, as the host lends them: the bindings' bit and +/// the camera's freelook. +fn with_look_reads(world: &mut World, f: impl FnOnce(&mut UiScript) -> R) -> R { + struct Lent<'a, 'w>(&'a mut super::LookLive<'w>); + impl benilla_ui::script::LiveReader for Lent<'_, '_> { + fn read_live(&mut self, ask: &mut benilla_ui::script::live::LiveAsk<'_>) -> bool { + crate::script_calls::live::LiveFamily::answer(self.0, ask) + } + } + let mut script = world.remove_non_send_resource::().expect("a VM"); + let mut state = bevy::ecs::system::SystemState::::new(world); + let mut live = state.get(world); + let r = script.reading(&mut Lent(&mut live), f); + world.insert_non_send_resource(script); + r +} + +/// `IsMouselooking()` as a script reads it: the bindings' bit. +fn is_mouselooking(world: &mut World) -> bool { + with_look_reads(world, |s| { + s.eval::>("return IsMouselooking()").unwrap() + }) == Some(1) } fn yaw(world: &mut World) -> f32 { @@ -140,12 +185,74 @@ fn cursor(world: &mut World) -> CursorOptions { .clone() } -fn press(world: &mut World, b: MouseButton) { - world.resource_mut::>().press(b); +/// The stock binding of a button run as the world frame's slot runs it, with no host lent: `BUTTON1` +/// runs `CAMERAORSELECTORMOVE`, `BUTTON2` `TURNORACTION`, and the bodies' calls reach the bindings' +/// state as the dispatch's tail hands them over. +fn bound(world: &mut World, b: MouseButton, down: bool) { + let body = match (b, down) { + (MouseButton::Left, true) => "CameraOrSelectOrMoveStart()", + (MouseButton::Left, false) => "CameraOrSelectOrMoveStop()", + (_, true) => "TurnOrActionStart()", + (_, false) => "TurnOrActionStop()", + }; + let inputs = { + let mut script = world.non_send_resource_mut::(); + script.run_binding(body).unwrap(); + script.take_binding_input() + }; + let mut binds = world.resource_mut::(); + for input in inputs { + binds.apply_unhosted(input); + } } +/// The interface's walk of a button record at the cursor, as the input records' feed runs it: +/// where it went ([`benilla_ui::script::PointerTarget`]). +fn walk(world: &mut World, b: MouseButton, down: bool) -> benilla_ui::script::PointerTarget { + let name = match b { + MouseButton::Left => "LeftButton", + _ => "RightButton", + }; + with_look_reads(world, |s| s.mouse_button_to(AT.0, AT.1, name, down)) +} + +/// The buttons whose press ran the stock binding, as the dispatch latches them. +#[derive(Resource, Default)] +struct Latched(Vec); + +/// A button goes down, the interface walks it, and the world frame runs the stock binding with no +/// host lent when the press went to it: the press's target, the frame holding a button else the +/// hover (`0x76637f`), or in freelook the world frame (`0x492bd9`). A press the feed consumed +/// ahead of the walk (`PlayerUiPressConsumed`) runs nothing. +fn press(world: &mut World, b: MouseButton) { + use benilla_ui::script::PointerTarget; + world.resource_mut::>().press(b); + let consumed = world + .get_resource::() + .is_some_and(|c| c.0); + let target = walk(world, b, true); + if !consumed && target == PointerTarget::World { + bound(world, b, true); + world.get_resource_or_init::().0.push(b); + } +} + +/// A button comes up, the interface walks it, and the stock binding's up-half runs as the +/// dispatch runs it: for a press it latched unless a frame took the release, and for none when +/// the release went to the world frame, in freelook through the hook (`0x492be5`). fn release(world: &mut World, b: MouseButton) { + use benilla_ui::script::PointerTarget; world.resource_mut::>().release(b); + let target = walk(world, b, false); + let latched = { + let mut latched = world.get_resource_or_init::(); + let was = latched.0.contains(&b); + latched.0.retain(|&l| l != b); + was + }; + if target != PointerTarget::Ui && (latched || target == PointerTarget::World) { + bound(world, b, false); + } } /// The right button's session, entered with no button: the mouse turns the camera and the body @@ -154,7 +261,7 @@ fn release(world: &mut World, b: MouseButton) { fn mouselook_start_turns_the_camera_and_the_character_with_no_button_held() { let mut w = world(false); frame(&mut w, 0.0); - assert!(!is_mouselooking(&w)); + assert!(!is_mouselooking(&mut w)); lua(&mut w, "MouselookStart()"); frame(&mut w, 40.0); @@ -164,7 +271,6 @@ fn mouselook_start_turns_the_camera_and_the_character_with_no_button_held() { Some(LookButton::Right), "the right button's session" ); - assert!(rig.freelook); let turned = yaw(&mut w); assert!(turned < 0.0, "the mouse turns the camera: {turned}"); assert_eq!( @@ -175,7 +281,7 @@ fn mouselook_start_turns_the_camera_and_the_character_with_no_button_held() { let c = cursor(&mut w); assert_eq!(c.grab_mode, CursorGrabMode::Locked); assert!(!c.visible); - assert!(is_mouselooking(&w)); + assert!(is_mouselooking(&mut w)); // It holds with no button while the mouse keeps moving. frame(&mut w, 40.0); @@ -183,6 +289,34 @@ fn mouselook_start_turns_the_camera_and_the_character_with_no_button_held() { assert!(w.resource::().is_looking()); } +/// A freelook the session enters outside any call, a `MouselookStart` made with no host lent, +/// moves the mouse focus to the world frame right after it (`0x493085`), and its leave has the +/// hover picked again (`0x4930a0`), so the VM's next update gives it back. +#[test] +fn a_freelook_entered_at_the_frame_moves_the_mouse_focus_and_its_leave_gives_it_back() { + let mut w = world(true); + let focus = |w: &mut World| { + w.non_send_resource::() + .eval::("return GetMouseFocus():GetName()") + .unwrap() + }; + assert_eq!(focus(&mut w), "F"); + lua(&mut w, "MouselookStart()"); + assert_eq!( + focus(&mut w), + "F", + "the call made no entry with no host lent" + ); + frame(&mut w, 0.0); + assert!(looking(&w)); + assert_eq!(focus(&mut w), "WorldFrame"); + lua(&mut w, "MouselookStop()"); + frame(&mut w, 0.0); + assert!(!looking(&w)); + w.non_send_resource_mut::().tick(0.0); + assert_eq!(focus(&mut w), "F"); +} + /// A right press over bare world that the UI consumed, as a layout-mode Alt press is /// (`0x766353`, before any frame sees it), turns nothing; the same press unconsumed turns. #[test] @@ -236,7 +370,70 @@ fn mouselook_stop_ends_the_session() { let c = cursor(&mut w); assert_eq!(c.grab_mode, CursorGrabMode::None); assert!(c.visible); - assert!(!is_mouselooking(&w)); + assert!(!is_mouselooking(&mut w)); +} + +/// A freelook a call enters and leaves inside it ([`LookSteps::call`]) hands the OS cursor at the +/// frames after: the session locks and hides it, then frees it and puts it back where the look +/// began. +#[test] +fn a_freelook_left_inside_its_call_gives_the_cursor_back_at_the_frame() { + use benilla_ui::script::LookCall; + let call = |w: &mut World, c: LookCall| { + w.run_system_once(move |mut steps: LookSteps| steps.call(c)) + .unwrap() + }; + let mut w = world(false); + let began = pointer(&mut w); + assert!(call(&mut w, LookCall::Mouselook(true)).entered); + frame(&mut w, 0.0); + let c = cursor(&mut w); + assert_eq!(c.grab_mode, CursorGrabMode::Locked); + assert!(!c.visible); + w.query::<&mut Window>() + .single_mut(&mut w) + .unwrap() + .set_cursor_position(Some(Vec2::new(10.0, 10.0))); + + call(&mut w, LookCall::Mouselook(false)); + assert!(!looking(&w), "left inside the call"); + frame(&mut w, 0.0); + let c = cursor(&mut w); + assert_eq!(c.grab_mode, CursorGrabMode::None); + assert!(c.visible); + assert_eq!(pointer(&mut w), began, "back where the look began"); +} + +/// A key bound to `TurnOrAction` holds the bit with no button down: the freelook its press entered +/// inside its call ([`LookSteps::bound`]) lasts through the frame's session while the binding holds +/// the bit (`[InputControl+4] & 1`), and ends with its release. +#[test] +fn a_freelook_a_bound_key_holds_lasts_with_no_button_down() { + let mut w = world(false); + w.insert_resource(BindingsState::after_calls( + vec![], + vec![BindingInput::Start(HeldInput::TurnOrAction)], + )); + let entered = w + .run_system_once(|mut steps: LookSteps| { + let start = BindingInput::Start(HeldInput::TurnOrAction); + steps.bound(start, PrimaryBits::default()) + }) + .unwrap() + .entered; + assert!(entered); + // The session takes the cursor, then the mouse turns the camera. + frame(&mut w, 0.0); + frame(&mut w, 40.0); + assert!(looking(&w), "the bound bit holds the session"); + assert_ne!(yaw(&mut w), 0.0, "and the mouse turns the camera"); + + w.insert_resource(BindingsState::after_calls( + vec![BindingInput::Start(HeldInput::TurnOrAction)], + vec![BindingInput::Stop(HeldInput::TurnOrAction)], + )); + frame(&mut w, 0.0); + assert!(!looking(&w), "its release ends it"); } /// CustomNameplates' steer: a right press a plate took calls `MouselookStart`, and the button's @@ -255,18 +452,75 @@ fn the_right_release_ends_a_mouselook_its_press_started_on_the_ui() { lua(&mut w, "MouselookStart()"); frame(&mut w, 40.0); assert_eq!(w.resource::().look, Some(LookButton::Right)); - assert!(is_mouselooking(&w)); + assert!(is_mouselooking(&mut w)); release(&mut w, MouseButton::Right); frame(&mut w, 0.0); assert_eq!(w.resource::().look, None); - assert!(!is_mouselooking(&w)); + assert!(!is_mouselooking(&mut w)); assert!( left_click_arms(&mut w), "the release freed the command's bit" ); } +/// The interface under the cursor changes: `chunk` runs, and the hover walks the cursor again. +fn reshape(world: &mut World, chunk: &str) { + let mut script = world.non_send_resource_mut::(); + script.run(chunk).unwrap(); + script.resolve(); + script.mouse_move(AT.0, AT.1); +} + +/// A right drag's bit outlives a frame appearing under the locked cursor, and the chord's second +/// button joins the drag there: the world frame holds the press, so the left press goes to it +/// (`0x76637f`), not to the frame under the cursor, and runs its binding, the both-button run. +#[test] +fn a_frame_appearing_under_a_drag_neither_ends_it_nor_takes_the_chord() { + let mut w = world(false); + press(&mut w, MouseButton::Right); + frame(&mut w, 0.0); + assert_eq!(w.resource::().look, Some(LookButton::Right)); + reshape( + &mut w, + r#"PRESSED = 0 + F = CreateFrame("Frame", "F") + F:SetPoint("BOTTOMLEFT", 50, 50) F:SetWidth(100) F:SetHeight(100) F:EnableMouse(true) + F:SetScript("OnMouseDown", function() PRESSED = PRESSED + 1 end)"#, + ); + frame(&mut w, 40.0); + frame(&mut w, 40.0); + assert!(looking(&w), "the drag outlives the frame"); + assert!(w.resource::().pressed(Input::TurnOrAction)); + press(&mut w, MouseButton::Left); + frame(&mut w, 0.0); + assert!( + w.resource::().steering(), + "the chord joined the drag" + ); + let pressed = w + .non_send_resource::() + .eval::("return PRESSED") + .unwrap(); + assert_eq!(pressed, 0, "the frame under the cursor saw no press"); +} + +/// A press while a frame holds a button goes to that frame (`0x76637f`), wherever the cursor is: +/// a right press over the world after a left press went to a frame runs no binding. +#[test] +fn a_press_while_a_frame_holds_a_button_goes_to_that_frame() { + let mut w = world(true); + press(&mut w, MouseButton::Left); + reshape( + &mut w, + "F:ClearAllPoints() F:SetPoint(\"BOTTOMLEFT\", 500, 500)", + ); + press(&mut w, MouseButton::Right); + frame(&mut w, 40.0); + assert!(!looking(&w)); + assert!(!w.resource::().pressed(Input::TurnOrAction)); +} + /// Whether a left press's `CameraOrSelectOrMoveStart` arms a world click, which it does only with /// neither primary bit held (`0x51481a`). fn left_click_arms(w: &mut World) -> bool { @@ -290,7 +544,7 @@ fn the_cover_ends_a_scripted_mouselook() { w.insert_resource(crate::loading_screen::LoadingScreen::test_covering()); frame(&mut w, 0.0); assert_eq!(w.resource::().look, None); - assert!(!is_mouselooking(&w)); + assert!(!is_mouselooking(&mut w)); assert!(left_click_arms(&mut w), "the cover cleared the bit"); } @@ -327,7 +581,7 @@ fn a_session_survives_focus_loss(start: impl Fn(&mut World)) { Some(LookButton::Right), "the session outlives the focus" ); - assert!(is_mouselooking(&w)); + assert!(is_mouselooking(&mut w)); let c = cursor(&mut w); assert_eq!(c.grab_mode, CursorGrabMode::None, "the OS pointer is free"); assert!(c.visible); @@ -351,7 +605,7 @@ fn a_session_survives_focus_loss(start: impl Fn(&mut World)) { ); frame(&mut w, 40.0); assert!(yaw(&mut w) < before, "and the mouse turns the view again"); - assert!(is_mouselooking(&w)); + assert!(is_mouselooking(&mut w)); } #[test] @@ -382,7 +636,7 @@ fn mouselook_stop_while_unfocused_ends_it_and_the_focus_takes_nothing_back() { lua(&mut w, "MouselookStop()"); frame(&mut w, 0.0); assert_eq!(w.resource::().look, None); - assert!(!is_mouselooking(&w)); + assert!(!is_mouselooking(&mut w)); assert_eq!(pointer(&mut w), Some(away), "no warp back to the stash"); focus(&mut w, true); @@ -405,10 +659,39 @@ fn mouselook_stop_ends_a_right_drag() { lua(&mut w, "MouselookStop()"); frame(&mut w, 0.0); assert_eq!(w.resource::().look, None); - assert!(!is_mouselooking(&w)); + assert!(!is_mouselooking(&mut w)); release(&mut w, MouseButton::Right); frame(&mut w, 0.0); - assert!(!is_mouselooking(&w)); + assert!(!is_mouselooking(&mut w)); +} + +/// The right drag's bit is the one `MouselookStop` and `ToggleMouseMove` act on, inside their +/// calls, with `BUTTON2` bound to `TURNORACTION`: the stop clears it and leaves (`0x514240` → +/// `0x514b70` → `0x514c48`), and a toggle leaves with the bit still held. Neither is entered again +/// while the button stays down: only the first primary press enters (`0x51490a`). +#[test] +fn a_right_drag_left_inside_a_call_is_not_entered_again_while_held() { + use benilla_ui::script::LookCall; + let call = |w: &mut World, c: LookCall| { + w.run_system_once(move |mut steps: LookSteps| steps.call(c)) + .unwrap() + }; + for leave in [LookCall::Mouselook(false), LookCall::ToggleMouseMove] { + let mut w = world(false); + press(&mut w, MouseButton::Right); + frame(&mut w, 0.0); + assert!(looking(&w), "{leave:?}: the drag entered"); + + assert!(call(&mut w, leave).left, "{leave:?}: left inside the call"); + frame(&mut w, 40.0); + frame(&mut w, 40.0); + assert!(!looking(&w), "{leave:?}: the held button enters nothing"); + release(&mut w, MouseButton::Right); + frame(&mut w, 0.0); + press(&mut w, MouseButton::Right); + frame(&mut w, 0.0); + assert!(looking(&w), "{leave:?}: the next press enters"); + } } /// `MouselookStart` under a left drag sets the other primary channel: the both-button run and its @@ -425,9 +708,12 @@ fn mouselook_start_under_a_left_drag_is_the_both_button_run() { w.resource_mut::().delta = Vec2::new(40.0, 0.0); w.run_system_once(latch_world_mouse).unwrap(); { - let wm = &w.resource::().world_mouse; - assert!(wm.both(), "both channels held"); - assert!(wm.rose(), "the transition into the run (0x514a73)"); + let binds = w.resource::(); + assert!(binds.steering(), "both primary bits held"); + assert!( + binds.steering_began(), + "the transition into the run (0x514a73)" + ); } w.run_system_once(look_frame).unwrap(); w.resource_mut::>().clear(); @@ -445,20 +731,31 @@ fn mouselook_start_under_a_left_drag_is_the_both_button_run() { } /// `ToggleMouseMove` with no button enters mouselook (`0x50f910` → `0x50f930`): the cursor locks, -/// the mouse turns the camera and not the body, since the hand-off wants the TurnOrAction bit -/// (`0x5145e0`), and `IsMouselooking` still answers nil. It lasts with no button until the next -/// call leaves it (`0x50f940(0)`). +/// and `IsMouselooking` still answers nil. With nothing held the command word is empty, and the +/// motion handler turns nothing (`0x51440c`); a key held, W here, gives the word a bit, and the +/// mouse turns the camera and not the body, since the hand-off wants the TurnOrAction bit +/// (`0x5145e0`). It lasts with no button until the next call leaves it (`0x50f940(0)`). #[test] -fn toggle_mouse_move_turns_the_camera_alone_until_toggled_back() { +fn toggle_mouse_move_turns_the_camera_alone_under_a_held_command_until_toggled_back() { let mut w = world(false); lua(&mut w, "ToggleMouseMove()"); frame(&mut w, 0.0); assert!(looking(&w)); assert_eq!(cursor(&mut w).grab_mode, CursorGrabMode::Locked); frame(&mut w, 100.0); - assert!(yaw(&mut w) != 0.0, "the camera turns"); + assert_eq!(yaw(&mut w), 0.0, "an empty command word turns nothing"); + let held = { + let mut script = w.non_send_resource_mut::(); + script.run_binding("MoveForwardStart()").unwrap(); + script.take_binding_input() + }; + for input in held { + w.resource_mut::().apply_unhosted(input); + } + frame(&mut w, 100.0); + assert!(yaw(&mut w) != 0.0, "W held, the camera turns"); assert_eq!(w.resource::().face_yaw, 0.0, "the body does not"); - assert!(!is_mouselooking(&w)); + assert!(!is_mouselooking(&mut w)); frame(&mut w, 0.0); assert!(looking(&w), "no button is needed to stay"); lua(&mut w, "ToggleMouseMove()"); @@ -547,10 +844,11 @@ fn a_mouselook_start_after_the_latch_reaches_the_frames_controller() { w.run_system_once(look_frame).unwrap(); lua(&mut w, "MouselookStart()"); w.run_system_once(apply_late_look_calls).unwrap(); - let wm = &w.resource::().world_mouse; + let binds = w.resource::(); assert!( - wm.turn() && wm.rose() && wm.late_rise(), - "the controller reads the channel risen after its session" + binds.just_pressed(Input::TurnOrAction) + && w.resource::().world_mouse.late_rise(), + "the controller reads the bit risen after its session" ); w.resource_mut::>().clear(); frame(&mut w, 40.0); @@ -572,3 +870,64 @@ fn a_toggle_after_the_session_reaches_the_next_one() { frame(&mut w, 0.0); assert!(looking(&w), "the toggle entered mouselook"); } + +/// A left orbit is freelook as a right drag is (`[cam+0x90] & 1`, `0x50fe41`): its entry hands the +/// ground's lean into the pitch (`0x50fe72`, `0x50fe79`) and its leave takes it back (`0x50fde6`, +/// `0x50fded`), so the view holds still across both. +#[test] +fn a_left_orbit_hands_the_ground_lean_into_the_pitch_and_back() { + let mut w = world(false); + frame(&mut w, 0.0); + let options = CameraOptions { + terrain_tilt: true, + ..CameraOptions::default() + }; + let moving = SubjectState { + move_flags: crate::creature_anim::move_flags::FORWARD, + ..SubjectState::default() + }; + { + let mut rig = w.resource_mut::(); + for _ in 0..900 { + rig.terrain_tilt.advance( + || 0.5, + true, + &moving, + FollowStyle::Smart, + &options, + 1.0 / 60.0, + ); + } + } + let lean = w.resource::().terrain_tilt.pitch(); + assert!(lean > 0.0, "uphill leans the view: {lean}"); + let pitch = |w: &mut World| w.query::<&FlyCam>().single(w).unwrap().pitch; + let hand_off = |w: &mut World| { + w.resource_scope(|w, mut rig: Mut| { + let mut cam = w.query::<&mut FlyCam>().single_mut(w).unwrap(); + rig.hand_off_ground_pitch(&mut cam); + }); + }; + hand_off(&mut w); + let level = pitch(&mut w); + + press(&mut w, MouseButton::Left); + frame(&mut w, 0.0); + assert_eq!(w.resource::().look, Some(LookButton::Left)); + hand_off(&mut w); + assert!( + (pitch(&mut w) - (level + lean)).abs() < 1.0e-6, + "the entry pushes the lean into the pitch" + ); + assert_eq!(w.resource::().terrain_tilt.pitch(), 0.0); + + release(&mut w, MouseButton::Left); + frame(&mut w, 0.0); + assert_eq!(w.resource::().look, None); + hand_off(&mut w); + assert!( + (pitch(&mut w) - level).abs() < 1.0e-6, + "the leave pops it back out" + ); + assert_eq!(w.resource::().terrain_tilt.pitch(), lean); +} diff --git a/crates/benilla-app/src/player/camera_axes.rs b/crates/benilla-app/src/player/camera_axes.rs index 2545dfb2c..7509e0260 100644 --- a/crates/benilla-app/src/player/camera_axes.rs +++ b/crates/benilla-app/src/player/camera_axes.rs @@ -11,13 +11,15 @@ use super::camera_zoom::CAM_DIST_MIN; /// `0x511550`), a quarter of the yaw's 0.001 (`0x801360` at `0x51149b`): degrees a second × 0.25. const PITCH_RATE_SCALE: f32 = 0.25; -/// One axis: `[cam+0x128]` bit `2i` (active) and `2i+1` (stopping), and whether its start time is -/// this frame's, so the first tick moves nothing (`now − [cam+0x12c + 4i]`). +/// One axis: `[cam+0x128]` bit `2i` (active) and `2i+1` (stopping), whether its start time is +/// this frame's, so the first tick moves nothing (`now − [cam+0x12c + 4i]`), and the seconds left +/// to its queued end (`[cam+0x15c + 4i]`), which a zoom sets. #[derive(Clone, Copy, Default, Debug)] struct Axis { active: bool, stopping: bool, fresh: bool, + queued: Option, } /// The six axes, indexed as [`ViewAxis`]. @@ -31,6 +33,29 @@ impl ViewAxes { let a = &mut self.0[axis as usize]; a.active = true; a.fresh = true; + a.queued = None; + } + + /// `CameraZoomIn`/`Out` (`0x50fc60`, `0x50fcd0`) on the distance axes: `yards` at `speed`, in + /// whole milliseconds (`0x50fc6c`-`0x50fc79`), the opposite axis stopped first (`0x50fc83`), + /// then added to the axis's queued end while it runs toward one (`0x50fca9`), else the axis + /// started with that end (`0x50fcbe` → `0x50fd40`), none for a zero span (`0x50fd80`). + pub(super) fn zoom(&mut self, out: bool, yards: f32, speed: f32) { + let (axis, other) = if out { + (ViewAxis::Out, ViewAxis::In) + } else { + (ViewAxis::In, ViewAxis::Out) + }; + let secs = (yards / speed * 1000.0).trunc() / 1000.0; + self.stop(other); + let a = &mut self.0[axis as usize]; + match a.queued { + Some(left) if a.active => a.queued = Some(left + secs), + _ => { + self.start(axis); + self.0[axis as usize].queued = (secs != 0.0).then_some(secs); + } + } } /// `0x50fd90(axis, now)`: on an active axis, set the stopping bit and the end time. @@ -52,6 +77,18 @@ impl ViewAxes { } } + /// Whether `axis` is active, its bit `2i` of `[cam+0x128]`. + #[cfg(test)] + pub(super) fn active(&self, axis: ViewAxis) -> bool { + self.0[axis as usize].active + } + + /// Whether `axis` is stopping, its bit `2i + 1`. + #[cfg(test)] + pub(super) fn stopping(&self, axis: ViewAxis) -> bool { + self.0[axis as usize].stopping + } + /// Whether any axis is active, the reference's `[cam+0x128] != 0` (`0x50ea48`). fn any(&self) -> bool { self.0.iter().any(|a| a.active) @@ -59,13 +96,22 @@ impl ViewAxes { /// Each active axis's seconds this tick, clearing the ones that stop: a continuing axis runs /// the frame, one started this frame runs nothing yet, and a stopping one runs to its end - /// time, then both bits clear (`0x511372`-`0x5113a0`, `max(end − start, 0)`). + /// time, then both bits clear (`0x511372`-`0x5113a0`, `max(end − start, 0)`). A queued end + /// reached stops its axis at the tick (`0x511341`-`0x511359`), which then runs whole. fn advance(&mut self, dt: f32) -> [f32; 6] { let mut secs = [0.0; 6]; for (a, s) in self.0.iter_mut().zip(&mut secs) { if !a.active { continue; } + if let Some(left) = a.queued.as_mut() { + if !a.fresh { + *left -= dt; + } + if *left <= 0.0 { + a.stopping = true; + } + } *s = if a.fresh { 0.0 } else { dt }; a.fresh = false; if a.stopping { @@ -215,6 +261,34 @@ mod tests { assert!(!r.view_axes.any()); } + /// A zoom queues its span on its distance axis (`0x50fc60`): 1 yd at 8.33 yd/s is 120 ms, + /// truncated (`0x50fc79`), and the axis stops at the first tick past it, which runs whole + /// (`0x511359`). A zoom the opposite way stops it first (`0x50fc83`): of `In` then `Out` in + /// one frame, the camera moves out alone. A second zoom the same way adds to the span + /// (`0x50fca9`). + #[test] + fn a_zoom_runs_its_axis_for_its_span_and_stops_the_opposite_one() { + let speed = 8.33; + let tick = |r: &mut CameraControl, c: &mut FlyCam| { + for _ in 0..10 { + super::tick(r, c, 0.05, LookConfig::default(), speed, 15.0); + } + }; + let (mut r, mut c) = (rig(10.0), cam()); + r.view_axes.zoom(false, 1.0, speed); + r.view_axes.zoom(true, 1.0, speed); + tick(&mut r, &mut c); + // The start tick runs nothing; the 0.12 s queued ends at the third tick after it. + assert!((r.target_distance - (10.0 + 3.0 * 0.05 * speed)).abs() < 1e-4); + assert!(!r.view_axes.any(), "both axes ended"); + + let (mut r, mut c) = (rig(10.0), cam()); + r.view_axes.zoom(true, 1.0, speed); + r.view_axes.zoom(true, 1.0, speed); + tick(&mut r, &mut c); + assert!((r.target_distance - (10.0 + 5.0 * 0.05 * speed)).abs() < 1e-4); + } + /// The Lua pairs reach the axes through the bindings' frame state, in call order. #[test] fn the_move_view_calls_reach_the_axes() { diff --git a/crates/benilla-app/src/player/camera_dynamics.rs b/crates/benilla-app/src/player/camera_dynamics.rs index 4b94aea9a..3f13e0845 100644 --- a/crates/benilla-app/src/player/camera_dynamics.rs +++ b/crates/benilla-app/src/player/camera_dynamics.rs @@ -62,7 +62,10 @@ pub(crate) struct CameraOptions { /// Applies a camera option CVar change. An out-of-range smooth speed, tilt time or bob rate never /// arrives: the registry refuses it as the reference's `0x50b330` does /// ([`benilla_ui::script::CvarCheck`]), and a saved one stands without firing. -pub(crate) fn on_cvar(ev: On, mut opts: ResMut) { +pub(crate) fn on_cvar( + ev: &crate::cvars::CvarChanged, + mut opts: bevy::prelude::Mut<'_, CameraOptions>, +) { let v = ev.num(); match ev.key().as_str() { "camerapivot" => opts.pivot = v != 0.0, diff --git a/crates/benilla-app/src/player/camera_saved.rs b/crates/benilla-app/src/player/camera_saved.rs index 33d5d8ab2..effa5bf8c 100644 --- a/crates/benilla-app/src/player/camera_saved.rs +++ b/crates/benilla-app/src/player/camera_saved.rs @@ -183,14 +183,14 @@ pub(super) fn plugin(app: &mut App) { app.init_resource::() .add_systems( Update, - // Before the controller, so the first in-world frame renders the restored pose. A - // capture resolves no state path, so this is inert there. + // Ahead of the frame's input records and packets: the reference reads the file as the + // world frame constructs its camera at the interface load (`0x481b4e` → `0x50c0e0`, + // `LoadSettings 0x50c5a0` at `0x50c3ea`), before any listener, and `SaveView` reads + // what it restores inside its call (`0x50fa30`). A capture resolves no state path, so + // this is inert there. load_camera_pose - .after(super::ControlRestore) + .before(crate::ui_script::UiInput) .before(super::control) - // And before the script calls after the packets, which read the player it - // restores; the restore follows the create, a packet. - .before(crate::vm_pass::VmPass::Resume) .in_set(InWorldGated), ) .add_systems(OnExit(ClientState::InWorld), save_on_session_end); diff --git a/crates/benilla-app/src/player/camera_view.rs b/crates/benilla-app/src/player/camera_view.rs index 594973c84..f99c6eaec 100644 --- a/crates/benilla-app/src/player/camera_view.rs +++ b/crates/benilla-app/src/player/camera_view.rs @@ -198,115 +198,119 @@ fn load_saved_views(cvars: Res, mut views: ResMut { - views: ResMut<'w, CameraViews>, - rig: ResMut<'w, CameraControl>, +pub(crate) struct ViewSteps<'w, 's> { + views: Option>, + rig: Option>, + /// `cameraDistanceMoveSpeed`, the zoom's rate (`[0xbe0fbc]+0x24`, `0x50fc63`). + zoom: Option>, cam: Query<'w, 's, &'static mut FlyCam, With>, - player: Res<'w, Player>, + player: Option>, + /// Capture parks the camera itself; a view must not move it. + capture: Option>, } -/// Drain the Lua queue into the rig, before [`super::control`] seats this frame's camera. -fn drain_view_requests( - mut hosted_vm: crate::script_calls::HostedVm, - mut cvars: ResMut, - mut targets: ViewTargets, -) { - hosted_vm.run(|script| { - let Some(script) = script else { - return; - }; - let requests = script.take_camera_view_requests(); - if requests.is_empty() { - return; +impl ViewSteps<'_, '_> { + /// `MoveView*Start`/`Stop` inside the call (`0x50b4b0` → `0x50fd40`, `0x50b4e0` → `0x50fd90`): + /// the axis's bits on the rig, which the camera's update runs (`0x5112d0`). + pub(crate) fn move_axis(&mut self, axis: benilla_ui::script::ViewAxis, start: bool) { + if let Some(rig) = self.rig.as_deref_mut() { + rig.view_axes.apply(&[(axis, start)]); } - let Ok(mut cam) = targets.cam.single_mut() else { - return; // no camera: a silent drop, as the reference's `0x4818f0` miss - }; - let face_yaw = targets.player.facing(); - // Written to the CVars after the batch: the slots a save or reset moved, and the live - // index. - let mut write_slots: Vec = Vec::new(); - let mut write_active = false; + } - for request in requests { - match request { - CameraViewRequest::Set(n) => { - write_active |= apply( - &mut targets.views, - &mut targets.rig, - &mut cam, - face_yaw, - usize::from(n), - ); + /// `CameraZoomIn`/`Out(yards)` inside the call (`0x50b400` → `0x50fc60`, `0x50b450` → + /// `0x50fcd0`): the distance axis queued for the yards' span on the rig. + pub(crate) fn zoom(&mut self, out: bool, yards: f32) { + let speed = self.zoom.as_deref().map_or_else( + || super::camera_zoom::ZoomLimit::default().move_speed, + |z| z.move_speed, + ); + if let Some(rig) = self.rig.as_deref_mut() { + rig.view_axes.zoom(out, yards, speed); + } + } + + /// Apply `request`, and the CVar writes it makes, `(name, value)` in order, for the registry + /// to take inside the same call. + pub(crate) fn apply(&mut self, request: CameraViewRequest) -> Vec<(&'static str, String)> { + let mut writes = Vec::new(); + if self.capture.is_some() { + return writes; + } + let (Some(views), Some(rig), Some(player)) = ( + self.views.as_deref_mut(), + self.rig.as_deref_mut(), + self.player.as_deref(), + ) else { + return writes; + }; + let Ok(mut cam) = self.cam.single_mut() else { + return writes; // no camera: a silent drop, as the reference's `0x4818f0` miss + }; + let face_yaw = player.facing(); + let mut write_slot = None; + let mut write_active = false; + match request { + CameraViewRequest::Set(n) => { + write_active = apply(views, rig, &mut cam, face_yaw, usize::from(n)); + } + CameraViewRequest::Save(n) => { + let view = usize::from(n); + views.save( + view, + ViewPose { + // The target zoom, not the collision-pulled arm (`cam+0x198`). + distance: rig.target_distance, + pitch: cam.pitch, + yaw: wrap_pi(cam.yaw - face_yaw), + }, + ); + write_slot = Some(view); + } + CameraViewRequest::Reset(n) => { + let view = usize::from(n); + if views.reset(view) { + write_active = apply(views, rig, &mut cam, face_yaw, view); } - CameraViewRequest::Save(n) => { - let view = usize::from(n); - targets.views.save( - view, - ViewPose { - // The target zoom, not the collision-pulled arm (`cam+0x198`). - distance: targets.rig.target_distance, - pitch: cam.pitch, - yaw: wrap_pi(cam.yaw - face_yaw), - }, - ); - write_slots.push(view); - } - CameraViewRequest::Reset(n) => { - let view = usize::from(n); - if targets.views.reset(view) { - apply( - &mut targets.views, - &mut targets.rig, - &mut cam, - face_yaw, - view, - ); - } - write_slots.push(view); - } - CameraViewRequest::Next | CameraViewRequest::Prev => { - let forward = request == CameraViewRequest::Next; - if let Some(view) = targets.views.step(forward) { - write_active |= apply( - &mut targets.views, - &mut targets.rig, - &mut cam, - face_yaw, - view, - ); - } - } - CameraViewRequest::FlipYaw(degrees) => { - // `cam[+0x100] += arg * pi/180` (`0x50b6a0`). The reference keeps the flip in - // its own yaw field, added outside the follow channel (`0x50f7de`), so it - // survives re-centring; the rig has one yaw, so auto-follow reels the flip back - // in on Smart and Always. - cam.yaw = wrap_pi(cam.yaw + degrees.to_radians()); + write_slot = Some(view); + } + CameraViewRequest::Next | CameraViewRequest::Prev => { + let forward = request == CameraViewRequest::Next; + if let Some(view) = views.step(forward) { + write_active = apply(views, rig, &mut cam, face_yaw, view); } } - } - - // Mirror into the registry so the change reaches `config.toml`. - for view in write_slots { - // A reset writes the default string verbatim, so the diff-shaped file drops the key. - let reset_to_default = targets.views.pose(view) == ViewPose::shipped(view); - let rendered = targets.views.pose(view).to_reference(); - for field in 0..3 { - let value = if reset_to_default { - VIEW_DEFAULTS[view][field] - } else { - rendered[field].as_str() - }; - cvars.set(VIEW_CVARS[view][field], value); + CameraViewRequest::FlipYaw(degrees) => { + // `cam[+0x100] += arg * pi/180` (`0x50b6a0`). The reference keeps the flip in its + // own yaw field, added outside the follow channel (`0x50f7de`), so it survives + // re-centring; the rig has one yaw, so auto-follow reels the flip back in on Smart + // and Always. + cam.yaw = wrap_pi(cam.yaw + degrees.to_radians()); } } if write_active { - cvars.set(CVAR_ACTIVE_VIEW, &targets.views.current.to_string()); + writes.push((CVAR_ACTIVE_VIEW, views.current.to_string())); } - }) + if let Some(view) = write_slot { + // A reset writes the default string verbatim, so the diff-shaped file drops the key. + let reset_to_default = views.pose(view) == ViewPose::shipped(view); + let rendered = views.pose(view).to_reference(); + for field in 0..3 { + let value = if reset_to_default { + VIEW_DEFAULTS[view][field].to_string() + } else { + rendered[field].clone() + }; + writes.push((VIEW_CVARS[view][field], value)); + } + } + writes + } } /// Seat one view; the distance glides through `target_distance`. `true` when the live index moved. @@ -327,22 +331,91 @@ fn apply( pub(super) fn plugin(app: &mut App) { app.init_resource::() // After the config load, so the persisted views are in before anything selects one. - .add_systems(Startup, load_saved_views.after(crate::cvars::CvarLoad)) - .add_systems( - Update, - drain_view_requests - // After the Lua tick that queues them, before the control pass seats the pose. - .in_set(crate::ui_script::UiDrain) - .before(super::control) - // Capture parks the camera itself; a queued view must not move it. - .run_if(not(resource_exists::)), - ); + .add_systems(Startup, load_saved_views.after(crate::cvars::CvarLoad)); } #[cfg(test)] mod tests { use super::*; + /// `SetView` writes `cameraView` inside its call (`0x512f17`) and `SaveView` the view's three + /// fields (`0x50fa09`), so the chunk's next line reads both: view 4's distance is the rig's + /// target after the set, and the save stores it into view 3. Main drained the views after the + /// chunk and read the defaults. + #[test] + fn a_view_verbs_cvar_writes_read_on_the_chunks_next_line() { + let mut app = crate::game_plugins::schedule_tests::headless_client(); + app.insert_resource(bevy::ecs::error::DefaultErrorHandler( + bevy::ecs::error::ignore, + )); + let (tx, _rx) = crossbeam_channel::unbounded(); + app.insert_resource(crate::net::NetCommands(tx)); + app.update(); + app.insert_non_send_resource(benilla_ui::script::UiScript::new().expect("a VM")); + app.insert_resource(State::new(crate::client_state::ClientState::InWorld)); + app.update(); + app.update(); + let cams = app + .world_mut() + .query_filtered::<(), (With, With)>() + .iter(app.world()) + .count(); + assert_eq!(cams, 1, "the world camera"); + let (active, distance): (String, String) = + crate::script_calls::with_hosted_vm(app.world_mut(), |s| { + s.expect("a VM").eval( + "SetView(4) SaveView(3) return GetCVar('cameraView'), GetCVar('cameraDistanceB')", + ) + }) + .expect("the chunk runs"); + assert_eq!(active, "3"); + assert_eq!(distance, "13.880000"); + } + + /// `MoveViewLeftStart()` sets its axis's bit on the camera inside the call (`0x50b540` → + /// `0x50b4b0` → `0x50fd40`), so the call returns with the axis running and the camera's next + /// update moves it (`0x5112d0`). Main left an edge for the frame's controller. + #[test] + fn a_move_view_call_starts_its_axis_inside_the_call() { + use benilla_ui::script::ViewAxis; + let mut app = crate::game_plugins::schedule_tests::headless_client_unrun(); + let (tx, _rx) = crossbeam_channel::unbounded(); + app.insert_resource(crate::net::NetCommands(tx)); + app.world_mut().init_resource::(); + app.insert_non_send_resource(benilla_ui::script::UiScript::new().expect("a VM")); + let left = |app: &mut App, chunk: &str| { + crate::script_calls::with_hosted_vm(app.world_mut(), |s| s.expect("a VM").run(chunk)) + .expect("the chunk runs"); + app.world() + .resource::() + .view_axes + .active(ViewAxis::Left) + }; + assert!( + left(&mut app, "MoveViewLeftStart()"), + "running as it returns" + ); + assert!( + app.world() + .resource::() + .view_calls() + .is_empty(), + "nothing waits for the frame" + ); + // A zoom stops the opposite axis inside its call (`0x50fc83`): of `In` then `Out`, the + // in axis returns stopping and the out axis running, its span queued. + crate::script_calls::with_hosted_vm(app.world_mut(), |s| { + s.expect("a VM").run("CameraZoomIn(1) CameraZoomOut(1)") + }) + .expect("the chunk runs"); + let axes = &app.world().resource::().view_axes; + assert_eq!( + (axes.stopping(ViewAxis::In), axes.active(ViewAxis::Out)), + (true, true), + "both set as the call returns" + ); + } + #[test] fn each_shipped_view_lands_its_recorded_pose() { // (Lua arg, distance yd, pitch in degrees down-positive), from `0x84f488`. diff --git a/crates/benilla-app/src/player/camera_zoom.rs b/crates/benilla-app/src/player/camera_zoom.rs index 80054c478..63a889213 100644 --- a/crates/benilla-app/src/player/camera_zoom.rs +++ b/crates/benilla-app/src/player/camera_zoom.rs @@ -1,5 +1,6 @@ //! The zoom: the orbit distance's range, from `cameraDistanceMax` × `cameraDistanceMaxFactor` -//! under the reference's 0 and 50 yd bounds, and the wheel's glide to the chosen distance. +//! under the reference's 0 and 50 yd bounds, and the distance's glide to its target. The zoom +//! verbs themselves run the distance axis ([`super::camera_axes`]). use bevy::prelude::*; @@ -24,8 +25,6 @@ const CAM_DISTANCE_MAX_FACTOR_DEFAULT: f32 = 1.0; /// anything else, NaN included (`fcom` unordered sets C0), is refused and the old value stands. pub(crate) const CAM_DISTANCE_MAX_RANGE: std::ops::RangeInclusive = CAM_DIST_MIN..=CAM_DIST_MAX; -/// Yards per wheel notch, the stock bindings' `CameraZoomIn(1.0)` (`Bindings.xml:707`). -const CAM_ZOOM_STEP: f32 = 1.0; /// Zoom speed in yd/s, `cameraDistanceMoveSpeed`'s default "8.33" (`0x50b7f3`): the reference runs /// the distance axis at this constant speed (`0x5112d0`), not an ease. const CAM_MOVE_SPEED: f32 = 8.33; @@ -99,23 +98,12 @@ fn orbit_limit(distance_max: f32, factor: f32) -> f32 { } } -/// Wheel zoom, run every frame: `CAMERAZOOMIN`/`OUT` move the target, and the distance glides to it -/// at a constant `cameraDistanceMoveSpeed` (`speed`), as the reference's does. `scroll` is this -/// frame's net zoom-in in notches (positive is closer). `max` is [`ZoomLimit::max`], CVar-fed, so -/// it bounds by `max`/`min`, never `f32::clamp`, which panics on a NaN or inverted bound. -pub(super) fn apply_zoom_scroll( - scroll: f32, - dt: f32, - rig: &mut CameraControl, - max: f32, - speed: f32, -) { - if scroll != 0.0 { - rig.target_distance = (rig.target_distance - scroll * CAM_ZOOM_STEP) - .max(CAM_DIST_MIN) - .min(max); - } - // Re-clamp every frame, so lowering the max-distance slider pulls the camera in. +/// The distance's glide, run every frame after the axes (`0x5112d0`, which move the target, the +/// zoom's among them): the target held to the limit, so lowering the max-distance slider pulls +/// the camera in, and the distance easing to it at a constant `cameraDistanceMoveSpeed` +/// (`speed`), as after a view's seat. `max` is [`ZoomLimit::max`], CVar-fed, so it bounds by +/// `max`/`min`, never `f32::clamp`, which panics on a NaN or inverted bound. +pub(super) fn glide_zoom(dt: f32, rig: &mut CameraControl, max: f32, speed: f32) { rig.target_distance = rig.target_distance.min(max); let max_step = speed * dt; rig.distance += (rig.target_distance - rig.distance).clamp(-max_step, max_step); @@ -178,6 +166,21 @@ mod tests { assert!(z.set_distance_max(50.0) && z.max == 50.0); } + /// The zoom through the distance axis it queues (`0x50fc60`, `0x50fcd0`), ticked whole. + fn zoom(rig: &mut CameraControl, out: bool, yards: f32, max: f32) { + rig.view_axes.zoom(out, yards, CAM_MOVE_SPEED); + let mut cam = super::super::camera::FlyCam { + yaw: 0.0, + pitch: 0.0, + speed: 0.0, + }; + let look = super::super::LookConfig::default(); + for _ in 0..200 { + super::super::camera_axes::tick(rig, &mut cam, 0.1, look, CAM_MOVE_SPEED, max); + glide_zoom(0.1, rig, max, CAM_MOVE_SPEED); + } + } + #[test] fn a_nan_factor_zooms_without_panicking() { let mut z = ZoomLimit::default(); @@ -187,22 +190,23 @@ mod tests { distance: 10.0, ..default() }; - apply_zoom_scroll(-1.0, 0.1, &mut rig, z.max, CAM_MOVE_SPEED); - assert_eq!(rig.target_distance, 11.0); + zoom(&mut rig, true, 1.0, z.max); + assert!(rig.target_distance > 10.0, "{}", rig.target_distance); // Even a NaN bound handed straight in bounds nothing and panics nowhere. - apply_zoom_scroll(-1.0, 0.1, &mut rig, f32::NAN, CAM_MOVE_SPEED); - assert_eq!(rig.target_distance, 12.0); + zoom(&mut rig, true, 1.0, f32::NAN); + assert!(rig.target_distance > 11.0, "{}", rig.target_distance); } #[test] fn the_wheel_stops_at_the_limit() { let mut rig = CameraControl { target_distance: 44.5, + distance: 44.5, ..default() }; - apply_zoom_scroll(-1.0, 0.1, &mut rig, limit(15.0, 3.0), CAM_MOVE_SPEED); + zoom(&mut rig, true, 1.0, limit(15.0, 3.0)); assert_eq!(rig.target_distance, 45.0); - apply_zoom_scroll(1000.0, 0.1, &mut rig, 45.0, CAM_MOVE_SPEED); + zoom(&mut rig, false, 1000.0, 45.0); assert_eq!(rig.target_distance, CAM_DIST_MIN); } } diff --git a/crates/benilla-app/src/player/controller.rs b/crates/benilla-app/src/player/controller.rs index 9458e68aa..9d337316f 100644 --- a/crates/benilla-app/src/player/controller.rs +++ b/crates/benilla-app/src/player/controller.rs @@ -39,7 +39,7 @@ pub(super) fn body_gates( self_driven: bool, pending: &super::StandPending, lock: &super::MoverLock, - view_subject: &view_subject::ViewSubject, + far_sight: &view_subject::FarSight, ) -> BodyGates { let (stunned, dead, stand_byte) = store .map(|s| { @@ -56,14 +56,12 @@ pub(super) fn body_gates( stand_byte }; // The shared precondition `0x5144e0`, once per tick. Its far-sight conjunct, - // `!(IsActivePlayer(mover) && [mover+0x1c70] & 1)`, reads the resolved subject (`0x5ee290` - // latches only once resolved) and spares a possessed mover, which sets the same field. + // `!(IsActivePlayer(mover) && [mover+0x1c70] & 1)` (`0x514537`, `0x514540`), reads the latch, + // not the camera: a field naming an object no longer held puts the camera home and keeps the + // bit (`0x5ee324`-`0x5ee360`). It spares a possessed mover, which sets the same field. let mover = state::MoverInput { dead, - view_is_out: state::view_is_out( - lock.foreign_mover.is_none(), - view_subject.remote.is_some(), - ), + view_is_out: state::view_is_out(lock.foreign_mover.is_none(), far_sight.on()), }; BodyGates { stunned, @@ -133,7 +131,8 @@ pub(super) fn sample_look( gates: ( Res, Res, - Res, + // The far-sight latch, the input tick's far-sight term. + Res, Res, // The loading cover blanks input at the source; a gesture in flight is unwound below. Res, @@ -160,11 +159,8 @@ pub(super) fn sample_look( return; }; let (mut window, mut cursor_opts) = window.into_inner(); - let (inspect, binds, view_subject, scoped) = (&gates.0, &gates.1, &gates.2, &gates.3); - let input::LookInput { - both_buttons, - follow_command, - } = input::look_input(binds, &player, &lock, &rig); + let (inspect, binds, far_sight, scoped) = (&gates.0, &gates.1, &gates.2, &gates.3); + let follow_command = input::look_input(binds, &player, &lock).follow_command; let body = body.single().ok(); let dynamics = dynamics_input( &pointer.3, @@ -186,7 +182,7 @@ pub(super) fn sample_look( gates.6.single().unwrap_or(false), &gates.5, &lock, - view_subject, + far_sight, ); // `0x5145e0`: `0x5145b0` and standing; a turn key stands a seated body up instead. let mouse_turns_body = mover.mouse_may_turn_body(stunned, stand_state); @@ -202,9 +198,9 @@ pub(super) fn sample_look( arm.disarm(); } let focused = window.focused; + let word_held = input::word_held(follow_command, &player); let looked = run_look_session( &pointer.0, - both_buttons, &mut rig, &mut cam, &mut player.face_yaw, @@ -215,6 +211,8 @@ pub(super) fn sample_look( *pointer.1, &dynamics, focused, + camera::Primaries::of(binds), + word_held, ); // The mouse turns the view, but the body hand-off (`0x514474`) skips a body that is stunned, // dead or seated (`0x5145e0`) or not ours to drive (`control_lost`, `reseat`), while the @@ -227,7 +225,7 @@ pub(super) fn sample_look( // The hand-off runs on each motion and on the press that completes both mouse bits, motion or // none (`0x514924`-`0x514966`), behind the same body gate `0x5145e0`. *sample = LookSample { - hands_off: (looked || input::both_engaged(binds, &rig, both_buttons)) + hands_off: (looked || input::both_engaged(binds)) && mouse_turns_body && !lock.control_lost && !lock.reseat, @@ -309,6 +307,10 @@ pub(super) fn control( Option>, // The predicted stand state `[player+0x1d68]`, which the posture verbs write. ResMut, + // The far-sight latch, the input tick's far-sight term. + Res, + // The pitch latch the calls left, which the frame's writes of the latch supersede. + Option>, ), mut commands: Commands, mut player: ResMut, @@ -336,6 +338,13 @@ pub(super) fn control( // Who we drive and whether we may. ResMut, ), + // The auto-move a root ack's tick stops, its release, and where its `AUTOFOLLOW_END` goes. + mut auto_move: ( + Option>, + Option>, + Option>, + Option>, + ), ) { let (world, transports, child_of) = (&world_q.0, &world_q.1, &world_q.2); let Ok((mut cam_t, mut cam)) = cameras.single_mut() else { @@ -380,7 +389,7 @@ pub(super) fn control( let input::LookInput { both_buttons, follow_command, - } = input::look_input(binds, &player, &world_q.6, &rig); + } = input::look_input(binds, &player, &world_q.6); // The word as `0x50fee0` read it in the frame's input, with the facing the input found. let dynamics = dynamics_input( @@ -408,7 +417,7 @@ pub(super) fn control( .is_some_and(|(.., embodied)| embodied), &speed_capsule.11, &world_q.6, - view_subject, + &speed_capsule.12, ); // `0x5145b0` now, for the key turn; its translate sibling waits for this frame's root edge. let may_turn = mover.may_turn(stunned); @@ -435,16 +444,23 @@ pub(super) fn control( && mover.mouse_may_turn_body(stunned, stand_state) && !world_q.6.control_lost && !world_q.6.reseat; + rig.world_mouse.close_late_window(); if late_hand_off { player.face_yaw = cam.yaw; } let hands_off = sample.hands_off || late_hand_off; - // A rebound zoom key steps 1.0 per press, the stock `CameraZoomIn(1.0)` (`Bindings.xml:707`). - let zoom = binds.amount(crate::bindings::Input::CameraZoomIn) - - binds.amount(crate::bindings::Input::CameraZoomOut); - apply_zoom_scroll(zoom, dt, &mut rig, zoom_max, pointer.2.move_speed); - // The `MoveView*` axes, the camera update's `0x5112d0`, after this frame's calls. + // The zooms and the `MoveView*` axes, the camera update's `0x5112d0`, after this frame's + // calls: those made with no host lent here, a lent host's inside them. + for (input, out) in [ + (crate::bindings::Input::CameraZoomIn, false), + (crate::bindings::Input::CameraZoomOut, true), + ] { + if binds.fired(input) { + rig.view_axes + .zoom(out, binds.amount(input), pointer.2.move_speed); + } + } rig.view_axes.apply(binds.view_calls()); camera_axes::tick( &mut rig, @@ -454,6 +470,7 @@ pub(super) fn control( pointer.2.move_speed, zoom_max, ); + glide_zoom(dt, &mut rig, zoom_max, pointer.2.move_speed); // Free fly is a dev tool on the dev chord: a bare `F` is the player's to bind. if crate::run_mode::dev_chord(&keys, KeyCode::KeyF) { @@ -485,6 +502,21 @@ pub(super) fn control( self_seat(&world_q.4), ); let speed_acks = server_moves.speed_acks; + // The root and unroot acks' input tick (`0x60e347`): a mover that may now neither translate + // nor turn takes its teardown leg (`0x5146d6`), so a stun before its root stops the auto-move + // here, at the root's ack. The steer ran ahead of this, so the release applies at once. + if server_moves.input_ticked && mover.torn_down(player.modes.rooted, stunned) { + let (follow, approach, autorun, lane) = &mut auto_move; + super::end_auto_move( + follow.as_deref_mut(), + approach.as_deref_mut(), + autorun.as_deref_mut(), + lane.as_deref_mut(), + ); + if let Some(follow) = follow.as_deref_mut() { + super::follow::release_owed(follow, &mut player, autorun.as_deref()); + } + } // A command press's message that ended the precast ([`super::press`]), with the acks'. let press_precast = std::mem::take(&mut player.press_ended_precast); if let (true, Ok((e, ..))) = (server_moves.precast_ended || press_precast, body.single()) { @@ -571,14 +603,7 @@ pub(super) fn control( info!("mouse: unmapped button Other({n}) — bindings know BUTTON4/BUTTON5 as winit Forward/Back"); } } - let axes = input::move_axes( - binds, - &mut player, - &rig, - both_buttons, - may_translate, - may_turn, - ); + let axes = input::move_axes(binds, &mut player, both_buttons, may_translate, may_turn); let input::MoveAxes { fwd: fwd_axis, side: side_axis, @@ -756,7 +781,7 @@ pub(super) fn control( // The pitch keys: the input tick's pitch emitter (`0x515010`, behind `0x514755` and the // swim test `0x514766`), then the mover's pitch at the pitch rate (`0x7c4f80`), before // the swim mover reads it. - swim::pitch_emitter( + let pitched = swim::pitch_emitter( &mut player, ( binds.pressed(crate::bindings::Input::PitchUp), @@ -766,6 +791,13 @@ pub(super) fn control( may_turn, swimming, ); + // Its run wrote the latch the calls read (`0x5147fa` unable to turn, else `0x515010` + // swimming under no TurnOrAction bit). + if !may_turn || (swimming && follow_command & camera::follow_cmd::RIGHT_MOUSE == 0) { + if let Some(call) = speed_capsule.13.as_deref_mut() { + call.frame_wrote(); + } + } // The integration runs in any mode the bits survive into (`0x7c53b9`), at three quarters // under a direction bit or FALLING (`0x200f`, `0x7c5cb3`). let pitch_integrating = if swimming { @@ -798,6 +830,9 @@ pub(super) fn control( // aim includes the pivot bias, as `0x5103e0` passes `[cam+0x104] + [cam+0xf4]`. if hands_off { swim::hand_off_pitch(&mut player, cam.pitch + rig.smart_pivot.bias()); + if let Some(call) = speed_capsule.13.as_deref_mut() { + call.frame_wrote(); + } } let mut swim_pitch = 0.0_f32; // Pre-step feet Y, the true take-off height: the step already rises one jump tick. @@ -984,7 +1019,9 @@ pub(super) fn control( // The loot window's walk-away, the movement-start guard `0x60e990`: forward, back, strafe, // keyboard turn, pitch and jump close it, mouse-look facing does not, and only for our // own character. - if steering_ourselves && (loot_walk_away(player.move_flags, move_flags_now) || jumped) { + if steering_ourselves + && (loot_walk_away(player.move_flags, move_flags_now) || jumped || pitched) + { net.13 .0 = true; } diff --git a/crates/benilla-app/src/player/controller/tests.rs b/crates/benilla-app/src/player/controller/tests.rs index 4d243a15c..6e0513f1f 100644 --- a/crates/benilla-app/src/player/controller/tests.rs +++ b/crates/benilla-app/src/player/controller/tests.rs @@ -399,10 +399,13 @@ fn a_late_mouselook_start_over_a_left_drag_hands_the_facing_and_pitch_off() { .single_mut(world) .expect("the camera") .yaw = 1.0; - world - .resource_mut::() - .world_mouse - .late_mouselook_start_over_a_left_drag(); + world.resource_scope(|world, mut binds: Mut| { + use benilla_ui::script::LookCall; + binds.apply_unhosted(Start(HeldInput::CameraOrSelectOrMove)); + let mut rig = world.resource_mut::(); + rig.world_mouse + .late_call_for_test(LookCall::Mouselook(true), &mut binds); + }); world.run_system(embody).expect("the embodiment runs"); world.run_system(drive).expect("the controller runs"); let player = client.player(); @@ -732,6 +735,82 @@ fn following(client: &mut Client) -> bool { .is_some() } +/// Far sight on, its object gone: the render's update (`0x483054` → `0x5ee290`) finds the field +/// naming no held object, puts the camera back on the player and returns with the bit still set +/// (`0x5ee324`-`0x5ee360`), so the input tick's precondition still refuses (`0x514540`): a forward +/// press starts nothing, though the camera is home. +#[test] +fn a_lost_far_sight_object_keeps_the_input_torn_down() { + use crate::player::{FarSight, ViewSubject}; + use benilla_protocol::field::FIELD_UNIT_HEALTH; + /// `PLAYER_FARSIGHT`, the guid's low word. + const FARSIGHT: u16 = 712; + const EYE: u64 = 0xF130_0000_0000_0043; + let mut client = Client::standing(Body::Own); + let world = client.app.world_mut(); + let me = world.resource::().0[&ME]; + world.entity_mut(me).insert(crate::net::ObjectStore( + benilla_protocol::ObjectFields::from_pairs(&[ + (FIELD_UNIT_HEALTH, 100), + (FARSIGHT, EYE as u32), + (FARSIGHT + 1, (EYE >> 32) as u32), + ]), + )); + let eye = world.spawn(Transform::from_xyz(30.0, 0.0, 0.0)).id(); + world.resource_mut::().0.insert(EYE, eye); + let index = world.resource::(); + world.resource::().start( + Some(EYE), + |g| index.0.contains_key(&g), + world.resource::(), + ); + world.resource_mut::().0.remove(&EYE); + world + .run_system_once(super::super::view_subject::publish_view_subject) + .expect("the render's update runs"); + let far_sight = world.resource::(); + assert!(far_sight.on() && far_sight.camera().is_none()); + assert!( + world.resource::().remote.is_none(), + "the camera is home" + ); + let sent = client.traced(vec![], forward(), |_| {}); + assert!( + !sent + .iter() + .any(|(_, s)| matches!(s, Sent::Move(crate::net::MoveKind::StartForward, _))), + "{sent:?}" + ); +} + +/// A stun that lands before its root: the stun's tick finds the mover free to translate, and the +/// root's ack runs the tick again (`0x60e33d` → `0x60e347`), which now takes the teardown leg +/// (`0x5146d6`): the follow ends and autorun clears at the ack. +#[test] +fn a_root_ack_after_a_stun_ends_the_follow_at_the_ack() { + use benilla_protocol::field::{FIELD_UNIT_FLAGS, FIELD_UNIT_HEALTH}; + let mut client = Client::new(Body::Own, |_| {}); + let world = client.app.world_mut(); + let me = world.resource::().0[&ME]; + world.entity_mut(me).insert(crate::net::ObjectStore( + benilla_protocol::ObjectFields::from_pairs(&[ + (FIELD_UNIT_HEALTH, 100), + (FIELD_UNIT_FLAGS, crate::player::UNIT_FLAG_STUNNED), + ]), + )); + follow(&mut client); + client.frame(vec![], vec![]); + assert!( + following(&mut client), + "a stun alone leaves the mover free to translate" + ); + client.player().autorun = true; + root(client.app.world_mut()); + client.frame(vec![], vec![]); + assert!(!following(&mut client), "the root's ack ends it"); + assert!(!client.player().autorun, "and releases autorun at once"); +} + /// `ToggleAutoRun`'s on press starts the move through `0x60dc60`, whose guard `0x60e990` ends a /// follow; its off press stops through `0x60dc90`, which has no guard, so the follow goes on. #[test] @@ -797,6 +876,96 @@ fn a_strafe_press_while_following_stops_then_strafes() { ); } +/// A `ToggleMouseMove` during a right drag leaves freelook (`0x50f910` → `0x50f940`) and keeps bit +/// 0x1 held, so a turn key strafes (`0x514e98`-`0x514eb1`) and starts no turn (`0x514f6d`): the +/// split reads the command bit, not the look. +#[test] +fn a_turn_key_strafes_under_bit_one_after_a_toggle_left_the_drag() { + use crate::creature_anim::move_flags::STRAFE_LEFT; + use crate::net::MoveKind::StartStrafeLeft; + let mut client = Client::standing(Body::Own); + let right = || vec![Start(HeldInput::TurnOrAction)]; + client.traced(vec![], right(), |_| {}); + assert!(client.app.world().resource::().is_looking()); + // The toggle as a call with no host lent hands it to the session. + client + .app + .world_mut() + .resource_scope(|world, mut rig: Mut| { + let mut binds = world.resource_mut::(); + rig.world_mouse + .late_call_for_test(benilla_ui::script::LookCall::ToggleMouseMove, &mut binds); + }); + let sent = client.traced(right(), vec![Start(HeldInput::TurnLeft)], |_| {}); + assert!( + !client.app.world().resource::().is_looking(), + "the toggle left freelook" + ); + assert_eq!( + sent, + vec![(When::Input, Sent::Move(StartStrafeLeft, STRAFE_LEFT))] + ); +} + +/// A follow ends at the mouse's hand-off to the body, whose facing write reaches the move guard +/// (`0x5103e0` → `0x5152e0` → `0x60de30` → `0x60e990(1, 1)`), behind bit 0x1 (`0x5145fa`): a +/// right press that has not moved the mouse hands nothing off and keeps it, and the first motion +/// ends it. +#[test] +fn a_right_drag_ends_a_follow_at_its_first_motion() { + use bevy::input::mouse::AccumulatedMouseMotion; + let mut client = Client::standing(Body::Own); + let leader = client.app.world_mut().spawn(Transform::default()).id(); + client + .app + .world_mut() + .resource_mut::() + .0 + .insert(0xCC, leader); + follow(&mut client); + let steer = |client: &mut Client| { + client + .app + .world_mut() + .run_system_once(super::super::follow::steer_follow) + .expect("the follow steers"); + }; + let right = || vec![Start(HeldInput::TurnOrAction)]; + client.traced(vec![], right(), |_| {}); + steer(&mut client); + assert!(following(&mut client), "a still press hands nothing off"); + client + .app + .world_mut() + .resource_mut::() + .delta = Vec2::new(10.0, 0.0); + client.traced(right(), vec![], |_| {}); + steer(&mut client); + assert!(!following(&mut client), "the motion's hand-off ended it"); +} + +/// The pitch latch a call left yields to the frame's own writes of it: the mouse hand-off clears +/// the latch (`0x515378`) in a frame whose word did not change, where the press's tick, which takes +/// the calls' latch over only past its changed-word gate, never runs, so the next call reads the +/// cleared latch, not the call's. +#[test] +fn the_mouse_hand_off_supersedes_the_pitch_latch_a_call_left() { + use super::super::press::CallPitch; + use bevy::input::mouse::AccumulatedMouseMotion; + let mut client = Client::standing(Body::Own); + let right = || vec![Start(HeldInput::TurnOrAction)]; + client.traced(vec![], right(), |_| {}); + let world = client.app.world_mut(); + world.resource_mut::().set_for_test(true); + world.resource_mut::().delta = Vec2::new(10.0, 0.0); + client.traced(right(), vec![], |_| {}); + assert_eq!( + client.app.world().resource::().called(), + None, + "the hand-off's clear is the latch the calls read" + ); +} + /// A move key while seated: the forward emitter stands the body (`0x514e0c` → `0x5ed430`, sent at /// once) before it queues the start (`0x514e6e`). #[test] @@ -817,6 +986,31 @@ fn a_move_key_while_seated_stands_before_it_starts() { ); } +/// The tick runs in the air: its translate predicate tests root alone (`0x514560` tests `0x1200`, +/// not the fall bit `0x2000`), so a key pressed while falling runs its emitter's start, whose +/// `0x60e990` closes the loot at the press (`0x60dc6a`) and ends a follow, before the frame time. +#[test] +fn a_move_key_in_the_air_closes_the_loot_and_ends_a_follow_at_the_press() { + let mut client = Client::new(Body::Own, |_| {}); + client.frame(vec![], vec![]); + assert!( + client.player().move_flags & crate::creature_anim::move_flags::FALLING != 0, + "falling through the empty world" + ); + follow(&mut client); + let world = client.app.world_mut(); + world.resource_mut::().0 = false; + *world.resource_mut::() = BindingsState::after_calls(vec![], forward()); + for system in [client.sample, client.commands, client.cancel, client.press] { + world.run_system(system).expect("the press runs"); + } + assert!( + world.resource::().0, + "the loot closes at the press" + ); + assert!(!following(&mut client), "and the follow ends there"); +} + /// The press cancels a cast that movement interrupts at once (`0x51512a` → `0x6e4940`, sent at /// `0x6e49ab`), before its tick queues the start: the cancel goes out first, once. #[test] diff --git a/crates/benilla-app/src/player/embody.rs b/crates/benilla-app/src/player/embody.rs index 39b14b31b..45f455695 100644 --- a/crates/benilla-app/src/player/embody.rs +++ b/crates/benilla-app/src/player/embody.rs @@ -15,8 +15,6 @@ use bevy::prelude::*; -use super::approach::Approach; -use super::follow::FollowState; use crate::creature_anim::MovementState; use crate::net::{ActiveMover, Embodied, GuidIndex, RemoteMotion, SelfGuid, SelfPlayer}; @@ -25,8 +23,6 @@ use crate::net::{ActiveMover, Embodied, GuidIndex, RemoteMotion, SelfGuid, SelfP pub(super) fn maintain_embodiment( mut commands: Commands, mut lock: ResMut, - mut follow: ResMut, - mut approach: ResMut, guids: (Res, Res), self_body: Query>, attached: Query>, @@ -47,10 +43,9 @@ pub(super) fn maintain_embodiment( if want_guid.is_some() { // `Player` holds the old body's pose; the controller adopts the new one's first. lock.reseat = true; - // `SetActiveMover` `0x6006e0` cancels click-to-move and follow on the outgoing mover, - // through `0x6103a0` → `0x60fb60(0, 1)`. - follow.stop(); - approach.stop(); + // `SetActiveMover` `0x6006e0` cancels click-to-move and follow on the outgoing mover + // (`0x600742`), inside the control update's handler + // ([`crate::player::AutoMoveStop::stop_mover`]). } } @@ -94,8 +89,6 @@ mod tests { let mut app = App::new(); app.init_resource::() .init_resource::() - .init_resource::() - .init_resource::() .init_resource::() .init_resource::() .add_systems(Update, maintain_embodiment); diff --git a/crates/benilla-app/src/player/follow.rs b/crates/benilla-app/src/player/follow.rs index f00fe3d95..26abd12cf 100644 --- a/crates/benilla-app/src/player/follow.rs +++ b/crates/benilla-app/src/player/follow.rs @@ -14,7 +14,16 @@ //! The reference's turn-away cancel (160°-220°, `0x80c604`, `0x80c600`) runs only while drunk, //! gated at `0x610a3d` on the drunk fraction, armed as the turn converges and disarmed at random //! (`0x61092e`); it is not built. The start gate (who may be followed) is -//! [`crate::target::by_name`]'s. +//! [`crate::target::by_name`]'s, and the start signals `AUTOFOLLOW_BEGIN` inside its call +//! (`0x610071`, [`crate::script_calls::ScriptCallHost`]). +//! +//! Every end goes through the canceller `0x60fb60`, which signals `AUTOFOLLOW_END` for a follow +//! first (`0x60fb76`-`0x60fb84`), where the end runs ([`end`]): the packet handlers' ends at their +//! packets ([`super::AutoMoveStop`]), the input's and the steer's at their place in the frame. +//! +//! Deviation: every end signals `END`, because the reference's three silent ends are a bug: two +//! writers reset the follow mode cell `0xc4d888` directly (`0x5fb646`, `0x60396f`), leaving a +//! stale guid at `0xc4d980`, and the canceller's early-out (`0x60fb70`) fires nothing. use std::f32::consts::PI; @@ -22,7 +31,6 @@ use bevy::prelude::*; use crate::net::GuidIndex; -use super::camera::{CameraControl, LookButton}; use super::state::{MoveSpeed, Player}; /// Follow's turn rate in rad/s, its own (`0xc4d93c`, seeded at `0x6111f9`), not the keyboard's. @@ -51,6 +59,10 @@ pub(crate) struct FollowState { pub(crate) name: String, /// The band's latch: the synthesized forward input is held. moving: bool, + /// A packet's auto-move stop owes its forward release (`0x60e7f0`): it clears autorun + /// (`0x514630`, [`super::press::CallAutorun::clear`]) behind its `AUTOFOLLOW_END`, and the + /// frame's steer ([`steer_follow`]) applies the bit the calls left before the controller's step. + release_owed: bool, /// `WOW_FOLLOW_TRACE` bookkeeping: the last trace line's time and position. traced_at: f64, traced_pos: Option, @@ -66,6 +78,17 @@ impl FollowState { self.traced_pos = None; } + /// Owe the forward release of an auto-move a packet stopped ([`super::end_auto_move`]). + pub(crate) fn owe_release(&mut self) { + self.release_owed = true; + } + + /// Whether a stop owes the frame its release, for a test. + #[cfg(test)] + pub(crate) fn owes_release(&self) -> bool { + self.release_owed + } + /// Stop following; `true` if we were. pub(crate) fn stop(&mut self) -> bool { self.moving = false; @@ -73,9 +96,27 @@ impl FollowState { } } -/// A start-following request: the chat input's `/follow`, or the UI's `FollowUnit`/`FollowByName`. -/// A name finds players only; the start gate refuses a creature either way. -#[derive(bevy::ecs::message::Message, Clone, Debug)] +/// The canceller's follow leg (`0x60fb60`): a follow in flight signals `AUTOFOLLOW_END` (`0x60fb84`) +/// on the notice lane at the caller's place, then ends (`0x60fc1e`); `true` if one ended. With no +/// lane, in a harness without the unit feed, it ends silently. +pub(crate) fn end( + follow: &mut FollowState, + lane: Option<&mut crate::field_watch::NoticeLane>, +) -> bool { + if follow.guid.is_none() { + return false; + } + if let Some(lane) = lane { + lane.write(crate::field_watch::FieldNotice::Global { + id: crate::field_watch::id::AUTOFOLLOW_END, + }); + } + follow.stop() +} + +/// A start-following request: `FollowUnit` or `FollowByName`. A name finds players only; the start +/// gate refuses a creature either way. +#[derive(Clone, Debug)] pub(crate) enum FollowRequest { /// `FollowUnit(unit)`; a bare `/follow` is `FollowUnit("target")`. Unit(String), @@ -104,15 +145,17 @@ fn should_move(was_moving: bool, distance: f32, speed: f32) -> bool { } /// `move_start` and `autorun_engaged` are key-down edges (the stop emitters and autorun's off edge, -/// `0x60dc90`, have no guard call); `mouse_look` is a level, re-entering the guard every frame. +/// `0x60dc90`, have no guard call); `hand_off` is the mouse's hand-off to the body, whose facing +/// write reaches the guard (`0x5103e0` → `0x5152e0` → `0x60de30` → `0x60e990(1, 1)`) on each +/// motion that turns the body: behind the TurnOrAction bit (`0x5145fa`), not the look. fn follow_cancelled( move_start: bool, autorun_engaged: bool, both_engaged: bool, - mouse_look: bool, + hand_off: bool, lost_mover: bool, ) -> bool { - move_start || autorun_engaged || both_engaged || mouse_look || lost_mover + move_start || autorun_engaged || both_engaged || hand_off || lost_mover } /// Wrap an angle into `[-π, π)`. @@ -150,20 +193,20 @@ pub(super) struct FollowInput<'w, 's> { buttons: Res<'w, ButtonInput>, /// The movement commands' press edges, wherever bound; typing in chat does not reach them. binds: Res<'w, crate::bindings::BindingsState>, - /// The mouse-look level, read a frame behind `control`, so its cancel lands a frame after the - /// reference's; the world's mouse buttons are current ([`super::camera::latch_world_mouse`] - /// runs first). - rig: Res<'w, CameraControl>, + /// The mouse's hand-off to the body this frame ([`super::LookSample`]), written by the look + /// session ahead of this; absent in a harness without the mouse, which hands nothing off. + sample: Option>, /// The mover's descriptor block, for the cancel terms that are state: health and stun. mover: Query<'w, 's, &'static crate::net::ObjectStore, With>, - /// What the camera orbits, for the far-sight term; possibly a frame behind its publisher. - view_subject: Res<'w, super::view_subject::ViewSubject>, + /// The far-sight latch, the input tick's far-sight term (`0x514540`). + far_sight: Res<'w, super::view_subject::FarSight>, /// Whether we drive our own body. lock: Res<'w, super::MoverLock>, } impl FollowInput<'_, '_> { - /// The press edge of any of the six movement commands; turn and strafe both cancel. + /// The press edge of any of the six movement commands; turn and strafe both cancel. A call's + /// own edge ran its start's stop inside it ([`super::press::TickLegs`]). fn move_start(&self) -> bool { use crate::bindings::Input; [ @@ -175,7 +218,7 @@ impl FollowInput<'_, '_> { Input::StrafeRight, ] .iter() - .any(|&c| self.binds.just_pressed(c)) + .any(|&c| self.binds.just_pressed(c) && !self.binds.settled(c)) } /// The cancel set, the start emitters' `0x60e990` and the input tick's teardown, which end any @@ -183,15 +226,17 @@ impl FollowInput<'_, '_> { pub(super) fn cancels(&self, player: &Player) -> bool { // The world's buttons, not the device's: the both-button run is two bindings held, and a // press a UI frame captured dispatches neither. - let both_engaged = self.rig.world_mouse.both() && self.rig.world_mouse.rose(); + let both_engaged = super::input::both_engaged(&self.binds); follow_cancelled( self.move_start(), // The on edge only, as the start reaches the guard (`0x60dc60` → `0x60e990`) and the // stop does not (`0x60dc90`): the press toggled `autorun` first ([`super::press`]), // so the flag is the post-toggle value. - self.buttons.just_pressed(MouseButton::Forward) && player.autorun, + self.buttons.just_pressed(MouseButton::Forward) + && player.autorun + && !self.binds.settled(crate::bindings::Input::ToggleAutoRun), both_engaged, - self.rig.look == Some(LookButton::Right), + self.sample.as_deref().is_some_and(|s| s.hands_off), // The teardown leg, or the body handed to a server spline; the ride term is not one of // the reference's conjuncts (`0x5144e0`), and its reference side is untraced. self.input_torn_down(player.modes.rooted, self.lock.foreign_mover.is_none()) @@ -206,10 +251,7 @@ impl FollowInput<'_, '_> { self.mover.single().is_ok_and(|s| { super::state::MoverInput { dead: s.0.unit_is_dead(), - view_is_out: super::state::view_is_out( - driving_own_body, - self.view_subject.remote.is_some(), - ), + view_is_out: super::state::view_is_out(driving_own_body, self.far_sight.on()), } .torn_down(rooted, s.0.unit_flags() & super::UNIT_FLAG_STUNNED != 0) }) @@ -218,7 +260,9 @@ impl FollowInput<'_, '_> { /// Cancel, re-resolve the followee, steer, and set [`Player::auto_forward`] for `control`. The /// cancel comes first, as the reference's start emitters run ahead of the axis math (`0x5150a7` vs -/// the emitter tail `0x5151a0`). +/// the emitter tail `0x5151a0`). Each end here is frame time's (`0x5146d6`, `0x6106b0`), after the +/// packets, and signals behind them ([`end`]). +#[allow(clippy::too_many_arguments)] // a Bevy system's full input set pub(super) fn steer_follow( time: Res