Files

1393 lines
93 KiB
C++

#include "diagnostics_journal.hpp"
#include "presentation_clock.hpp"
#include "gateway/cast_visual_profile.hpp"
#include "gateway/aura_visual_profile.hpp"
#include "gateway/unit_presentation.hpp"
#include "gateway/creature_unit_classes.hpp"
#include "../src/creature_display_scale.hpp"
#include "object_update_layout_guard.hpp"
#include <atomic>
#include <cstdarg>
#include <cstdio>
#include <cstdlib>
static void gw_go_log(const char* fmt,...){ // LOCAL GO-create trace -> GW_NATIVE_STARTUP_LOG
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);
}
#include <string_view>
#include "entity_translation.hpp"
#include "gateway/exploration.hpp"
#include "serializer.h"
#include "gateway/object_updates.hpp"
#include "gateway/corpse.hpp"
#include "gateway/turtle_entity_profile.hpp"
#include "gateway/gameplay.hpp"
#include "gateway/remote_speeds.hpp"
#include "gateway/observer_motion.hpp"
#include "gateway/pet_presentation.hpp"
#include "gateway/gameobject_queries.hpp"
#include "gateway/wmo_game_object_displays.hpp"
#ifdef GW_GAMEOBJECT_AUTHORITY_PROFILE_HEADER
#include GW_GAMEOBJECT_AUTHORITY_PROFILE_HEADER
// Gitea #8: the build scripts kept passing the 11-17 profile, which has no lifts (Undercity 20649-20657) and no MO
// transports (zeppelins/ships), so every rebuild silently dropped them. Refuse to build against such a profile.
static_assert([]{bool lift=false,ship=false;for(const auto& r:gateway::gameobject_authority_profile::Rows){lift|=r.entry==20649;ship|=r.entry==164871;}return lift&&ship;}(),
"GO authority profile lacks transports (Undercity lift 20649 / zeppelin 164871): stale GW_GAMEOBJECT_AUTHORITY_PROFILE_HEADER");
#endif
#include <algorithm>
#include <bit>
#include <cmath>
using namespace gateway;
static_assert(SourceQuestLogFirstField==turtle_entity_fields::PLAYER_QUEST_LOG_1_1);
static_assert(SourceQuestLogFirstField+SourceQuestLogSlots*SourceQuestLogWordsPerSlot-1==turtle_entity_fields::PLAYER_QUEST_LOG_LAST_3);
namespace {
uint32_t action_motion_reason(std::string_view);
std::atomic<uint64_t> action_event_sequence{0};
// Tortoise Unit::IsSpiritService checks these two UNIT_NPC_FLAGS bits.
constexpr uint32_t spirit_service_flags=0x20u|0x40u;
Bytes header(const Character& self,uint16_t realm,uint32_t address,uint32_t map){
Bytes b;le(b,self.guid,8);le(b,realm,2);le(b,address,4);le(b,map,4);le(b,self.zone,4);
le(b,0,4);le(b,0,4);cstring(b,self.name);append(b,Bytes{self.race,self.cls,self.gender});return b;
}
uint32_t create_count(const Bytes& body){Reader r(body);r.le(2);return uint32_t(r.le(4));}
}
namespace {
void append_undercity_create(Bytes& body,const UndercityTransportSpawn& row){
namespace F=turtle_entity_fields;
constexpr unsigned Scale=4, Rotation=10, Position=15;
Bytes raw;le(raw,NativeEntityTranslation::undercity_source_guid(row),8);
le(body,2,1);append(body,pack_guid(raw));le(body,5,1);
// vmangos type 11 has a zero stationary movement block and world XYZO in GO fields.
le(body,0x40,1);body.insert(body.end(),16,0);
std::map<unsigned,uint32_t> fields{{F::OBJECT_FIELD_ENTRY,row.entry},{Scale,std::bit_cast<uint32_t>(1.f)},
{F::GAMEOBJECT_DISPLAYID,row.display},{F::GAMEOBJECT_FLAGS,40},{F::GAMEOBJECT_STATE,1},{F::GAMEOBJECT_TYPE_ID,11}};
const std::array<float,4> position{row.x,row.y,row.z,row.o};
for(unsigned i=0;i<4;++i){
fields[Rotation+i]=std::bit_cast<uint32_t>(row.rot[i]);
fields[Position+i]=std::bit_cast<uint32_t>(position[i]);
}
uint32_t mask=0;
for(const auto& field:fields)mask|=1u<<field.first;
le(body,1,1);le(body,mask,4);
for(const auto& field:fields)le(body,field.second,4);
}
}
void NativeEntityTranslation::fill_undercity(const Character& self,uint16_t realm,uint32_t address,
const Codec& codec,std::vector<LegacyPacket>& output){
const auto missing=~(undercity_seen|undercity_filled);
if(missing.none())return;
Bytes body;le(body,missing.count(),4);le(body,0,1);
for(size_t i=0;i<UndercityTransportSpawns.size();++i)
if(missing[i])append_undercity_create(body,UndercityTransportSpawns[i]);
Bytes input=header(self,realm,address,0);le(input,0xa9,4);append(input,body);
auto result=codec(GW_CODEC_GAMEOBJECTS,input);
if(create_count(result)!=missing.count())throw Error("Undercity transport serializer identity mismatch");
output.push_back({0x5e0000,std::move(result)});
undercity_filled|=missing;
}
void NativeEntityTranslation::leave_undercity(uint16_t realm,bool remove_from_client,std::vector<LegacyPacket>& output){
if(remove_from_client && undercity_filled.any()){
std::vector<Guid128> ids;
for(size_t i=0;i<UndercityTransportSpawns.size();++i)if(undercity_filled[i]){
const auto& row=UndercityTransportSpawns[i];
ids.push_back(forever_game_object_guid(undercity_source_guid(row),row.entry,realm,0));
}
output.push_back({0x5e0000,forever_object_removal(0,{},ids)});
}
undercity_filled.reset();
}
bool NativeEntityTranslation::native_creature_query(std::span<const uint8_t> body){
// TC QueryCreature::Read (Classic 1.60): 6-bit count (MSB first, flushed), then u32 creature IDs.
std::vector<uint32_t> entries;
try{
Reader r(body);const auto head=r.le(1);if(head&3)return false;
const auto count=head>>2;if(!count || count>16)return false;
for(uint64_t i=0;i<count;++i){const auto e=uint32_t(r.le(4));if(!e || e>0x7fffff)return false;entries.push_back(e);}
r.end();
}catch(const Error&){return false;}
for(auto e:entries){
if(!native_asked.contains(e) && native_asked.size()>=4096)return false;
if(!queries.contains(e) && requests.size()>=4096)return false;
}
for(auto e:entries){
native_asked.insert(e);
if(queries.insert(e).second)requests.push_back({0x60,turtle_creature_query(e)});
}
return true;
}
void NativeEntityTranslation::invalidate_self_display() noexcept{
self_display_guid=0;self_display_known=0;self_source_scale=0;self_appearance_after_morph=false;
++self_display_generation;equipment_visibility.clear();
}
void NativeEntityTranslation::observe_equipment_visibility(const LegacyObjectUpdate& u,uint64_t self,uint16_t realm,uint32_t map){
const bool create=(u.kind==2 || u.kind==3) && u.type==4;
if(!self || u.guid!=self || (!create && u.kind!=0))return;
auto flag=u.fields.find(turtle_entity_fields::PLAYER_FLAGS);
if(create)equipment_visibility.begin(self,realm,map,flag==u.fields.end()?0:flag->second);
else if(!equipment_visibility.bound(self,realm,map))equipment_visibility.clear();
else if(flag!=u.fields.end())equipment_visibility.observe(flag->second);
}
void NativeEntityTranslation::observe_self_display(const LegacyObjectUpdate& u,uint64_t selected,uint16_t realm,uint32_t map){
const bool create=(u.kind==2 || u.kind==3) && u.type==4;
if(!selected || u.guid!=selected || (!create && u.kind!=0))return;
if(create){
++self_display_generation;self_display_guid=selected;self_display_realm=realm;self_display_map=map;self_display_known=0;
}else if(self_display_guid!=selected || self_display_realm!=realm || self_display_map!=map){
invalidate_self_display();return;
}
if(!self_display_generation)return;
auto observe=[&](uint16_t index,uint32_t& word,uint8_t bit){
auto found=u.fields.find(index);if(found!=u.fields.end()){word=found->second;self_display_known|=bit;}
};
observe(turtle_entity_fields::UNIT_FIELD_BYTES_0,self_display_bytes0,1);
observe(SourceUnitDisplayIdField,self_display_id,2);
observe(SourceUnitNativeDisplayIdField,self_native_display_id,4);
}
void NativeEntityTranslation::project_self_display(const LegacyObjectUpdate& u,uint64_t selected,uint16_t realm,uint32_t map,std::map<uint16_t,uint32_t>& fields) const{
const bool create=(u.kind==2 || u.kind==3) && u.type==4;
// Self scale deltas (Enlarge etc.): divide the Turtle race base out, as the create path does; unknown race -> drop.
// Forms/morphs: the divisor follows the current display (self_display_* already observed this update).
if(create && u.guid==selected)if(auto sc=u.fields.find(SourceObjectScaleField);sc!=u.fields.end())self_source_scale=sc->second;
if(u.kind==0 && u.guid==selected){
if(auto sc=fields.find(SourceObjectScaleField);sc!=fields.end())self_source_scale=sc->second;
else if(u.fields.contains(SourceUnitDisplayIdField) && self_source_scale)fields[SourceObjectScaleField]=self_source_scale;
if(auto sc=fields.find(SourceObjectScaleField);sc!=fields.end()){
if(self_display_known&1 && self_display_guid==selected && self_display_generation)
sc->second=std::bit_cast<uint32_t>(forever_native_player_scale(std::bit_cast<float>(sc->second),self_display_bytes0&255,
(self_display_bytes0>>16)&255,self_display_known&2?self_display_id:0,self_display_known&4?self_native_display_id:0,
forever_display_scale::client));
else fields.erase(sc);
}
}
if(u.guid!=selected || (!create && u.kind!=0) || self_display_known!=7 ||
self_display_guid!=selected || self_display_realm!=realm || self_display_map!=map || !self_display_generation)return;
if(!u.fields.contains(turtle_entity_fields::UNIT_FIELD_BYTES_0) && !u.fields.contains(SourceUnitDisplayIdField) &&
!u.fields.contains(SourceUnitNativeDisplayIdField))return;
auto displays=forever_player_default_displays(self_display_bytes0&255,(self_display_bytes0>>16)&255,self_display_id,self_native_display_id);
fields[SourceUnitDisplayIdField]=displays.display;
fields[SourceUnitNativeDisplayIdField]=displays.native_display;
}
void NativeEntityTranslation::observe_source_fields(const std::vector<LegacyObjectUpdate>& updates,uint64_t self,uint32_t opcode){
if(!source_packets || (opcode!=0xa9 && opcode!=0x1f6))return;
auto allowed=[](uint16_t field){
namespace F=turtle_entity_fields;
return field==F::UNIT_FIELD_TARGET || field==F::UNIT_FIELD_TARGET+1 ||
(field>=F::UNIT_FIELD_HEALTH && field<=F::UNIT_FIELD_MAXPOWER1+4) ||
field==F::UNIT_FIELD_FLAGS || field==F::UNIT_FIELD_BYTES_1 || field==F::UNIT_FIELD_BYTES_2 || field==F::UNIT_FIELD_MOUNTDISPLAYID;
};
std::set<uint64_t> created;
for(const auto& update:updates){
const bool create=(update.kind==2 || update.kind==3) && (update.type==3 || update.type==4);
if(create && update.guid)created.insert(update.guid);
auto actor=actors.find(update.guid);
const bool known=update.guid==self || created.contains(update.guid) || (actor!=actors.end() && (actor->second.kind==3 || actor->second.kind==4));
if(!update.guid || (update.kind!=0 && !create) || (!known && !create))continue;
for(auto [field,value]:update.fields)if(allowed(field)){
if(source_field_count==UINT32_MAX){source_field_overflow=true;return;}
if(source_fields.size()==64)source_fields.pop_front();
source_fields.push_back({update.guid,++source_field_count,source_packets,opcode,update.kind,field,value});
}
}
}
bool NativeEntityTranslation::observe_owned_source_position(const GroundMovement& movement,uint64_t self,uint16_t realm,uint32_t map) noexcept{
source_positions.erase(self);
if(!self || movement.guid!=self || !self_presentation_ready || !self_position_generation ||
position_realm!=realm || position_map!=map)return false;
if(source_positions.size()>=4097)return false;
std::array<float,3> xyz{};
for(unsigned i=0;i<3;++i){xyz[i]=movement.position[i];if(!std::isfinite(xyz[i]) || std::abs(xyz[i])>100000)return false;}
try{source_positions[self]={self_position_generation,realm,map,xyz,true};return true;}
catch(...){return false;}
}
void NativeEntityTranslation::Actor::observe_movement_victim(uint64_t owner,uint64_t victim,std::vector<LegacyPacket>& out){
if(victim==melee_victim)return;
if(!victim && sent)
out.push_back({0x4d0018,forever_attack_event(TurtleAttackEvent{owner,0,true,false},{{owner,modern}})});
melee_victim=victim;
melee_pending=victim!=0;
}
std::vector<LegacyPacket> NativeEntityTranslation::translate(const LegacyPacket& packet,const Character& self,uint16_t realm,uint32_t address,uint32_t map,const Codec& codec,bool viewer_ghost,NativeInventoryTranslation* peer_items){
set_action_scope(self.guid,realm,map);
std::vector<LegacyPacket> out;
std::vector<LegacyObjectUpdate> position_updates;
if(position_realm!=realm || position_map!=map){
source_positions.clear();position_realm=realm;position_map=map;
// A native world transition owns destruction of the old world. Never
// carry a map-local Source dynamic counter into the new presentation.
for(const auto& [guid,ground]:persistent_ground){(void)ground;actors.erase(guid);}
persistent_ground.clear();
}
std::map<uint64_t,std::map<uint16_t,uint32_t>> values;
std::map<uint64_t,std::pair<uint64_t,std::map<uint16_t,uint32_t>>> gameobject_values;
std::set<uint64_t> ground_dirty;
auto emit=[&](uint32_t op,Bytes body){out.push_back({op,std::move(body)});};
std::shared_ptr<const LegacyPacket> retained_packet;
auto retain_create=[&](Actor& actor){
if(!retained_packet)retained_packet=std::make_shared<LegacyPacket>(packet);
auto [it,inserted]=retained_create_refs.try_emplace(retained_packet.get(),0);
if(inserted){
if(packet.body.size()>16777216-retained_create_bytes){retained_create_refs.erase(it);throw Error("native spirit service create retention bound");}
retained_create_bytes+=packet.body.size();
}
++it->second;actor.source_create=retained_packet;
};
auto release_create=[&](Actor& actor){
if(!actor.source_create)return;
auto it=retained_create_refs.find(actor.source_create.get());
if(it==retained_create_refs.end() || !it->second)throw Error("native spirit service create reference mismatch");
if(!--it->second){retained_create_bytes-=actor.source_create->body.size();retained_create_refs.erase(it);}
actor.source_create.reset();
};
auto unit_binding=[&](uint64_t id)->std::optional<Guid128>{
if(id==self.guid && self_presentation_ready)return forever_player_guid(id,realm);
auto actor=actors.find(id);
if(actor!=actors.end() && (actor->second.kind==3 || actor->second.kind==4) && actor->second.sent)return actor->second.modern;
return {};
};
auto source_position=[&](uint64_t guid,const GroundMovement& movement){
// Named source Object.h modes which do not imply displacement. Any
// direction/fall/spline/transport/flying/unknown bit invalidates XYZ.
constexpr uint32_t stable_modes=0x100u|0x400u|0x800u|0x1000u|0x200000u|0x10000000u|0x20000000u|0x40000000u;
if(movement.flags&~stable_modes){
source_positions.erase(guid);
if(auto a=actors.find(guid);a!=actors.end())a->second.source_pose_moving=true;
return;
}
uint64_t gen=0;
if(guid==self.guid && self_presentation_ready)gen=self_position_generation;
else if(auto a=actors.find(guid);a!=actors.end() && (a->second.kind==3 || a->second.kind==4))gen=a->second.generation;
if(!gen){source_positions.erase(guid);return;}
std::array<float,3> xyz{};
for(unsigned i=0;i<3;++i){xyz[i]=movement.position[i];if(!std::isfinite(xyz[i]) || std::abs(xyz[i])>100000)throw Error("source position bound");}
if(source_positions.size()>=4097 && !source_positions.contains(guid))throw Error("source position cache bound");
source_positions[guid]={gen,realm,map,xyz};
if(auto a=actors.find(guid);a!=actors.end())a->second.source_pose_moving=false;
};
auto observed_motion=[&](const LegacyPacket& record){
uint64_t guid=0;
try{
Reader r(record.body);auto packed=unpack_guid(r,8);Reader id(packed);guid=id.le(8);
source_positions.erase(guid);
auto move=turtle_ground_movement(r.take(r.left()),guid);
source_position(guid,move);
}catch(const Error&){if(!guid)source_positions.clear();else source_positions.erase(guid);}
};
if(packet.opcode<=0xffff && peer_movement_opcode(uint16_t(packet.opcode)))observed_motion(packet);
auto visible_mover=[&](uint64_t guid,bool allow_self){
if(guid==self.guid && !(allow_self && self_presentation_ready))
throw Error("movement outside presented self");
if(guid!=self.guid){
auto actor=actors.find(guid);
if(actor==actors.end() || !actor->second.eligible || !actor->second.sent ||
!actor->second.generation || actor->second.presentation_realm!=realm ||
actor->second.presentation_map!=map)throw Error("movement outside presented actor");
if(actor->second.kind==4){
auto peer=peer_players.find(guid);
if(peer==peer_players.end() || peer->second.blocked || !peer->second.named ||
peer->second.generation!=actor->second.generation)throw Error("movement outside presented peer");
}
}
auto bound=unit_binding(guid);
if(!bound)throw Error("movement has no active unit binding");
return *bound;
};
if(const auto* route=observer_motion::route(packet.opcode)){
uint64_t guid=0;
const bool has_position=route->body==observer_motion::Body::movement ||
route->body==observer_motion::Body::teleport || route->body==observer_motion::Body::knockback;
try{
Reader input(packet.body);
auto raw=unpack_guid(input,8);Reader id(raw);guid=id.le(8);
const bool allow_self=route->body==observer_motion::Body::spline_flag ||
route->body==observer_motion::Body::control;
const auto bound=visible_mover(guid,allow_self);
remote_speeds::validate_binding(guid,bound,realm,map);
auto update=observer_motion::read(*route,guid,input);
auto translated=observer_motion::write(*route,update,bound);
if(update.movement)source_position(guid,update.movement->state);
emit(translated.opcode,std::move(translated.body));
}catch(const Error&){
if(has_position){if(guid)source_positions.erase(guid);else source_positions.clear();}
++unsupported;
}
return out;
}
if(const auto* speed_route=remote_speeds::route(packet.opcode)){
uint64_t observed=0;
const bool has_position=packet.opcode==speed_route->observer;
try{
if(has_position){Reader r(packet.body);auto packed=unpack_guid(r,8);Reader id(packed);observed=id.le(8);source_positions.erase(observed);}
const auto update=remote_speeds::turtle_packet(packet.opcode,packet.body);
if(!update)throw Error("remote speed route differs");
auto bound=visible_mover(update->source_guid,false);
auto translated=remote_speeds::forever_packet(*update,bound,realm,map);
if(update->movement)source_position(update->source_guid,update->movement->state);
emit(translated.opcode,std::move(translated.body));
}catch(const Error&){
if(has_position){if(observed)source_positions.erase(observed);else source_positions.clear();}
++unsupported;
}
return out;
}
auto forget=[&](uint64_t guid,bool destroyed){
persistent_ground.erase(guid);
source_positions.erase(guid);
if(guid==self.guid){self_presentation_ready=false;self_unit_bytes1=self_player_bytes2=0;self_faction=0;self_quest_log.clear();self_profession_skills.clear();invalidate_self_display();}
if(guid==self.guid){
self_melee_target.reset();
self_combo={};self_farsight={};self_farsight_clear_since.reset();self_res_spell=0;self_res_submitted=false;
if(auto own=values.find(guid);own!=values.end())own->second.erase(turtle_entity_fields::PLAYER_SELF_RES_SPELL);
}
for(auto& control:self_controlled){
if(guid==self.guid)control={};
else if(control.known==3 && control.source_guid()==guid){
// A new generation must be selected afresh by the source.
control.words={};control.known=3;
}
}
targets.erase(guid);target_dirty.erase(guid);spell_channels.forget(guid);
for(auto& [owner,target]:targets)if(target.known==3 &&
(uint64_t(target.words[0])|(uint64_t(target.words[1])<<32))==guid){
target.presented.reset();target_dirty.insert(owner);
}
for(auto& [owner,actor]:actors)if(actor.melee_victim==guid){
(void)owner;actor.melee_victim=0;actor.melee_pending=false;
}
auto it=actors.find(guid);if(it==actors.end())return;
if(it->second.sent){
std::vector<Guid128> ids{it->second.modern},empty;
emit(0x5e0000,forever_object_removal(uint16_t(map),destroyed?ids:empty,destroyed?empty:ids));
}
if(it->second.kind==3 && (guid>>48)==0xf140)
pet_source_value_fields-=it->second.pending_values.size();
else pending_value_fields-=it->second.pending_values.size();
release_create(it->second);
values.erase(guid);
actors.erase(it);++removals;
};
// GM mode can keep source spirit services in its visibility set while the
// player is alive. The native presentation still follows ghost state.
if(!viewer_ghost){
std::vector<Guid128> hidden;
for(auto& [guid,actor]:actors)if(actor.kind==3 && actor.spirit_service && actor.sent){
hidden.push_back(actor.modern);actor.sent=false;actor.melee_pending=actor.melee_victim!=0;
if(auto t=targets.find(guid);t!=targets.end()){
t->second.presented=Guid128{};
if(t->second.words[0] || t->second.words[1])target_dirty.insert(guid);
}
for(auto& [owner,target]:targets)if(target.known==3 &&
(uint64_t(target.words[0])|(uint64_t(target.words[1])<<32))==guid){
target.presented.reset();target_dirty.insert(owner);
}
}
if(!hidden.empty())emit(0x5e0000,forever_object_removal(uint16_t(map),{},hidden));
}
auto target_state=[&](const LegacyObjectUpdate& update,bool create,bool existing_self=false){
spell_channels.observe(update, create, existing_self, cast_visual_profile::link);
constexpr auto first=turtle_entity_fields::UNIT_FIELD_TARGET;
if(!create && !update.fields.contains(first) && !update.fields.contains(first+1))return;
if(targets.size()>=4097 && !targets.contains(update.guid))throw Error("native target state bound");
auto& target=targets[update.guid];
if(create){
auto previous=target.presented;
target=TargetState{};target.known=3;target.presented=existing_self?previous:std::optional<Guid128>{Guid128{}};
// New full objects already present an empty Target. A repeated
// self create does not re-emit that object, so retain only its
// presented identity while resetting both authoritative words.
target_dirty.erase(update.guid);
}
for(unsigned half=0;half<2;++half){auto field=update.fields.find(first+half);
if(field!=update.fields.end()){target.words[half]=field->second;target.known|=uint8_t(1u<<half);}
}
if(!create || existing_self || target.words[0] || target.words[1])target_dirty.insert(update.guid);
};
// A peer exists while its name query is outstanding. Source starts and
// stops during that interval supersede the victim in its original create.
auto tracks_melee=[](const Actor& actor){
return actor.kind==4 || (actor.kind==3 && actor.eligible);
};
if(packet.opcode==0x143 || packet.opcode==0x144){
auto event=turtle_attack_event(uint16_t(packet.opcode),packet.body);
auto actor=actors.find(event.attacker);
if(actor!=actors.end() && tracks_melee(actor->second)){
auto& state=actor->second;state.melee_victim=event.stopped?0:event.victim;
// The world handler already sends normal events whose two actors
// were presented before this call. Retain only deferred init state.
state.melee_pending=!event.stopped && state.melee_victim &&
(!state.sent || !unit_binding(state.melee_victim));
}
}
if(packet.opcode==0xdd || packet.opcode==0x2ae || packet.opcode==0x2fb){
std::vector<LegacyMovementRecord> records;
try{records=packet.opcode==0x2fb?turtle_compressed_moves(packet.body):std::vector<LegacyMovementRecord>{{uint16_t(packet.opcode),packet.body}};}
catch(const Error& error){source_positions.clear();++motion_rejected;note_self_motion({},packet.opcode,false,action_motion_reason(error.what()),0);return out;}
for(const auto& record:records){
++motion_received;
if(record.opcode!=0xdd && record.opcode!=0x2ae){
if(remote_speeds::route(record.opcode) || observer_motion::route(record.opcode)){
// Source MoveSplineInit brackets a genuine spline with
// speed override/restore in this same ordered envelope.
// The existing decoder rejects nested envelopes and caps
// the stream/record count; this branch never recurses on
// compression and never replays an unpresented identity.
auto speeds=translate({record.opcode,record.body},self,realm,address,map,codec);
for(auto& speed:speeds)out.push_back(std::move(speed));
}else if(peer_movement_opcode(record.opcode))observed_motion({record.opcode,record.body});
else ++motion_rejected;
continue;
}
// Even a held spline proves its mover's former static XYZ stale.
try{Reader r(record.body);auto raw=unpack_guid(r,8);Reader id(raw);source_positions.erase(id.le(8));}
catch(const Error&){source_positions.clear();}
SplineParseObservation observation;uint32_t diagnostic_stage=1;
try{
auto spline=turtle_monster_spline(record.body,&observation,record.opcode==0x2ae);auto actor=actors.find(spline.guid);Guid128 modern;
if(actor!=actors.end())actor->second.source_pose_moving=!spline.stop;
if(spline.guid==self.guid && self_presentation_ready)modern=forever_player_guid(self.guid,realm);
else if(actor!=actors.end() && (actor->second.kind==3 || actor->second.kind==4) && actor->second.sent)modern=actor->second.modern;
else{++motion_unknown;note_self_motion(observation,packet.opcode,false,1001,2);continue;}
std::optional<Guid128> transport;
if(spline.transport_guid){
modern=visible_mover(spline.guid,true);
remote_speeds::validate_binding(spline.guid,modern,realm,map);
auto found=actors.find(spline.transport_guid);
if(found==actors.end() || found->second.kind!=5 || found->second.gameobject_type!=15 ||
!found->second.sent || !found->second.eligible || !found->second.generation ||
found->second.presentation_map!=map || found->second.presentation_realm!=realm)
throw Error("source moving transport has no current native presentation");
// The pose cache uses world coordinates; deriving a bearing
// to another actor needs both poses in this transport's frame.
if(spline.face==3)throw Error("missing transport-local target bearing");
transport=found->second.modern;
}
if(spline.stop && !transport){
GroundMovement stopped{spline.guid,0,0,{spline.start[0],spline.start[1],spline.start[2],0}};
source_position(spline.guid,stopped);
}
std::optional<SplineFacingTarget> facing;
auto projected=spline;bool final_facing_held=false;
if(spline.face==3){
diagnostic_stage=3;
auto target=unit_binding(spline.facing_target);auto pos=source_positions.find(spline.facing_target);
uint64_t target_generation=0;
if(spline.facing_target==self.guid)target_generation=self_position_generation;
else if(auto a=actors.find(spline.facing_target);a!=actors.end())target_generation=a->second.generation;
if(!target || !target_generation)throw Error("spline target has no current source position");
if(pos==source_positions.end()){
auto a=actors.find(spline.facing_target);
const bool controlled_ground=spline.guid==self.guid && !spline.flying && self_presentation_ready &&
self_position_generation && position_realm==realm && position_map==map;
const bool live_moving_target=a!=actors.end() && (a->second.kind==3 || a->second.kind==4) && a->second.sent &&
a->second.source_pose_moving && a->second.generation==target_generation &&
a->second.presentation_realm==realm && a->second.presentation_map==map;
bool identity=false;
if(live_moving_target){
if(spline.facing_target<=UINT32_MAX)identity=*target==forever_player_guid(spline.facing_target,realm);
else if((spline.facing_target>>48)==0xf130)
identity=*target==forever_creature_guid(spline.facing_target,uint32_t(spline.facing_target>>24)&0xffffff,realm,map);
}
if(!controlled_ground || !live_moving_target || !identity)throw Error("spline target has no current source position");
// Explicit partial projection: preserve the proven path
// and time through the existing normal-path producer.
// No angle/XYZ is invented and TARGET is not presented
// as equivalent to this natural path-heading behavior.
projected.face=0;projected.facing_target=0;final_facing_held=true;
}else{
if(pos->second.generation!=target_generation ||
pos->second.realm!=realm || pos->second.map!=map)throw Error("spline target has no current source position");
auto dx=pos->second.xyz[0]-spline.start[0],dy=pos->second.xyz[1]-spline.start[1];
if(!std::isfinite(dx) || !std::isfinite(dy) || (dx==0 && dy==0))throw Error("spline target bearing unavailable");
facing=SplineFacingTarget{*target,std::atan2(dy,dx)};
}
}
diagnostic_stage=4;auto body=forever_monster_spline(projected,modern,facing,transport);
emit(0x600002,std::move(body));++motion_sent;note_self_motion(observation,packet.opcode,true,final_facing_held?1002:0,4);
if(motion.size()==16)motion.pop_front();
motion.push_back({std::move(spline),modern});
}catch(const Error& error){++motion_rejected;note_self_motion(observation,packet.opcode,false,action_motion_reason(error.what()),diagnostic_stage);}
}
auto peer_output=translate_peers(packet,self,realm,address,map,codec,peer_items);
for(auto& item:peer_output)out.push_back(std::move(item));
return out;
}
if(packet.opcode==0xaa){Reader r(packet.body);auto guid=r.le(8);r.end();forget(guid,true);}
if(packet.opcode==0xa9 || packet.opcode==0x1f6){
auto updates=turtle_object_updates(packet.opcode,packet.body);
// A legacy corpse lacks its owner's class/faction. Class comes from
// the authenticated roster; faction comes from this actual self unit.
// Pre-scan makes one mixed create batch independent of object order.
for(const auto& u:updates)if(u.guid==self.guid && (u.kind==0 || ((u.kind==2 || u.kind==3) && u.type==4))){
auto f=u.fields.find(turtle_entity_fields::UNIT_FIELD_FACTIONTEMPLATE);
if(f!=u.fields.end())self_faction=f->second;
else if(u.kind!=0)self_faction=0;
observe_self_display(u,self.guid,realm,map);
}
// Definition collection is independent of renderer admission. Pets use
// their actual OBJECT_FIELD_ENTRY; their GUID middle is a PetNumber.
auto template_query=[&](uint32_t entry,uint8_t cls,bool strict){
auto reject=[&](const char* reason){if(strict)throw Error(reason);return false;};
if(!entry || entry>0x7fffff || !turtle_presentable_creature_class(cls))return false;
if(strict){
if(classes.contains(entry) && classes.at(entry)!=cls)return reject("creature class changed within entry");
if(classes.size()>=4096 && !classes.contains(entry))return reject("native creature class cache bound");
}
const bool needed=!templates.contains(entry) && !queries.contains(entry);
// Pet::InitStatsForLevel may override UnitClass to Warrior.
// It cannot establish or consume the F130 class authority/cache.
if(!strict && needed && templates.size()+queries.size()>=classes.size()+4096)return false;
if(needed && requests.size()>=4096)return reject("native entity request bound");
if(strict)classes[entry]=cls;
// A template the native client asked for before any class was observed is announced now.
if(strict && template_unannounced.erase(entry) && templates.contains(entry) && templates.at(entry).found)
emit(0x4b0006,forever_creature_template(templates.at(entry),cls));
if(needed){queries.insert(entry);requests.push_back({0x60,turtle_creature_query(entry)});}
return true;
};
std::map<uint32_t,uint8_t> pet_definitions;
auto pet_source=[&](Actor& actor,const auto& update){
size_t added=0;for(auto [index,value]:update.fields){(void)value;added+=!actor.pending_values.contains(index);}
if(pet_source_value_fields>65536 || added>65536-pet_source_value_fields)return false;
for(auto [index,value]:update.fields)actor.pending_values[index]=value;
pet_source_value_fields+=added;
if(auto f=actor.pending_values.find(turtle_entity_fields::OBJECT_FIELD_ENTRY);f!=actor.pending_values.end())actor.entry=f->second;
auto bytes=actor.pending_values.find(turtle_entity_fields::UNIT_FIELD_BYTES_0);
if(bytes==actor.pending_values.end())return false;
actor.unit_class=uint8_t(bytes->second>>8);
// Owner/creator sparse halves and PetNumber remain source fields
// for this generation. No native identity is synthesized here.
if(!actor.entry || actor.entry>0x7fffff || !turtle_presentable_creature_class(actor.unit_class))return false;
if(pet_definitions.size()>=4096 && !pet_definitions.contains(actor.entry))return false;
pet_definitions.try_emplace(actor.entry,actor.unit_class);return true;
};
Batch batch;batch.packet=packet;bool corpses=false;
size_t gameobject_creates=0;
std::vector<size_t> gameobject_blocks;
for(const auto& u:updates){
if(u.type==5 && (u.kind==2 || u.kind==3))++gameobject_creates;
// Gitea #8: Octo UC lifts (20649-20657, GUID high 0xF120) never reach the create path. Trace every block that
// names a transport GUID, whatever its kind (values/movement/create/out-of-range), to see what the server sends.
if((u.guid>>48)==0xf120){static unsigned traced=0;if(traced<400){++traced;
auto e=u.fields.find(turtle_entity_fields::OBJECT_FIELD_ENTRY);
gw_go_log("GW_GO f120 guid=%llx kind=%u type=%u entry=%u fields=%zu movement=%d op=%x\n",(unsigned long long)u.guid,
unsigned(u.kind),unsigned(u.type),e==u.fields.end()?0u:e->second,u.fields.size(),int(bool(u.movement)),unsigned(packet.opcode));}}
auto power=[&](uint8_t& type){
auto f=u.fields.find(turtle_entity_fields::UNIT_FIELD_BYTES_0);
if(f!=u.fields.end())type=(f->second>>24)<4?uint8_t(f->second>>24):255;
};
if(u.guid==self.guid){
const bool full=(u.kind==2 || u.kind==3) && u.type==4;
if(full || u.kind==0)for(size_t role=0;role<self_controlled.size();++role){
auto& control=self_controlled[role];
const auto start=role?SourceSummonField:SourceCharmField;
if(full){control.words={};control.known=3;}
for(unsigned i=0;i<2;++i)if(auto word=u.fields.find(start+i);word!=u.fields.end()){
control.words[i]=word->second;control.known|=uint8_t(1u<<i);
}
}
if((full || u.kind==0) && (self.cls==4 || self.cls==11)){ // Tortoise combo points: Rogue, Druid
constexpr uint16_t combo_field=714; // Tortoise be0706 UpdateFields.h PLAYER_FIELD_COMBO_TARGET
// A repeated self create re-emits no native self object, so the presented GUID stays;
// omitted words are known zeros and clear it. forget(self) starts a fresh object.
if(full){auto shown=self_combo.presented;self_combo=TargetState{};self_combo.known=3;self_combo.presented=shown;}
for(unsigned i=0;i<2;++i)if(auto word=u.fields.find(combo_field+i);word!=u.fields.end()){
self_combo.words[i]=word->second;self_combo.known|=uint8_t(1u<<i);
}
}
if(full || u.kind==0){
constexpr uint16_t farsight_field=712; // Tortoise be0706 UpdateFields.h PLAYER_FARSIGHT
if(full){auto shown=self_farsight.presented;self_farsight=TargetState{};self_farsight.known=3;self_farsight.presented=shown;}
for(unsigned i=0;i<2;++i)if(auto word=u.fields.find(farsight_field+i);word!=u.fields.end()){
self_farsight.words[i]=word->second;self_farsight.known|=uint8_t(1u<<i);
}
}
constexpr auto res_field=turtle_entity_fields::PLAYER_SELF_RES_SPELL;
const auto res=u.fields.find(res_field);
if(u.is_self_player_create(self.guid) || (self_presentation_ready && u.kind==0 && res!=u.fields.end())){
const auto spell=res==u.fields.end()?0u:res->second;
if(spell!=self_res_spell){
// The world sends the initial list in the full native self. Source recreates
// reuse that native object and must publish a changed or omitted option.
if(full)values[self.guid][res_field]=spell;
self_res_spell=spell;self_res_submitted=false;
}
}
observe_equipment_visibility(u,self.guid,realm,map);
power(self_power_type);
constexpr auto unit_word=turtle_entity_fields::UNIT_FIELD_BYTES_1;
constexpr auto player_word=turtle_entity_fields::PLAYER_FIELD_BYTES2;
auto word=[&](unsigned index){auto it=u.fields.find(index);return it==u.fields.end()?0u:it->second;};
if((u.kind==2 || u.kind==3) && u.type==4){
(void)self_quest_log.observe(u.fields,true);
self_profession_skills.initialize(u.fields,SourceSkillFirst,self.guid);
// Missing words in a full create are known zeros, not
// unknown sparse values. A recreate starts a fresh state.
auto existing=self_presentation_ready;
self_appearance_identity = word(turtle_entity_fields::UNIT_FIELD_BYTES_0);
self_appearance = word(turtle_entity_fields::PLAYER_BYTES);
self_appearance2 = word(turtle_entity_fields::PLAYER_BYTES_2);
self_appearance_after_morph=false;
self_unit_bytes1=word(unit_word);self_player_bytes2=word(player_word);self_presentation_ready=true;
self_explored_zone_words.fill(0);
for(unsigned i=0;i<SourceExploredZoneWords;++i)
self_explored_zone_words[i]=word(turtle_entity_fields::PLAYER_EXPLORED_ZONES_1+i);
target_state(u,true,existing);
}
if(u.kind==0){
if(self_presentation_ready)target_state(u,false);
auto& fields=values[u.guid];
for (auto [index, value] : u.fields) {
// The appearance word needs its matching identity and
// facial hair. Publish it only with a scoped snapshot.
if (index == res_field && !self_presentation_ready) continue;
if (index != turtle_entity_fields::PLAYER_BYTES) fields[index] = value;
}
if (self_presentation_ready && self_display_guid == self.guid &&
self_display_realm == realm && self_display_map == map) {
using namespace turtle_entity_fields;
auto merge = [&](unsigned index, uint32_t& cached, uint32_t mask) {
auto it = u.fields.find(index);
if (it == u.fields.end()) return false;
const bool changed = ((cached ^ it->second) & mask) != 0;
cached = it->second;
return changed;
};
const bool identity = merge(UNIT_FIELD_BYTES_0, self_appearance_identity, 0x00ff00ff);
const bool appearance = merge(PLAYER_BYTES, self_appearance, UINT32_MAX);
const bool facial = merge(PLAYER_BYTES_2, self_appearance2, 0xff);
if (identity || appearance || facial) {
fields[UNIT_FIELD_BYTES_0] = self_appearance_identity;
fields[PLAYER_BYTES] = self_appearance;
fields[PLAYER_BYTES_2] = self_appearance2;
// A spell can change skin while its temporary model
// is active. Re-send the current customization with
// the later display restore, after the client rebuilds
// its native player model.
self_appearance_after_morph = self_display_known==7 &&
self_display_id!=self_native_display_id;
} else if (self_appearance_after_morph &&
u.fields.contains(SourceUnitDisplayIdField) &&
self_display_known==7 &&
self_display_id==self_native_display_id) {
fields[UNIT_FIELD_BYTES_0] = self_appearance_identity;
fields[PLAYER_BYTES] = self_appearance;
fields[PLAYER_BYTES_2] = self_appearance2;
self_appearance_after_morph=false;
}
}
ProfessionDelta profession;
try{profession=self_profession_skills.observe(u.fields,SourceSkillFirst,self.guid);}
catch(const Error&){
// A malformed/over-capacity source snapshot cannot be
// guessed into two native profession slots. Preserve
// the established raw sparse path until a new create.
self_profession_skills.clear();
}
if(self_presentation_ready && (!profession.rows.empty() || profession.slot_mask)){
emit(0x5e0000,codec(GW_CODEC_PROFESSION_VALUES,profession_delta_input(realm,map,self.guid,profession)));
for(auto slot:profession.source_slots)for(unsigned word=0;word<3;++word)
fields.erase(SourceSkillFirst+3*slot+word);
}
const auto quest_log=self_quest_log.observe(u.fields,false);
if(self_presentation_ready && !quest_log.empty())
emit(0x5e0000,codec(GW_CODEC_QUEST_LOG_VALUES,quest_log_update_input(realm,map,self.guid,quest_log)));
std::erase_if(fields,[](const auto& row){return source_quest_log_field(row.first);});
bool explored_changed=false;
for(auto [index,value]:u.fields)if(source_explored_zone_field(index)){
if(self_presentation_ready){
self_explored_zone_words[index-turtle_entity_fields::PLAYER_EXPLORED_ZONES_1]=value;
explored_changed=true;
}else fields.erase(index);
}
// The native destination is a dynamic uint64 vector. A
// complete cached snapshot preserves both halves and its
// length32 on sparse Source DWORD updates.
if(explored_changed)for(unsigned i=0;i<SourceExploredZoneWords;++i)
fields[turtle_entity_fields::PLAYER_EXPLORED_ZONES_1+i]=self_explored_zone_words[i];
project_self_display(u,self.guid,realm,map,fields);
if(self_presentation_ready && (u.fields.contains(unit_word) || u.fields.contains(player_word))){
if(u.fields.contains(unit_word))self_unit_bytes1=word(unit_word);
if(u.fields.contains(player_word))self_player_bytes2=word(player_word);
fields[unit_word]=self_unit_bytes1;fields[player_word]=self_player_bytes2;
}
continue;
}
}
if(u.kind==4){for(auto guid:u.removed)forget(guid,false);continue;}
if(u.kind==1){
auto actor=actors.find(u.guid);
if(u.melee_victim && actor!=actors.end() && actor->second.kind==3 && actor->second.eligible)
actor->second.observe_movement_victim(u.guid,*u.melee_victim,out);
continue;
}
if(u.kind==0){
auto it=actors.find(u.guid);
if(it==actors.end())continue;
if(it->second.kind==6){
auto ground=persistent_ground.find(u.guid);
if(ground==persistent_ground.end()||!persistent_ground_enabled)continue;
if(std::none_of(u.fields.begin(),u.fields.end(),[](const auto& field){return field.first==4||(field.first>=6&&field.first<=14);}))continue;
// Moving a stationary area is not a values-field update.
// Keep this unsupported boundary explicit; never snap it.
const auto position=ground->second.position;
it->second.eligible=ground->second.observe(u,false)&&ground->second.spell==it->second.entry;
if(ground->second.position!=position)it->second.eligible=false;
ground_dirty.insert(u.guid);continue;
}
if(it->second.kind==5){
auto& actor=it->second;
if(auto type=u.fields.find(turtle_entity_fields::GAMEOBJECT_TYPE_ID);type!=u.fields.end())actor.gameobject_type=type->second;
// A values block can follow this chest's create in the same
// Source batch. The native create is emitted before the
// generation-checked sparse values below.
const bool chest=actor.gameobject_type==3;
if((!actor.sent && !chest) || !actor.eligible || actor.presentation_realm!=realm || actor.presentation_map!=map)continue;
auto& update=gameobject_values[u.guid];
if(update.first && update.first!=actor.generation)update.second.clear();
update.first=actor.generation;
if(chest){
auto dyn=u.fields.find(turtle_game_object_dynamic_flags_field);
if(dyn!=u.fields.end())update.second[dyn->first]=dyn->second;
}
for(auto index:{turtle_entity_fields::GAMEOBJECT_FLAGS,turtle_entity_fields::GAMEOBJECT_STATE,turtle_entity_fields::GAMEOBJECT_ARTKIT}){
auto field=u.fields.find(index);if(field==u.fields.end())continue;
// A presented transport stays native TRANSPORT_ACTIVE; Source door states never reach it.
if(index==turtle_entity_fields::GAMEOBJECT_STATE && actor.gameobject_type==11)continue;
if(index==turtle_entity_fields::GAMEOBJECT_STATE && !turtle_static_game_object_state(field->second)){++unsupported;continue;}
update.second[index]=field->second;
}
continue;
}
if(it->second.kind!=3)continue;
if(auto flags=u.fields.find(turtle_entity_fields::UNIT_NPC_FLAGS);flags!=u.fields.end())it->second.npc_flags=flags->second;
if((u.guid>>48)==0xf140){
if(!pet_source(it->second,u))++unsupported;
if(it->second.companion || it->second.owned_stat_pet) spell_channels.observe(u, false, false, cast_visual_profile::link);
if(it->second.companion || it->second.owned_stat_pet){power(it->second.power_type);for(auto [index,value]:u.fields)it->second.companion_dirty[index]=value;}
continue;
}
if(!it->second.eligible)continue;
auto& actor=it->second;power(actor.power_type);
if(auto flags=u.fields.find(turtle_entity_fields::UNIT_NPC_FLAGS);flags!=u.fields.end()){actor.questgiver=(flags->second&2u)!=0;actor.npc_flags=flags->second;}
target_state(u,false);
auto& fields=actor.sent?values[u.guid]:actor.pending_values;
for(auto [index,value]:u.fields){
if(!actor.sent && !fields.contains(index) && ++pending_value_fields>65536)throw Error("native pending unit value bound");
fields[index]=value;
}
if(auto d=u.fields.find(SourceUnitDisplayIdField);d!=u.fields.end())actor.display=d->second;
// Legacy scale is absolute; 70334 multiplies Scale by CreatureModelScale (same division as the create path).
if(auto sc=fields.find(SourceObjectScaleField);sc!=fields.end() && u.fields.contains(SourceObjectScaleField)){
const float source=std::bit_cast<float>(sc->second),model=forever_display_scale::client(actor.display);
if(actor.display && source>0 && source<=100 && model>0)sc->second=std::bit_cast<uint32_t>(source/model);else fields.erase(sc);
}
continue;
}
// Kind5 is a near-list, never a destruction request.
// Peer recreation uses the same removal/target-generation boundary
// as other real actors, before the dedicated Player writer runs.
if((u.kind==2 || u.kind==3) && u.type==4 && u.guid!=self.guid && actors.contains(u.guid))
forget(u.guid,true);
if((u.kind!=2 && u.kind!=3) || (u.type!=3 && u.type!=5 && u.type!=7 &&
!(u.type==6&&persistent_ground_enabled)))continue;
// vmangos re-sends a transport's full CREATE periodically (lifts ~every 80 s). Destroying and
// re-creating the presented lift drops every passenger mid-ride, so keep the live object.
if(u.type==5)if(auto old=actors.find(u.guid);old!=actors.end() && old->second.kind==5 && (old->second.gameobject_type==11 || old->second.gameobject_type==15) &&
old->second.sent && old->second.eligible && old->second.presentation_realm==realm && old->second.presentation_map==map){
auto entry=u.fields.find(turtle_entity_fields::OBJECT_FIELD_ENTRY);
if(entry!=u.fields.end() && entry->second==old->second.entry)continue;
}
if(actors.contains(u.guid))forget(u.guid,true);
if(actors.size()>=4096)throw Error("native visible actor bound");
// Retain every observed unit/gameobject create, even if presentation
// is unsupported. Never report a filtered subset as server population.
auto& actor=actors[u.guid];actor.kind=u.type;actor.generation=++generation;actor.presentation_realm=realm;actor.presentation_map=map;
if(auto flags=u.fields.find(turtle_entity_fields::UNIT_NPC_FLAGS);flags!=u.fields.end())actor.npc_flags=flags->second; // pets (0xF140) included
if(auto d=u.fields.find(SourceUnitDisplayIdField);d!=u.fields.end())actor.display=d->second;
if(u.type==6){
auto& ground=persistent_ground[u.guid];
ground.cast_time=native_presentation_milliseconds();
actor.eligible=ground.observe(u,true);
if(actor.eligible){actor.entry=ground.spell;actor.modern=forever_persistent_ground_guid(u.guid,ground.spell,realm,map);}
else ++unsupported;
ground_dirty.insert(u.guid);continue;
}
auto entry=u.fields.find(turtle_entity_fields::OBJECT_FIELD_ENTRY);
if(entry!=u.fields.end())actor.entry=entry->second;
if(u.type==3 && (u.guid>>48)==0xf140){
const bool valid_source=pet_source(actor,u);actor.pet_original_entry=actor.entry;
actor.companion=u.movement && source_passive_companion(actor.pending_values);
actor.owned_stat_pet=valid_source && u.movement && (self.cls==3 || self.cls==9) && source_owned_stat_pet(actor.pending_values,self.guid,u.guid);
if(actor.companion || actor.owned_stat_pet){
spell_channels.observe(u, true, false, cast_visual_profile::link);
actor.pet_initial_owner=source_pet_guid(actor.pending_values,SourcePetOwner);power(actor.power_type);retain_create(actor);
}else ++unsupported;
continue;
}
if(u.type==7){
auto word=[&](uint16_t i){auto f=u.fields.find(i);return f==u.fields.end()?0u:f->second;};
actor.corpse_owner=uint64_t(word(turtle_entity_fields::CORPSE_FIELD_OWNER))|(uint64_t(word(turtle_entity_fields::CORPSE_FIELD_OWNER+1))<<32);
if(!u.movement || actor.corpse_owner!=self.guid){++unsupported;continue;}
actor.modern=forever_corpse_guid(u.guid,realm,map);actor.eligible=true;corpses=true;continue;
}
// vmangos MO_TRANSPORT creates carry no position block (UPDATEFLAG_TRANSPORT only); the ship's spawn is in
// GAMEOBJECT_POS_X.. and its phase in the transport word, so they are admitted without movement.
const bool mo_transport=u.type==5 && (u.guid>>48)==0x1FC0 && u.transport_time.has_value();
if((!u.movement && !mo_transport) || !actor.entry || actor.entry>0x7fffff){
if(u.type==5)gw_go_log("GW_GO dropped guid=%llx entry=%u movement=%d\n",(unsigned long long)u.guid,actor.entry,int(bool(u.movement)));
++unsupported;continue;}
if(u.type==3){
auto bytes=u.fields.find(turtle_entity_fields::UNIT_FIELD_BYTES_0);auto cls=bytes==u.fields.end()?0:uint8_t(bytes->second>>8);
if((u.guid>>48)!=0xf130 || !turtle_presentable_creature_class(cls)){++unsupported;continue;}
// Creature::InitEntry/UpdateEntry can change OBJECT_FIELD_ENTRY
// without changing the server's ObjectGuid. Keep identity tied
// to its immutable encoded entry; query/present the live entry.
actor.unit_class=cls;actor.modern=forever_creature_guid(u.guid,uint32_t(u.guid>>24)&0xffffff,realm,map);
if(auto flags=u.fields.find(turtle_entity_fields::UNIT_NPC_FLAGS);flags!=u.fields.end()){actor.questgiver=(flags->second&2u)!=0;actor.npc_flags=flags->second;}
actor.melee_victim=u.melee_victim.value_or(0);actor.melee_pending=actor.melee_victim!=0;
if(auto flags=u.fields.find(turtle_entity_fields::UNIT_NPC_FLAGS);flags!=u.fields.end() && (flags->second&spirit_service_flags)){
actor.spirit_service=true;retain_create(actor);
}
target_state(u,true);
power(actor.power_type);
const bool first_class=!classes.contains(actor.entry);
(void)template_query(actor.entry,cls,true);
if(first_class)if(auto meta=templates.find(actor.entry);meta!=templates.end())
emit(0x4b0006,forever_creature_template(meta->second,cls));
batch.actors.push_back({u.guid,actor.generation});
}else{
auto type_field=u.fields.find(turtle_entity_fields::GAMEOBJECT_TYPE_ID);
// A full Source CREATE omits zero-valued words. Missing type
// therefore means DOOR(0), matching the create serializer.
const uint32_t type=type_field==u.fields.end()?0:type_field->second;
actor.gameobject_type=type;
auto display=u.fields.find(turtle_entity_fields::GAMEOBJECT_DISPLAYID);
{auto st=u.fields.find(turtle_entity_fields::GAMEOBJECT_STATE);
auto lvl=u.fields.find(turtle_entity_fields::GAMEOBJECT_LEVEL);
gw_go_log("GW_GO create guid=%llx entry=%u type=%u display=%u state=%u kind=%u flags=0x%x ttime=%lld level=%u pos=%.2f,%.2f,%.2f,%.2f\n",(unsigned long long)u.guid,actor.entry,type,
display==u.fields.end()?0u:display->second,st==u.fields.end()?0u:st->second,unsigned(u.kind),unsigned(u.update_flags),
u.transport_time?(long long)*u.transport_time:-1LL,lvl==u.fields.end()?0u:lvl->second,
u.movement?double(u.movement->position[0]):-1.0,u.movement?double(u.movement->position[1]):-1.0,
u.movement?double(u.movement->position[2]):-1.0,u.movement?double(u.movement->position[3]):-1.0);}
actor.questgiver=type==2;
auto state=u.fields.find(turtle_entity_fields::GAMEOBJECT_STATE);
// Same rule as the create serializer (codec), so both count the same presented objects.
if(!turtle_presentable_game_object(type,actor.entry,display==u.fields.end()?0:display->second,
state==u.fields.end()?0:state->second)){++unsupported;continue;}
if(type==15){
// Codec rule for MO transports: a loop period (GAMEOBJECT_LEVEL or the route table) and the path word.
// Octo sends ship creates with a position block, so movement alone must not admit one the codec
// leaves out: that count mismatch dropped the whole update (Gitea #8, zeppelins/boats on OCTO).
auto level=u.fields.find(turtle_entity_fields::GAMEOBJECT_LEVEL);
uint32_t period=level==u.fields.end()?0u:level->second;if(!period)period=turtle_mo_server_period(actor.entry);
if(!period || period>86400000u || !u.transport_time){
gw_go_log("GW_GO dropped-mo guid=%llx entry=%u period=%u ttime=%d\n",(unsigned long long)u.guid,actor.entry,period,int(bool(u.transport_time)));
++unsupported;continue;}
}
actor.modern=forever_game_object_guid(u.guid,actor.entry,realm,map);
actor.map_object=display!=u.fields.end() && turtle_wmo_game_object_display(display->second);
#ifdef GW_GAMEOBJECT_AUTHORITY_PROFILE_HEADER
// A 70334 MO transport is built from its GameObject template at create time (live 2026-11-24: an
// uncached ship create crashed the client, ACCESS_VIOLATION at 0x10). Push the reviewed template first,
// as the creature branch does with 0x4b0006; the client's later query gets the same reply.
if(type==15){
GameObjectTemplateReply probe;probe.entry=actor.entry;
if(auto authority=gameobject_authority_profile::lookup(probe)){
GameObjectTemplateReply reply;reply.entry=actor.entry;reply.found=true;reply.type=authority->type;
reply.display=authority->source_display;reply.names[0]=authority->source_name;reply.data=authority->source_data;
GameObjectTemplateBinding binding;binding.source_guid=u.guid;binding.request_generation=binding.current_generation=actor.generation;
binding.entry=actor.entry;binding.map=map;binding.realm=realm;binding.native_guid=actor.modern;
binding.template_size=authority->template_size;binding.native_display_id=authority->native_display;binding.references=authority->references;
auto projection=forever_gameobject_template(reply,binding);
if(projection.packet){emit(projection.packet->opcode,projection.packet->body);gw_go_log("GW_GO template-pushed entry=%u bytes=%zu\n",actor.entry,projection.packet->body.size());}
else{gw_go_log("GW_GO template-held entry=%u holds=%zu\n",actor.entry,projection.held.size());++unsupported;continue;} // never create a ship the client cannot resolve
}else{++unsupported;continue;}
}
#endif
bool present=true;
if(map==0 && type==11){
auto lift=std::find_if(UndercityTransportSpawns.begin(),UndercityTransportSpawns.end(),
[&](const auto& row){return row.entry==actor.entry;});
if(lift!=UndercityTransportSpawns.end()){
const auto index=size_t(lift-UndercityTransportSpawns.begin());
undercity_seen.set(index);
if(undercity_filled[index]){
const auto prior=forever_game_object_guid(undercity_source_guid(*lift),actor.entry,realm,0);
if(prior==actor.modern){actor.sent=true;present=false;}
else emit(0x5e0000,forever_object_removal(0,{},std::span(&prior,1)));
undercity_filled.reset(index);
}
}
}
if(present)gameobject_blocks.push_back(size_t(&u-updates.data()));
}
actor.eligible=true;
}
// Complete ordinary create/query admission before optional Pet
// discovery can occupy the shared outgoing request queue.
for(auto [entry,cls]:pet_definitions)if(!template_query(entry,cls,false))++unsupported;
if(corpses){
Bytes b;le(b,self.guid,8);le(b,realm,2);le(b,map,4);le(b,self_faction,4);le(b,self.cls,1);le(b,packet.opcode,4);append(b,packet.body);
auto result=codec(GW_CODEC_CORPSES,b);auto count=create_count(result);uint32_t expected=0;
for(const auto& u:updates)if(u.type==7 && (u.kind==2 || u.kind==3)){
auto i=actors.find(u.guid);if(i!=actors.end() && i->second.kind==7 && i->second.eligible){i->second.sent=true;++expected;}
}
if(count!=expected)throw Error("native corpse serializer identity mismatch");
if(count)emit(0x5e0000,std::move(result));
}
if(!gameobject_blocks.empty()){
// The serializer receives only newly admitted creates when a refresh/adoption
// shares a source batch with another GO. A full batch would re-create the rider's lift.
const bool skip_gameobject=gameobject_blocks.size()!=gameobject_creates;
const auto filtered=skip_gameobject?turtle_object_update_subset(packet,gameobject_blocks):LegacyPacket{};
const auto& input=skip_gameobject?filtered:packet;
Bytes b=header(self,realm,address,map);le(b,input.opcode,4);append(b,input.body);
auto result=codec(GW_CODEC_GAMEOBJECTS,b);
if(create_count(result)!=gameobject_blocks.size())throw Error("native gameobject serializer identity mismatch");
for(auto block:gameobject_blocks)if(auto it=actors.find(updates[block].guid);it!=actors.end())it->second.sent=true;
emit(0x5e0000,std::move(result));
}
if(!batch.actors.empty()){
if(pending.size()>=4096 || pending_bytes+batch.packet.body.size()>16777216)throw Error("native pending creature batch bound");
pending_bytes+=batch.packet.body.size();pending.push_back(std::move(batch));
}
position_updates=std::move(updates);
}
if(packet.opcode==0x61){
auto reply=turtle_creature_template(packet.body);
gw_diagnostics::journal().definition(0x61,reply.entry,reply.found,packet.body);
if(queries.erase(reply.entry)){
templates[reply.entry]=reply;
const bool asked=native_asked.erase(reply.entry)>0;
template_unannounced.erase(reply.entry);
if(auto cls=classes.find(reply.entry);cls!=classes.end())
emit(0x4b0006,forever_creature_template(reply,cls->second));
else if(asked && !reply.found)emit(0x4b0006,forever_creature_template(reply,0)); // genuine Source miss
// #87: a creature the client asked about but never saw spawned (mail sender, link) has no observed class;
// use the server's creature_template.unit_class so the name resolves instead of staying "Unknown".
else if(auto known=asked?creature_unit_classes::find(reply.entry):std::nullopt;known && turtle_presentable_creature_class(*known))
emit(0x4b0006,forever_creature_template(reply,*known));
else if(asked && template_unannounced.size()<4096)template_unannounced.insert(reply.entry);
}
}
for(auto it=pending.begin();it!=pending.end();){
bool waiting=false;uint32_t rejected=0;std::vector<uint64_t> alive;std::map<uint32_t,uint8_t> types;
for(auto [guid,gen]:it->actors){
auto actor=actors.find(guid);
if(actor==actors.end() || actor->second.generation!=gen)continue;
if(actor->second.spirit_service && !viewer_ghost)continue;
auto entry=actor->second.entry;auto meta=templates.find(entry);
if(meta==templates.end()){waiting=true;break;}
if(meta->second.found){alive.push_back(guid);types[entry]=meta->second.type;}
else ++rejected;
}
if(waiting){++it;continue;}
unsupported+=rejected;
if(!alive.empty()){
Bytes b=header(self,realm,address,map);le(b,types.size(),4);
for(auto [entry,type]:types){le(b,entry,4);le(b,type,1);}
le(b,alive.size(),4);for(auto guid:alive)le(b,guid,8);
Bytes combat;uint32_t combat_count=0;
for(auto guid:alive){
const auto& actor=actors.at(guid);
if(auto victim=actor.melee_victim?unit_binding(actor.melee_victim):std::optional<Guid128>{}){
le(combat,guid,8);append(combat,*victim);++combat_count;
}
}
if(combat_count){le(b,combat_count,4);append(b,combat);}
auto presentation=turtle_creature_create_presentation(it->packet,self.guid);
le(b,presentation.opcode,4);append(b,presentation.body);
auto result=codec(combat_count?GW_CODEC_NPCS_COMBAT:GW_CODEC_NPCS_TYPES,b);
if(create_count(result)!=alive.size())throw Error("native NPC serializer identity mismatch");
emit(0x5e0000,std::move(result));for(auto guid:alive){
auto& actor=actors.at(guid);actor.sent=true;
if(!actor.pending_values.empty()){
for(auto [index,value]:actor.pending_values)values[guid][index]=value;
pending_value_fields-=actor.pending_values.size();actor.pending_values.clear();
}
}
}
pending_bytes-=it->packet.body.size();it=pending.erase(it);
}
// The source need not resend a create when an alive GM viewer releases.
// Replay only retained, source-observed service creates after real ghost
// state arrives. This also handles metadata replies after that transition.
if(viewer_ghost)for(auto& [guid,actor]:actors){
if(actor.kind!=3 || !actor.spirit_service || actor.sent || !actor.eligible || !actor.source_create ||
actor.presentation_realm!=realm || actor.presentation_map!=map)continue;
auto meta=templates.find(actor.entry);
if(meta==templates.end() || !meta->second.found)continue;
Bytes b=header(self,realm,address,map);le(b,1,4);le(b,actor.entry,4);le(b,meta->second.type,1);
le(b,1,4);le(b,guid,8);
if(auto victim=actor.melee_victim?unit_binding(actor.melee_victim):std::optional<Guid128>{}){
le(b,1,4);le(b,guid,8);append(b,*victim);
}
auto presentation=turtle_creature_create_presentation(*actor.source_create,self.guid);
le(b,presentation.opcode,4);append(b,presentation.body);
auto result=codec(actor.melee_victim && unit_binding(actor.melee_victim)?GW_CODEC_NPCS_COMBAT:GW_CODEC_NPCS_TYPES,b);
if(create_count(result)!=1)throw Error("native spirit service serializer identity mismatch");
emit(0x5e0000,std::move(result));actor.sent=true;
if(!actor.pending_values.empty()){
for(auto [index,value]:actor.pending_values)values[guid][index]=value;
pending_value_fields-=actor.pending_values.size();actor.pending_values.clear();
}
}
// Source effect97 MINI_PET has a real F140 identity, owner and creator.
// A genuine local stat-window pet also requires its original template and owner.
for(auto& [guid,actor]:actors)if(actor.companion || actor.owned_stat_pet){
auto owner=source_pet_guid(actor.pending_values,SourcePetOwner);
auto bound=unit_binding(owner);
auto meta=templates.find(actor.entry);
const bool ready=actor.presentation_realm==realm && actor.presentation_map==map &&
(actor.companion ? source_passive_companion(actor.pending_values) : source_owned_stat_pet(actor.pending_values,self.guid,guid)) &&
owner==actor.pet_initial_owner && actor.entry==actor.pet_original_entry && bound &&
// Source CreatureType 0 is a valid template value: the shop
// repair bot and Caravan Kodo use it. The query parser and native
// creature-template writer both admit 0; requiring nonzero here
// hid those genuine, owner-bound companions.
meta!=templates.end() && meta->second.found &&
(!actor.owned_stat_pet || (self.cls==9 ? meta->second.type==3 : meta->second.type==1)) &&
!meta->second.names[0].empty() && meta->second.names[0].size()<=255 &&
(!classes.contains(actor.entry) || classes.at(actor.entry)==actor.unit_class);
if(!ready){
actor.eligible=false;
if(actor.sent){emit(0x5e0000,forever_object_removal(uint16_t(map),{},std::span(&actor.modern,1)));actor.sent=false;
for(auto& [target,words]:targets)if(words.known==3 &&
(uint64_t(words.words[0])|(uint64_t(words.words[1])<<32))==guid){words.presented.reset();target_dirty.insert(target);}}
continue;
}
actor.eligible=true;
CompanionBinding binding{guid,actor.pet_original_entry,*bound,*bound};
if(!actor.sent){
if(!actor.source_create)continue;
actor.modern=forever_pet_guid(guid,actor.pet_original_entry,realm,map);
// MINI_PET's InitEntry/SelectLevel preserves its template class;
// this does not populate the ordinary F130 class authority cache.
if(!actor.companion_template_sent){emit(0x4b0006,forever_creature_template(meta->second,actor.unit_class));actor.companion_template_sent=true;}
Bytes input=header(self,realm,address,map);le(input,1,4);le(input,actor.entry,4);le(input,meta->second.type,1);
le(input,1,4);le(input,guid,8);le(input,1,2);companion_binding(input,binding);
auto presentation=turtle_creature_create_presentation(*actor.source_create,self.guid);
le(input,presentation.opcode,4);append(input,presentation.body);
auto encoded=codec(actor.owned_stat_pet?GW_CODEC_OWNED_STAT_PET:GW_CODEC_COMPANIONS,input);
if(create_count(encoded)!=1)throw Error("native pet create identity mismatch");
emit(0x5e0000,std::move(encoded));actor.sent=true;
}
if(!actor.companion_dirty.empty()){
Bytes input;le(input,realm,2);le(input,map,4);le(input,self.guid,8);le(input,self.cls,1);
le(input,actor.power_type<4?1:0,2);if(actor.power_type<4){le(input,guid,8);le(input,actor.power_type,1);}
le(input,1,2);companion_binding(input,binding);le(input,0xa9,4);
Bytes body;le(body,1,4);le(body,0,1);le(body,0,1);Bytes raw;le(raw,guid,8);append(body,pack_guid(raw));
auto count=actor.companion_dirty.rbegin()->first/32+1;if(count>255)throw Error("companion value mask bound");
le(body,count,1);std::vector<uint32_t> mask(count);for(auto [index,value]:actor.companion_dirty){(void)value;mask[index/32]|=1u<<(index%32);}
for(auto word:mask)le(body,word,4);
for(auto [index,value]:actor.companion_dirty){(void)index;le(body,value,4);}
append(input,body);auto encoded=codec(actor.owned_stat_pet?GW_CODEC_OWNED_STAT_PET_VALUES:GW_CODEC_COMPANION_VALUES,input);
if(create_count(encoded))emit(0x5e0000,std::move(encoded));
actor.companion_dirty.clear();
}
}
if(!gameobject_values.empty()){
Bytes rows;uint32_t count=0;
for(const auto& [guid,observed]:gameobject_values){
const auto actor=actors.find(guid);const auto& fields=observed.second;
if(actor==actors.end() || actor->second.generation!=observed.first || !actor->second.sent ||
!actor->second.eligible || actor->second.kind!=5 || actor->second.presentation_realm!=realm ||
actor->second.presentation_map!=map || fields.empty())continue;
uint8_t present=(fields.contains(turtle_entity_fields::GAMEOBJECT_FLAGS)?1:0) |
(fields.contains(turtle_entity_fields::GAMEOBJECT_STATE)?2:0) |
(fields.contains(turtle_entity_fields::GAMEOBJECT_ARTKIT)?4:0) |
(actor->second.gameobject_type==3 && fields.contains(turtle_game_object_dynamic_flags_field)?8:0);
if(!present)continue;
append(rows,actor->second.modern);le(rows,present,1);
if(present&1)le(rows,turtle_static_game_object_flags(fields.at(turtle_entity_fields::GAMEOBJECT_FLAGS))|(actor->second.map_object?GO_FLAG_MAP_OBJECT:0u),4);
if(present&2)le(rows,fields.at(turtle_entity_fields::GAMEOBJECT_STATE),1);
if(present&4)le(rows,fields.at(turtle_entity_fields::GAMEOBJECT_ARTKIT),4);
if(present&8)le(rows,fields.at(turtle_game_object_dynamic_flags_field),4);
++count;
}
if(count){Bytes input;le(input,map,2);le(input,count,2);append(input,rows);emit(0x5e0000,codec(GW_CODEC_GAMEOBJECT_VALUES,input));}
}
if(!values.empty()){
// Same audited sparse-mask encoding as the gateway reference. Only
// self/already-created actors enter the source-derived values writer.
Bytes wire,powers;uint32_t count=0,power_count=0;std::vector<LegacyPacket> power_updates;
for(const auto& [guid,fields]:values){
if(fields.empty())continue;
if(count>=4096)throw Error("native unit value block bound");
uint8_t power=255;Guid128 modern;
if(guid==self.guid){power=self_power_type;modern=forever_player_guid(guid,realm);}
else{
auto it=actors.find(guid);if(it==actors.end() || !it->second.sent || it->second.kind!=3)continue;
power=it->second.power_type;modern=it->second.modern;
}
le(wire,0,1);Bytes raw;le(raw,guid,8);append(wire,pack_guid(raw));
auto n=fields.rbegin()->first/32+1;if(n>255)throw Error("native unit value mask bound");
le(wire,n,1);std::vector<uint32_t> mask(n);
for(auto [index,value]:fields){(void)value;mask[index/32]|=1u<<(index%32);}
for(auto word:mask)le(wire,word,4);
for(auto [index,value]:fields){(void)index;le(wire,value,4);}++count;
if(power<4){le(powers,guid,8);le(powers,power,1);++power_count;}
auto changed=fields.find(uint16_t(turtle_entity_fields::UNIT_FIELD_POWER1+power));
if(power<4 && changed!=fields.end())power_updates.push_back({0x47017e,forever_power_update(modern,power,changed->second)});
}
if(count){
Bytes input;le(input,realm,2);le(input,map,4);le(input,self.guid,8);le(input,self.cls,1);
le(input,power_count,2);append(input,powers);le(input,0xa9,4);le(input,count,4);le(input,0,1);append(input,wire);
auto result=codec(GW_CODEC_UNIT_VALUES_PROFILE,input);
if(create_count(result))emit(0x5e0000,std::move(result));
for(auto& update:power_updates)out.push_back(std::move(update));
}
}
// Keep genuine target changes after object creation. Never derive a
// native GUID from arbitrary source high bits or force a facing angle.
auto peer_output=translate_peers(packet,self,realm,address,map,codec,peer_items);
for(auto& item:peer_output)out.push_back(std::move(item));
// Apply source observations after actor/peer generation creation. No UI,
// database, predicted endpoint, or unacknowledged native XYZ is used.
for(const auto& update:position_updates){
if(update.kind==4){for(auto guid:update.removed)source_positions.erase(guid);continue;}
const bool create=update.kind==2 || update.kind==3;
if(create){
source_positions.erase(update.guid);
if(update.guid==self.guid && update.type==4){
if(self_position_generation==UINT64_MAX)throw Error("self source position generation bound");
++self_position_generation;
}
}
if(update.movement)source_position(update.guid,*update.movement);
else if(create || update.kind==1)source_positions.erase(update.guid);
}
if(self_presentation_ready)for(size_t role=0;role<self_controlled.size();++role){
auto& control=self_controlled[role];
if(control.known!=3)continue;
Guid128 next{};
const auto id=control.source_guid();
auto a=actors.find(id);
if(id && a!=actors.end() && a->second.sent && a->second.eligible &&
a->second.presentation_realm==realm && a->second.presentation_map==map &&
(role ? a->second.owned_stat_pet : (id>>48)==0xf130))next=a->second.modern;
if(control.presented.value_or(Guid128{})==next)continue;
Bytes input;le(input,map,2);append(input,forever_player_guid(self.guid,realm));
append(input,next);le(input,role,1);
emit(0x5e0000,codec(GW_CODEC_CONTROLLED_UNIT,input));
control.presented=next;
}
if(self_presentation_ready && self_combo.known==3){
// Points live on one source unit; a target not presented natively shows none (empty GUID).
const auto id=self_combo.source_guid();
const auto next=id?unit_binding(id).value_or(Guid128{}):Guid128{};
if(self_combo.presented.value_or(Guid128{})!=next){ // native default is empty
if(map>8191)throw Error("native combo target map bound");
Bytes input;le(input,map,2);append(input,forever_player_guid(self.guid,realm));append(input,next);
emit(0x5e0000,codec(GW_CODEC_COMBO_TARGET,input));self_combo.presented=next;
}
}
// Needs the codec's FarsightObject writer (build_forever_create.py allowed_active 56); without it the
// mask bit ships with no GUID and 70334 crashes (2026-11-24).
if(self_presentation_ready && self_farsight.known==3){
// Camera viewpoint: a source unit not presented natively leaves the camera on self (empty GUID).
const auto id=self_farsight.source_guid();
const auto next=id?unit_binding(id).value_or(Guid128{}):Guid128{};
const auto shown=self_farsight.presented.value_or(Guid128{});
bool hold=false;
if(next==Guid128{} && shown!=Guid128{}){
const auto now=std::chrono::steady_clock::now();
if(!self_farsight_clear_since)self_farsight_clear_since=now;
hold=now-*self_farsight_clear_since<std::chrono::milliseconds(1500);
}else self_farsight_clear_since.reset();
if(!hold && shown!=next){
if(map>8191)throw Error("native farsight map bound");
Bytes input;le(input,map,2);append(input,forever_player_guid(self.guid,realm));append(input,next);
emit(0x5e0000,codec(GW_CODEC_FARSIGHT,input));self_farsight.presented=next;self_farsight_clear_since.reset();
}
}
for(auto it=target_dirty.begin();it!=target_dirty.end();){
auto state=targets.find(*it);
if(state==targets.end()){it=target_dirty.erase(it);continue;}
auto owner=unit_binding(*it);auto& target=state->second;
if(!owner || target.known!=3){++it;continue;}
auto legacy=uint64_t(target.words[0])|(uint64_t(target.words[1])<<32);
auto bound=legacy?unit_binding(legacy):std::optional<Guid128>{Guid128{}};
if(!bound){++it;continue;}
if(!target.presented || *target.presented!=*bound){
if(map>8191)throw Error("native target map bound");
Bytes input;le(input,map,2);append(input,*owner);append(input,*bound);
emit(0x5e0000,codec(GW_CODEC_UNIT_TARGET,input));target.presented=*bound;
}
it=target_dirty.erase(it);
}
for(auto& [guid,actor]:actors)if(actor.sent && tracks_melee(actor) && actor.melee_pending && actor.melee_victim){
auto victim=unit_binding(actor.melee_victim);if(!victim)continue;
// Native Player::SendInitialVisiblePackets initializes an already
// attacking newly visible unit after its create. Source create flag4
// or a real attack event supplies this state, never UnitData::Target.
std::map<uint64_t,Guid128> known{{guid,actor.modern},{actor.melee_victim,*victim}};
emit(0x4d0017,forever_attack_event(TurtleAttackEvent{guid,actor.melee_victim,false,false},known));
actor.melee_pending=false;
}
if(persistent_ground_enabled)for(auto& [guid,ground]:persistent_ground){
auto found=actors.find(guid);if(found==actors.end())continue;
auto& actor=found->second;
if(actor.kind!=6||!actor.eligible||actor.presentation_realm!=realm||actor.presentation_map!=map)continue;
auto caster=unit_binding(ground.caster);auto visual=aura_visual_profile::link(ground.spell);
if(!caster||!visual||(!ground_dirty.contains(guid)&&actor.sent))continue;
auto result=codec(GW_CODEC_PERSISTENT_GROUND,
persistent_ground_input(actor.sent?1:0,uint16_t(map),actor.modern,*caster,ground,visual));
if(create_count(result)!=1)throw Error("persistent ground serializer identity mismatch");
emit(0x5e0000,std::move(result));actor.sent=true;
}
flush_channels(self.guid, realm, map, codec, out);
return out;
}
void NativeEntityTranslation::flush_channels(uint64_t self, uint16_t realm, uint32_t map,
const Codec& codec, std::vector<LegacyPacket>& out) {
if (spell_channels.empty()) return;
if (map > 8191) throw Error("channel map bound");
auto bind = [&](uint64_t id, bool unit_only) -> std::optional<Guid128> {
if (id == self && self_presentation_ready) return forever_player_guid(id, realm);
auto it = actors.find(id);
if (it == actors.end() || !it->second.sent ||
it->second.presentation_map != map || it->second.presentation_realm != realm) return {};
const auto kind = it->second.kind;
if (kind == 3 || kind == 4 || (!unit_only && (kind == 5 || kind == 6))) return it->second.modern;
return {};
};
auto emit = [&](uint32_t op, Bytes bytes) { out.push_back({op, std::move(bytes)}); };
spell_channels.flush(uint16_t(map), bind, codec, emit);
}
Bytes NativeEntityTranslation::snapshot() const{
constexpr uint32_t limit=1024,identity_bytes=48+40*limit,field_bytes=32+64*32,bytes=identity_bytes+field_bytes;Bytes b;uint32_t npcs=0,sent=0,gos=0;
for(const auto& [guid,a]:actors){(void)guid;if(a.kind==3){++npcs;if(a.sent)++sent;}else if(a.kind==5 && a.sent)++gos;}
for(auto value:{3u,bytes,npcs,sent,gos,uint32_t(templates.size()),uint32_t(pending.size()),uint32_t(requests.size()),removals,unsupported,uint32_t(std::min<size_t>(actors.size(),limit)),uint32_t(actors.size()>limit)})le(b,value,4);
uint32_t count=0;
for(const auto& [guid,a]:actors){if(count++>=limit)break;le(b,guid,8);append(b,a.modern);le(b,a.entry,4);le(b,a.kind,4);le(b,a.sent,4);auto t=templates.find(a.entry);le(b,a.kind!=3 || t==templates.end()?0:t->second.type,4);}
b.resize(identity_bytes);
for(auto value:{1u,field_bytes,source_packets,source_field_count,uint32_t(source_fields.size()),source_field_count-uint32_t(source_fields.size()),uint32_t(source_field_overflow),0u})le(b,value,4);
for(const auto& field:source_fields){
le(b,field.legacy,8);
for(auto value:{field.sequence,field.source_packet,field.opcode,field.kind,field.index,field.value})le(b,value,4);
}
b.resize(bytes);return b;
}
namespace {
uint32_t action_motion_reason(std::string_view text){
if(text=="modern monster spline profile bound")return 1;
if(text=="monster spline coordinate bound")return 2;
if(text=="monster spline duration bound")return 3;
if(text=="monster spline facing target has no matching binding")return 4;
if(text=="monster spline packet bound")return 5;
if(text=="monster spline point count bound")return 6;
if(text=="monster spline spot facing unsupported")return 7;
if(text=="monster spline target outside unit profile")return 8;
if(text=="spline outside linear-ground/smooth-flight flags")return 9;
if(text=="spline outside ordinary creature/player profile")return 10;
if(text=="spline target bearing unavailable")return 11;
if(text=="spline target has no current source position")return 12;
if(text=="unexpected monster spline target binding")return 13;
return 65535;
}
}
void NativeEntityTranslation::set_action_scope(uint64_t guid,uint16_t realm,uint32_t map){
if(diagnostic_scope_known&&diagnostic_self==guid&&diagnostic_realm==realm&&diagnostic_map==map)return;
self_melee_target.reset();
spell_channels.clear();
pending_actions.clear();latest_action.reset();diagnostic_scope_known=true;diagnostic_self=guid;diagnostic_realm=realm;diagnostic_map=map;
record_action({0,0,guid,7,0,0,realm,map,0,0,0,0,0});
}
void NativeEntityTranslation::clear_action_scope(){
self_melee_target.reset();
spell_channels.clear();
pending_actions.clear();latest_action.reset();diagnostic_scope_known=false;
}
void NativeEntityTranslation::record_action(ActionDiagnostic row){
row.sequence=++action_event_sequence;
if(action_journal.size()==16){action_journal.pop_front();}
action_journal.push_back(row);
}
void NativeEntityTranslation::note_spell_queued(uint32_t spell,uint64_t target){
if(!diagnostic_scope_known)return;
if(!spell)return;
if(!pending_actions.contains(spell)&&pending_actions.size()==16)pending_actions.erase(pending_actions.begin());
auto& pending=pending_actions[spell];if(!pending.entries.empty())pending.ambiguous=true;
if(pending.entries.size()==16){pending.entries.pop_front();pending.ambiguous=true;}
ActionBinding binding{++action_counter,target,diagnostic_self,spell,diagnostic_realm,diagnostic_map};
pending.entries.push_back(binding);latest_action=binding;
record_action({binding.action,target,diagnostic_self,1,spell,0x12e,0,0,0,0,1,0,0});
}
void NativeEntityTranslation::note_spell_result(uint32_t spell,uint32_t status,uint32_t reason){
if(!diagnostic_scope_known)return;
uint64_t action=0,target=0;uint32_t match=0;auto found=pending_actions.find(spell);
if(found!=pending_actions.end()&&!found->second.entries.empty()){
auto& pending=found->second;const auto& b=pending.entries.front();
if(!pending.ambiguous&&pending.entries.size()==1&&b.mover==diagnostic_self&&b.realm==diagnostic_realm&&b.map==diagnostic_map){action=b.action;target=b.target;match=1;}else match=2;
if(status){pending.entries.pop_front();if(pending.entries.empty())pending_actions.erase(found);}
}
record_action({action,target,diagnostic_self,2,spell,0x130,status,reason,0,0,match,0,0});
}
void NativeEntityTranslation::note_spell_go(uint32_t spell,uint64_t target){
if(!diagnostic_scope_known)return;
uint64_t action=0;uint32_t match=0;auto found=pending_actions.find(spell);
if(found!=pending_actions.end()&&!found->second.entries.empty()){
auto& pending=found->second;const auto& b=pending.entries.front();
if(!pending.ambiguous&&pending.entries.size()==1&&b.mover==diagnostic_self&&b.realm==diagnostic_realm&&b.map==diagnostic_map){action=b.action;match=1;}else match=2;
pending.entries.pop_front();if(pending.entries.empty())pending_actions.erase(found);
}
record_action({action,target,diagnostic_self,3,spell,0x132,0,0,0,0,match,0,0});
}
void NativeEntityTranslation::note_spell_damage(uint32_t spell,uint64_t target,uint32_t damage,uint32_t blocked){
if(!diagnostic_scope_known)return;
ActionDiagnostic row;row.kind=6;row.spell=spell;row.target=target;row.mover=diagnostic_self;row.opcode=0x250;row.status=damage;row.reason=blocked;
if(latest_action&&latest_action->mover==diagnostic_self&&latest_action->realm==diagnostic_realm&&latest_action->map==diagnostic_map&&target==latest_action->target){
auto parent=latest_action->spell;bool execute_child=spell==20647&&(parent==5308||parent==20658||parent==20660||parent==20661||parent==20662);
if(spell==parent||execute_child){row.action=latest_action->action;row.match=execute_child?5:3;}
}
record_action(row);
}
void NativeEntityTranslation::note_self_motion(const SplineParseObservation& observed,uint32_t opcode,bool accepted,uint32_t reason,uint32_t stage){
if((observed.available&1)&&observed.guid!=diagnostic_self)return;
ActionDiagnostic row;row.target=observed.target;row.mover=observed.guid;row.kind=accepted?4:5;row.opcode=opcode;
row.status=stage;row.reason=reason;row.spline=observed.id;row.flags=observed.flags;row.available=observed.available;row.facing=observed.face;
if(latest_action&&latest_action->mover==diagnostic_self&&latest_action->realm==diagnostic_realm&&latest_action->map==diagnostic_map){
row.action=latest_action->action;row.spell=latest_action->spell;
row.match=(observed.available&16)&&observed.target==latest_action->target&&observed.target?3:4;
}
record_action(row);
}
Bytes NativeEntityTranslation::motion_snapshot() const{
constexpr uint32_t bytes=2208;Bytes b;
for(auto v:{2u,bytes,motion_received,motion_sent,motion_unknown,motion_rejected,uint32_t(motion.size()),uint32_t(action_journal.size())})le(b,v,4);
for(const auto& item:motion){
const auto& s=item.spline;le(b,s.guid,8);append(b,item.modern);le(b,s.id,4);le(b,s.duration,4);
for(auto v:s.start)le(b,std::bit_cast<uint32_t>(v),4);
// Source STOP has no path: its authoritative start is the stop point.
for(auto v:s.points.empty()?s.start:s.points.back())le(b,std::bit_cast<uint32_t>(v),4);
le(b,s.points.size(),4);le(b,s.face,4);
}
// Each row is64 bytes: identity24, id/duration8, XYZ24, count/facing8.
b.resize(1056);
for(const auto& row:action_journal){
le(b,row.action,8);le(b,row.target,8);le(b,row.mover,8);
for(auto v:{row.kind,row.spell,row.opcode,row.status,row.reason,row.spline,row.flags,row.match,row.available,row.facing})le(b,v,4);
le(b,row.sequence,8);
}
b.resize(bytes);return b;
}
std::optional<Bytes> NativeEntityTranslation::companion_name_query(std::span<const uint8_t> body,uint16_t realm,uint32_t map) const{
Reader reader(body);auto raw=unpack_guid(reader,16);reader.end();Guid128 modern{};std::copy(raw.begin(),raw.end(),modern.begin());
for(const auto& [source,actor]:actors){(void)source;
if(!actor.companion || !actor.sent || !actor.eligible || actor.modern!=modern ||
actor.presentation_realm!=realm || actor.presentation_map!=map || !source_passive_companion(actor.pending_values))continue;
auto meta=templates.find(actor.entry);if(meta==templates.end() || !meta->second.found || meta->second.names[0].empty() || meta->second.names[0].size()>255)return {};
Bytes input;append(input,modern);le(input,source_pet_word(actor.pending_values,SourcePetNameTimestamp),4);cstring(input,meta->second.names[0]);return input;
}return {};
}