Files

6504 lines
424 KiB
C++

#include "gateway/source_party_target_profile.hpp"
#include "gateway/source_drop_catalogue.hpp"
#include "gateway/source_skinning_spells.hpp"
#include "gateway/spell_gcd_categories.hpp"
#include "gateway/spell_modifiers.hpp"
#include <set>
#include <cstdarg>
#include "gateway/warrior_stance_profile.hpp"
#include "account_data_store.hpp"
#include "gateway/auction_aux.hpp"
#include "diagnostics_journal.hpp"
#include "roster_diagnostics.hpp"
#include "gateway/who.hpp"
#include "gateway/pvp_statistics.hpp"
#include "gateway/source_team.hpp"
#include "gateway/source_proficiency.hpp"
#include "presentation_clock.hpp"
#include "gateway/spell_visual_kit_profile.hpp"
#include "accepted_feature_defaults.h"
#include "gateway/guild_management.hpp"
#include "gateway/guild_notifications.hpp"
#include "gateway/remote_speeds.hpp"
#include "gateway/observer_motion.hpp"
#include "object_update_layout_guard.hpp"
#include "gateway/forever_opcode_profile.hpp"
#include "gateway/merchant_opcode_profile.hpp"
#include "world_translation.hpp"
#include "gateway/spell_log_sources.hpp"
#include "gateway/source_zones.hpp"
#include "mailbox_world_binding.hpp"
#include "auction_battleground_responses.hpp"
#include "gateway/pet_presentation.hpp"
#include "gateway/exploration.hpp"
#include "gateway/object_updates.hpp"
#include "gateway/shop_forge_focus_authority.hpp"
#include "gateway/native_spell_focus_objects.hpp"
#include "gateway/gameobject_type_references.hpp"
#include "gateway/queries.hpp"
#include "gateway/roster_translation.hpp"
#include "gateway/turtle_login_profile.hpp"
#include "gateway/chat.hpp"
#include "gateway/turtle_trade.hpp"
#include "gateway/turtle_mail.hpp"
#include "gateway/turtle_duel.hpp"
#include "gateway/inventory_result_profile.hpp"
#include "gateway/source_feedback.hpp"
#include "gateway/raid_reset_warning.hpp"
#include "gateway/random_roll.hpp"
#include "gateway/pvp.hpp"
#include "gateway/spell_result_profile.hpp"
#include "gateway/turtle_entity_profile.hpp"
#include "gateway/server_cast_identity.hpp"
#include "gateway/aura_visual_profile.hpp"
#include "gateway/cast_visual_profile.hpp"
#include "gateway/aura_definition_profile.hpp"
#include "gateway/source_mounted_spells.hpp"
#include "gateway/source_mount_aura_profile.hpp"
#include "gateway/mount_action_spells.hpp"
#include "gateway/source_ghost_aura_profile.hpp"
#include "gateway/spell_damage.hpp"
#include "gateway/turtle_combat_logs.hpp"
#include "gateway/source_combat_events.hpp"
#include "gateway/talents.hpp"
#include "gateway/warrior_cooldown_modifiers.hpp"
#include "gateway/taxi.hpp"
#include "gateway/corpse.hpp"
#include "gateway/mirror_timer.hpp"
#include "gateway/movement_modes.hpp"
#include "gateway/source_faction_profile.hpp"
#include "gateway/trainer_offer_filter.hpp"
#ifdef GW_GAMEOBJECT_AUTHORITY_PROFILE_HEADER
#include GW_GAMEOBJECT_AUTHORITY_PROFILE_HEADER
#endif
#include "gateway/quest_poi_dataset.hpp"
#include "gateway/quest_poi_request.hpp"
#ifdef GW_QUEST_POI_DATASET_HEADER
#include GW_QUEST_POI_DATASET_HEADER
#endif
#ifdef GW_QUEST_POI_60141_GEOMETRY_HEADER
#include GW_QUEST_POI_60141_GEOMETRY_HEADER
#endif
#include <algorithm>
#include <bit>
#include <chrono>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
// Source service NPCs: world creatures (HIGHGUID_UNIT) and Turtle shop mini-pets (HIGHGUID_PET).
static inline bool service_unit(uint64_t guid){const auto high=guid>>48;return high==0xf130 || high==0xf140;}
// Always-on mailbox decisions. Reason: 1 same-box coalesce, 2 switch queued,
// 3 unanswered list expired, 4 held reply, 5 omitted mail.
static void mail_list_log(unsigned reason,unsigned source=0,unsigned shown=0,
size_t omitted=0,size_t holds=0,unsigned detail=0){
std::fprintf(stderr,"GW_MAIL reason=%u detail=%u source=%u shown=%u omitted=%zu holds=%zu\n",
reason,detail,source,shown,omitted,holds);
}
namespace {
std::vector<gateway::LegacyPacket> project_received_modifiers(uint8_t character_class,
const std::map<std::tuple<bool,uint8_t,uint8_t>,int32_t>& received,
bool percent, uint8_t operation, std::optional<uint8_t> changed_bit=std::nullopt) {
// This is the fresh client's received-state baseline, not a claim that
// every server update has arrived. Late updates replace and recompute it.
// World retains the map through transfers and clears it at logout.
// Both kinds are passed: a flat group is sent relative to its percent partner.
std::array<int32_t,64> flat{},percent_values{};
for(const auto& [key,value]:received) {
const auto [is_percent,op,bit]=key;
if(op==operation)(is_percent?percent_values:flat)[bit]=value;
}
using gateway::spell_modifier::Kind;
std::optional<gateway::spell_modifier::ChangedSource> changed;
if(changed_bit)changed=gateway::spell_modifier::ChangedSource{percent?Kind::Percent:Kind::Flat,*changed_bit};
// Without a changed bit every route of this operation (both kinds) is sent.
return gateway::spell_modifier::translate_group_state(character_class,operation,
flat,percent_values,~uint64_t(0),changed);
}
// Item moves are logged one line each (bank-sort error hunt, owner 2026-11-23): native opcode, Turtle opcode, body.
static void gw_inv_log(const char* fmt,...){ // appended to GW_NATIVE_STARTUP_LOG (bank-sort error hunt)
const char* path=std::getenv("GW_NATIVE_STARTUP_LOG");if(!path || !*path)return;
FILE* file=std::fopen(path,"a");if(!file)return;
va_list args;va_start(args,fmt);std::vfprintf(file,fmt,args);va_end(args);std::fclose(file);
}
gateway::LegacyPacket log_inventory_move(uint32_t native,gateway::LegacyPacket p){
char hex[2*64+1]{};for(size_t i=0;i<p.body.size() && i<64;++i)std::snprintf(hex+2*i,3,"%02x",unsigned(p.body[i]));
gw_inv_log("GW_INV move native=0x%x legacy=0x%x body=%s\n",unsigned(native),unsigned(p.opcode),hex);return p;
}
}
namespace {
// Only NPC create inputs on the fixture's world-update paths carry replay data.
// Other codec failures retain their numeric envelope without any payload.
void dump_rejected_codec_input(uint32_t mode, uint32_t opcode, const gateway::Bytes& input,
const std::string& name) noexcept {
const char* path = std::getenv("GW_PRIVATE_CODEC_FAILURE_DUMP");
if (!path || !*path) return;
constexpr size_t name_offset = 30; // entity_translation.cpp header(), preceding C string
const bool npc_mode = mode == GW_CODEC_NPCS_TYPES || mode == GW_CODEC_NPCS_COMBAT;
const bool update = opcode == 0x61 || opcode == 0xaa || opcode == 0xa9 || opcode == 0x1f6;
static const bool dump_all = [] { const char* v = std::getenv("GW_PRIVATE_CODEC_FAILURE_DUMP_ALL"); return v && *v == '1'; }();
const bool named = !name.empty() && input.size() > name_offset + name.size() &&
std::equal(name.begin(), name.end(), input.begin() + name_offset) && input[name_offset + name.size()] == 0;
const bool replay = (npc_mode || dump_all) && update && input.size() <= (1u << 20) && !name.empty() &&
input.size() > name_offset && name.size() < input.size() - name_offset &&
(dump_all || named);
std::FILE* file = std::fopen(path, "ab");
if (!file) return;
if (replay) {
std::fprintf(file, "{\"kind\":\"codec-reject-input-v1\",\"mode\":%u,\"opcode\":%u,\"hex\":\"", mode, opcode);
for (size_t i = 0; i < input.size(); ++i) {
auto byte = (named && i >= name_offset && i < name_offset + name.size()) ? uint8_t('X') : input[i];
std::fprintf(file, "%02x", unsigned(byte));
}
std::fputs("\"}\n", file);
} else {
std::fprintf(file, "{\"kind\":\"codec-reject-summary-v1\",\"mode\":%u,\"opcode\":%u,\"bytes\":%zu}\n",
mode, opcode, input.size());
}
std::fclose(file);
}
}
using namespace gateway;
static Bytes trade_status_input(uint32_t status,const Bytes& partner,uint32_t id,bool failure_for_self) {
Bytes input{0,uint8_t(status)};
append(input,partner);le(input,id,4);le(input,failure_for_self,1);le(input,0,4);le(input,0,4);
return input;
}
static std::optional<ChannelCommand> native_channel_command(uint32_t opcode) {
switch(opcode) {
case 0x2d0000:return ChannelCommand::Join;
case 0x2d0001:return ChannelCommand::Leave;
// WPP V1_60_1_69876 + upstream ff699fb5 (wire-checked): 0x2D000F/10 are /afk and /dnd
// (also the client's own auto-AFK), the channel lists are 0x2D0011/12.
case 0x2d0011:return ChannelCommand::List;
case 0x2d0012:return ChannelCommand::DisplayList;
case 0x2d0007:return ChannelCommand::Message;
default:return std::nullopt;
}
}
bool NativeWorldTranslation::party_invitation_current() const {
if(!party_invitation || party_invitation->accepted || !self_created || !location || far_transfer ||
std::chrono::steady_clock::now()>=party_invitation->expires)return false;
if(!party_invitation->generation)return true; // Name-only or guild/chat offer: no visible actor lifetime.
auto p=entities.peer_players.find(party_invitation->guid);auto a=entities.actors.find(party_invitation->guid);
return p!=entities.peer_players.end() && a!=entities.actors.end() && p->second.named && !p->second.blocked &&
p->second.generation==party_invitation->generation && a->second.generation==party_invitation->generation &&
a->second.kind==4 && a->second.sent && a->second.presentation_realm==realm && a->second.presentation_map==location->map;
}
std::optional<uint32_t> NativeWorldTranslation::player_guild(uint64_t guid) const{
if(guid==selected.guid)return guild_id;
auto peer=entities.peer_players.find(guid);auto actor=entities.actors.find(guid);
if(!location || peer==entities.peer_players.end() || actor==entities.actors.end() ||
peer->second.blocked || actor->second.kind!=4 || peer->second.generation!=actor->second.generation ||
actor->second.presentation_realm!=realm || actor->second.presentation_map!=location->map)return std::nullopt;
auto field=peer->second.fields.find(turtle_entity_fields::PLAYER_GUILDID);
if(field==peer->second.fields.end())return std::nullopt;
return field->second;
}
namespace {
struct SpeedRoute {uint32_t source,source_ack,native,native_ack;};
// Pinned Tortoise Opcodes_1_12_1/MovementPacketSender and original70334
// ClassicOpcodes normalization oracle. These are six movement mechanics,
// independent of which item, spell, mount or aura caused the server change.
constexpr SpeedRoute speed_routes[]={
{0xe2,0xe3,0x600020,0x420029}, //run
{0xe4,0xe5,0x600021,0x42002a}, //run back
{0xe6,0xe7,0x600022,0x42002b}, //swim
{0x2da,0x2db,0x600026,0x42003f}, //walk
{0x2dc,0x2dd,0x600023,0x420040}, //swim back
{0x2de,0x2df,0x600027,0x420041}, //turn rate
};
const FactionMappings& native_faction_mappings(){
static const FactionMappings result=[](){FactionMappings out;
// Installed Faction rows retain source bases and race/class masks.
for(auto row:source_factions::Mappings)out.emplace(row.source_index,FactionMapping{row.id,row.index,0,0});
return out;
}();
return result;
}
bool source_talent_class(uint32_t cls){
// Original Turtle class IDs, not the newer expansion's class table.
switch(cls){case 1:case 2:case 3:case 4:case 5:case 7:case 8:case 9:case 11:return true;default:return false;}
}
constexpr size_t WorldBundleRecordLimit=1024;
Bytes world_bundle(const std::vector<LegacyPacket>& output){
if(output.size()>WorldBundleRecordLimit)throw Error("native translated packet-count bound");
Bytes bundle;le(bundle,output.size(),4);
for(const auto& item:output){le(bundle,item.opcode,4);le(bundle,item.body.size(),4);append(bundle,item.body);}
if(bundle.size()>GW_CODEC_BOUND)throw Error("native translated bundle bound");
return bundle;
}
}
bool NativeWorldTranslation::talent_ready() const noexcept {
return self_created && selected.guid && selected.guid<=0xffffffffULL && realm && realm<=8191 &&
talent_spells_ready && spells.size()<=4096 && std::all_of(spells.begin(),spells.end(),[](uint32_t id){return id && id<=10000000;}) && talent_level && *talent_level>=1 && *talent_level<=60 &&
talent_points && *talent_points<=1000 && talent_class && *talent_class==selected.cls && source_talent_class(*talent_class);
}
bool NativeWorldTranslation::talent_reset_offer_bound() const noexcept {
if(!talent_reset_offer || !talent_ready() || (talent_reset_offer->guid>>48)!=0xf130)return false;
auto actor=entities.actors.find(talent_reset_offer->guid);
return actor!=entities.actors.end() && actor->second.kind==3 && actor->second.sent &&
actor->second.generation && actor->second.generation==talent_reset_offer->generation &&
std::any_of(actor->second.modern.begin(),actor->second.modern.end(),[](uint8_t byte){return byte!=0;});
}
void NativeWorldTranslation::clear_talent_state(){
talent_level.reset();talent_points.reset();talent_class.reset();
talent_self_generation=false;talent_snapshot_pending=false;talent_initial_snapshot=false;talent_notice.reset();
talent_reset_offer.reset();
// The initial-spells snapshot and its learn/remove/supersede deltas belong
// to this authenticated character, not its current map's unit generation.
// Source worldport sends initial spells BEFORE adding/recreating the self
// actor. Retain readiness with the retained spells cache through removal
// or recreation; a fresh character/auth entry constructs a fresh translator.
// Keep sequence monotonic through a same-session object generation change.
// A new owned world session constructs a new translator and Lua clears on
// PLAYER_LEAVING_WORLD. General spell/cast state is managed independently.
}
void NativeWorldTranslation::observe_talent_updates(const std::vector<LegacyObjectUpdate>& updates){
for(const auto& update:updates){
if(update.kind==4 && std::find(update.removed.begin(),update.removed.end(),selected.guid)!=update.removed.end()){clear_talent_state();continue;}
if(update.guid!=selected.guid || (update.kind!=0 && update.kind!=2 && update.kind!=3))continue;
if(update.kind==2 || update.kind==3){
if(update.type!=4)continue;
if(talent_self_generation)clear_talent_state();
talent_self_generation=true;
// A full source create omits zero-valued update fields. Its absent
// PLAYER_CHARACTER_POINTS1 is genuinely zero, unlike a delta's
// absent field, which must retain prior authoritative state.
talent_level.reset();talent_class.reset();talent_points=0;
}
bool changed=false;
// Tortoise Objects/UpdateFields.h: UNIT_FIELD_LEVEL=34,
// UNIT_FIELD_BYTES_0=36, PLAYER_CHARACTER_POINTS1=1102.
if(auto field=update.fields.find(34);field!=update.fields.end()){
talent_level=field->second>=1 && field->second<=60?std::optional<uint32_t>(field->second):std::nullopt;changed=true;
}
if(auto field=update.fields.find(36);field!=update.fields.end()){
auto cls=(field->second>>8)&255;
talent_class=source_talent_class(cls) && cls==selected.cls?std::optional<uint32_t>(cls):std::nullopt;changed=true;
}
if(auto field=update.fields.find(1102);field!=update.fields.end()){
talent_points=field->second<=1000?std::optional<uint32_t>(field->second):std::nullopt;changed=true;
}
if(changed){
talent_snapshot_pending=talent_ready();
}
}
}
void NativeWorldTranslation::guild_control_state(){
if(!guild_control_subscribed || guild_control_notices.size()>=32)return;
if(guild_id && guild_rank_info && guild_rank_info->id==guild_id && guild_management_roster)
guild_control_notices.push_back("GWTURTLE1 GUILD STATE "+std::to_string(guild_id)+" "+std::to_string(guild_control_revision)+" "+std::to_string(guild_control_serial));
}
void NativeWorldTranslation::guild_control_clear(){
guild_control_inflight.reset();guild_control_notices.clear();guild_control_subscribed=false;guild_control_serial=0;guild_control_revision=0;
}
void NativeWorldTranslation::guild_control_refresh(){
++guild_control_revision;
if(guild_control_inflight && guild_rank_info && guild_management_roster && guild_control_inflight->reflected(*guild_rank_info,*guild_management_roster)){
if(guild_control_notices.size()<31)guild_control_notices.push_back("GWTURTLE1 GUILD CONFIRMED "+std::to_string(guild_control_inflight->serial));
guild_control_inflight.reset();guild_management_pending=false;
}else if(guild_control_inflight)guild_management_pending=true;
guild_control_state();
}
std::optional<GuildControlIntent> NativeWorldTranslation::guild_control_prepare(std::string_view text){
try{
const bool enabled=gw_accepted_feature_enabled("GW_GUILD_MANAGEMENT_PROTOTYPE");
if(!enabled || !self_created || !guild_id)throw Error("guild control unavailable");
guild_control_subscribed=true;
if(text=="guild1 state"){
if(!guild_rank_info || guild_rank_info->id!=guild_id || !guild_management_roster){
if(requests.size()>4093)throw Error("guild query queue bound");
requests.push_back({0x89,{}});Bytes query;le(query,guild_id,4);requests.push_back({0x54,std::move(query)});
// The established PE drains local world presentation after a
// zero-byte addon result, then sends these Source requests.
// An absent roster is waiting state, never a ready snapshot.
if(guild_control_notices.size()<32)guild_control_notices.push_back("GWTURTLE1 GUILD WAIT");
}else guild_control_state();
return std::nullopt;
}
if(!guild_rank_info || guild_rank_info->id!=guild_id || !guild_management_roster || guild_management_pending)throw Error("guild control stale or pending");
if(requests.size()>4093)throw Error("guild control query queue bound");
return source_guild_control(text,*guild_rank_info,*guild_management_roster,selected.guid,realm,guild_rank,guild_control_revision,guild_control_serial);
}catch(const Error&){
if(guild_control_notices.size()<31){
if(text=="guild1 state"){
guild_control_notices.emplace_back("GWTURTLE1 GUILD UNAVAILABLE");
}else{
std::string notice="GWTURTLE1 GUILD ERROR ";
if(text.starts_with("guild1 ")){
auto fields=text.substr(7);
auto serial=fields.substr(0,fields.find(' '));
if(!serial.empty() && serial.size()<=16 && serial.find_first_not_of("0123456789")==serial.npos){
notice.append(serial);
notice+=' ';
}
}
guild_control_notices.push_back(notice+"invalid-or-stale-request");
}
}
guild_control_state();return std::nullopt;
}
}
void NativeWorldTranslation::guild_control_sent(const GuildControlIntent& intent){
guild_control_serial=intent.serial;guild_control_inflight=intent;
gameplay_sent(intent.native_opcode,intent.body);
if(intent.native_opcode==0x2f0008){Bytes query;le(query,guild_id,4);requests.push_back({0x54,std::move(query)});}
if(guild_control_notices.size()<31)guild_control_notices.push_back("GWTURTLE1 GUILD PENDING "+std::to_string(intent.serial));
guild_control_state();
}
bool NativeWorldTranslation::talent_control(std::string_view text,std::optional<LegacyPacket>& outgoing){
outgoing.reset();
if(!text.starts_with(".gwtalent"))return false;
try{
const auto command=turtle_talent_control(text);
if(!command)throw Error("missing reserved talent command");
if(command->visibility){
auto& visibility=entities.equipment_visibility;const auto part=unsigned(command->visibility-1);
if(!self_created || !location || !visibility.bound(selected.guid,realm,location->map)){
talent_notice="GWTURTLE1 VISIBILITY unavailable";return true;
}
// Source handlers toggle; an on/off request must not blindly replay.
visibility.dirty=true;
if(visibility.needs_toggle(part,command->visibility_action))
outgoing=LegacyPacket{part?0x2bau:0x2b9u,{}};
return true;
}
if(!talent_ready()){talent_notice="GWTURTLE1 ERROR state-not-ready";return true;}
if(command->reset_guid){
if(!talent_reset_offer_bound() || talent_reset_offer->guid!=command->reset_guid){
talent_notice="GWTURTLE1 ERROR reset-offer-unavailable";return true;
}
// Tortoise SkillHandler::HandleTalentWipeConfirmOpcode reads only
// the real GUID and independently validates interaction and cost.
// This prepares a request, not an ACK or an optimistic reset.
Bytes request;le(request,command->reset_guid,8);
outgoing=LegacyPacket{0x2aa,std::move(request)};
// Consume only after the existing transport successfully encodes
// it; output-capacity retries must retain this genuine offer.
return true;
}
if(command->talent){
if(*talent_level<10 || !*talent_points){talent_notice="GWTURTLE1 ERROR no-available-points";return true;}
Bytes request;le(request,command->talent,4);le(request,command->rank-1,4);
outgoing=LegacyPacket{0x251,std::move(request)};
// Sending a purchase is not an ACK. Only genuine source known-
// spell and points packets can alter the next committed snapshot.
}else talent_snapshot_pending=true;
}catch(const Error&){talent_notice="GWTURTLE1 ERROR invalid-request";}
return true;
}
void NativeWorldTranslation::talent_control_sent(const LegacyPacket& packet) noexcept {
if((packet.opcode==0x2b9 || packet.opcode==0x2ba) && packet.body.empty()){
auto& visibility=entities.equipment_visibility;
if(self_created && location && visibility.bound(selected.guid,realm,location->map))visibility.sent(packet.opcode==0x2ba?1:0);
return;
}
if(packet.opcode!=0x2aa || packet.body.size()!=8 || !talent_reset_offer)return;
uint64_t guid=0;for(unsigned i=0;i<8;++i)guid|=uint64_t(packet.body[i])<<(8*i);
if(guid==talent_reset_offer->guid)talent_reset_offer.reset();
}
std::vector<LegacyPacket> NativeWorldTranslation::take_talent_presentation(uint32_t address){
std::vector<std::string> messages;
if(talent_notice)messages.push_back(*talent_notice);
messages.insert(messages.end(),guild_control_notices.begin(),guild_control_notices.end());guild_control_notices.clear();
auto& visibility=entities.equipment_visibility;
if(visibility.dirty && self_created && location && visibility.bound(selected.guid,realm,location->map)){
for(unsigned part=0;part<2;++part)messages.push_back(std::string("GWTURTLE1 VISIBILITY ")+
(part?"cloak ":"helm ")+(visibility.hidden(part)?"off ":"on ")+
(visibility.pending[part]?"pending":"confirmed"));
}
visibility.dirty=false;
if(talent_snapshot_pending && talent_ready()){
if(talent_sequence>=9007199254740991ULL)throw Error("talent presentation sequence bound");
auto seq=std::to_string(talent_sequence+1);const std::string prefix="GWTURTLE1 ";
messages.push_back(prefix+"BEGIN "+seq+" "+std::to_string(selected.guid)+" "+std::to_string(*talent_class)+" "+
std::to_string(*talent_level)+" "+std::to_string(*talent_points)+" "+std::to_string(spells.size()));
std::string chunk;unsigned count=0;
for(auto spell:spells){
if(!spell || spell>10000000)throw Error("talent known-spell identity bound");
if(count++)chunk+=',';
chunk+=std::to_string(spell);
if(count==20){messages.push_back(prefix+"SPELLS "+seq+" "+chunk);chunk.clear();count=0;}
}
if(count)messages.push_back(prefix+"SPELLS "+seq+" "+chunk);
messages.push_back(prefix+"END "+seq);
}
std::vector<LegacyPacket> output;RosterRealm target;target.realm_id=realm;target.virtual_address=address;
for(const auto& text:messages){
if(text.size()>1024)throw Error("talent presentation text bound");
Bytes body{10};le(body,0,4);le(body,0,8);le(body,text.size()+1,4);cstring(body,text);le(body,0,1);
output.push_back({0x4c0001,forever_chat(body,{selected},target,0,true)});
}
if(talent_snapshot_pending && talent_ready()){++talent_sequence;talent_initial_snapshot=true;}
talent_snapshot_pending=false;talent_notice.reset();return output;
}
bool NativeWorldTranslation::queue_social(uint32_t mode,const Bytes& input){
if(social_presentations.size()>=128){++social_holds;return false;}
social_presentations.emplace_back(mode,input);
return true;
}
namespace {
const QuestPoiDataset* active_quest_poi_dataset(){
#ifdef GW_QUEST_POI_DATASET_HEADER
// Parsed once from the build-time SHA256-pinned immutable data.
static const QuestPoiDataset dataset{std::span(quest_poi_dataset_bytes)};
return &dataset;
#else
return nullptr;
#endif
}
}
bool NativeWorldTranslation::queue_quest_poi(std::span<const uint8_t> request,bool explicit_opt_in){
if(!explicit_opt_in || !local_gameobject_authority || !self_created || logout_complete || !location ||
pending_teleport || !quest_poi_pending.empty() || !entities.self_quest_log.initialized())return false;
try{
const auto* dataset=active_quest_poi_dataset();if(!dataset)return false;
const auto query=native_quest_poi_request(request);
const auto active=entities.self_quest_log.active_quests();
std::vector<uint32_t> ids;std::set<uint32_t> missing;
for(size_t i=0;i<query.count;++i){
const auto id=uint32_t(query.ids[i]);
if(std::find(active.begin(),active.end(),id)==active.end() || !dataset->contains(id) ||
std::find(ids.begin(),ids.end(),id)!=ids.end())continue;
ids.push_back(id);if(!quests.definitions.contains(id))missing.insert(id);
}
if(ids.empty() || requests.size()+missing.size()>4096)return false;
for(auto id:missing)if(!quests.awaiting_definition.contains(id)){
Bytes body;le(body,id,4);requests.push_back({0x05c,std::move(body)});
}
quest_poi_pending=std::move(ids);quest_poi_waiting_definitions=std::move(missing);return true;
}catch(const Error&){return false;}
}
std::optional<LegacyPacket> NativeWorldTranslation::take_quest_poi(){
if(quest_poi_pending.empty() || !quest_poi_waiting_definitions.empty())return std::nullopt;
auto pending=std::move(quest_poi_pending);quest_poi_pending.clear();
if(!local_gameobject_authority || !self_created || logout_complete || !location || pending_teleport)return std::nullopt;
try{
const auto* dataset=active_quest_poi_dataset();if(!dataset)return std::nullopt;
const auto active=entities.self_quest_log.active_quests();std::vector<QuestPoiRecord> records;
for(auto id:pending){
if(std::find(active.begin(),active.end(),id)==active.end())continue;
auto found=quests.definitions.find(id);if(found==quests.definitions.end())continue;
if(auto record=dataset->project(id,source_quest_definition(found->second)))records.push_back(std::move(*record));
}
// Both native count fields describe only records actually serialized.
return LegacyPacket{0x67001d,serialize_quest_poi_response(records)};
}catch(const Error&){return std::nullopt;}
}
void NativeWorldTranslation::observe_quest_poi_updates(const std::vector<LegacyObjectUpdate>& updates){
if(!quest_poi_60141_pending && quest_poi_pending.empty())return;
for(const auto& u:updates){
bool invalidate=(u.guid==selected.guid && (u.kind==2 || u.kind==3) && u.type==4);
if(u.kind==4 && std::find(u.removed.begin(),u.removed.end(),selected.guid)!=u.removed.end())invalidate=true;
if(u.guid==selected.guid && u.kind==0)
for(const auto& [field,value]:u.fields){(void)value;if(source_quest_log_field(field)){invalidate=true;break;}}
if(invalidate){quest_poi_pending.clear();quest_poi_waiting_definitions.clear();quest_poi_60141_pending.reset();quest_poi_60141_waiting_definition=false;return;}
}
}
bool NativeWorldTranslation::queue_quest_poi_60141(std::span<const uint8_t> request,bool explicit_opt_in){
#ifdef GW_QUEST_POI_60141_GEOMETRY_HEADER
if(!explicit_opt_in || !local_gameobject_authority || !self_created || logout_complete || !location ||
pending_teleport || quest_poi_60141_pending || !entities.self_quest_log.initialized())return false;
try{
const auto query=native_quest_poi_request(request);
if(std::find(query.ids.begin(),query.ids.begin()+query.count,60141)==query.ids.begin()+query.count)return false;
const auto active=entities.self_quest_log.active_quests();
if(std::find(active.begin(),active.end(),60141)==active.end())return false;
auto found=quests.definitions.find(60141);
if(found!=quests.definitions.end()){
const auto definition=source_quest_definition(found->second);
if(!quest_poi_60141_candidate(true,entities.self_quest_log,request,definition,quest_poi_60141_regions))return false;
quest_poi_60141_pending=Bytes(request.begin(),request.end());return true;
}
if(requests.size()>=4096)return false;
quest_poi_60141_pending=Bytes(request.begin(),request.end());quest_poi_60141_waiting_definition=true;
if(!quests.awaiting_definition.contains(60141)){
Bytes query_body;le(query_body,60141,4);requests.push_back({0x05c,std::move(query_body)});
}
return true;
}catch(const Error&){return false;}
#else
(void)request;(void)explicit_opt_in;return false;
#endif
}
std::optional<LegacyPacket> NativeWorldTranslation::take_quest_poi_60141(){
if(!quest_poi_60141_pending || quest_poi_60141_waiting_definition)return std::nullopt;
auto request=std::move(*quest_poi_60141_pending);quest_poi_60141_pending.reset();
#ifdef GW_QUEST_POI_60141_GEOMETRY_HEADER
if(!local_gameobject_authority || !self_created || logout_complete || !location || pending_teleport)return std::nullopt;
auto found=quests.definitions.find(60141);if(found==quests.definitions.end())return std::nullopt;
try{
const auto definition=source_quest_definition(found->second);
if(auto candidate=quest_poi_60141_candidate(true,entities.self_quest_log,request,definition,quest_poi_60141_regions))
return LegacyPacket{candidate->opcode,std::move(candidate->body)};
}catch(const Error&){}
#else
(void)request;
#endif
return std::nullopt;
}
std::vector<LegacyPacket> NativeWorldTranslation::take_social_presentation(decltype(&gw_codec_serialize) codec){
std::vector<LegacyPacket> out;if(!self_created||logout_complete)return out;
auto encode=[&](uint32_t mode,const Bytes& input){
uint32_t required=0;
if(!codec||codec(mode,input.data(),uint32_t(input.size()),0,nullptr,0,&required)!=GW_CODEC_CAPACITY||required>GW_CODEC_BOUND)throw Error("Social codec sizing failed");
Bytes encoded(required);if(codec(mode,input.data(),uint32_t(input.size()),0,encoded.data(),uint32_t(encoded.size()),&required)!=GW_CODEC_OK||required!=encoded.size())throw Error("Social codec serialization failed");
return encoded;
};
if(trade.notify_changed){
out.push_back({0x470017,encode(GW_CODEC_TRADE_EVENT,trade_status_input(9,Bytes(16),trade.id,false))});
trade.notify_changed=false;
}
while(!native_presentations.empty()){out.push_back(std::move(native_presentations.front()));native_presentations.pop_front();}
while(!social_presentations.empty()){
const auto& [mode,input]=social_presentations.front();
auto encoded=encode(mode,input);
auto opcode=NativeContactNameReply;
if(mode==GW_CODEC_AUCTION_BUCKETS)opcode=0x4702f6; // SMSG_AUCTION_LIST_BUCKETS_RESULT
else if(mode==GW_CODEC_PET_STABLE)opcode=0x5e0000; // SMSG_UPDATE_OBJECT (self PetStable)
else if(mode==GW_CODEC_AUCTION_ITEMS)opcode=0x4702f7; // SMSG_AUCTION_LIST_ITEMS_RESULT
else if(mode==GW_CODEC_COMMODITY_QUOTE)opcode=0x4702fb; // SMSG_AUCTION_GET_COMMODITY_QUOTE_RESULT
else if(mode==GW_CODEC_COMPANION_NAME)opcode=NativePetNameResponse;
else if(mode!=GW_CODEC_CONTACT_NAMES){
const auto kind=social_projection_from_input(input).kind;
opcode=kind==SocialProjection::Kind::List?NativeContactList:
kind==SocialProjection::Kind::LegacyConfiguration?NativeSocialMirrorVars:NativeFriendStatus;
}
out.push_back({opcode,std::move(encoded)});social_presentations.pop_front();
}return out;
}
namespace {
Bytes world_codec(decltype(&gw_codec_serialize) codec,uint32_t mode,const Bytes& input,
uint32_t source_opcode,const std::string& name){
uint32_t required=0;
if(!codec || codec(mode,input.data(),uint32_t(input.size()),0,nullptr,0,&required)!=GW_CODEC_CAPACITY || required>GW_CODEC_BOUND){
dump_rejected_codec_input(mode,source_opcode,input,name);
throw Error("native world source sizing failed");
}
Bytes result(required);
if(codec(mode,input.data(),uint32_t(input.size()),0,result.data(),uint32_t(result.size()),&required)!=GW_CODEC_OK || result.size()!=required)
throw Error("native world source serialization failed");
return result;
}
}
void NativeWorldTranslation::stage_early_undercity(const LegacyPacket& packet,const std::vector<LegacyObjectUpdate>& updates,bool includes_self){
if(self_created || !location || location->map!=0 || !selected.guid || !realm ||
(far_transfer && !(transfer_owned() && far_transfer->phase==4)))return;
for(size_t i=0;i<updates.size();++i){
const auto& update=updates[i];
if(update.kind==4){
for(const auto guid:update.removed)std::erase_if(early_undercity,[guid](const auto& pair){return pair.second.guid==guid;});
continue;
}
if(update.type!=5 || (update.kind!=2 && update.kind!=3) || !update.movement)continue;
auto entry=update.fields.find(turtle_entity_fields::OBJECT_FIELD_ENTRY);
auto type=update.fields.find(turtle_entity_fields::GAMEOBJECT_TYPE_ID);
if(entry==update.fields.end() || type==update.fields.end() || type->second!=11)continue;
const auto spawn=std::find_if(UndercityTransportSpawns.begin(),UndercityTransportSpawns.end(),
[&](const auto& row){return row.entry==entry->second;});
if(spawn==UndercityTransportSpawns.end())continue;
if(includes_self){
// The normal post-self pass will present this fresher create in its original packet.
early_undercity.erase(entry->second);
}else{
const auto index=size_t(spawn-UndercityTransportSpawns.begin());
entities.undercity_seen.set(index);
auto single=turtle_object_update_subset(packet,std::span(&i,1));
early_undercity.insert_or_assign(entry->second,EarlyUndercityCreate{update.guid,std::move(single)});
}
}
}
std::optional<bool> NativeWorldTranslation::undercity_position() const noexcept{
if(!self_created || !entities.self_presentation_ready || !selected.guid || !realm || !location ||
location->map!=0 || logout_complete || far_transfer || pending_teleport)return false;
const auto found=entities.source_positions.find(selected.guid);
if(found==entities.source_positions.end() || !entities.self_position_generation)return {};
const auto& pos=found->second;
if(pos.realm!=realm || pos.map!=0 || pos.generation!=entities.self_position_generation)return {};
const auto [x,y,z]=pos.xyz;
if(!std::isfinite(x) || !std::isfinite(y) || !std::isfinite(z))return {};
if(z < -65.f || z > 80.f)return false;
// Visibility around the three shafts includes both the upper Ruins and lower city.
for(const auto& row:UndercityTransportSpawns)if(row.display==455){
const auto dx=x-row.x,dy=y-row.y;
if(dx*dx+dy*dy<=75.f*75.f)return true;
}
return false;
}
bool NativeWorldTranslation::undercity_due() const noexcept{
const auto inside=undercity_position();
if(!inside.has_value())return undercity_settle.has_value();
if(!*inside)return undercity_settle.has_value() || entities.undercity_filled.any();
if(undercity_generation!=entities.self_position_generation || !undercity_settle)return true;
return !(entities.undercity_seen|entities.undercity_filled).all() && std::chrono::steady_clock::now()>=*undercity_settle;
}
void NativeWorldTranslation::service_undercity(uint32_t address,decltype(&gw_codec_serialize) codec,
std::vector<LegacyPacket>& output,bool idle){
const auto inside=undercity_position();
const bool new_self=undercity_generation && undercity_generation!=entities.self_position_generation;
if((inside && !*inside) || new_self){
const bool same_world=location && location->map==0 && realm && !logout_complete && !far_transfer;
entities.leave_undercity(realm,same_world,output);
undercity_generation=0;undercity_settle.reset();
}
if(!inside.value_or(false)){
// During a transient unknown pose, wait for a fresh position before filling or retiring.
undercity_settle.reset();return;
}
undercity_generation=entities.self_position_generation;
const auto now=std::chrono::steady_clock::now();
if(!undercity_settle)undercity_settle=now+std::chrono::seconds(2);
if(idle && now>=*undercity_settle){
auto encode=[&](uint32_t mode,const Bytes& in){return world_codec(codec,mode,in,0,selected.name);};
entities.fill_undercity(selected,realm,address,encode,output);
}
}
Bytes NativeWorldTranslation::local_presentation(uint32_t address,decltype(&gw_codec_serialize) codec){
std::vector<LegacyPacket> output;
equipment_sets.expire(equipment_sets::Clock::now());
while (!equipment_sets.replies.empty()) {
output.push_back(std::move(equipment_sets.replies.front()));
equipment_sets.replies.pop_front();
}
while(!transfer_presentation.empty()){
auto packet=std::move(transfer_presentation.front());transfer_presentation.pop_front();
if(packet.opcode==0x47002b){
if(!transfer_owned() || far_transfer->phase!=1)throw Error("NewWorld presentation phase differs");
trainer.reset();entities.self_profession_skills.clear();
far_transfer->phase=2;self_created=false;published_home_party=false;stable.reset();binder_offer.reset();auction_browse.reset();auction_personal.reset();auction_personal_deferred.clear();auction_commodity.reset();self_coinage.reset();ah_list_inflight=false;ah_list_retired=false;pet_rename_sent.clear();pet_rename_dropped=0;book_text_pending.clear();page_chains.clear();pet_unlearn_offer.reset();entities.spell_channels.clear();talent_snapshot_pending=false;talent_notice.reset();
needs_class_talent_group=true;
}
output.push_back(std::move(packet));
}
service_undercity(address,codec,output,true);
service_bg_positions(output);
for(auto& packet:take_talent_presentation(address))output.push_back(std::move(packet));
for(auto& packet:take_social_presentation(codec))output.push_back(std::move(packet));
if(auto packet=take_quest_poi())output.push_back(std::move(*packet));
if(auto packet=take_quest_poi_60141())output.push_back(std::move(*packet));
if(auto summon=take_summon_presentation(address))output.push_back(std::move(*summon));
present_guild(address,output);
return world_bundle(output);
}
bool NativeWorldTranslation::observe_death_updates(const std::vector<LegacyObjectUpdate>& updates){
const auto old_health=source_health;const auto old_ghost=source_ghost;
bool released=false;
for(const auto& u:updates)if(u.guid==selected.guid && (u.kind==0 || ((u.kind==2 || u.kind==3) && u.type==4))){
if(u.kind!=0){source_health.reset();source_stand.reset();source_stand_pending=false;standing_cast.reset();clear_stance_cast();source_form=0;}
if(auto stand=u.fields.find(turtle_entity_fields::UNIT_FIELD_BYTES_1);stand!=u.fields.end()){
source_stand=uint8_t(stand->second);source_form=uint8_t(stand->second>>16);
if(standing_cast && *source_stand!=0 && !source_stand_pending)standing_cast.reset();
}
if(auto hp=u.fields.find(turtle_entity_fields::UNIT_FIELD_HEALTH);hp!=u.fields.end())source_health=hp->second;
auto f=u.fields.find(turtle_entity_fields::PLAYER_FLAGS);
if(f==u.fields.end() && u.kind==0)continue;
bool ghost=f!=u.fields.end() && (f->second&16);
// Native BuildPlayerRepop sends PreRessurect before the ghost update.
// Derive that lifecycle notification only from an actual non-ghost
// -> ghost transition; an initial/repeated ghost snapshot is not a
// fresh release, and must not restart the client's death lifecycle.
released|=ghost && source_ghost==false;
if(ghost && source_ghost!=true){
if(requests.size()>=4096)throw Error("native corpse metadata queue bound");
// Forever's own login does not issue the legacy corpse query.
// Request genuine state once per source ghost transition, exactly
// like source creature-template discovery; never invent a location.
requests.push_back({0x216,{}});
}
if(source_ghost==true && !ghost){pending_ghost_cast.reset();ghost_cast_packet_budget=0;release={};}
source_ghost=ghost;
}
if(source_ghost==false && source_health && *source_health>0)release={};
if(old_health!=source_health || old_ghost!=source_ghost)trace_release("source_player_state");
return released;
}
void NativeWorldTranslation::trace_release(const char* stage) noexcept{
static const bool enabled=[](){const auto* v=std::getenv("GW_NATIVE_COMBAT_DIAGNOSTICS");return v && std::strcmp(v,"1")==0;}();
if(!enabled || release_diagnostic_rows>=64)return;
++release_diagnostic_rows;
std::fprintf(stderr,"GWCorpse {\"sequence\":%u,\"source_packet\":%u,\"stage\":\"%s\",\"health_known\":%s,\"health\":%u,\"ghost\":%d,\"request_sent\":%s,\"corpse_valid\":%s,\"transfer_seen\":%s}\n",
release_diagnostic_rows,entities.source_packets,stage,source_health?"true":"false",source_health.value_or(0),
source_ghost?(*source_ghost?1:0):-1,release.requested?"true":"false",release.corpse_valid?"true":"false",release.transfer?"true":"false");
}
void NativeWorldTranslation::trace_combat(const char* stage,uint32_t opcode,uint64_t attacker,uint64_t victim,uint32_t state,uint32_t flags,uint32_t damage,uint32_t blocked){
static const bool enabled=[](){const auto* value=std::getenv("GW_NATIVE_COMBAT_DIAGNOSTICS");return value && std::strcmp(value,"1")==0;}();
if(!enabled || combat_diagnostic_rows>=256)return;
++combat_diagnostic_rows;
std::fprintf(stderr,"GWCombat {\"sequence\":%u,\"source_packet\":%u,\"stage\":\"%s\",\"opcode\":%u,\"attacker\":\"%llu\",\"victim\":\"%llu\",\"state\":%u,\"flags\":%u,\"damage\":%u,\"blocked\":%u}\n",
combat_diagnostic_rows,entities.source_packets,stage,opcode,static_cast<unsigned long long>(attacker),static_cast<unsigned long long>(victim),state,flags,damage,blocked);
}
bool NativeWorldTranslation::defer_standing_cast(uint32_t opcode,std::span<const uint8_t> body,const LegacyPacket& packet){
if(opcode!=0x3e0176)return false;
auto request=forever_spell_request(body);
const auto now=std::chrono::steady_clock::now();
// Report 58f1cc: a GCD spell inside the Turtle wand GCD fails NOT_READY, and the 70334 client has already
// cancelled the wand for it. Hold it until the GCD ends; a newer press replaces a cast held only for time.
const bool wand=self_created && (wand_repeating || (wand_gcd_until && now<*wand_gcd_until)) && spell_gcd_categories::global(request.spell);
if(standing_cast && wand && standing_cast->release_at && standing_cast->acknowledged)standing_cast.reset();
if(standing_cast)throw Error("cast already waiting for source standing acknowledgement");
const bool stand=source_stand_pending && source_stand && *source_stand!=0;
if(!stand && !wand)return false;
if(!self_created || !location || pending_teleport)throw Error("stand cast outside live world location");
StandingCast held;held.packet=packet;held.original.assign(body.begin(),body.end());
held.owner=selected.guid;held.realm=realm;held.map=location->map;
held.deadline=now+std::chrono::seconds(5);
if(wand){held.release_at=now+std::chrono::seconds(3);held.acknowledged=!stand;}
for(const auto& [guid,actor]:entities.actors)
if(((request.target_flags&0x802u) && request.unit!=Guid128{} && actor.modern==request.unit) ||
((request.target_flags&16u) && request.item!=Guid128{} && actor.modern==request.item))
held.target_generations.emplace(guid,actor.generation);
standing_cast=std::move(held);return true;
}
bool NativeWorldTranslation::cancel_standing_cast(uint32_t opcode,std::span<const uint8_t> body){
if(opcode!=0x3e0179 || !standing_cast)return false;
Reader r(body);auto cast=unpack_guid(r,16);auto spell=r.le(4);r.end();
const auto request=forever_spell_request(standing_cast->original);
if(!std::equal(cast.begin(),cast.end(),request.cast.begin()) || spell!=request.spell)
throw Error("cancel outside source-standing queued cast");
standing_cast.reset();return true;
}
void NativeWorldTranslation::stand_state_received(uint8_t state){
source_stand=state;source_stand_pending=false;
if(standing_cast){if(state==0)standing_cast->acknowledged=true;else standing_cast.reset();}
}
std::optional<LegacyPacket> NativeWorldTranslation::standing_cast_request(){
if(!standing_cast)return std::nullopt;
const auto& held=*standing_cast;
bool valid=self_created && !logout_complete && location && !pending_teleport &&
selected.guid==held.owner && realm==held.realm && location->map==held.map &&
(!source_health || *source_health>0) && std::chrono::steady_clock::now()<=held.deadline;
for(const auto& [guid,generation]:held.target_generations){
const auto actor=entities.actors.find(guid);
valid=valid && actor!=entities.actors.end() && actor->second.sent && actor->second.generation==generation;
}
if(!valid){standing_cast.reset();return std::nullopt;}
if(held.release_at){
const auto now=std::chrono::steady_clock::now();
const bool gcd=wand_repeating || (wand_gcd_until && now<*wand_gcd_until);
if(gcd && now<*held.release_at)return std::nullopt;
}
if(!held.acknowledged)return std::nullopt;
try{
const auto current=gameplay(0x3e0176,held.original);
if(current.opcode!=held.packet.opcode || current.body!=held.packet.body){standing_cast.reset();return std::nullopt;}
}catch(const Error&){standing_cast.reset();return std::nullopt;}
return held.packet;
}
void NativeWorldTranslation::standing_cast_sent(){
if(!standing_cast || !standing_cast->acknowledged)throw Error("standing cast sent before source acknowledgement");
const auto original=std::move(standing_cast->original);standing_cast.reset();
gameplay_sent(0x3e0176,original);
}
std::optional<NativeWorldTranslation::StanceCast> NativeWorldTranslation::prepare_stance_cast(
uint32_t opcode,std::span<const uint8_t>body,const LegacyPacket&packet) const{
if(opcode!=0x3e0176 || selected.cls!=1)return std::nullopt;
if(stance_cast)throw Error("cast already waiting for source stance acknowledgement");
const auto request=forever_spell_request(body);
const auto choice=warrior_stance::choose(request.spell,selected.cls,source_form,spells);
if(!choice)return std::nullopt;
if(!self_created||!location||pending_teleport||far_transfer||logout_complete||source_health==0)
throw Error("stance switch outside live source world");
StanceCast held;held.packet=packet;held.original.assign(body.begin(),body.end());
held.owner=selected.guid;held.realm=realm;held.map=location->map;
held.stance=choice->spell;held.form=choice->form;
held.deadline=std::chrono::steady_clock::now()+std::chrono::seconds(5);
for(const auto&[guid,actor]:entities.actors)
if(((request.target_flags&0x802u)&&request.unit!=Guid128{}&&actor.modern==request.unit)||
((request.target_flags&16u)&&request.item!=Guid128{}&&actor.modern==request.item))
held.target_generations.emplace(guid,actor.generation);
return held;
}
LegacyPacket NativeWorldTranslation::stance_switch_packet(const StanceCast&held) const{
ForeverSpellRequest request{};request.spell=held.stance;
return {0x12e,turtle_spell_request(request,bindings())};
}
void NativeWorldTranslation::stance_switch_sent(StanceCast held){
const auto request=forever_spell_request(held.original);
pending_cast=PendingCast{request,forever_player_guid(selected.guid,realm)};cast_prepared=false;
standing_cast.reset();stance_cast=std::move(held);
}
static bool next_swing_spell(uint32_t spell){
return std::binary_search(spell_log_sources::NextSwing.begin(),spell_log_sources::NextSwing.end(),spell);
}
void NativeWorldTranslation::queue_cast(PendingCast cast){
const bool swing=next_swing_spell(cast.spell.spell);
// #136: a next-swing request (Heroic Strike...) resolves only at the next main-hand swing; instants pressed
// meanwhile must not orphan it (TrinityCore CURRENT_MELEE_SPELL). A newer next-swing request replaces it.
if(pending_cast && !swing && next_swing_spell(pending_cast->spell.spell)){
melee_cast=HeldCast{*pending_cast,cast_prepared};superseded_cast.reset();
}else{
// Only a started cast (START seen, still awaiting GO) is worth holding; an unanswered request is replaced.
if(pending_cast && cast_prepared)superseded_cast=HeldCast{*pending_cast,true};else superseded_cast.reset();
if(swing)melee_cast.reset();
}
pending_cast=std::move(cast);cast_prepared=false;
}
bool NativeWorldTranslation::select_cast(uint32_t spell){
if(pending_cast && pending_cast->spell.spell==spell)return false;
std::optional<HeldCast>* slot=nullptr;
if(superseded_cast && superseded_cast->cast.spell.spell==spell)slot=&superseded_cast;
else if(melee_cast && melee_cast->cast.spell.spell==spell)slot=&melee_cast;
if(!slot)return false;
auto held=std::move(**slot);slot->reset();
if(pending_cast)(next_swing_spell(pending_cast->spell.spell)?melee_cast:superseded_cast)=HeldCast{*pending_cast,cast_prepared};
pending_cast=std::move(held.cast);cast_prepared=held.prepared;return true;
}
void NativeWorldTranslation::release_cast(){
pending_cast.reset();cast_prepared=false;
auto& next=superseded_cast?superseded_cast:melee_cast;
if(next){pending_cast=std::move(next->cast);cast_prepared=next->prepared;next.reset();}
}
void NativeWorldTranslation::clear_stance_cast(){
if(!stance_cast)return;
const auto request=forever_spell_request(stance_cast->original);
if(pending_cast&&pending_cast->spell.cast==request.cast){pending_cast.reset();cast_prepared=false;}
stance_cast.reset();
}
bool NativeWorldTranslation::cancel_stance_cast(uint32_t opcode,std::span<const uint8_t>body){
if(opcode!=0x3e0179||!stance_cast)return false;
Reader r(body);const auto cast=unpack_guid(r,16);const auto spell=r.le(4);r.end();
const auto request=forever_spell_request(stance_cast->original);
if(!std::equal(cast.begin(),cast.end(),request.cast.begin())||spell!=request.spell)
throw Error("cancel outside source-stance queued cast");
clear_stance_cast();return true;
}
std::optional<LegacyPacket> NativeWorldTranslation::stance_cast_request(){
if(!stance_cast)return std::nullopt;
const auto&held=*stance_cast;
bool valid=self_created&&!logout_complete&&location&&!pending_teleport&&!far_transfer&&
selected.guid==held.owner&&realm==held.realm&&location->map==held.map&&
source_health!=0&&spells.contains(held.stance)&&std::chrono::steady_clock::now()<=held.deadline;
for(const auto&[guid,generation]:held.target_generations){
const auto actor=entities.actors.find(guid);
valid=valid&&actor!=entities.actors.end()&&actor->second.sent&&actor->second.generation==generation;
}
if(!valid){clear_stance_cast();return std::nullopt;}
if(held.failed||!source_form||*source_form!=held.form)return std::nullopt;
try{
const auto current=gameplay(0x3e0176,held.original);
if(current.opcode!=held.packet.opcode||current.body!=held.packet.body){clear_stance_cast();return std::nullopt;}
}catch(const Error&){clear_stance_cast();return std::nullopt;}
return held.packet;
}
void NativeWorldTranslation::stance_ability_sent(){
if(!stance_cast||!source_form||*source_form!=stance_cast->form||stance_cast->failed)
throw Error("ability sent before source stance acknowledgement");
const auto original=std::move(stance_cast->original);stance_cast.reset();
gameplay_sent(0x3e0176,original);
}
void NativeWorldTranslation::qualify_spell_location(const ForeverSpellRequest& request) const{
if(!request.source_location && !request.destination_location)return;
if(!location || pending_teleport || far_transfer || logout_complete ||
(request.target_map && *request.target_map!=location->map))
throw Error("spell target outside active world map");
}
void NativeWorldTranslation::qualify_spell_gameobject(const Guid128& unit) const{
if(!self_created || !location || pending_teleport || far_transfer)throw Error("gameobject spell outside live world");
auto id=pack_guid(unit);Reader target(id);auto guid=bound_legacy_guid(target,bindings());target.end();
auto actor=entities.actors.find(guid);
if(actor==entities.actors.end() || actor->second.kind!=5 || !actor->second.sent || !actor->second.eligible ||
!actor->second.generation || actor->second.presentation_realm!=realm || actor->second.presentation_map!=location->map ||
actor->second.modern!=forever_game_object_guid(guid,actor->second.entry,realm,location->map))
throw Error("spell gameobject outside current source binding");
}
bool NativeWorldTranslation::queue_undercity_template(std::span<const uint8_t> body){
if(entities.undercity_filled.none() || !undercity_position().value_or(false) ||
!undercity_generation || undercity_generation!=entities.self_position_generation)return false;
const auto query=forever_gameobject_query(body);
for(size_t i=0;i<UndercityTransportSpawns.size();++i){
const auto& spawn=UndercityTransportSpawns[i];
if(!entities.undercity_filled[i] || query.entry!=spawn.entry)continue;
const auto guid=NativeEntityTranslation::undercity_source_guid(spawn);
if(query.guid!=forever_game_object_guid(guid,spawn.entry,realm,0))return false;
// These nine reviewed templates have unit size, faction zero, and all 24 data words zero.
// This binds only the local template writer; no source actor, request or interaction is installed.
GameObjectTemplateReply reply;reply.found=true;reply.entry=spawn.entry;reply.type=11;
reply.display=spawn.display;reply.names[0]=spawn.name;
GameObjectTemplateBinding binding;binding.source_guid=guid;binding.native_guid=query.guid;
binding.entry=spawn.entry;binding.realm=realm;binding.map=0;binding.template_size=1.f;
binding.native_display_id=spawn.display;binding.request_generation=binding.current_generation=undercity_generation;
auto projection=forever_gameobject_template(reply,binding);
if(!projection.packet)throw Error("Undercity transport template projection failed");
if(native_presentations.size()>=256)throw Error("Undercity transport template queue bound");
native_presentations.push_back({projection.packet->opcode,std::move(projection.packet->body)});
return true;
}
return false;
}
uint64_t NativeWorldTranslation::gameobject_query_actor(const GameObjectQuery& query) const{
if(!self_created || !realm || !location || pending_teleport || logout_complete)
throw Error("game-object query outside current source world");
for(const auto& [guid,actor]:entities.actors){
if(actor.modern!=query.guid)continue;
if(actor.kind!=5 || !actor.sent || !actor.eligible || !actor.generation ||
actor.entry!=query.entry || actor.presentation_realm!=realm ||
actor.presentation_map!=location->map ||
actor.modern!=forever_game_object_guid(guid,query.entry,realm,location->map))
throw Error("game-object query outside current source binding");
return guid;
}
throw Error("game-object query actor missing");
}
bool NativeWorldTranslation::gameobject_query_current(const PendingGameObjectQuery& query) const{
if(!self_created || !location || pending_teleport || logout_complete ||
query.realm!=realm || query.map!=location->map)return false;
auto actor=entities.actors.find(query.source);
return actor!=entities.actors.end() && actor->second.kind==5 && actor->second.sent &&
actor->second.eligible && actor->second.entry==query.entry &&
actor->second.generation==query.generation && query.generation &&
actor->second.presentation_realm==query.realm && actor->second.presentation_map==query.map &&
actor->second.modern==query.modern &&
query.modern==forever_game_object_guid(query.source,query.entry,query.realm,query.map);
}
LegacyPacket NativeWorldTranslation::mail_request(uint32_t opcode,std::span<const uint8_t> body) const{
// Native 70334 mail requests (ClassicClientOpcodes.inc wire values) -> Source 1.12 CMSG bodies.
Reader r(body);
auto mailbox=[&]{
// Packed native mailbox GUID: bind through the same correlated type-19 actor as the list request.
const size_t start=body.size()-r.left();const auto mask=uint16_t(body[start]|(body[start+1]<<8));
const size_t n=2+std::popcount(mask);if(start+n>body.size())throw Error("mail mailbox GUID");
const auto bound=mailbox_binding(body.subspan(start,n));(void)r.take(n);return bound.actor.source_guid;
};
auto mail_id=[&]{const auto id=r.le(8);if(!id || id>UINT32_MAX)throw Error("mail id outside Source u32");return uint32_t(id);};
auto listed=[&]{if(!mailbox_source)throw Error("mail action without a listed mailbox");return mailbox_source;};
switch(opcode){
case 0x3f00dc:{const auto box=mailbox();const auto id=mail_id();(void)r.le(8);r.end();return {0x245,source_mailbox_mail(box,id)};}
case 0x3f00dd:{const auto box=mailbox();const auto id=mail_id();(void)r.le(8);r.end();return {0x246,source_mailbox_mail(box,id)};}
case 0x3f00df:{const auto box=mailbox();const auto id=mail_id();r.end();return {0x247,source_mailbox_mail(box,id)};}
case 0x3f00e0:{const auto box=mailbox();const auto id=mail_id();r.end();
// HandleMailCreateTextItem reads a trailing u32 mailTemplateId (read_skip).
auto b=source_mailbox_mail(box,id);le(b,0,4);return {0x24a,std::move(b)};}
case 0x3e00e9:{const auto id=mail_id();(void)r.le(4);r.end();return {0x249,source_mailbox_mail(listed(),id)};}
case 0x440081:{const auto id=mail_id();(void)unpack_guid(r,16);r.end();return {0x248,source_mailbox_mail(listed(),id)};}
case 0x3f00de:{r.end();return {0x284,source_query_next_mail_time()};}
case 0x440026:return mail_send_packets(body).front();
}
throw Error("unsupported native mail request");
}
std::vector<LegacyPacket> NativeWorldTranslation::mail_send_packets(std::span<const uint8_t> body) const{
// Native SendMail {packed mailbox, u32 stationery, u64 money, u64 cod, bits 9/9/11/5, target, subject, body,
// n x {u8 slot, packed item}}. Source (1.12) mail carries at most one item, the 70334 window up to 12:
// send one Source mail per attachment (owner 2026-11-27: multi-item mail on OCTO was refused).
Reader r(body);
const size_t start=0;if(body.size()<2)throw Error("mail mailbox GUID");
const auto mask=uint16_t(body[start]|(body[start+1]<<8));const size_t n=2+std::popcount(mask);if(n>body.size())throw Error("mail mailbox GUID");
const auto box=mailbox_binding(body.first(n)).actor.source_guid;(void)r.take(n);
(void)r.le(4); // StationeryID: Source picks stationery itself.
const auto money=r.le(8),cod=r.le(8);
if(money>UINT32_MAX || cod>UINT32_MAX)throw Error("mail money exceeds Source u32");
// 9 target bits, 9 subject bits, 11 body bits, 5 attachment-count bits, flushed (MSB first).
uint64_t bits=0;for(int i=0;i<5;++i)bits=(bits<<8)|r.le(1);
const auto target_n=size_t((bits>>31)&0x1ff),subject_n=size_t((bits>>22)&0x1ff),body_n=size_t((bits>>11)&0x7ff),items=size_t((bits>>6)&0x1f);
auto take=[&](size_t k){auto v=r.take(k);return std::string(v.begin(),v.end());};
const auto target=take(target_n),subject=take(subject_n),text=take(body_n);
if(target.empty())throw Error("Source mail needs a recipient");
if(items>12)throw Error("mail attachments above the native 12");
// COD is charged per Source mail: splitting would make the receiver pay it once per item.
if(cod && items>1)throw Error("Source COD mail carries one item");
std::vector<uint64_t> attached;const auto& owned=inventory.owned_bindings();
for(size_t i=0;i<items;++i){(void)r.le(1);const auto item=bound_legacy_guid(r,owned);if(!item)throw Error("mail item outside owned inventory");
if(std::find(attached.begin(),attached.end(),item)!=attached.end())throw Error("mail item attached twice");
attached.push_back(item);}
r.end();
// Source receiver names are the plain character name (no realm suffix).
const auto name=target.substr(0,target.find('-'));
std::vector<LegacyPacket> out;
if(attached.empty())attached.push_back(0);
for(size_t i=0;i<attached.size();++i) // money (and COD) travel with the first mail only
out.push_back({0x238,source_send_mail(box,name,subject,text,41,attached[i],i?0u:uint32_t(money),i?0u:uint32_t(cod))}); // 41 = standard stationery
return out;
}
NativeWorldTranslation::MailboxBinding NativeWorldTranslation::mailbox_binding(std::span<const uint8_t> body) const{
const auto bound=mailbox_world::bind(body,entities.actors,mailbox_templates,
mailbox_world::Context{self_created,pending_teleport.has_value(),far_transfer.has_value(),
logout_complete,realm,location?location->map:0},
[&](uint32_t entry)->std::optional<GameObjectTemplateReply>{
// Client answered the template from gameobjectcache.wdb: it only holds what we
// published, which was the exact reviewed row. Rebuild that reply from the row.
GameObjectTemplateReply probe;probe.entry=entry;probe.found=true;
std::optional<GameObjectTemplateAuthority> row;
if(gameobject_template_authority)row=gameobject_template_authority(probe);
#ifdef GW_GAMEOBJECT_AUTHORITY_PROFILE_HEADER
else row=gameobject_authority_profile::lookup(probe);
#endif
if(!row || row->type!=19 || row->entry!=entry)return std::nullopt;
GameObjectTemplateReply out;out.entry=entry;out.found=true;out.type=row->type;out.display=row->source_display;
out.names[0]=row->source_name;out.data=row->source_data;return out;
});
if(!location || !gameobject_query_current(PendingGameObjectQuery{
bound.actor.source_guid,bound.actor.generation,bound.actor.entry,bound.actor.map,
bound.actor.realm,bound.actor.native_guid}))
throw Error("mailbox query actor became stale");
return MailboxBinding{bound.actor,bound.evidence};
}
gateway::MailboxActor NativeWorldTranslation::current_mailbox_actor() const{
auto current=mailbox_list.bound().value_or(MailboxActor{});
if(current.source_guid){
auto actor=entities.actors.find(current.source_guid);
if(!self_created || !location || pending_teleport || far_transfer || logout_complete ||
actor==entities.actors.end() || actor->second.kind!=5){
current.sent=false;
}else{
current.generation=actor->second.generation;current.entry=actor->second.entry;
current.map=location->map;current.realm=realm;current.native_guid=actor->second.modern;
current.sent=actor->second.sent;current.eligible=actor->second.eligible;
}
}
return current;
}
bool NativeWorldTranslation::coalesce_mailbox_list(std::span<const uint8_t> body){
if(mailbox_list.expire_list()){
next_mailbox_actor.reset();mail_list_log(3);return false;
}
if(!mailbox_list.awaiting_list())return false;
const auto target=mailbox_binding(body).actor;
if(mailbox_detail::current(*mailbox_list.bound(),target)){
next_mailbox_actor.reset();
mail_list_log(1);
}else{
next_mailbox_actor=target;
mail_list_log(2);
}
return true;
}
std::optional<MailboxPrepared> NativeWorldTranslation::next_mailbox_list(){
if(mailbox_list.expire_list())mail_list_log(3);
if(!next_mailbox_actor || mailbox_list.pending())return {};
const auto request=pack_guid(next_mailbox_actor->native_guid);
try{
const auto bound=mailbox_binding(request);
if(mailbox_detail::current(*next_mailbox_actor,bound.actor))
return mailbox_list.prepare(request,bound.actor,bound.evidence);
}catch(const Error&){/* The selected mailbox may have despawned before its query could be sent. */}
next_mailbox_actor.reset();
return {};
}
void NativeWorldTranslation::clear_mailbox(){
mailbox_list.clear();next_mailbox_actor.reset();mailbox_templates.clear();mailbox_source=0;
}
void NativeWorldTranslation::gameobject_query_queued(std::span<const uint8_t> body){
const auto query=forever_gameobject_query(body);auto guid=gameobject_query_actor(query);
const auto& actor=entities.actors.at(guid);
if(gameobject_queries.contains(query.entry) || gameobject_queries.size()>=256)
throw Error("game-object query pending-entry bound");
gameobject_queries.emplace(query.entry,PendingGameObjectQuery{guid,actor.generation,query.entry,location->map,realm,query.guid});
mailbox_templates.erase(guid); // Re-query retires an older template for this actor.
gameobject_query_evidence.reset();
trace_combat("gameobject_query_queued",0x5e,selected.guid,guid,query.entry);
}
static const char* gameobject_hold_name(GameObjectTemplateHold reason){
switch(reason){
case GameObjectTemplateHold::Binding:return "Binding";
case GameObjectTemplateHold::UnsupportedType:return "UnsupportedType";
case GameObjectTemplateHold::DisplayClosure:return "DisplayClosure";
case GameObjectTemplateHold::TemplateSize:return "TemplateSize";
case GameObjectTemplateHold::ExtraString:return "ExtraString";
case GameObjectTemplateHold::ReferenceClosure:return "ReferenceClosure";
case GameObjectTemplateHold::UnmappedChestField:return "UnmappedChestField";
case GameObjectTemplateHold::RestockRange:return "RestockRange";
case GameObjectTemplateHold::MissingName:return "MissingName";
case GameObjectTemplateHold::UnmappedMailboxField:return "UnmappedMailboxField";
case GameObjectTemplateHold::UnmappedTypeField:return "UnmappedTypeField";
case GameObjectTemplateHold::ScalarRange:return "ScalarRange";
case GameObjectTemplateHold::MetadataAuthority:return "MetadataAuthority";
}
return "Unknown";
}
std::optional<GameObjectTemplatePacket> NativeWorldTranslation::gameobject_query_reply(std::span<const uint8_t> body){
const auto reply=turtle_gameobject_template(body);gameobject_query_evidence.reset();
gw_diagnostics::journal().definition(0x5f,reply.entry,reply.found,body);
const auto log_reply=[&](bool answered,const char* reason){
if(gameobject_template_replies_logged.insert(reply.entry).second)
gw_inv_log("GW_GO template-reply entry=%u type=%u result=%s reason=%s\n",
reply.entry,reply.type,answered?"answered":"held",reason);
};
auto pending=gameobject_queries.find(reply.entry);
if(pending==gameobject_queries.end()){
log_reply(false,"Unsolicited");
trace_combat("gameobject_query_unsolicited",0x5f,selected.guid,0,reply.entry);return std::nullopt;
}
const auto request=pending->second;gameobject_queries.erase(pending);
if(!gameobject_query_current(request)){
log_reply(false,"Stale");
trace_combat("gameobject_query_stale",0x5f,selected.guid,request.source,reply.entry);return std::nullopt;
}
GameObjectQueryEvidence evidence{request,reply.found,reply.type,reply.display,{},false,{}};
GameObjectTemplateBinding binding;binding.source_guid=request.source;
binding.request_generation=request.generation;binding.current_generation=request.generation;
binding.entry=request.entry;binding.map=request.map;binding.realm=request.realm;binding.native_guid=request.modern;
bool authority_matched=false;
if(reply.found){
// The exact shop profile is available on Octo's public realm. The general
// compiled profile also applies there, but only when the live reply is
// byte-identical to the reviewed row (gameobject_template_authority_matches:
// entry, type, display, name and all 24 data words), so a changed Octo
// template stays held. Mailboxes, chests and doors need this to be usable.
auto authority=shop_forge_focus_authority::select(reply,true,
[&](const GameObjectTemplateReply& source)->std::optional<GameObjectTemplateAuthority>{
if(gameobject_template_authority)return gameobject_template_authority(source);
#ifdef GW_GAMEOBJECT_AUTHORITY_PROFILE_HEADER
if(auto a=gameobject_authority_profile::lookup(source)){
// Spell focus IDs are the vanilla numbers on both sides; the profile resolver only knows Locks, so
// every type-8 template (Moonwell, anvil, forge, Sacred Chalice) was held and the client saw no
// focus (owner 11-28: Mooncloth "Moonwell" stayed red). Pass a focus ID the native table has.
a->references=[base=a->references,type=source.type](GameObjectTemplateReference kind,uint32_t value)->std::optional<uint32_t>{
if(kind==GameObjectTemplateReference::SpellFocusObject && native_spell_focus::exists(value))return value;
if(auto closed=gameobject_type_references::reference(type,kind,value))return closed;
return base?base(kind,value):std::nullopt;
};
return a;
}
auto grave=turtle_hardcore_grave_authority(source,std::binary_search(std::begin(gameobject_authority_profile::Displays),
std::end(gameobject_authority_profile::Displays),source.display));
if(grave)grave->references=gameobject_authority_profile::reference;
return grave;
#else
return std::nullopt;
#endif
});
if(authority && gameobject_template_authority_matches(reply,*authority)){
authority_matched=true;binding.template_size=authority->template_size;
binding.native_display_id=authority->native_display;binding.references=authority->references;
// Source display6624 has an empty model in every installed Octo DBC layer;
// native GameObjectDisplayInfo6624 is likewise an explicit FileDataID0 row.
// Preserve this invisible trap identity, only after exact Source authority matching.
if(!authority->native_display && reply.type==6 && reply.display==6624)binding.native_display_id=6624;
evidence.authority_provenance=authority->provenance;
}
}
auto projection=forever_gameobject_template(reply,binding);
evidence.presentation_holds=std::move(projection.held);
if(reply.found && !authority_matched)evidence.presentation_holds.push_back({GameObjectTemplateHold::MetadataAuthority,-1});
if(!evidence.presentation_holds.empty())projection.packet.reset();
evidence.published=projection.packet.has_value();
log_reply(evidence.published,evidence.published?(reply.found?"None":"NotFound"):
(evidence.presentation_holds.empty()?"Unknown":gameobject_hold_name(evidence.presentation_holds.front().reason)));
// A native MailGetList is admitted only for an exact, current template
// that the client actually received. A held Source-only template cannot
// silently arm an invisible mailbox.
if(reply.found && reply.type==19 && evidence.published){
if(mailbox_templates.contains(request.source) || mailbox_templates.size()<256)
mailbox_templates.insert_or_assign(request.source,MailboxTemplateEvidence{
request.source,request.generation,request.map,request.realm,reply});
}else mailbox_templates.erase(request.source);
gameobject_query_evidence=std::move(evidence);
trace_combat(gameobject_query_evidence->published?"gameobject_query_published":"gameobject_query_presentation_held",0x5f,
selected.guid,request.source,reply.entry,reply.type,reply.display,
uint32_t(gameobject_query_evidence->presentation_holds.size()));
return projection.packet;
}
void NativeWorldTranslation::clear_inspect_selection(){
inspect_requests.retire();
inspect_name_entries.fill(0);
inspect_selection.reset();
inspect_permission.reset();
inspect_talents.reset();
inspect_transmogs.reset();
++inspect_selection_epoch;
}
std::optional<NativeWorldTranslation::InspectPeer> NativeWorldTranslation::live_inspect_peer(uint64_t guid) const{
if(!self_created || !location || logout_complete || far_transfer || pending_teleport ||
!selected.guid || !realm || realm>8191 || !guid || guid>UINT32_MAX || guid==selected.guid)return {};
auto player=entities.peer_players.find(guid);
auto actor=entities.actors.find(guid);
if(player==entities.peer_players.end() || actor==entities.actors.end())return {};
const auto& p=player->second;
const auto& a=actor->second;
if(!p.named || p.blocked || p.identity.guid!=guid || p.identity.name.empty() ||
a.kind!=4 || !a.sent || !a.eligible || !a.generation || p.generation!=a.generation ||
a.presentation_realm!=realm || a.presentation_map!=location->map ||
a.modern!=forever_player_guid(guid,realm))return {};
return InspectPeer{guid,a.generation,selected.guid,location->map,world_transfer_counter,realm};
}
void NativeWorldTranslation::boss_feed_control(std::string_view text){
if(text=="R"){boss_feed_on=true;boss_feed_spells.clear();return;}
if(text=="O"){boss_feed_on=false;boss_feed_spells.clear();return;}
if(!text.starts_with("S ") || text.size()>250)throw Error("boss feed control");
text.remove_prefix(2);
while(!text.empty()){
const auto end=text.find(' ');const auto token=text.substr(0,end);
if(token.empty() || token.size()>9 || std::any_of(token.begin(),token.end(),[](char c){return c<'0' || c>'9';}))
throw Error("boss feed spell id");
const auto spell=uint32_t(std::stoul(std::string(token)));
if(!spell || (boss_feed_spells.size()>=4096 && !boss_feed_spells.contains(spell)))throw Error("boss feed spell bound");
boss_feed_spells.insert(spell);
if(end==text.npos)break;
text.remove_prefix(end+1);
}
}
// The native client answers party invitations it alone saw expire or close (live: during a fear in Molten Core).
// With no current Source invitation there is nothing to accept or decline; it is never forwarded and never fatal.
bool NativeWorldTranslation::party_response_idle(uint32_t opcode,std::span<const uint8_t> body) const{
return opcode==0x440032 && body.size()==1 && !party_invitation_current();
}
std::optional<Bytes> NativeWorldTranslation::inspect_control(std::string_view text) const{
if(!inspect_selection || live_inspect_peer(inspect_selection->guid)!=inspect_selection ||
text!=std::to_string(realm)+" "+std::to_string(inspect_selection->guid))
throw Error("Inspect action no longer matches selected peer");
const auto now=std::chrono::steady_clock::now();
if(inspect_requests.waiting(*inspect_selection,inspect_selection_epoch,now))return {};
return pack_guid(forever_player_guid(inspect_selection->guid,realm));
}
std::optional<std::pair<uint64_t,uint64_t>> NativeWorldTranslation::authorized_inspect_peer() const{
if(!inspect_permission || inspect_permission!=inspect_selection ||
std::chrono::steady_clock::now()>=inspect_permission_until ||
live_inspect_peer(inspect_permission->guid)!=inspect_permission)return {};
return std::pair{inspect_permission->guid,inspect_permission->generation};
}
// Show Talents opens immediately after NotifyInspect. Preserve the click while
// the ordinary Inspect travels to the server, and qualify it again at send time.
void NativeWorldTranslation::begin_inspect_talents(std::string_view text){
if(!inspect_selection || live_inspect_peer(inspect_selection->guid)!=inspect_selection)return;
const auto& peer=*inspect_selection;
const auto& identity=entities.peer_players.at(peer.guid).identity;
if(text!="request "+identity.name)return;
const auto key=std::pair{peer.guid,peer.generation};
const auto now=std::chrono::steady_clock::now();
if(inspect_talents && inspect_talents->peer==key && now<inspect_talents->until)return;
inspect_talents=InspectTalentRequest{key,now+std::chrono::seconds(15)};
}
std::optional<LegacyPacket> NativeWorldTranslation::next_inspect_talents(){
if(!inspect_talents)return {};
const auto& request=*inspect_talents;
if(std::chrono::steady_clock::now()>=request.until || !inspect_selection ||
request.peer!=std::pair{inspect_selection->guid,inspect_selection->generation} ||
live_inspect_peer(request.peer.first)!=inspect_selection){
inspect_talents.reset();
return {};
}
if(request.sent || authorized_inspect_peer()!=request.peer)return {};
const auto& identity=entities.peer_players.at(request.peer.first).identity;
return LegacyPacket{0x95,turtle_inspect_talents_request(identity)};
}
std::optional<LegacyPacket> NativeWorldTranslation::next_inspect_transmogs(){
if(!inspect_transmogs)return {};
const auto& request=*inspect_transmogs;
if(std::chrono::steady_clock::now()>=request.until || authorized_inspect_peer()!=request.peer){
inspect_transmogs.reset();
return {};
}
if(request.sent)return {};
const auto& identity=entities.peer_players.at(request.peer.first).identity;
return LegacyPacket{0x95,turtle_inspect_transmogs_request(identity)};
}
std::optional<Bytes> NativeWorldTranslation::inspect_transmog_answer(std::string_view text){
auto answer=turtle_inspect_transmog_answer(text);
const auto now=std::chrono::steady_clock::now();
auto asker=transmog_askers.find(answer.asker);
// Only answer a peer that asked within the last 10 s: start + at most 19 slot rows.
if(asker==transmog_askers.end() || asker->second.until<=now || asker->second.rows>=20)return {};
++asker->second.rows;
return std::move(answer.packet);
}
std::optional<std::array<Bytes,3>> NativeWorldTranslation::inspect_ack(std::span<const uint8_t> body,uint32_t address){
// Tortoise sends only this GUID after its own distance and hostility checks.
if(body.size()!=8)return {};
Reader read(body);const auto guid=read.le(8);
const auto now=std::chrono::steady_clock::now();
const auto previous=inspect_requests.consume(guid,now);
if(!previous || previous->epoch!=inspect_selection_epoch || inspect_selection!=previous->peer ||
live_inspect_peer(guid)!=previous->peer)return {};
const auto& fields=entities.peer_players.at(guid).fields;
std::array<Bytes,3> reply;
for(unsigned layer=0;layer<reply.size();++layer){
// Tortoise Player::SetVisibleItemSlot writes visible entry, permanent
// enchant and temporary enchant consecutively within each slot.
std::array<std::optional<uint32_t>,19> slots{};
for(unsigned slot=0;slot<slots.size();++slot){
auto it=fields.find(turtle_entity_fields::PLAYER_VISIBLE_ITEM_1_0+12*slot+layer);
if(it!=fields.end())slots[slot]=it->second;
if(layer==0)inspect_name_entries[slot]=slots[slot].value_or(0);
}
reply[layer]=forever_inspect_equipment_reply(selected,{realm,address,0},uint32_t(guid),slots,layer);
}
inspect_permission=previous->peer;
inspect_permission_until=now+std::chrono::seconds(30);
inspect_transmogs=InspectTalentRequest{{previous->peer.guid,previous->peer.generation},now+std::chrono::seconds(15)};
return reply;
}
void NativeWorldTranslation::append_inspect_names(std::vector<LegacyPacket>& out,uint32_t address){
if(std::none_of(inspect_name_entries.begin(),inspect_name_entries.end(),[](auto e){return e!=0;}))return;
const auto peer=authorized_inspect_peer();
if(!peer){inspect_name_entries.fill(0);return;}
const auto& fields=entities.peer_players.at(peer->first).fields;
for(unsigned slot=0;slot<inspect_name_entries.size();++slot){
auto& entry=inspect_name_entries[slot];
if(!entry)continue;
const auto visible=fields.find(turtle_entity_fields::PLAYER_VISIBLE_ITEM_1_0+12*slot);
if(entry>0x7fffffff || visible==fields.end() || visible->second!=entry){entry=0;continue;}
const auto* source=inventory.peer_template(entry);
if(!source){
inventory.request_peer_template(entry);
continue;
}
if(source->found && source->entry==entry){
auto packets=forever_inspect_item_name(selected,{realm,address,0},uint32_t(peer->first),
slot+1,entry,source->name);
for(auto& packet:packets)out.push_back({0x4c0001,std::move(packet)});
}
entry=0;
}
}
std::optional<uint8_t> NativeWorldTranslation::source_match_team(uint64_t leader) const {
// TeamId order of the native writer: 0 Alliance, 1 Horde.
std::optional<uint8_t> race;
if(leader==selected.guid)race=selected.race;
else if(auto c=chat_players.find(leader);c!=chat_players.end())race=c->second.race;
else if(auto p=entities.peer_players.find(leader);p!=entities.peer_players.end() && p->second.named && !p->second.blocked && p->second.identity.guid==leader)race=p->second.identity.race;
if(!race)return std::nullopt;
const auto team=source_team_for_race(*race);if(!team)return std::nullopt;
return *team==SourceTeam::Alliance?0:1;
}
const GossipMenu* NativeWorldTranslation::current_npc_text_menu() const {
if (!gossip || !self_created || !location || logout_complete || far_transfer || pending_teleport)
return nullptr;
const auto actor = entities.actors.find(gossip->guid);
if (actor == entities.actors.end() || !actor->second.sent ||
actor->second.generation != gossip_actor_generation)
return nullptr;
return &*gossip;
}
namespace {
// Native ListOwnedItems {Guid, u32 Offset, bit tainted, bits2 sorts, [AddOnInfo], sorts{u8 order, bit reverse}}
// and ListBiddedItems {Guid, u32 Offset, bit tainted, bits7 ids, bits2 sorts, [AddOnInfo], ids, sorts}.
// TC lists every matching auction (no Offset window); the AddOnInfo is skipped exactly (SizedCString len+1).
struct PersonalListQuery {uint64_t npc=0;std::vector<AuctionSort> sorts;std::vector<uint32_t> ids;};
PersonalListQuery personal_list_query(uint32_t opcode,std::span<const uint8_t> body,const std::map<uint64_t,Guid128>& known){
Reader q(body);PersonalListQuery out;out.npc=bound_legacy_guid(q,known);
if(!service_unit(out.npc))throw Error("auction request outside a tracked auctioneer");
q.le(4); // Offset: TC ignores it for personal lists
uint32_t bits,ids=0,sorts;bool tainted;
if(opcode==0x3f0069){bits=uint32_t(q.le(1));tainted=bits&0x80;sorts=(bits>>5)&3;if(bits&0x1f)throw Error("owned list bit padding");}
else{bits=uint32_t((q.le(1)<<8)|q.le(1));tainted=bits&0x8000;ids=(bits>>8)&0x7f;sorts=(bits>>6)&3;if(bits&0x3f)throw Error("bidded list bit padding");}
if(tainted){auto b0=q.le(1),b1=q.le(1),b2=q.le(1);const uint32_t a=uint32_t((b0<<16)|(b1<<8)|b2);
const uint32_t name=(a>>14)&0x3ff,version=(a>>4)&0x3ff;q.take(name>1?name:0);q.take(version>1?version:0);}
for(uint32_t i=0;i<ids;++i){const auto id=uint32_t(q.le(4));if(!id || id>INT32_MAX)throw Error("bidded list auction identity");out.ids.push_back(id);}
for(uint32_t i=0;i<sorts;++i){AuctionSort s;s.order=uint8_t(q.le(1));const auto r=q.le(1);
if(r&0x7f)throw Error("auction sort bit padding");
s.reverse=r&0x80;
if(s.order>5)throw Error("auction sort order outside the Source columns");
out.sorts.push_back(s);}
q.end();return out;
}
Bytes personal_list_request(bool owned,const PersonalListQuery& q,uint32_t listfrom){
// Tortoise 0x259 {u64 npc, u32 listfrom}; 0x264 {u64 npc, u32 listfrom, u32 n, n x u32 outbid auction id}.
Bytes out;le(out,q.npc,8);le(out,listfrom,4);if(owned)return out;
le(out,q.ids.size(),4);for(auto id:q.ids)le(out,id,4);return out;
}
}
void NativeWorldTranslation::auction_commodity_resolve(bool ok){
native_presentations.push_back({forever_opcodes::SMSG_AUCTION_COMMAND_RESULT,commodity_purchase_command_result(ok)});
for(uint32_t i=0;auction_commodity && i<auction_commodity->late_failures;++i)
native_presentations.push_back({forever_opcodes::SMSG_AUCTION_COMMAND_RESULT,commodity_purchase_command_result(false)});
auction_commodity.reset();
}
void NativeWorldTranslation::auction_bid_dispatched(std::span<const uint8_t> body){
if(auction_commodity && auction_commodity->bid_queued && std::equal(body.begin(),body.end(),auction_commodity->bid.begin(),auction_commodity->bid.end())){
auction_commodity->bid_queued=false;auction_commodity->bid_sent=true;auction_commodity->bid_since=std::chrono::steady_clock::now();
}
}
void NativeWorldTranslation::auction_commodity_fail(bool confirm){
if(confirm && auction_commodity){auction_commodity_resolve(false);return;}
if(confirm)native_presentations.push_back({forever_opcodes::SMSG_AUCTION_COMMAND_RESULT,commodity_purchase_command_result(false)});
else if(auction_commodity){CommodityQuoteResult none;none.item=int32_t(auction_commodity->item);social_presentations.emplace_back(GW_CODEC_COMMODITY_QUOTE,commodity_quote_input(none));}
if(auction_commodity && !auction_commodity->bid_sent && !auction_commodity->bid_queued)auction_commodity.reset();
}
void NativeWorldTranslation::cancel_unsent_commodity(){
auto& purchase=*auction_commodity;
if(purchase.bid_sent)return;
if(purchase.bid_queued){
std::erase_if(requests,[&](const LegacyPacket& packet){
return packet.opcode==0x25a && packet.body==purchase.bid;
});
}
if(purchase.bid_queued || (purchase.confirm && purchase.awaiting))
auction_commodity_resolve(false);
else
auction_commodity.reset();
}
bool NativeWorldTranslation::auction_commodity_local(uint32_t opcode,std::span<const uint8_t> body){
Reader r(body);const auto npc=bound_legacy_guid(r,bindings());
// A bid whose Source acknowledgement never arrived has an unknown outcome: forget it, claim nothing about
// it; repeat confirms recorded meanwhile were definite failures.
if(auction_commodity && auction_commodity->bid_sent && std::chrono::steady_clock::now()-auction_commodity->bid_since>std::chrono::seconds(60)){
for(uint32_t i=0;i<auction_commodity->late_failures;++i)
native_presentations.push_back({forever_opcodes::SMSG_AUCTION_COMMAND_RESULT,commodity_purchase_command_result(false)});
auction_commodity.reset();
}
if(opcode==0x3f006e){ // CancelCommoditiesPurchase {npc, opt TaintedBy}: no Source message
const auto bits=r.le(1);if(bits&0x7f)throw Error("commodity cancel padding");
if(bits&0x80)throw Error("tainted commodity cancel");
r.end();
// Deferred requests of this house never reach Source: each still gets its one answer.
for(uint32_t op:{0x3f006cu,0x3f006du}){
auto d=auction_personal_deferred.find(op);if(d==auction_personal_deferred.end())continue;
Reader q(d->second);bool mine=false;try{mine=bound_legacy_guid(q,bindings())==npc;}catch(const Error&){mine=true;}
if(!mine)continue;
if(op==0x3f006d)native_presentations.push_back({forever_opcodes::SMSG_AUCTION_COMMAND_RESULT,commodity_purchase_command_result(false)});
else{CommodityQuoteResult none;none.item=int32_t(native_commodity_request(d->second).item);queue_social(GW_CODEC_COMMODITY_QUOTE,commodity_quote_input(none));}
auction_personal_deferred.erase(d);
}
if(auction_commodity && auction_commodity->auctioneer==npc)cancel_unsent_commodity();
return true; // a dispatched buyout stays correlated to its Source result
}
const auto c=native_commodity_request(body);
if(opcode==0x3f006d){
const bool live=auction_commodity && auction_commodity->quote && !auction_commodity->awaiting && !auction_commodity->bid_sent && !auction_commodity->bid_queued &&
auction_commodity->auctioneer==npc && auction_commodity->item==c.item && auction_commodity->quantity==c.quantity &&
std::chrono::steady_clock::now()<auction_commodity->deadline;
if(live)return false;
if(auction_commodity && (auction_commodity->bid_queued || auction_commodity->bid_sent || (auction_commodity->confirm && auction_commodity->awaiting))){
if(auction_commodity->late_failures<16)++auction_commodity->late_failures; // answered after the outstanding one
return true;
}
native_presentations.push_back({forever_opcodes::SMSG_AUCTION_COMMAND_RESULT,commodity_purchase_command_result(false)});
auction_commodity.reset();
return true;
}
const bool busy=auction_commodity && (auction_commodity->bid_sent || auction_commodity->bid_queued || (auction_commodity->confirm && auction_commodity->awaiting));
const auto* t=inventory.peer_template(c.item);
if(!busy && t && t->found && t->stack>1 && !t->name.empty())return false;
if(!t)inventory.request_peer_template(c.item);
CommodityQuoteResult none;none.item=int32_t(c.item);queue_social(GW_CODEC_COMMODITY_QUOTE,commodity_quote_input(none));
return true;
}
void NativeWorldTranslation::present_guild(uint32_t address,std::vector<LegacyPacket>& output) {
// Source charter and administrator additions can update membership without
// GE_JOINED. The native guild sends PlayerJoined to the new member before
// OnClubAdded. Only a transition observed in this session can produce it.
if (own_guild_join == OwnGuildJoin::AwaitingRoster && self_created && !logout_complete &&
realm && address && guild_id && guild_rank_info && guild_rank_info->id == guild_id && guild_management_roster) {
const auto& members = guild_management_roster->members;
const auto self = std::find_if(members.begin(), members.end(),
[&](const auto& row) { return row.guid == selected.guid; });
if (self != members.end() && (selected.name.empty() || selected.name == self->name)) {
if (auto joined = guild_player_joined(self->guid, self->name, {realm,address})) {
output.push_back(std::move(*joined));
own_guild_join = OwnGuildJoin::Presented;
}
}
}
// Preserve explicit RPC responses while withholding only the unsolicited
// membership addition if authenticated self data is still incomplete.
clubs.refresh(guild_id,selected.guid,realm,guild_rank_info,guild_management_roster,internal_source_account,
own_guild_join != OwnGuildJoin::AwaitingRoster);
clubs.take(output,&requests);
}
void NativeWorldTranslation::observe_guild_rank(uint32_t rank){
if(rank!=guild_rank)guild_roster_context.awaiting_details.reset();
const bool refresh=guild_permissions.rank_changed(guild_rank,rank);
if(rank!=guild_rank && guild_id && guild_management_roster){
// Authoritative rank transition (e.g. leadership moved): the cached management roster is stale in
// either arrival order; block management until a roster showing the new rank arrives.
guild_management_roster.reset();guild_management_pending=false;guild_rank_assignment.reset();
if(!refresh && requests.size()<4096)requests.push_back({0x89,{}});
}
if(refresh){
if(requests.size()>=4096)throw Error("native guild permissions refresh bound");
requests.push_back({0x89,{}});
}
guild_rank=rank;
}
void NativeWorldTranslation::ah_list_arm(uint16_t reply,uint64_t npc){
ah_list_inflight=true;ah_list_reply=reply;ah_list_npc=npc;ah_list_since=std::chrono::steady_clock::now();
}
void NativeWorldTranslation::addon_local(std::string_view prefix,const std::string& text){
RosterRealm ctx;ctx.realm_id=realm;ctx.virtual_address=virtual_realm_address;
try{native_presentations.push_back({0x4c0001,forever_local_addon(selected,ctx,prefix,text)});}catch(const Error&){}
}
void NativeWorldTranslation::aux_local(const std::string& text){
RosterRealm ctx;ctx.realm_id=realm;ctx.virtual_address=virtual_realm_address;
try{native_presentations.push_back({0x4c0001,forever_local_addon(selected,ctx,AuxPrefix,text)});}catch(const Error&){}
}
std::string NativeWorldTranslation::aux_name(uint64_t guid) const{
if(guid==selected.guid)return selected.name;
if(auto p=entities.peer_players.find(guid);p!=entities.peer_players.end() && p->second.named)return p->second.identity.name;
if(auto c=chat_players.find(guid);c!=chat_players.end())return c->second.name;
return {};
}
std::optional<LegacyPacket> NativeWorldTranslation::aux_request(std::string_view text){
try{
auto r=aux_source_request(text,aux_auctioneer,[&](uint64_t counter)->std::optional<uint64_t>{
for(const auto& [legacy,native]:inventory.owned_bindings()){
uint64_t low=0;for(unsigned i=0;i<8;++i)low|=uint64_t(native[i])<<(8*i);
if(low==counter)return legacy;
}
return std::nullopt;});
if(r.kind=='Q' || r.kind=='O' || r.kind=='I'){
// One Source list at a time (Tortoise throttles and answers each in order).
if(ah_list_busy()){aux_local("X;busy");return std::nullopt;}
aux_list_reply=r.kind=='Q'?0x25c:r.kind=='O'?0x25d:0x265;ah_list_arm(aux_list_reply,aux_auctioneer);
}
if(r.opcode==0x25a)ordinary_bid_since=std::chrono::steady_clock::now();
return LegacyPacket{r.opcode,std::move(r.body)};
}catch(const Error& e){aux_local(std::string("X;")+e.what());return std::nullopt;}
}
bool NativeWorldTranslation::ah_list_busy(){
// Tortoise returns without a reply (and without taking its guard) when the auctioneer check fails;
// after 15 s the request is treated as declined and its state retired.
if(ah_list_inflight && std::chrono::steady_clock::now()-ah_list_since>std::chrono::seconds(15)){
ah_list_inflight=false;ah_list_retired=false;
std::erase_if(requests,[](const LegacyPacket& p){return p.opcode==0x258 || p.opcode==0x259 || p.opcode==0x264;});
if(auction_browse && auction_browse->awaiting)auction_browse.reset();
if(auction_personal && auction_personal->awaiting)auction_personal.reset();
if(auction_commodity && auction_commodity->awaiting)auction_commodity_fail(auction_commodity->confirm);
++auction_holds;
}
return ah_list_inflight;
}
bool NativeWorldTranslation::defer_personal_list(uint32_t opcode,std::span<const uint8_t> body){
// Browse (0x3F0066) waits only for the Source guard; a personal list also waits for the previous
// personal result to publish (one snapshot slot).
const bool personal=opcode==0x3f0069 || opcode==0x3f006a;
const bool busy=ah_list_busy() || (personal && auction_personal);
if(!busy)return false;
if(opcode==0x3f0066){Reader r(body);bound_legacy_guid(r,bindings());native_auction_browse_query(body);}
else if(opcode==0x3f0068){Reader r(body);bound_legacy_guid(r,bindings());native_auction_items_by_item_query(body);}
else if(opcode==0x3f0067){Reader r(body);bound_legacy_guid(r,bindings());native_auction_items_query(body);}
else if(opcode==0x3f006b){Reader r(body);bound_legacy_guid(r,bindings());native_auction_bucket_keys_query(body);}
else if(opcode==0x3f006c || opcode==0x3f006d){Reader r(body);bound_legacy_guid(r,bindings());native_commodity_request(body);}
else personal_list_query(opcode,body,bindings()); // validate now; invalid requests reject through gameplay
auction_personal_deferred[opcode]=Bytes(body.begin(),body.end());return true;
}
void NativeWorldTranslation::start_deferred_personal_list(){
for(auto it=auction_personal_deferred.begin();it!=auction_personal_deferred.end() && !ah_list_busy() && requests.size()<4096;){
const auto opcode=it->first;
if((opcode==0x3f0069 || opcode==0x3f006a) && auction_personal){++it;continue;}
const auto body=std::move(it->second);it=auction_personal_deferred.erase(it);
try{
if((opcode==0x3f006c || opcode==0x3f006d) && auction_commodity_local(opcode,body))continue;
auto packet=gameplay(opcode,body); // same translation and checks as a direct request
requests.push_back(std::move(packet));gameplay_sent(opcode,body);
}catch(const Error& e){ // auctioneer no longer bound, or the request no longer valid
gw_inv_log("GW_AH deferred-drop native=0x%x why=%s\n",unsigned(opcode),e.what());++auction_holds;
if(opcode==0x3f006c || opcode==0x3f006d)auction_commodity_fail(opcode==0x3f006d);
}
}
}
void NativeWorldTranslation::gameplay_sent(uint32_t opcode,std::span<const uint8_t> body){
if(opcode==0x440096){
Reader r(body);auto guid=unpack_guid(r,16);auto accept=r.le(1);r.end();
if(accept!=0x80 || !summon_offer || !std::equal(guid.begin(),guid.end(),summon_offer->modern.begin()))
throw Error("summon serialization commit differs from current offer");
summon_offer.reset();return; // Already serialized; expiry cannot undo that send.
}
if(opcode==0x3f006f){auto more=commodity_sell_packets(body);for(size_t i=1;i<more.size();++i)requests.push_back(std::move(more[i]));}
if(opcode==0x440026){auto more=mail_send_packets(body);for(size_t i=1;i<more.size();++i)requests.push_back(std::move(more[i]));}
if(opcode>=0x3f0061 && opcode<=0x3f006f)gw_inv_log("GW_AH sent native=0x%x bytes=%zu\n",unsigned(opcode),body.size());
if(opcode==0x3f0066){try{const auto p=gameplay(opcode,body);std::string h;char x[4];for(auto c:p.body){snprintf(x,sizeof x,"%02x",unsigned(c));h+=x;}
const auto q=native_auction_browse_query(body);std::string cl;for(const auto& c:q.classes){cl+=std::to_string(c.item_class)+"[";for(const auto& sc:c.subclasses){cl+=std::to_string(sc.subclass)+":"+std::to_string(sc.inv_type_mask)+",";}cl+="]";}
gw_inv_log("GW_AH browse name='%s' lvl=%u-%u filters=0x%x classes=%s source=%s\n",q.name.c_str(),unsigned(q.min_level),unsigned(q.max_level),unsigned(q.filters),cl.c_str(),h.c_str());}catch(...){}}
if(opcode==0x3f00d6){
Reader r(body);const auto spell=r.le(4);r.end();
if(spell && spell==entities.self_res_spell)entities.self_res_submitted=true;
return;
}
if(opcode==0x3f0066 || opcode==0x3f0067 || opcode==0x3f0068 || opcode==0x3f006b || opcode==0x3f0069 || opcode==0x3f006a || opcode==0x3f006c || opcode==0x3f006d){
Reader q(body);const auto npc=bound_legacy_guid(q,bindings());
ah_list_arm(opcode==0x3f0069?0x25d:opcode==0x3f006a?0x265:0x25c,npc);
auction_personal_deferred.erase(opcode); // a newer request of the same kind supersedes a deferred one
}
if(opcode==0x3f006c){
Reader q(body);AuctionCommodityState s;s.auctioneer=bound_legacy_guid(q,bindings());
const auto c=native_commodity_request(body);s.item=c.item;s.quantity=c.quantity;
s.name=inventory.peer_template(c.item)->name;s.awaiting=true;auction_commodity=std::move(s);return; // replaces any earlier quote (TC: one per buyer)
}
if(opcode==0x3f0065)ordinary_bid_since=std::chrono::steady_clock::now();
if(opcode==0x3f006d){auction_commodity->confirm=true;auction_commodity->awaiting=true;auction_commodity->snapshot=AuctionSnapshot{};return;}
if(opcode==0x4400b0){
Reader q(body);const auto pet=bound_legacy_guid(q,bindings());q.le(4);const auto len=q.le(1);q.le(1);
auto name=q.take(len);q.end();
// Silent successes are never answered; past the bound, failures can no longer be attributed.
if(pet_rename_sent.size()>=8){pet_rename_sent.pop_front();if(pet_rename_dropped<64)++pet_rename_dropped;}
pet_rename_sent.push_back({pet,std::string(name.begin(),name.end())});return;
}
if(opcode==0x3f0069 || opcode==0x3f006a){
// A new personal list replaces the previous one of either kind (Tortoise serves one AH list request at a time).
AuctionPersonalState s;s.owned=opcode==0x3f0069;s.snapshot.repeats=!s.owned;auto q=personal_list_query(opcode,body,bindings());
s.auctioneer=q.npc;s.sorts=q.sorts;s.ids=q.ids;s.awaiting=true;auction_personal=std::move(s);return;
}
if(opcode==0x3f0066){
Reader r(body);AuctionBrowseState s;s.auctioneer=bound_legacy_guid(r,bindings());s.query=native_auction_browse_query(body);
s.awaiting=true;auction_browse=std::move(s);return; // a new search replaces the previous snapshot
}
if(opcode==0x3f0067 || opcode==0x3f0068 || opcode==0x3f006b){
Reader r(body);AuctionBrowseState s;s.auctioneer=bound_legacy_guid(r,bindings());
uint32_t item=0;std::vector<AuctionSort> sorts;
if(opcode==0x3f006b){
const auto q=native_auction_bucket_keys_query(body);item=q.keys.front().item;
s.query.name=inventory.peer_template(item)->name;s.query.sorts=q.sorts;s.specific_keys=true;
s.awaiting=true;auction_browse=std::move(s);return;
}
if(opcode==0x3f0068){const auto q=native_auction_items_by_item_query(body);item=q.item;sorts=q.sorts;}
else{const auto q=native_auction_items_query(body);item=q.key.item;sorts=q.sorts;s.by_key=q.key;}
s.query.name=inventory.peer_template(item)->name;s.by_item=item;s.by_item_sorts=sorts;
s.awaiting=true;auction_browse=std::move(s);return;
}
if(opcode==npc_text::Query){Reader r(body);npc_text_queries.sent(uint32_t(r.le(4)));return;}
// A new NPC interaction retires any pending greeting from the previous one.
if(opcode==0x3f0029 || opcode==0x3f0038 || opcode==0x3f0045)gossip.reset();
if(opcode==0x3e0148 && source_pet_name_query(body)){
Reader r(body);const auto by=bound_legacy_guid(r,bindings());
const auto known=bindings();if(auto it=known.find(by);it!=known.end())pet_name_pending[uint32_t((by>>24)&0xffffff)]=it->second;
if(pet_name_pending.size()>64)pet_name_pending.erase(pet_name_pending.begin());
return;
}
if(opcode==0x3e0000 && !trade.open){
Reader r(body);const auto target=bound_legacy_guid(r,bindings());r.end();
trade.close();trade.partner=target;
}
if(opcode==0x3e0002 || opcode==0x3e0003 || opcode==0x3e0006)trade.close();
if(opcode==0x3e0004)trade.notify_changed=false;
if(opcode==0x3f00cd){
Reader read(body);const auto guid=bound_legacy_guid(read,bindings(),true);read.end();
auto peer=live_inspect_peer(guid);
if(inspect_selection!=peer){
clear_inspect_selection();
inspect_selection=peer;
}
return;
}
if(opcode==0x3f00ce && inspect_selection){
const auto now=std::chrono::steady_clock::now();
inspect_requests.sent(*inspect_selection,inspect_selection_epoch,now);
inspect_permission.reset();
return;
}
if(opcode==0x2f001b){guild_permissions.sent(guild_id);return;}
if(native_guild_management_opcode(opcode) || opcode==0x2f0002){
guild_management_pending=true;
if(opcode==0x2f0002){
if(!guild_rank_info || !guild_management_roster)throw Error("rank assignment context retired");
guild_rank_assignment=GuildRankAssignment::prepare(body,*guild_rank_info,*guild_management_roster,selected.guid,realm,guild_rank).first;
}
// Member rank and guild-text edits need a fresh roster. Ask Source once
// after its real mutation, preserving TCP request order. Notes/ranks
// already receive their authoritative Source roster responses.
if(opcode==0x2f0000 || opcode==0x2f0001 || opcode==0x2f0002 || opcode==0x2f0015 || opcode==0x2f0016 || opcode==0x2f0006){
if(requests.size()>=4096)throw Error("native guild refresh queue bound");
requests.push_back({0x89,{}});
}
return;
}
if(opcode==0x2f000e){
// The successfully sent roster query supplies fresh permissions; fetch
// current names as well so rank renames do not retain old labels.
if(requests.size()>=4096)throw Error("native guild metadata queue bound");
Bytes query;le(query,guild_id,4);requests.push_back({0x54,std::move(query)});
return;
}
if(opcode==0x440025){worldport_prepared();return;}
if(opcode==0x3e0144)gameobject_query_queued(body);
if(opcode==0x44008e){Reader r(body);duel_target=bound_legacy_guid(r,bindings());return;}
if(opcode==0x3e00d8 || opcode==0x3f00db){
const auto bound=mailbox_binding(body);
mailbox_list.sent(body,bound.actor,bound.evidence);
mailbox_source=bound.actor.source_guid;next_mailbox_actor.reset();
return;
}
if(auto command=native_channel_command(opcode)) {
chat_channels.sent(chat_channels.request(*command,body));
return;
}
if(opcode==0x4400ad){pending_who=PendingWho{native_who_request(body).token,selected.guid,realm};return;}
if(location)entities.set_action_scope(selected.guid,realm,location->map);
else entities.clear_action_scope();
if(opcode==0x3e0036){
const auto state=body.front();
source_stand_pending=state==0 && source_stand && *source_stand!=0;
if(state!=0)standing_cast.reset();
// #100 (owner 2026-11-26: standing up did not cancel Exit Game): in 1.12 standing up during the camp countdown
// cancels the logout. The modern client only sends the stand change, so the genuine stand is followed by the
// Source's own LogoutCancel (the same request the dialog's Cancel sends); its ack closes the native countdown.
if(state==0 && logout_countdown && requests.size()<4096){requests.push_back({0x4e,{}});logout_countdown=false;}
}
bank_sent(opcode,body);
loot.sent(opcode,body,entities);
if(opcode==0x3f008b && location){
// #99: only after the genuine GameObjUse serialized, arm fishing loot for the player's own bobber (type 17).
Reader r(body);auto guid=bound_legacy_guid(r,bindings());r.end();
if(auto a=entities.actors.find(guid);a!=entities.actors.end() && a->second.gameobject_type==17)
{loot.confirmed_fishing_use(guid,realm,location->map,entities);
gw_inv_log("GW_FISH arm go=%llx armed=%d fishing=%d eligible=%d\n",(unsigned long long)guid,int(loot.opening.has_value()),int(loot.fishing),int(a->second.eligible));}
}
if(opcode==0x440029 || opcode==0x44002a)pending_guild_invitation=false;
if(opcode==0x440032 && party_invitation){
// Keep the accepted offer until its roster/expiry so a repeated source
// invite cannot reopen the dialog after its own OnAccept closed it.
if(source_party_invite_response(body))party_invitation->accepted=true;
else party_invitation.reset();
}
// Only an actually serialized original request from a genuinely dead,
// not-yet-released source character starts graveyard initialization.
// Preparing/sizing a request or logging in already ghosted cannot do so.
if(opcode==0x3f00cb && source_health==0 && source_ghost==false){release={};release.requested=true;}
if(opcode==0x3f00cb)trace_release("original_release_serialized");
if(opcode==0x3f0047)spirit_healer_offer.reset();
if(opcode==0x3f004a)binder_offer.reset();
if(opcode==0x3e00ca)pet_unlearn_offer.reset();
if(opcode==0x3e0212){Guid128 item{};auto text=owned_item_text(body,&item);
book_text_pending.emplace_back(text,item);}
if(opcode==0x3e0147){
Reader r(body);
const auto root=uint32_t(r.le(4));
// Client ids above 65535 are aliases (70334 ItemSparse.PageID is u16); the chain waits for the real id.
page_chains.push_back(PageChain{root,gateway::page_text_aliases::to_source(root),{}});
}
// Pet unlearn authority: only an actually sent GossipSelectOption (Source 0x17C) to the shown
// menu's NPC arms it (Tortoise: option -> CloseGossip -> 0x2F1). A new interaction retires both.
if(opcode==0x3f002b){pet_unlearn_offer.reset();
character_bank.reset();
last_gossip_npc=gossip?std::optional<SpiritHealerOffer>(SpiritHealerOffer{gossip->guid,gossip_actor_generation}):std::nullopt;}
if(opcode==0x3f0029 || opcode==0x3f0045 || opcode==0x3f0038 || opcode==0x3f004b || opcode==0x3f0061 || opcode==0x3f0028 ||
opcode==0x3f004a || opcode==0x3e0188 || opcode==0x3f005e){pet_unlearn_offer.reset();last_gossip_npc.reset();character_bank.reset();}
if(talent_reset_offer && (opcode==0x3f0029 || opcode==0x3f0045 || opcode==0x3f0038 || opcode==0x3f002b || opcode==0x3f004b)){
// A new genuinely sent NPC interaction replaces the previous offer
// context. RESET0/0 only clears the UI offer; no ranks/points change.
talent_reset_offer.reset();talent_notice="GWTURTLE1 RESET 0 0";
}
if(opcode==0x3f001f){
// The real request has already passed serialization/queue acceptance.
// Observing it must never create a request or change sheath state.
Reader r(body);auto state=uint32_t(r.le(4)),animate=uint32_t(r.le(1));r.end();
trace_combat("sheath_request",opcode,selected.guid,0,state,animate);
}else if(opcode==0x3e0171){
auto use=forever_item_use(body);queue_cast(PendingCast{use.spell,use.item});pending_item_entry=0;
Reader id(use.item);auto raw=(0x4000ULL<<48)|(id.le(8)&0xffffffff);
auto item=inventory.items.find(raw);
if(item!=inventory.items.end())pending_item_entry=item->second.fields.at(turtle_entity_fields::OBJECT_FIELD_ENTRY);
}else if(opcode==0x3e0176){
queue_cast(PendingCast{forever_spell_request(body),forever_player_guid(selected.guid,realm)});pending_item_entry=0;
uint64_t diagnostic_target=0;for(const auto& [legacy,modern]:bindings())if(modern==pending_cast->spell.unit){diagnostic_target=legacy;break;}
entities.note_spell_queued(pending_cast->spell.spell,diagnostic_target);
}
}
std::map<uint64_t,Guid128> NativeWorldTranslation::bindings() const{
std::map<uint64_t,Guid128> result;
if(self_created)result[selected.guid]=forever_player_guid(selected.guid,realm);
for(const auto& [guid,actor]:entities.actors)if(actor.sent)result[guid]=actor.modern;
return result;
}
NativeQuestTranslation::Bindings NativeWorldTranslation::quest_bindings(QuestBindingSet set) const{
NativeQuestTranslation::Bindings result;
if(!self_created || !location || logout_complete || pending_teleport || far_transfer)return result;
if(set==QuestBindingSet::All && entities.self_position_generation)
result[selected.guid]={forever_player_guid(selected.guid,realm),entities.self_position_generation,4,false};
for(const auto& [guid,actor]:entities.actors)
if(actor.sent && actor.eligible && actor.generation && actor.presentation_realm==realm && actor.presentation_map==location->map &&
(set==QuestBindingSet::All || (actor.questgiver && (actor.kind==3 || actor.kind==5))))
result[guid]={actor.modern,actor.generation,actor.kind,actor.questgiver};
if(set==QuestBindingSet::VisibleQuestGivers)return result;
for(const auto& [guid,item]:inventory.quest_starters(selected.guid))
result[guid]={item.modern,item.generation,1,false,item.quest};
return result;
}
std::optional<QuestStatusRefresh::Request> NativeWorldTranslation::next_quest_status_refresh(){
if(quest_status_refresh.pending.empty() || !quest_status_refresh.can_send(1))return std::nullopt;
return quest_status_refresh.next(quest_bindings());
}
std::optional<LegacyPacket> NativeWorldTranslation::area_trigger_request(std::span<const uint8_t> body) const{
if(!self_created || logout_complete || far_transfer)
throw Error("area trigger outside active source self");
Reader r(body);const auto ident=r.le(4);const auto control=r.le(1);r.end();
// Original70334 controlled107 reports: high-bit inside/outside transition,
// constant0x40 and zero lower6bits. Admit only these observed forms. The
// constant-bit meaning and high-bit-ID signedness remain unverified.
if(!ident || ident>0x7fffffff || (control!=0xc0 && control!=0x40))
throw Error("unobserved native area-trigger report");
if(control==0x40)return std::nullopt;
// Turtle consumes only triggerID. Its real map/position, volume(+5),
// scripts and portal requirements decide whether an entry is actionable.
Bytes request;le(request,ident,4);return LegacyPacket{0xb4,std::move(request)};
}
static void wf_guid(Bytes& out,const Guid128& g){append(out,pack_guid(g));}
// Big-endian 16-bit image of an MSB-first bit run (callers left-align the bits).
static void wf_bits16(Bytes& out,uint32_t v){out.push_back(uint8_t(v>>8));out.push_back(uint8_t(v));}
std::optional<Guid128> NativeWorldTranslation::native_guid(uint64_t source) const{
if(!source)return Guid128{};
const auto known=bindings();
if(auto it=known.find(source);it!=known.end())return it->second;
if(source<=UINT32_MAX && realm)return forever_player_guid(source,realm);
return std::nullopt;
}
bool NativeWorldTranslation::source_pet_name_query(std::span<const uint8_t> body) const{
try{Reader r(body);const auto by=bound_legacy_guid(r,bindings());r.end();return (by>>48)==0xf140 && ((by>>24)&0xffffff);}
catch(const std::exception&){return false;}
}
std::vector<LegacyPacket> NativeWorldTranslation::commodity_sell_packets(std::span<const uint8_t> body) const{
// SellCommodity {Guid npc, u64 UnitPrice, u32 RunTime, bit tainted, bits6 n, [addon], n x {Guid, u32 UseCount}}.
// Source auctions one whole item stack per CMSG_AUCTION_SELL_ITEM: each native stack becomes its own
// auction (start bid = buyout = unit price x stack), like aux posting N stacks.
Reader q(body);const auto npc=bound_legacy_guid(q,bindings());
if(!service_unit(npc))throw Error("auction request outside a tracked auctioneer");
const auto unit=q.le(8);const auto minutes=uint32_t(q.le(4));const auto bits=q.le(1);
const bool tainted=bits&0x80;const auto count=(bits>>1)&0x3f;if(bits&1)throw Error("commodity sell bit padding");
if(tainted){auto b0=q.le(1),b1=q.le(1),b2=q.le(1);const uint32_t ab=uint32_t((b0<<16)|(b1<<8)|b2);
const uint32_t name=(ab>>14)&0x3ff,version=(ab>>4)&0x3ff;q.take(name>1?name:0);q.take(version>1?version:0);}
if(!count)throw Error("commodity auction without items");
if(!unit)throw Error("commodity price outside Source bounds");
if(minutes!=120 && minutes!=480 && minutes!=1440)throw Error("auction duration outside Source 2/8/24 h");
// The native client names the stacks it would draw from, but Source can only auction whole stacks.
// Sell exactly the requested quantity from whole carried stacks: one stack of exactly that size first
// (the AH stack poster splits bags into the chosen stack size beforehand, like aux), else the listed
// stacks when all are whole, else the fewest whole stacks summing to the quantity.
const auto& items=inventory.owned_bindings();std::set<uint64_t> seen;uint64_t quantity=0;uint32_t entry=0;
std::vector<uint64_t> listed;bool listed_whole=true;
for(uint32_t i=0;i<count;++i){
const auto item=bound_legacy_guid(q,items);const auto use=q.le(4);
if(!seen.insert(item).second)throw Error("commodity stack listed twice");
auto record=inventory.items.find(item);if(record==inventory.items.end())throw Error("commodity item outside owned inventory");
auto e=record->second.fields.find(3);const auto id=e==record->second.fields.end()?0u:e->second;
if(!id || (entry && id!=entry))throw Error("commodity auction mixes items");
entry=id;
auto stack=record->second.fields.find(14);const auto have=stack==record->second.fields.end()?0u:stack->second;
if(!use || use>have)throw Error("commodity quantity above carried stack");
if(use!=have)listed_whole=false;
quantity+=use;listed.push_back(item);
}
q.end();
std::vector<uint64_t> chosen;
const auto stacks=inventory.carried_stacks(selected.guid,entry);
for(const auto& [guid,n]:stacks)if(n==quantity){chosen={guid};break;}
if(chosen.empty() && listed_whole)chosen=listed;
if(chosen.empty() && quantity<=20000){
// fewest whole stacks with an exact sum (stacks are small; quantity is bounded by the bags)
constexpr uint32_t none=~0u;std::vector<uint32_t> best(quantity+1,none);std::vector<std::pair<int,uint64_t>> from(quantity+1,{-1,0});
best[0]=0;
for(size_t k=0;k<stacks.size();++k){const auto n=stacks[k].second;
for(uint64_t v=quantity;v>=n && v>0;--v)if(best[v-n]!=none && best[v-n]+1<best[v]){best[v]=best[v-n]+1;from[v]={int(k),v-n};}}
if(best[quantity]!=none)for(uint64_t v=quantity;v;v=from[v].second)chosen.push_back(stacks[size_t(from[v].first)].first);
}
if(chosen.empty())throw Error("partial-stack commodity auction has no Source form");
std::vector<LegacyPacket> out;
for(const auto item:chosen){
uint32_t n=0;for(const auto& [guid,c]:stacks)if(guid==item)n=c;
if(!n){auto record=inventory.items.find(item);auto stack=record->second.fields.find(14);n=stack==record->second.fields.end()?1u:stack->second;}
const auto total=unit*n;if(total>2000000000)throw Error("commodity price outside Source bounds");
Bytes b;le(b,npc,8);le(b,item,8);le(b,total,4);le(b,total,4);le(b,minutes,4);out.push_back({0x256,std::move(b)});
}
return out;
}
bool NativeWorldTranslation::service_shortcut(const GossipMenu& menu) const{
// One plain service option, no quests: no-gossip NPCs (their menu is the Source default list) and
// one-option bankers open the service directly. Gossip NPCs with own text, several options,
// quests or coded/money options keep their menu.
if(menu.options.size()!=1 || !menu.quests.empty() || menu.options.front().coded)return false;
auto actor=entities.actors.find(menu.guid);
if(actor==entities.actors.end() || actor->second.kind!=3)return false;
const auto flags=actor->second.npc_flags;
if(!(flags&1u))return flags!=0;
return (flags&0x100u) && menu.options.front().icon==6;
}
std::optional<LegacyPacket> NativeWorldTranslation::take_summon_presentation(uint32_t address){
if(!summon_offer)return {};
if(logout_complete || summon_offer->owner!=selected.guid || summon_offer->realm!=realm ||
std::chrono::steady_clock::now()>=summon_offer->expires){summon_offer.reset();return {};}
if(summon_offer->presented || !self_created || !location || far_transfer || pending_teleport || !address)return {};
Bytes out=pack_guid(summon_offer->modern);le(out,address,4);le(out,summon_offer->zone,4);
le(out,0,1);le(out,0,1); // Reason SPELL, no SkipStartingArea.
summon_offer->map=location->map;
summon_offer->presented=true; // No deadline extension and no second presentation.
return LegacyPacket{0x4701cd,std::move(out)};
}
std::optional<LegacyPacket> NativeWorldTranslation::summon_response(std::span<const uint8_t> body) const{
Reader r(body);auto guid=unpack_guid(r,16);auto accept=r.le(1);r.end();
if(accept&0x7f)throw Error("summon response reserved bits");
if(!summon_offer || !summon_offer->presented || !self_created || !location || logout_complete || far_transfer || pending_teleport ||
summon_offer->owner!=selected.guid || summon_offer->realm!=realm || summon_offer->map!=location->map ||
std::chrono::steady_clock::now()>=summon_offer->expires ||
!std::equal(guid.begin(),guid.end(),summon_offer->modern.begin()))
throw Error("summon response without current Source offer");
if(!accept)return {}; // Source handler always accepts: never send a decline to it.
Bytes out;le(out,summon_offer->source,8);return LegacyPacket{0x2ac,std::move(out)};
}
bool NativeWorldTranslation::summon_decline(uint32_t opcode,std::span<const uint8_t> body){
if(opcode!=0x440096)return false;
if(summon_response(body))return false;
summon_offer.reset();return true;
}
LegacyPacket NativeWorldTranslation::gameplay(uint32_t opcode,std::span<const uint8_t> body) const{
if(opcode==0x440096){
auto response=summon_response(body);
if(!response)throw Error("summon decline is local-only");
return *response;
}
if(opcode==0x3f00ce){
if(!inspect_selection || live_inspect_peer(inspect_selection->guid)!=inspect_selection)
throw Error("inspect requires the current selected peer");
const auto expected=pack_guid(forever_player_guid(inspect_selection->guid,realm));
if(!std::equal(body.begin(),body.end(),expected.begin(),expected.end()))
throw Error("inspect payload differs from the selected peer identity");
if(!inspect_requests.can_send(inspect_selection->guid))
throw Error("Inspect count exhausted for this peer");
Bytes request;le(request,inspect_selection->guid,8);return {0x114,std::move(request)};
}
if(opcode==0x440025)return worldport_response(body);
if(far_transfer)throw Error("gameplay while source world transfer is pending");
if(opcode==0x3e018b){
if(!self_created)throw Error("PvP request before source self-create");
return {0x253,source_set_pvp_request(body)};
}
if(opcode==0x440074){
if(!self_created || !loot.group || loot.group_transition || loot.group->explicit_solo || loot.group->leader!=selected.guid)
throw Error("loot method outside current source group leader");
Reader r(body);auto optional=r.le(1);if(optional&0x7f)throw Error("loot method optional bits");
auto method=r.le(1);auto master=unpack_guid(r,16);auto threshold=r.le(4);
if((optional&0x80) && r.le(1)!=0)throw Error("loot method outside home group");
r.end();
if(method>4 || threshold<1 || threshold>5)throw Error("source loot policy range");
uint64_t source_master=0;
if(method==2){
auto own=forever_player_guid(selected.guid,realm);
if(std::equal(own.begin(),own.end(),master.begin()))source_master=selected.guid;
for(const auto& member:loot.group->members){auto id=forever_player_guid(member.guid,realm);if(std::equal(id.begin(),id.end(),master.begin()))source_master=member.guid;}
if(!source_master)throw Error("loot master outside authoritative source roster");
}else if(std::any_of(master.begin(),master.end(),[](uint8_t value){return value!=0;}))throw Error("non-master method carries master identity");
Bytes request;le(request,method,4);le(request,source_master,8);le(request,threshold,4);return {0x7a,std::move(request)};
}
if(opcode==0x440075){
// Original LeaveGroup::Read: MSB optional PartyIndex. Classic has
// one represented home group; the source decides leave/disband.
Reader r(body);auto optional=r.le(1);
if(optional&0x7f)throw Error("unsupported leave-party optional bits");
if((optional&0x80) && r.le(1)!=0)throw Error("leave outside represented home party");
r.end();return {0x7b,{}};
}
if(auto command=native_channel_command(opcode)) {
if(*command==ChannelCommand::Join && body.size()>=6){
// Numeric-only header evidence (ChatChannelId, 16-bit flag/length word);
// the channel name is never journaled.
gw_diagnostics::journal().packet(gw_diagnostics::Stream::Error,0x7d0010u,uint32_t(body[0])|uint32_t(body[1])<<8|uint32_t(body[2])<<16|uint32_t(body[3])<<24);
gw_diagnostics::journal().packet(gw_diagnostics::Stream::Error,0x7d0011u,uint32_t(body[4])<<8|body[5]);
}
auto request=chat_channels.request(*command,body);
return {request.opcode,std::move(request.body)};
}
if(auto request=bank_request(opcode,body))return *request;
if(!self_created)throw Error("gameplay before authenticated self-create");
if(opcode==0x44010c){
// TC TutorialSetFlag::Read: Bits<2> Action (0 update, 1 clear, 2 reset); u32 TutorialBit
// only for update. Tortoise: CMSG_TUTORIAL_FLAG 0xFE {u32}, _CLEAR 0xFF, _RESET 0x100.
Reader r(body);const auto bits=uint32_t(r.le(1));
if(bits&0x3f)throw Error("tutorial action padding");
const auto action=bits>>6;
if(action==0){
const auto bit=uint32_t(r.le(4));r.end();
if(bit>=256)throw Error("tutorial bit outside the 8 Source tutorial words");
Bytes out;le(out,bit,4);return {0xfe,std::move(out)};
}
r.end();
if(action==1)return {0xff,{}};
if(action==2)return {0x100,{}};
throw Error("unknown tutorial action");
}
if(gw_battleground_request(opcode)) {
if(!location || logout_complete)throw Error("battleground request outside active world");
if(opcode==GW_BATTLEFIELD_PORT)return battlegrounds.port(body, forever_player_guid(selected.guid, realm));
return auction_battleground::battlefield_request(opcode, body, location->map);
}
if(opcode==0x3e0144){
const auto query=forever_gameobject_query(body);auto guid=gameobject_query_actor(query);
if(gameobject_queries.contains(query.entry) || gameobject_queries.size()>=256)
throw Error("game-object query pending-entry bound");
return {0x5e,turtle_gameobject_query(query.entry,guid)};
}
if(opcode==0x3e00d8 || opcode==0x3f00db){
const auto bound=mailbox_binding(body);
const auto request=mailbox_list.prepare(body,bound.actor,bound.evidence);
return {request.source_opcode,request.source_body};
}
// 0x4400AF..0x4400B2 follow WowPacketParser V1_60_1_69876 (RESURRECT_RESPONSE 0xAF, PET_RENAME 0xB0,
// BUG_REPORT 0xB1, SET_SAVED_INSTANCE_EXTEND 0xB2) like the measured neighbours 0x440094/0x4400F9; upstream
// advocaite/TrinityCore confirmed the old +1 guess live (pet rename arrived as resurrect response).
if(opcode==0x4400af){ // ResurrectResponse: offerer, u32 Response (0 accept) -> Source u64, u8 status (1 accept)
Reader r(body);const auto by=bound_legacy_guid(r,bindings());const auto response=r.le(4);r.end();
if(!by)throw Error("resurrect response for an unbound offerer");
Bytes out;le(out,by,8);le(out,response==0?1:0,1);return {0x15c,std::move(out)};
}
if(opcode==0x3f0073 || opcode==0x4400ca){
Reader r(body);r.end();if(pending_time_kinds.size()>=16)throw Error("time request queue bound");
pending_time_kinds.push_back(opcode==0x4400ca);return {0x1ce,{}};
}
if(opcode==0x3e0147){ // QueryPageText: u32 page, item/object GUID
Reader r(body);
const auto page=r.le(4);
if(!page || page_chains.size()>=16)throw Error("page query has no root or no free response slot");
auto known=bindings();
const auto& owned=inventory.owned_bindings();
known.insert(owned.begin(),owned.end());
const auto by=bound_legacy_guid(r,known);
r.end();
Bytes out;le(out,gateway::page_text_aliases::to_source(uint32_t(page)),4);le(out,by,8);return {0x5a,std::move(out)};
}
if(opcode==0x3e0148){ // QueryPetName for a Source pet (0xf140, pet number in bits 24..47)
if(!source_pet_name_query(body))throw Error("pet name query for a non-Source pet");
Reader r(body);const auto by=bound_legacy_guid(r,bindings());r.end();
Bytes out;le(out,(by>>24)&0xffffff,4);le(out,by,8);return {0x52,std::move(out)};
}
if(opcode==0x44008e){
// CanDuel: TargetGUID (packed), ToTheDeath bit. The Source starts a duel by casting Duel 7266 at the target.
Reader r(body);const auto target=bound_legacy_guid(r,bindings());(void)r.le(1);r.end();
if(!target || target>UINT32_MAX || target==selected.guid)throw Error("duel target is not another bound player");
Bytes cast;le(cast,7266,4);le(cast,0x0002,2);Bytes raw;le(raw,target,8);append(cast,pack_guid(raw));
return {0x12e,std::move(cast)};
}
if(opcode==0x3f007f){
// DuelResponse: ArbiterGUID (packed), Accepted bit, Forfeited bit -> CMSG_DUEL_ACCEPTED / CANCELLED (u64 flag).
Reader r(body);(void)unpack_guid(r,16);const auto bits=uint8_t(r.le(1));r.end();
if(!duel_flag)throw Error("duel response without a Source duel");
const bool accepted=(bits&0x80) && !(bits&0x40);
return {uint32_t(accepted?0x16c:0x16d),source_duel_flag(duel_flag)};
}
if(opcode==0x3f00dc || opcode==0x3f00dd || opcode==0x3f00de || opcode==0x3f00df || opcode==0x3f00e0 ||
opcode==0x3e00e9 || opcode==0x440026 || opcode==0x440081)return mail_request(opcode,body);
if(opcode==0x3f001e || opcode==0x3f00e6 || opcode==0x2d0024)return emote_request(opcode,body);
if(opcode==0x3e00cc || opcode==0x3e00cd || opcode==0x3e00d2 || opcode==0x3e00d3)return loot.gameplay(opcode,body,entities);
if(opcode==0x3f008b){
// Classic70334 GameObjUse::Read is packed128 GUID only. ReportUse
// has different source semantics and is deliberately not redirected.
Reader r(body);auto guid=bound_legacy_guid(r,bindings());r.end();
auto actor=entities.actors.find(guid);
if(!location || pending_teleport || actor==entities.actors.end() ||
actor->second.kind!=5 || !actor->second.sent || !actor->second.eligible ||
!actor->second.generation || actor->second.presentation_realm!=realm ||
actor->second.presentation_map!=location->map ||
actor->second.modern!=forever_game_object_guid(guid,actor->second.entry,realm,location->map))
throw Error("game-object use outside current source binding");
gw_inv_log("GW_GOSSIP use go=%llx entry=%u\n",(unsigned long long)guid,actor->second.entry);
Bytes out;le(out,guid,8);return {0xb1,std::move(out)};
}
if(opcode==0x3f0074){
// Original LogoutRequest::Read accepts an empty historical payload
// or one MSB IdleLogout bit. Turtle has no idle-logout distinction;
// reject that unrepresented policy rather than changing its meaning.
Reader r(body);if(r.left() && r.le(1)!=0)throw Error("unsupported idle logout policy");r.end();
return {0x4b,{}};
}
if(opcode==0x3f0075){Reader r(body);r.end();return {0x4e,{}};}
/* #115 (owner: new-character mobs evade/flap until relog): Source START 0xfa sets
* watching_cinematic_entry, and Unit::IsTargetable refuses that player until COMPLETE 0xfc
* (MiscHandler.cpp:991 -> Player::CinematicEnd) arrives. The 70334 client sends empty
* CMSG_COMPLETE_CINEMATIC 0x3f00ea and CMSG_NEXT_CINEMATIC_CAMERA 0x3f00e9 (LOCAL capture
* 2026-11-30); both are empty in Source 1.12 too, so they are forwarded unchanged. */
if(opcode==0x3f00ea){Reader r(body);r.end();return {0xfc,{}};}
if(opcode==0x3f00e9){Reader r(body);r.end();return {0xfb,{}};}
if(opcode==0x44008c){
Reader r(body);auto requested=unpack_guid(r,16);r.end();
auto own=forever_player_guid(selected.guid,realm);
if(!std::equal(requested.begin(),requested.end(),own.begin()))throw Error("corpse query outside authenticated player");
return {0x216,{}};
}
if(opcode==0x3f0078){
Reader r(body);auto guid=bound_legacy_guid(r,bindings());r.end();
auto actor=entities.actors.find(guid);
if(actor==entities.actors.end() || actor->second.kind!=7 || !actor->second.sent || actor->second.corpse_owner!=selected.guid)
throw Error("reclaim outside current own corpse binding");
Bytes out;le(out,guid,8);return {0x1d2,std::move(out)};
}
if(opcode==0x3f00cb){
// Original RepopRequest::Read consumes one MSB CheckInstance bit.
// Tortoise HandleRepopRequestOpcode reads no body; it validates death,
// creates the corpse/ghost and schedules its own graveyard teleport.
Reader r(body);auto bits=r.le(1);r.end();
if(bits&0x7f)throw Error("unsupported native release-spirit bit payload");
return {0x15a,{}};
}
if(opcode==0x3f0047){
Reader r(body);auto guid=bound_legacy_guid(r,bindings());r.end();
auto actor=entities.actors.find(guid);
if(!spirit_healer_offer || spirit_healer_offer->guid!=guid || actor==entities.actors.end() ||
actor->second.kind!=3 || !actor->second.sent || actor->second.generation!=spirit_healer_offer->generation)
throw Error("spirit-healer activation without current server offer");
Bytes out;le(out,guid,8);return {0x21c,std::move(out)};
}
if(opcode==0x3f005e || opcode==0x3f005f || opcode==0x3f0060 || opcode==0x3e014b ||
opcode==0x3f00d8 || opcode==0x3f00d9 || opcode==0x3f00da || opcode==0x4400f8){
auto known=bindings();
auto npc=[&](const Bytes& native)->uint64_t{
for(const auto& [legacy,modern]:known)if((legacy>>48)==0xf130 && Bytes(modern.begin(),modern.end())==native)return legacy;
return 0;
};
auto source=source_petition_request(opcode,body,npc);
if(!source)throw Error("petition request has no Source form");
return {source->opcode,std::move(source->body)};
}
if(opcode==0x3e00ca){
// CMSG_CONFIRM_RESPEC_WIPE {Guid RespecMaster, u8 RespecType}: only type 3 naming the offering
// trainer, while the offered pet is still the current Source pet -> CMSG_PET_UNLEARN 0x2F0 {u64}.
Reader r(body);auto master=unpack_guid(r,16);auto type=r.le(1);r.end();
if(type!=3 || !pet_unlearn_offer_live())throw Error("respec confirm outside a live Source pet unlearn offer");
auto known=bindings();
if(master!=Bytes(known.at(pet_unlearn_offer->trainer).begin(),known.at(pet_unlearn_offer->trainer).end()))throw Error("respec confirm names another trainer");
Bytes out;le(out,pet_unlearn_offer->pet,8);return {0x2f0,std::move(out)};
}
if(opcode==0x3e0156){
// CMSG_MOUNT_SPECIAL_ANIM {u32 n, i32 SequenceVariation, n x i32 kit} -> Tortoise 0x171 (empty).
// The Source relays only the player GUID, so the native kits are not representable there.
Reader r(body);auto n=r.le(4);r.le(4);if(n>2)throw Error("mount special kit bound"); // TC Array<int32,2>
for(uint64_t i=0;i<n;++i)r.le(4);
r.end();return {0x171,{}};
}
if(opcode==0x3e0188 || opcode==0x3e0186){
// CMSG_TABARD_VENDOR_ACTIVATE {Guid Vendor, i32 Type} / CMSG_SAVE_GUILD_EMBLEM {Guid Vendor, 5 x i32}.
Reader r(body);auto guid=bound_legacy_guid(r,bindings());
if((guid>>48)!=0xf130)throw Error("tabard vendor outside a tracked creature");
Bytes out;le(out,guid,8);
if(opcode==0x3e0188){
auto type=r.le(4);r.end();
if(type!=0)throw Error("personal tabard vendor has no Source form"); // TabardVendorType::Guild only
return {0x1f2,std::move(out)};
}
for(int i=0;i<5;++i)le(out,r.le(4),4); // emblem style/color, border style/color, background
r.end();return {0x1f1,std::move(out)};
}
if(opcode==0x3f0028){
// CMSG_REQUEST_STABLED_PETS {Guid StableMaster} -> Tortoise MSG_LIST_STABLED_PETS {u64 npc}.
Reader r(body);auto guid=bound_legacy_guid(r,bindings());r.end();
if((guid>>48)!=0xf130)throw Error("stable request outside a tracked creature");
Bytes out;le(out,guid,8);return {0x26f,std::move(out)};
}
if(opcode==0x3e0012){
// CMSG_SET_PET_SLOT: only against the current Source snapshot of this stablemaster.
const auto q=native_set_pet_slot(body);
if(!stable || !stable->published || q.master!=Bytes(stable->master.begin(),stable->master.end()))throw Error("pet slot change outside the open stable");
auto source=source_set_pet_slot(q,stable->list);
if(!source)throw Error("pet slot change has no Source form");
return *source;
}
if(opcode==0x3f004a){
// CMSG_BINDER_ACTIVATE (client 0x3F004A) {Guid Unit} after the native Binder confirmation -> Tortoise 0x1B5 {u64}.
Reader r(body);auto guid=bound_legacy_guid(r,bindings());r.end();
auto actor=entities.actors.find(guid);
if(!self_created || !location || logout_complete || pending_teleport || far_transfer ||
!binder_offer || binder_offer->guid!=guid || actor==entities.actors.end() ||
actor->second.kind!=3 || !actor->second.sent || !actor->second.eligible || !actor->second.generation ||
actor->second.presentation_realm!=realm || actor->second.presentation_map!=location->map ||
actor->second.generation!=binder_offer->generation)
throw Error("binder activation without current server offer");
Bytes out;le(out,guid,8);return {0x1b5,std::move(out)};
}
if(opcode==0x2d0008)return {0x95,turtle_whisper_request(body,realm,virtual_realm_address)};
if(opcode==0x2d0025 || opcode==0x2d0026 || opcode==0x2d0027 || opcode==0x2d0029){
// Native Yell/Party/Raid/RaidWarning (TC 0x2C0025..29) -> Tortoise CMSG_MESSAGECHAT types 5/1/2/0x58.
// Tortoise enforces membership, leader/assistant rights and language; nothing is decided here.
const uint8_t type=opcode==0x2d0025?5:opcode==0x2d0026?1:opcode==0x2d0027?2:0x58;
return {0x95,turtle_chat_request(body,type,selected.race)};
}
if(opcode==0x2d000f || opcode==0x2d0010)return {0x95,turtle_away_request(body,opcode==0x2d0010)};
if(opcode==0x2f0003){
// CMSG_GUILD_LEAVE (WPP 0x2F0003, empty) -> Tortoise CMSG_GUILD_LEAVE 0x08D (empty).
Reader r(body);r.end();if(!guild_id)throw Error("guild leave outside a Source guild");
return {0x8d,{}};
}
if(opcode==0x3f0082){
// CMSG_UNLEARN_SKILL (WPP 0x3F0082) {i32 SkillLine} -> Tortoise 0x202 {u32}; Tortoise checks
// SkillRaceClassInfo SKILL_FLAG_UNLEARNABLE itself. SkillLine IDs are shared with the native client.
Reader r(body);const auto skill=r.le(4);r.end();if(!skill || skill>0xffff)throw Error("unlearn skill bound");
Bytes legacy;le(legacy,skill,4);return {0x202,std::move(legacy)};
}
if(opcode==0x3f00d6){
// CMSG_SELF_RES (WPP 0x3F00D6) {i32 SpellID} -> Tortoise CMSG_SELF_RES 0x2B3 (empty). Tortoise casts
// its own PLAYER_SELF_RES_SPELL and clears it. Match the selected option before forwarding.
Reader r(body);auto spell=r.le(4);r.end();if(!spell || spell>0x7fffffff)throw Error("self-res spell request");
if(!location || far_transfer || pending_teleport || logout_complete || !entities.self_presentation_ready)
throw Error("self-res outside current world");
// Only the spell Tortoise currently offers: a stale popup must not consume a different, newer offer.
if(spell!=entities.self_res_spell || entities.self_res_submitted)throw Error("self-res spell is not the current source offer");
return {0x2b3,{}};
}
if(opcode==0x2d000d || opcode==0x2d000e){
if(!guild_id)throw Error("guild chat before real membership");
return {0x95,turtle_chat_request(body,opcode==0x2d000d?3:4)};
}
if(opcode==0x440030){
try{return {0x6e,source_party_invite_request(body,virtual_realm_address)};}
catch(const Error&){
// Numeric-only failure facts: 0x7d0020 = first byte | last byte<<8 | size<<16,
// 0x7d0021 = whether target address bytes 4..7 equal our virtual address (1), are zero (0) or differ (2).
if(!body.empty()){
gw_diagnostics::journal().packet(gw_diagnostics::Stream::Error,0x7d0020u,uint32_t(body.front())|uint32_t(body.back())<<8|uint32_t(std::min<size_t>(body.size(),0xffff))<<16);
if(body.size()>=8){const uint32_t a=uint32_t(body[4])|uint32_t(body[5])<<8|uint32_t(body[6])<<16|uint32_t(body[7])<<24;
gw_diagnostics::journal().packet(gw_diagnostics::Stream::Error,0x7d0021u,a==virtual_realm_address?1u:a==0?0u:2u);}
// 0x7d0022 = name length | realm length<<9 | GUID low mask<<18 | (high mask!=0)<<26;
// 0x7d0023 = bytes left after the name (the unexplained tail length).
if(body.size()>=10){
const uint32_t n=(uint32_t(body[1])<<1)|(body[2]>>7),realm_len=((uint32_t(body[2])&127)<<2)|(body[3]>>6);
const uint32_t lo=body[8],hi=body[9];
gw_diagnostics::journal().packet(gw_diagnostics::Stream::Error,0x7d0022u,n|realm_len<<9|lo<<18|uint32_t(hi!=0)<<26);
const size_t used=10+std::popcount(lo)+std::popcount(hi)+n+realm_len;
gw_diagnostics::journal().packet(gw_diagnostics::Stream::Error,0x7d0023u,body.size()>=used?uint32_t(body.size()-used):0xffffu);
// 0x7d0024 = byte0 | (byte3 low 6 bits, the spare bits after both 9-bit lengths)<<8 | last byte<<16:
// tells whether the unexplained tail is the optional PartyIndex and where its presence bit sits.
gw_diagnostics::journal().packet(gw_diagnostics::Stream::Error,0x7d0024u,uint32_t(body[0])|uint32_t(body[3]&0x3f)<<8|uint32_t(body.back())<<16);
}
}
throw;
}
}
if(opcode==0x440032){
if(!party_invitation_current())throw Error("party response without current presented Source invitation");
return {source_party_invite_response(body)?0x72u:0x73u,{}};
}
if(opcode>=0x3e0000 && opcode<=0x3e0009){
// Native trade requests -> Source CMSG_*_TRADE 0x116-0x11F (same order).
const uint32_t source_opcode=0x116+(opcode-0x3e0000);
Reader r(body);
switch(opcode-0x3e0000){
case 0:{auto guid=bound_legacy_guid(r,bindings());r.end();
if(trade.partner && trade.partner!=guid)throw Error("another trade is pending");
if(!guid || guid>UINT32_MAX || guid==selected.guid)throw Error("trade target is not another bound player");
return {source_opcode,source_initiate_trade(guid)};}
case 4:{
const auto revision=r.le(4);r.end();
if(!trade.open || !trade.partner)throw Error("trade acceptance outside a presented trade");
if(revision!=trade.offers[1].revision)throw TradeOfferChanged("partner offer revision changed");
return {source_opcode,source_accept_trade()};}
case 7:{auto trade_slot=uint8_t(r.le(1));auto bag=uint8_t(r.le(1)),slot=uint8_t(r.le(1));r.end();
if(trade_slot>=TRADE_SLOT_COUNT)throw Error("trade slot bound");
auto from=inventory.position(bag,slot);if(!from.item)throw Error("trade item outside authenticated inventory");
return {source_opcode,source_set_trade_item(trade_slot,from.bag,from.slot)};}
case 8:{auto trade_slot=uint8_t(r.le(1));r.end();if(trade_slot>=TRADE_SLOT_COUNT)throw Error("trade slot bound");
return {source_opcode,source_clear_trade_item(trade_slot)};}
case 9:{auto gold=r.le(8);r.end();if(gold>UINT32_MAX)throw Error("trade gold exceeds Source u32");
return {source_opcode,source_set_trade_gold(uint32_t(gold))};}
default:r.end();return {source_opcode,source_empty_trade()};
}
}
if(opcode==0x440077 || opcode==0x44007c || opcode==0x44005e || opcode==0x44005f || opcode==0x440076){
// Native group requests (MinimapPingClient, UpdateRaidTarget, DoReadyCheck,
// ReadyCheckResponseClient, SetPartyLeader). Bit 0x80 = optional PartyIndex.
if(!loot.group || loot.group->explicit_solo)throw Error("group request outside a Source group");
Reader r(body);auto bits=r.le(1);const bool index=bits&0x80;
auto party_index=[&]{if(index && r.le(1)!=0)throw Error("group request foreign party index");r.end();};
auto member=[&](const Bytes& g)->uint64_t{
for(const auto& m:loot.group->members){auto e=forever_player_guid(m.guid,realm);if(std::equal(g.begin(),g.end(),e.begin()))return m.guid;}
throw Error("group request target outside Source roster");
};
if(opcode==0x440077){
if(bits&0x7f)throw Error("minimap ping bits");
auto x=r.take(4),y=r.take(4);party_index();
Bytes out;append(out,x);append(out,y);return {0x1d5,std::move(out)};
}
if(opcode==0x44007c){
if(bits&0x7f)throw Error("raid target bits");
auto target=unpack_guid(r,16);auto symbol=int8_t(r.le(1));party_index();
Bytes out;
if(symbol==-1){le(out,0xff,1);return {0x321,std::move(out)};}
if(symbol<0 || symbol>7)throw Error("raid target symbol bound");
uint64_t id=0;
if(target!=Bytes(16)){
for(const auto& [source_id,native]:bindings())if(std::equal(target.begin(),target.end(),native.begin())){id=source_id;break;}
if(!id)id=member(target);
}
le(out,symbol,1);le(out,id,8);return {0x321,std::move(out)};
}
if(opcode==0x44005e){
if(bits&0x7f)throw Error("ready check bits");
party_index();return {0x322,{}};
}
if(opcode==0x44005f){
if(bits&0x3f)throw Error("ready check response bits");
party_index();
Bytes out;le(out,(bits&0x40)?1:0,1);return {0x322,std::move(out)};
}
if(bits&0x7f)throw Error("set leader bits");
auto target=unpack_guid(r,16);party_index();
Bytes out;le(out,member(target),8);return {0x78,std::move(out)};
}
if(opcode==0x440094){ // CMSG_RESET_INSTANCES (TC 0x430094, empty) -> Tortoise 0x31D (empty). Tortoise decides
// leader/solo authority and answers with SMSG_INSTANCE_RESET(_FAILED) 0x31E/0x31F, already presented.
if(!body.empty())throw Error("reset instances body");
return {0x31d,{}};
}
if(opcode==0x440073 || opcode==0x440078 || opcode==0x440079 || opcode==0x44007a || opcode==0x44007b){
// Raid management (PartyUninvite, ChangeSubGroup, SwapSubGroups, ConvertRaid,
// SetAssistantLeader). Targets resolve only through the authoritative Source
// roster; Tortoise moves subgroup members by name, the others by GUID.
if(!loot.group || loot.group->explicit_solo)throw Error("raid request outside a Source group");
Reader r(body);
auto party_index=[&](bool present){if(present && r.le(1)!=0)throw Error("raid request foreign party index");};
auto member=[&](const Bytes& g)->const TurtleGroupMember*{
for(const auto& m:loot.group->members){auto e=forever_player_guid(m.guid,realm);if(g.size()==e.size() && std::equal(g.begin(),g.end(),e.begin()))return &m;}
return nullptr;
};
auto name_of=[&](const Bytes& g)->std::string{
auto self=forever_player_guid(selected.guid,realm);
if(g.size()==self.size() && std::equal(g.begin(),g.end(),self.begin()))return selected.name;
if(auto m=member(g); m && !m->name.empty())return m->name;
throw Error("raid request target outside Source roster");
};
auto guid_of=[&](const Bytes& g)->uint64_t{if(auto m=member(g))return m->guid;throw Error("raid request target outside Source roster");};
Bytes out;
if(opcode==0x44007a){ // ConvertRaid: Tortoise converts party -> raid only.
const auto bits=r.le(1);r.end();if(bits!=0x80)throw Error("convert raid outside party-to-raid");
return {0x28e,{}};
}
if(opcode==0x440073){
const auto b0=r.le(1),b1=r.le(1);if(b1&0x3f)throw Error("uninvite bits");
const auto reason=size_t(((b0&0x7f)<<2)|(b1>>6));const auto target=unpack_guid(r,16);party_index(b0&0x80);r.take(reason);r.end();
le(out,guid_of(target),8);return {0x76,std::move(out)};
}
if(opcode==0x440078){
const auto target=unpack_guid(r,16);const auto group=r.le(1);const auto bits=r.le(1);
if(bits&0x7f)throw Error("change subgroup bits");
party_index(bits&0x80);r.end();
if(group>7)throw Error("raid subgroup bound");
cstring(out,name_of(target));le(out,group,1);return {0x27e,std::move(out)};
}
if(opcode==0x440079){
const auto bits=r.le(1);if(bits&0x7f)throw Error("swap subgroup bits");
const auto first=unpack_guid(r,16),second=unpack_guid(r,16);party_index(bits&0x80);r.end();
cstring(out,name_of(first));cstring(out,name_of(second));return {0x280,std::move(out)};
}
const auto bits=r.le(1);if(bits&0x3f)throw Error("assistant bits");
const auto target=unpack_guid(r,16);party_index(bits&0x80);r.end();
le(out,guid_of(target),8);le(out,(bits&0x40)?1:0,1);return {0x28f,std::move(out)};
}
if(opcode==0x3e018a){
// #150 /pvp: TogglePvP (empty) -> Tortoise CMSG_TOGGLE_PVP 0x253 (empty body toggles PLAYER_FLAGS_PVP_DESIRED).
Reader r(body);r.end();if(!self_created)throw Error("pvp toggle before world entry");
return {0x253,{}};
}
if(opcode==0x440034){
if(!guild_id)throw Error("guild invite before real membership");
return {0x82,turtle_guild_invite_request(body)};
}
if(opcode==0x440029 || opcode==0x44002a){
if(guild_id || !pending_guild_invitation)throw Error("guild response without live source invitation");
Reader r(body);auto guild=unpack_guid(r,16);
if(guild!=Bytes(16))throw Error("guild invitation has no source numeric identity");
if(opcode==0x44002a && (r.le(1)&0x7f))throw Error("invalid guild decline bits");
r.end();return {opcode==0x440029?0x84u:0x85u,{}};
}
if(native_guild_management_opcode(opcode) || opcode==0x2f0002){
const bool enabled=gw_accepted_feature_enabled("GW_GUILD_MANAGEMENT_PROTOTYPE");
if(!enabled || !guild_id || !guild_rank_info ||
guild_rank_info->id!=guild_id || !guild_management_roster || guild_management_pending)
throw Error("guild management disabled, stale or pending");
if(opcode==0x2f0002)
return GuildRankAssignment::prepare(body,*guild_rank_info,*guild_management_roster,selected.guid,realm,guild_rank).second;
return source_guild_management(opcode,body,*guild_rank_info,*guild_management_roster,selected.guid,realm,guild_rank);
}
if(opcode==0x2f000e){
const bool enabled=gw_accepted_feature_enabled("GW_GUILD_RANKS_PROTOTYPE");
if(!enabled || !guild_id)throw Error("guild ranks prototype disabled or unguilded");
Reader r(body);auto guid=unpack_guid(r,16);r.end();
const auto own=forever_guild_guid(guild_id,realm);
if(!std::equal(guid.begin(),guid.end(),own.begin()))throw Error("guild ranks request differs from current membership");
return {0x89,{}};
}
if(opcode==0x2f001b)return GuildPermissions::request(body);
if(opcode==0x2f0014){
Reader roster_request(body);roster_request.end();
// Empty legacy query uses the authenticated source player's membership.
// The source handler safely returns without a response when unguilded.
return {0x89,{}};
}
if(opcode==0x4400b6){
Reader r(body);auto guild=unpack_guid(r,16),player=unpack_guid(r,16);r.end();
std::optional<uint32_t> source_guild;
auto self=forever_player_guid(selected.guid,realm);
const bool requester=player==Bytes(16) || std::equal(player.begin(),player.end(),self.begin());
auto candidate=[&](uint64_t guid){
auto id=player_guild(guid);if(!id || !*id)return;
auto expected=forever_guild_guid(*id,realm),expected_player=forever_player_guid(guid,realm);
if(std::equal(guild.begin(),guild.end(),expected.begin()) &&
(requester || std::equal(player.begin(),player.end(),expected_player.begin())))source_guild=*id;
};
candidate(selected.guid);
for(const auto& [guid,peer]:entities.peer_players){(void)peer;candidate(guid);}
if(!source_guild)throw Error("guild query outside live source identity");
Bytes out;le(out,*source_guild,4);return {0x54,std::move(out)};
}
if(opcode==0x3f0040 || opcode==0x3f0041 || opcode==0x3f0042){
// Original70334 ClassicClientOpcodes.inc -> TaxiPackets GUID-only
// queries. Turtle available-nodes query also learns an unknown node.
Reader r(body);auto guid=bound_legacy_guid(r,bindings());r.end();
if((guid>>48)!=0xf130)throw Error("taxi query outside visible creature binding");
Bytes out;le(out,guid,8);return {opcode==0x3f0040?0x1aau:0x1acu,std::move(out)};
}
if(opcode==0x3f0043){
Reader r(body);auto vendor=bound_legacy_guid(r,bindings());auto node=r.le(4),ground=r.le(4),flying=r.le(4);r.end();
auto actor=entities.actors.find(vendor);
if(ground || flying || !taxi_menu || taxi_menu->vendor!=vendor || actor==entities.actors.end() ||
!actor->second.sent || actor->second.generation!=taxi_vendor_generation)throw Error("taxi activation outside genuine bound menu/default mount");
return {0x312,turtle_taxi_activation(*taxi_menu,uint32_t(node))};
}
if(opcode==0x3f0084){
if(!self_created)throw Error("cancel auto-repeat before source self-create");
Reader reader(body);
reader.end();
return {0x26d,{}};
}
if(opcode==0x3e0179){
if(!pending_cast && !melee_cast)throw Error("cancel without active spell cast");
Reader r(body);auto id=unpack_guid(r,16);auto spell=r.le(4);r.end();
auto bound=[&](const PendingCast& c){return std::equal(id.begin(),id.end(),c.spell.cast.begin()) && spell==c.spell.spell;};
if(!(pending_cast && bound(*pending_cast)) && !(melee_cast && bound(melee_cast->cast)))throw Error("cancel outside bound cast");
Bytes out;le(out,spell,4);return {0x12f,std::move(out)};
}
if(opcode==0x3e0155){
Reader r(body);r.end(); // Original CancelMountAura has no payload.
auto unit=auras.units.find(selected.guid);std::set<uint32_t> mounted;
// The source can apply mounts whose effects have no native display
// definition. Cancel the actual holder reported on the mounted player.
if(unit!=auras.units.end() && unit->second.mount_display)
for(auto spell:unit->second.spells)
if(source_mounted_spells::contains(spell))mounted.insert(spell);
if(mounted.size()!=1)throw Error("cancel mount without one genuine source mounted holder");
Bytes out;le(out,*mounted.begin(),4);return {0x136,std::move(out)};
}
if(opcode==0x3e0061){
// CancelAura, client wire 0x3E0061 (ClassicClientOpcodes; live native_out 11 bytes, C52K1b; core 0x3D0060
// never sent). Original70334 CancelAura reads SpellID and packed CasterGUID.
// Turtle cancels an aura on the authenticated player by SpellID only;
// its handler independently enforces passive/positive/cannot-cancel.
Reader r(body);auto spell=uint32_t(r.le(4));auto caster=unpack_guid(r,16);r.end();
auto unit=auras.units.find(selected.guid);
if(!spell || unit==auras.units.end() || std::find(unit->second.spells.begin(),unit->second.spells.end(),spell)==unit->second.spells.end())
throw Error("cancel aura absent from authenticated source self state");
if(caster!=Bytes(16)){
const auto known=bindings();
if(std::none_of(known.begin(),known.end(),[&](const auto& row){return std::equal(caster.begin(),caster.end(),row.second.begin());}))
throw Error("cancel aura caster outside live bindings");
}
Bytes out;le(out,spell,4);return {0x136,std::move(out)};
}
if(opcode==0x3e0036){
Reader state(body);auto value=state.le(1);state.end();
if(value!=0 && value!=1 && value!=3 && value!=8)throw Error("stand request outside Turtle player states");
Bytes out;le(out,value,4);return {0x101,std::move(out)};
}
// Pinned70334 opcode normalization: actual3F001F -> CMSG_SET_SHEATHED.
if(opcode==0x3f001f)return {0x1e0,turtle_sheath_request(body)};
if(opcode==0x3e0171){
// Item spells aimed at a game object (MC runes: Aqual/Eternal Quintessence on a Lock) use the same current
// object binding as a plain spell cast; the Source server owns the lock, range and script.
auto use=forever_item_use(body);
qualify_spell_location(use.spell);
const bool gameobject=(use.spell.target_flags&0x800)!=0;
if(gameobject)qualify_spell_gameobject(use.spell.unit);
return inventory.use_item(body,bindings(),gameobject);
}
if(opcode==0x3f0089){
// CMSG_REPAIR_ITEM {Guid Npc, Guid Item (empty = all), bit UseGuildBank} -> Tortoise 0x2A8 {u64 npc, u64 item}.
// Tortoise has no guild-bank repair funds (NPCHandler.cpp:905): that variant has no Source form.
Reader q(body);auto npc=bound_legacy_guid(q,bindings());
const auto& items=inventory.owned_bindings();
auto item=bound_legacy_guid(q,items,true);auto bits=q.le(1);q.end();
if(bits)throw Error("guild bank repair has no Source form");
if(!service_unit(npc))throw Error("repair outside a tracked creature");
Bytes out;le(out,npc,8);le(out,item,8);return {0x2a8,std::move(out)};
}
if(opcode==0x3e028c){
// CMSG_OFFER_PETITION (WPP 0x3E028C) {Guid ItemGUID, Guid TargetPlayer} -> Tortoise 0x1C3 {u64 item, u64 player}.
Reader q(body);const auto item=legacy_charter_item(unpack_guid(q,16));const auto target=unpack_guid(q,16);q.end();
if(!item)throw Error("petition offer without a Source charter item");
uint64_t player=0;
for(const auto& [id,actor]:entities.actors){
if(id>>32)continue; // Source player GUIDs only
const auto native=forever_player_guid(id,realm);
if(target.size()==native.size() && std::equal(target.begin(),target.end(),native.begin())){player=id;break;}
}
if(!player || player==selected.guid)throw Error("petition offer target outside visible Source players");
Bytes out;le(out,*item,8);le(out,player,8);return {0x1c3,std::move(out)};
}
if(opcode==0x3f007d){
// SetFactionInactive (WPP 0x3F007D) {u32 Index, bit State} -> Tortoise 0x317 {u32 repListID, u8 inactive}.
Reader q(body);const auto index=uint32_t(q.le(4));const auto bits=uint8_t(q.le(1));q.end();
if(bits&0x7f)throw Error("faction inactive padding bits");
std::optional<uint32_t> source;
for(const auto& [src,map]:native_faction_mappings())if(map.index==index){source=src;break;}
if(!source || !reputation_values.contains(*source))throw Error("faction index outside the Source reputation list");
Bytes out;le(out,*source,4);le(out,(bits&0x80)?1:0,1);return {0x317,std::move(out)};
}
if(opcode==0x3f007b || opcode==0x3f007c || opcode==0x3f007e){
// SetFactionAtWar/NotAtWar {u16 index} -> 0x125 {u32 repListID, u8 flag}; SetWatchedFaction
// {u32 index} -> 0x318 {i32}. Native ReputationIndex is mapped back to the Source list index.
Reader q(body);const auto index=uint32_t(q.le(opcode==0x3f007e?4:2));q.end();
Bytes out;
if(opcode==0x3f007e && index==0xffffffffu){le(out,0xffffffffu,4);return {0x318,std::move(out)};}
std::optional<uint32_t> source;
for(const auto& [src,map]:native_faction_mappings())if(map.index==index){source=src;break;}
if(!source || (opcode!=0x3f007e && !reputation_values.contains(*source)))throw Error("faction index outside the Source reputation list");
le(out,*source,4);
if(opcode==0x3f007e)return {0x318,std::move(out)};
le(out,opcode==0x3f007b?1:0,1);return {0x125,std::move(out)};
}
if(opcode==0x3f00d7){Reader q(body);auto mask=q.le(1);q.end();return {0x2bf,Bytes{uint8_t(mask)}};} // stored byte, Source restores it
if(opcode==0x3e0212){ // ItemTextQuery -> Tortoise 0x243 {u32 itemTextId, u32 mailId (unused), u32 unk}
auto text=owned_item_text(body);if(book_text_pending.size()>=32)throw Error("too many outstanding item text queries");
Bytes out;le(out,text,4);le(out,0,4);le(out,0,4);return {0x243,std::move(out)};
}
if(opcode==0x3e013a){
// CMSG_CANCEL_CHANNELLING {i32 ChannelSpell, i32 Reason} -> 0x13B {u32 spell} (Source skips the id).
Reader q(body);auto spell=q.le(4);q.le(4);q.end();
if(!spell || spell>INT_MAX)throw Error("channel cancel identity");
Bytes out;le(out,spell,4);return {0x13b,std::move(out)};
}
if(opcode==0x3f0062 || opcode==0x3f006f || opcode==0x3f0063 || opcode==0x3f0065 || opcode==0x3f0069 || opcode==0x3f006a){
// Auction writes and personal lists (TC AuctionHousePackets Read -> Tortoise AuctionHouseHandler).
// Optional TaintedBy AddOnInfo is skipped exactly: bits10 name, bits10 version, 2 flags, then
// SizedCString data (length+1 bytes when non-empty; TC PacketOperators.h:322-79).
Reader q(body);const auto npc=bound_legacy_guid(q,bindings());
if(!service_unit(npc))throw Error("auction request outside a tracked auctioneer");
auto skip_addon=[&](){auto b0=q.le(1),b1=q.le(1),b2=q.le(1);const uint32_t bits=uint32_t((b0<<16)|(b1<<8)|b2);
const uint32_t name=(bits>>14)&0x3ff,version=(bits>>4)&0x3ff;q.take(name>1?name:0);q.take(version>1?version:0);};
Bytes out;le(out,npc,8);
if(opcode==0x3f006f)return commodity_sell_packets(body).front();
if(opcode==0x3f0062){ // SellItem {u64 MinBid, u64 Buyout, u32 RunTime, bit tainted, bits6 n, [addon], n x {Guid, u32 UseCount}}
const auto bid=q.le(8),buyout=q.le(8);const auto minutes=uint32_t(q.le(4));const auto bits=q.le(1);
const bool tainted=bits&0x80;const auto count=(bits>>1)&0x3f;if(bits&1)throw Error("auction sell bit padding");
if(tainted)skip_addon();
if(count!=1)throw Error("multi-stack auction has no Source form");
const auto& items=inventory.owned_bindings();
const auto item=bound_legacy_guid(q,items);const auto use=q.le(4);q.end();
auto record=inventory.items.find(item);if(record==inventory.items.end())throw Error("auction item outside owned inventory");
auto stack=record->second.fields.find(14);const auto have=stack==record->second.fields.end()?0u:stack->second;
if(!use || use!=have)throw Error("partial-stack auction has no Source form"); // Source auctions the whole item
// Buyout Mode sends MinBid 0 (buyout-only); Source needs a start bid, and bid == buyout is the same auction.
const auto start=(!bid && buyout)?buyout:bid;
if(!start || start>2000000000 || buyout>2000000000 || (buyout && start>buyout))throw Error("auction price outside Source bounds");
if(minutes!=120 && minutes!=480 && minutes!=1440)throw Error("auction duration outside Source 2/8/24 h");
le(out,item,8);le(out,start,4);le(out,buyout,4);le(out,minutes,4);return {0x256,std::move(out)};
}
if(opcode==0x3f0063 || opcode==0x3f0065){ // RemoveItem {i32 id, i32 item, opt} / PlaceBid {i32 id, u64 bid, opt}
const auto id=uint32_t(q.le(4));uint64_t price=0;
if(opcode==0x3f0063)q.le(4);else price=q.le(8);
const auto bits=q.le(1);if(bits&0x7f)throw Error("auction request bit padding");if(bits)skip_addon();q.end();
if(!id || id>INT32_MAX)throw Error("auction identity");
le(out,id,4);
if(opcode==0x3f0063)return {0x257,std::move(out)};
if(!price || price>2000000000)throw Error("auction bid outside Source bounds");
le(out,price,4);return {0x25a,std::move(out)};
}
const auto list=personal_list_query(opcode,body,bindings());(void)npc;
return {opcode==0x3f0069?0x259u:0x264u,personal_list_request(opcode==0x3f0069,list,0)};
}
// Pet commands (TC PetPackets Read -> Tortoise PetHandler). Action words share the packing
// spell/value:24 | type:8 on both sides (TC CharmInfo.h, Tortoise UNIT_ACTION_BUTTON_*).
if(opcode==0x3f0021){ // CMSG_PET_ACTION {Guid Pet, u32 Action, Guid Target, XYZ} -> 0x175 {u64, u32, u64}
Reader q(body);auto pet=current_pet_command_unit(q);auto action=uint32_t(q.le(4));auto target=bound_legacy_guid(q,bindings(),true);
for(int i=0;i<3;++i){auto f=q.f32();if(!std::isfinite(f))throw Error("pet action position");}q.end();
const auto type=action>>24,value=action&0xffffff;
const bool ok=(type==0x07 && value<=3) || (type==0x06 && value<=2) || // no MOVE_TO / ASSIST in Source
((type==0x01 || type==0x81 || type==0xc1) && pet_bar_spell(value)); // Source never dispatches type 0
if(!ok)throw Error("pet action outside the Source command/reaction/spell set");
Bytes out;le(out,pet,8);le(out,action,4);le(out,target,8);return {0x175,std::move(out)};
}
if(opcode==0x3f0020){ // CMSG_PET_SET_ACTION {Guid, u32 Index, u32 Action} -> 0x174 {u64, u32 pos, u32 data}
Reader q(body);auto pet=current_pet_command_unit(q);auto index=uint32_t(q.le(4)),action=uint32_t(q.le(4));q.end();
const auto type=action>>24,value=action&0xffffff;
if(index>=10)throw Error("pet bar index beyond the ten Source cells"); // native supplemental cells 10..17
// Tortoise PetHandler.cpp:337-362: a single cell may place/clear a spell; command and reaction
// cells move only as a validated 24-byte pair, and singletons are ignored. Native sends one cell
// per packet, so command/reaction drags are held rather than paired speculatively.
if(type==0x07 || type==0x06)throw Error("command/reaction cell move has no single-cell Source form");
{const auto current=pet_bar->state.buttons[index]>>24; // a native swap onto a command cell would drop it in Source
if(current==0x07 || current==0x06)throw Error("pet bar destination holds a command/reaction cell");}
// Empty cell: raw 0 or the Source/TC empty encodings ACT_PASSIVE|0, ACT_DISABLED|0.
if(action && !(value==0 && (type==0x01 || type==0x81)) && !((type==0x01 || type==0x81 || type==0xc1) && pet_bar_spell(value)))
throw Error("pet bar action outside the Source set");
Bytes out;le(out,pet,8);le(out,index,4);le(out,action,4);return {0x174,std::move(out)};
}
if(opcode==0x3f0022 || opcode==0x3f0023){ // STOP_ATTACK -> 0x2EA, ABANDON (stock confirmed) -> 0x176: {u64}
Reader q(body);auto pet=current_pet_command_unit(q);q.end();
if(opcode==0x3f0023 && ((pet>>48)!=0xf140 || selected.cls!=3))throw Error("abandon outside the hunter's Source pet"); // stock ABANDON is hunter-only
Bytes out;le(out,pet,8);return {opcode==0x3f0022?0x2eau:0x176u,std::move(out)};
}
if(opcode==0x3f0025){ // CMSG_PET_CANCEL_AURA {Guid, i32 spell} -> 0x26B {u64, u32}
Reader q(body);auto pet=current_pet_command_unit(q);auto spell=q.le(4);q.end();
if(!spell || spell>INT_MAX)throw Error("pet aura identity");
Bytes out;le(out,pet,8);le(out,spell,4);return {0x26b,std::move(out)};
}
if(opcode==0x3f0026){ // CMSG_PET_SPELL_AUTOCAST {Guid, u32 spell, bit enabled} -> 0x2F3 {u64, u32, u8}
Reader q(body);auto pet=current_pet_command_unit(q);auto spell=uint32_t(q.le(4));auto bits=q.le(1);q.end();
if((bits&0x7f) || !pet_bar_spell(spell))throw Error("pet autocast outside the Source pet spells");
Bytes out;le(out,pet,8);le(out,spell,4);le(out,bits?1:0,1);return {0x2f3,std::move(out)};
}
if(opcode==0x3f0027){Reader q(body);q.end();if(!self_created)throw Error("pet info outside world");return {0x279,{}};} // REQUEST_PET_INFO: Source answers only when a pet/charm exists
if(opcode==0x3e0175){ // CMSG_PET_CAST_SPELL {Guid Pet, SpellCastRequest} -> 0x1F0 {u64, u32 spell, targets}
Reader q(body);auto pet=current_pet_command_unit(q);auto rest=q.take(q.left());
auto request=forever_spell_request(rest);
if(!pet_bar_spell(request.spell))throw Error("pet cast outside the Source pet spells");
qualify_spell_location(request);
auto known=bindings();Bytes out;le(out,pet,8);append(out,turtle_spell_request(request,known));return {0x1f0,std::move(out)};
}
if(opcode==0x4400b0){ // CMSG_PET_RENAME {Guid, i32 PetNumber, bits8 len, bit declined, name} -> 0x177 {u64, cstring}
Reader q(body);auto pet=current_pet_command_unit(q);auto number=q.le(4);auto len=q.le(1);auto flags=q.le(1);
if((pet>>48)!=0xf140 || selected.cls!=3 || number!=((pet>>24)&0xffffff))throw Error("rename outside the current Source hunter pet");
if(flags || !len)throw Error("declined names / empty pet name have no Source form");
auto name=q.take(len);q.end();
for(auto c:name)if(!c)throw Error("pet name byte");
Bytes out;le(out,pet,8);out.insert(out.end(),name.begin(),name.end());out.push_back(0);return {0x177,std::move(out)};
}
if(opcode==0x3e0176){
auto request=forever_spell_request(body);
if(!spells.contains(request.spell))throw Error("cast spell absent from authenticated server spellbook");
qualify_spell_location(request);
if(request.target_flags&0x800)qualify_spell_gameobject(request.unit);
auto known=bindings();const auto& owned=inventory.owned_bindings();known.insert(owned.begin(),owned.end());
if(source_party_target_profile::contains(request.spell) && !(request.target_flags&0x802u) && request.unit==Guid128{}){
// Turtle casts these on a unit and buffs that unit's party (ImplicitTarget 37); the 70334 client sends no
// unit (caster-party spell). Use the selected player when it is a known player, else self, like 1.12.
const auto sel=known.find(current_selection);
const bool player=current_selection && (current_selection>>48)==0 && sel!=known.end();
request.target_flags|=2u;
request.unit=player?sel->second:known.at(selected.guid);
}
return {0x12e,turtle_spell_request(request,known)};
}
if(opcode==0x440062){
// Original70334 SetActionButton::Read uses uint64 action +uint16
// index. Turtle uses index8 +packed action24/type8 (120 slots).
Reader r(body);auto packed=r.le(8),index=r.le(2);r.end();auto value=packed&0x00ffffffffffffffULL;auto type=uint8_t(packed>>56);
if (type == 0x60) {
const auto spell = mount_action_spells::spell_for(value);
if (!spell || !spells.contains(spell))
throw Error("mount action has no learned Source riding spell");
value = spell;
type = 0;
}
if(index>=120 || value>0xffffff || (packed && !value) || (type!=0 && type!=0x80))throw Error("action button outside Turtle spell/item/index representation");
Bytes out;le(out,index,1);le(out,value|(uint64_t(type)<<24),4);return {0x128,std::move(out)};
}
if(opcode==0x3f0046){
Reader r(body);auto npc=bound_legacy_guid(r,bindings());auto context=r.le(4),spell=r.le(4);r.end();
if (logout_complete || far_transfer || !trainer || trainer_self_guid != selected.guid || trainer->guid != npc || context != trainer->native_id)
throw Error("training outside genuine trainer offer context");
const auto service = std::find_if(trainer->spells.begin(), trainer->spells.end(),
[&](const TrainerSpell& row) { return row.display_spell() == spell; });
if (service == trainer->spells.end() || (trainer->type == 2 && !service->available_to_buy()))
throw Error("training outside genuine available service");
Bytes out;le(out,npc,8);le(out,service->spell,4);return {0x1b2,std::move(out)};
}
if(opcode==0x3f003b){
// ItemPackets::BuyItem::Read: ItemInstance is ID +7bit-mod-list
// +optional-bonus bit, each flushed. Current genuine vendor packets
// contain neither modifiers nor bonuses; do not discard unknown data.
Reader r(body);auto vendor=bound_legacy_guid(r,bindings());auto container=unpack_guid(r,16);
auto entry=r.le(4);if(r.le(1) || r.le(1))throw Error("unreviewed vendor item modifiers/bonus");
auto quantity=r.le(4),muid=r.le(4),slot=r.le(4),type=r.le(4);r.end();
if(!merchant || *merchant!=vendor || !vendor_inventory || vendor_inventory->guid!=vendor || type!=1)throw Error("buy outside genuine item merchant context");
const VendorItem* offer=nullptr;unsigned same_entry=0;
for(const auto& item:vendor_inventory->items){if(item.item==entry)++same_entry;if(item.slot==muid && item.item==entry)offer=&item;}
if(!offer || same_entry!=1 || !offer->stack || !quantity || quantity%offer->stack || quantity/offer->stack>255)throw Error("buy item/quantity outside Turtle vendor bundle representation");
auto bundles=quantity/offer->stack;Bytes out;le(out,vendor,8);le(out,entry,4);
bool empty=std::all_of(container.begin(),container.end(),[](uint8_t v){return v==0;});
if(empty || slot==255 || slot==0xffffffff){
// Empty container is the original engine's automatic storage path.
if(!empty){auto player=forever_player_guid(selected.guid,realm);if(!std::equal(container.begin(),container.end(),player.begin()))throw Error("auto-buy container is not self");}
le(out,bundles,1);le(out,0,1);return {0x1a2,std::move(out)};
}
if(slot>255)throw Error("buy destination slot overflow");
uint64_t bag=0;NativeInventoryPosition destination{};auto player=forever_player_guid(selected.guid,realm);
if(std::equal(container.begin(),container.end(),player.begin())){bag=selected.guid;destination=inventory.position(255,uint8_t(slot));}
else{
const auto& owned=inventory.owned_bindings();auto packed_bytes=pack_guid(container);Reader packed(packed_bytes);bag=bound_legacy_guid(packed,owned);bool found=false;
for(uint8_t i=30;i<34;++i)if(inventory.position(255,i).item==bag){destination=inventory.position(i,uint8_t(slot));found=true;break;}
if(!found)throw Error("buy destination not an equipped bag");
}
le(out,bag,8);le(out,destination.slot,1);le(out,bundles,1);return {0x1a3,std::move(out)};
}
if(opcode==0x3f003c){
// Original BuyBackItem::Read: packed vendor, uint32 native slot.
Reader r(body);auto vendor=bound_legacy_guid(r,bindings());auto slot=r.le(4);r.end();
if(!merchant || *merchant!=vendor)throw Error("buyback outside authenticated merchant context");
auto legacy=inventory.buyback_slot(uint32_t(slot));
Bytes out;le(out,vendor,8);le(out,legacy,4);return {0x290,std::move(out)};
}
if(opcode==0x3f0039){
// ItemPackets::SellItem::Read vs Tortoise ItemHandler::HandleSellItemOpcode.
Reader r(body);auto vendor=bound_legacy_guid(r,bindings());auto item=bound_legacy_guid(r,inventory.owned_bindings());auto amount=r.le(4);r.end();
if(!merchant || *merchant!=vendor)throw Error("sell outside authenticated merchant context");
// Zero retains the server's sell-whole-stack semantic. Never truncate
// an explicit modern amount or replace it with a racy sell-all request.
if(amount>255)throw Error("sell quantity outside Turtle byte-count protocol");
Bytes out;le(out,vendor,8);le(out,item,8);le(out,amount,1);return {0x1a0,std::move(out)};
}
if(opcode==0x3f012c){
// BankPackets::BuyBankTab::Read (packed banker, uint8 BankType): Classic buys character bank
// bag slots with it (bank type 0, official sniff 70170). Tortoise ItemHandler::
// HandleBuyBankSlotOpcode reads the banker guid and answers 0x1ba only on failure.
Reader r(body);auto banker=bound_legacy_guid(r,bindings());auto type=r.le(1);r.end();
if(type!=0)throw Error("only the character bank has purchasable bag slots");
if(!equipment_bank_open() || character_bank->banker!=banker)throw Error("bank slot purchase outside the open bank");
Bytes out;le(out,banker,8);return {0x1b9,std::move(out)};
}
if(opcode==0x410002 || opcode==0x410003){
if(!equipment_bank_open()){
if(!character_bank || !self_created || !location || logout_complete || pending_teleport || far_transfer)
throw Error("character bank is not open in this world");
throw Error("character banker is no longer present");
}
return log_inventory_move(opcode,inventory.gameplay(opcode,body));
}
if(opcode==0x410007 || opcode==0x410004 || opcode==0x410008 || opcode==0x410006 || opcode==0x3f0105 || opcode==0x3e016c ||
opcode==0x3e0213 || opcode==0x3e0214)return log_inventory_move(opcode,inventory.gameplay(opcode,body));
if(opcode==npc_text::Query)
return {0x17f,npc_text_queries.request(body,current_npc_text_menu(),bindings())};
Reader r(body);auto known=bindings();
if(opcode==0x3e011f){r.end();return {0x142,{}};}
// RequestRaidInfo (core 0x4300F9, empty; wire 0x4400f9 continues the 1:1
// F5/F7/F8 run, the BattlePay confirm it is tabled as always has a body).
if(opcode==0x4400f9){r.end();return {0x2cd,{}};}
if(opcode==0x3e0029){r.end();if(!self_created)throw Error("PvP log request before world entry");return {0x2e0,{}};}
if(opcode==0x4400ad){
if(!self_created)throw Error("who request before world entry");
auto who=native_who_request(body);return {0x62,std::move(who.source)};
}
if(opcode==0x3e014e){
// RequestPlayedTime: one bit TriggerScriptEvent (high bit). Tortoise
// CMSG_PLAYED_TIME 0x1cc is empty; the flag is echoed on the reply.
auto flags=r.le(1);r.end();if(flags&0x7f)throw Error("played-time request padding");
played_trigger=flags&0x80;
// Tortoise answers every played-time request with a system line ("Death counter: N | Quests completed: N").
// Only a /played (TriggerScriptEvent) shows it; the client's silent login request must not print it.
if(played_trigger)played_silent_notes=0;else if(played_silent_notes<4)++played_silent_notes;
return {0x1cc,{}};
}
if(opcode==0x3f002b){
if(!current_npc_text_menu() || !gossip->broadcast_text){
// #109: name the failing condition; the reason lands in the player's GatewayRequests.log.
std::string why="gossip selection without current displayed menu:";
if(!gossip)why+=" no-menu";
else{
const auto actor=entities.actors.find(gossip->guid);
why+=" text="+std::to_string(gossip->text_id)+" greeting="+(gossip->broadcast_text?"1":"0");
if(actor==entities.actors.end())why+=" actor=gone";
else why+=" sent="+std::to_string(int(actor->second.sent))+" gen="+std::to_string(actor->second.generation)+"/"+std::to_string(gossip_actor_generation);
}
if(!self_created)why+=" not-in-world";
if(!location)why+=" no-location";
if(logout_complete)why+=" logged-out";
if(far_transfer)why+=" far-transfer";
if(pending_teleport)why+=" teleport";
throw Error(why);
}
return {0x17c,turtle_gossip_selection(r,*gossip,known)};
}
if(opcode==0x3f006c || opcode==0x3f006d){
// Commodity quote / confirm: a fresh name-scoped Source snapshot (one AH list at a time).
auto guid=bound_legacy_guid(r,known);
if(!service_unit(guid))throw Error("commodity request outside a tracked auctioneer");
const auto c=native_commodity_request(body);
if(opcode==0x3f006d && (!auction_commodity || !auction_commodity->quote || auction_commodity->awaiting || auction_commodity->bid_sent || auction_commodity->bid_queued ||
auction_commodity->auctioneer!=guid || auction_commodity->item!=c.item || auction_commodity->quantity!=c.quantity ||
std::chrono::steady_clock::now()>=auction_commodity->deadline))throw Error("commodity confirm without its live quote");
const auto* t=inventory.peer_template(c.item);
if(!t || !t->found || t->stack<=1)throw Error("commodity item without a stackable Source template");
return {0x258,source_auction_name_request(guid,t->name,0)};
}
if(opcode==0x3f006b){
// LIST_BUCKETS_BY_BUCKET_KEYS (commodity sell frame): one Source name search for the key's item;
// its rows are narrowed to the requested keys and published as buckets in SpecificKeys mode.
auto guid=bound_legacy_guid(r,known);
if(!service_unit(guid))throw Error("auction bucket-keys lookup outside a tracked auctioneer");
const auto q=native_auction_bucket_keys_query(body);
for(const auto& k:q.keys)if(k.item!=q.keys.front().item)throw Error("auction bucket-keys lookup spans several Source items");
const auto* t=inventory.peer_template(q.keys.front().item);
if(!t || !t->found || t->name.empty())throw Error("auction bucket-keys lookup before its Source template");
return {0x258,source_auction_name_request(guid,t->name,0)};
}
if(opcode==0x3f0067 || opcode==0x3f0068){
// LIST_ITEMS_BY_BUCKET_KEY / BY_ITEM_ID with no snapshot row (bucket click during a refresh, Sell tab
// price lookup): one Source 0x258 name search for that item, narrowed to the entry, published as items.
auto guid=bound_legacy_guid(r,known);
if(!service_unit(guid))throw Error("auction item lookup outside a tracked auctioneer");
uint32_t item=0,offset=0;
if(opcode==0x3f0068){const auto q=native_auction_items_by_item_query(body);item=q.item;offset=q.offset;}
else{const auto q=native_auction_items_query(body);item=q.key.item;offset=q.offset;}
if(offset)throw Error("auction item lookup page outside its snapshot");
const auto* t=inventory.peer_template(item);
if(!t || !t->found || t->name.empty())throw Error("auction item lookup before its Source template"); // bag items carry templates
return {0x258,source_auction_name_request(guid,t->name,0)};
}
if(opcode==0x3f0066){
// CMSG_AUCTION_BROWSE_QUERY, first page: one Source 0x258 page at listfrom 0. Later
// native pages (Offset>0) are answered from the snapshot by auction_local_request.
auto guid=bound_legacy_guid(r,known);
if(!service_unit(guid))throw Error("auction browse outside a tracked auctioneer");
const auto q=native_auction_browse_query(body);
if(q.offset)throw Error("auction browse page outside its snapshot");
return {0x258,source_auction_superset_request(q,guid,0)};
}
if(opcode==0x3e0191 || opcode==0x3f0048 || opcode==0x3f0049){
// BATTLEMASTER_HELLO / AREA_SPIRIT_HEALER_QUERY / _QUEUE (WPP 69876): {packed Guid128 npc}
// -> Tortoise 0x2D7 / 0x2E2 / 0x2E3 {u64 npc}. Tortoise checks the creature's flags itself.
auto guid=bound_legacy_guid(r,known);r.end();
if((guid>>48)!=0xf130)throw Error("battle service outside tracked creature category");
Bytes legacy;le(legacy,guid,8);
return {opcode==0x3e0191?0x2d7u:opcode==0x3f0048?0x2e2u:0x2e3u,std::move(legacy)};
}
if(opcode==0x3f00c0){
// BATTLEMASTER_JOIN (WPP 1.60 -> V8.1.5 parser; upstream BattlemasterJoin::Read):
// {u32 count,u8 roles,i32 blacklist[2],u64 queue[count]}. Tortoise 0x2EE {u64 battlemaster,
// u32 map,u32 instance,u8 asGroup}. Battlemaster = owner of the last NPC list for that map, else 0
// (Tortoise then allows only its tabard queue). Native has no group bit: like the reference
// server, a group leader's join queues the group.
if(!location || logout_complete || far_transfer)throw Error("battlemaster join outside the current world");
const auto count=r.le(4);(void)r.le(1);(void)r.le(4);(void)r.le(4);
if(count!=1)throw Error("battlemaster join needs exactly one Source queue");
const auto queue=r.le(8);r.end();
if(((queue>>16)&0xf) || ((queue>>20)&1) || ((queue>>24)&0x3f))throw Error("non-battleground native queue");
const auto list=uint32_t(queue&0xffff);
auto field=std::find_if(battleground::fields.begin(),battleground::fields.end(),[list](const auto& f){return f.list==list;});
if(field==battleground::fields.end())throw Error("unknown native battleground queue");
const bool grouped=loot.group && !loot.group->explicit_solo && !loot.group->members.empty();
// Reference server (TC BattleGroundHandler) ignores a grouped non-leader's join; never solo-queue it.
if(grouped && loot.group->leader!=selected.guid)throw Error("battlemaster join from a group non-leader");
const bool group=grouped;
if(group && field->map==30)throw Error("Source refuses Alterac Valley group queues");
Bytes legacy;le(legacy,battlemaster_offer && battlemaster_offer->map==field->map?battlemaster_offer->source:0,8);
le(legacy,field->map,4);le(legacy,0,4);le(legacy,group?1:0,1);
return {0x2ee,std::move(legacy)};
}
if(opcode!=0x3f00cd && opcode!=0x3e011e && opcode!=0x3f0038 && opcode!=0x3f0029 && opcode!=0x3f0045 && opcode!=0x3f004b && opcode!=0x3f0061)throw Error("unsupported native gameplay request");
auto guid=bound_legacy_guid(r,known,opcode==0x3f00cd);
if(opcode==0x3f004b){
// Pinned BankPackets::BankerActivate::Read: packed GUID, int32 type.
// Turtle has only the character bank, never modern account storage.
auto type=r.le(4);if(type!=8 && type!=67)throw Error("unsupported bank interaction type");
}
r.end();
// Turtle shop helpers (Field Repair Bot, Mechanical Auctioneer, portable bank) are mini-pets (Pet,
// HIGHGUID_PET 0xF140; random_scripts_3 GetMiniPet), so services also open on pet units.
if(opcode!=0x3f00cd && opcode!=0x3e011e && !service_unit(guid))throw Error("interaction outside tracked creature category");
if(opcode==0x3f00cd)current_selection=guid;
Bytes legacy;le(legacy,guid,8);
return {opcode==0x3f00cd?0x13du:opcode==0x3e011e?0x141u:opcode==0x3f0038?0x19eu:opcode==0x3f0045?0x1b0u:opcode==0x3f004b?0x1b7u:opcode==0x3f0061?0x255u:0x17bu,std::move(legacy)};
}
NativeWorldTranslation::KnockbackAck NativeWorldTranslation::knockback_ack(
std::span<const uint8_t> body,const std::vector<Character>& owned) const {
size_t consumed=0;
auto move=forever_basic_movement_prefix(body,realm,owned,consumed);
Reader tail(body.subspan(consumed));
auto sequence=uint32_t(tail.le(4));
auto optional=tail.le(1);
if(optional!=0 && optional!=0x80)throw Error("invalid knockback speed presence");
if(optional){
auto horizontal=tail.f32(),vertical=tail.f32();
if(!std::isfinite(horizontal) || !std::isfinite(vertical) ||
std::abs(horizontal-move.horizontal_speed)>0.01f || std::abs(vertical-move.vertical_speed)>0.01f)
throw Error("knockback ACK speeds differ from its movement");
}
tail.end();
auto pending=pending_knockbacks.find(sequence);
if(!authorizes_movement(move.state.guid) || pending==pending_knockbacks.end() ||
!move.falling || !move.has_direction)throw Error("knockback ACK outside selected pending movement");
const std::array actual{move.cos_angle,move.sin_angle,move.horizontal_speed,move.vertical_speed};
for(size_t i=0;i<actual.size();++i)
if(std::abs(actual[i]-pending->second[i])>0.01f)throw Error("knockback ACK disagrees with server impulse");
return {sequence,move};
}
std::vector<LegacyPacket> NativeWorldTranslation::cast_move_update(uint32_t opcode,std::span<const uint8_t> body,const std::vector<Character>& owned) const{
// #87 (owner 2026-11-26): while the right mouse button turns the player, the native client sends the new facing
// only inside CastSpell's MoveUpdate. Turtle has no such field and checks melee facing (Crusader/Holy Strike)
// against its own orientation, so the same MovementInfo goes to it as an ordinary MSG_MOVE_SET_FACING first.
if(opcode!=0x3e0176)return {};
const auto request=forever_spell_request(body);
if(request.move_update.empty())return {};
return player_movement(0x420027,request.move_update,owned);
}
std::vector<LegacyPacket> NativeWorldTranslation::player_movement(uint32_t opcode,std::span<const uint8_t> body,const std::vector<Character>& owned) const{
if(!self_created)throw Error("movement before server self-create");
// Possess (Mind Control, Eye of Kilrogg...): the native client moves the charmed unit under its own GUID.
// Tortoise 1.12 movement carries no mover GUID; the Source moves its active mover (set by 0x26a on the
// client's SET_ACTIVE_MOVER). Re-key the presented charm GUID to the selected character so the ordinary
// projection applies (claude 2026-11-24).
if(const auto charm=possessed_unit();charm && opcode!=0x420039){
Reader r(body);const auto mover=unpack_guid(r,16);
if(mover.size()==charm->size() && std::equal(mover.begin(),mover.end(),charm->begin())){
Bytes rekeyed=pack_guid(forever_player_guid(selected.guid,realm));
rekeyed.insert(rekeyed.end(),body.end()-r.left(),body.end());
return player_movement_checked(opcode,rekeyed,owned);
}
}
return player_movement_checked(opcode,body,owned);
}
std::optional<Guid128> NativeWorldTranslation::possessed_unit() const{
const auto& control=entities.self_controlled[0];
if(control.known!=3 || !control.source_guid() || !control.presented || *control.presented==Guid128{})return std::nullopt;
return control.presented;
}
std::optional<uint64_t> NativeWorldTranslation::possessed_source(std::span<const uint8_t> packed) const{
const auto charm=possessed_unit();if(!charm)return std::nullopt;
Reader r(packed);const auto mover=unpack_guid(r,16);r.end();
if(mover.size()!=charm->size() || !std::equal(mover.begin(),mover.end(),charm->begin()))return std::nullopt;
return entities.self_controlled[0].source_guid();
}
std::vector<LegacyPacket> NativeWorldTranslation::player_movement_checked(uint32_t opcode,std::span<const uint8_t> body,const std::vector<Character>& owned) const{
uint32_t legacy=0;
if(opcode==0x420039){
// MoveTimeSkipped {packed MoverGUID, u32 TimeSkipped} -> Tortoise CMSG_MOVE_TIME_SKIPPED
// 0x2ce {u64 mover, u32 lag}; the Source feeds it to its movement clock and anti-cheat.
Reader r(body);const auto guid=unpack_guid(r,16);const auto skipped=uint32_t(r.le(4));r.end();
const auto self=forever_player_guid(selected.guid,realm);
if(guid.size()!=self.size() || !std::equal(guid.begin(),guid.end(),self.begin()) || !authorizes_movement(selected.guid))
throw Error("time skip outside selected character");
Bytes out;le(out,selected.guid,8);le(out,skipped,4);return {{0x2ce,std::move(out)}};
}
if(opcode==0x420030){
const auto ack=knockback_ack(body,owned);
Bytes legacy;le(legacy,selected.guid,8);le(legacy,ack.sequence,4);
append(legacy,turtle_basic_movement(ack.move));
std::vector<LegacyPacket> out;
if(!mover_confirmed){Bytes mover;le(mover,selected.guid,8);out.push_back({0x26a,std::move(mover)});}
out.push_back({0xf0,std::move(legacy)});return out;
}
for(const auto& route:movement_modes::Routes)if(opcode==route.native_ack){
if(body.size()<4)throw Error("truncated movement mode acknowledgment");
auto move=forever_basic_movement(body.first(body.size()-4),realm,owned);
if(!authorizes_movement(move.state.guid))throw Error("mode ACK outside selected character");
Reader tail(body.last(4));auto sequence=uint32_t(tail.le(4));tail.end();
auto pending=pending_modes.find(sequence);
if(pending==pending_modes.end())throw Error("mode ACK without genuine source change");
auto expected=std::find_if(std::begin(movement_modes::Routes),std::end(movement_modes::Routes),[&](const auto& row){return row.source==pending->second;});
if(expected==std::end(movement_modes::Routes) || expected->native_ack!=opcode ||
bool(move.state.flags&expected->flag)!=expected->apply)throw Error("mode ACK category or applied-state mismatch");
Bytes ack;le(ack,selected.guid,8);le(ack,sequence,4);append(ack,turtle_basic_movement(move));
if(expected->toggle_tail)le(ack,expected->apply,4);
std::vector<LegacyPacket> out;
if(!mover_confirmed){Bytes mover;le(mover,selected.guid,8);out.push_back({0x26a,std::move(mover)});}
out.push_back({expected->source_ack,std::move(ack)});return out;
}
for(const auto& route:speed_routes)if(opcode==route.native_ack){
if(body.size()<8)throw Error("truncated controller speed acknowledgment");
auto move=forever_basic_movement(body.first(body.size()-8),realm,owned);
if(!authorizes_movement(move.state.guid))throw Error("speed ACK outside selected character");
Reader tail(body.last(8));auto sequence=uint32_t(tail.le(4));auto value=tail.f32();tail.end();
auto pending=pending_speeds.find(sequence);
if(pending==pending_speeds.end() || pending->second.source_opcode!=route.source ||
!std::isfinite(value) || value<0 || value!=pending->second.value)
throw Error("speed ACK outside genuine pending source change");
Bytes ack;le(ack,selected.guid,8);le(ack,sequence,4);
append(ack,turtle_basic_movement(move));le(ack,std::bit_cast<uint32_t>(value),4);
std::vector<LegacyPacket> out;
if(!mover_confirmed){Bytes mover;le(mover,selected.guid,8);out.push_back({0x26a,std::move(mover)});}
out.push_back({route.source_ack,std::move(ack)});return out;
}
if(opcode==0x420016){
if(!pending_teleport)throw Error("teleport acknowledgment without server request");
return {{0xc7,turtle_near_teleport_ack(body,*pending_teleport,realm)}};
}
if(opcode>=0x420000&&opcode<=0x420005)legacy=0xb5+(opcode-0x420000);
else if(opcode>=0x420008&&opcode<=0x42000d)legacy=0xbc+(opcode-0x420008);
else if(opcode==0x420006)legacy=0xbb;
else if(opcode==0x420017)legacy=0xc9;
else if(opcode==0x42000e)legacy=0xc2;
else if(opcode==0x42000f)legacy=0xc3;
else if(opcode==0x420018)legacy=0xca;
else if(opcode==0x420019)legacy=0xcb;
else if(opcode==0x420027 || opcode==0x42007f)legacy=0xda;
else if(opcode==0x420028)legacy=0xdb;
else if(opcode==0x42002e || opcode==0x420048 || opcode==0x420049 || opcode==0x42004f)legacy=0xee;
if(!legacy)throw Error("movement opcode outside supported subset");
auto move=forever_basic_movement(body,realm,owned);
// Modern up/down input has no vanilla opcode. Valid ordinary swimming
// projects its world XYZ/pitch to source heartbeat. The neutral stop may
// follow STOP_SWIM on land; basic parsing still rejects flying/vertical land.
if((opcode==0x420048 || opcode==0x42004f) && !move.swimming)
throw Error("vertical movement start outside ordinary swimming");
if(!authorizes_movement(move.state.guid))throw Error("movement outside selected character");
std::vector<LegacyPacket> packets;
// Tortoise Player::GetConfirmedMover compares the session-confirmed GUID;
// the modern init-complete ACK carries ticks, not that legacy control GUID.
// Bind control to the first real, validated self movement before sending it.
if(!mover_confirmed){Bytes mover;le(mover,selected.guid,8);packets.push_back({0x26a,std::move(mover)});}
packets.push_back({legacy,turtle_basic_movement(move)});
return packets;
}
void NativeWorldTranslation::movement_sent(uint32_t opcode,std::span<const uint8_t> body,std::span<const LegacyPacket> serialized) noexcept{
// Called only after validation and source serialization succeeded. Source
// normally does not echo this player's ordinary movement back to itself.
// Keep the exact serialized current XYZ for NPC TARGET facing; never infer
// a future spline endpoint or label this a source-server acknowledgment.
entities.invalidate_source_position(selected.guid);
try{
// Require byte-for-byte correspondence to this exact owned native
// intent. This also rejects arbitrary source bytes and unsupported ACKs
// when the observational hook is exercised directly by a caller.
const auto expected=player_movement(opcode,body,std::vector<Character>{selected});
if(expected.size()!=serialized.size())throw Error("serialized movement packet count mismatch");
for(size_t i=0;i<expected.size();++i)
if(expected[i].opcode!=serialized[i].opcode || expected[i].body!=serialized[i].body)
throw Error("serialized movement intent mismatch");
uint32_t source_ack=opcode==0x420030?0xf0:0;
for(const auto& route:movement_modes::Routes)if(opcode==route.native_ack)source_ack=route.source_ack;
for(const auto& route:speed_routes)if(opcode==route.native_ack)source_ack=route.source_ack;
const LegacyPacket* movement=nullptr;size_t offset=0;
for(const auto& packet:serialized){
bool regular=packet.opcode<=0xffff && NativeEntityTranslation::peer_movement_opcode(uint16_t(packet.opcode));
if(!regular && (!source_ack || packet.opcode!=source_ack))continue;
if(movement)throw Error("duplicate serialized owned movement");
movement=&packet;offset=regular?0:12;
}
// Possession re-keys the controlled unit for the Source wire. Its movement
// cannot locate the selected player, including proximity to the Undercity lifts.
if(movement && location && !pending_teleport && !possessed_unit()){
Reader r(movement->body);
if(offset){if(r.le(8)!=selected.guid)throw Error("serialized movement owner mismatch");(void)r.le(4);}
if(r.left()<28)throw Error("truncated serialized MovementInfo");
GroundMovement move;move.guid=selected.guid;move.flags=uint32_t(r.le(4));move.time=uint32_t(r.le(4));
for(auto& value:move.position)value=r.f32();
// Remaining swim/fall/spline tails already passed the original
// native parser and turtle_basic_movement before stream.encode.
entities.observe_owned_source_position(move,selected.guid,realm,location->map);
}
if(opcode==0x420030){
auto ack=knockback_ack(body,std::vector<Character>{selected});
pending_knockbacks.erase(ack.sequence);mover_confirmed=true;return;
}
}catch(...){entities.invalidate_source_position(selected.guid);return;}
if(opcode==0x420016){pending_teleport.reset();return;}
for(const auto& route:movement_modes::Routes)if(opcode==route.native_ack && body.size()>=4){
auto tail=body.last(4);uint32_t sequence=0;for(unsigned i=0;i<4;++i)sequence|=uint32_t(tail[i])<<(8*i);
pending_modes.erase(sequence);mover_confirmed=true;return;
}
for(const auto& route:speed_routes)if(opcode==route.native_ack && body.size()>=8){
auto tail=body.last(8);uint32_t sequence=0;
for(unsigned i=0;i<4;++i)sequence|=uint32_t(tail[i])<<(8*i);
pending_speeds.erase(sequence);break;
}
mover_confirmed=true;
}
std::optional<LegacyPacket> NativeWorldTranslation::take_pet_bar(){
if(!pet_bar)return {};
auto& bar=*pet_bar;
if(!location || far_transfer || logout_complete || bar.realm!=realm || bar.map!=location->map){
pet_bar.reset();return {};
}
if(!self_created || pending_teleport)return {};
const auto it=entities.actors.find(bar.state.unit);
if(it==entities.actors.end()){
if(bar.generation)pet_bar.reset();
return {};
}
const auto& actor=it->second;
const bool stat_pet=(bar.state.unit>>48)==0xf140;
if(actor.kind!=3 || !actor.generation || actor.presentation_realm!=realm || actor.presentation_map!=bar.map ||
(bar.generation && bar.generation!=actor.generation) || actor.companion ||
(stat_pet && (!actor.owned_stat_pet || !source_owned_stat_pet(actor.pending_values,selected.guid,bar.state.unit)))){
pet_bar.reset();return {};
}
bar.generation=actor.generation;
if(!actor.sent || !actor.eligible){
if(bar.shown)pet_bar.reset();
return {};
}
const auto& control=entities.self_controlled[stat_pet?1:0];
if(control.known!=3 || control.source_guid()!=bar.state.unit || control.presented!=actor.modern){
if(bar.shown)pet_bar.reset();
return {};
}
if(!bar.shown){
uint16_t family=0;
if(stat_pet){
auto meta=entities.templates.find(actor.entry);
if(meta==entities.templates.end() || !meta->second.found || meta->second.family>UINT16_MAX)return {};
family=uint16_t(meta->second.family);
}
bar.shown=true;bar.mode_changed=false;
return LegacyPacket{0x690014,forever_pet_spellbook(bar.state,actor.modern,family)};
}
if(!bar.mode_changed)return {};
bar.mode_changed=false;
auto body=pack_guid(actor.modern);
append(body,Bytes{bar.state.command,bar.state.flag,bar.state.react});
return LegacyPacket{0x47001f,std::move(body)};
}
Bytes NativeWorldTranslation::translate(const LegacyPacket& packet,uint32_t address,uint64_t clock,decltype(&gw_codec_serialize) codec){
gw_diagnostics::journal().begin(realm);
// Actual Type9 rendering is accepted. Qualified persistent areas are normal
// gameplay; the private zero override is only a diagnostic comparison.
static const bool ground_enabled=[](){const auto* value=std::getenv("GW_PRIVATE_PERSISTENT_GROUND_OBJECTS");return !value||std::strcmp(value,"0")!=0;}();
entities.persistent_ground_enabled=ground_enabled;
const bool had_self_create=self_created;
if(location)entities.set_action_scope(selected.guid,realm,location->map);
else entities.clear_action_scope();
virtual_realm_address=address;
// One invocation per genuinely received source packet. The transport
// caches world_encoded, so output-capacity retries do not count twice.
if(pending_ghost_cast && (!ghost_cast_packet_budget || !--ghost_cast_packet_budget))pending_ghost_cast.reset();
if(entities.source_packets==UINT32_MAX)entities.source_field_overflow=true;
else ++entities.source_packets;
bool initial=false,initial_replayed_owned_items=false;
std::vector<LegacyPacket> output;
std::optional<std::pair<size_t,source_combat_events::Bindings>> pending_execute;
// Self create on a ship/zeppelin: output index of that create and the ship's Source GUID (see translate below).
std::optional<std::pair<size_t,uint64_t>> self_on_mo_transport;
auto emit=[&](uint32_t opcode,Bytes body){
// A newly opened NPC interaction supersedes the previous character bank.
if(opcode==0x47031b)character_bank.reset();
output.push_back({opcode,std::move(body)});
};
// Custom animation is emitted by Source GameObject (including bobbers),
// unlike the broader WorldObject despawn/sound producers.
auto go_anim_world_active=[&]{return selected.guid && realm && self_created && location &&
!logout_complete && !pending_teleport && !far_transfer;};
auto go_anim_actor=[&](uint64_t id)->const NativeEntityTranslation::Actor*{
const auto it=entities.actors.find(id);if(it==entities.actors.end() || !location)return nullptr;
const auto& a=it->second;
if(a.kind!=5 || !a.generation || a.presentation_realm!=realm || a.presentation_map!=location->map)return nullptr;
return &a;
};
// Server combat facts for the built-in boss mods (no addon syncs: every raider hears the server).
// Spell events need a subscribed spell; spell 0 (deaths, own parried swings) passes the switch only.
auto boss=[&](std::string_view sub,uint32_t spell,uint64_t src,uint64_t dst,uint32_t amount=0,std::string_view extra={}){
if(!boss_feed_on || !self_created || !location || (spell && !boss_feed_spells.contains(spell)))return;
auto actor=[&](uint64_t guid){
BossFeedActor a;if(!guid)return a;
const std::string* name=nullptr;
if(guid==selected.guid)name=&selected.name;
else if(auto peer=entities.peer_players.find(guid);peer!=entities.peer_players.end() && peer->second.named)name=&peer->second.identity.name;
else if(auto c=chat_players.find(guid);c!=chat_players.end())name=&c->second.name;
if(name){a.kind='P';a.name=*name;return a;}
if(auto found=entities.actors.find(guid);found!=entities.actors.end() && found->second.kind==3 && found->second.entry){
a.kind='C';a.id=found->second.entry;a.low=uint32_t(guid&0xffffffu); // HIGHGUID_UNIT: entry<<24 | counter
}
return a;
};
RosterRealm context;context.realm_id=realm;context.virtual_address=address;
try{emit(0x4c0001,forever_boss_feed(selected,context,sub,spell,actor(src),actor(dst),amount,extra));}
catch(const Error&){} // An unpresentable name never disturbs the session.
};
auto refresh_guild_roster=[&]{
if(!guild_id)return;
// Membership can change after the client's guildless club query. Prime
// all Source metadata independently of another C_Club request.
const size_t needed=(clubs.queried?0u:2u)+(guild_management_pending?0u:1u);
if(requests.size()+needed>4096)throw Error("guild refresh queue bound");
if(!clubs.queried){
Bytes query;le(query,guild_id,4);requests.push_back({0x54,std::move(query)});
requests.push_back({0x87,{}});guild_roster_context.requested=true;
clubs.queried=true;
}
if(!guild_management_pending){
requests.push_back({0x89,{}});guild_management_pending=true;
guild_management_roster.reset();clubs.snapshot.reset();
}
};
auto publish_guild_details=[&]{
auto& state=guild_roster_context;
if(!state.awaiting_details || !state.matched())return;
RosterRealm context;context.realm_id=realm;context.virtual_address=address;
emit(0x530003,forever_guild_roster(*state.awaiting_details,context,state.matched()));
state.awaiting_details.reset();
};
auto source=[&](uint32_t mode,const Bytes& input){return world_codec(codec,mode,input,packet.opcode,selected.name);};
auto cast_payload=[&](const TurtleSpellCast& event,const std::map<uint64_t,Guid128>& known,
const Guid128& identity,uint32_t visual,uint32_t script,uint8_t kind){
auto bound=[&](uint64_t id)->Guid128{if(!id)return {};auto it=known.find(id);if(it==known.end())throw Error("spell event target outside live binding");return it->second;};
Bytes input{kind};append(input,bound(event.caster));append(input,bound(event.unit));append(input,identity);
le(input,event.spell,4);le(input,visual,4);le(input,script,4);
auto tick=native_presentation_milliseconds();
le(input,(kind==0 || kind==8)?event.time:tick,4);le(input,event.targets,4);
append(input,bound(event.target_unit));append(input,bound(event.target_item));
le(input,event.hits.size(),1);for(auto id:event.hits)append(input,bound(id));
le(input,event.misses.size(),1);for(auto miss:event.misses){append(input,bound(miss.guid));le(input,miss.reason,1);le(input,miss.reflect,1);}
append(input,spell_cast_location_payload(event));
if(event.flags&0x20u){le(input,event.ammo_display,4);le(input,event.ammo_inventory_type,4);}
return source(GW_CODEC_SPELL_CAST,input);
};
const auto& body=packet.body;
if(self_created && !login_equip_casts.empty() &&
(!login_equip_packet_budget || !--login_equip_packet_budget))login_equip_casts.clear();
auto chat=[&](const Bytes& message,const Character& sender,uint32_t guild){
if(!message.empty() && message[0]==0x5e){
RosterRealm local;local.realm_id=realm;local.virtual_address=virtual_realm_address;
emit(0x4c0001,forever_local_addon(selected,local,HardcorePrefix,octo_hardcore_line(turtle_hardcore_message(message),sender.name)));
return;
}
if(!message.empty() && message[0]==14 && !chat_channels.contains(turtle_chat_channel(message))) {
++channel_semantic_holds;return;
}
RosterRealm context;context.realm_id=realm;context.virtual_address=address;
emit(forever_opcodes::SMSG_CHAT,forever_chat(message,{sender},context,0,true,guild));
};
auto fail_cast=[&](const TurtleCastFailure& failure,bool interrupted_only){
const auto& request=*pending_cast;Bytes input{uint8_t(interrupted_only?3:2)};
append(input,request.spell.cast);append(input,forever_player_guid(selected.guid,realm));le(input,failure.spell,4);
le(input,request.spell.visual,4);le(input,request.spell.script_visual,4);le(input,uint32_t(failure.reason),4);le(input,uint32_t(failure.arg1),4);le(input,uint32_t(failure.arg2),4);
emit(interrupted_only?0x690046:0x69004a,source(GW_CODEC_SPELL_CAST,input));
// Spell::cancel sends FAILED_OTHER before CAST_RESULT. Retain the
// request identity until that result so CastFailed can release the
// original item-use lock too; do not lose the second half of failure.
if(interrupted_only){cast_prepared=false;return;}
if(!interrupted_only && cast_prepared){input[0]=3;emit(0x690046,source(GW_CODEC_SPELL_CAST,input));}
release_cast();
};
// Native ITEM objectives are stored values, just like native creature
// counters. Reconcile only genuine active Source quests and referenced
// owned inventory/bank/keyring items; no client-derived progress is used.
auto sync_quest_items=[&] {
if(!self_created || logout_complete || !location || !entities.self_quest_log.initialized())return;
const auto active=entities.self_quest_log.active_quests();
std::erase_if(quest_item_waiting_definitions,[&](uint32_t id){
return quests.definitions.contains(id) || std::find(active.begin(),active.end(),id)==active.end();
});
const auto inventory_counts=inventory.quest_item_counts(selected.guid);
std::map<uint32_t,std::array<uint16_t,4>> counts;
for(auto id:active) {
auto known=quests.definitions.find(id);
if(known==quests.definitions.end()){
// The native client may already cache this quest and never
// query it. Inventory alone cannot identify its item objectives.
// Fetch the genuine Source definition once per active lifetime.
if(!quest_item_waiting_definitions.contains(id) && requests.size()<4096){
if(!quests.awaiting_definition.contains(id) && !quest_poi_waiting_definitions.contains(id)){
Bytes query;le(query,id,4);requests.push_back({0x05c,std::move(query)});
}
quest_item_waiting_definitions.insert(id);
}
continue;
}
const auto definition=source_quest_definition(known->second);
auto& values=counts[id];
for(const auto& objective:definition.objectives)if(objective.type==1) {
if(objective.storage<4 || objective.storage>=8 || objective.count>32767)
throw Error("quest item objective storage/count bound");
auto amount=inventory_counts.find(objective.object);
values[objective.storage-4]=uint16_t(std::min<uint64_t>(objective.count,
amount==inventory_counts.end()?0:amount->second));
}
}
auto projection=entities.self_quest_log.set_item_counts(counts);
if(!projection.empty()){
emit(0x5e0000,source(GW_CODEC_QUEST_LOG_VALUES,
quest_log_update_input(realm,location->map,selected.guid,projection)));
quest_status_refresh.invalidate();
quest_status_refresh.observe(quest_bindings(QuestBindingSet::VisibleQuestGivers));
}
};
bool social_handled=false;
bool contact_name_queued=false;
RosterRealm social_realm;social_realm.realm_id=realm;social_realm.virtual_address=address;
if(packet.opcode==0x67 || packet.opcode==0x68 || packet.opcode==0x6b){
social_handled=true;
try{
const auto translated=social.receive(uint16_t(packet.opcode),body,social_realm);
contact_names.sync(social,selected.guid,realm);
if(packet.opcode==0x67 && !social_legacy_queued){
// A genuine, validated Source friend snapshot qualifies its
// legacy service before the native list/API becomes usable.
SocialProjection config;config.kind=SocialProjection::Kind::LegacyConfiguration;
config.virtual_address=address;
social_legacy_queued=queue_social(GW_CODEC_SOCIAL_PACKET,social_projection_input(config));
}
if(translated)for(const auto& p:*translated)queue_social(GW_CODEC_SOCIAL_PACKET,social_projection_input(p));
}catch(const SocialHold&){++social_holds;}
}
if(packet.opcode==0x51){
// Observe alongside independent peer/chat handlers, never consume it
// globally or grant an actor binding from a friend/ignore identity.
if(auto name=contact_names.receive(body,social,social_realm))
contact_name_queued=queue_social(GW_CODEC_CONTACT_NAMES,contact_names_input({*name}));
}
bool quest_handled=false;
std::optional<NativeQuestTranslation::Bindings> packet_quest_bindings;
auto current_quest_bindings=[&]() -> const NativeQuestTranslation::Bindings& {
if(!packet_quest_bindings)packet_quest_bindings=quest_bindings();
return *packet_quest_bindings;
};
if(packet.opcode==0x183 && body.size()>=8){
Reader status_guid(body);const auto guid=status_guid.le(8);
if(!quest_status_refresh.accept(guid,current_quest_bindings()))quest_handled=true;
}
if(!quest_handled && self_created && location && packet.opcode<=UINT16_MAX){
// Valid Source quest shapes without a reviewed native representation
// are presentation holds; they must not tear down this world session.
if(NativeQuestTranslation::handles_source(uint16_t(packet.opcode))){
try{
if(auto translated=quests.receive(uint16_t(packet.opcode),body,current_quest_bindings(),realm,location->map,source)){
// Refresh only after the genuine reward/progress packet has
// passed the maintained native serializer. No status is guessed.
const uint32_t changed_opcode=packet.opcode==0x191?0x670003:
packet.opcode==0x198?0x670009:packet.opcode==0x199?0x67000c:0;
if(changed_opcode && std::any_of(translated->begin(),translated->end(),[&](const auto& event){return event.opcode==changed_opcode;})){
quest_status_refresh.invalidate();
quest_status_refresh.observe(current_quest_bindings());
}
quest_handled=true;sync_quest_items();for(auto& event:*translated)output.push_back(std::move(event));
}
}catch(const Error&){++quests.held;quest_handled=true;}
}
if(!quest_poi_waiting_definitions.empty() && packet.opcode==0x05d && body.size()>=4){
Reader id(body);const auto quest=uint32_t(id.le(4));
// A malformed or rejected reply cannot unblock unpublished metadata.
if(quests.definitions.contains(quest))quest_poi_waiting_definitions.erase(quest);
}
if(quest_poi_60141_pending && quest_poi_60141_waiting_definition && packet.opcode==0x05d && body.size()>=4){
Reader id(body);if(id.le(4)==60141)quest_poi_60141_waiting_definition=false;
}
while(!quests.requests.empty()){
if(requests.size()>=4096)throw Error("native quest metadata request queue bound");
requests.push_back(std::move(quests.requests.front()));quests.requests.pop_front();
}
}
bool primary_handled=true;
if(!quest_handled && !social_handled && !source_no_native_consumer(packet.opcode).empty()) {
auto& count=no_native_consumer_drops[packet.opcode];
if(count!=UINT64_MAX)++count;
// primary_handled stays true: no unknown-packet journal entry or wire output.
} else if(!quest_handled && !social_handled)switch(packet.opcode){
case 0x26f:{
// Tortoise SendStablePet after the stablemaster gossip option or a stable refresh.
try{
auto list=turtle_stable_list(body);auto known=bindings();auto target=known.find(list.npc);
auto actor=entities.actors.find(list.npc);
if((list.npc>>48)!=0xf130 || target==known.end() || actor==entities.actors.end() || !actor->second.sent)throw Error("stable list outside a visible creature");
for(const auto& p:list.pets)if(!entities.templates.contains(p.entry) && !entities.queries.contains(p.entry) && entities.requests.size()<4096){
entities.queries.insert(p.entry);entities.requests.push_back({0x60,turtle_creature_query(p.entry)});
}
validate_stable_list(list);
stable=StableSnapshot{std::move(list),target->second,false};
}catch(const Error&){++stable_holds;}
break;
}
case 0x173:case 0x273:case 0x2c6:{
if(auto response=pet_owner_feedback(packet.opcode,body))emit(response->opcode,std::move(response->body));
// A Source stable/unstable/swap success changes the roster: re-read the Source's own list.
if(packet.opcode==0x273 && body.size()==1 && (body[0]==8 || body[0]==9) && stable && requests.size()<4096){
Bytes again;le(again,stable->list.npc,8);requests.push_back({0x26f,std::move(again)});
}
break;
}
case 0x179:{
auto book=turtle_pet_spellbook(body);
pet_bar.reset(); // Every full source snapshot supersedes the previous unit.
if(!book.unit){
if(self_created && !logout_complete)emit(0x690014,forever_pet_spellbook(book,{},0));
}else if(location && !far_transfer && !logout_complete && ((book.unit>>48)==0xf140 || (book.unit>>48)==0xf130)){
pet_bar=PetBar{std::move(book),realm,location->map};
}
break;
}
case 0x324:{
Reader r(body);const auto guid=r.le(8),action=r.le(4);r.end();
if(action>1 || !pet_bar || !pet_bar->shown || guid!=pet_bar->state.unit ||
!self_created || !location || logout_complete || far_transfer || pending_teleport)break;
auto actor=entities.actors.find(guid);
const auto& control=entities.self_controlled[1];
if(actor!=entities.actors.end() && actor->second.owned_stat_pet && actor->second.sent &&
actor->second.eligible && actor->second.generation==pet_bar->generation &&
actor->second.presentation_realm==realm && actor->second.presentation_map==location->map &&
control.known==3 && control.source_guid()==guid && control.presented==actor->second.modern){
auto packet=pack_guid(actor->second.modern);le(packet,action,4);emit(0x47014d,std::move(packet));
}
break;
}
case 0x17a:{
Reader r(body);PetSpellbook mode;mode.unit=r.le(8);turtle_pet_mode(r,mode);r.end();
if(pet_bar && (mode.unit>>48)==0xf140 && pet_bar->state.unit==mode.unit){
pet_bar->state.react=mode.react;pet_bar->state.command=mode.command;
pet_bar->state.flag=mode.flag;pet_bar->mode_changed=true;
}
break;
}
case 0x115:{
if(auto result=inspect_ack(body,address)){
for(auto& layer:*result)emit(0x4c0001,std::move(layer));
append_inspect_names(output,address);
}
break;
}
case 0x1cb:case 0x291:case 0x2b8:case 0x33b:case 0x2fd:{
const auto message=turtle_source_feedback(packet.opcode,body);
if (!message) break;
if (packet.opcode == 0x291 && message->context != 3) {
if (auto timed = forever_timed_server_message(*message)) emit(0x4c001e, std::move(*timed));
break;
}
RosterRealm target;target.realm_id=realm;target.virtual_address=address;
emit(forever_opcodes::SMSG_CHAT,forever_source_system_feedback(*message,target));break;
}
case 0x3e:case 0x3f:case 0x40:{
for(auto& event:receive_far_transfer(packet.opcode,body,source))output.push_back(std::move(event));
break;
}
case 0x5f:{if(auto response=gameobject_query_reply(body))emit(response->opcode,std::move(response->body));break;}
case 0x244:case 0x23b:{
// Tortoise SMSG_ITEM_TEXT_QUERY_RESPONSE {u32 id, cstring}: a pending book query wins; native
// QueryItemTextResponse {bit Valid, Guid Id, bits13 len, text} (TC QueryPackets.cpp:512-530).
if(packet.opcode==0x244 && body.size()>=4){
Reader peek(body);const auto id=uint32_t(peek.le(4));
auto book=std::find_if(book_text_pending.begin(),book_text_pending.end(),[&](const auto& p){return p.first==id;});
if(book!=book_text_pending.end()){
// Replies arrive in send order; the oldest query for this id owns it. The same id may also
// be awaited by the mailbox (a saved letter shares its mail's text): that request gets the next reply.
// A malformed reply must not consume the pending query: a later
// complete source response still belongs to this owned item.
auto text=peek.cstring(8191);peek.end();
auto item=book->second;book_text_pending.erase(book);
const auto& owned=inventory.owned_bindings();
if(std::none_of(owned.begin(),owned.end(),[&](const auto& p){return p.second==item;}))break; // item gone: consumed, nothing shown
Bytes out{0x80};append(out,pack_guid(item));
const auto n=uint32_t(text.size());out.push_back(uint8_t(n>>5));out.push_back(uint8_t((n&0x1f)<<3));
out.insert(out.end(),text.begin(),text.end());emit(0x4b0010,std::move(out));break;
}
}
// Source never echoes the mailbox GUID. Drain the previous list before sending the queued switch.
if(packet.opcode==0x23b && next_mailbox_actor && mailbox_list.awaiting_list()){
mailbox_list.clear();
break;
}
const auto current=current_mailbox_actor();
if(packet.opcode==0x23b && current.source_guid && mailbox_list.awaiting_list()){
try{
uint8_t count=0;std::set<uint64_t> senders;
for(const auto& mail:mailbox_detail::source_list(body,count))
if(mail.sender_type==0 && mail.sender)senders.insert(mail.sender);
contact_names.mail_senders(std::move(senders),social,selected.guid,realm);
}catch(const Error&){/* An invalid list cannot grant a name query. */}
}
auto result=packet.opcode==0x23b?mailbox_list.receive_list(body,current):mailbox_list.receive_text(body,current);
if(packet.opcode==0x23b && (!result.holds.empty() || !result.omitted.empty())){
const unsigned shown=result.native_body?unsigned(Reader(*result.native_body).le(4)):0;
const unsigned detail=result.holds.empty()?unsigned(result.omitted.front().second):
unsigned(result.holds.front());
mail_list_log(result.holds.empty()?5:4,result.source_count,shown,
result.omitted.size(),result.holds.size(),detail);
}
if(result.native_body)emit(result.native_opcode,std::move(*result.native_body));
break;
}
case 0x1d9:case 0x1da:case 0x1db:{
auto timer=forever_mirror_timer(packet.opcode,packet.body);
emit(timer.opcode,std::move(timer.body));break;
}
case 0x2fa:{
if (auto warning = forever_raid_reset_warning(body, {realm, address}))
emit(warning->opcode, std::move(warning->body));
break;
}
case 0x2cb:{ // Both DungeonMap bind notifications send a zero non-GM flag.
if(body.size()==4 && Reader(body).le(4)==0)emit(0x470228,{0});
break;
}
case 0x31e:case 0x320:{ // Reset succeeded / last saved instance, each carrying one MapID.
if(body.size()==4)emit(packet.opcode==0x31e ? 0x470133 : 0x470135,body);
break;
}
case 0x31f:{
if(body.size()!=8)break;
Reader r(body);
const auto reason=r.le(4);
if(reason>2)break; // Source reasons >= 3 deliberately produce no player message.
Bytes failed;
le(failed,r.le(4),4);
failed.push_back(uint8_t(reason<<6));
emit(0x470134,std::move(failed));
break;
}
case 0x32b:{ // Sent before the individual map IDs on login and map transfers.
if(body.size()==4 && Reader(body).le(4)<=1)emit(0x470156,body);
break;
}
case 0x1fb:{
if(!self_created)break;
try{
const auto roll=turtle_random_roll(body);
if(random_roll_player_bound(roll,selected.guid,loot.group))
emit(0x4700da,source(GW_CODEC_RANDOM_ROLL,random_roll_codec_input(roll,realm)));
}catch(const Error&){/* Malformed/unbound result is held, never invented. */}
break;
}
case 0x166:{loot_receipts.push(turtle_item_push(body),selected.guid);break;}
case 0x77:case 0x7c:case 0x7d:case 0x160:case 0x161:case 0x162:case 0x163:case 0x165:case 0x29e:case 0x29f:case 0x2a1:case 0x2a2:case 0x2a4:{
if(packet.opcode==0x160 && !location)throw Error("source loot before world location");
loot.templates=&inventory.peer_templates;
if(packet.opcode==0x160 && body.size()>=9){uint64_t o=0;for(int i=7;i>=0;--i)o=(o<<8)|body[i];
auto h=entities.actors.find(o);
gw_inv_log("GW_FISH loot-response owner=%llx type=%u size=%zu armed=%d armed_src=%llx fishing=%d actor=%d gotype=%d sent=%d eligible=%d\n",
(unsigned long long)o,unsigned(body[8]),body.size(),int(loot.opening.has_value()),(unsigned long long)(loot.opening?loot.opening->source:0),int(loot.fishing),
int(h!=entities.actors.end()),h!=entities.actors.end()?int(h->second.gameobject_type):-1,h!=entities.actors.end()?int(h->second.sent):-1,h!=entities.actors.end()?int(h->second.eligible):-1);}
{auto events=loot.translate(packet,selected,realm,location?location->map:0,entities,source);
if(packet.opcode==0x160)gw_inv_log("GW_FISH loot-response emitted=%zu\n",events.size());
for(auto& event:events)emit(event.opcode,std::move(event.body));}
while(!loot.received_award_intents.empty()){loot_receipts.roll(loot.received_award_intents.front());loot.received_award_intents.pop_front();}
while(!loot.roll_chat_notices.empty()){
const auto text=std::move(loot.roll_chat_notices.front());loot.roll_chat_notices.pop_front();
RosterRealm target;target.realm_id=realm;target.virtual_address=address;
Bytes notice{10};le(notice,0,4);le(notice,0,8);le(notice,text.size()+1,4);cstring(notice,text);le(notice,0,1);
emit(0x4c0001,forever_chat(notice,{selected},target,0,true));
}
if(packet.opcode==0x7d){party.changed();party_invitation.reset();}
break;
}
case 0x4c:{
// Original CharacterPackets::LogoutResponse: int32 reason, MSB bool.
// Tortoise uses uint32 reason, uint8 bool; reviewed reasons0..3 agree.
Reader r(body);auto reason=r.le(4),instant=r.le(1);r.end();
if(reason>3 || instant>1 || (reason && instant))throw Error("invalid source logout response");
logout_countdown=reason==0 && instant==0;Bytes result;le(result,reason,4);le(result,instant?0x80:0,1);emit(0x470130,std::move(result));break;
}
case 0x4f:{Reader r(body);r.end();logout_countdown=false;emit(0x470132,{});break;}
case 0x1f8:{emit(0x47020a,forever_exploration_experience(body));break;}
case 0x4d:{
Reader r(body);r.end();
pending_guild_invitation=false;
party_invitation.reset();summon_offer.reset();pre_self_items.clear();pre_self_item_map.reset();
// Original LogoutComplete's optional SwitchGameMode is absent for
// Turtle. No account proof, realm transport or session key changes.
early_undercity.clear();undercity_settle.reset();undercity_generation=0;entities.undercity_seen.reset();entities.undercity_filled.reset();
entities.self_melee_target.reset();
emit(0x470131,Bytes{0});logout_countdown=false;trade.close();battlegrounds={};logout_complete=true;self_created=false;trainer.reset();entities.self_profession_skills.clear();forced_reactions.reset();forced_reactions_dirty=false;wand_repeating=false;wand_gcd_until.reset();published_home_party=false;stable.reset();binder_offer.reset();auction_browse.reset();auction_personal.reset();auction_personal_deferred.clear();auction_commodity.reset();self_coinage.reset();ah_list_inflight=false;ah_list_retired=false;pet_rename_sent.clear();pet_rename_dropped=0;book_text_pending.clear();page_chains.clear();pet_unlearn_offer.reset();source_zone.reset();gossip.reset();pending_who.reset();bg_team={};pending_time_kinds.clear();observed_casts.clear();auras.pending_self_hits.clear();entities.spell_channels.clear();clear_bank();clear_inspect_selection();
equipment_sets = {};
character_bank.reset();
clear_mailbox();
guild_rank_info.reset();guild_roster_rights.reset();guild_management_roster.reset();guild_management_pending=false;guild_control_clear();clubs.reset();guild_roster_context={};guild_rank_assignment.reset();guild_permissions.reset();
own_guild_join=OwnGuildJoin::None;
cooldown_flat.fill(0);cooldown_percent.fill(0);cooldown_flat_received=0;spell_modifier_aggregates.clear();
pending_speeds.clear();pending_modes.clear();pending_knockbacks.clear();requests.clear();
quest_item_waiting_definitions.clear();social.reset();contact_names.invalidate();social_presentations.clear();social_legacy_queued=false;quest_poi_pending.clear();quest_poi_waiting_definitions.clear();quest_poi_60141_pending.reset();quest_poi_60141_waiting_definition=false;quest_status_refresh={};
standing_cast.reset();source_stand.reset();source_stand_pending=false;clear_stance_cast();source_form.reset();
entities.requests.clear();inventory.requests.clear();inventory.deferred_template_projection=false;
release={};source_health.reset();
{auto serial=loot.serial;loot={};loot.serial=serial;} // Do not recycle presentation IDs on the same transport.
loot_receipts.reset();
break;
}
case 0x216:{
// A real source location, not an invented corpse object/identity.
const auto corpse=turtle_corpse_location(body);
if(release.requested){
release.corpse_valid=corpse.valid;
if(!corpse.valid)release={};
}
if(source_ghost==true)trace_release("source_corpse_reply");
Bytes input{0};le(input,realm,2);le(input,selected.guid,8);append(input,body);
emit(0x4700f8,source(GW_CODEC_CORPSE_EVENT,input));break;
}
case 0x269:{
Reader r(body);auto remaining=r.le(4);r.end();
Bytes input{1};le(input,realm,2);le(input,selected.guid,8);le(input,remaining,4);
emit(0x4701f5,source(GW_CODEC_CORPSE_EVENT,input));break;
}
case 0xef:{
Reader r(body);auto packed=unpack_guid(r,8);Reader id(packed);auto guid=id.le(8);
auto sequence=uint32_t(r.le(4));
std::array<float,4> impulse;for(auto& value:impulse)value=r.f32();r.end();
if(!self_created || !authorizes_movement(guid) ||
!std::all_of(impulse.begin(),impulse.end(),[](float f){return std::isfinite(f);}) ||
std::abs(impulse[0])>1.01f || std::abs(impulse[1])>1.01f || impulse[2]<0)
throw Error("invalid server controller knockback");
auto it=pending_knockbacks.find(sequence);
if(pending_modes.contains(sequence) || pending_speeds.contains(sequence) ||
(it!=pending_knockbacks.end() && it->second!=impulse))throw Error("conflicting knockback sequence");
if(it==pending_knockbacks.end() && pending_modes.size()+pending_speeds.size()+pending_knockbacks.size()>=128)
throw Error("pending knockback bound");
Bytes out=pack_guid(forever_player_guid(guid,realm));le(out,sequence,4);
for(float value:impulse)le(out,std::bit_cast<uint32_t>(value),4);
pending_knockbacks[sequence]=impulse;emit(0x600033,std::move(out));native_movement_counter=sequence+1;
break;
}
case 0xde:case 0xdf:case 0xe8:case 0xea:case 0xf2:case 0xf3:case 0xf4:case 0xf5:{
if(!self_created)throw Error("controller mode before self-create");
Reader r(body);auto id=unpack_guid(r,8);Reader raw(id);auto guid=raw.le(8);auto sequence=uint32_t(r.le(4));r.end();
if(guid!=selected.guid)throw Error("mode change outside selected controller");
auto route=std::find_if(std::begin(movement_modes::Routes),std::end(movement_modes::Routes),[&](const auto& row){return row.source==packet.opcode;});
auto pending=pending_modes.find(sequence);
if(pending_knockbacks.contains(sequence) || pending_speeds.contains(sequence) || (pending!=pending_modes.end() && pending->second!=packet.opcode))throw Error("conflicting movement mode sequence");
if(pending==pending_modes.end() && pending_modes.size()+pending_speeds.size()+pending_knockbacks.size()>=128)throw Error("pending movement control bound");
pending_modes[sequence]=packet.opcode;
auto payload=pack_guid(forever_player_guid(guid,realm));le(payload,sequence,4);emit(route->native,std::move(payload));native_movement_counter=sequence+1;break;
}
case 0xe2:case 0xe4:case 0xe6:case 0x2da:case 0x2dc:case 0x2de:{
if(!self_created)throw Error("controller speed change before self-create");
Reader r(body);auto guid=unpack_guid(r,8);auto sequence=uint32_t(r.le(4));auto value=r.f32();r.end();
uint64_t source_guid=0;for(unsigned i=0;i<8;++i)source_guid|=uint64_t(guid[i])<<(8*i);
if(!authorizes_movement(source_guid) || !std::isfinite(value) || value<0)
throw Error("controller speed change outside authenticated finite self state");
auto existing=pending_speeds.find(sequence);
if(pending_knockbacks.contains(sequence) || pending_modes.contains(sequence) || (existing!=pending_speeds.end() && (existing->second.source_opcode!=packet.opcode || existing->second.value!=value)))
throw Error("conflicting source speed sequence");
if(existing==pending_speeds.end() && pending_speeds.size()+pending_modes.size()+pending_knockbacks.size()>=128)throw Error("pending speed change bound");
for(const auto& route:speed_routes)if(route.source==packet.opcode){
Bytes update=pack_guid(forever_player_guid(source_guid,realm));le(update,sequence,4);le(update,std::bit_cast<uint32_t>(value),4);
pending_speeds.insert_or_assign(sequence,PendingSpeed{packet.opcode,value});emit(route.native,std::move(update));native_movement_counter=sequence+1;break;
}
break;
}
case 0x122:{
const auto mappings=native_faction_mappings();
auto states=turtle_initial_reputation(body);std::map<uint32_t,int32_t> next;
for(const auto& row:states)if(mappings.contains(row.index))next.emplace(row.index,row.standing);
const auto* diagnostic=std::getenv("GW_NATIVE_REPUTATION_DIAGNOSTICS");
if(diagnostic && std::strcmp(diagnostic,"1")==0)for(const auto& row:states){
if(reputation_diagnostic_rows>=256)break;
auto found=mappings.find(row.index);if(found==mappings.end())continue;
++reputation_diagnostic_rows;
std::fprintf(stderr,"GWReputation {\"source_index\":%u,\"faction_id\":%u,\"native_index\":%u,\"flags\":%u,\"source_delta\":%d,\"base_adjustment\":%d}\n",row.index,found->second.id,found->second.index,unsigned(row.flags),row.standing,found->second.legacy_base);
}
auto init=forever_initial_reputation(states,mappings);
reputation_values=std::move(next);emit(0x4701cf,std::move(init));break;
}
case 0x124:{
emit(0x4701d7,forever_reputation_standing(body,native_faction_mappings(),reputation_values));break;
}
case 0x313:{ // Player::SendFactionAtWar: u32 repListID, u8 0|FACTION_FLAG_AT_WAR(2).
// Native 0x4701ab constructor reads u32 index then u16 flags; its handler only
// sets/clears bit 0x2 of that reputation row (index < 1000).
Reader r(body);const auto index=uint32_t(r.le(4));const auto flags=uint32_t(r.le(1));r.end();
if(flags & ~2u)break;
const auto mappings=native_faction_mappings();const auto found=mappings.find(index);
if(found==mappings.end())break;
Bytes out;le(out,found->second.index,4);le(out,flags,2);emit(0x4701ab,std::move(out));break;
}
case 0x123:{
Reader r(body);auto index=r.le(4);r.end();
const auto mappings=native_faction_mappings();
if(mappings.contains(index))emit(0x4701d5,forever_reputation_visible(body,mappings));
break;
}
case 0x51:{
// This response also services independent peer-player name queries.
// Only our outstanding chat query authorizes strict chat metadata use.
if(body.size()<8)break;
Reader identity(body);const auto guid=identity.le(8);
// A group member whose name is answered on the peer-entity path (its query is
// deduplicated there) still needs this Source identity for the party roster;
// otherwise NativePartyTranslation holds the whole update forever.
if(!chat_name_queries.contains(guid) && loot.group && !loot.group->explicit_solo && !chat_players.contains(guid) &&
std::any_of(loot.group->members.begin(),loot.group->members.end(),[&](const auto& m){return m.guid==guid;})){
try{auto member=turtle_chat_player(body);if(chat_players.size()<4096)chat_players[member.guid]=member;}
catch(const Error&){}
break;
}
if(!chat_name_queries.contains(guid))break;
Character player;
try{player=turtle_chat_player(body);}
catch(const Error&){
// Keep the existing bounded query/messages for a genuine later
// reply. No invented identity, automatic retry or native output.
break;
}
chat_name_queries.erase(guid);
if(chat_players.size()>=4096 && !chat_players.contains(player.guid))break;
chat_players[player.guid]=player;
// Source 0x51 is the answer to our bounded query for this chat sender.
// The chat packet supplies a GUID and name, but GetPlayerInfoByGUID
// needs a native player-name response to learn the sender's class.
// Present that response before releasing held chat messages so their
// first visible line can use the original client's class-color path.
if (contact_name_queued && self_created && !logout_complete) {
// The friend lookup already has the sender's level and class. Publish
// it before the held chat so both views use the same name response.
for (auto& reply : take_social_presentation(codec)) output.push_back(std::move(reply));
} else if(turtle_source_roster_pair(player.race,player.cls)){
ContactNameProjection name{};
name.guid=forever_player_guid(player.guid,realm);
name.virtual_address=address;
name.name=player.name;
name.race=player.race;
name.sex=player.gender;
name.cls=player.cls;
// Source name replies omit level. Preserve unknown as zero, like
// other Source-backed native name projections.
name.pvp_faction=(player.race==1 || player.race==3 || player.race==4 ||
player.race==7 || player.race==10)?1:0;
try{
emit(NativeContactNameReply,source(GW_CODEC_CONTACT_NAMES,contact_names_input({name})));
}catch(const Error&){++social_holds;}
}
for(auto it=pending_chats.begin();it!=pending_chats.end();){
Reader r(*it);auto type=r.le(1);auto language=r.le(4);auto sender=r.le(8);
if(sender!=player.guid){++it;continue;}
// Name queries do not establish foreign guild membership. Keep
// SenderGuildGUID absent; channel type still comes from real wire.
if(language==0xffffffffu){
try{
RosterRealm context;context.realm_id=realm;context.virtual_address=address;
if(auto peer=turtle_peer_addon_message(*it)){
for(auto& part:forever_peer_addon_messages(*peer,player,context))emit(0x4c0001,std::move(part));
if(auto pull=bigwigs_pull_seconds(*peer);pull && peer->sender!=selected.guid)emit(0x47003e,forever_start_timer(*pull,*pull,nullptr));
}else for(auto& part:forever_server_addon_replies(turtle_server_addon_message(*it),player,context))emit(0x4c0001,std::move(part));
}catch(const Error&){
++channel_semantic_holds;
// NameQuery only releases queued work. Attribute a held
// addon projection to its original source0x96 and bounded
// pending index, not this otherwise valid source0x51.
trace_combat("queued_addon_projection_held",0x96,selected.guid,player.guid,0,
uint32_t(it-pending_chats.begin()),0,1);
}
// Only guild/officer chat depends on current guild membership.
// Name resolution must preserve ordinary whisper/channel delivery.
}else if((type!=3 && type!=4) || guild_id)chat(*it,player,0);
it=pending_chats.erase(it);
}
break;
}
case 0x99:{
RosterRealm context;context.realm_id=realm;context.virtual_address=address;
try {
for(auto& packet:chat_channels.notify(body,context,selected.guid))
emit(packet.opcode,std::move(packet.body));
} catch(const ChannelHold&) { ++channel_semantic_holds; }
// Rapid zone changes: a request skipped while an earlier move was unacknowledged
// is re-evaluated against the latest Source zone once that acknowledgement lands.
if(self_created && !logout_complete && source_zone)follow_source_zone();
break;
}
case 0x9b:{
RosterRealm context;context.realm_id=realm;context.virtual_address=address;
try {
auto packet=chat_channels.list(body,context);
// Upstream ClassicOpcodes.cpp blocks SMSG_CHANNEL_LIST ("Classic chat index 0x1D, reader rva
// 0xA10E70, layout not verified yet"). Validate and settle the request, but send the native
// reply only on explicit opt-in until a fixture verifies the 70334 reader.
const char* opt_in=std::getenv("GW_CHANNEL_LIST_RESPONSE");
if(opt_in && std::string_view(opt_in)=="1")emit(packet.opcode,std::move(packet.body));
else ++channel_semantic_holds;
} catch(const ChannelHold&) { ++channel_semantic_holds; }
break;
}
case 0x8a:{
if(!guild_id)break; // A late response cannot cross cleared membership.
RosterRealm context;context.realm_id=realm;context.virtual_address=address;
auto* roster_writer=gw_roster_diagnostics::process_writer();
gw_roster_diagnostics::Timing roster_timing(roster_writer,body.size());
auto roster=turtle_guild_roster(body);
roster_timing.parsed_now();
if(roster_writer)roster_writer->submit({selected.guid,realm,guild_id},roster.members,body.size(),gw_roster_diagnostics::now_us()/1000);
if(auto permissions=guild_permissions.observe(roster,selected.guid,guild_rank))emit(0x530028,std::move(*permissions));
// Preserve authoritative members even when the classic roster arrives
// before the first club query. UI/control feature gates do not gate data.
if(std::any_of(roster.members.begin(),roster.members.end(),[&](const auto& m){return m.guid==selected.guid && m.rank==guild_rank;})){
guild_management_roster=roster;guild_management_pending=false;guild_control_refresh();
if(guild_rank_assignment && guild_rank_info){
if(auto next=guild_rank_assignment->observe(*guild_rank_info,roster,guild_rank)){
if(requests.size()>4093)throw Error("guild rank continuation queue bound");
requests.push_back(std::move(*next));requests.push_back({0x89,{}});
}
if(guild_rank_assignment->complete || guild_rank_assignment->conflicted)guild_rank_assignment.reset();
else guild_management_pending=true;
}
}
const bool ranks_enabled=gw_accepted_feature_enabled("GW_GUILD_RANKS_PROTOTYPE");
if (ranks_enabled) {
const auto self=std::find_if(roster.members.begin(),roster.members.end(),[&](const auto& member){return member.guid==selected.guid;});
if(self!=roster.members.end() && self->rank==guild_rank){
guild_roster_rights=roster.source_rank_rights;
if(guild_rank_info && guild_rank_info->id==guild_id){
try{emit(0x530010,forever_guild_ranks(*guild_rank_info,*guild_roster_rights));}
catch(const Error&){/* A rank-count race waits for matching Source records. */}
}
}
}
auto& details=guild_roster_context;
details.awaiting_details.reset();
if(!details.details && !details.requested && !clubs.queried && requests.size()<4096){
requests.push_back({0x87,{}});
details.requested=true;
}
try {
emit(0x530003,forever_guild_roster(roster,context,details.matched()));
if(!details.matched())details.awaiting_details=roster;
} catch(const GuildRosterHold&) {
// Preserve complete Source parsing and the bank permissions below.
// Do not truncate text or turn an unavailable presentation into
// a transport failure; a later representable roster can publish.
}
if(!bank_roster_pending || !bank_current())break;
auto rights=roster.source_rank_rights;
if(guild_rank>=rights.size())throw Error("bank roster rank differs");
bank_rank_rights=std::move(rights);bank_roster_pending=false;
bank_player_guids.clear();
for(const auto& m:roster.members)bank_player_guids[m.name]=forever_player_guid(m.guid,realm);
GuildBankChange change;change.metadata=true;
for(auto& p:bank_presentation(change))emit(p.opcode,std::move(p.body));
break;
}
case 0x6f:{
// Source supplies a name only. #110 (owner 2026-11-26, OCTO: invites from a guild mate did nothing, the
// retry said "already in a group"): the offer was published only for a visible peer of the player's own
// race, so every other invite stayed pending on the server and invisible here. Resolve the inviter's GUID
// from a unique visible peer (any race: Source invites are same-faction already), else from the Source
// guild roster or a known chat sender. A genuine name-only offer gets a system-line fallback.
const auto previous=party_invitation;
party_invitation.reset();Reader r(body);auto name=r.cstring(48);r.end();
auto ascii_name=[](const std::string& v){return !v.empty() && std::all_of(v.begin(),v.end(),[](unsigned char c){return (c>='A'&&c<='Z')||(c>='a'&&c<='z');});};
if(!self_created || !location || far_transfer || !address || !ascii_name(name))break;
if(loot.group && !loot.group_transition && !loot.group->explicit_solo)break;
uint64_t guid=0,generation=0;bool ambiguous=false;
for(const auto& [id,peer]:entities.peer_players){
auto actor=entities.actors.find(id);
if(id==selected.guid || !id || id>UINT32_MAX || !peer.named || peer.blocked ||
peer.identity.guid!=id || !ascii_name(peer.identity.name) ||
normalize(peer.identity.name)!=normalize(name) || actor==entities.actors.end() ||
!actor->second.sent || actor->second.kind!=4 || !peer.generation ||
actor->second.generation!=peer.generation || actor->second.presentation_realm!=realm ||
actor->second.presentation_map!=location->map)continue;
if(guid){ambiguous=true;break;}guid=id;generation=peer.generation;
}
if(ambiguous)break;
auto unique=[&](auto&& each){uint64_t found=0;bool twice=false;
each([&](uint64_t id,const std::string& n){
if(!id || id>UINT32_MAX || id==selected.guid || normalize(n)!=normalize(name) || id==found)return;
if(found)twice=true;else found=id;});
if(twice)ambiguous=true;
return twice?uint64_t(0):found;};
if(!guid && guild_management_roster)
guid=unique([&](auto&& f){for(const auto& m:guild_management_roster->members)f(m.guid,m.name);});
if(!guid)guid=unique([&](auto&& f){for(const auto& [id,c]:chat_players)f(id,c.name);});
if(ambiguous)break;
if(!guid){
const auto now=std::chrono::steady_clock::now();
if(previous && !previous->guid && normalize(previous->name)==normalize(name) && now<previous->expires){
party_invitation=previous;break;
}
// Source owns the pending offer. CMSG_GROUP_ACCEPT/DECLINE have no
// inviter identity, so a real name-only offer is sufficient to reply.
const auto text=name+" invites you to a group. Type /run AcceptGroup() to accept or /run DeclineGroup() to decline (within 60 seconds).";
Bytes chat{10};le(chat,0,4);le(chat,0,8);le(chat,text.size()+1,4);cstring(chat,text);le(chat,0,1);
RosterRealm target;target.realm_id=realm;target.virtual_address=address;
emit(0x4c0001,forever_chat(chat,{selected},target,0,true));
party_invitation=PartyInvitation{0,0,now+std::chrono::seconds(60),false,name};
break;
}
if(previous && previous->guid==guid && (previous->accepted || previous->generation==generation) &&
std::chrono::steady_clock::now()<previous->expires){party_invitation=previous;break;}
Bytes input;le(input,realm,2);le(input,address,4);le(input,guid,8);cstring(input,name);
cstring(input,realm_name);
auto native=source(GW_CODEC_PARTY_INVITE,input);emit(0x470061,std::move(native));
party_invitation=PartyInvitation{guid,generation,std::chrono::steady_clock::now()+std::chrono::seconds(60),false,name};
break;
}
// ---- Source world/feedback batch: catalogue claude-lane/exports/unhandled-source-smsg-20261121.json ----
case 0x15b:{ // RESURRECT_REQUEST: u64 offerer, u32 name size, name, u8 sickness, u8 !no-timer
Reader r(body);const auto by=r.le(8);(void)r.le(4);const auto name=r.cstring(2047);
const bool sick=r.le(1)!=0,timer=r.le(1)!=0;r.end();auto g=native_guid(by);if(!g)break;
// ResurrectRequest: offerer, VRA, PetNumber, SpellID (Source sends none), 11-bit name, UseTimer, Sickness.
Bytes out;wf_guid(out,*g);le(out,virtual_realm_address,4);le(out,0,4);le(out,0,4);
wf_bits16(out,(uint32_t(name.size())<<5)|(timer?0x10u:0u)|(sick?0x08u:0u));out.insert(out.end(),name.begin(),name.end());
emit(0x470012,std::move(out));break;
}
case 0x2ab:{ // SUMMON_REQUEST: u64 summoner, u32 zone, u32 auto-decline ms
Reader r(body);const auto by=r.le(8);const auto zone=r.le(4);const auto delay=r.le(4);r.end();
summon_offer.reset(); // A complete new source offer supersedes the prior one.
if(logout_complete || !selected.guid || !realm || !by || !delay)break;
auto g=native_guid(by);if(!g)break;
// Keep one genuine offer across loading; the normal/local presentation
// drain binds its map and emits it once world entry is ready.
summon_offer=SummonOffer{by,selected.guid,*g,realm,0,
std::chrono::steady_clock::now()+std::chrono::milliseconds(delay),uint32_t(zone),false};
break;
}
case 0x1d4:{ // LEVELUP_INFO: level, hp, 5 powers, 5 stats
Reader r(body);uint32_t v[12];for(auto& x:v){x=uint32_t(r.le(4));}
r.end();if(!v[0] || v[0]>255)break;
Bytes out;le(out,v[0],4);le(out,v[1],4);for(int i=0;i<10;++i){le(out,i<5?v[2+i]:0,4);}
for(int i=0;i<5;++i){le(out,v[7+i],4);}
le(out,v[0]>=10?1:0,4);le(out,0,4); // classic grants one talent point per level from 10
emit(0x470194,std::move(out));break;
}
case 0x2f4:{ // WEATHER: u32 type 0..3, f32 grade, u32 1.12 sound, u8 instant
Reader r(body);const auto type=r.le(4);const float grade=r.f32();(void)r.le(4);const bool instant=r.le(1)!=0;r.end();
if(type>3 || !(grade>=0.f && grade<=1.f))break;
// Native state rule (Weather::GetWeatherState): fine below 0.27, then light/medium/heavy at 0.40/0.70.
static constexpr uint32_t states[4][3]={{0,0,0},{3,4,5},{6,7,8},{22,41,42}};
const uint32_t state=grade<0.27f?0:states[type][grade<0.40f?0:grade<0.70f?1:2];
Bytes out;le(out,state,4);le(out,std::bit_cast<uint32_t>(grade),4);le(out,instant?0x80:0,1);
emit(0x470153,std::move(out));break;
}
case 0x2c3:{Reader r(body);const auto id=r.le(4),value=r.le(4);r.end();Bytes out;le(out,id,4);le(out,value,4);le(out,0,1);emit(0x4701f3,std::move(out));break;}
case 0x277:{Reader r(body);const auto kit=r.le(4);r.end();Bytes out;le(out,kit,4);emit(0x470214,std::move(out));break;}
case 0x278:{ // PLAY_OBJECT_SOUND: u32 kit, u64 source object
Reader r(body);const auto kit=r.le(4);const auto by=r.le(8);r.end();
// Source WorldObject::PlayDistanceSound is ignored when the object is
// not loaded. The generic native_guid player fallback is not evidence
// of a live spatial emitter, particularly across logout/map transfer.
if(!by || !realm || !self_created || !location || logout_complete || pending_teleport || far_transfer)break;
Guid128 emitter{};
if(by==selected.guid)emitter=forever_player_guid(by,realm);
else{
const auto found=entities.actors.find(by);if(found==entities.actors.end())break;
const auto& actor=found->second;
if(actor.kind<3 || actor.kind>7 || !actor.sent || !actor.eligible || !actor.generation ||
actor.modern==Guid128{} || actor.presentation_realm!=realm || actor.presentation_map!=location->map)break;
emitter=actor.modern;
}
Bytes out;le(out,kit,4);wf_guid(out,emitter);wf_guid(out,emitter);for(int i=0;i<3;++i){le(out,0,4);}
le(out,0,4); // played at the source object
emit(0x470216,std::move(out));break;
}
case 0x2d2:{Reader r(body);const auto kit=r.le(4);r.end();Bytes out;le(out,kit,4);wf_guid(out,Guid128{});le(out,0,4);emit(0x470213,std::move(out));break;}
case 0x14e:{Reader r(body);r.end();emit(0x4d0025,{});break;}
case 0x2e4:{Reader r(body);const auto by=r.le(8);const auto ms=r.le(4);r.end();auto g=native_guid(by);if(!g)break;Bytes out;wf_guid(out,*g);le(out,ms,4);emit(0x4701eb,std::move(out));break;}
case 0x2bd:{Reader r(body);r.end();Bytes out;le(out,10,4);emit(0x4701f0,std::move(out));break;} // 1.12 death durability loss is 10%
case 0x127:{const auto out=forever_set_proficiency(body);emit(0x4701e0,Bytes(out.begin(),out.end()));break;}
case 0x2a9:{
Reader r(body);const auto name=r.cstring(511);r.end();Bytes out;wf_bits16(out,uint32_t(name.size())<<7);
out.insert(out.end(),name.begin(),name.end());emit(0x4c000f,std::move(out));break;
}
case 0x254:{Reader r(body);const auto area=r.le(4);r.end();Bytes out;le(out,area,4);emit(0x4c000d,std::move(out));break;}
case 0xb3:{
Reader r(body);const auto by=r.le(8);const auto anim=uint32_t(r.le(4));r.end();
const auto high=by>>48;
if(!go_anim_world_active() || (high!=0xf110 && high!=0xf120 && high!=0x1fc0))break;
const auto* actor=go_anim_actor(by);
if(entities.actors.contains(by) && !actor)break;
if(actor && actor->sent){
if(!actor->eligible || actor->modern==Guid128{})break;
Bytes out;wf_guid(out,actor->modern);le(out,anim,4);le(out,0,1);emit(0x470068,std::move(out));break;
}
// Preserve the pre-create / pre-template bobber splash, but never let
// it cross character, world scope, or an observed actor incarnation.
gw_inv_log("GW_GO custom-anim held go=%llx anim=%u\n",(unsigned long long)by,unsigned(anim));
if(held_go_anims.size()>=16)held_go_anims.erase(held_go_anims.begin());
held_go_anims.push_back({by,anim,std::chrono::steady_clock::now()+std::chrono::seconds(5),
selected.guid,actor?actor->generation:0,realm,location->map});
break;
}
case 0x215:{ // Source WorldObject::SendObjectDeSpawnAnim, before object removal.
Reader r(body);const auto by=r.le(8);r.end();
if(!by || !realm || !self_created || !location || logout_complete || pending_teleport || far_transfer)break;
Guid128 emitter{};
if(by==selected.guid)emitter=forever_player_guid(by,realm);
else{
const auto found=entities.actors.find(by);if(found==entities.actors.end())break;
const auto& actor=found->second;
// Totems and dynamic objects also produce this Source event.
// Require their current presentation, not a synthetic player GUID
// or a stale sent flag from another map/realm/generation.
if(actor.kind<3 || actor.kind>7 || !actor.sent || !actor.eligible || !actor.generation ||
actor.modern==Guid128{} || actor.presentation_realm!=realm || actor.presentation_map!=location->map)break;
emitter=actor.modern;
}
emit(0x470069,pack_guid(emitter));break;
}
case 0x2a7:{ // GameObject::SendGameObjectReset -> native packed-GUID reset reader.
if(body.size()!=8)break;
Reader r(body);const auto by=r.le(8);r.end();
if(!self_created || !location || logout_complete || pending_teleport || far_transfer)break;
const auto found=entities.actors.find(by);
if(found==entities.actors.end())break;
const auto& actor=found->second;
if(actor.kind!=5 || !actor.sent || !actor.eligible || !actor.generation || actor.modern==Guid128{} ||
actor.presentation_realm!=realm || actor.presentation_map!=location->map)break;
emit(0x4701ca,pack_guid(actor.modern));break;
}
case 0xfa:{Reader r(body);const auto id=r.le(4);r.end();Bytes out;le(out,id,4);wf_guid(out,Guid128{});emit(0x470275,std::move(out));break;}
case 0x158:{Reader r(body);const auto by=r.le(8);const auto area=r.le(4);r.end();Bytes out;wf_guid(out,native_guid(by).value_or(Guid128{}));le(out,area,4);emit(0x660000,std::move(out));break;}
case 0x1cf:{Reader r(body);const auto now=r.le(4);r.end();Bytes out;le(out,now,8);
bool offset=false;if(!pending_time_kinds.empty()){offset=pending_time_kinds.front();pending_time_kinds.pop_front();}
emit(offset?0x4701c0:0x47018f,std::move(out));break;}
case 0x1ea:{Reader r(body);const auto by=r.le(8);const auto left=r.le(4);r.end();auto g=native_guid(by);if(!g)break;Bytes out;wf_guid(out,*g);le(out,left,4);emit(0x4701ff,std::move(out));break;}
case 0x1df:{Reader r(body);const auto by=r.le(8);r.end();auto g=native_guid(by);if(!g)break;Bytes out;wf_guid(out,*g);emit(0x4701c6,std::move(out));break;}
// Tortoise HandleReadItemOpcode appends the item GUID a second time; accept the short form too.
case 0xae:{Reader r(body);const auto by=r.le(8);if(r.left()){if(r.le(8)!=by)break;}r.end();auto g=native_guid(by);if(!g){const auto& owned=inventory.owned_bindings();if(auto it=owned.find(by);it!=owned.end())g=it->second;}if(!g)break;Bytes out;wf_guid(out,*g);emit(0x47024c,std::move(out));break;}
case 0xaf:{Reader r(body);const auto by=r.le(8);const auto sub=r.le(1);if(r.left()){if(r.le(8)!=by)break;}r.end();auto g=native_guid(by);if(!g){const auto& owned=inventory.owned_bindings();if(auto it=owned.find(by);it!=owned.end())g=it->second;}if(!g || sub>3)break;Bytes out;wf_guid(out,*g);le(out,0,4);le(out,sub<<6,1);emit(0x470254,std::move(out));break;}
case 0x178:{ // SMSG_PET_NAME_INVALID: empty (Tortoise SendPetNameInvalid drops the reason and name)
Reader r(body);r.end();if(pet_rename_sent.empty() && !pet_rename_dropped)break;
// Failures answer the oldest attempt (FIFO), whichever pet it was for.
const uint64_t current=pet_bar?pet_bar->state.unit:0;
// PetNameInvalid {u32 Result, Guid, i32 number, bits8 len, bit declined=0, name} as TC HandlePetRename
// sends it (empty pet GUID, number 0). The Source reason is not on the wire: generic PET_NAME_INVALID (1).
// Failures arrive in send order, but a silent success ahead of this one would shift the names:
// the name is shown only when exactly one attempt is outstanding.
// Dropped (oldest) attempts answer first; any of them outstanding makes every name uncertain.
std::string name=(pet_rename_sent.size()==1 && !pet_rename_dropped && pet_rename_sent.front().pet==current)?pet_rename_sent.front().name:std::string{};
if(pet_rename_dropped)--pet_rename_dropped;else if(!pet_rename_sent.empty())pet_rename_sent.pop_front();
Bytes out;le(out,1,4);append(out,pack_guid(Bytes(16,0)));le(out,0,4);out.push_back(uint8_t(name.size()));out.push_back(0);
out.insert(out.end(),name.begin(),name.end());emit(0x470170,std::move(out));break;
}
case 0x5b:{ // PAGE_TEXT_QUERY_RESPONSE: u32 page, text, u32 next page
Reader r(body);const auto id=uint32_t(r.le(4));const auto text=r.cstring(4095);const auto next=uint32_t(r.le(4));r.end();
auto page_info=[](Bytes& out,uint32_t page,uint32_t following,const std::string& s){
le(out,page,4);le(out,following,4);le(out,0,4);le(out,0,1);
wf_bits16(out,uint32_t(s.size())<<4);out.insert(out.end(),s.begin(),s.end());};
// Tortoise sends the whole linked list for the original query. Each response names
// the following page, which lets overlapping requests collect their own pages.
auto chain=std::find_if(page_chains.begin(),page_chains.end(),
[&](const PageChain& pending){return pending.expected==id;});
if(chain!=page_chains.end()){
// Keep the existing 32-page presentation limit while draining the complete Source stream.
if(chain->pages.size()<32)chain->pages.push_back({id,next,text});
const bool loop=std::any_of(chain->pages.begin(),chain->pages.end(),
[&](const PageChainPage& page){return page.id==next;});
if(next && !loop){
chain->expected=next;
break;
}
chain->pages.back().next=0;
Bytes out;le(out,chain->root,4);le(out,0x80,1);le(out,chain->pages.size(),4);
for(const auto& page:chain->pages)page_info(out,gateway::page_text_aliases::to_client(page.id),gateway::page_text_aliases::to_client(page.next),page.text);
page_chains.erase(chain);emit(0x4b0009,std::move(out));break;
}
// Unsolicited (or pre-chain) reply: the single Source page under its own id.
Bytes out;le(out,gateway::page_text_aliases::to_client(id),4);le(out,0x80,1);le(out,1,4);page_info(out,gateway::page_text_aliases::to_client(id),gateway::page_text_aliases::to_client(next),text);
emit(0x4b0009,std::move(out));break;
}
case 0x53:{ // PET_NAME_QUERY_RESPONSE: u32 pet number, name, u32 timestamp
Reader r(body);const auto number=uint32_t(r.le(4));const auto name=r.cstring(255);const auto stamp=r.le(4);r.end();
auto it=pet_name_pending.find(number);if(it==pet_name_pending.end())break;const auto unit=it->second;pet_name_pending.erase(it);
// QueryPetNameResponse: unit, Allow, 8-bit name, HasDeclined=0, five empty 7-bit declined names, timestamp, name.
Bytes out;wf_guid(out,unit);const uint64_t bits=((1ull<<44)|(uint64_t(name.size())<<36))<<3;
for(int i=5;i>=0;--i){out.push_back(uint8_t(bits>>(8*i)));}
le(out,stamp,8);out.insert(out.end(),name.begin(),name.end());
emit(0x4b000b,std::move(out));break;
}
case 0x138:{ // PET_CAST_FAILED: u32 spell, u8 2 (failure), u8 1.12 SpellCastResult
Reader r(body);const auto spell=r.le(4);const auto status=r.le(1);const auto result=uint8_t(r.le(1));r.end();
if(status!=2 || !spell || spell>INT32_MAX){break;}
const auto reason=spell_results::forever(result);
if(reason<0)break; // No semantic native error: never serialize the mapping sentinel.
// PetCastFailed: empty CastID (Source casts carry none), spell, native result, no failure args.
Bytes out;wf_guid(out,Guid128{});le(out,spell,4);le(out,uint32_t(reason),4);le(out,0xffffffff,4);le(out,0xffffffff,4);
emit(0x69004b,std::move(out));break;
}
case 0x1c8:{Reader r(body);r.end();emit(0x47017c,{});break;}
case 0x1c9:{Reader r(body);r.end();emit(0x47017d,{});break;}
case 0x31c:{Reader r(body);const auto by=r.le(8);r.end();if(!by || by>UINT32_MAX || !realm)break;Bytes out;wf_guid(out,forever_player_guid(by,realm));emit(0x660007,std::move(out));break;}
case 0x16e:{Reader r(body);const auto result=r.le(4);r.end();if(result>10)break;Bytes out;le(out,result,4);emit(0x47000f,std::move(out));break;}
case 0x224:{ // GOSSIP_POI: u32 flags, f32 x, f32 y, u32 icon, u32 importance, name
Reader r(body);const auto flags=r.le(4);const float x=r.f32(),y=r.f32();const auto icon=r.le(4),importance=r.le(4);const auto name=r.cstring(63);r.end();
Bytes out;le(out,0,4);le(out,flags,4);le(out,std::bit_cast<uint32_t>(x),4);le(out,std::bit_cast<uint32_t>(y),4);le(out,0,4);
le(out,icon,4);le(out,importance,4);le(out,0,4);le(out,uint32_t(name.size())<<2,1);out.insert(out.end(),name.begin(),name.end());
emit(0x470243,std::move(out));break;
}
case 0x21e: // SMSG_SET_REST_START (u32): retired in the native protocol, which reads
break; // resting from the PLAYER_FLAGS update field; consumed, nothing to present.
// ---- Source duel (wire SMSG_DUEL_* 0x4d001a-0x4d0021) ----
case 0x167:{
auto e=turtle_duel_requested(body);if(!e || (e->flagGuid>>48)!=0xf110 || !e->initiatorGuid || e->initiatorGuid>UINT32_MAX)break;
duel_flag=e->flagGuid;
const auto entry=uint32_t((e->flagGuid>>24)&0xffffff);
auto actor=entities.actors.find(e->flagGuid);
const auto arbiter=actor!=entities.actors.end()?actor->second.modern:
forever_game_object_guid(e->flagGuid,entry,realm,location?location->map:0);
// DuelRequested: ArbiterGUID, RequestedByGUID, RequestedByWowAccount (packed), ToTheDeath bit.
Bytes out;append(out,pack_guid(Bytes(arbiter.begin(),arbiter.end())));
const auto by=forever_player_guid(e->initiatorGuid,realm);append(out,pack_guid(Bytes(by.begin(),by.end())));
append(out,pack_guid(Bytes(16,0)));le(out,0,1);
if(e->initiatorGuid==selected.guid && duel_target){
// The Source accepted this client's own challenge: answer the native CanDuel with success.
Bytes ok;const auto target=forever_player_guid(duel_target,realm);append(ok,pack_guid(Bytes(target.begin(),target.end())));le(ok,0x80,1);
emit(0x4d0021,std::move(ok));
}
emit(0x4d001a,std::move(out));break;
}
case 0x168:{Reader r(body);r.end();emit(0x4d001c,{});break;}
case 0x169:{Reader r(body);r.end();emit(0x4d001d,{});break;}
case 0x2b7:{
auto e=turtle_duel_countdown(body);if(!e)break;
// Source DuelHandler sends 3000 for its three-second countdown;
// native DuelCountdown carries the same uint32 milliseconds.
Bytes out;le(out,e->milliseconds,4);emit(0x4d001e,std::move(out));break;
}
case 0x16a:{
auto e=turtle_duel_complete(body);if(!e)break;
duel_flag=0;duel_target=0;Bytes out;le(out,e->notInterrupted?0x80:0,1);emit(0x4d001f,std::move(out));break;
}
case 0x16b:{
auto e=turtle_duel_winner(body);if(!e || e->winner.size()>63 || e->loser.size()>63)break;
// DuelWinner: 6-bit beaten length, 6-bit winner length, Fled bit (flushed by the following u32),
// beaten and winner virtual realm addresses, then both names.
const uint32_t bits=(uint32_t(e->loser.size())<<10)|(uint32_t(e->winner.size())<<4)|(e->reason?8u:0u);
Bytes out;le(out,(bits>>8)&0xff,1);le(out,bits&0xff,1);le(out,virtual_realm_address,4);le(out,virtual_realm_address,4);
out.insert(out.end(),e->loser.begin(),e->loser.end());out.insert(out.end(),e->winner.begin(),e->winner.end());
emit(0x4d0020,std::move(out));break;
}
// ---- Source mail results ----
case 0x239:{
// SMSG_SEND_MAIL_RESULT -> SMSG_MAIL_COMMAND_RESULT (wire 0x4700e5): MailID u64, Command, ErrorCode,
// BagResult, AttachID u64, QtyInInventory. MailResponseType/Result values are equal in both.
Reader r(body);const auto mail=r.le(4),action=r.le(4),error=r.le(4);
uint32_t equip=0,item_count=0;
// SendMailResult always includes item/count for ITEM_TAKEN, even on
// non-equipment errors; a bare command prefix is not a confirmation.
if(error==1)equip=uint32_t(r.le(4));else if(action==2){(void)r.le(4);item_count=uint32_t(r.le(4));}
r.end();if(action>5 || error>15)break;
Bytes out;le(out,mail,8);le(out,action,4);le(out,error,4);
le(out,error==1?uint32_t(inventory_results::forever(uint8_t(equip))):0u,4);
le(out,action==2?mail:0,8);le(out,item_count,4);
emit(0x4700e5,std::move(out));break;
}
case 0x284:{
Reader r(body);
const float seconds=r.f32();
r.end();
if(!std::isfinite(seconds) || (seconds<0 && seconds!=-86400.0f))break;
const bool unread=seconds==0.0f;
Bytes out(body.begin(),body.end()); // NextMailTime
le(out,unread ? 1 : 0,4);
if(unread){
// Build 70334 clears pending mail on an empty list. Source confirms unread
// mail but supplies no sender, so serialize one entry with empty identity.
append(out,pack_guid(Bytes(16,0)));
le(out,0,4); // TimeLeft (already delivered)
le(out,0,4); // AltSenderID
le(out,0,4); // AltSenderType
le(out,0,4); // StationeryID
}
emit(0x470202,std::move(out));break;
}
case 0x285:{
// SMSG_RECEIVED_MAIL u32 -> SMSG_NOTIFY_RECEIVED_MAIL (wire 0x4700e6): float Delay.
Reader r(body);(void)r.le(4);r.end();Bytes out;le(out,0,4);emit(0x4700e6,std::move(out));break;
}
// ---- Source trade window (GW_CODEC_TRADE_EVENT) ----
case 0x120:{
auto e=turtle_trade_status(body);if(!e)break;
auto player=[&](uint64_t id){Bytes g(16,0);if(id && id<=UINT32_MAX){auto n=forever_player_guid(id,realm);std::copy(n.begin(),n.end(),g.begin());}return g;};
// Source TradeStatus 0-21 equal the native values; 13 is handled as cancelled,
// 22 (only conjured, cross-realm) has no native status and becomes FAILED.
uint32_t status=e->status==13?3:e->status==22?12:e->status;
if(status==1){
if(!e->guid || e->guid>UINT32_MAX || e->guid==selected.guid)break;
trade.close();trade.partner=e->guid;
}
if(status==2){
if(trade.open || !trade.partner)break;
if(trade.id==UINT32_MAX)trade.id=0;
++trade.id;
}
const auto input=trade_status_input(status,player(status==1?trade.partner:0),trade.id,e->isTargetError);
emit(0x470017,source(GW_CODEC_TRADE_EVENT,input));
if(status==2)trade.open=true;
// Too far during acceptance can be retried with the same source trade.
else if(status!=1 && status!=4 && status!=7 && status!=9 && !(status==10 && trade.open))trade.close();
break;
}
case 0x121:{
auto e=turtle_trade_status_extended(body);if(!e || !trade.open)break;
auto player=[&](uint64_t id){Bytes g(16,0);if(id && id<=UINT32_MAX){auto n=forever_player_guid(id,realm);std::copy(n.begin(),n.end(),g.begin());}return g;};
if(e->traderState>1)break;
auto& offer=trade.offers[e->traderState];
const bool changed=packet.body!=offer.source;
if(changed && (trade.last_revision==UINT32_MAX || offer.client_index==UINT32_MAX))
throw Error("trade offer revision exhausted");
const auto revision=changed?trade.last_revision+1:offer.revision;
const auto client_index=changed?offer.client_index+1:offer.client_index;
Bytes input;le(input,1,1);le(input,e->traderState,1);le(input,trade.id,4);le(input,client_index,4);le(input,revision,4);
le(input,e->gold,8);le(input,e->spell,4);
uint8_t n=uint8_t(std::count_if(e->items.begin(),e->items.end(),[](const auto& i){return i.present;}));le(input,n,1);
for(const auto& i:e->items){
if(!i.present)continue;
le(input,i.slot,1);le(input,i.entry,4);le(input,i.count,4);append(input,player(i.giftCreator));
le(input,i.wrapped?0:1,1);
if(!i.wrapped){le(input,i.permEnchant,4);append(input,player(i.creator));le(input,i.charges,4);le(input,i.lockId?1:0,1);
le(input,i.maxDurability,4);le(input,i.durability,4);}
}
emit(0x470016,source(GW_CODEC_TRADE_EVENT,input));
if(changed){
trade.last_revision=revision;
offer={revision,client_index,packet.body};
}
break;
}
case 0x92: {
RosterRealm context;
context.realm_id=realm;
context.virtual_address=address;
const auto* roster=guild_id && guild_management_roster ? &*guild_management_roster : nullptr;
const auto* info=guild_rank_info && guild_rank_info->id==guild_id ? &*guild_rank_info : nullptr;
auto event=guild_notification(body,context,roster,info);
if(event){
bool already_shown = false;
// A valid GE_JOINED has the affected Source character GUID at the end.
if (body.front() == 3 && Reader(std::span(body).last(8)).le(8) == selected.guid) {
already_shown = own_guild_join == OwnGuildJoin::Presented ||
own_guild_join == OwnGuildJoin::SourceEventBeforeMembership;
own_guild_join = guild_id ? OwnGuildJoin::Presented : OwnGuildJoin::SourceEventBeforeMembership;
}
if (!already_shown) emit(event->opcode,std::move(event->body));
// A Source-confirmed membership/rank/online change invalidates the
// snapshot. Coalesce events until the requested roster returns.
const auto kind=body.front();
if(kind==0 || kind==1 || kind==3 || kind==4 || kind==5 || kind==12 || kind==13)
refresh_guild_roster();
}
break;
}
case 0x1bc: case 0x1bf: case 0x1c1: case 0x1c5: case 0x1c7: case 0x2c1: {
auto event=petition_notification(packet.opcode,body,realm,
packet.opcode==0x1bc ? bindings() : std::map<uint64_t,Guid128>{});
if(event)emit(event->opcode,std::move(event->body));
break;
}
case 0x21b: {
auto event=ticket_queue_notification(body);
if(event)emit(event->opcode,std::move(event->body));
break;
}
// ---- Source group/raid notifications (GW_CODEC_GROUP_EVENT) ----
case 0x79: case 0x74:{
// SMSG_GROUP_SET_LEADER / SMSG_GROUP_DECLINE: one name.
Reader r(body);auto name=r.cstring(48);r.end();if(name.empty())break;
Bytes input;le(input,packet.opcode==0x79?0:1,1);cstring(input,name);
emit(packet.opcode==0x79?0x4700d7:0x47023c,source(GW_CODEC_GROUP_EVENT,input));break;
}
case 0x7f:{
// SMSG_PARTY_COMMAND_RESULT u32 operation, name, u32 result. The native
// PartyResult inserts TARGET_NOT_IN_INSTANCE (3); source 10 is server-internal.
Reader r(body);auto operation=r.le(4);auto name=r.cstring(48);auto result=r.le(4);r.end();
static constexpr uint8_t results[]={0,1,2,4,5,6,7,8,9};
if((operation!=0 && operation!=2) || result>=std::size(results))break;
Bytes input;le(input,2,1);le(input,operation,1);le(input,results[result],1);cstring(input,name);
emit(0x470241,source(GW_CODEC_GROUP_EVENT,input));break;
}
case 0x1d5:{
// MSG_MINIMAP_PING from a group member: u64 guid, float x, float y.
Reader r(body);auto guid=r.le(8);auto x=r.take(4),y=r.take(4);r.end();
if(!guid || guid>UINT32_MAX || guid==selected.guid)break;
auto sender=forever_player_guid(guid,realm);
Bytes input;le(input,3,1);input.insert(input.end(),sender.begin(),sender.end());append(input,x);append(input,y);
emit(0x47017b,source(GW_CODEC_GROUP_EVENT,input));break;
}
case 0x321:{
// MSG_RAID_TARGET_UPDATE: u8 0 + icon + guid, or u8 1 + (icon, guid)*.
auto known=bindings();
auto native=[&](uint64_t id)->std::optional<Guid128>{
if(!id)return Guid128{};
if(auto it=known.find(id);it!=known.end())return it->second;
if(id<=UINT32_MAX){auto g=forever_player_guid(id,realm);Guid128 out{};std::copy(g.begin(),g.end(),out.begin());return out;}
return std::nullopt; // Unbound creature: no native identity to mark.
};
Reader r(body);auto full=r.le(1);Bytes input;
if(full==0){
auto icon=r.le(1);auto target=r.le(8);r.end();if(icon>7)break;
auto g=native(target);if(!g)break;
le(input,4,1);le(input,target?icon:0xff,1);input.insert(input.end(),g->begin(),g->end());input.resize(input.size()+16,0);
emit(0x4700d9,source(GW_CODEC_GROUP_EVENT,input));break;
}
if(full!=1)break;
std::vector<std::pair<uint8_t,Guid128>> icons;
while(r.left()){auto icon=r.le(1);auto target=r.le(8);if(icon>7)throw Error("raid target icon bound");
if(auto g=native(target);g && target)icons.emplace_back(uint8_t(icon),*g);}
le(input,5,1);le(input,icons.size(),1);
for(auto& [icon,g]:icons){le(input,icon,1);input.insert(input.end(),g.begin(),g.end());}
emit(0x4700d8,source(GW_CODEC_GROUP_EVENT,input));break;
}
case 0x322:{
// MSG_RAID_READY_CHECK: empty = started (to all); guid + u8 = answer (to leader).
if(!party.counter || !loot.group || loot.group->explicit_solo)break;
auto player=[&](uint64_t id){auto g=forever_player_guid(id,realm);return Bytes(g.begin(),g.end());};
auto& check=party.ready_check;
if(body.empty()){
check=NativeReadyCheck{true,loot.group->leader,{}};
Bytes input;le(input,6,1);le(input,party.counter,8);append(input,player(loot.group->leader));le(input,30000,4);
emit(0x47009a,source(GW_CODEC_GROUP_EVENT,input));break;
}
Reader r(body);auto guid=r.le(8);auto state=r.le(1);r.end();
if(!check.active || !guid || guid>UINT32_MAX || state>1)break;
Bytes input;le(input,7,1);le(input,party.counter,8);append(input,player(guid));le(input,state,1);
emit(0x47009b,source(GW_CODEC_GROUP_EVENT,input));
check.answered.insert(guid);
size_t others=std::count_if(loot.group->members.begin(),loot.group->members.end(),[](const auto& m){return (m.status&1)!=0;});
if(check.answered.size()>=others){
Bytes done;le(done,8,1);le(done,party.counter,8);
emit(0x47009c,source(GW_CODEC_GROUP_EVENT,done));check={};
}
break;
}
case 0x7e: case 0x2f2:{
// SMSG_PARTY_MEMBER_STATS (delta) / _FULL: merge, then publish the full native state.
if(!loot.group || loot.group->explicit_solo)break;
auto id=apply_party_member_stats(party.members,body);
if(std::none_of(loot.group->members.begin(),loot.group->members.end(),[&](const auto& m){return m.guid==id;}))break;
const auto& m=party.members.at(id);
auto member=forever_player_guid(id,realm);Guid128 native{};std::copy(member.begin(),member.end(),native.begin());
auto known=bindings();const Guid128* pet=nullptr;
if(m.pet)if(auto it=known.find(m.pet);it!=known.end())pet=&it->second;
emit(0x470204,source(GW_CODEC_GROUP_EVENT,party_member_state_input(m,native,pet)));break;
}
case 0x286:{
// SMSG_RAID_GROUP_ONLY u32 delay, u32 reason (source 1 = native RAID_GROUP_ERR_ONLY 2).
Reader r(body);auto delay=r.le(4),reason=r.le(4);r.end();if(delay>INT32_MAX)break;
Bytes input;le(input,10,1);le(input,delay,4);le(input,reason==1?2:reason,4);
emit(0x47025a,source(GW_CODEC_GROUP_EVENT,input));break;
}
case 0x83:{
auto invite=turtle_guild_invitation(body);
if(guild_id)break;
try {
auto packet=forever_guild_invitation(invite,address);
emit(forever_opcodes::SMSG_GUILD_INVITE,packet);pending_guild_invitation=true;
} catch(const GuildInvitationHold&) {
// An unpresented offer cannot authorize a later native response.
// Keep the genuine Source offer untouched; never synthesize decline.
pending_guild_invitation=false;
}
break;
}
case 0x93:{
auto result=forever_guild_command_result(body);
uint32_t status=0;if(body.size()>=4)for(unsigned i=0;i<4;++i)status|=uint32_t(body[body.size()-4+i])<<(8*i);
if(guild_control_inflight && status){
if(guild_control_notices.size()<31)guild_control_notices.push_back("GWTURTLE1 GUILD REJECTED "+std::to_string(guild_control_inflight->serial)+" "+std::to_string(status));
guild_control_inflight.reset();
}
if(status)guild_rank_assignment.reset();
guild_management_pending=guild_control_inflight.has_value() || guild_rank_assignment.has_value();
if(!result.empty())emit(forever_opcodes::SMSG_GUILD_COMMAND_RESULT,result);
break;
}
case 0x88:{
if(!guild_id)break;
auto details=turtle_guild_details(body);
auto& state=guild_roster_context;
if(!state.name.empty() && state.name!=details.name)break;
state.details=std::move(details);
clubs.creation=body;
publish_guild_details();
break;
}
case 0x55:{
auto guild=turtle_guild_info(body);
bool known=player_guild(selected.guid)==guild.id;
for(const auto& [guid,peer]:entities.peer_players){(void)peer;if(player_guild(guid)==guild.id){known=true;break;}}
if(!guild.id || !known)break;
RosterRealm context;context.realm_id=realm;context.virtual_address=address;
emit(forever_opcodes::SMSG_QUERY_GUILD_INFO_RESPONSE,forever_guild_info(guild,context));
if(guild.id==guild_id){
auto& state=guild_roster_context;
state.name=guild.name;
if(state.details && !state.matched()){
state.details.reset();
state.requested=false;
if(state.awaiting_details && requests.size()<4096){
requests.push_back({0x87,{}});
state.requested=true;
}
}
publish_guild_details();
}
if(guild.id==guild_id){
guild_rank_info=std::move(guild);guild_control_refresh();
if(guild_roster_rights){
try{emit(0x530010,forever_guild_ranks(*guild_rank_info,*guild_roster_rights));}
catch(const Error&){/* Wait for matching Source rank counts. */}
}
}
break;
}
case 0x1a1:{
// Player::SendSellError only emits failure1..6; successful sales use
// genuine inventory/money updates, not a fabricated success packet.
Reader r(body);auto vendor=r.le(8),item=r.le(8),reason=r.le(1);r.end();
if(reason<1 || reason>6)throw Error("unreviewed Turtle sell error");
auto actors=bindings();const auto& owned=inventory.owned_bindings();
if((vendor && !actors.contains(vendor)) || (item && !owned.contains(item)))break;
emit(merchant_opcodes::SellResponse,forever_sell_error(vendor?actors.at(vendor):Guid128{},item?owned.at(item):Guid128{},uint8_t(reason)));break;
}
case 0x103:case 0x105:{
if(self_created)for(auto& event:emote_event(packet))emit(event.opcode,event.body);
break;
}
case 0x143:case 0x144:{
if(!self_created)break;
auto event=turtle_attack_event(uint16_t(packet.opcode),body);auto known=bindings();
if(!known.contains(event.attacker))break;
const bool owned=event.attacker==selected.guid;
auto& target=entities.self_melee_target;
if(owned && event.stopped && target && event.victim){
if(event.victim!=target->source)break; // Late stop for a replaced attack.
known[event.victim]=target->native;
}
if(event.victim && !known.contains(event.victim)){
if(owned && !event.stopped)target.reset();
break;
}
trace_combat(event.stopped?"attack_stop":"attack_start",packet.opcode,event.attacker,event.victim,event.dead);
emit(event.stopped?0x4d0018:0x4d0017,forever_attack_event(event,known));
if(owned){
if(event.stopped)target.reset();
else target=NativeEntityTranslation::MeleeTarget{event.victim,known.at(event.victim)};
}
break;
}
case 0x145:case 0x146:case 0x148:case 0x149:
if(self_created)emit(0x4d0026,forever_attack_error(uint16_t(packet.opcode),body));
break;
case 0x2af:{ // SMSG_PET_BROKEN (empty): ERR_PET_BROKEN "Your pet has run away"
if(!body.empty())break;
auto e=auction_battleground::game_error(559);emit(e.opcode,std::move(e.body));break;
}
case 0x16f:{ // SMSG_DISMOUNTRESULT u32: 0 no pet, 1 not mounted, 2 not your pet (ERR_DISMOUNT_* 266..268), 3 ok
if(body.size()!=4)break;
Reader r(body);const auto result=r.le(4);
if(result<3){auto e=auction_battleground::game_error(266+uint32_t(result));emit(e.opcode,std::move(e.body));}
break;
}
// Server messages with no 70334 counterpart, consumed on purpose (audit ec1b15b3):
// 0x147 ATTACKSWING_NOTSTANDING (the native client stands up by itself; no native error exists),
// 0x2c5 ITEM_NAME_QUERY_RESPONSE (answers a 1.12 request the native client never sends),
// 0x206/0x208/0x212 GMTICKET_* (Blizzard support UI removed; a GM answer also arrives as system chat),
// 0x214 GAMEOBJECT_SPAWN_ANIM (native objects animate from their create), 0x299 MEETINGSTONE_MEMBER_ADDED
// (Octo meeting stones only open the dungeon finder; no meeting-stone grouping exists).
case 0x147:case 0x2c5:case 0x206:case 0x208:case 0x212:case 0x214:case 0x299:break;
case 0x24e:{
if(!self_created)break;
auto event=turtle_periodic_aura_log(body);if(!event)break;
auto known=bindings();if(!known.contains(event->target) || !known.contains(event->caster))break;
emit(forever_opcodes::SMSG_SPELL_PERIODIC_AURA_LOG,forever_periodic_aura_log(*event,known));break;
}
case 0x24f:{ // #91 SMSG_SPELLDAMAGESHIELD {u64 shield owner, u64 attacker hit, u32 damage, u32 school index}
if(!self_created)break;
Reader r(body);auto owner=r.le(8),hit=r.le(8);auto damage=uint32_t(r.le(4)),school=uint32_t(r.le(4));r.end();
auto known=bindings();auto a=known.find(owner),d=known.find(hit);
auto unit=auras.units.find(owner);if(a==known.end() || d==known.end() || unit==auras.units.end() || school>6 || damage>INT_MAX)break;
// The shield is the owner's current aura-15 spell of that school (Thorns, Fire/Frost/Lightning Shield...).
uint32_t spell=0;
for(auto s:unit->second.spells){
auto it=std::lower_bound(spell_log_sources::DamageShields.begin(),spell_log_sources::DamageShields.end(),std::pair<uint32_t,uint8_t>{s,0});
if(s && it!=spell_log_sources::DamageShields.end() && it->first==s && it->second==school){spell=s;break;}
}
if(!spell)break; // No shield aura of that school known: never invent a spell id.
auto out=pack_guid(a->second);append(out,pack_guid(d->second));
le(out,spell,4);le(out,damage,4);le(out,damage,4);le(out,0,4);le(out,1u<<school,4);le(out,0,4);le(out,0,1);
gw_inv_log("GW_SPELLLOG damage_shield spell=%u school=%u damage=%u\n",spell,school,damage);
emit(0x69001f,out);break; // SMSG_SPELL_DAMAGE_SHIELD (core 0x67001F)
}
case 0x27b:case 0x262:{ // #91 SMSG_SPELLDISPELLOG {pguid victim, pguid caster, u32 n, n*u32} / DISPEL_FAILED {u64 caster, u64 victim, u32...}
if(!self_created)break;
Reader r(body);uint64_t victim=0,caster=0;std::vector<uint32_t> ids;
auto packed=[&](){auto bytes=unpack_guid(r,8);Reader raw(bytes);return raw.le(8);};
// A malformed observational log is dropped like the other combat logs, never thrown out of translate.
try{
if(packet.opcode==0x27b){victim=packed();caster=packed();auto n=r.le(4);if(n>64)break;for(uint64_t i=0;i<n;++i)ids.push_back(uint32_t(r.le(4)));}
else{caster=r.le(8);victim=r.le(8);while(r.left()>=4 && ids.size()<64)ids.push_back(uint32_t(r.le(4)));}
r.end();
}catch(const Error&){break;}
auto known=bindings();auto c=known.find(caster),v=known.find(victim);auto by=recent_dispel(caster);
if(c==known.end() || v==known.end() || !by || ids.empty())break;
Bytes out;
if(packet.opcode==0x27b){
le(out,0,1); // IsSteal/IsBreak bits (Turtle dispel effect 38 is neither)
append(out,pack_guid(v->second));append(out,pack_guid(c->second));le(out,*by,4);le(out,ids.size(),4);
for(auto id:ids){le(out,id,4);le(out,0,1);} // SpellDispellData: Harmful/Rolled/Needed bits unset (as TC)
gw_inv_log("GW_SPELLLOG dispel_log by=%u removed=%zu\n",*by,ids.size());
emit(0x690007,out); // SMSG_SPELL_DISPELL_LOG (core 0x670007)
}else{
append(out,pack_guid(c->second));append(out,pack_guid(v->second));le(out,*by,4);le(out,ids.size(),4);
for(auto id:ids)le(out,id,4);
gw_inv_log("GW_SPELLLOG dispel_failed by=%u failed=%zu\n",*by,ids.size());
emit(0x69001e,out); // SMSG_DISPEL_FAILED (core 0x67001E)
}
break;
}
case 0x250:{
if(!self_created)break;
auto event=turtle_spell_damage_log(body);if(!event)break;
boss(event->periodic?"SPELL_PERIODIC_DAMAGE":"SPELL_DAMAGE",event->spell,event->caster,event->target,event->damage);
if(event->caster==selected.guid)entities.note_spell_damage(event->spell,event->target,event->damage,event->blocked);
auto known=bindings();if(!known.contains(event->target) || !known.contains(event->caster))break;
trace_combat("spell_damage",packet.opcode,event->caster,event->target,event->spell,event->flags,event->damage,event->blocked);
emit(forever_opcodes::SMSG_SPELL_NON_MELEE_DAMAGE_LOG,forever_spell_damage_log(*event,known));break;
}
case 0x2f1:{
// Tortoise SendPetSkillWipeConfirm {u64 current pet, u32 cost}, sent after the pet-trainer gossip
// option closes the menu -> SMSG_RESPEC_WIPE_CONFIRM {i8 SPEC_RESET_PET_TALENTS 3, u32 Cost,
// Guid RespecMaster = that trainer (as TC PetSpecializationMaster), i32 0}. Only the self
// hunter's current Source pet (pet bar unit, 0xF140) with a live trainer gossip qualifies.
Reader r(body);auto pet=r.le(8);auto cost=uint32_t(r.le(4));r.end();
pet_unlearn_offer.reset();
if(!self_created || selected.cls!=3 || (pet>>48)!=0xf140 || !pet_bar || pet_bar->state.unit!=pet || !last_gossip_npc)break;
auto actor=entities.actors.find(pet);auto trainer=entities.actors.find(last_gossip_npc->guid);
auto known=bindings();auto master=known.find(last_gossip_npc->guid);
if(actor==entities.actors.end() || !actor->second.sent || trainer==entities.actors.end() || !trainer->second.sent ||
trainer->second.kind!=3 || trainer->second.generation!=last_gossip_npc->generation || master==known.end())break;
pet_unlearn_offer=PetUnlearnOffer{pet,actor->second.generation,last_gossip_npc->guid,last_gossip_npc->generation};
last_gossip_npc.reset(); // one offer per genuine gossip menu; never reused as later authority
if(!pet_unlearn_offer_live()){pet_unlearn_offer.reset();break;}
Bytes out;le(out,3,1);le(out,cost,4);append(out,pack_guid(master->second));le(out,0,4);
emit(0x4700bd,std::move(out));break;
}
case 0x2e9:{
// Tortoise HandleBattleGroundPlayerPositionsOpcode: u32 n x {u64, f x, f y} teammates (native has
// no field: party/raid frames show them), then u8 carrier [u64, f x, f y]: the player holding the
// flag of the viewer's opposite faction (viewer GetTeam(), i.e. own Source race). Native
// SMSG_BATTLEGROUND_PLAYER_POSITIONS lists flag carriers only {u32 n, n x {Guid, f x, f y,
// i8 IconID, i8 ArenaSlot}}; TC icon 1 Horde flag, 2 Alliance flag, ArenaSlot NONE = 1.
// Only the one outstanding poll is accepted; late or unsolicited replies are ignored.
if(!bg_positions_pending)break;
bg_positions_pending=false;
const auto team=source_team_for_race(selected.race);
if(!self_created || !location || location->map!=489 || !team)break;
Reader r(body);auto n=r.le(4);if(n>80)break;
for(uint64_t i=0;i<n;++i){r.le(8);r.le(4);r.le(4);}
auto has=r.le(1);uint64_t carrier=0;uint32_t x=0,y=0;
if(has==1){carrier=r.le(8);x=uint32_t(r.le(4));y=uint32_t(r.le(4));}else if(has!=0)break;
r.end();
if(has && (!carrier || carrier>UINT32_MAX))break;
Bytes out;le(out,has?1:0,4);
if(has){append(out,pack_guid(forever_player_guid(carrier,realm)));le(out,x,4);le(out,y,4);
le(out,*team==SourceTeam::Alliance?1:2,1);le(out,1,1);} // Alliance viewer: Horde flag
bg_positions_shown=has==1;
emit(0x4d0006,std::move(out));break;
}
case 0x172:{
// Tortoise HandleMountSpecialAnimOpcode {u64 player} -> SMSG_SPECIAL_MOUNT_ANIM {Guid, u32 0 kits,
// i32 SequenceVariation 0}: the Source carries no kit list or variation, so TC's empty defaults apply.
Reader r(body);auto guid=r.le(8);r.end();
// This predicate validates only the current named peer presentation;
// it does not grant inspect permission or generate an inspect request.
if(!live_inspect_peer(guid))break;
auto out=pack_guid(entities.actors.at(guid).modern);le(out,0,4);le(out,0,4);emit(0x47014c,std::move(out));break;
}
case 0x2b4:{
// Tortoise SendFeignDeathResisted: empty; native SMSG_FEIGN_DEATH_RESISTED has no fields either.
if(!self_created || !body.empty())break;
emit(0x4701ef,{});break;
}
case 0x29c:{ // Turtle's direct, empty auto-repeat cancellation names the recipient.
if(body.empty())wand_repeating=false;
if(self_created && body.empty())
emit(0x470189,pack_guid(forever_player_guid(selected.guid,realm)));
break;
}
case 0x1e2:{ // Spell::Delayed notifies the casting player of actual pushback.
if(!self_created || body.size()!=12)break;
Reader r(body);
if(r.le(8)!=selected.guid)break;
Bytes delayed=pack_guid(forever_player_guid(selected.guid,realm));
le(delayed,r.le(4),4);
emit(0x690032,std::move(delayed));
break;
}
case 0x1ba: { // HandleBuyBankSlotOpcode sends a result only on failure.
if (!self_created || !location || logout_complete || far_transfer || pending_teleport || body.size() != 4) break;
Reader r(body);
const auto result = r.le(4);
// SharedDefines::GameError for too many slots, insufficient funds, and no banker.
constexpr uint32_t errors[] = {319, 320, 321};
if (result >= std::size(errors)) break;
Bytes error;
le(error, errors[result], 4);
le(error, 0, 1); // DisplayGameError has neither optional argument.
emit(forever_opcodes::SMSG_DISPLAY_GAME_ERROR, std::move(error));
break;
}
case 0x28c: { // HonorMgr::SendPVPCredit has one award and an optional victim.
if (!self_created || !location || logout_complete || far_transfer || pending_teleport || body.size() != 16) break;
Reader r(body);
const auto honor = r.le(4);
const auto victim = r.le(8);
const auto rank = std::bit_cast<int32_t>(uint32_t(r.le(4)));
if (rank < INT8_MIN || rank > INT8_MAX || (!victim && rank)) break;
Guid128 target{};
if (victim && victim <= UINT32_MAX) {
target = forever_player_guid(victim, realm);
} else if (victim) {
const auto actor = entities.actors.find(victim);
if (actor == entities.actors.end() || !actor->second.sent || !actor->second.eligible ||
actor->second.kind != 3 || actor->second.presentation_realm != realm ||
actor->second.presentation_map != location->map || actor->second.modern == Guid128{}) break;
target = actor->second.modern;
}
Bytes credit;
// The native reward writer sets both amounts to the final awarded honor.
le(credit, honor, 4);
le(credit, honor, 4);
append(credit, pack_guid(target));
le(credit, uint8_t(rank), 1);
emit(forever_opcodes::SMSG_PVP_CREDIT, std::move(credit));
break;
}
case 0x1f5:{
if(!self_created || body.size()!=16)break;
const auto kill=turtle_party_kill_log(body);
if(!kill || kill->killer>UINT32_MAX)break;
Bytes result=pack_guid(forever_player_guid(kill->killer,realm));
if(kill->victim<=UINT32_MAX){
append(result,pack_guid(forever_player_guid(kill->victim,realm)));
}else{
const auto actor=entities.actors.find(kill->victim);
if(actor==entities.actors.end() || !actor->second.sent ||
(actor->second.kind!=3 && actor->second.kind!=4))break;
append(result,pack_guid(actor->second.modern));
}
emit(0x470205,std::move(result));
break;
}
case 0x151:case 0x1d0:case 0x24b:case 0x24c:case 0x260:{
if(!self_created || !location || logout_complete || far_transfer || pending_teleport)break;
if(packet.opcode==0x24b && boss_feed_on){
// The feed never judges a body: malformed logs keep their existing rejection below.
std::optional<TurtleSpellMissLog> miss;try{miss=turtle_spell_miss_log(body);}catch(const Error&){}
if(miss)for(const auto& target:miss->targets)boss("SPELL_MISSED",miss->spell,miss->caster,target.target);
}
source_combat_events::Bindings known{{selected.guid,forever_player_guid(selected.guid,realm)}};
for(const auto& [guid,actor]:entities.actors)
if(actor.sent && actor.eligible && actor.generation && actor.presentation_realm==realm &&
actor.presentation_map==location->map)known.emplace(guid,actor.modern);
if(packet.opcode==0x24c){
// Keep the event's position and actor identities. Other world output must
// finish before we know how many optional logs this bundle can carry.
pending_execute.emplace(output.size(),std::move(known));
}else if(auto event=source_combat_events::translate(packet.opcode,body,known))
emit(event->opcode,std::move(event->body));
break;
}
case 0x150:{
if(!self_created)break;
auto event=turtle_spell_heal_log(body);if(!event || event->amount>INT_MAX)break;
auto known=bindings();if(!known.contains(event->target) || !known.contains(event->caster))break;
emit(NativeSpellHealLogOpcode,forever_spell_heal_log(*event,known));break;
}
case 0x1fc:{
if(!self_created)break;
auto event=turtle_environmental_damage_log(body);
if(!event || event->damage>INT_MAX || event->absorbed>INT_MAX)break;
auto known=bindings();if(!known.contains(event->victim))break;
emit(NativeEnvironmentalDamageLogOpcode,forever_environmental_damage_log(*event,known));break;
}
case 0x263:{
if(!self_created)break;
auto event=turtle_spell_immune_log(body);if(!event)break;
auto known=bindings();if(!known.contains(event->target) || !known.contains(event->caster))break;
emit(NativeSpellImmuneLogOpcode,forever_spell_immune_log(*event,known));break;
}
case 0x14a:{
if(!self_created)break;
auto damage=turtle_melee_damage(body);auto known=bindings();
if(damage.attacker==selected.guid && damage.state==3)boss("SWING_MISSED",0,damage.attacker,damage.victim,0,"PARRY");
if(!known.contains(damage.attacker) || !known.contains(damage.victim))break;
trace_combat("melee",packet.opcode,damage.attacker,damage.victim,damage.state,damage.legacy_flags,damage.damage,damage.blocked);
const auto basic=forever_melee_damage(damage,known);
emit(0x4d002c,basic);
if(damage.attacker==selected.guid || damage.victim==selected.guid){
// Pinned Unit::SendAttackStateUpdate follows player-involved
// swings with LE32(0) + the same attack round. Its source uses
// FULL victim log data, which Turtle does not provide. Preserve
// the genuine BASIC body without inventing that data; actual
// engine acceptance of BASIC landed logs is a controlled test.
Bytes landed;le(landed,0,4);append(landed,basic);
emit(0x4d0027,std::move(landed));
}
break;
}
case 0xb0: case 0x135: case 0x13c: case 0x1f3: case 0x1f7: {
if (!self_created || !location || !selected.guid || !realm || logout_complete || far_transfer) break;
Reader r(body); Bytes input; le(input, packet.opcode, 2);
if (packet.opcode == 0x135) {
const uint32_t spell = r.le(4); const auto owner = r.le(8); r.end();
if (!spell || spell > INT32_MAX || !owner) throw Error("invalid source cooldown event");
const auto high = owner >> 48;
if (owner > UINT32_MAX && high != 0xf130 && high != 0xf140) throw Error("non-unit cooldown owner");
// Tortoise addresses this single packet to GetAffectingPlayer. The native
// SpellHistory sends this same recipient the bit (_owner != playerOwner).
le(input, spell, 4); input.push_back(uint8_t(owner != selected.guid));
emit(0x470166, source(GW_CODEC_SPELL_FEEDBACK, input)); break;
}
const auto id = r.le(8); const uint32_t value = r.le(4); r.end();
if (packet.opcode == 0xb0) {
if (!value) throw Error("invalid source item cooldown spell");
const auto& known = inventory.owned_bindings(); auto it = known.find(id);
if (it == known.end()) break;
append(input, it->second); le(input, value, 4);
emit(0x470273, source(GW_CODEC_SPELL_FEEDBACK, input));
const auto now = uint64_t(std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now().time_since_epoch()).count());
auto& until = item_cooldown_until[value];
until = std::max(until, now + 30000);
break;
}
Guid128 unit{};
if (id == selected.guid && packet.opcode != 0x13c) unit = forever_player_guid(id, realm);
else {
const auto actor = entities.actors.find(id);
if (actor == entities.actors.end() || !actor->second.sent || !actor->second.eligible ||
actor->second.presentation_map != location->map || actor->second.presentation_realm != realm) break;
const auto kind = actor->second.kind;
if (kind != 3 && (kind != 4 || packet.opcode == 0x13c)) break;
unit = actor->second.modern;
}
if (packet.opcode == 0x13c) {
if (value > 4) throw Error("invalid source AI reaction");
append(input, unit); le(input, value, 4);
emit(0x470162, source(GW_CODEC_SPELL_FEEDBACK, input)); break;
}
// Direct visuals name a kit, independently of the spell-to-visual link.
// Only kit 362 has corroborating native impact playback (Trainer::TeachSpell).
if (packet.opcode == 0x1f7 && value != 362) break;
const uint32_t kit = spell_visual_kit_profile::resolve(value);
if (!kit) break;
append(input, unit); le(input, kit, 4);
emit(0x69003c, source(GW_CODEC_SPELL_FEEDBACK, input)); break;
}
case 0x134:{
Reader r(body);auto owner=r.le(8);if(r.left()%8 || r.left()/8>4096)throw Error("Turtle forced cooldown list bound");
if(owner!=selected.guid || !self_created)break;
auto count=r.left()/8;if(!count)break;Bytes input{4};append(input,forever_player_guid(owner,realm));le(input,count,2);
auto now=uint64_t(std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now().time_since_epoch()).count());
while(r.left()){auto spell=uint32_t(r.le(4)),duration=uint32_t(r.le(4));le(input,spell,4);le(input,duration,4);if(duration)item_cooldown_until[spell]=now+duration;else item_cooldown_until.erase(spell);}
emit(0x690005,source(GW_CODEC_SPELL_CAST,input));++inventory.cooldown_packets;break;
}
case 0x1de:{
Reader r(body);auto spell=uint32_t(r.le(4));auto owner=r.le(8);r.end();if(owner!=selected.guid || !self_created)break;
item_cooldown_until.erase(spell);Bytes input{6};le(input,spell,4);emit(0x470167,source(GW_CODEC_SPELL_CAST,input));break;
}
case 0x1e1:{
Reader r(body);auto owner=r.le(8);r.end();if(owner!=selected.guid || !self_created)break;
auto ids=spells;for(auto [spell,until]:item_cooldown_until){(void)until;ids.insert(spell);}
for(const auto& [entry,profile]:inventory.templates){(void)entry;if(profile.found)for(const auto& spell:profile.spells)if(spell.spell)ids.insert(spell.spell);}
item_cooldown_until.clear();if(ids.empty())break;
Bytes input{5};le(input,ids.size(),2);for(auto spell:ids)le(input,spell,4);emit(0x690015,source(GW_CODEC_SPELL_CAST,input));break;
}
case 0x266:case 0x267:{
Reader r(body);auto bit=r.le(1),operation=r.le(1);auto value=int32_t(r.le(4));r.end();
if(bit>=64)throw Error("Turtle spell modifier bit bound");
if(operation<34){
const bool percent=packet.opcode==0x267;
spell_modifier_aggregates[{percent,uint8_t(operation),uint8_t(bit)}]=value;
if(self_created)for(auto& translated:project_received_modifiers(selected.cls,
spell_modifier_aggregates,percent,uint8_t(operation),uint8_t(bit)))
emit(translated.opcode,std::move(translated.body));
}
if(operation==11){
(packet.opcode==0x266?cooldown_flat:cooldown_percent)[bit]=value;
if(packet.opcode==0x266){
cooldown_flat_received|=uint64_t(1)<<bit;
}
}
break;
}
case 0x130:{
// Validate the complete source result even without an active cast.
// Malformed status/argument framing must not retire deferred state.
auto failure=turtle_cast_failure(body);
if(stance_cast){
if(failure&&failure->spell==stance_cast->stance){
const auto ability=forever_spell_request(stance_cast->original);stance_cast.reset();
if(pending_cast&&pending_cast->spell.cast==ability.cast){failure->spell=ability.spell;fail_cast(*failure,false);}
break;
}
}
if(body.size()>=5 && body[4]!=0 && (uint32_t(body[0])|(uint32_t(body[1])<<8)|(uint32_t(body[2])<<16)|(uint32_t(body[3])<<24))==5019u)wand_repeating=false;
if(body.size()>=5){uint32_t actual_spell=uint32_t(body[0])|(uint32_t(body[1])<<8)|(uint32_t(body[2])<<16)|(uint32_t(body[3])<<24);
entities.note_spell_result(actual_spell,body[4],body.size()>=6?body[5]:0);}
// A cast held for the wand GCD survives the wand's own result (its "Interrupted" is that hold's trigger).
if(!standing_cast || !standing_cast->release_at || !failure || failure->spell==forever_spell_request(standing_cast->original).spell)
standing_cast.reset();
if(!pending_cast && !superseded_cast && !melee_cast)break;
if(failure)select_cast(failure->spell);
if(failure && pending_cast && failure->spell==pending_cast->spell.spell)fail_cast(*failure,false);
break;
}
case 0x2a6:{
Reader r(body);auto unit=r.le(8);auto spell=uint32_t(r.le(4));r.end();
// This is a broadcast for one caster/spell, not a global cancellation.
// Validate framing before committing any deferred-cast retirement.
if(standing_cast && unit==standing_cast->owner &&
spell==forever_spell_request(standing_cast->original).spell)
standing_cast.reset();
// Tortoise Spell::SendInterrupted broadcasts only FAILED_OTHER. For an
// observed cast still current (same owner/realm/map/actor generation)
// end the native cast bar with the START's own cast identity.
if(unit!=selected.guid && location){
const auto observed=observed_casts.find({unit,spell});const auto actor=entities.actors.find(unit);
const auto known=bindings();const auto caster=known.find(unit);
if(observed!=observed_casts.end() && actor!=entities.actors.end() && caster!=known.end() &&
observed->second.owner==selected.guid && observed->second.realm==realm && observed->second.map==location->map &&
observed->second.generation==actor->second.generation && std::chrono::steady_clock::now()<observed->second.expires){
Bytes input{3};append(input,observed->second.identity);append(input,caster->second);le(input,spell,4);
le(input,cast_visual_profile::link(spell),4);le(input,0,4);
le(input,uint32_t(spell_results::forever(35)),4);le(input,uint32_t(-1),4);le(input,uint32_t(-1),4); // SPELL_FAILED_INTERRUPTED
emit(0x690046,source(GW_CODEC_SPELL_CAST,input));
}
}
observed_casts.erase({unit,spell});
if(stance_cast&&unit==selected.guid&&spell==stance_cast->stance){
stance_cast->failed=true;
if(pending_cast)fail_cast(TurtleCastFailure{pending_cast->spell.spell,spell_results::forever(35),-1,-1},true);
break;
}
if(unit==selected.guid)select_cast(spell);
if(pending_cast && unit==selected.guid && spell==pending_cast->spell.spell)
fail_cast(TurtleCastFailure{spell,spell_results::forever(35),-1,-1},true); // SPELL_FAILED_INTERRUPTED
break;
}
case 0x131:case 0x132:{
std::optional<TurtleSpellCast> event;
try{event=turtle_spell_cast(uint16_t(packet.opcode),body);}
catch(const Error&){
// Keep validation of the actual pending request strict. A malformed
// unrelated broadcast must not interrupt the observer's session.
if(self_created && pending_cast){
bool matching=false;
try{
Reader header(body);
unpack_guid(header,8);
const auto raw_unit=unpack_guid(header,8);
Reader unit(raw_unit);
matching=unit.le(8)==selected.guid && header.le(4)==pending_cast->spell.spell;
}catch(const Error&){}
if(matching)throw;
}
break;
}
if(!event)break;
if(packet.opcode==0x132 && self_created && event->caster==selected.guid && event->spell==5019){ // Shoot, Category 351
const auto now=std::chrono::steady_clock::now();
if(wand_shot){
const auto gap=std::chrono::duration_cast<std::chrono::milliseconds>(now-*wand_shot);
if(gap>=std::chrono::milliseconds(500) && gap<=std::chrono::milliseconds(4000))wand_interval=gap;
}
wand_shot=now;wand_gcd_until=now+(wand_interval.count()?wand_interval:std::chrono::milliseconds(2000));
wand_repeating=true;
}
if(packet.opcode==0x131 && self_created && event->caster==selected.guid && event->spell==5019)wand_repeating=true;
if(packet.opcode==0x132 && self_created && location && !far_transfer && !pending_teleport && !logout_complete &&
event->caster==selected.guid && event->unit==selected.guid && source_skinning_spells::contains(event->spell) &&
event->targets==2 && event->target_unit && !event->target_item && event->misses.empty() &&
event->hits==std::vector<uint64_t>{event->target_unit})
loot.confirmed_skinning_cast(event->target_unit,realm,location->map,entities);
if(packet.opcode==0x132){
if(auto actor=entities.actors.find(event->unit);actor!=entities.actors.end() && actor->second.sent)
auras.remember_caster(event->unit,actor->second.modern);
auras.observe_go(event->unit,event->spell,event->hits);
}
if(packet.opcode==0x132 && std::binary_search(spell_log_sources::Dispels.begin(),spell_log_sources::Dispels.end(),event->spell)){
if(dispel_go.size()>=4096)dispel_go.clear();
dispel_go[event->caster]={event->spell,std::chrono::steady_clock::now()+std::chrono::seconds(2)};
}
boss(packet.opcode==0x131?"SPELL_CAST_START":"SPELL_CAST_SUCCESS",event->spell,event->caster,event->target_unit);
if(packet.opcode==0x132){
if(source_ghost_aura_profile::mask(event->spell))
trace_combat("source_ghost_go_observed",packet.opcode,event->caster,event->target_unit,event->spell,event->targets);
if(source_ghost_aura_profile::mask(event->spell) && aura_visual_profile::link(event->spell) &&
event->caster==selected.guid && event->unit==selected.guid && event->targets==2 &&
event->target_unit==selected.guid && !event->target_item && event->hits==std::vector<uint64_t>{selected.guid} && event->misses.empty()){
pending_ghost_cast=*event;ghost_cast_packet_budget=64;break;
}
}
if(!self_created){
if(packet.opcode!=0x132 || pending_cast)break;
if(event->unit!=selected.guid || event->targets!=2 || event->target_unit!=selected.guid ||
event->target_item || event->hits!=std::vector<uint64_t>{selected.guid} || !event->misses.empty() ||
(event->caster>>48)!=0x4000 || !aura_definition_profile::mask(event->spell) || !aura_visual_profile::link(event->spell))break;
auto found=login_equip_casts.find(event->spell);
if(found!=login_equip_casts.end())found->second.ambiguous=true;
else if(login_equip_casts.size()<16)login_equip_casts.emplace(event->spell,LoginEquipCast{*event,false,{}});
login_equip_packet_budget=256;
break;
}
// A unit cast received from the source is independent of any unrelated
// local request. Item-originated spells retain their owned-item policy.
if(event->unit==selected.guid)select_cast(event->spell);
bool self_request=pending_cast && event->unit==selected.guid &&
event->spell==pending_cast->spell.spell &&
pending_cast->caster==forever_player_guid(selected.guid,realm);
if(self_request && (event->targets&2u) && (pending_cast->spell.target_flags&2u)){
const auto known=bindings();
const auto target=known.find(event->target_unit);
self_request=target!=known.end() && pending_cast->spell.unit==target->second;
}
if(event->caster && event->caster==event->unit && !self_request){
if(event->unit==selected.guid && source_ghost_aura_profile::mask(event->spell))break;
if(!location || far_transfer || pending_teleport || logout_complete ||
!realm || realm>8191 || location->map>8191 || event->spell>0x7fffff ||
event->target_item || (event->targets&16u))break;
std::map<uint64_t,Guid128> known;
auto visible=[&](uint64_t id,bool object=false){
if(!id)return false;
if(id==selected.guid && !object){
known[id]=forever_player_guid(id,realm);return true;
}
const auto pos=entities.actors.find(id);
if(pos==entities.actors.end())return false;
const auto& actor=pos->second;
if(!actor.sent || !actor.eligible || !actor.generation ||
actor.presentation_realm!=realm || actor.presentation_map!=location->map ||
actor.modern==Guid128{} ||
(object?actor.kind!=5:actor.kind!=3 && actor.kind!=4))return false;
known[id]=actor.modern;return true;
};
if(!visible(event->unit) ||
((event->targets&0x802u) && !visible(event->target_unit,(event->targets&0x800u)!=0)) ||
!std::all_of(event->hits.begin(),event->hits.end(),[&](uint64_t id){return visible(id,(event->targets&0x800u) && id==event->target_unit);}) ||
!std::all_of(event->misses.begin(),event->misses.end(),[&](const auto& m){return visible(m.guid,(event->targets&0x800u) && m.guid==event->target_unit);}))break;
const bool start=packet.opcode==0x131;
const auto now=std::chrono::steady_clock::now();
std::erase_if(observed_casts,[&](const auto& entry){return entry.second.expires<=now;});
const auto key=std::pair{event->unit,event->spell};
const auto prior=observed_casts.find(key);
auto generation_of=[&](uint64_t guid)->uint64_t{
if(guid==selected.guid)return entities.self_position_generation;
const auto found=entities.actors.find(guid);
return found==entities.actors.end()?0:found->second.generation;
};
const auto generation=generation_of(event->unit);
const bool current=prior!=observed_casts.end() &&
prior->second.owner==selected.guid && prior->second.realm==realm &&
prior->second.map==location->map && prior->second.generation==generation &&
(!prior->second.target || prior->second.target_generation==generation_of(prior->second.target));
const bool paired=!start && current &&
(!prior->second.target || !event->target_unit || prior->second.target==event->target_unit);
if(start && prior==observed_casts.end() && observed_casts.size()>=256)break;
if(!paired && server_cast_counter>=0xffffffffffULL)break;
const auto id=paired?prior->second.identity:forever_server_cast_guid(realm,location->map,event->spell,server_cast_counter+1);
auto payload=cast_payload(*event,known,id,cast_visual_profile::link(event->spell),0,start?8:9);
if(!paired)++server_cast_counter;
if(start)observed_casts[key]={id,selected.guid,generation,event->target_unit,generation_of(event->target_unit),realm,location->map,
now+std::chrono::milliseconds(event->time)+std::chrono::seconds(5)};
else if(prior!=observed_casts.end() && (paired || !current))observed_casts.erase(prior);
emit(start?0x69002d:0x69002c,std::move(payload));
if(!start && event->unit==selected.guid && event->misses.empty() &&
(event->targets==0 || (event->targets==2 && event->target_unit==selected.guid)) &&
event->hits.size()==1 && event->hits.front()==selected.guid)
auras.observe_speed_aura_hit(selected.guid,event->spell,id,realm);
break;
}
if(!pending_cast){
// This branch is only for a source-attested on-equip self GO.
if(packet.opcode!=0x132 || !location)break;
if(event->unit!=selected.guid || event->targets!=2 || event->target_unit!=selected.guid || event->target_item ||
event->hits!=std::vector<uint64_t>{selected.guid} || !event->misses.empty())break;
if(!aura_definition_profile::mask(event->spell))break;
auto item=inventory.items.find(event->caster);if(item==inventory.items.end())break;
auto entry=item->second.fields.find(turtle_entity_fields::OBJECT_FIELD_ENTRY);if(entry==item->second.fields.end())break;
auto definition=inventory.templates.find(entry->second);if(definition==inventory.templates.end() || !definition->second.found)break;
unsigned matches=0;bool equip=false;
for(auto spell:definition->second.spells)if(spell.spell==event->spell){++matches;equip=spell.trigger==1;}
auto visual=aura_visual_profile::link(event->spell);
if(matches!=1 || !equip || !visual || !realm || realm>8191 || location->map>8191 ||
event->spell>0x7fffff || server_cast_counter>=0xffffffffffULL)break;
auto known=bindings();const auto& owned=inventory.owned_bindings();known.insert(owned.begin(),owned.end());
auto id=forever_server_cast_guid(realm,location->map,event->spell,server_cast_counter+1);
auto payload=cast_payload(*event,known,id,visual,0,7);
++server_cast_counter;emit(0x69002c,std::move(payload));
// GO precedes effects. Retain context only as a candidate; a fresh
// actual source slot must independently confirm aura installation.
auras.observe_equip_cast(selected.guid,event->spell,id,owned.at(event->caster));
break;
}
if(packet.opcode==0x132&&event->unit==selected.guid)entities.note_spell_go(event->spell,event->target_unit);
const auto& request=*pending_cast;
if(event->unit!=selected.guid || event->spell!=request.spell.spell)break;
auto known=bindings();
for(const auto& [id,record]:inventory.items){(void)record;Guid128 modern{};Bytes raw;le(raw,id&0xffffffff,8);le(raw,uint64_t(3)<<58,8);std::copy(raw.begin(),raw.end(),modern.begin());known[id]=modern;}
if(event->targets&0x800){
auto actor=entities.actors.find(event->target_unit);
if(request.spell.target_flags!=0x800 || !location || actor==entities.actors.end() ||
actor->second.kind!=5 || !actor->second.sent || !actor->second.eligible || !actor->second.generation ||
actor->second.presentation_realm!=realm || actor->second.presentation_map!=location->map ||
actor->second.modern!=request.spell.unit ||
!std::all_of(event->hits.begin(),event->hits.end(),[&](uint64_t id){return known.contains(id);}) ||
!std::all_of(event->misses.begin(),event->misses.end(),[&](const auto& miss){return known.contains(miss.guid);}))break;
}
auto caster=known.find(event->caster);if(caster==known.end() || caster->second!=request.caster)break;
auto visual=request.spell.visual;
if(self_request && event->caster==event->unit && !visual && !request.spell.script_visual)
visual=cast_visual_profile::link(event->spell);
auto payload=cast_payload(*event,known,request.spell.cast,visual,request.spell.script_visual,uint8_t(packet.opcode==0x132));
// Turtle has no server cast GUID. Preserve the actual unique client
// ID as the adapter identity and confirm that identity only upon the
// matching genuine server event, never on outgoing request alone.
if(!cast_prepared){auto id=pack_guid(request.spell.cast);auto prepare=id;append(prepare,id);emit(0x69002b,std::move(prepare));cast_prepared=true;}
emit(packet.opcode==0x131?0x69002d:0x69002c,std::move(payload));
if(packet.opcode==0x132){
// Source GO is necessary but not sufficient: only a later genuine
// same-owner loot response can publish a chest window.
if(location && request.spell.target_flags==0x800 && event->targets==0x800 && event->target_unit &&
std::find(event->hits.begin(),event->hits.end(),event->target_unit)!=event->hits.end() && event->misses.empty()){
auto actor=entities.actors.find(event->target_unit);
if(actor!=entities.actors.end() && actor->second.modern==request.spell.unit)
loot.confirmed_chest_cast(event->target_unit,realm,location->map,entities);
}
auto meta=inventory.templates.find(pending_item_entry);
if(meta!=inventory.templates.end() && meta->second.found){
auto definition=std::find_if(meta->second.spells.begin(),meta->second.spells.end(),[&](const auto& spell){return spell.spell==event->spell && spell.trigger==0;});
if(definition!=meta->second.spells.end()){
bool modified=std::any_of(cooldown_flat.begin(),cooldown_flat.end(),[](auto v){return v!=0;}) || std::any_of(cooldown_percent.begin(),cooldown_percent.end(),[](auto v){return v!=0;});
if(modified)++inventory.cooldown_modifier_blocks;
else{
auto recovery=uint32_t(std::max({0,definition->cooldown,definition->category_cooldown}));
if(recovery){
std::map<uint32_t,uint32_t> durations{{event->spell,recovery}};
if(definition->category && definition->category_cooldown>0)
for(const auto& [entry,profile]:inventory.templates){(void)entry;if(profile.found)for(const auto& spell:profile.spells)if(spell.spell && spell.trigger==0 && spell.category==definition->category)durations[spell.spell]=std::max(durations[spell.spell],uint32_t(definition->category_cooldown));}
auto now=uint64_t(std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now().time_since_epoch()).count());
Bytes cooldown{4};append(cooldown,forever_player_guid(selected.guid,realm));le(cooldown,durations.size(),2);
for(auto [spell,duration]:durations){auto& until=item_cooldown_until[spell];until=std::max(until,now+duration);le(cooldown,spell,4);le(cooldown,until-now,4);}
emit(0x690005,source(GW_CODEC_SPELL_CAST,cooldown));++inventory.cooldown_packets;
}
}
}
}
release_cast();
}break;
}
case 0x29d:{
Reader r(body);auto state=r.le(1);r.end();if(state>8)throw Error("unsupported server stand state");
stand_state_received(uint8_t(state));
if(self_created){Bytes result{uint8_t(state)};le(result,0,4);emit(0x4701c9,std::move(result));}
break;
}
case 0x1b1:{
const auto previous_guid = trainer && trainer_self_guid == selected.guid ? trainer->guid : 0;
trainer.reset();
auto list=turtle_trainer_list(body);auto known=bindings();auto target=known.find(list.guid);
const bool already_open = previous_guid == list.guid;
if(target==known.end() || !selected.guid || logout_complete || far_transfer)break;
if(!prepare_trainer_offers(list)){
if(list.type==2)std::fprintf(stderr,"GWTrainerStepHeld entry=%u\n",uint32_t((list.guid>>24)&0xffffffu));
break;
}
// The server admits every race/class when a taught spell has no
// SkillLineAbility row. Remove only offers proved unassigned in both
// the source DBC and native 70334 DB2 across the complete trainer DB.
// Cache the filtered list too, so a hidden offer cannot be purchased.
const auto entry=uint32_t((list.guid>>24)&0xffffffu);
auto end=std::remove_if(list.spells.begin(),list.spells.end(),[&](const TrainerSpell& spell){
auto row=trainer_offer_filter::blocked(entry,selected.cls,spell.spell);
if(!row)return false;
std::fprintf(stderr,"GWTrainerFilter {\"entry\":%u,\"class\":%u,\"service\":%u,\"taught\":%u}\n",
entry,unsigned(selected.cls),spell.spell,row->taught_spell);
return true;
});
list.spells.erase(end,list.spells.end());
if(!supports_trainer(list))break;
if(!already_open)emit(0x47031b,forever_interaction_open(target->second,7));
const auto skill = trainer_profession_skill(list);
const bool learned = self_created && entities.self_profession_skills.has_learned_skill(selected.guid,skill);
emit(forever_opcodes::SMSG_TRAINER_LIST,forever_trainer_list(list,target->second,learned ? skill : 0));
trainer_self_guid=selected.guid;trainer=std::move(list);break;
}
case 0x1b3:{
// Source success acknowledges the purchased service, not a learned
// spell or a new offer state. Refresh from the same genuine trainer;
// only its subsequent list can update the original native list.
Reader r(body);auto npc=r.le(8),service=r.le(4);r.end();
if(!self_created || logout_complete || far_transfer || !trainer || trainer_self_guid!=selected.guid || trainer->guid!=npc ||
!supports_trainer(*trainer) || !bindings().contains(npc) ||
std::none_of(trainer->spells.begin(),trainer->spells.end(),[&](const auto& row){return row.spell==service;}))break;
Bytes query;le(query,npc,8);
if(requests.size()<4096 && std::none_of(requests.begin(),requests.end(),[&](const auto& row){return row.opcode==0x1b0 && row.body==query;}))
requests.push_back({0x1b0,std::move(query)});
break;
}
case 0x1b4:{
Reader r(body);auto npc=r.le(8),spell=r.le(4),reason=r.le(4);r.end();auto known=bindings();
if(reason>2)throw Error("unreviewed Turtle training failure");
if(logout_complete || far_transfer || !trainer || trainer_self_guid!=selected.guid || trainer->guid!=npc || !known.contains(npc))break;
if (trainer->type == 2) {
const auto offered = std::find_if(trainer->spells.begin(), trainer->spells.end(),
[&](const TrainerSpell& row) { return row.spell == spell; });
if (offered == trainer->spells.end()) break;
spell = offered->display_spell();
}
auto out=pack_guid(known.at(npc));le(out,spell,4);le(out,reason,4);emit(forever_opcodes::SMSG_TRAINER_BUY_FAILED,std::move(out));break;
}
case 0x2aa:{
// Source Player::SendTalentWipeConfirm: GUID64 + cost32. This follows
// CloseGossip, so an open menu is deliberately not required here.
Reader r(body);auto guid=r.le(8);auto cost=uint32_t(r.le(4));r.end();
if(!guid && cost)throw Error("invalid empty Turtle talent reset offer");
talent_reset_offer.reset();
if(guid){
auto actor=entities.actors.find(guid);
if(actor!=entities.actors.end())talent_reset_offer=TalentResetOffer{guid,actor->second.generation,cost};
}
if(talent_reset_offer_bound())talent_notice="GWTURTLE1 RESET "+std::to_string(guid)+" "+std::to_string(cost);
else{talent_reset_offer.reset();talent_notice="GWTURTLE1 RESET 0 0";}
break;
}
case 0x12b:case 0x203:case 0x12c:{
auto out=forever_spell_learning(packet.opcode,body);Reader state(body);
if(packet.opcode==0x12b)spells.insert(uint32_t(state.le(4)));
else if(packet.opcode==0x203)spells.erase(uint32_t(state.le(2)));
else{auto old=state.le(2),next=state.le(2);spells.erase(uint32_t(old));spells.insert(uint32_t(next));}
// These are independently acknowledged source facts. Points may arrive
// before or after the learned-rank packet; the UI requires BOTH facts
// before advancing its pending purchase, never an optimistic rank.
talent_snapshot_pending=talent_ready();
emit(packet.opcode==0x12b?forever_opcodes::SMSG_LEARNED_SPELLS:packet.opcode==0x203?forever_opcodes::SMSG_UNLEARNED_SPELLS:forever_opcodes::SMSG_SUPERCEDED_SPELLS,std::move(out));break;
}
case 0x1a4:{
Reader r(body);auto vendor=r.le(8),muid=r.le(4),stock=r.le(4),bundles=r.le(4);r.end();auto known=bindings();
if(!merchant || *merchant!=vendor || !vendor_inventory || vendor_inventory->guid!=vendor || !known.contains(vendor))break;
auto offer=std::find_if(vendor_inventory->items.begin(),vendor_inventory->items.end(),[&](const auto& v){return v.slot==muid;});
if(offer==vendor_inventory->items.end() || !offer->stack || !bundles || bundles>255 || bundles*offer->stack>0xffffffff)throw Error("Turtle buy response outside vendor bundle bound");
emit(merchant_opcodes::BuySucceeded,forever_buy_success(known.at(vendor),uint32_t(muid),uint32_t(stock),uint32_t(bundles*offer->stack)));break;
}
case 0x1a5:{
Reader r(body);auto vendor=r.le(8),item=r.le(4),reason=r.le(1);r.end();
if(reason!=0 && reason!=1 && reason!=2 && reason!=4 && reason!=5 && reason!=7 && reason!=8 && reason!=11 && reason!=12)throw Error("unreviewed Turtle buy error");
auto known=bindings();if(vendor && !known.contains(vendor))break;
emit(merchant_opcodes::BuyFailed,forever_buy_failure(vendor?known.at(vendor):Guid128{},uint32_t(item),uint8_t(reason)));break;
}
case 0x1a9:{
auto menu=turtle_taxi_menu(body);auto known=bindings();auto target=known.find(menu.vendor);
if(target==known.end())throw Error("taxi menu outside visible creature binding");
// TaxiHandler::SendTaxiMenu sends ShowTaxiNodes itself. An additional
// NPC_INTERACTION_OPEN_RESULT(TaxiNode) makes the engine request this
// menu again: source1a9 -> open ->3f0042 ->source1ac ->source1a9.
// That feedback loop also reopens a window the user just closed.
emit(0x47017a,forever_taxi_menu(menu,target->second));
taxi_vendor_generation=entities.actors.at(menu.vendor).generation;taxi_menu=std::move(menu);break;
}
case 0x1ab:{
Reader r(body);auto guid=r.le(8),status=r.le(1);r.end();auto known=bindings();auto target=known.find(guid);
if(target!=known.end())emit(0x470129,forever_taxi_status(target->second,uint8_t(status)));
break;
}
case 0x1ae:emit(0x47012a,forever_taxi_reply(body));break;
// Source1af is empty, while native NewTaxiPath needs a node ID. The next
// genuine status update still updates the NPC. Do not invent a learned ID.
case 0x1af:{Reader r(body);r.end();break;}
case 0x17d:{
auto menu=turtle_gossip_menu(body);auto known=bindings();auto target=known.find(menu.guid);
gw_inv_log("GW_GOSSIP menu guid=%llx text=%u options=%zu bound=%d\n",(unsigned long long)menu.guid,menu.text_id,menu.options.size(),int(target!=known.end()));
if(target==known.end())throw Error("native gossip response outside visible identity binding");
npc_text_queries.new_menu();
// Any genuine menu (guild bank included) supersedes a pending pet unlearn from another NPC
// and any selection authority not yet answered by the Source.
if(pet_unlearn_offer && pet_unlearn_offer->trainer!=menu.guid)pet_unlearn_offer.reset();
last_gossip_npc.reset();
character_bank.reset();
if(bank_gossip(menu)){gossip.reset();break;}
gossip_actor_generation=entities.actors.at(menu.guid).generation;
clear_bank();
if(service_shortcut(menu) && requests.size()<4096){
// The 1.12 client never asks a no-gossip service NPC (auctioneer, repair bot, companions) for
// a menu; it opens the service. The native client always does, and the Source answers with its
// one-option default list ("GOSSIP_OPTION_AUCTIONEER"). Select that option like the 1.12 client
// would have opened it; the Source's own service reply then opens the native window.
Bytes pick;le(pick,menu.guid,8);le(pick,menu.options.front().index,4);
gw_inv_log("GW_GOSSIP shortcut guid=%llx option=%u icon=%u\n",(unsigned long long)menu.guid,menu.options.front().index,menu.options.front().icon);
gossip=std::move(menu);gossip->broadcast_text=0;
requests.push_back({0x17c,std::move(pick)});
break;
}
gossip=std::move(menu);
if (requests.size() < 4096) {
if (auto query=npc_text_queries.greeting_request(*gossip)) {
requests.push_back({0x17f,std::move(*query)});
break;
}
}
gossip->broadcast_text=0;
emit(0x670018,forever_gossip_menu(*gossip,target->second));
break;
}
case 0x17e:{Reader r(body);r.end();gossip.reset();emit(0x670017,Bytes{0});break;}
case 0x2d4:{
if (!selected.guid || !self_created || !location || logout_complete) break;
try {
const auto now = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now().time_since_epoch()).count();
{
Reader q(body);const auto slot=q.le(4);const auto map=uint32_t(q.le(4));
if(slot<bg_team.size()){
if(!map)bg_team[slot].reset();
else if(!bg_team[slot] || bg_team[slot]->map!=map){
bg_team[slot].reset();q.le(1);q.le(4);
// Only a fresh Queued status starts evidence; an Invited/Active
// status with no observed queue (e.g. relog in a BG) stays unknown.
if(q.le(4)==1){BgTeamEvidence e{map,{}};if(!loot.group || loot.group->explicit_solo)e.team=source_match_team(selected.guid);bg_team[slot]=e;}
else bg_team[slot]=BgTeamEvidence{map,{}};
}
}
}
battlegrounds.status(body, forever_player_guid(selected.guid, realm), uint32_t(now), output);
} catch (const Error&) { /* malformed optional status */ }
break;
}
case 0x2e0:{
// Partial known-team scoreboard: only self and members of the proven BG
// raid, on the map whose queue established the match team, with a genuine
// identity. Other rows are held; an all-held board is not shown as empty.
const auto log=turtle_pvp_log(body);
if(!self_created || !location){pvp_held_rows+=log.rows.size();break;}
std::optional<uint8_t> team;
for(const auto& e:bg_team)if(e && e->map==location->map && e->team)team=e->team;
if(!team){pvp_held_rows+=log.rows.size();break;}
std::set<uint64_t> allies{selected.guid};
if(loot.group && !loot.group->explicit_solo)for(const auto& m:loot.group->members)allies.insert(m.guid);
std::vector<PvpStatisticsRow> shown;std::set<uint64_t> seen;
for(const auto& row:log.rows){
std::optional<Character> who;
if(row.guid==selected.guid)who=selected;
else if(auto c=chat_players.find(row.guid);c!=chat_players.end())who=c->second;
else if(auto p=entities.peer_players.find(row.guid);p!=entities.peer_players.end() && p->second.named && !p->second.blocked && p->second.identity.guid==row.guid)who=p->second.identity;
if(!allies.contains(row.guid) || !who || !row.guid || row.guid>UINT32_MAX || who->gender>1 || !seen.insert(row.guid).second){++pvp_held_rows;continue;}
PvpStatisticsRow p;p.guid=forever_player_guid(row.guid,realm);p.team=*team;p.race=who->race;p.sex=who->gender;p.cls=who->cls;
p.kills=row.killing_blows;p.honorable_kills=row.honorable_kills;p.deaths=row.deaths;p.contribution=row.bonus_honor;
if(auto stats=native_pvp_stats(location->map,row.fields))p.stats=std::move(*stats);
shown.push_back(std::move(p));
}
if(shown.empty())break;
emit(0x4d0010,source(GW_CODEC_PVP_STATISTICS,pvp_statistics_input(shown)));
break;
}
case 0x63:{
// Tortoise SMSG_WHO rows carry no GUID. Show a row only for a unique,
// exact-name, current-realm identity already established from genuine
// Source data whose race/class agree; hold every other row.
const auto rows=turtle_who(body);
if(!pending_who || !self_created || pending_who->owner!=selected.guid || pending_who->realm!=realm){who_held_rows+=rows.size();break;}
const auto token=pending_who->token;pending_who.reset();
std::vector<WhoProjection> shown;
for(const auto& row:rows){
std::set<uint64_t> matches;std::optional<Character> found;
auto consider=[&](const Character& c){if(c.guid && c.name==row.name){matches.insert(c.guid);found=c;}};
consider(selected);
for(const auto& entry:chat_players)consider(entry.second);
for(const auto& entry:entities.peer_players)if(entry.second.named && !entry.second.blocked)consider(entry.second.identity);
const auto team=found?source_team_for_race(found->race):std::nullopt;
if(matches.size()!=1 || !team || found->guid>UINT32_MAX || found->race!=row.race || found->cls!=row.cls ||
found->gender>1 || row.level>255 || row.guild.size()>127){++who_held_rows;continue;}
WhoProjection w;auto& p=w.player;p.guid=forever_player_guid(found->guid,realm);p.virtual_address=address;p.name=row.name;
p.race=uint8_t(row.race);p.sex=found->gender;p.cls=uint8_t(row.cls);p.level=uint8_t(row.level);p.pvp_faction=*team==SourceTeam::Alliance?1:0;
w.guild=row.guild;w.area=int32_t(row.zone);shown.push_back(std::move(w));
}
// Never present held rows as absent: an all-held answer shows nothing.
if(shown.empty() && !rows.empty())break;
emit(0x4c0002,source(GW_CODEC_WHO,who_input(token,shown)));
break;
}
case 0x2cc:{
// Tortoise Player::SendRaidInfo: count, (map, seconds to scheduled reset,
// instance)* for permanent binds -> native InstanceInfo. DifficultyID is
// the native MapDifficulty row of that classic raid (40-player 9,
// 20-player 148); a map without one is not presented.
static const std::map<uint32_t,int16_t> raid_difficulty{{249,9},{309,148},{409,9},{469,9},{509,148},{531,9},{533,9}};
Reader r(body);const auto count=r.le(4);if(count>64)throw Error("Source raid lock bound");
Bytes locks;uint32_t shown=0;
for(uint64_t i=0;i<count;++i){
const auto map=uint32_t(r.le(4)),reset=uint32_t(r.le(4)),instance=uint32_t(r.le(4));
const auto difficulty=raid_difficulty.find(map);
if(difficulty==raid_difficulty.end() || !instance || reset>0x7fffffffu)continue;
le(locks,map,4);le(locks,uint16_t(difficulty->second),2);le(locks,instance,8);le(locks,reset,4);
le(locks,0,4);le(locks,0x80,1); // CompletedMask: no Source field; Locked=1 (permanent bind), Extended=0
++shown;
}
r.end();
Bytes out;le(out,shown,4);append(out,locks);emit(0x4700de,std::move(out));break;
}
case 0x1cd:{
// Tortoise SMSG_PLAYED_TIME: u32 total, u32 level -> native PlayedTime
// TotalTime, LevelTime, bit TriggerEvent (0x470181).
if(body.size()!=8)throw Error("invalid Turtle played-time response");
Bytes out(body.begin(),body.end());out.push_back(played_trigger?0x80:0);played_trigger=false;
emit(0x470181,std::move(out));break;
}
case 0x180:{
if (auto reply=npc_text_queries.response(body,current_npc_text_menu())) {
if (!gossip->broadcast_text) {
npc_text_queries.resolve(*gossip,*reply);
gw_inv_log("GW_GOSSIP greeting text=%u broadcast=%u\n",gossip->text_id,unsigned(gossip->broadcast_text.value_or(0)));
emit(0x670018,forever_gossip_menu(*gossip,entities.actors.at(gossip->guid).modern));
} else {
emit(npc_text::Response,std::move(*reply));
}
}
break;
}
case 0x2a5:{
forced_reactions=turtle_forced_reactions(body);forced_reactions_dirty=true;
break;
}
case 0x28d:{ // Source owner cancellation to bidder; never fabricate AuctionOutbid.
if(body.size()!=12){++auction_holds;break;}
Reader r(body);const auto id=r.le(4),item=r.le(4),property=r.le(4);r.end();
if(!id || !item){++auction_holds;break;}
aux_local("D;"+std::to_string(id)+";"+std::to_string(item)+";"+std::to_string(property));
break;
}
case 0x25d: case 0x265:{
// The Source guard is released before its reply is sent; only the awaited kind releases ours.
if(ah_list_inflight && ah_list_reply==packet.opcode){ah_list_inflight=false;
if(ah_list_retired){ah_list_retired=false;aux_list_reply=0;break;}} // reply for a closed interaction: no output
if(aux_list_reply==packet.opcode){
aux_list_reply=0;
try{for(const auto& t:aux_page_texts(packet.opcode==0x25d?'O':'I',turtle_auction_list(body),[&](uint64_t g){return aux_name(g);}))aux_local(t);}
catch(const Error& e){aux_local(std::string("X;")+e.what());}
break;
}
// Owned / bidder list for the pending native request: page the complete Source snapshot.
if(auction_personal && auction_personal->awaiting && auction_personal->owned==(packet.opcode==0x25d)){
try{
if(auto next=auction_personal->snapshot.add(turtle_auction_list(body))){
if(requests.size()>=4096)throw AuctionHold("auction page request");
PersonalListQuery q{auction_personal->auctioneer,auction_personal->sorts,auction_personal->ids};
requests.push_back({uint16_t(packet.opcode==0x25d?0x259:0x264),personal_list_request(auction_personal->owned,q,*next)});
ah_list_arm(uint16_t(packet.opcode),auction_personal->auctioneer);
}else{
auction_personal->awaiting=false;
if(auction_personal->snapshot.rows.empty()){ // empty: no codec needed (existing empty result)
emit(packet.opcode==0x25d?0x4702f9:0x4702fa,Bytes(packet.opcode==0x25d?13:9,0));auction_personal.reset();
}
}
}catch(const Error& e){gw_inv_log("GW_AH personal-page-hold why=%s\n",e.what());auction_personal.reset();++auction_holds;}
}
break; // every native personal request arms a state: an unarmed list has no native owner
}
case 0x23d: case 0x25b: case 0x25e: case 0x25f:
case 0x295: case 0x297: case 0x298: case 0x2bb: case 0x2e8: case 0x2ec: case 0x2ed:{
if (!self_created) break;
if(packet.opcode==0x25b && aux_auctioneer && body.size()>=12){try{aux_local(aux_command_text(body));}catch(const Error&){}}
if(packet.opcode==0x25b && auction_commodity && auction_commodity->bid_sent && body.size()>=12){
// The one Source result for the dispatched commodity buyout: native AuctionID 0, PlaceBid, Ok or 21.
// Success needs the exact auction ID and the complete success body (ID, command, 0, increment).
// Zero-ID PlaceBid errors (4, 10) are ours only when no ordinary bid could own them.
Reader q(body);const auto id=uint32_t(q.le(4)),command=uint32_t(q.le(4)),result=uint32_t(q.le(4));
const bool exact=id==auction_commodity->quote->lots[auction_commodity->next_lot].first;
const bool zero_error=!id && (result==4 || result==10) && body.size()==12 &&
std::chrono::steady_clock::now()-ordinary_bid_since>std::chrono::seconds(60);
if(command==2 && exact && result==0 && body.size()==16){
auto& c=*auction_commodity;
if(++c.next_lot<c.quote->lots.size() && requests.size()<4096){ // next whole stack of a multi-stack purchase
const auto& lot=c.quote->lots[c.next_lot];Bytes bid;le(bid,c.auctioneer,8);le(bid,lot.first,4);le(bid,uint32_t(lot.second),4);
c.bid=bid;c.bid_sent=false;c.bid_queued=true;requests.push_back({0x25a,std::move(bid)});break;
}
auction_commodity_resolve(c.next_lot>=c.quote->lots.size());break;
}
if(command==2 && ((exact && result!=0) || zero_error)){auction_commodity_resolve(false);break;}
}
try {
if (packet.opcode == 0x2e8 && selected.guid && location && !logout_complete){
Reader q(body);const auto map=uint32_t(q.le(4));
// Group enrollment: the queue team is the group leader's at this moment.
for(auto& e:bg_team)if(e && e->map==map)e->team=loot.group && !loot.group->explicit_solo?source_match_team(loot.group->leader):std::nullopt;
battlegrounds.group_joined(body, forever_player_guid(selected.guid, realm), output);
}
Reader input(body);
auto translated = packet.opcode == 0x23d
? auction_battleground::battlefield_list(input, selected.guid, bindings())
: auction_battleground::response(packet.opcode, input, realm);
if (translated && packet.opcode == 0x23d) {
Reader peek(body);const auto actor=peek.le(8);const auto map=uint32_t(peek.le(4));
// A self-addressed list is Turtle's minimap queue (TW_BGQueue sets the entry point);
// its join must name the player itself (BattleGroundHandler queuedAtBGPortal), not 0.
battlemaster_offer=BattlemasterOffer{actor,map};
}
if (translated) output.push_back(std::move(*translated));
} catch (const Error&) {
// Drop a malformed optional service report without retiring the world.
}
break;
}
case 0x25c:{
if(ah_list_inflight && ah_list_reply==0x25c){ah_list_inflight=false;if(ah_list_retired){ah_list_retired=false;aux_list_reply=0;break;}}
if(aux_list_reply==0x25c){
aux_list_reply=0;
try{for(const auto& t:aux_page_texts('Q',turtle_auction_list(body),[&](uint64_t g){return aux_name(g);}))aux_local(t);}
catch(const Error& e){aux_local(std::string("X;")+e.what());}
break;
}
if(auction_commodity && auction_commodity->awaiting){
auto& c=*auction_commodity;
try{
if(auto next=c.snapshot.add(turtle_auction_list(body))){
if(requests.size()>=4096)throw AuctionHold("commodity page request");
requests.push_back({0x258,source_auction_name_request(c.auctioneer,c.name,*next)});ah_list_arm(0x25c,c.auctioneer);
break;
}
c.awaiting=false;
const auto* t=inventory.peer_template(c.item);
if(!t || !t->found)throw AuctionHold("commodity template retired");
const AuctionItemFacts f{t->cls,t->subclass,t->item_level,t->required_level,t->stack,t->container_slots,t->required_skill_rank,t->name};
// Decided on the last authoritative balance only; without one there is no quote (Source drops unaffordable buyouts silently).
auto q=self_coinage?commodity_quote(c.snapshot,[&](uint32_t e)->const AuctionItemFacts*{return e==c.item?&f:nullptr;},c.item,c.quantity,selected.guid,self_coinage):std::nullopt;
c.snapshot=AuctionSnapshot{};
if(!c.confirm){
CommodityQuoteResult res;res.item=int32_t(c.item);
if(q){res.total=q->buyout;res.quantity=q->quantity;res.remaining_ms=30000;c.quote=q;c.deadline=std::chrono::steady_clock::now()+std::chrono::seconds(30);}
emit(0x4702fb,source(GW_CODEC_COMMODITY_QUOTE,commodity_quote_input(res)));
if(!q)auction_commodity.reset();
}else if(q && c.quote && *q==*c.quote &&
std::chrono::steady_clock::now()<c.deadline && requests.size()<4096 &&
std::all_of(q->lots.begin(),q->lots.end(),[](const auto& l){return l.second<=UINT32_MAX;})){
c.next_lot=0;Bytes bid;le(bid,c.auctioneer,8);le(bid,q->lots[0].first,4);le(bid,uint32_t(q->lots[0].second),4);
c.bid=bid;requests.push_back({0x25a,std::move(bid)});c.bid_queued=true;
}else auction_commodity_resolve(false);
}catch(const Error&){++auction_holds;auction_commodity_fail(c.confirm);}
break;
}
// SMSG_AUCTION_LIST_RESULT for the pending native search only.
gw_inv_log("GW_AH list-result bytes=%zu browse=%d awaiting=%d\n",body.size(),auction_browse?1:0,(auction_browse && auction_browse->awaiting)?1:0);
if(!auction_browse || !auction_browse->awaiting)break;
try{
if(auto next=auction_browse->snapshot.add(turtle_auction_list(body))){
auto page=auction_browse->by_item?std::optional<Bytes>(source_auction_name_request(auction_browse->auctioneer,auction_browse->query.name,*next))
:std::optional<Bytes>(source_auction_superset_request(auction_browse->query,auction_browse->auctioneer,*next));
if(!page || requests.size()>=4096)throw AuctionHold("auction page request");
requests.push_back({0x258,std::move(*page)});ah_list_arm(0x25c,auction_browse->auctioneer);
}else auction_browse->awaiting=false;
}catch(const Error&){auction_browse.reset();++auction_holds;}
break;
}
case 0x255:{
// Only the authenticated Source server can authorize the house and
// return an auctioneer GUID. The typed adapter checks the live binding.
auto response=forever_auction_hello(body,bindings());
Reader r(body);const auto auctioneer=r.le(8); // Full framing/house/binding validated above.
emit(0x470199,std::move(response));
aux_auctioneer=auctioneer;gossip.reset();break;
}
case 0x1f2:{
// Tortoise SendTabardVendorActivate {u64 vendor} -> NPCInteractionOpenResult(GuildTabardVendor 14),
// as TC SendTabardVendorActivate(Guild).
Reader r(body);auto guid=r.le(8);r.end();auto known=bindings();auto target=known.find(guid);
if((guid>>48)!=0xf130 || target==known.end())throw Error("tabard vendor outside visible creature binding");
emit(0x47031b,forever_interaction_open(target->second,14));break;
}
case 0x1f1:{
// Tortoise SendSaveGuildEmblem {u32}. 0..4 share TC GuildEmblemError meanings. Source 5
// (FAIL_NO_MESSAGE) is deliberately silent, while TC 5 says "not an emblem vendor": drop it.
Reader r(body);auto code=r.le(4);r.end();
if(code<=4){Bytes out;le(out,code,4);emit(0x530040,std::move(out));}
break;
}
case 0x2eb:{
// Tortoise Player::SetBindPoint sends SMSG_BINDER_CONFIRM {u64 innkeeper}; TC answers the
// same gossip option with NPCInteractionOpenResult(Binder 20), whose UI asks to confirm.
Reader r(body);auto guid=r.le(8);r.end();
auto known=bindings();auto actor=entities.actors.find(guid);auto target=known.find(guid);
if(!self_created || !location || logout_complete || pending_teleport || far_transfer ||
(guid>>48)!=0xf130 || actor==entities.actors.end() || target==known.end() ||
actor->second.kind!=3 || !actor->second.sent || !actor->second.eligible || !actor->second.generation ||
actor->second.presentation_realm!=realm || actor->second.presentation_map!=location->map)
throw Error("binder offer outside visible creature binding");
binder_offer=SpiritHealerOffer{guid,actor->second.generation};
emit(0x47031b,forever_interaction_open(target->second,20));break;
}
case 0x222:{
// Source SpellEffects.cpp sends this genuine GUID-only confirmation.
// Native Player.cpp starts interaction SpiritHealer18 after the same
// service selection. Reuse its original confirmation UI/activation.
Reader r(body);auto guid=r.le(8);r.end();auto known=bindings();
auto actor=entities.actors.find(guid);auto target=known.find(guid);
if((guid>>48)!=0xf130 || actor==entities.actors.end() || target==known.end() ||
actor->second.kind!=3 || !actor->second.sent)
throw Error("spirit-healer offer outside visible creature binding");
spirit_healer_offer=SpiritHealerOffer{guid,actor->second.generation};
emit(0x47031b,forever_interaction_open(target->second,18));break;
}
case 0x1b8:{
// Genuine authenticated Tortoise NPCHandler::SendShowBank: GUID64.
// Reuse the engine interaction manager, as Forever SendShowBank does.
Reader r(body);auto banker=r.le(8);r.end();
if(!selected.guid || !realm || !self_created || !location || logout_complete || pending_teleport || far_transfer)break;
auto known=bindings();
if(banker && banker==selected.guid){
// GM .bank: Tortoise SendShowBank(GetObjectGuid()) names the player itself.
emit(0x47031b,forever_interaction_open(forever_player_guid(selected.guid,realm),67));
character_bank=CharacterBankInteraction{banker,0};
break;
}
auto target=known.find(banker);
if(!service_unit(banker) || target==known.end())throw Error("bank response outside visible creature binding");
const auto actor=entities.actors.find(banker);
if(actor==entities.actors.end() || actor->second.kind!=3 || !actor->second.sent || !actor->second.eligible ||
!actor->second.generation || actor->second.presentation_realm!=realm || actor->second.presentation_map!=location->map)
throw Error("character banker is outside current presentation");
emit(0x47031b,forever_interaction_open(target->second,67));
character_bank=CharacterBankInteraction{banker,actor->second.generation};
break;
}
case 0x19f:{
auto inventory=turtle_vendor_inventory(body);auto known=bindings();auto target=known.find(inventory.guid);
if(target==known.end())throw Error("native vendor response outside visible identity binding");
if(merchant!=inventory.guid){emit(0x47031b,forever_interaction_open(target->second,5));merchant=inventory.guid;}
emit(0x47005c,forever_vendor_inventory(inventory,target->second));vendor_inventory=std::move(inventory);break;
}
case 0xc7:{
if(!self_created || pending_teleport)throw Error("native near teleport outside ready self state");
auto teleport=turtle_near_teleport(body,selected.guid);
emit(0x600034,forever_near_teleport(teleport,realm));
native_movement_counter=teleport.sequence+1;
if(release.requested && location){
WorldLocation transfer;transfer.map=location->map;transfer.position=teleport.position;
release.transfer=transfer;
}
trace_release("source_owned_transfer");
character_bank.reset();
trade.close();clear_mailbox();clear_inspect_selection();observed_casts.clear();auras.pending_self_hits.clear();if (equipment_sets.pending) equipment_sets.finish(1);
pending_teleport=std::move(teleport);break;
}
case 0x96:{
Reader r(body);auto type=r.le(1);
if(type==10 && played_silent_notes){ // Turtle CHAT_MSG_SYSTEM = 0x0A
static constexpr std::string_view note="Death counter: ";
if(std::search(body.begin(),body.end(),note.begin(),note.end())!=body.end()){--played_silent_notes;break;}
}
if(!source_player_chat_type(uint8_t(type)) && type!=10 && type!=14 && type!=0x5e)break; // Other formats remain counted.
// Reviewed services retain prefix, payload and real sender identity.
// Unknown prefixes never become ordinary chat or trigger name queries.
if(r.le(4)==0xffffffffu){
RosterRealm context;context.realm_id=realm;context.virtual_address=address;
uint64_t addon_sender=0;
try{
// Peer addon traffic (party/raid/guild/officer/raid leader, any non-service prefix).
if(auto peer=turtle_peer_addon_message(body)){
addon_sender=peer->sender;
if(peer->native_type==4 || peer->native_type==5){if(!guild_id)break;}
const Character* from=peer->sender==selected.guid?&selected:nullptr;
if(!from)if(auto known=chat_players.find(peer->sender);known!=chat_players.end())from=&known->second;
if(!from){
if(!self_created || pending_chats.size()>=32 || chat_name_queries.size()>=256 || requests.size()>=4096)break;
pending_chats.push_back(body);
if(chat_name_queries.insert(peer->sender).second){Bytes query;le(query,peer->sender,8);requests.push_back({0x50,std::move(query)});}
break;
}
for(auto& part:forever_peer_addon_messages(*peer,*from,context))emit(0x4c0001,std::move(part));
// BigWigs /pull from a raid member also drives the native countdown timer.
if(auto pull=bigwigs_pull_seconds(*peer);pull && peer->sender!=selected.guid)emit(0x47003e,forever_start_timer(*pull,*pull,nullptr));
break;
}
auto message=turtle_server_addon_message(body);addon_sender=message.sender;
if(message.prefix=="TW_CHAT_MSG_WHISPER" && is_inspect_talent_reply(message)){
if(!inspect_talents || !inspect_talents->sent || message.sender!=inspect_talents->peer.first)break;
const auto current=authorized_inspect_peer();
if(!current || *current!=inspect_talents->peer || std::chrono::steady_clock::now()>=inspect_talents->until ||
inspect_talents->messages>=256){
inspect_talents.reset();break;
}
const auto& peer=entities.peer_players.at(message.sender).identity;
emit(0x4c0001,forever_inspect_talents_reply(message,peer,context));
++inspect_talents->messages;
if(message.text=="INSTalentEND;")inspect_talents.reset();
break;
}
if(is_inspect_transmog_query(message)){
// Octo InspectPaperDollFrame asks the inspected client; our addon answers from its saved looks.
const Character* asker=nullptr;
if(auto known=chat_players.find(message.sender);known!=chat_players.end())asker=&known->second;
else if(auto peer=entities.peer_players.find(message.sender);peer!=entities.peer_players.end())asker=&peer->second.identity;
if(!asker || asker->name.empty() || message.sender==selected.guid)break;
const auto now=std::chrono::steady_clock::now();
std::erase_if(transmog_askers,[&](const auto& row){return row.second.until<=now;});
if(transmog_askers.size()>=16 && !transmog_askers.contains(asker->name))break;
if(auto seen=transmog_askers.find(asker->name);seen!=transmog_askers.end() && seen->second.until-now>std::chrono::seconds(8))break;
transmog_askers[asker->name]={now+std::chrono::seconds(10),0};
emit(0x4c0001,forever_inspect_transmog_query(selected,context,asker->name));
break;
}
if(auto transmog=inspect_transmog_reply(message)){
if(!inspect_transmogs || !inspect_transmogs->sent || message.sender!=inspect_transmogs->peer.first)break;
const auto current=authorized_inspect_peer();
if(!current || *current!=inspect_transmogs->peer || std::chrono::steady_clock::now()>=inspect_transmogs->until ||
inspect_transmogs->messages>=32){
inspect_transmogs.reset();break;
}
emit(0x4c0001,forever_inspect_transmog_reply(selected,context,uint32_t(message.sender),*transmog));
++inspect_transmogs->messages;
break;
}
if(message.prefix=="TW_GUILDBANK" && (message.sender==selected.guid || guild_id)){
auto change=guild_bank.consume(message.text,message.sender==selected.guid);
for(auto& p:bank_presentation(change))emit(p.opcode,std::move(p.body));
}
if(message.prefix=="TW_TRANSMOG" && message.text.empty())break;
if(message.sender==selected.guid){
{for(auto& part:forever_server_addon_replies(message,selected,context))emit(0x4c0001,std::move(part));}break;
}
// Source broadcasts/forwarded whispers name the actor; all
// other reviewed services currently reply using self identity.
if(message.prefix!="TW_GUILDBANK" && message.prefix!="TW_CHAT_MSG_WHISPER")break;
if(message.prefix=="TW_GUILDBANK" && !guild_id)break;
if(auto known=chat_players.find(message.sender);known!=chat_players.end()){
{for(auto& part:forever_server_addon_replies(message,known->second,context))emit(0x4c0001,std::move(part));}break;
}
// Reuse the same native serializer as the known-sender path
// before issuing a name query. This provisional name is only
// an eligibility input and is never emitted or cached.
Character provisional{};provisional.guid=message.sender;provisional.name="?";
(void)forever_server_addon_reply(message,provisional,context);
if(!self_created || pending_chats.size()>=32 || chat_name_queries.size()>=256 || requests.size()>=4096)break;
pending_chats.push_back(body);
if(chat_name_queries.insert(message.sender).second){
Bytes query;le(query,message.sender,8);requests.push_back({0x50,std::move(query)});
}
}catch(const Error&){
++channel_semantic_holds;
trace_combat("addon_projection_held",0x96,selected.guid,addon_sender,0,0,0,1);
}
break;
}
uint64_t sender=0;
if(type!=10){
sender=turtle_chat_sender(body);
if((!sender && type!=14) || sender>0xffffffff)break;
}
// Turtle has no Battle.net account identifier. Keep it absent, retaining
// the real Turtle player GUID/name; never invent an external identity.
if((type==3 || type==4) && !guild_id)break;
if(type==3 || type==4)clubs.receive_chat(body);
if(type==10 || (type==14 && !sender) || sender==selected.guid){chat(body,selected,guild_id);break;}
if(auto known=chat_players.find(sender);known!=chat_players.end()){chat(body,known->second,0);break;}
// Validate all framing before retaining public chat. A provisional
// name is only a parser input, never emitted to the engine.
Character provisional{};provisional.guid=sender;provisional.name="?";
RosterRealm context;context.realm_id=realm;context.virtual_address=address;
if(type==0x5e)(void)turtle_hardcore_message(body);else (void)forever_chat(body,{provisional},context,0,true);
if(!self_created || pending_chats.size()>=32 || chat_name_queries.size()>=256 || requests.size()>=4096)break;
pending_chats.push_back(body);
if(chat_name_queries.insert(sender).second){Bytes query;le(query,sender,8);requests.push_back({0x50,std::move(query)});}
break;
}
case 0x236:
early_undercity.clear();undercity_settle.reset();undercity_generation=0;entities.undercity_seen.reset();entities.undercity_filled.reset();
character_bank.reset();
pet_bar.reset();trade.close();clear_mailbox();stable.reset();binder_offer.reset();auction_browse.reset();auction_personal.reset();auction_personal_deferred.clear();auction_commodity.reset();self_coinage.reset();ah_list_inflight=false;ah_list_retired=false;pet_rename_sent.clear();pet_rename_dropped=0;book_text_pending.clear();page_chains.clear();pet_unlearn_offer.reset();clear_inspect_selection();gossip.reset();pending_who.reset();bg_team={};pending_time_kinds.clear();observed_casts.clear();auras.pending_self_hits.clear();published_home_party=false;source_zone.reset();location=turtle_login_world(body);
emit(0x470046,Bytes(11)); // Verified fallback normal-world policy.
emit(0x47002f,forever_login_world(*location));break;
case 0x209:{
if(body!=Bytes(128))throw Error("unsupported stored Turtle account cache");
const auto player=forever_player_guid(selected.guid,realm);
auto times=pack_guid(player);le(times,clock,8);
// Per-character account data (bindings, config, macros, layouts, Edit Mode...) is stored client-locally
// (account_data_store.hpp); report each real time so the client keeps or requests it (#80). Global types 0.
for(uint32_t type=0;type<account_data::Types;++type)
le(times,uint64_t(account_data::per_character(type)?account_data::stored_time(internal_source_account,type,player):0),8);
emit(0x4701b6,std::move(times));
Bytes zones{0x0e,0x1c,0x38};for(unsigned i=0;i<3;++i)append(zones,std::span(reinterpret_cast<const uint8_t*>("Etc/UTC"),7));
emit(0x470124,std::move(zones));emit(0x470063,source(GW_CODEC_FEATURES,{}));break;
}
case 0x12a:{
auto initial=forever_initial_spells(body);
Reader r(initial.known);r.le(1);auto count=r.le(4);r.le(4);spells.clear();for(unsigned i=0;i<count;++i)spells.insert(uint32_t(r.le(4)));r.end();gw_diagnostics::journal().known(selected.guid,spells);talent_spells_ready=true;talent_snapshot_pending=talent_ready();
// The stock client selects its HUD layout by the active talent group.
// Publish the class group at login and worldport before known spells.
if (needs_class_talent_group) {
if (auto group = forever_class_talent_group(selected.cls))
emit(0x47007a, std::move(*group));
needs_class_talent_group = false;
}
emit(0x690019,std::move(initial.known));emit(0x69001a,std::move(initial.history));emit(0x69001b,Bytes(4));emit(0x69001c,Bytes(4));break;
}
case 0x139: case 0x13a: {
if (!self_created || !entities.self_presentation_ready || !location || !selected.guid || !realm || far_transfer || logout_complete) break;
auto channel = entities.spell_channels.event(packet.opcode, body, selected.guid,
forever_player_guid(selected.guid, realm), native_presentation_milliseconds(), cast_visual_profile::link, source);
output.push_back(std::move(channel));
entities.flush_channels(selected.guid, realm, location->map, source, output);
break;
}
case 0x137:auras.consume_duration(selected.guid,body);break;
case 0x129:{
auto buttons=forever_action_buttons(body);
extended_action_bars::merge(buttons,extended_action_bars::load(extended_action_bar_file()));
emit(0x470083,std::move(buttons));break;
}
case 0x155:emit(0x470011,forever_bind_point(body));break;
case 0x2c2:{
emit(0x4701f1,forever_initial_world_states(body));
// Tortoise sends INIT_WORLD_STATES {map, zone, ...} on every real zone entry and leaves
// local-channel moves to the client (Player::UpdateLocalChannels is empty).
if(self_created && !logout_complete && body.size()>=8){
const uint32_t zone=uint32_t(body[4])|uint32_t(body[5])<<8|uint32_t(body[6])<<16|uint32_t(body[7])<<24;
source_zone=zone;follow_source_zone();
}
break;
}
case 0x42:emit(0x4701b9,forever_login_time(body));break;
case 0xfd:if(body.size()!=32)throw Error("invalid Turtle tutorial packet");emit(0x470269,body);break;
case 0xa9:case 0x1f6:{
auto updates=turtle_object_updates(packet.opcode,body);
for(const auto& update:updates){
if(update.is_self_player_create(selected.guid))held_go_anims.clear();
if(update.kind==4)for(auto removed:update.removed){
if(removed==selected.guid)held_go_anims.clear();
else std::erase_if(held_go_anims,[&](const HeldGoAnim& h){return h.source==removed;});
}
}
if(pet_bar)for(const auto& update:updates){
const auto unit=pet_bar->state.unit;
if((update.is_self_player_create(selected.guid) && self_created) ||
(update.kind==4 && (std::count(update.removed.begin(),update.removed.end(),unit) ||
std::count(update.removed.begin(),update.removed.end(),selected.guid)))){
pet_bar.reset();break;
}
}
observe_quest_poi_updates(updates);
const auto self_create=std::find_if(updates.begin(),updates.end(),[&](const auto& u){
return u.is_self_player_create(selected.guid);
});
const bool real_self=self_create!=updates.end();
stage_early_undercity(packet,updates,real_self);
if(real_self)quest_status_refresh.reset_presentation();
else if(self_created && std::any_of(updates.begin(),updates.end(),[&](const auto& u){
return u.guid==selected.guid && u.kind==0 && std::any_of(u.fields.begin(),u.fields.end(),
[](const auto& field){return source_quest_log_field(field.first);});
}))quest_status_refresh.invalidate();
// Do not lose an owned item create merely because the authenticated
// Source server sent it in a separate packet before ThisIsYou. Stage
// only data belonging to the selected character; native publication and
// Source template queries wait for the actual SELF create below.
namespace F=gateway::turtle_entity_fields;
// A completed owned worldport has a new location but retains its
// transfer context until the destination SELF is received.
const bool pre_self_world=location && (!far_transfer ||
(transfer_owned() && far_transfer->phase==4 && location->map==far_transfer->destination.map));
if(!self_created && (!pre_self_world || !inventory.items.empty())){
pre_self_items.clear();pre_self_item_map.reset();
}
if(!self_created && pre_self_world && inventory.items.empty() && selected.guid && realm){
if(pre_self_item_map && *pre_self_item_map!=location->map){pre_self_items.clear();pre_self_item_map.reset();}
for(const auto& u:updates){
if(u.kind==4){for(auto id:u.removed)pre_self_items.erase(id);continue;}
if((u.kind==2 || u.kind==3) && (u.type==1 || u.type==2)){
// SELF's packet is translated by GW_CODEC_SELF. Its item
// creates must not be staged or published a second time.
if(real_self)continue;
auto value=[&](unsigned index){auto it=u.fields.find(index);return it==u.fields.end()?0u:it->second;};
auto owner=uint64_t(value(F::ITEM_FIELD_OWNER))|(uint64_t(value(F::ITEM_FIELD_OWNER+1))<<32);
auto entry=value(F::OBJECT_FIELD_ENTRY);
if((u.guid>>48)!=0x4000 || owner!=selected.guid || !entry || entry>0x7fffffff){pre_self_items.erase(u.guid);continue;}
for(auto [index,v]:u.fields){(void)v;if(index>=F::CONTAINER_END)throw Error("pre-self owned-item field bound");}
if(pre_self_items.size()>=4096 && !pre_self_items.contains(u.guid))throw Error("pre-self owned-item bound");
pre_self_items[u.guid]=u;pre_self_item_map=location->map;continue;
}
if(u.kind==0){
auto item=pre_self_items.find(u.guid);if(item==pre_self_items.end())continue;
for(auto [index,v]:u.fields){if(index>=F::CONTAINER_END)throw Error("pre-self owned-item field bound");item->second.fields[index]=v;}
auto value=[&](unsigned index){auto it=item->second.fields.find(index);return it==item->second.fields.end()?0u:it->second;};
auto owner=uint64_t(value(F::ITEM_FIELD_OWNER))|(uint64_t(value(F::ITEM_FIELD_OWNER+1))<<32);
auto entry=value(F::OBJECT_FIELD_ENTRY);
if(owner!=selected.guid || !entry || entry>0x7fffffff)pre_self_items.erase(item);
}
}
}
observe_talent_updates(updates);
const bool was_ghost=source_ghost==true;
if(observe_death_updates(updates) && self_created){
Bytes input{2};le(input,realm,2);le(input,selected.guid,8);
emit(0x470212,source(GW_CODEC_CORPSE_EVENT,input));
}
if(was_ghost && source_ghost==false && self_created){
// Original ResurrectPlayer clears the death-release location.
Bytes input{3};le(input,realm,2);le(input,selected.guid,8);le(input,0xffffffff,4);
for(unsigned i=0;i<3;++i)le(input,0,4);
emit(0x47017f,source(GW_CODEC_CORPSE_EVENT,input));
trace_release("graveyard_cleared");
}
entities.observe_source_fields(updates,selected.guid,packet.opcode);
for(const auto& update:updates){
if((update.kind==4 && std::find(update.removed.begin(),update.removed.end(),selected.guid)!=update.removed.end()) ||
(update.guid==selected.guid && self_created && (update.kind==2 || update.kind==3))){login_equip_casts.clear();pending_speeds.clear();pending_modes.clear();pending_knockbacks.clear();}
if(update.kind==4)std::erase_if(login_equip_casts,[&](const auto& row){
return std::find(update.removed.begin(),update.removed.end(),row.second.event.caster)!=update.removed.end();
});
if((update.kind==2 || update.kind==3) && inventory.items.contains(update.guid))
std::erase_if(login_equip_casts,[&](const auto& row){return row.second.event.caster==update.guid;});
if(update.guid==selected.guid && update.kind==0){
std::erase_if(login_equip_casts,[&](const auto& row){
if(!row.second.slot)return false;
auto field=update.fields.find(turtle_entity_fields::UNIT_FIELD_AURA+*row.second.slot);
return field!=update.fields.end() && field->second!=row.first;
});
}
}
auras.consume(updates);
if(boss_feed_on){
static constexpr std::string_view aura_events[4]{"SPELL_AURA_APPLIED","SPELL_AURA_REMOVED","SPELL_AURA_APPLIED_DOSE","SPELL_AURA_REMOVED_DOSE"};
for(const auto& t:auras.take_transitions())boss(aura_events[t.kind],t.spell,0,t.unit,t.stacks);
for(const auto& update:updates){
if(update.kind!=0)continue;
const auto health=update.fields.find(turtle_entity_fields::UNIT_FIELD_HEALTH);
const auto actor=entities.actors.find(update.guid);
if(health!=update.fields.end() && !health->second && actor!=entities.actors.end() && actor->second.kind==3)
boss("UNIT_DIED",0,0,update.guid);
}
}else auras.transitions.clear();
for(const auto& update:updates)if(update.guid==selected.guid && (update.kind==0 || update.type==4)){
if(auto money=update.fields.find(turtle_entity_fields::PLAYER_FIELD_COINAGE);money!=update.fields.end())self_coinage=money->second;
else if(update.kind==2 || update.kind==3)self_coinage=0; // a full create omits zero words
if(auto rank=update.fields.find(turtle_entity_fields::PLAYER_GUILDRANK);rank!=update.fields.end()){
if(rank->second>=10)throw Error("source guild rank bound");
observe_guild_rank(rank->second);
}
auto id = update.fields.find(turtle_entity_fields::PLAYER_GUILDID);
// A full self create omits zero words. When the selected character
// already had a guild, require an explicit zero to establish a leave.
const bool self_create = update.is_self_player_create(selected.guid);
const bool own_world = !logout_complete && (update.kind == 0 ? self_created : self_create);
if (own_world && !guild_id && own_guild_join == OwnGuildJoin::None &&
(id != update.fields.end() ? !id->second : self_create && !selected.guild))
own_guild_join = OwnGuildJoin::Guildless;
if(id!=update.fields.end() && guild_id!=id->second){
if (!own_world) own_guild_join = OwnGuildJoin::None;
else if (!id->second) own_guild_join = OwnGuildJoin::Guildless;
else if (!guild_id && own_guild_join == OwnGuildJoin::Guildless)
own_guild_join = OwnGuildJoin::AwaitingRoster;
else if (!guild_id && own_guild_join == OwnGuildJoin::SourceEventBeforeMembership)
own_guild_join = OwnGuildJoin::Presented;
else own_guild_join = OwnGuildJoin::None;
guild_id=id->second;
// Source Guild::AddMember consumes any outstanding invitation.
pending_guild_invitation=false;
guild_rank_info.reset();guild_roster_rights.reset();guild_management_roster.reset();guild_management_pending=false;guild_control_clear();
// Preserve the connection membership listener across join/leave/switch.
clubs.leave_guild();
guild_roster_context={};guild_rank_assignment.reset();guild_permissions.reset();
clear_bank();
pending_chats.clear();chat_name_queries.clear();
if(guild_id)refresh_guild_roster();
}
}
if(!self_created && real_self){
if(!location)throw Error("self create before world map");
if(pre_self_item_map && *pre_self_item_map==location->map && pre_self_world && inventory.items.empty()){
// SELF's own packet is already translated by GW_CODEC_SELF.
// Avoid creating its items twice if the Source server repeats
// a GUID in that packet. Recheck the latest owner before any
// earlier staged object can become visible to the client.
for(const auto& u:updates)if((u.kind==2 || u.kind==3) && (u.type==1 || u.type==2))pre_self_items.erase(u.guid);
for(auto it=pre_self_items.begin();it!=pre_self_items.end();){
auto value=[&](unsigned index){auto p=it->second.fields.find(index);return p==it->second.fields.end()?0u:p->second;};
auto owner=uint64_t(value(F::ITEM_FIELD_OWNER))|(uint64_t(value(F::ITEM_FIELD_OWNER+1))<<32);
auto entry=value(F::OBJECT_FIELD_ENTRY);
if(owner!=selected.guid || !entry || entry>0x7fffffff){it=pre_self_items.erase(it);continue;}
++it;
}
// SELF's serializer can only derive visible items from item
// creates in its own source packet. Project only when a staged
// item is actually in one of the source equipment slots.
for(unsigned slot=0;slot<19 && !initial_replayed_owned_items;++slot){
const auto index=F::PLAYER_FIELD_INV_SLOT_HEAD+2*slot;
auto low=self_create->fields.find(index),high=self_create->fields.find(index+1);
const auto id=(low==self_create->fields.end()?uint64_t(0):uint64_t(low->second)) |
(high==self_create->fields.end()?uint64_t(0):uint64_t(high->second)<<32);
initial_replayed_owned_items=pre_self_items.contains(id);
}
auto it=pre_self_items.begin();
while(it!=pre_self_items.end()){
auto end=it;unsigned count=0;while(end!=pre_self_items.end() && count<64){++end;++count;}
Bytes item_input;le(item_input,selected.guid,8);le(item_input,realm,2);le(item_input,location->map,4);le(item_input,count,4);
for(;it!=end;++it){const auto& u=it->second;le(item_input,u.guid,8);le(item_input,u.type,1);le(item_input,u.kind,1);le(item_input,u.fields.size(),2);for(auto [index,v]:u.fields){le(item_input,index,2);le(item_input,v,4);}}
auto encoded=source(GW_CODEC_INVENTORY,item_input);Reader item_reader(encoded);item_reader.le(2);
if(item_reader.le(4))emit(0x5e0000,std::move(encoded));
}
for(auto& [id,u]:pre_self_items){
auto entry=u.fields.at(F::OBJECT_FIELD_ENTRY);
inventory.request_owned_template(entry);
inventory.items.emplace(id,std::move(u));++inventory.creates;
}
}
pre_self_items.clear();pre_self_item_map.reset();
Bytes input;le(input,selected.guid,8);le(input,realm,2);le(input,address,4);le(input,location->map,4);le(input,selected.zone,4);
// Turtle authentication has no Battle.net identity (BnetAccount stays empty). WowAccount carries the
// gateway's stable per-login key (also in club member ids): with it empty, every censored auction row
// (no OwnerAccountID) compared equal to our account, so all commodities read as own-account items.
le(input,internal_source_account,4);le(input,0,4);cstring(input,selected.name);append(input,Bytes{selected.race,selected.cls,selected.gender});
le(input,packet.opcode,4);append(input,body);
// TC Player login while grouped: SetPartyType(HOME, NORMAL) is part of the self values.
// Seed it only from a complete, non-solo Source roster of this session.
if(loot.group && !loot.group->explicit_solo && !loot.group_transition){
Bytes seeded{0,1};append(seeded,input);emit(0x5e0000,source(GW_CODEC_SELF_PARTY_TYPE,seeded));published_home_party=true;
}else{
if(self_create->source_transport && (self_create->source_transport->guid>>48)==0x1FC0)
self_on_mo_transport.emplace(output.size(),self_create->source_transport->guid);
emit(0x5e0000,source(GW_CODEC_SELF,input));
}
// The self-create packet marks this player as ThisIsYou. Trinity's
// Map::SendInitSelf expects MOVE_INIT_ACTIVE_MOVER_COMPLETE in
// response; SET_ACTIVE_MOVER is reserved for later control
// handoffs (Unit::SetMovedUnit), so do not send it during login.
const auto res=self_create->fields.find(turtle_entity_fields::PLAYER_SELF_RES_SPELL);
entities.self_res_spell=res==self_create->fields.end()?0u:res->second;
entities.self_res_submitted=false;
self_created=true;
if(transfer_owned() && far_transfer->phase==4)far_transfer.reset();
// Source AddSpellMod can precede self-create. Project each received
// operation/kind once after native ThisIsYou. Unseen values retain
// the fresh received-state baseline; late packets still recompute.
std::set<uint8_t> replayed;
for(const auto& [key,value]:spell_modifier_aggregates){
const auto [percent,operation,bit]=key;
(void)value;(void)bit;(void)percent;
if(!replayed.emplace(operation).second)continue;
for(auto& translated:project_received_modifiers(selected.cls,
spell_modifier_aggregates,false,operation))
emit(translated.opcode,std::move(translated.body));
}
initial=true;
}
break;
}
case 0xaa:{
Reader r(body);auto removed=r.le(8);r.end();auras.forget(removed);
if(!early_undercity.empty())std::erase_if(early_undercity,[removed](const auto& pair){return pair.second.guid==removed;});
if(removed==selected.guid)held_go_anims.clear();
else std::erase_if(held_go_anims,[&](const HeldGoAnim& h){return h.source==removed;});
if(removed==selected.guid || removed==trade.partner)trade.close();
if(removed==selected.guid)observed_casts.clear();
else std::erase_if(observed_casts,[&](const auto& row){return row.first.first==removed || row.second.target==removed;});
if(pet_bar && (removed==selected.guid || removed==pet_bar->state.unit))pet_bar.reset();
if(!self_created)pre_self_items.erase(removed);
if(removed==selected.guid){clear_stance_cast();source_form.reset();pending_ghost_cast.reset();ghost_cast_packet_budget=0;source_ghost.reset();source_health.reset();release={};login_equip_casts.clear();pending_speeds.clear();pending_modes.clear();pending_knockbacks.clear();clear_talent_state();}
else std::erase_if(login_equip_casts,[&](const auto& row){return row.second.event.caster==removed;});
break;
}
default:primary_handled=false;break;
}
if(self_created && source_ghost==true && release.requested && release.corpse_valid && release.transfer){
// Source RePopAtGraveyard's real same-map controller transfer is the
// only location accepted here. Never label an arbitrary ghost login
// position or the corpse/body coordinates as a graveyard. The source
// witnesses may arrive in either order; publish once per real request.
Bytes input{3};le(input,realm,2);le(input,selected.guid,8);le(input,release.transfer->map,4);
for(unsigned i=0;i<3;++i)le(input,std::bit_cast<uint32_t>(release.transfer->position[i]),4);
emit(0x47017f,source(GW_CODEC_CORPSE_EVENT,input));trace_release("graveyard_published");release={};
}
if(!self_created && transfer_owned() && far_transfer->phase>=2 && far_transfer->phase<=4 && packet.opcode==0x58){
// Only a genuine response to this authenticated world's pending query
// may survive the same-owner transfer. It has no native presentation
// until a new SELF update is actually accepted.
bool peer_only=false;
if(inventory.cache_pending_template_reply(packet.body,&peer_only) && !peer_only)
inventory.deferred_template_projection=true;
}
bool entity_handled=false;
if(self_created && location && (remote_speeds::route(packet.opcode) || observer_motion::route(packet.opcode) || packet.opcode==0xa9 || packet.opcode==0x1f6 || packet.opcode==0x61 || packet.opcode==0xaa || packet.opcode==0xdd || packet.opcode==0x2ae || packet.opcode==0x2fb || packet.opcode==0x1eb || packet.opcode==0x58 || packet.opcode==0x112 || packet.opcode==0x143 || packet.opcode==0x144 || packet.opcode==0x51 || (packet.opcode<=UINT16_MAX && NativeEntityTranslation::peer_movement_opcode(uint16_t(packet.opcode))))){
entity_handled=true;
const auto replies_before=inventory.profile_replies;
if(packet.opcode==0xa9 || packet.opcode==0x1f6 || packet.opcode==0xaa || packet.opcode==0x1eb || packet.opcode==0x58 || packet.opcode==0x112){
auto owned=inventory.translate(packet,selected.guid,realm,location->map,initial,source,initial && initial_replayed_owned_items);
for(auto& item:owned)output.push_back(std::move(item));
if (internal_source_account && !far_transfer && !pending_teleport) {
auto& sets = equipment_sets;
if (packet.opcode == 0x112 && sets.pending && sets.pending->waiting &&
!packet.body.empty() && packet.body.front()) {
auto reason = packet.body.front();
sets.finish(reason == 4 || reason == 50 || reason == 53 || reason == 56 || reason == 62 ? 4 : 1);
} else if ((packet.opcode == 0xa9 || packet.opcode == 0x1f6 || packet.opcode == 0xaa) &&
(!sets.loaded || sets.pending)) {
if (sets.pending) sets.pending->next.reset();
try {
const auto carried = equipment_sets::accessible(inventory, sets.pending && equipment_bank_open());
if (!sets.loaded) {
auto catalogue = equipment_sets::load(equipment_set_file());
output.push_back({equipment_sets::Load, catalogue.packet()});
sets.loaded = true;
}
sets.advance(carried, equipment_sets::Clock::now());
} catch (const gateway::Error&) {
// Source may report a bag, its contents and their positions in separate updates.
}
}
}
}
if(packet.opcode==0x58 && replies_before!=inventory.profile_replies){
auto updates=entities.refresh_peer_item(inventory.last_profile,realm,address,location->map,inventory,source);
for(auto& update:updates)output.push_back(std::move(update));
}
const auto before_translate=output.size();
if(initial && !early_undercity.empty()){
for(const auto& [entry,pending]:early_undercity){
auto creates=entities.translate(pending.create,selected,realm,address,location->map,source,source_ghost==true,&inventory);
for(auto& create:creates)output.push_back(std::move(create));
}
early_undercity.clear();
}
auto translated=entities.translate(packet,selected,realm,address,location->map,source,source_ghost==true,&inventory);
for(auto& item:translated)output.push_back(std::move(item));
// TrinityCore Map::SendInitSelf (and Turtle's) create the passenger's transport before ThisIsYou. Created after
// it, 70334 cannot attach the arriving passenger, keeps the stale old-map position and drops them into the void
// (Orgrimmar-Undercity ride, 2026-11-24). Move the game-object create batch with that ship in front of SELF.
if(self_on_mo_transport){
const auto ship=entities.actors.find(self_on_mo_transport->second);
bool moved=false;
if(ship!=entities.actors.end() && ship->second.kind==5 && ship->second.sent)
for(size_t i=before_translate;i<output.size();++i)if(output[i].opcode==0x5e0000 && entities.created_in(output[i],ship->second)){
auto batch=std::move(output[i]);output.erase(output.begin()+i);
output.insert(output.begin()+self_on_mo_transport->first,std::move(batch));moved=true;break;
}
if(const char* log=std::getenv("GW_NATIVE_STARTUP_LOG");log && *log)if(FILE* f=std::fopen(log,"a")){
std::fprintf(f,"GW_SHIP self on transport %llx known=%d moved=%d\n",(unsigned long long)self_on_mo_transport->second,
int(ship!=entities.actors.end()),int(moved));std::fclose(f);}
}
if((packet.opcode==0x58 && replies_before!=inventory.profile_replies) ||
packet.opcode==0xa9 || packet.opcode==0x1f6 || packet.opcode==0xaa)
append_inspect_names(output,address);
sync_quest_items();
quest_status_refresh.observe(quest_bindings(QuestBindingSet::VisibleQuestGivers));
}
if(self_created && location && forced_reactions && (forced_reactions_dirty || !had_self_create)){
emit(0x5e0000,source(GW_CODEC_FORCED_REACTIONS,
forced_reactions_input(realm,uint16_t(location->map),selected.guid,*forced_reactions)));
forced_reactions_dirty=false;
}
// A main-switch miss can still be owned by the inventory/entity stage.
// A recognized route may legitimately emit nothing (pending metadata,
// unknown actor, or a retained update); output size is not acceptance.
// Record only after that stage returns, so its failures remain errors.
if(!primary_handled && !quest_handled && !social_handled && !entity_handled)
gw_diagnostics::journal().packet(gw_diagnostics::Stream::Unhandled,packet.opcode,uint32_t(body.size()));
if(self_created && location && (packet.opcode==0xa9 || packet.opcode==0x1f6 || packet.opcode==0xaa || packet.opcode==0x166 || packet.opcode==0x29f)){
loot_receipts.observe(inventory,selected.guid,initial);
RosterRealm target;target.realm_id=realm;target.virtual_address=address;
for(const auto& text:loot_receipts.take()){
Bytes notice{10};le(notice,0,4);le(notice,0,8);le(notice,text.size()+1,4);cstring(notice,text);le(notice,0,1);
emit(0x4c0001,forever_chat(notice,{selected},target,0,true));
}
}
if(self_created && pending_ghost_cast && source_ghost==true && location){
const auto& event=*pending_ghost_cast;auto visual=aura_visual_profile::link(event.spell);
if(visual && realm && realm<=8191 && location->map<=8191 && server_cast_counter<0xffffffffffULL){
auto id=forever_server_cast_guid(realm,location->map,event.spell,server_cast_counter+1);
auto payload=cast_payload(event,bindings(),id,visual,0,7);
if(auras.bind_server_self_cast(selected.guid,event.spell,id,realm)){
++server_cast_counter;emit(0x69002c,std::move(payload));
trace_combat("source_ghost_self_go",0x132,event.caster,event.target_unit,event.spell);
pending_ghost_cast.reset();ghost_cast_packet_budget=0;
}
}
}
if(self_created){
// LoadFromDB applies real equip casts before map/self creation. Wait
// only for the same login's genuine owned-item template, then present
// the original GO followed by the first confirmed aura snapshot.
// No recast, inventory action, PREPARE or source aura is manufactured.
for(auto it=login_equip_casts.begin();it!=login_equip_casts.end();){
const auto& event=it->second.event;bool reject=it->second.ambiguous || pending_cast.has_value();
auto unit=auras.units.find(selected.guid);
if(unit==auras.units.end() || !unit->second.initial || unit->second.source_type!=4)reject=true;
if(!reject){
const auto& spells=unit->second.spells;
if(std::count(spells.begin(),spells.end(),event.spell)!=1)reject=true;
else{
auto slot=unsigned(std::find(spells.begin(),spells.end(),event.spell)-spells.begin());
if(it->second.slot && *it->second.slot!=slot)reject=true;
it->second.slot=slot;
}
}
auto field=[&](unsigned index){auto v=inventory.player_fields.find(index);return v==inventory.player_fields.end()?0u:v->second;};
unsigned equipped=0;
for(unsigned slot=0;slot<19;++slot){auto index=turtle_entity_fields::PLAYER_FIELD_INV_SLOT_HEAD+2*slot;
if((uint64_t(field(index))|(uint64_t(field(index+1))<<32))==event.caster)++equipped;
}
if(equipped!=1)reject=true;
if(reject){it=login_equip_casts.erase(it);continue;}
auto item=inventory.items.find(event.caster);
if(item==inventory.items.end()){++it;continue;}
auto entry=item->second.fields.find(turtle_entity_fields::OBJECT_FIELD_ENTRY);
if(entry==item->second.fields.end()){it=login_equip_casts.erase(it);continue;}
auto profile=inventory.templates.find(entry->second);
if(profile==inventory.templates.end()){++it;continue;}
unsigned matches=0;bool equip=false;
if(profile->second.found)for(auto definition:profile->second.spells)if(definition.spell==event.spell){++matches;equip=definition.trigger==1;}
if(matches!=1 || !equip || !location || !realm || realm>8191 || location->map>8191 || event.spell>0x7fffff || server_cast_counter>=0xffffffffffULL){it=login_equip_casts.erase(it);continue;}
auto known=bindings();const auto& owned=inventory.owned_bindings();known.insert(owned.begin(),owned.end());
auto id=forever_server_cast_guid(realm,location->map,event.spell,server_cast_counter+1);
auto payload=cast_payload(event,known,id,aura_visual_profile::link(event.spell),0,7);
if(auras.bind_initial_equip_cast(selected.guid,event.spell,id,owned.at(event.caster),realm)){
++server_cast_counter;emit(0x69002c,std::move(payload));
}
it=login_equip_casts.erase(it);
}
// Emit only after the corresponding source-backed object creation.
// Metadata-delayed creatures retain pending slots until bound.
// Source GM visibility AddAura has no cast event; present it with the
// native self-cast context (CastID+NOCASTER) like native AddAura.
// A pending login equip event withholds SELF's initial aura output.
// Do not mint fallback provenance before that event can supply the
// real item context; otherwise both cast contexts occupy one slot.
const auto deferred_aura_owner=login_equip_casts.empty()?uint64_t(0):selected.guid;
if(location && !deferred_aura_owner)auras.bind_self_applied(selected.guid,realm,location->map,server_cast_counter);
if(location)auras.bind_casters(realm,location->map,server_cast_counter,deferred_aura_owner);
auto known=bindings();if(deferred_aura_owner)known.erase(deferred_aura_owner);
for(auto& item:auras.flush(known))output.push_back(std::move(item));
}
if(talent_reset_offer && !talent_reset_offer_bound()){
// Real source removal/recreation invalidates the NPC generation.
talent_reset_offer.reset();talent_notice="GWTURTLE1 RESET 0 0";
}
if(!talent_initial_snapshot && talent_ready())talent_snapshot_pending=true;
for(auto& packet:take_talent_presentation(address))output.push_back(std::move(packet));
// Numeric-only party projection trace (packets_error stream, pseudo-opcodes
// 0x7d00SS, size field = value); no names or member GUIDs are recorded.
auto party_trace=[&](uint32_t stage,uint32_t value){gw_diagnostics::journal().packet(gw_diagnostics::Stream::Error,0x7d0000u|stage,value);};
auto party_state=[&]{return uint32_t(self_created)|uint32_t(party.pending)<<1|uint32_t(bool(loot.group))<<2|uint32_t(loot.group_transition)<<3|
uint32_t(loot.group && loot.group->explicit_solo)<<4|uint32_t(party.shown)<<5|uint32_t(had_self_create)<<6;};
if(packet.opcode==0x7d){party_trace(1,uint32_t(body.size()));party_trace(2,party_state());}
if(self_created && !had_self_create)party_trace(7,party_state());
if(self_created && party.pending && loot.group && !loot.group_transition &&
(packet.opcode==0x7d || packet.opcode==0x51 || !had_self_create)){
// Reuse the authoritative roster already parsed for loot policy.
// Identity queries enrich presentation only; no membership is created.
if(!loot.group->explicit_solo)for(const auto& member:loot.group->members){
// Reuse an identity the peer stage already confirmed from a genuine Source 0x51
// (named, not blocked, current generation of a visible player actor) instead
// of queuing a duplicate lookup; stale or unavailable peers keep their own query.
if(member.guid && member.guid!=selected.guid && !chat_players.contains(member.guid) && chat_players.size()<4096){
const auto peer=entities.peer_players.find(member.guid);const auto actor=entities.actors.find(member.guid);
if(peer!=entities.peer_players.end() && actor!=entities.actors.end() && actor->second.kind==4 &&
peer->second.named && !peer->second.blocked && peer->second.generation==actor->second.generation &&
peer->second.identity.guid==member.guid)
chat_players[member.guid]=peer->second.identity;
}
if(member.guid==selected.guid || chat_players.contains(member.guid) ||
!member.guid || member.guid>UINT32_MAX || party.queried.contains(member.guid))continue;
if(chat_name_queries.contains(member.guid) || entities.peer_name_queries.contains(member.guid))continue;
party.queried.insert(member.guid);
if(requests.size()>=4096 || chat_name_queries.size()>=4096)throw Error("party identity query bound");
Bytes query;le(query,member.guid,8);requests.push_back({0x50,std::move(query)});
chat_name_queries.insert(member.guid);
}
const bool was_shown=party.shown;
party_trace(3,uint32_t(loot.group->members.size()));
// TC Group::AddMember / RemoveMember: PlayerData.PartyType[HOME] follows Source membership
// (party<->raid and held identities keep NORMAL). Publish real changes before the PartyUpdate;
// a clear also goes out when no PartyUpdate follows (solo before any roster was shown).
auto publish_home=[&](bool home){
if(home==published_home_party || !location)return;
Bytes kind{1,uint8_t(home)};le(kind,realm,2);le(kind,location->map,4);le(kind,selected.guid,8);
output.push_back({0x5e0000,source(GW_CODEC_SELF_PARTY_TYPE,kind)});published_home_party=home;
};
const bool home=!loot.group->explicit_solo;
if(auto update=party.take(*loot.group,selected,chat_players,realm,source)){
publish_home(home);
party_trace(5,uint32_t(loot.group->members.size()));
// Stage 8: group type (bit 24), own subgroup/assistant flags (bits 16-23), first member flags (bits 8-15), member count.
party_trace(8,uint32_t(loot.group->type==TurtleGroupType::raid)<<24|uint32_t(loot.group->own_flags)<<16|
(loot.group->members.empty()?0u:uint32_t(loot.group->members.front().flags))<<8|uint32_t(loot.group->members.size()));
output.push_back(std::move(*update));
}else{
if(!home)publish_home(false);
uint32_t missing=0;for(const auto& m:loot.group->members)if(m.guid!=selected.guid && !chat_players.contains(m.guid))++missing;
party_trace(4,missing);party_trace(6,uint32_t(std::min<uint64_t>(party.held,0xffff)));
}
// The 70334 client never asks for the icon list; Source answers 0xFF with the full set.
if(!was_shown && party.shown && requests.size()<4096)requests.push_back({0x321,Bytes{0xff}});
}
{std::vector<LegacyPacket> bg;service_bg_positions(bg);for(auto& p:bg)emit(p.opcode,std::move(p.body));}
if(stable && !stable->published && self_created && !logout_complete && location){
bool missing=false;
for(const auto& p:stable->list.pets)if(!entities.templates.contains(p.entry))missing=true;
if(!missing){
try{
auto dto=pet_stable_snapshot_input(realm,location->map,selected.guid,stable->list,
[&](uint32_t e){const auto& t=entities.templates.at(e);return t.found?t.display:0u;});
emit(0x5e0000,source(GW_CODEC_PET_STABLE,dto));
stable->published=true;
}catch(const Error&){stable.reset();++stable_holds;} // includes a codec without the mode
}
}
if(auction_personal && auction_personal->snapshot.complete && !auction_personal->awaiting && self_created && !logout_complete){
// Wait for every real Source template (0x58); then publish the whole TC-sorted personal list once.
bool missing=false;
for(const auto& a:auction_personal->snapshot.rows)if(!inventory.peer_template(a.entry)){inventory.request_peer_template(a.entry);missing=true;}
if(!missing){
try{
std::map<uint32_t,AuctionItemFacts> facts;
for(const auto& a:auction_personal->snapshot.rows){
const auto* t=inventory.peer_template(a.entry);if(!t->found)continue;
facts[a.entry]=AuctionItemFacts{t->cls,t->subclass,t->item_level,t->required_level,t->stack,t->container_slots,t->required_skill_rank,t->name};
}
auto result=auction_personal_result(auction_personal->snapshot,[&](uint32_t e)->const AuctionItemFacts*{auto f=facts.find(e);return f==facts.end()?nullptr:&f->second;},
auction_personal->sorts,auction_personal->owned,realm);
emit(auction_personal->owned?0x4702f9:0x4702fa,source(GW_CODEC_AUCTION_PERSONAL,auction_personal_input(result)));
}catch(const Error& e){++auction_holds;gw_inv_log("GW_AH personal-hold owned=%d rows=%zu why=%s\n",auction_personal->owned?1:0,auction_personal->snapshot.rows.size(),e.what());} // includes a codec without the mode
auction_personal.reset();
}
}
if(self_created && !logout_complete)start_deferred_personal_list();
if(!held_go_anims.empty()){
if(!go_anim_world_active())held_go_anims.clear();
else{
const auto now=std::chrono::steady_clock::now();
std::erase_if(held_go_anims,[&](HeldGoAnim& h){
if(now>=h.until){gw_inv_log("GW_GO custom-anim expired go=%llx anim=%u\n",(unsigned long long)h.source,unsigned(h.anim));return true;}
if(h.owner!=selected.guid || h.realm!=realm || h.map!=location->map)return true;
const auto* actor=go_anim_actor(h.source);
if(!actor)return h.generation!=0 || entities.actors.contains(h.source);
if(h.generation && h.generation!=actor->generation)return true;
h.generation=actor->generation; // bind the first observed pre-template incarnation
if(!actor->sent)return false;
if(!actor->eligible || actor->modern==Guid128{})return true;
Bytes out;wf_guid(out,actor->modern);le(out,h.anim,4);le(out,0,1);emit(0x470068,std::move(out));
gw_inv_log("GW_GO custom-anim replayed go=%llx anim=%u\n",(unsigned long long)h.source,unsigned(h.anim));
return true;
});
}
}
if(auction_browse &&auction_browse->snapshot.complete && !auction_browse->ordered && self_created && !logout_complete){
// Wait for every real Source template (0x58); then publish the first bucket window.
bool missing=false;
for(const auto& a:auction_browse->snapshot.rows)if(!inventory.peer_template(a.entry)){inventory.request_peer_template(a.entry);missing=true;}
if(!missing){
try{
if(auction_browse->specific_keys){
// Name search is a superset: keep only the requested item's rows.
const auto want=[&]{for(const auto& a:auction_browse->snapshot.rows){const auto* t=inventory.peer_template(a.entry);if(t->found && t->name==auction_browse->query.name)return a.entry;}return 0u;}();
std::erase_if(auction_browse->snapshot.rows,[&](const TurtleAuctionRow& a){return a.entry!=want;});
}
else if(!auction_browse->by_item && !auction_query_exact(auction_browse->query)){
// Superset Source page: keep exactly the rows the native category/filters ask for.
const auto& q=auction_browse->query;
std::erase_if(auction_browse->snapshot.rows,[&](const TurtleAuctionRow& a){
const auto* t=inventory.peer_template(a.entry);
return !t->found || !auction_row_matches(q,t->cls,auction_native_subclass(a.entry,t->cls,t->subclass),t->inventory_type,t->quality,t->required_level);});
}
std::map<uint32_t,AuctionItemFacts> facts;
for(const auto& a:auction_browse->snapshot.rows){
const auto* t=inventory.peer_template(a.entry);if(!t->found)continue;
facts[a.entry]=AuctionItemFacts{t->cls,t->subclass,t->item_level,t->required_level,t->stack,t->container_slots,t->required_skill_rank,t->name};
}
AuctionCommodityOmissions omitted;
auto ordered=auction_buckets(auction_browse->snapshot,[&](uint32_t e)->const AuctionItemFacts*{auto f=facts.find(e);return f==facts.end()?nullptr:&f->second;},
auction_browse->query.sorts,selected.guid,&omitted);
auction_commodity_omitted+=omitted.total();
if(auction_browse->by_key){
// Bucket-key list: answer for exactly the requested key (item + item level), or the client drops it.
const auto key=*auction_browse->by_key;const auto* t=inventory.peer_template(key.item);const bool stackable=t && t->found && t->stack>1;
AuctionItemsResult r;
if(auto b=std::find_if(ordered.begin(),ordered.end(),[&](const AuctionBucket& x){return x.key==key;});b!=ordered.end())
r=auction_items_result(*b,auction_browse->by_item_sorts,0,realm);
r.key=key;if(stackable)r.list_type=1;
emit(0x4702f7,source(GW_CODEC_AUCTION_ITEMS,auction_items_input(r)));
}
else if(auction_browse->by_item)
emit(0x4702f7,source(GW_CODEC_AUCTION_ITEMS,auction_items_input(auction_items_by_item_result(ordered,*auction_browse->by_item,auction_browse->by_item_sorts,0,realm,[&]{const auto* t=inventory.peer_template(*auction_browse->by_item);return t && t->found && t->stack>1;}()))));
else{
auto reply=source(GW_CODEC_AUCTION_BUCKETS,auction_buckets_input(auction_buckets_result(ordered,0,auction_browse->query.filters)));
// TC AuctionListBucketsResult ends with Bits<1>(BrowseMode) Bits<1>(HasMore): MSB of the last byte.
if(auction_browse->specific_keys && !reply.empty())reply.back()|=0x80;
emit(0x4702f6,std::move(reply));
}
gw_inv_log("GW_AH published rows=%zu by_item=%d keys=%d\n",auction_browse->snapshot.rows.size(),auction_browse->by_item?1:0,auction_browse->specific_keys?1:0);
auction_browse->ordered=std::move(ordered);
}catch(const Error&){auction_browse.reset();++auction_holds;} // includes a codec without the mode
}
}
for(auto& p:take_social_presentation(codec))output.push_back(std::move(p));
// Definition replies can finish a POI request during normal Source input.
// Publish it in that same engine bundle rather than waiting for an unrelated
// native action to request local presentation.
if(auto p=take_quest_poi())output.push_back(std::move(*p));
if(auto p=take_quest_poi_60141())output.push_back(std::move(*p));
if(auto summon=take_summon_presentation(address))output.push_back(std::move(*summon));
present_guild(address,output);
if(auto bar=take_pet_bar())output.push_back(std::move(*bar));
if(pet_unlearn_offer && !pet_unlearn_offer_live())pet_unlearn_offer.reset();
service_undercity(address,codec,output,false);
if(pending_execute)
source_combat_events::insert_spell_execute(output,pending_execute->first,body,pending_execute->second,
inventory.owned_bindings(),WorldBundleRecordLimit,GW_CODEC_BOUND);
return world_bundle(output);
}
void NativeWorldTranslation::follow_source_zone(){
if(!source_zone)return;
// Unknown zone IDs give no names: zone channels are left (and parked), never guessed.
const auto* z=gateway::source_zones::find(*source_zone);
for(auto& q:chat_channels.follow_zone(z?std::optional<std::string_view>(z->name):std::nullopt,z && z->capital)){
if(requests.size()>=4096)throw Error("zone channel request bound");
chat_channels.sent(q);requests.push_back({q.opcode,std::move(q.body)});
}
}
bool NativeWorldTranslation::bg_positions_due() const noexcept{
const bool on=self_created && !logout_complete && location && location->map==489 && !far_transfer && source_team_for_race(selected.race);
if(!on)return bg_positions_shown || bg_positions_pending;
const auto now=std::chrono::steady_clock::now();
return bg_positions_pending ? now>=bg_positions_sent+std::chrono::seconds(10) : now>=bg_positions_next;
}
void NativeWorldTranslation::service_bg_positions(std::vector<LegacyPacket>& output){
const bool on=self_created && !logout_complete && location && location->map==489 && !far_transfer && source_team_for_race(selected.race);
if(!on){
// Departure or lost context: one explicit empty list while still presented, then retire.
// Includes a far transfer out of WSG (Source 0x3E), ahead of its NewWorld presentation.
if(bg_positions_shown && self_created && !logout_complete){Bytes empty;le(empty,0,4);output.push_back({0x4d0006,std::move(empty)});}
if(bg_positions_shown || bg_positions_pending)std::erase_if(requests,[](const LegacyPacket& p){return p.opcode==0x2e9;}); // only the unsent poll
bg_positions_shown=false;bg_positions_pending=false;bg_positions_next={};return;
}
// Servicing runs on Source traffic (continuous inside a battleground) and opportunistic local
// presentation; the host has no timer. A poll still queued (unsent) is never appended again.
// The Source reply has no sequence: a late original answering a retry is still genuine data.
const auto now=std::chrono::steady_clock::now();
if(std::any_of(requests.begin(),requests.end(),[](const LegacyPacket& p){return p.opcode==0x2e9;})){bg_positions_sent=now;return;}
if(bg_positions_pending && now>=bg_positions_sent+std::chrono::seconds(10))bg_positions_pending=false; // bounded retry
if(!bg_positions_pending && now>=bg_positions_next && requests.size()<4096){
requests.push_back({0x2e9,{}});bg_positions_pending=true;bg_positions_sent=now;
bg_positions_next=now+std::chrono::milliseconds(5000); // TC PLAYER_POSITION_UPDATE_INTERVAL
}
}
uint64_t NativeWorldTranslation::current_pet_command_unit(Reader& r) const{
// Tortoise PetHandler acts only on GetPet()/GetCharm(); the gateway's shown pet bar is exactly
// that Source unit (take_pet_bar enforces ownership, generation and current control).
const auto unit=bound_legacy_guid(r,bindings());
// Fixed tags identify the first existing failed predicate; no identities or values.
if(!self_created)throw Error("pet command outside the current Source pet bar [reason=self-not-created]");
if(pending_teleport)throw Error("pet command outside the current Source pet bar [reason=pending-teleport]");
if(far_transfer)throw Error("pet command outside the current Source pet bar [reason=far-transfer]");
if(!pet_bar)throw Error("pet command outside the current Source pet bar [reason=bar-missing]");
if(!pet_bar->shown)throw Error("pet command outside the current Source pet bar [reason=bar-unshown]");
if(pet_bar->state.unit!=unit)throw Error("pet command outside the current Source pet bar [reason=bar-unit-mismatch]");
// Revalidate live Source control (charm field for charms, summon field for pets), not only the cached bar.
auto actor=entities.actors.find(unit);const auto& control=entities.self_controlled[(unit>>48)==0xf140?1:0];
if(actor==entities.actors.end())throw Error("pet command unit is no longer under current Source control [reason=actor-missing]");
if(!actor->second.sent)throw Error("pet command unit is no longer under current Source control [reason=actor-unsent]");
if(!actor->second.eligible)throw Error("pet command unit is no longer under current Source control [reason=actor-ineligible]");
if(actor->second.generation!=pet_bar->generation)throw Error("pet command unit is no longer under current Source control [reason=actor-generation-mismatch]");
if(control.known!=3)throw Error("pet command unit is no longer under current Source control [reason=control-unknown]");
if(control.source_guid()!=unit)throw Error("pet command unit is no longer under current Source control [reason=control-unit-mismatch]");
if(control.presented!=actor->second.modern)throw Error("pet command unit is no longer under current Source control [reason=control-presentation-mismatch]");
return unit;
}
bool NativeWorldTranslation::pet_bar_spell(uint32_t spell) const noexcept{
if(!pet_bar || !spell)return false;
for(auto a:pet_bar->state.actions)if((a&0xffffff)==spell)return true; // PetSpellInitialize: spell:24 | state:8
for(auto b:pet_bar->state.buttons){auto type=b>>24;if((type==0x01 || type==0x81 || type==0xc1) && (b&0xffffff)==spell)return true;}
return false;
}
uint32_t NativeWorldTranslation::owned_item_text(std::span<const uint8_t> body,Guid128* native) const{
// CMSG_ITEM_TEXT_QUERY {Guid Id}: an owned item whose Source ITEM_FIELD_ITEM_TEXT_ID (45) is set.
Reader q(body);const auto& items=inventory.owned_bindings();
auto legacy=bound_legacy_guid(q,items);q.end();
auto item=inventory.items.find(legacy);if(item==inventory.items.end())throw Error("item text query outside owned inventory");
auto text=item->second.fields.find(45);
if(text==item->second.fields.end() || !text->second)throw Error("item has no Source text");
if(native)*native=items.at(legacy);
return text->second;
}
bool NativeWorldTranslation::pet_unlearn_offer_live() const{
if(!pet_unlearn_offer || !self_created || !pet_bar || !pet_bar->shown || pet_bar->state.unit!=pet_unlearn_offer->pet)return false;
auto pet=entities.actors.find(pet_unlearn_offer->pet);auto trainer=entities.actors.find(pet_unlearn_offer->trainer);
const auto& control=entities.self_controlled[1]; // UNIT_FIELD_SUMMON = this pet, presented
if(pet==entities.actors.end() || control.known!=3 || control.source_guid()!=pet_unlearn_offer->pet || control.presented!=pet->second.modern)return false;
auto known=bindings();
return pet!=entities.actors.end() && pet->second.sent && pet->second.generation==pet_unlearn_offer->pet_generation &&
trainer!=entities.actors.end() && trainer->second.sent && trainer->second.generation==pet_unlearn_offer->trainer_generation &&
known.contains(pet_unlearn_offer->trainer);
}
std::optional<Bytes> NativeWorldTranslation::close_interaction(std::span<const uint8_t> body){
Reader r(body);const auto guid=unpack_guid(r,16);r.end();
if(pet_unlearn_offer){auto known=bindings();auto m=known.find(pet_unlearn_offer->trainer);
if(m==known.end() || Bytes(m->second.begin(),m->second.end())==guid)pet_unlearn_offer.reset();}
// An explicit client close of the selected trainer also retires the armed authority (fail closed).
if(last_gossip_npc){auto known=bindings();auto m=known.find(last_gossip_npc->guid);
if(m==known.end() || Bytes(m->second.begin(),m->second.end())==guid)last_gossip_npc.reset();}
{auto known=bindings();auto same=[&](uint64_t npc){auto m=known.find(npc);return m==known.end() || Bytes(m->second.begin(),m->second.end())==guid;};
if(character_bank && same(character_bank->banker))character_bank.reset();
if(auction_browse && same(auction_browse->auctioneer))auction_browse.reset();
// Guild vault: the Source bank protocol has no close request; only native state ends.
if(bank_window && Bytes(bank_window->modern.begin(),bank_window->modern.end())==guid)clear_bank();
if(auction_personal && same(auction_personal->auctioneer))auction_personal.reset();
if(auction_commodity && same(auction_commodity->auctioneer))cancel_unsent_commodity();
// A cached result and the outstanding request can belong to different auctioneers.
bool withdrew_active_page = false;
std::erase_if(requests, [&](const LegacyPacket& packet) {
uint16_t reply;
switch (packet.opcode) {
case 0x258: reply = 0x25c; break;
case 0x259: reply = 0x25d; break;
case 0x264: reply = 0x265; break;
default: return false;
}
Reader page(packet.body);
const auto npc = page.le(8);
if (!same(npc)) return false;
if (ah_list_inflight && npc == ah_list_npc && reply == ah_list_reply)
withdrew_active_page = true;
return true;
});
if (withdrew_active_page) {
ah_list_inflight = false;
ah_list_retired = false;
} else if (ah_list_inflight && same(ah_list_npc)) {
ah_list_retired = true;
}
std::erase_if(auction_personal_deferred,[&](const auto& d){Reader q(d.second);try{return same(bound_legacy_guid(q,known));}catch(const Error&){return true;}});}
if(!stable || !location || Bytes(stable->master.begin(),stable->master.end())!=guid)return std::nullopt;
const bool shown=stable->published;stable.reset();
if(!shown)return std::nullopt;
return pet_stable_close_input(realm,location->map,selected.guid); // K2: StableMaster cleared, rows kept
}
std::optional<std::pair<uint32_t,Bytes>> NativeWorldTranslation::auction_local_request(uint32_t opcode,std::span<const uint8_t> body) const{
if(!auction_browse || !auction_browse->ordered || !self_created || logout_complete)return std::nullopt;
const auto known=bindings();Reader r(body);
if(bound_legacy_guid(r,known)!=auction_browse->auctioneer)return std::nullopt;
try{
if(opcode==0x3f0066){
auto q=native_auction_browse_query(body);
if(!q.offset)return std::nullopt; // a new search always refreshes from the Source
const auto& p=auction_browse->query;
const bool same=q.name==p.name && q.min_level==p.min_level && q.max_level==p.max_level && q.filters==p.filters &&
q.classes.size()==p.classes.size() && q.sorts.size()==p.sorts.size() &&
std::equal(q.classes.begin(),q.classes.end(),p.classes.begin(),[](const auto& a,const auto& b){
return a.item_class==b.item_class && a.subclasses.size()==b.subclasses.size() &&
std::equal(a.subclasses.begin(),a.subclasses.end(),b.subclasses.begin(),[](const auto& x,const auto& y){return x.inv_type_mask==y.inv_type_mask && x.subclass==y.subclass;});}) &&
std::equal(q.sorts.begin(),q.sorts.end(),p.sorts.begin(),[](const auto& a,const auto& b){return a.order==b.order && a.reverse==b.reverse;});
if(!same || q.offset>auction_browse->ordered->size())return std::nullopt;
return std::pair{uint32_t(GW_CODEC_AUCTION_BUCKETS),auction_buckets_input(auction_buckets_result(*auction_browse->ordered,q.offset,q.filters))};
}
if(opcode==0x3f0067){
const auto q=native_auction_items_query(body);
const auto& buckets=*auction_browse->ordered;
auto b=std::find_if(buckets.begin(),buckets.end(),[&](const AuctionBucket& x){return x.key==q.key;});
if(b==buckets.end() || q.offset>b->rows.size())return std::nullopt; // never synthesized
return std::pair{uint32_t(GW_CODEC_AUCTION_ITEMS),auction_items_input(auction_items_result(*b,q.sorts,q.offset,realm))};
}
if(opcode==0x3f0068){
const auto q=native_auction_items_by_item_query(body);
const auto& buckets=*auction_browse->ordered;
if(std::none_of(buckets.begin(),buckets.end(),[&](const AuctionBucket& x){return x.key.item==q.item;}))return std::nullopt;
auto result=auction_items_by_item_result(buckets,q.item,q.sorts,q.offset,realm);
if(q.offset>result.total_count)return std::nullopt;
return std::pair{uint32_t(GW_CODEC_AUCTION_ITEMS),auction_items_input(result)};
}
}catch(const Error&){}
return std::nullopt;
}
size_t NativeWorldTranslation::party_stats_request(std::span<const uint8_t> body){
// RequestPartyMemberStats: bit PartyIndex, u32 count, [u8 index], packed GUID*.
// Source CMSG_REQUEST_PARTY_MEMBER_STATS (0x27F) takes one u64 GUID per request.
if(!loot.group || loot.group->explicit_solo)throw Error("party stats request outside a Source group");
Reader r(body);auto bits=r.le(1);if(bits&0x7f)throw Error("party stats bits");
auto count=r.le(4);if(count>40)throw Error("party stats target bound");
if((bits&0x80) && r.le(1)!=0)throw Error("party stats foreign party index");
std::vector<uint64_t> ids;
for(uint64_t i=0;i<count;++i){
auto g=unpack_guid(r,16);uint64_t id=0;
for(const auto& m:loot.group->members){auto e=forever_player_guid(m.guid,realm);if(std::equal(g.begin(),g.end(),e.begin())){id=m.guid;break;}}
if(id)ids.push_back(id);
}
r.end();
if(requests.size()+ids.size()>4096)throw Error("party stats request queue bound");
for(auto id:ids){Bytes out;le(out,id,8);requests.push_back({0x27f,std::move(out)});}
return ids.size();
}
std::optional<uint32_t> NativeWorldTranslation::recent_dispel(uint64_t caster) const {
auto it=dispel_go.find(caster);
if(it==dispel_go.end() || std::chrono::steady_clock::now()>it->second.second)return {};
return it->second.first;
}