Files

2399 lines
192 KiB
C++

#include "gateway/club_identity.hpp"
// SPDX-License-Identifier: GPL-2.0-or-later
// Experimental adapter for read-only Trinity serializer types; no server/database access.
#include "UpdateFields.h"
#include "ByteBuffer.h"
#include "Errors.h"
#include "SystemPackets.h"
#include "QueryPackets.h"
#include "MiscPackets.h"
#include "gateway/corpse.hpp"
#include "gateway/movement_modes.hpp"
#include "MovementPackets.h"
#include "NPCPackets.h"
#include "ItemPackets.h"
#include "CombatLogPackets.h"
#include "CombatPackets.h"
#include "ReputationPackets.h"
#include "SpellPackets.h"
#include "AuthenticationPackets.h"
#include "HotfixPackets.h"
#include "ClientConfigPackets.h"
#include "CollectionPackets.h"
#include "GuildPackets.h"
#include "LootPackets.h"
#include "PartyPackets.h"
#include "InstancePackets.h"
#include "TradePackets.h"
#include "Group.h"
#include "Player.h"
#include "Loot.h"
#include "gateway/chat.hpp"
#include "gateway/character_creation.hpp"
#include "gateway/random_roll.hpp"
#include "gateway/auras.hpp"
#include "gateway/aura_state.hpp"
#include "gateway/aura_visual_profile.hpp"
#include "gateway/unit_presentation.hpp"
#include "gateway/peer_armor_numeric.hpp"
#include "gateway/emote_profile.hpp"
#include "ObjectMgr.h"
#include "BaseEntity.h"
#include "gateway/object_updates.hpp"
#include "gateway/pet_presentation.hpp"
#include "gateway/pet_stable.hpp"
#include "gateway/world.hpp"
#include "gateway/roster_translation.hpp"
#include "gateway/queries.hpp"
#include "gateway/splines.hpp"
#include "gateway/gameplay.hpp"
#include "gateway/quest_packets.hpp"
#include "gateway/quest_log.hpp"
#include "gateway/spell_damage.hpp"
#include "gateway/loot.hpp"
#include "gateway/reputation.hpp"
#include "gateway/talents.hpp"
#include "gateway/professions.hpp"
#include "gateway/profession_delta.hpp"
#include "gateway/exploration.hpp"
#ifndef GW_TURTLE_LOGIN_PROFILE_HEADER
#define GW_TURTLE_LOGIN_PROFILE_HEADER "gateway/turtle_login_profile.hpp"
#endif
#include GW_TURTLE_LOGIN_PROFILE_HEADER
#include "gateway/item_sparse_compat.hpp"
#include "gateway/source_toy_compat.hpp"
#include "gateway/source_recipe_compat.hpp"
#include "gateway/generated_transmog_items.hpp"
#include "gateway/broadcast_text_reply.hpp"
#include "gateway/item_enchantment_visual_profile.hpp"
#include "gateway/item_random_property_profile.hpp"
#ifndef GW_ITEM_RENDER_PROFILE_HEADER
#define GW_ITEM_RENDER_PROFILE_HEADER "gateway/item_render_profile.hpp"
#endif
#include GW_ITEM_RENDER_PROFILE_HEADER
#include "gateway/peer_item_visual.hpp"
#include "gateway/peer_item_appearances.hpp"
#include "turtle_fields.hpp"
#include "forever_power_profile.hpp"
#include "forever_spec_profile.hpp"
#include "gateway/forever_serializer.hpp"
#include "gateway/keyring_wire.hpp"
#include <bit>
#include <cstdlib>
#include <algorithm>
#include <cmath>
#include <numbers>
#include <set>
#include <limits>
void ByteBuffer::append(uint8 const* src,size_t count) {
if(!src || !count || _wpos+count>1048576) throw ByteBufferPositionException(_wpos,size(),count);
FlushBits(); if(_storage.size()<_wpos+count) _storage.resize(_wpos+count);
std::memcpy(_storage.data()+_wpos,src,count);_wpos+=count;
}
void ByteBuffer::put(size_t pos,uint8 const* src,size_t count) {
if(!src || pos>size() || count>size()-pos)throw ByteBufferPositionException(pos,size(),count);
std::memcpy(_storage.data()+pos,src,count);
}
ByteBuffer& operator<<(ByteBuffer& b,Position::ConstStreamer<Position::XYZ> const& s) {
b<<s.Pos->GetPositionX()<<s.Pos->GetPositionY()<<s.Pos->GetPositionZ();return b;
}
WorldPackets::Packet::Packet(WorldPacket&& p):_worldPacket(std::move(p)) {}
WorldPackets::ServerPacket::ServerPacket(OpcodeServer opcode,size_t size,ConnectionType connection)
:Packet(WorldPacket(opcode,size,connection)) {}
void WorldPackets::ServerPacket::Read() {std::abort();}
ObjectGuid const ObjectGuid::Empty{};
ByteBuffer& operator<<(ByteBuffer& b,ObjectGuid const& guid) {
auto bytes=gateway::pack_guid(guid.GetRawValue()); b.append(bytes.data(),bytes.size()); return b;
}
ByteBufferPositionException::ByteBufferPositionException(size_t,size_t,size_t):ByteBufferException("buffer range"){}
ByteBufferInvalidValueException::ByteBufferInvalidValueException(char const*,std::string_view):ByteBufferException("invalid buffer value"){}
namespace Trinity {
[[noreturn]] void Assert(char const*,int,char const*,char const*,std::string) noexcept { std::abort(); }
[[noreturn]] void Assert(char const*,int,char const*,char const*,std::string,char const*,...) noexcept { std::abort(); }
}
std::string GetDebugInfo() { return {}; }
template<class F,class V> void set(F& field,V value) { using T=typename F::value_type; const_cast<T&>(*field)=T(value); }
// Instance flags are not ItemSparse prototype flags. Tortoise Item.h::
// ItemDynFlags and Forever ItemTemplate.h::ItemFieldFlags share these four
// confirmed meanings only: soulbound, unlocked, wrapped and readable. In
// particular source UNK6 (0x40) and custom BOA (0x40000) are not permission
// to enable unrelated native flags. Unreviewed state remains unrepresented.
static uint32 forever_item_dynamic_flags(uint32 flags) {
return flags & (0x1u | 0x4u | 0x8u | 0x200u);
}
// Existing installed packages contain valid rows only. New staged packages
// can also carry source-authoritative per-item relation removals; accept both
// generated header shapes without changing a running client's package.
template<class Record> DB2Manager::HotfixRecord::Status item_hotfix_status(const Record& row) {
if constexpr(requires { row.status; })return static_cast<DB2Manager::HotfixRecord::Status>(row.status);
else return DB2Manager::HotfixRecord::Status::Valid;
}
template<class M,class T,int32 B,uint32 I,class V>
void changed(M& mask,UF::UpdateField<T,B,I>& field,V value){set(field,value);if constexpr(B>=0)mask.Set(B);mask.Set(I);}
static uint8_t source_xp_rest_state(uint32_t player_bytes2) {
// Tortoise Player::SetRestBonus publishes this in PLAYER_BYTES_2 byte 3.
// The native RestInfo XP state uses the same rested/normal values.
const auto state = uint8_t(player_bytes2 >> 24);
// Zero carries no rest transition in an unrelated PLAYER_BYTES_2 update.
if (state != 0 && state != 1 && state != 2) throw gateway::Error("unsupported source XP rest state");
return state;
}
static float player_cast_factor(uint32_t word) {
const float factor = std::bit_cast<float>(word);
if (!std::isfinite(factor) || factor < 0.0f) throw gateway::Error("invalid player cast time factor");
return factor;
}
static bool player_damage_modifier(UF::ActivePlayerData& active, unsigned index, uint32_t word) {
if (index < Turtle::PLAYER_FIELD_MOD_DAMAGE_DONE_POS || index > Turtle::PLAYER_FIELD_MOD_DAMAGE_DONE_PCT_END)
return false;
UF::MutableFieldReference<UF::ActivePlayerData, true> ref{active};
if (index < Turtle::PLAYER_FIELD_MOD_DAMAGE_DONE_NEG) {
ref.ModifyValue(&UF::ActivePlayerData::ModDamageDonePos, index - Turtle::PLAYER_FIELD_MOD_DAMAGE_DONE_POS)
.SetValue(std::bit_cast<int32_t>(word));
} else if (index < Turtle::PLAYER_FIELD_MOD_DAMAGE_DONE_PCT) {
ref.ModifyValue(&UF::ActivePlayerData::ModDamageDoneNeg, index - Turtle::PLAYER_FIELD_MOD_DAMAGE_DONE_NEG)
.SetValue(std::bit_cast<int32_t>(word));
} else {
const auto factor = std::bit_cast<float>(word);
if (!std::isfinite(factor)) throw gateway::Error("nonfinite school damage modifier");
ref.ModifyValue(&UF::ActivePlayerData::ModDamageDonePercent, index - Turtle::PLAYER_FIELD_MOD_DAMAGE_DONE_PCT)
.SetValue(factor);
}
return true;
}
static void explored_zone_fields(UF::ActivePlayerData& active,const std::map<uint16_t,uint32_t>& fields,bool create){
static_assert(PLAYER_DATA_FLAG_EXPLORED_ZONES_INDEX==1);
auto pairs=gateway::source_explored_zone_pairs(fields,create);
UF::MutableFieldReference<UF::ActivePlayerData,true> ref{active};
auto vector=ref.ModifyValue(&UF::ActivePlayerData::BitVectors)
.ModifyValue(&UF::BitVectors::Values,PLAYER_DATA_FLAG_EXPLORED_ZONES_INDEX);
for(unsigned i=0;i<pairs.size();++i)
vector.ModifyValue(&UF::BitVector::Values,i).SetValue(pairs[i]);
}
void unit_combat_fields(UF::UnitData& unit,const gateway::LegacyObjectUpdate& update) {
auto value=[&](unsigned index){auto it=update.fields.find(index);return it==update.fields.end()?uint32_t(0):it->second;};
auto number=[&](unsigned index){auto v=std::bit_cast<float>(value(index));if(!std::isfinite(v))throw gateway::Error("nonfinite unit combat statistic");return v;};
for(unsigned i=0;i<2;++i)const_cast<uint32&>(unit.AttackRoundBaseTime[i])=value(Turtle::UNIT_FIELD_BASEATTACKTIME+i);
set(unit.RangedAttackRoundBaseTime,value(Turtle::UNIT_FIELD_RANGEDATTACKTIME));
set(unit.MinDamage,number(Turtle::UNIT_FIELD_MINDAMAGE));set(unit.MaxDamage,number(Turtle::UNIT_FIELD_MAXDAMAGE));
set(unit.MinOffHandDamage,number(Turtle::UNIT_FIELD_MINOFFHANDDAMAGE));set(unit.MaxOffHandDamage,number(Turtle::UNIT_FIELD_MAXOFFHANDDAMAGE));
set(unit.MinRangedDamage,number(Turtle::UNIT_FIELD_MINRANGEDDAMAGE));set(unit.MaxRangedDamage,number(Turtle::UNIT_FIELD_MAXRANGEDDAMAGE));
set(unit.AttackPower,int32_t(value(Turtle::UNIT_FIELD_ATTACK_POWER)));set(unit.RangedAttackPower,int32_t(value(Turtle::UNIT_FIELD_RANGED_ATTACK_POWER)));
auto melee=value(Turtle::UNIT_FIELD_ATTACK_POWER_MODS),ranged=value(Turtle::UNIT_FIELD_RANGED_ATTACK_POWER_MODS);
set(unit.AttackPowerModPos,std::bit_cast<int16_t>(uint16_t(melee)));set(unit.AttackPowerModNeg,std::bit_cast<int16_t>(uint16_t(melee>>16)));
set(unit.RangedAttackPowerModPos,std::bit_cast<int16_t>(uint16_t(ranged)));set(unit.RangedAttackPowerModNeg,std::bit_cast<int16_t>(uint16_t(ranged>>16)));
set(unit.AttackPowerMultiplier,number(Turtle::UNIT_FIELD_ATTACK_POWER_MULTIPLIER));set(unit.RangedAttackPowerMultiplier,number(Turtle::UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER));
for(unsigned i=0;i<5;++i)const_cast<int32&>(unit.Stats[i])=int32_t(value(Turtle::UNIT_FIELD_STAT0+i));
for(unsigned i=0;i<7;++i)const_cast<int32&>(unit.Resistances[i])=int32_t(value(Turtle::UNIT_FIELD_RESISTANCES+i));
set(unit.BaseHealth,int32_t(value(Turtle::UNIT_FIELD_BASE_HEALTH)));set(unit.BaseMana,int32_t(value(Turtle::UNIT_FIELD_BASE_MANA)));
set(unit.AuraState,gateway::translate_aura_states(value(Turtle::UNIT_FIELD_AURASTATE)).native_flags);
}
void trait_config(UF::ActivePlayerData& active,uint32_t spec,uint32_t config_id,const std::vector<gateway::TalentRank>& ranks) {
set(active.ActiveCombatTraitConfigID,config_id);
UF::MutableFieldReference<UF::ActivePlayerData,true> ref{active};
auto config=ref.ModifyValue(&UF::ActivePlayerData::TraitConfigs,int32_t(config_id));
config.ModifyValue(&UF::TraitConfig::ID).SetValue(int32_t(config_id));
config.ModifyValue(&UF::TraitConfig::Name).SetValue(std::string("Local Turtle"));
config.ModifyValue(&UF::TraitConfig::Type).SetValue(int32(1));
config.ModifyValue(&UF::TraitConfig::ChrSpecializationID).SetValue(int32_t(spec));
config.ModifyValue(&UF::TraitConfig::CombatConfigFlags).SetValue(int32(1));
config.ModifyValue(&UF::TraitConfig::LocalIdentifier).SetValue(int32(1));
auto entries=config.ModifyValue(&UF::TraitConfig::Entries);
for(auto r:ranks){
auto& entry=UF::AddDynamicUpdateFieldValue(entries);
entry.TraitNodeID=int32_t(r.node);
entry.TraitNodeEntryID=int32_t(r.entry);
entry.Rank=int32_t(r.rank);
}
}
// Peer wire policy: Player.cpp::BuildValuesCreate(None) writes Object, Unit,
// Player only. ActivePlayer/owner/party data never enters this separate route.
namespace {
using namespace gateway;
static_assert(SourceSkillFirst==Turtle::PLAYER_SKILL_INFO_1_1);
struct PeerSnapshot {
std::string name;
std::map<uint16_t,uint32_t> fields;
std::map<unsigned,peer_item_visual::Template> visible_templates;
};
static float peer_number(uint32_t bits) { auto n=std::bit_cast<float>(bits);if(!std::isfinite(n))throw Error("nonfinite peer statistic");return n; }
static Bytes peer_status(const BasicMovement& move,uint16_t realm,bool source_create_snapshot=false) {
const auto& m=move.state;
// The object-create decoder has already exhausted its bounded spline tail.
// Admit its authoritative position snapshot without forwarding the legacy
// spline-active bit or claiming the trajectory is implemented. Standalone
// movement still requires its original stricter contract.
const uint32_t allowed=0x1ffu|0x6000u|0x200000u|movement_modes::SourceMask|
(source_create_snapshot?0x00400000u:0u);
if(!m.guid || (m.guid>>32) || (m.flags&~allowed) || move.has_spline_elevation)
throw Error("unproven peer movement flags or identity");
// Source1.12 carries the direction quartet only with FALLING. Native
// Status requires it for FALLING_FAR too; far-only has no lossless proof.
if(move.falling_far&&!move.falling)throw Error("peer far-only movement lacks source direction quartet");
for(auto v:m.position)if(!std::isfinite(v))throw Error("nonfinite peer position");
for(auto pair:{3u,12u,48u,192u})if((m.flags&pair)==pair)throw Error("contradictory peer movement directions");
if((m.flags&0x1000) && (m.flags&(0xffu|0x6000u)))throw Error("rooted peer movement contradiction");
if(move.falling!=bool(m.flags&0x2000) || move.falling_far!=bool(m.flags&0x4000) ||
move.swimming!=bool(m.flags&0x200000) || move.has_direction!=move.falling ||
move.has_fall!=(move.falling||move.falling_far||move.fall_time!=0))
throw Error("inconsistent peer movement tails");
for(auto v:{move.swim_pitch,move.vertical_speed,move.sin_angle,move.cos_angle,move.horizontal_speed})
if(!std::isfinite(v))throw Error("nonfinite peer movement tail");
// MovementPackets.cpp::operator<<(MovementInfo): server Status, nine bits.
Bytes out=pack_guid(forever_player_guid(m.guid,realm));
uint64_t flags=(m.flags&0x1ffu)|movement_modes::to_native(m.flags);
if(move.falling)flags|=0x800;if(move.falling_far)flags|=0x1000;if(move.swimming)flags|=0x100000;
le(out,flags,8);le(out,m.time,4);
for(unsigned i=0;i<4;++i){auto v=i==3?forever_facing(m.position[i]):m.position[i];le(out,std::bit_cast<uint32_t>(v),4);}
le(out,std::bit_cast<uint32_t>(move.swim_pitch),4);le(out,0,4);
le(out,0,4);le(out,0,4);le(out,std::bit_cast<uint32_t>(1.0f),4);
le(out,move.has_fall?0x20:0,1);le(out,0,1);
if(move.has_fall){le(out,move.fall_time,4);le(out,std::bit_cast<uint32_t>(move.vertical_speed),4);
bool direction=move.falling||move.falling_far;le(out,direction?0x80:0,1);
if(direction){le(out,std::bit_cast<uint32_t>(move.sin_angle),4);le(out,std::bit_cast<uint32_t>(move.cos_angle),4);le(out,std::bit_cast<uint32_t>(move.horizontal_speed),4);}}
return out;
}
static BasicMovement peer_source_movement(Reader& r,uint64_t expected) {
auto raw=unpack_guid(r,8);Reader id(raw);if(id.le(8)!=expected)throw Error("peer movement identity mismatch");
BasicMovement m{};m.state.guid=expected;m.state.flags=uint32_t(r.le(4));m.state.time=uint32_t(r.le(4));
if(m.state.flags&0x02000000)throw Error("peer transport movement unsupported");
for(auto& v:m.state.position)v=r.f32();
m.swimming=bool(m.state.flags&0x200000);if(m.swimming)m.swim_pitch=r.f32();
m.fall_time=uint32_t(r.le(4));m.falling=bool(m.state.flags&0x2000);m.falling_far=bool(m.state.flags&0x4000);
m.has_fall=m.falling||m.falling_far||m.fall_time!=0;m.has_direction=m.falling;
if(m.has_direction){m.vertical_speed=r.f32();m.cos_angle=r.f32();m.sin_angle=r.f32();m.horizontal_speed=r.f32();}
if(m.state.flags&0x04000000){m.has_spline_elevation=true;m.spline_elevation=r.f32();}
r.end();return m;
}
// A full Source player-create supplies zero for omitted value words. On a
// delta the caller supplies the complete appearance from this player's create
// and subsequent values. Existing appearances only need a forward mapping.
static void player_customizations(UF::PlayerData& player, uint32_t identity,
uint32_t appearance, uint32_t appearance2) {
const auto choices = gateway::character_creation::source_presentation_choices(
uint8_t(identity), uint8_t(identity >> 16),
{uint8_t(appearance), uint8_t(appearance >> 8), uint8_t(appearance >> 16),
uint8_t(appearance >> 24), uint8_t(appearance2)});
UF::MutableFieldReference<UF::PlayerData, true> ref{player};
auto customizations = ref.ModifyValue(&UF::PlayerData::Customizations);
for (const auto& [option, choice] : choices) {
auto& value = UF::AddDynamicUpdateFieldValue(customizations);
value.ChrCustomizationOptionID = option;
value.ChrCustomizationChoiceID = choice;
}
}
static void set_home_party_type(UF::PlayerData& player, uint8_t home) {
UF::MutableFieldReference<UF::PlayerData, true> ref{player};
ref.ModifyValue(&UF::PlayerData::PartyType, GROUP_CATEGORY_HOME).SetValue(home);
}
static void set_stable_fields(UF::ActivePlayerData& active, const PetStableDto* snapshot,
uint16_t realm, uint32_t map) {
UF::MutableFieldReference<UF::ActivePlayerData, true> self{active};
auto stable = self.ModifyValue(&UF::ActivePlayerData::PetStable, 0);
ObjectGuid master;
if (snapshot && snapshot->list.npc) {
const auto raw = forever_creature_guid(snapshot->list.npc, uint32_t(snapshot->list.npc >> 24) & 0xffffff, realm, map);
Reader id(raw);
const auto low = id.le(8), high = id.le(8);
master.SetRawValue(high, low);
}
stable.ModifyValue(&UF::StableInfo::StableMaster).SetValue(master);
if (!snapshot)
return; // Close changes only StableMaster, retaining the acquired slots and pets.
if (snapshot->list.slots > 4)
throw Error("Source pet stable capacity");
self.ModifyValue(&UF::ActivePlayerData::NumStableSlots).SetValue(snapshot->list.slots);
auto pets = stable.ModifyValue(&UF::StableInfo::Pets);
uint32_t stabled = 0;
for (size_t i = 0; i < snapshot->list.pets.size(); ++i) {
const auto& row = snapshot->list.pets[i];
const auto& metrics = snapshot->metrics[i];
if (!row.number || !row.entry || !snapshot->displays[i])
throw Error("Source pet stable identity");
if (!row.current && (metrics.loyalty_points || metrics.happiness || metrics.experience || metrics.next_xp))
throw Error("Source stabled pet metrics unavailable");
auto pet = UF::AddDynamicUpdateFieldValue(pets);
pet.ModifyValue(&UF::StablePetInfo::PetSlot).SetValue(row.current ? 0 : ++stabled);
pet.ModifyValue(&UF::StablePetInfo::PetNumber).SetValue(row.number);
pet.ModifyValue(&UF::StablePetInfo::CreatureID).SetValue(row.entry);
pet.ModifyValue(&UF::StablePetInfo::DisplayID).SetValue(snapshot->displays[i]);
pet.ModifyValue(&UF::StablePetInfo::ExperienceLevel).SetValue(row.level);
pet.ModifyValue(&UF::StablePetInfo::Name).SetValue(row.name);
pet.ModifyValue(&UF::StablePetInfo::PetFlags).SetValue(row.current ? 1 : 3);
pet.ModifyValue(&UF::StablePetInfo::LoyaltyLevel).SetValue(row.loyalty);
pet.ModifyValue(&UF::StablePetInfo::LoyaltyPoints).SetValue(metrics.loyalty_points);
pet.ModifyValue(&UF::StablePetInfo::Happiness).SetValue(metrics.happiness);
pet.ModifyValue(&UF::StablePetInfo::Experience).SetValue(metrics.experience);
pet.ModifyValue(&UF::StablePetInfo::NextLevelExperience).SetValue(metrics.next_xp);
}
}
static Bytes stable_values(const PetStableDto& dto) {
if (!dto.self || dto.self > UINT32_MAX || !dto.realm || dto.realm > 8191 || dto.map > UINT16_MAX)
throw Error("pet stable self identity");
const bool replace = dto.kind == 1;
if (replace && !dto.list.npc)
throw Error("open stable requires a bound master");
UF::ActivePlayerData active;
set_stable_fields(active, replace ? &dto : nullptr, dto.realm, dto.map);
ByteBuffer values;
values << uint8(1) << uint8(0) << uint8(3) << uint32(1u << TYPEID_ACTIVE_PLAYER);
// Full nested mask replaces the complete roster, including removed or empty rows.
active.WriteUpdate(active.GetChangesMask(), values, nullptr, nullptr, replace);
values.FlushBits();
Bytes block{0};
append(block, pack_guid(forever_player_guid(dto.self, dto.realm)));
le(block, values.size(), 4);
append(block, std::span(values.data(), values.size()));
Bytes out;
le(out, dto.map, 2);
le(out, 1, 4);
le(out, 0x80, 1);
le(out, block.size(), 4);
append(out, block);
return out;
}
static Bytes self_party_type_values(Reader& input, uint8_t home) {
auto realm = uint16_t(input.le(2));
auto map = uint32_t(input.le(4));
auto self = input.le(8);
input.end();
if (!self || self > UINT32_MAX || !realm || realm > 8191 || map > UINT16_MAX)
throw Error("invalid self party type identity");
UF::PlayerData player;
set_home_party_type(player, home);
ByteBuffer values;
values << uint8(1) << uint8(0) << uint8(3) << uint32(1u << TYPEID_PLAYER);
player.WriteUpdate(player.GetChangesMask(), values, nullptr, nullptr, false);
values.FlushBits();
Bytes block{0};
append(block, pack_guid(forever_player_guid(self, realm)));
le(block, values.size(), 4);
append(block, std::span(values.data(), values.size()));
Bytes packet;
le(packet, map, 2);
le(packet, 1, 4);
le(packet, 0x80, 1);
le(packet, block.size(), 4);
append(packet, block);
return packet;
}
static void peer_public_fields(const LegacyObjectUpdate& snapshot,const LegacyObjectUpdate& delta,
const PeerSnapshot& peer,uint16_t realm,uint32_t address,bool full,
UF::ObjectData& object,UF::UnitData& unit,UF::PlayerData& player,
UF::ObjectData::Mask& om,UF::UnitData::Mask& um,UF::PlayerData::Mask& pm) {
auto value=[&](unsigned i){auto it=snapshot.fields.find(i);return it==snapshot.fields.end()?0u:it->second;};
auto wants=[&](unsigned i){return full||delta.fields.contains(i);};
auto bytes=value(Turtle::UNIT_FIELD_BYTES_0);auto race=bytes&255,cls=(bytes>>8)&255,sex=(bytes>>16)&255;
// Tortoise SharedDefines.h::Classes: source has exactly these nine classes.
const bool source_class=cls==1||cls==2||cls==3||cls==4||cls==5||cls==7||cls==8||cls==9||cls==11;
if(!race||race>10||!source_class||sex>1||!value(Turtle::UNIT_FIELD_DISPLAYID)||!value(Turtle::UNIT_FIELD_NATIVEDISPLAYID))
throw Error("peer authoritative appearance identity missing");
if(wants(Turtle::OBJECT_FIELD_SCALE_X))changed(om,object.Scale,peer_number(value(Turtle::OBJECT_FIELD_SCALE_X)));
if(wants(Turtle::UNIT_DYNAMIC_FLAGS))changed(om,object.DynamicFlags,forever_unit_dynamic_flags(value(Turtle::UNIT_DYNAMIC_FLAGS)));
#define PEER_UNIT(source,field,type) if(wants(Turtle::source))changed(um,unit.field,type(value(Turtle::source)))
PEER_UNIT(UNIT_FIELD_DISPLAYID,DisplayID,int32_t);PEER_UNIT(UNIT_FIELD_NATIVEDISPLAYID,NativeDisplayID,int32_t);
if(value(Turtle::UNIT_FIELD_MOUNTDISPLAYID)>0x7fffffff)throw Error("invalid peer mount display");
PEER_UNIT(UNIT_FIELD_MOUNTDISPLAYID,MountDisplayID,int32_t);
if(wants(Turtle::UNIT_FIELD_BYTES_0)){
changed(um,unit.Race,uint8_t(race));changed(um,unit.ClassId,uint8_t(cls));changed(um,unit.PlayerClassId,uint8_t(cls));changed(um,unit.Sex,uint8_t(sex));
if((bytes>>24)>3)throw Error("unsupported peer power type");changed(um,unit.DisplayPower,uint8_t(bytes>>24));changed(pm,player.NativeSex,uint8_t(sex));}
PEER_UNIT(UNIT_FIELD_HEALTH,Health,int64_t);PEER_UNIT(UNIT_FIELD_MAXHEALTH,MaxHealth,int64_t);
PEER_UNIT(UNIT_FIELD_LEVEL,Level,int32_t);PEER_UNIT(UNIT_FIELD_LEVEL,EffectiveLevel,int32_t);
PEER_UNIT(UNIT_FIELD_FACTIONTEMPLATE,FactionTemplate,int32_t);
if(wants(Turtle::UNIT_FIELD_AURASTATE))changed(um,unit.AuraState,translate_aura_states(value(Turtle::UNIT_FIELD_AURASTATE)).native_flags);
if(wants(Turtle::UNIT_NPC_EMOTESTATE))changed(um,unit.EmoteState,int32_t(emote_profile::animation(value(Turtle::UNIT_NPC_EMOTESTATE))));
if(wants(Turtle::UNIT_FIELD_FLAGS)){changed(um,unit.Flags,forever_unit_flags(value(Turtle::UNIT_FIELD_FLAGS)));changed(um,unit.PvpFlags,uint8_t((value(Turtle::UNIT_FIELD_FLAGS)&0x1000)?1:0));}
if(wants(Turtle::UNIT_FIELD_BYTES_1)){changed(um,unit.StandState,uint8_t(value(Turtle::UNIT_FIELD_BYTES_1)));changed(um,unit.ShapeshiftForm,uint8_t(value(Turtle::UNIT_FIELD_BYTES_1)>>16));}
if(wants(Turtle::UNIT_FIELD_BYTES_1)||wants(Turtle::PLAYER_FIELD_BYTES2))changed(um,unit.VisFlags,forever_unit_vis_flags(value(Turtle::UNIT_FIELD_BYTES_1),value(Turtle::PLAYER_FIELD_BYTES2)));
if(wants(Turtle::UNIT_FIELD_BYTES_2))changed(um,unit.SheatheState,uint8_t(value(Turtle::UNIT_FIELD_BYTES_2)));
if(wants(Turtle::PLAYER_GUILDID)){auto raw=forever_guild_guid(value(Turtle::PLAYER_GUILDID),realm);Reader r(raw);auto low=r.le(8),high=r.le(8);ObjectGuid id;id.SetRawValue(high,low);changed(um,unit.GuildGUID,id);}
if(full)
set(player.GuildClubMemberID,guild_club_member_id(snapshot.guid,realm));
if(wants(Turtle::PLAYER_GUILDRANK)){auto rank=value(Turtle::PLAYER_GUILDRANK);if(rank>=10)throw Error("peer guild rank bound");changed(pm,player.GuildRankID,rank);}
if(wants(Turtle::PLAYER_FLAGS))changed(pm,player.PlayerFlags,forever_player_flags(value(Turtle::PLAYER_FLAGS)));
if(wants(Turtle::PLAYER_BYTES_3))changed(pm,player.PvpTitle,uint8_t(value(Turtle::PLAYER_BYTES_3)>>24));
if(wants(Turtle::UNIT_FIELD_BOUNDINGRADIUS))changed(um,unit.BoundingRadius,peer_number(value(Turtle::UNIT_FIELD_BOUNDINGRADIUS)));
if(wants(Turtle::UNIT_FIELD_COMBATREACH))changed(um,unit.CombatReach,peer_number(value(Turtle::UNIT_FIELD_COMBATREACH)));
for(unsigned power=0;power<4;++power){auto slot=ForeverClassPowerSlots[cls][power];if(slot<0)continue;
if(wants(Turtle::UNIT_FIELD_POWER1+power)){const_cast<int32&>(unit.Power[slot])=int32_t(value(Turtle::UNIT_FIELD_POWER1+power));um.Set(139);um.Set(140+slot);}
if(wants(Turtle::UNIT_FIELD_MAXPOWER1+power)){const_cast<int32&>(unit.MaxPower[slot])=int32_t(value(Turtle::UNIT_FIELD_MAXPOWER1+power));um.Set(139);um.Set(150+slot);}}
UF::MutableFieldReference<UF::PlayerData,true> player_ref{player};
for(unsigned slot=0;slot<19;++slot){auto index=Turtle::PLAYER_VISIBLE_ITEM_1_0+12*slot;
bool selected=full || (visibility_mask(slot) && delta.fields.contains(Turtle::PLAYER_FLAGS));
selected|=slot==7 && delta.fields.contains(Turtle::UNIT_FIELD_BYTES_0);
for(unsigned j=0;j<12;++j)selected|=delta.fields.contains(index+j);
if(!selected)continue;
const auto original=value(index);
auto display=race_slot_hide_profile::source_display(original),render=original;
if(auto it=peer.visible_templates.find(slot);it!=peer.visible_templates.end()){
const auto& source=it->second;
if(source.item!=original || !source.display || !peer_item_visual::matches(slot,source.inventory_type) ||
peer_item_appearances::has_native_look(original))throw Error("peer presentation template mismatch");
display=source.display;
if(auto donor=peer_item_appearances::render_item(display,source.inventory_type))render=donor;
}
auto id=forever_visible_item_id(value(Turtle::PLAYER_FLAGS),slot,render,uint8_t(race),uint8_t(sex),display);
auto visual=id?item_enchantment_visual_profile::resolve(value(index+1),value(index+2)):0;
if(visual>65535)throw Error("peer item visual bound");auto visible=player_ref.ModifyValue(&UF::PlayerData::VisibleItems,slot);
visible.ModifyValue(&UF::VisibleItem::ItemID).SetValue(id);
visible.ModifyValue(&UF::VisibleItem::ItemModifiedAppearanceID).SetValue(item_render_profile::modified_appearance(id));
visible.ModifyValue(&UF::VisibleItem::ItemVisual).SetValue(uint16_t(visual));pm.Set(229);pm.Set(230+slot);
if(slot>=15 && slot<=17){
UF::MutableFieldReference<UF::UnitData,true> unit_ref{unit};
auto weapon=unit_ref.ModifyValue(&UF::UnitData::VirtualItems,slot-15);
weapon.ModifyValue(&UF::VisibleItem::ItemID).SetValue(id);
weapon.ModifyValue(&UF::VisibleItem::ItemModifiedAppearanceID).SetValue(item_render_profile::modified_appearance(id));
weapon.ModifyValue(&UF::VisibleItem::ItemVisual).SetValue(uint16_t(visual));
um.Set(180);um.Set(181+slot-15);
}
}
if(full || delta.fields.contains(Turtle::UNIT_FIELD_BYTES_0) ||
delta.fields.contains(Turtle::UNIT_FIELD_DISPLAYID) || delta.fields.contains(Turtle::UNIT_FIELD_NATIVEDISPLAYID)) {
auto displays=forever_player_default_displays(race,sex,value(Turtle::UNIT_FIELD_DISPLAYID),value(Turtle::UNIT_FIELD_NATIVEDISPLAYID));
changed(um,unit.DisplayID,int32_t(displays.display));
changed(um,unit.NativeDisplayID,int32_t(displays.native_display));
}
if (full || delta.fields.contains(Turtle::PLAYER_BYTES) ||
delta.fields.contains(Turtle::PLAYER_BYTES_2) || delta.fields.contains(Turtle::UNIT_FIELD_BYTES_0)) {
player_customizations(player, bytes, value(Turtle::PLAYER_BYTES), value(Turtle::PLAYER_BYTES_2));
pm |= player.GetChangesMask();
}
if(full){set(player.Name,peer.name);set(player.VirtualPlayerRealm,address);set(unit.CreatureType,uint8_t(7));
set(unit.DisplayScale,1.0f);set(unit.NativeXDisplayScale,1.0f);set(unit.ModCastingSpeed,1.0f);set(unit.ModCastingSpeedNeg,1.0f);
set(unit.ModSpellHaste,1.0f);set(unit.ModHaste,1.0f);set(unit.ModRangedHaste,1.0f);set(unit.ModHasteRegen,1.0f);
set(unit.ModTimeRate,1.0f);set(unit.MaxHealthModifier,1.0f);set(unit.ManaCostMultiplier,1.0f);set(unit.NameplateDistanceMod,1.0f);
unit_combat_fields(unit,snapshot);}
UF::UnitData::FilterDisallowedFieldsMaskForFlag(um,UF::UpdateFieldFlag::None);
UF::PlayerData::FilterDisallowedFieldsMaskForFlag(pm,UF::UpdateFieldFlag::None);
#undef PEER_UNIT
}
static Bytes peer_players(std::string_view mode,const Bytes& input) {
Reader r(input);auto realm=uint16_t(r.le(2));auto address=uint32_t(r.le(4)),map=uint32_t(r.le(4));
if(realm>8191||map>65535)throw Error("peer realm or map bound");
auto header=uint16_t(r.le(2));bool templates=header&peer_item_visual::TemplateSections,refresh=header&peer_item_visual::Refresh;
auto n=unsigned(header&0x3fff);
if(n>4096 || (refresh && (n!=1 || !templates || mode!="--player-values")))throw Error("peer descriptor count or refresh bound");
std::map<uint64_t,PeerSnapshot> peers;
for(unsigned i=0;i<n;++i){auto guid=r.le(8);PeerSnapshot p;p.name=r.cstring(63);if(!guid||(guid>>32)||p.name.empty())throw Error("peer descriptor identity bound");
for(unsigned char c:p.name)if(c<32||c==127)throw Error("peer name control character");
auto fields=r.le(2);if(fields>2048)throw Error("peer source field count bound");unsigned previous=0;
for(unsigned j=0;j<fields;++j){auto index=uint16_t(r.le(2));auto value=uint32_t(r.le(4));if(index>=2048||(j&&index<=previous))throw Error("peer source fields unordered");previous=index;p.fields.emplace(index,value);}
if(templates){
auto count=r.le(1);if(count>19 || (refresh && !count))throw Error("peer visible template count");
for(unsigned j=0;j<count;++j){
auto slot=uint8_t(r.le(1));auto item=uint32_t(r.le(4)),display=uint32_t(r.le(4));auto type=uint8_t(r.le(1));
auto original=p.fields.find(Turtle::PLAYER_VISIBLE_ITEM_1_0+12*slot);
if(!item || item>0x7fffffff || !display || !peer_item_visual::matches(slot,type) ||
original==p.fields.end() || original->second!=item ||
!p.visible_templates.emplace(slot,peer_item_visual::Template{slot,item,display,type}).second)
throw Error("peer visible template source slot mismatch");
}
}
if(!peers.emplace(guid,std::move(p)).second)throw Error("duplicate peer descriptor");}
std::vector<LegacyObjectUpdate> updates;
if(refresh){
r.end();auto& [guid,peer]=*peers.begin();LegacyObjectUpdate delta;delta.kind=0;delta.guid=guid;
for(const auto& [slot,source]:peer.visible_templates)delta.fields.emplace(Turtle::PLAYER_VISIBLE_ITEM_1_0+12*slot,source.item);
updates.push_back(std::move(delta));
}else{
auto opcode=uint16_t(r.le(2));updates=turtle_object_updates(opcode,r.take(r.left()));
}
Bytes blocks;unsigned count=0;std::set<uint64_t> emitted;
for(const auto& u:updates){auto found=peers.find(u.guid);if(found==peers.end())continue;
bool create=u.kind==2||u.kind==3;if(mode=="--players"?!create:u.kind!=0)continue;
if(!emitted.insert(u.guid).second)throw Error("duplicate peer packet record");
if(create&&(u.type!=4||(u.update_flags&1)||!u.basic_movement))throw Error("invalid peer source create role");
for(const auto& [index,value]:u.fields){auto f=found->second.fields.find(index);if(f==found->second.fields.end()||f->second!=value)throw Error("peer historical snapshot differs from raw packet");}
auto& fields=found->second.fields;
if(!fields.contains(0)||fields.at(0)!=uint32_t(u.guid)||(fields.contains(1)&&fields.at(1)!=0)||!fields.contains(2)||fields.at(2)!=0x19)
throw Error("peer snapshot GUID/type identity mismatch");
LegacyObjectUpdate snapshot=u;snapshot.fields=fields;UF::ObjectData object;UF::UnitData unit;UF::PlayerData player;
UF::ObjectData::Mask om;UF::UnitData::Mask um;UF::PlayerData::Mask pm;
peer_public_fields(snapshot,u,found->second,realm,address,create,object,unit,player,om,um,pm);
ByteBuffer values;auto visibility=UF::UpdateFieldFlag::None;Bytes block;
if(create){values<<uint8(visibility)<<uint8(3)<<uint8(204)<<uint8(205)<<uint8(255)<<uint8(1);
object.WriteCreate(visibility,values,nullptr,nullptr);unit.WriteCreate(visibility,values,nullptr,nullptr);player.WriteCreate(visibility,values,nullptr,nullptr);values.FlushBits();
block={2};append(block,pack_guid(forever_player_guid(u.guid,realm)));le(block,6,1);append(block,Bytes{0x84,0,0});le(block,0,4);
append(block,peer_status(*u.basic_movement,realm,true));for(float speed:{u.speeds[0],u.speeds[1],u.speeds[2],u.speeds[3],u.speeds[4],7.0f,4.5f,u.speeds[5],3.141593f})le(block,std::bit_cast<uint32_t>(speed),4);
le(block,0,4);le(block,std::bit_cast<uint32_t>(1.0f),4);for(unsigned j=0;j<17;++j)le(block,0,4);le(block,0,1);
}else{bool have_o=om.IsAnySet(),have_u=um.IsAnySet(),have_p=pm.IsAnySet();if(!have_o&&!have_u&&!have_p)continue;
values<<uint8(0)<<uint8(0)<<uint8(3)<<uint32((have_o?(1u<<TYPEID_OBJECT):0)|(have_u?(1u<<TYPEID_UNIT):0)|(have_p?(1u<<TYPEID_PLAYER):0));
if(have_o)object.WriteUpdate(om,values,nullptr,nullptr,false);if(have_u)unit.WriteUpdate(um,values,nullptr,nullptr,false);if(have_p)player.WriteUpdate(pm,values,nullptr,nullptr,false);values.FlushBits();
block={0};append(block,pack_guid(forever_player_guid(u.guid,realm)));}
le(block,values.size(),4);append(block,std::span(values.data(),values.size()));append(blocks,block);++count;
if (peer_armor_numeric::capture_path()) {
std::array<peer_armor_numeric::Slot, 19> slots;
size_t selected = 0;
for (unsigned slot = 0; slot < slots.size(); ++slot) {
if (!create && !pm[230 + slot]) continue;
auto field = fields.find(Turtle::PLAYER_VISIBLE_ITEM_1_0 + 12 * slot);
const auto& v = player.VisibleItems[slot];
slots[selected++] = {slot, field == fields.end() ? 0u : field->second,
uint32_t(v.ItemID), uint32_t(v.ItemModifiedAppearanceID)};
}
peer_armor_numeric::write(create, slots, selected);
}
}
Bytes out;le(out,map,2);le(out,count,4);le(out,0x80,1);le(out,blocks.size(),4);append(out,blocks);return out;
}
}
gateway::Bytes gateway::source_forever_serialize(std::string_view mode,const Bytes& input,bool talent_experiment) {
require_legacy_object_update_layout(nullptr);
if(input.size()>1048576)throw Error("codec input bound");
if(mode=="--guild-permissions"){
Reader r(input);const auto rank=uint32_t(r.le(4)),flags=uint32_t(r.le(4));r.end();
if(rank>=10)throw Error("guild permissions rank bound");
WorldPackets::Guild::GuildPermissionsQueryResults packet;
packet.RankID=rank;packet.Flags=std::bit_cast<int32_t>(flags);
packet.WithdrawGoldLimit=0;packet.NumTabs=0;packet.Tab.resize(8);
const auto* output=packet.Write();return Bytes(output->data(),output->data()+output->size());
}
if(mode=="--random-roll"){
Reader r(input);const auto realm=uint16_t(r.le(2));
const auto roll=turtle_random_roll(r.take(20));r.end();
if(!realm)throw Error("random roll realm absent");
WorldPackets::Misc::RandomRoll packet;
auto guid=forever_player_guid(roll.player,realm);Reader id(guid);
const auto low=id.le(8),high=id.le(8);packet.Roller.SetRawValue(high,low);
// Source name/chat/self projections carry no modern WowAccount proof.
packet.RollerWowAccount.Clear();
packet.Min=int32_t(roll.minimum);packet.Max=int32_t(roll.maximum);packet.Result=int32_t(roll.result);
const auto* output=packet.Write();return Bytes(output->data(),output->data()+output->size());
}
if(mode=="--world-transfer"){
Reader r(input);auto kind=r.le(1);
auto bytes=[](WorldPacket const* p){return Bytes(p->data(),p->data()+p->size());};
if(kind==0){WorldPackets::Movement::TransferPending p;p.MapID=int32_t(r.le(4));
auto x=r.f32(),y=r.f32(),z=r.f32();if(p.MapID<0 || p.MapID>65535 || !std::isfinite(x)||!std::isfinite(y)||!std::isfinite(z))throw Error("transfer destination bound");
p.OldMapPosition.Pos.Relocate(x,y,z);r.end();return bytes(p.Write());}
if(kind==1 || kind==3){auto sequence=uint32_t(r.le(4));r.end();
if(kind==1){WorldPackets::Movement::SuspendToken p;p.SequenceIndex=sequence;p.Reason=1;return bytes(p.Write());}
WorldPackets::Movement::ResumeToken p;p.SequenceIndex=sequence;p.Reason=1;return bytes(p.Write());}
if(kind==2){WorldPackets::Movement::NewWorld p;p.MapID=int32_t(r.le(4));
auto x=r.f32(),y=r.f32(),z=r.f32(),o=r.f32();auto counter=r.le(4);r.end();
if(p.MapID<0 || p.MapID>65535 || !counter || counter>INT32_MAX || !std::isfinite(x)||!std::isfinite(y)||!std::isfinite(z)||!std::isfinite(o))throw Error("NewWorld destination/counter bound");
p.Loc.Pos.Pos.Relocate(x,y,z,forever_facing(o));p.Reason=16; // Pinned NEW_WORLD_NORMAL, nonseamless.
p.Counter=int32_t(counter);return bytes(p.Write());}
throw Error("unsupported world-transfer kind");
}
if(mode=="--party-invite"){
Reader r(input);auto realm=uint16_t(r.le(2));auto address=uint32_t(r.le(4));auto guid=r.le(8);auto name=r.cstring(48);r.end();
if(!realm || realm>8191 || !address || !guid || guid>UINT32_MAX || name.empty())throw Error("party invite identity bound");
auto raw=forever_player_guid(guid,realm);Reader id(raw);auto low=id.le(8),high=id.le(8);
WorldPackets::Party::PartyInvite packet;packet.InviterGUID.SetRawValue(high,low);packet.InviterName=name;
packet.CanAccept=true;packet.InviterRealm=WorldPackets::Auth::VirtualRealmInfo(address,true,false,"","");
auto p=packet.Write();return Bytes(p->data(),p->data()+p->size());
}
if(mode=="--party-update"){
Reader r(input);auto realm=uint16_t(r.le(2));auto counter=r.le(8);auto sequence=uint32_t(r.le(4));
auto clear=r.le(1),raid=r.le(1),leader_faction=r.le(1),leader=r.le(8),count=r.le(1);
if(!realm || realm>8191 || !counter || !sequence || clear>1 || raid>1 || count>(raid?40u:5u) ||
(clear?(count||leader||leader_faction):(!count||!leader||(leader_faction!=3&&leader_faction!=5))))throw Error("party presentation header bound");
auto player_guid=[&](uint64_t id){if(!id || id>UINT32_MAX)throw Error("party source player identity bound");auto raw=forever_player_guid(id,realm);Reader g(raw);auto low=g.le(8),high=g.le(8);ObjectGuid result;result.SetRawValue(high,low);return result;};
WorldPackets::Party::PartyUpdate packet;
// The published 70338 capture supplies these values for the 70291+ layout.
packet.Classic70291_BeforeLeader=1;
packet.Classic70291_BeforeMemberCount=0;
// Exact reference CreateGlobal(Party,0,counter), using the existing
// bounded codec's raw-value API instead of a game-server allocator.
packet.PartyGUID.SetRawValue(uint64_t(HighGuid::Party)<<58,counter);
packet.SequenceNum=int32_t(sequence);packet.PartyIndex=GROUP_CATEGORY_HOME;
packet.PartyFlags=clear?GROUP_FLAG_DESTROYED:(raid?GROUP_FLAG_RAID:GROUP_FLAG_NONE);
packet.PartyType=clear?GROUP_TYPE_NONE:GROUP_TYPE_NORMAL;packet.MyIndex=clear?-1:0;
packet.LeaderFactionGroup=uint8_t(leader_faction);if(leader)packet.LeaderGUID=player_guid(leader);
std::set<uint64_t> unique;
for(unsigned i=0;i<count;++i){
auto guid=r.le(8);auto name=r.cstring(48);auto cls=r.le(1),subgroup=r.le(1),flags=r.le(1),connected=r.le(1),faction=r.le(1);
if(!unique.insert(guid).second || name.empty() || !cls || cls>11 || subgroup>7 || flags>1 || connected>1 || (faction!=3&&faction!=5))throw Error("party presentation member bound");
auto& info=packet.PlayerList.emplace_back();info.GUID=player_guid(guid);info.Name=name;info.Class=uint8_t(cls);
info.Subgroup=uint8_t(subgroup);info.Flags=flags?MEMBER_FLAG_ASSISTANT:0;info.Connected=connected;info.FactionGroup=uint8_t(faction);
// Classic has no social-queue, roles, voice or LeaverInfo fields.
// Preserve the original native structure's explicit neutral defaults.
}
if(!clear && !unique.contains(leader))throw Error("party leader absent from authoritative roster");
auto loot=r.le(1);if(loot>1 || (clear&&loot))throw Error("party loot optional bound");
if(loot){
auto method=r.le(1),master=r.le(8),threshold=r.le(1);
if(method>4 || threshold>6 || (method!=2&&master))throw Error("party source loot policy bound");
static constexpr uint8_t methods[]={FREE_FOR_ALL,ROUND_ROBIN,MASTER_LOOT,GROUP_LOOT,NEED_BEFORE_GREED};
auto& settings=packet.LootSettings.emplace();settings.Method=methods[method];settings.Threshold=uint8_t(threshold);
if(master)settings.LootMaster=player_guid(master);
}
r.end();auto out=packet.Write();return Bytes(out->data(),out->data()+out->size());
}
if(mode=="--trade-event"){
// Source SMSG_TRADE_STATUS(_EXTENDED) on the original 70334 TradeStatus/TradeUpdated writers.
Reader r(input);auto kind=r.le(1);
auto guid=[&]{auto low=r.le(8),high=r.le(8);ObjectGuid g;g.SetRawValue(high,low);return g;};
auto bytes=[](WorldPacket const* p){return Bytes(p->data(),p->data()+p->size());};
if(kind==0){
WorldPackets::Trade::TradeStatus p;auto status=r.le(1);if(status>21)throw Error("trade status bound");
p.Status=::TradeStatus(status);p.Partner=guid();p.PartnerAccount.Clear();p.PartnerIsSameBnetAccount=false;
p.ID=uint32_t(r.le(4));p.FailureForYou=r.le(1)!=0;p.BagResult=int32_t(r.le(4));p.ItemID=uint32_t(r.le(4));r.end();
if(p.Status==TRADE_STATUS_PROPOSED && p.Partner.IsEmpty())throw Error("trade proposal partner absent");
return bytes(p.Write());
}
if(kind==1){
WorldPackets::Trade::TradeUpdated p;p.WhichPlayer=uint8_t(r.le(1));p.ID=uint32_t(r.le(4));
p.ClientStateIndex=uint32_t(r.le(4));p.CurrentStateIndex=uint32_t(r.le(4));p.Gold=r.le(8);
p.ProposedEnchantment=int32_t(r.le(4));auto n=r.le(1);if(p.WhichPlayer>1 || n>7)throw Error("trade update bound");
std::set<unsigned> slots;
for(unsigned i=0;i<n;++i){
auto& item=p.Items.emplace_back();item.Slot=uint8_t(r.le(1));
if(item.Slot>6 || !slots.insert(item.Slot).second)throw Error("trade item slot bound");
item.Item.ItemID=uint32_t(r.le(4));item.StackCount=int32_t(r.le(4));item.GiftCreator=guid();
if(!item.Item.ItemID || item.StackCount<=0)throw Error("trade item identity bound");
if(r.le(1)){auto& u=item.Unwrapped.emplace();u.EnchantID=int32_t(r.le(4));u.OnUseEnchantmentID=0;u.Creator=guid();
u.Charges=int32_t(r.le(4));u.Lock=r.le(1)!=0;u.MaxDurability=uint32_t(r.le(4));u.Durability=uint32_t(r.le(4));}
}
r.end();return bytes(p.Write());
}
throw Error("unsupported trade event kind");
}
if(mode=="--group-event"){
// Source group/raid notifications projected onto the original 70334
// writers. All GUIDs arrive as bound native 16-byte values (low,high).
Reader r(input);auto kind=r.le(1);
auto guid=[&](bool allow_empty){auto low=r.le(8),high=r.le(8);if(!allow_empty && !low && !high)throw Error("group event GUID absent");ObjectGuid g;g.SetRawValue(high,low);return g;};
auto party=[&]{auto counter=r.le(8);if(!counter)throw Error("group event party counter absent");ObjectGuid g;g.SetRawValue(uint64_t(HighGuid::Party)<<58,counter);return g;};
auto name=[&]{auto s=r.cstring(48);if(s.empty())throw Error("group event name absent");return s;};
auto bytes=[](WorldPacket const* p){return Bytes(p->data(),p->data()+p->size());};
auto finite=[](float v){if(!std::isfinite(v))throw Error("group event coordinate bound");return v;};
auto auras=[&](std::vector<WorldPackets::Party::PartyMemberAuraStates>& out){
auto n=r.le(1);if(n>48)throw Error("group member aura bound");
for(unsigned i=0;i<n;++i){auto spell=r.le(4),flags=r.le(2);if(!spell || spell>INT32_MAX)throw Error("group member aura spell bound");
auto& a=out.emplace_back();a.SpellID=int32_t(spell);a.Flags=uint16_t(flags);a.ActiveFlags=1;}
};
switch(kind){
case 0:{WorldPackets::Party::GroupNewLeader p;p.PartyIndex=0;p.Name=name();r.end();return bytes(p.Write());}
case 1:{auto n=name();r.end();WorldPackets::Party::GroupDecline p(n);return bytes(p.Write());}
case 2:{WorldPackets::Party::PartyCommandResult p;p.Command=uint8_t(r.le(1));p.Result=uint8_t(r.le(1));p.Name=r.cstring(48);r.end();
if(p.Command>4 || p.Result>30)throw Error("party command result bound");return bytes(p.Write());}
case 3:{WorldPackets::Party::MinimapPing p;p.Sender=guid(false);p.PositionX=finite(r.f32());p.PositionY=finite(r.f32());r.end();return bytes(p.Write());}
case 4:{WorldPackets::Party::SendRaidTargetUpdateSingle p;p.PartyIndex=0;auto symbol=int8_t(r.le(1));p.Target=guid(true);p.ChangedBy=guid(true);r.end();
if(symbol<-1 || symbol>7)throw Error("raid target symbol bound");p.Symbol=symbol;return bytes(p.Write());}
case 5:{WorldPackets::Party::SendRaidTargetUpdateAll p;p.PartyIndex=0;auto n=r.le(1);if(n>8)throw Error("raid target list bound");
std::set<unsigned> seen;
for(unsigned i=0;i<n;++i){auto symbol=r.le(1);auto g=guid(false);if(symbol>7 || !seen.insert(symbol).second)throw Error("raid target list symbol bound");p.TargetIcons.emplace_back(uint8_t(symbol),g);}
r.end();return bytes(p.Write());}
case 6:{WorldPackets::Party::ReadyCheckStarted p;p.PartyIndex=0;p.PartyGUID=party();p.InitiatorGUID=guid(false);auto ms=r.le(4);r.end();
if(!ms || ms>120000)throw Error("ready check duration bound");p.Duration=Milliseconds(ms);return bytes(p.Write());}
case 7:{WorldPackets::Party::ReadyCheckResponse p;p.PartyGUID=party();p.Player=guid(false);auto ready=r.le(1);r.end();if(ready>1)throw Error("ready check state bound");p.IsReady=ready;return bytes(p.Write());}
case 8:{WorldPackets::Party::ReadyCheckCompleted p;p.PartyIndex=0;p.PartyGUID=party();r.end();return bytes(p.Write());}
case 9:{WorldPackets::Party::PartyMemberFullState p;p.ForEnemy=false;p.MemberGuid=guid(false);auto& s=p.MemberStats;
s.Level=uint16_t(r.le(2));s.Status=uint32_t(r.le(1));s.CurrentHealth=int32_t(r.le(4));s.MaxHealth=int32_t(r.le(4));
s.PowerType=uint8_t(r.le(1));s.CurrentPower=uint16_t(r.le(2));s.MaxPower=uint16_t(r.le(2));s.ZoneID=uint16_t(r.le(2));
s.PositionX=int16_t(r.le(2));s.PositionY=int16_t(r.le(2));s.PositionZ=0;
if(s.Level>255 || s.PowerType>6 || s.CurrentHealth<0 || s.MaxHealth<0)throw Error("group member stats bound");
// Source has no phasing: the reference default PhaseShift is Unphased.
s.Phases.PhaseShiftFlags=0x08;
auras(s.Auras);
if(r.le(1)){auto& pet=s.PetStats.emplace();pet.GUID=guid(false);pet.Name=r.cstring(48);pet.ModelId=int16_t(r.le(2));
pet.CurrentHealth=int32_t(r.le(4));pet.MaxHealth=int32_t(r.le(4));auras(pet.Auras);}
r.end();return bytes(p.Write());}
case 10:{WorldPackets::Instance::RaidGroupOnly p;p.Delay=int32_t(r.le(4));p.Reason=uint32_t(r.le(4));r.end();if(p.Delay<0)throw Error("raid group only delay bound");return bytes(p.Write());}
default:throw Error("unsupported group event kind");
}
}
if(mode=="--players"||mode=="--player-values")return peer_players(mode,input);
if(mode=="--peer-movement"){Reader r(input);auto realm=uint16_t(r.le(2));auto guid=r.le(8);auto opcode=uint16_t(r.le(2));
switch(opcode){case 0xB5:case 0xB6:case 0xB7:case 0xB8:case 0xB9:case 0xBA:case 0xBB:case 0xBC:case 0xBD:case 0xBE:case 0xBF:case 0xC0:case 0xC1:case 0xC2:case 0xC3:case 0xC9:case 0xCA:case 0xCB:case 0xDA:case 0xDB:case 0xEE:break;default:throw Error("unsupported peer movement opcode");}
if(realm>8191)throw Error("peer realm bound");return peer_status(peer_source_movement(r,guid),realm);}
if(mode=="--corpse-event"){
Reader r(input);auto kind=r.le(1),realm=r.le(2),self=r.le(8);
if(!self || realm>8191)throw Error("invalid corpse event owner");
auto bytes=[](WorldPacket const* p){return Bytes(p->data(),p->data()+p->size());};
if(kind==0){
auto source=turtle_corpse_location(r.take(r.left()));
WorldPackets::Query::CorpseLocation packet;packet.Valid=source.valid;
auto raw=forever_player_guid(self,realm);Reader g(raw);auto low=g.le(8),high=g.le(8);
packet.Player.SetRawValue(high,low);packet.MapID=int32_t(source.map);packet.ActualMapID=int32_t(source.actual_map);
packet.Position.Pos.Relocate(source.position[0],source.position[1],source.position[2]);
return bytes(packet.Write());
}
if(kind==1){WorldPackets::Misc::CorpseReclaimDelay packet;packet.Remaining=uint32_t(r.le(4));r.end();return bytes(packet.Write());}
if(kind==2){
r.end();WorldPackets::Misc::PreRessurect packet;
auto raw=forever_player_guid(self,realm);Reader g(raw);auto low=g.le(8),high=g.le(8);
packet.PlayerGUID.SetRawValue(high,low);return bytes(packet.Write());
}
if(kind==3){
auto map=std::bit_cast<int32_t>(uint32_t(r.le(4)));
std::array<float,3> point;for(auto& v:point){v=r.f32();if(!std::isfinite(v))throw Error("nonfinite graveyard location");}
r.end();if(map< -1 || map>8191 || (map== -1 && point!=std::array<float,3>{}))throw Error("invalid death-release location");
WorldPackets::Misc::DeathReleaseLoc packet;packet.MapID=map;
packet.Loc.Pos.Relocate(point[0],point[1],point[2]);return bytes(packet.Write());
}
throw Error("unknown corpse event kind");
}
if(mode=="--persistent-ground"){
Reader r(input);auto kind=r.le(1);auto map=uint16_t(r.le(2));
auto guid=[&](Guid128* copy=nullptr){auto raw=r.take(16);if(copy)std::copy(raw.begin(),raw.end(),copy->begin());Reader v(raw);auto low=v.le(8),high=v.le(8);ObjectGuid id;id.SetRawValue(high,low);return id;};
Guid128 raw_id{};auto id=guid(&raw_id),caster=guid();auto spell=uint32_t(r.le(4)),visual=uint32_t(r.le(4));
auto type=uint8_t(r.le(1));auto radius=r.f32();auto tick=uint32_t(r.le(4));auto scale=r.f32();
std::array<float,4> position;for(auto& v:position){v=r.f32();if(!std::isfinite(v)||std::abs(v)>100000)throw Error("invalid ground position");}r.end();
if(kind>1||map>8191||!id.IsDynamicObject()||!id.GetCounter()||id.GetMapId()!=map||
(!caster.IsPlayer()&&!caster.IsCreatureOrPet())||caster.IsEmpty()||type!=1||!spell||spell>0x7fffff||
!visual||visual>0x7fffffff||!std::isfinite(radius)||radius<=0||radius>1000||
!std::isfinite(scale)||scale<=0||scale>100)throw Error("unqualified persistent ground context");
UF::ObjectData object;UF::DynamicObjectData ground;
set(object.EntryID,int32_t(spell));set(object.Scale,scale);
set(ground.Caster,caster);set(ground.Type,type);set(ground.SpellID,int32_t(spell));
set(ground.Radius,radius);set(ground.CastTime,tick);
auto& cast_visual=const_cast<UF::SpellCastVisual&>(*ground.SpellVisual);
cast_visual.SpellXSpellVisualID=int32_t(visual);cast_visual.ScriptVisualID=0;
ByteBuffer values;Bytes block{uint8_t(kind?0:2)};append(block,pack_guid(raw_id));
if(!kind){
values<<uint8(UF::UpdateFieldFlag::None)<<uint8(3)<<uint8(207)<<uint8(255)<<uint8(1);
object.WriteCreate(UF::UpdateFieldFlag::None,values,nullptr,nullptr);
ground.WriteCreate(UF::UpdateFieldFlag::None,values,nullptr,nullptr);
le(block,9,1);append(block,Bytes{0x81,0,0});le(block,0,4);
for(unsigned i=0;i<4;++i){auto v=i==3?forever_facing(position[i]):position[i];le(block,std::bit_cast<uint32_t>(v),4);}
}else{
// Original values framing: CGObject fragment2 / DynamicObject9.
// Full nested masks retain this object's initial CastTime.
values<<uint8(0)<<uint8(0)<<uint8(3)<<uint32((1u<<TYPEID_OBJECT)|(1u<<TYPEID_DYNAMICOBJECT));
UF::ObjectData::Mask om;om.Set(0);om.Set(1);om.Set(3);
UF::DynamicObjectData::Mask dm;for(unsigned i=0;i<7;++i)dm.Set(i);
object.WriteUpdate(om,values,nullptr,nullptr,true);
ground.WriteUpdate(dm,values,nullptr,nullptr,true);
}
values.FlushBits();le(block,values.size(),4);append(block,std::span(values.data(),values.size()));
Bytes packet;le(packet,map,2);le(packet,1,4);le(packet,0x80,1);le(packet,block.size(),4);append(packet,block);return packet;
}
if(mode=="--corpses"){
Reader r(input);auto self=r.le(8);auto realm=uint16_t(r.le(2));auto map=uint32_t(r.le(4));
auto faction=uint32_t(r.le(4));auto cls=uint8_t(r.le(1));auto opcode=uint32_t(r.le(4));
if(faction>0x7fffffff)throw Error("invalid corpse owner faction");
if(!self || !cls || cls>=12 || map>8191 || realm>8191)throw Error("invalid authenticated corpse context");
auto updates=turtle_object_updates(opcode,r.take(r.left()));Bytes blocks;uint32_t count=0;
auto native=[](Guid128 raw){Reader r(raw);auto low=r.le(8),high=r.le(8);ObjectGuid id;id.SetRawValue(high,low);return id;};
for(const auto& u:updates)if(u.type==7 && (u.kind==2 || u.kind==3) && u.movement){
auto value=[&](unsigned index){auto i=u.fields.find(index);return i==u.fields.end()?0u:i->second;};
auto owner=uint64_t(value(Turtle::CORPSE_FIELD_OWNER))|(uint64_t(value(Turtle::CORPSE_FIELD_OWNER+1))<<32);
// Source corpses carry no class. Use only this authenticated
// character's genuine class, never guess other owners' classes.
if(owner!=self)continue;
auto id=forever_corpse_guid(u.guid,realm,map);
UF::ObjectData object;UF::CorpseData corpse;
auto scale=std::bit_cast<float>(value(Turtle::OBJECT_FIELD_SCALE_X));
if(!std::isfinite(scale) || scale<=0)throw Error("invalid corpse scale");
set(object.Scale,scale);set(corpse.Owner,native(forever_player_guid(owner,realm)));
set(corpse.DisplayID,value(Turtle::CORPSE_FIELD_DISPLAY_ID));set(corpse.FactionTemplate,int32_t(faction));
auto traits=value(Turtle::CORPSE_FIELD_BYTES_1);
set(corpse.RaceID,uint8_t(traits>>8));set(corpse.Sex,uint8_t(traits>>16));set(corpse.Class,cls);
auto source_flags=value(Turtle::CORPSE_FIELD_FLAGS);
// Original70334 recovery rejects native corpse flag8. Source
// HIDE_HELM=8 is cosmetic and must not enter that behavior
// word. Preserve bones1; express head/back hiding in Items.
// Source UNK2 and lootability are not native behavior flags.
set(corpse.Flags,source_flags&0x01u);
auto guild=value(Turtle::CORPSE_FIELD_GUILD);
if(guild)set(corpse.GuildGUID,native(forever_guild_guid(guild,realm)));
for(unsigned i=0;i<19;++i){
if((i==0 && (source_flags&0x08u)) || (i==14 && (source_flags&0x10u)))continue;
auto source=value(Turtle::CORPSE_FIELD_ITEM+i);
if(auto mapped=item_render_profile::find(source&0xffffff,source>>24))
const_cast<uint32&>(corpse.Items[i])=mapped->native_display|((source>>24)<<24);
}
ByteBuffer values;auto visibility=UF::UpdateFieldFlag::None;
values<<uint8(visibility)<<uint8(3)<<uint8(208)<<uint8(255)<<uint8(1);
object.WriteCreate(visibility,values,nullptr,nullptr);corpse.WriteCreate(visibility,values,nullptr,nullptr);values.FlushBits();
Bytes block{2};append(block,pack_guid(id));le(block,10,1);
append(block,Bytes{0x81,0,0});le(block,0,4);
for(float v:u.movement->position){if(!std::isfinite(v))throw Error("nonfinite corpse position");le(block,std::bit_cast<uint32_t>(v),4);}
le(block,values.size(),4);append(block,std::span(values.data(),values.size()));append(blocks,block);++count;
}
Bytes packet;le(packet,map,2);le(packet,count,4);le(packet,0x80,1);le(packet,blocks.size(),4);append(packet,blocks);return packet;
}
if(mode=="--loot-event"){
// Neutral adapter context followed by one genuine source payload.
// No socket/database/engine access or session authorization here.
Reader r(input);auto kind=r.le(1);
auto guid=[&](){auto bytes=r.take(16);Reader raw(bytes);auto low=raw.le(8),high=raw.le(8);ObjectGuid id;id.SetRawValue(high,low);return id;};
auto world_owner=[&](){auto id=guid();if(id.IsEmpty() || !(id.IsPlayer() || id.IsCreature() || id.IsPet() || id.IsGameObject() || id.IsItem() || id.IsCorpse()))throw Error("unsupported loot world owner");return id;};
auto loot_object=[&](bool empty=false){auto id=guid();if((!empty || !id.IsEmpty()) && (id.GetHigh()!=HighGuid::LootObject || !id.GetCounter()))throw Error("invalid loot presentation identity");return id;};
auto bytes=[](WorldPacket const* packet){return Bytes(packet->data(),packet->data()+packet->size());};
auto error=[](TurtleLootError value)->uint8_t{
// Source LootMgr.h -> pinned native Loot.h, by named meaning.
// In particular source DIDNT_KILL0 is never native success.
switch(value){
case TurtleLootError::didnt_kill:return LOOT_ERROR_DIDNT_KILL;
case TurtleLootError::too_far:return LOOT_ERROR_TOO_FAR;
case TurtleLootError::bad_facing:return LOOT_ERROR_BAD_FACING;
case TurtleLootError::locked:return LOOT_ERROR_LOCKED;
case TurtleLootError::not_standing:return LOOT_ERROR_NOTSTANDING;
case TurtleLootError::stunned:return LOOT_ERROR_STUNNED;
case TurtleLootError::player_not_found:return LOOT_ERROR_PLAYER_NOT_FOUND;
case TurtleLootError::play_time_exceeded:return LOOT_ERROR_PLAY_TIME_EXCEEDED;
case TurtleLootError::master_inventory_full:return LOOT_ERROR_MASTER_INV_FULL;
case TurtleLootError::master_unique_item:return LOOT_ERROR_MASTER_UNIQUE_ITEM;
case TurtleLootError::master_other:return LOOT_ERROR_MASTER_OTHER;
case TurtleLootError::already_pickpocketed:return LOOT_ERROR_ALREADY_PICKPOCKETED;
case TurtleLootError::not_while_shapeshifted:return LOOT_ERROR_NOT_WHILE_SHAPESHIFTED;
}
throw Error("unreviewed loot error mapping");
};
if(kind==0 || kind==10){
// source owner64, bound worldOwner128, LootObj128,
// REQUIRED native method8/threshold8, then actual source160.
// Method/threshold are absent from160: a caller must establish
// them independently. This writer never invents solo/group state.
auto expected=r.le(8);auto owner=world_owner(),object=loot_object(true);
auto method=r.le(1),threshold=r.le(1);
if(method>NEED_BEFORE_GREED || threshold>ITEM_QUALITY_ARTIFACT)throw Error("unsupported Turtle loot method/threshold context");
auto event=turtle_loot_response(r.take(r.left()));
if(event.owner!=expected)throw Error("loot response owner/context mismatch");
if(kind==10 && (event.error || event.type!=2 || !owner.IsGameObject()))throw Error("gameobject chest loot context mismatch");
WorldPackets::Loot::LootResponse packet;packet.Owner=owner;packet.LootObj=object;
if(event.error){
// Original Player::SendLootError retains constructor defaults
// for acquire/method/threshold and explicitly Acquired=false.
packet.FailureReason=error(*event.error);packet.Acquired=false;
}else{
if(object.IsEmpty())throw Error("successful loot lacks presentation identity");
// Original Player::SendLoot sets Acquired=true and leaves
// FailureReason17 unchanged; success is NOT numeric error0.
packet.Acquired=true;packet.AcquireReason=kind==10?LOOT_CHEST:event.type;
packet._LootMethod=uint8_t(method);packet.Threshold=uint8_t(threshold);packet.Coins=event.money;
for(const auto& row:event.items){
const auto random_list=row.random_property>0?item_random_property_profile::resolve(row.item,uint32_t(row.random_property)):0;
if(row.random_property<0)throw Error("loot random suffix requires a verified native item-data adapter");
// An unmapped positive property presents the base item
// (never an unrelated bonus); the server still grants
// the authoritative item on pickup.
auto& item=packet.Items.emplace_back();item.Type=LootItemType::Item;item.LootListID=row.slot;
item.Quantity=row.count;item.Loot.ItemID=row.item;
if(random_list){item.Loot.ItemBonus.emplace();item.Loot.ItemBonus->BonusListIDs.push_back(int32_t(random_list));}
switch(row.ui){
case TurtleLootSlotUi::allow:item.UIType=LOOT_SLOT_TYPE_ALLOW_LOOT;break;
case TurtleLootSlotUi::roll_ongoing:item.UIType=LOOT_SLOT_TYPE_ROLL_ONGOING;break;
case TurtleLootSlotUi::master:item.UIType=LOOT_SLOT_TYPE_MASTER;break;
case TurtleLootSlotUi::locked:item.UIType=LOOT_SLOT_TYPE_LOCKED;break;
case TurtleLootSlotUi::owner:item.UIType=LOOT_SLOT_TYPE_OWNER;break;
}
// Source displayID is not a modern ItemInstance field;
// matching client definitions remain a separate dependency.
}
}
return bytes(packet.Write());
}
if(kind==1){
// Bound worldOwner128, LootObj128, actual source162 slot8.
WorldPackets::Loot::LootRemoved packet;packet.Owner=world_owner();packet.LootObj=loot_object();
packet.LootListID=turtle_loot_removed(r.take(r.left()));return bytes(packet.Write());
}
if(kind==2){
// LootObj128 + actual source165 (empty), no fabricated amount.
WorldPackets::Loot::CoinRemoved packet;packet.LootObj=loot_object();
turtle_loot_clear_money(r.take(r.left()));return bytes(packet.Write());
}
if(kind==3){
// Source owner64, bound worldOwner128, self128, actual161.
// Original DoLootRelease -> Player::SendLootRelease(worldOwner):
// packet.LootObj is the WORLD owner here, Owner is the player.
auto expected=r.le(8);auto owner=world_owner(),player=guid();
if(!player.IsPlayer())throw Error("loot release lacks authenticated player context");
auto event=turtle_loot_release_response(r.take(r.left()));
if(event.owner!=expected)throw Error("loot release owner/context mismatch");
WorldPackets::Loot::LootReleaseResponse packet;packet.LootObj=owner;packet.Owner=player;return bytes(packet.Write());
}
if(kind==4){
// REQUIRED external context MoneyMod64/SoleLooter8, source163.
// Neither field exists in the source group money notification;
// callers cannot infer them from its amount or invent a solo event.
WorldPackets::Loot::LootMoneyNotify packet;packet.MoneyMod=r.le(8);auto sole=r.le(1);
if(sole>1)throw Error("invalid loot sole-looter context");
packet.SoleLooter=sole;packet.Money=turtle_loot_money_notify(r.take(r.left()));return bytes(packet.Write());
}
if(kind==5){
auto realm=uint16_t(r.le(2));if(!realm || realm>8191)throw Error("master candidates realm bound");
WorldPackets::Loot::MasterLootCandidateList packet;packet.LootObj=loot_object();auto count=r.le(1);
if(count>40)throw Error("source master candidates bound");
std::set<uint64_t> seen;
for(unsigned i=0;i<count;++i){auto id=r.le(8);if(!id || id>UINT32_MAX || !seen.insert(id).second)throw Error("source master player identity");
auto raw=forever_player_guid(id,realm);Reader bytes(raw);auto low=bytes.le(8),high=bytes.le(8);ObjectGuid player;player.SetRawValue(high,low);packet.Players.insert(player);}
r.end();return bytes(packet.Write());
}
if(kind>=6 && kind<=9){
auto object=loot_object();auto slot=uint8_t(r.le(1));auto entry=uint32_t(r.le(4));
auto count=uint32_t(r.le(4));auto property=std::bit_cast<int32_t>(uint32_t(r.le(4)));
if(slot>=16 || !entry || !count || property<0)throw Error("invalid source roll item context");
auto fill=[&](WorldPackets::Loot::LootItemData& item,uint8_t ui){
item.Type=LootItemType::Item;item.LootListID=slot;item.Quantity=count;item.UIType=ui;item.Loot.ItemID=entry;
auto bonus=property>0?item_random_property_profile::resolve(entry,uint32_t(property)):0;
if(bonus){item.Loot.ItemBonus.emplace();item.Loot.ItemBonus->BonusListIDs.push_back(int32_t(bonus));}
};
if(kind==6){
auto map=uint32_t(r.le(4)),ms=uint32_t(r.le(4));auto method=uint8_t(r.le(1));r.end();
if(map>8191 || !ms || ms>60000 || (method!=GROUP_LOOT && method!=NEED_BEFORE_GREED))throw Error("invalid source roll start context");
WorldPackets::Loot::StartLootRoll packet;packet.LootObj=object;packet.MapID=int32_t(map);
packet.RollTime=Milliseconds(ms);packet.ValidRolls=7;packet.Method=method;fill(packet.Item,LOOT_SLOT_TYPE_ROLL_ONGOING);
return bytes(packet.Write());
}
if(kind==9){r.end();WorldPackets::Loot::LootAllPassed packet;packet.LootObj=object;fill(packet.Item,LOOT_SLOT_TYPE_ALLOW_LOOT);return bytes(packet.Write());}
auto player=guid();auto number=std::bit_cast<int32_t>(uint32_t(r.le(4)));auto vote=uint8_t(r.le(1));
if(!player.IsPlayer() || vote>2)throw Error("invalid source roll player context");
if(kind==7){
auto ui=r.le(1);r.end();if(ui>1 || (ui==0 && (number<1 || number>100)))throw Error("invalid roll recipient UIType");
if((number==-1 && vote!=0 && vote!=2) || (number==0 && vote!=1) || (number!=-1 && number!=0 && (number<1 || number>100 || vote==0)))throw Error("invalid source roll announcement");
WorldPackets::Loot::LootRollBroadcast packet;packet.LootObj=object;packet.Player=player;packet.Roll=number;packet.RollType=vote;
fill(packet.Item,ui?LOOT_SLOT_TYPE_ROLL_ONGOING:LOOT_SLOT_TYPE_ALLOW_LOOT);return bytes(packet.Write());
}
auto own=r.le(1);r.end();if(own>1 || number<1 || number>100 || (vote!=1 && vote!=2))throw Error("invalid source roll winner");
WorldPackets::Loot::LootRollWon packet;packet.LootObj=object;packet.Winner=player;packet.Roll=number;packet.RollType=vote;packet.MainSpec=true;
fill(packet.Item,own?LOOT_SLOT_TYPE_ALLOW_LOOT:LOOT_SLOT_TYPE_LOCKED);return bytes(packet.Write());
}
throw Error("unsupported loot event kind");
}
if(mode=="--quest-packet")return serialize_source_quest_packet(input);
if(mode=="--quest-log-values")return serialize_quest_log_update(input);
if(mode=="--profession-values"){
Reader r(input);auto realm=uint16_t(r.le(2));auto map=uint32_t(r.le(4));auto self=r.le(8);
auto slot_mask=uint8_t(r.le(1));if(!realm || realm>8191 || map>8191 || !self || slot_mask>3)throw Error("profession values context");
UF::ActivePlayerData active;UF::ActivePlayerData::Mask am;
for(unsigned i=0;i<2;++i)if(slot_mask&(1u<<i)){
auto id=uint32_t(r.le(4));if(id>65535)throw Error("profession slot identity");
const_cast<int32&>(active.ProfessionSkillLine[i])=int32_t(id);am.Set(374);am.Set(375+i);
}
auto n=r.le(2);if(n>140 || (!n&&!slot_mask))throw Error("profession values row count");
std::set<unsigned> seen;auto& skills=const_cast<UF::SkillInfo&>(*active.Skill);
for(unsigned i=0;i<n;++i){
auto slot=unsigned(r.le(2));if(slot>=140 || !seen.insert(slot).second)throw Error("profession values row slot");
const_cast<uint16&>(skills.SkillLineID[slot])=r.le(2);const_cast<uint16&>(skills.SkillStep[slot])=r.le(2);
const_cast<uint16&>(skills.SkillRank[slot])=r.le(2);const_cast<uint16&>(skills.SkillStartingRank[slot])=r.le(2);
const_cast<uint16&>(skills.SkillMaxRank[slot])=r.le(2);const_cast<int16&>(skills.SkillTempBonus[slot])=std::bit_cast<int16_t>(uint16_t(r.le(2)));
const_cast<uint16&>(skills.SkillPermBonus[slot])=r.le(2);
skills.MarkChanged(&UF::SkillInfo::SkillLineID,slot);skills.MarkChanged(&UF::SkillInfo::SkillStep,slot);
skills.MarkChanged(&UF::SkillInfo::SkillRank,slot);skills.MarkChanged(&UF::SkillInfo::SkillStartingRank,slot);
skills.MarkChanged(&UF::SkillInfo::SkillMaxRank,slot);skills.MarkChanged(&UF::SkillInfo::SkillTempBonus,slot);
skills.MarkChanged(&UF::SkillInfo::SkillPermBonus,slot);
}
r.end();if(n){am.Set(32);am.Set(63);}
ByteBuffer values;values<<uint8(1)<<uint8(0)<<uint8(3)<<uint32(1u<<TYPEID_ACTIVE_PLAYER);
active.WriteUpdate(am,values,nullptr,nullptr,false);values.FlushBits();
Bytes block{0};append(block,pack_guid(forever_player_guid(self,realm)));le(block,values.size(),4);
append(block,std::span(values.data(),values.size()));Bytes out;le(out,map,2);le(out,1,4);le(out,0x80,1);
le(out,block.size(),4);append(out,block);return out;
}
if(mode=="--gameobject-values"){
Reader r(input);auto map=uint16_t(r.le(2));auto count=r.le(2);
if(!count || count>4096)throw Error("game-object sparse update count bound");
Bytes blocks;std::set<Guid128> seen;
for(unsigned i=0;i<count;++i){
Guid128 raw{};auto bytes=r.take(16);std::copy(bytes.begin(),bytes.end(),raw.begin());
Reader id(bytes);auto low=id.le(8),high=id.le(8);ObjectGuid owner;owner.SetRawValue(high,low);
if(!owner.IsGameObject() || !seen.insert(raw).second)throw Error("game-object sparse owner identity");
auto present=r.le(1);if(!present || (present&~7u))throw Error("game-object sparse field mask");
UF::GameObjectData go;UF::GameObjectData::Mask mask;
if(present&1){auto flags=uint32_t(r.le(4));if(flags&~0x37u)throw Error("game-object sparse flag roles");changed(mask,go.Flags,flags);}
if(present&2){auto state=uint8_t(r.le(1));if(!turtle_static_game_object_state(state))throw Error("game-object sparse state bound");changed(mask,go.State,int8_t(state));}
if(present&4)changed(mask,go.ArtKit,uint32_t(r.le(4)));
ByteBuffer values;values<<uint8(0)<<uint8(0)<<uint8(3)<<uint32(1u<<TYPEID_GAMEOBJECT);
go.WriteUpdate(mask,values,nullptr,nullptr,false);values.FlushBits();
Bytes block{0};append(block,pack_guid(raw));le(block,values.size(),4);
append(block,std::span(values.data(),values.size()));append(blocks,block);
}
r.end();Bytes out;le(out,map,2);le(out,count,4);le(out,0x80,1);le(out,blocks.size(),4);append(out,blocks);return out;
}
if (mode == "--spell-feedback") {
Reader r(input);
const auto opcode = r.le(2);
auto read_guid = [&] {
const auto low = r.le(8), high = r.le(8);
ObjectGuid guid; guid.SetRawValue(high, low); return guid;
};
auto serialize = [](auto& packet) { auto p = packet.Write(); return Bytes(p->data(), p->data() + p->size()); };
if (opcode == 0xb0) {
WorldPackets::Item::ItemCooldown packet;
packet.ItemGuid = read_guid(); packet.SpellID = uint32_t(r.le(4)); r.end();
if (!packet.ItemGuid.IsItem() || !packet.SpellID) throw Error("invalid equip cooldown");
// Tortoise Player::ApplyEquipCooldown is the only emitter, and sets exactly 30 seconds.
packet.Cooldown = 30000;
return serialize(packet);
}
if (opcode == 0x135) {
auto spell = uint32_t(r.le(4)); auto pet = r.le(1); r.end();
if (!spell || spell > INT32_MAX || pet > 1) throw Error("invalid cooldown event");
WorldPackets::Spells::CooldownEvent packet{bool(pet), int32_t(spell)};
return serialize(packet);
}
if (opcode == 0x13c) {
WorldPackets::Combat::AIReaction packet;
packet.UnitGUID = read_guid(); packet.Reaction = uint32_t(r.le(4)); r.end();
if (!packet.UnitGUID.IsCreatureOrPet() || packet.Reaction > 4) throw Error("invalid AI reaction");
return serialize(packet);
}
if (opcode == 0x1f3 || opcode == 0x1f7) {
WorldPackets::Spells::PlaySpellVisualKit packet;
packet.Unit = read_guid(); packet.KitRecID = int32_t(r.le(4)); r.end();
if (!packet.Unit.IsUnit() || packet.KitRecID <= 0) throw Error("invalid spell visual kit");
packet.KitType = opcode == 0x1f7 ? 1 : 0;
return serialize(packet);
}
throw Error("unsupported source spell feedback");
}
if (mode == "--spell-channel") {
Reader r(input);
const auto flags = r.le(1);
auto read_guid = [&]() {
const auto low = r.le(8), high = r.le(8);
ObjectGuid guid; guid.SetRawValue(high, low); return guid;
};
auto owner = read_guid();
if (flags == 4) {
WorldPackets::Spells::SpellChannelStart packet;
packet.CasterGUID = owner;
packet.SpellID = int32_t(r.le(4)); packet.Visual.SpellXSpellVisualID = int32_t(r.le(4));
packet.ChannelDuration = uint32_t(r.le(4)); r.end();
if (!owner.IsPlayer() || packet.SpellID <= 0 || packet.Visual.SpellXSpellVisualID < 0)
throw Error("invalid channel start");
// The source has neither interrupt-immunity nor predicted-heal optional data.
auto out = packet.Write(); return Bytes(out->data(), out->data() + out->size());
}
if (flags == 5) {
WorldPackets::Spells::SpellChannelUpdate packet;
packet.CasterGUID = owner;
packet.TimeRemaining = int32_t(r.le(4)); r.end();
if (!owner.IsPlayer()) throw Error("invalid channel update");
// The source supplies no interrupting unit, so FailedBy remains empty.
auto out = packet.Write(); return Bytes(out->data(), out->data() + out->size());
}
const auto map = r.le(2);
UF::UnitChannel channel;
channel.SpellID = int32_t(r.le(4)); channel.SpellVisual.SpellXSpellVisualID = int32_t(r.le(4));
channel.StartTimeMs = uint32_t(r.le(4)); channel.Duration = uint32_t(r.le(4));
auto target = read_guid(); r.end();
if (map > 8191 || !flags || flags > 3 || (!owner.IsPlayer() && !owner.IsCreatureOrPet()) ||
channel.SpellID < 0 || channel.SpellVisual.SpellXSpellVisualID < 0 ||
(!target.IsEmpty() && !target.IsUnit() && !target.IsGameObject() && !target.IsDynamicObject()))
throw Error("invalid channel values");
UF::UnitData unit; UF::UnitData::Mask mask;
if (flags & 1) changed(mask, unit.ChannelData, channel);
if (flags & 2) {
mask.Set(0); mask.Set(5);
if (!target.IsEmpty()) {
UF::MutableFieldReferenceWithChangesMask<UF::UnitData, true> ref(unit);
ref.ModifyValue(&UF::UnitData::ChannelObjects, 0).SetValue(target);
}
}
ByteBuffer values; values << uint8(0) << uint8(0) << uint8(3) << uint32(1u<<TYPEID_UNIT);
unit.WriteUpdate(mask, values, nullptr, nullptr, true); values.FlushBits();
Bytes block{0}; append(block, pack_guid(owner.GetRawValue())); le(block, values.size(), 4);
append(block, std::span(values.data(), values.size()));
Bytes out; le(out, map, 2); le(out, 1, 4); le(out, 0x80, 1); le(out, block.size(), 4); append(out, block); return out;
}
if(mode=="--combo-target"){
// Tortoise PLAYER_FIELD_COMBO_TARGET -> UF::UnitData::ClassicComboTarget (bit 230, Classic
// remapper 141). The stock 70334 combo bars read GetComboPoints(unit,"target") against it.
Reader r(input);auto map=uint16_t(r.le(2));Guid128 owner_raw{};
auto read_guid=[&](Guid128* raw=nullptr){
auto bytes=r.take(16);if(raw)std::copy(bytes.begin(),bytes.end(),raw->begin());
Reader id(bytes);auto low=id.le(8),high=id.le(8);ObjectGuid guid;guid.SetRawValue(high,low);return guid;
};
auto owner=read_guid(&owner_raw),target=read_guid();r.end();
if(!owner.IsPlayer() || (!target.IsEmpty() && !target.IsPlayer() && !target.IsCreatureOrPet()))throw Error("unsupported combo target identity");
UF::UnitData unit;UF::UnitData::Mask mask;changed(mask,unit.ClassicComboTarget,target);
// Self-only values: Unit.cpp sets the Owner fragment flag when receiver == this, and
// Object.cpp writes it as the first byte (01), like ordinary selected-self unit values.
ByteBuffer values;values<<uint8(1)<<uint8(0)<<uint8(3)<<uint32(1u<<TYPEID_UNIT);
unit.WriteUpdate(mask,values,nullptr,nullptr,false);values.FlushBits();
Bytes block{0};append(block,pack_guid(owner_raw));le(block,values.size(),4);append(block,std::span(values.data(),values.size()));
Bytes out;le(out,map,2);le(out,1,4);le(out,0x80,1);le(out,block.size(),4);append(out,block);return out;
}
if(mode=="--unit-target" || mode=="--controlled-unit"){
// A single public UF::UnitData::Target update. The original field
// is group0/bit22; the Classic changes-mask remapper preserves22.
// The caller resolves genuine source identities before this pure
// serializer. No LookAtControllerTarget or movement is implied.
Reader r(input);auto map=uint16_t(r.le(2));Guid128 owner_raw{};
auto read_guid=[&](Guid128* raw=nullptr){
auto bytes=r.take(16);if(raw)std::copy(bytes.begin(),bytes.end(),raw->begin());
Reader id(bytes);auto low=id.le(8),high=id.le(8);ObjectGuid guid;guid.SetRawValue(high,low);return guid;
};
auto owner=read_guid(&owner_raw),target=read_guid();
const bool control=mode=="--controlled-unit";
const unsigned role=control ? unsigned(r.le(1)) : 0;
r.end();
auto supported_unit=[](const ObjectGuid& guid){return guid.IsPlayer() || guid.IsCreatureOrPet();};
if(!supported_unit(owner) || (!target.IsEmpty() && !supported_unit(target)))throw Error("unsupported unit target identity");
UF::UnitData unit;UF::UnitData::Mask mask;
if(control){
if(!owner.IsPlayer() || role>1 ||
(!target.IsEmpty() && (role ? !target.IsPet() : !target.IsCreature())))
throw Error("unsupported controlled unit identity");
if(role)changed(mask,unit.Summon,target);
else changed(mask,unit.Charm,target);
}else changed(mask,unit.Target,target);
ByteBuffer values;values<<uint8(0)<<uint8(0)<<uint8(3)<<uint32(1u<<TYPEID_UNIT);
unit.WriteUpdate(mask,values,nullptr,nullptr,false);values.FlushBits();
Bytes block{0};append(block,pack_guid(owner_raw));le(block,values.size(),4);append(block,std::span(values.data(),values.size()));
Bytes out;le(out,map,2);le(out,1,4);le(out,0x80,1);le(out,block.size(),4);append(out,block);return out;
}
if(mode=="--aura-update"){
// Bounded neutral test format, not either version's wire packet.
// Bit7 adds context presence; bit6 adds remaining-time presence.
// Without either extension old neutral bytes stay unchanged.
Reader r(input);AuraSlotUpdate checked;auto raw=r.take(16);std::copy(raw.begin(),raw.end(),checked.unit.begin());
auto all=r.le(1);if(all&~0xe1u)throw Error("invalid aura update-all/context marker");bool contexts=all&0x80,timings=all&0x40,server_casts=all&0x20;checked.all=all&1;auto count=r.le(1);if(count>48)throw Error("aura count bound");
WorldPackets::Spells::AuraUpdate packet;Reader id(checked.unit);auto low=id.le(8),high=id.le(8);packet.UnitGUID.SetRawValue(high,low);packet.UpdateAll=checked.all;
for(unsigned i=0;i<count;++i){
AuraSlotChange change;change.slot=r.le(1);auto present=r.le(1);if(present>1)throw Error("invalid aura presence");
auto& aura=packet.Auras.emplace_back();aura.Slot=change.slot;
if(present){
AuraSlotData data;data.spell=r.le(4);data.flags=r.le(2);data.level=r.le(2);data.applications=r.le(1);data.active_flags=r.le(4);
if(contexts){
auto context=r.le(1);if(context>1)throw Error("invalid aura context presence");
if(context){
data.self_cast.emplace();auto cast=r.take(16),item=r.take(16);
std::copy(cast.begin(),cast.end(),data.self_cast->cast.begin());std::copy(item.begin(),item.end(),data.self_cast->item.begin());
}
}
if(server_casts){auto present=r.le(1);if(present>1)throw Error("invalid server aura cast presence");if(present){data.server_self_cast.emplace();auto raw=r.take(16);std::copy(raw.begin(),raw.end(),data.server_self_cast->begin());}}
if(timings){auto present=r.le(1);if(present>1)throw Error("invalid aura timing presence");if(present)data.remaining_ms=r.le(4);}
change.data=data;
aura.AuraData.emplace();auto& dest=*aura.AuraData;dest.SpellID=data.spell;dest.Flags=data.flags|((data.self_cast || data.server_self_cast)?1:0);dest.CastLevel=data.level;dest.Applications=data.applications;dest.ActiveFlags=data.active_flags;dest.Visual.SpellXSpellVisualID=aura_visual_profile::link(data.spell);
if(data.remaining_ms){dest.Flags|=4;dest.Duration=*data.remaining_ms;dest.Remaining=*data.remaining_ms;}
if(data.self_cast){
auto assign=[](ObjectGuid& output,const Guid128& raw){Reader input(raw);auto low=input.le(8),high=input.le(8);output.SetRawValue(high,low);};
assign(dest.CastID,data.self_cast->cast);assign(dest.CastItem.emplace(),data.self_cast->item);
}else if(data.server_self_cast){Reader r(*data.server_self_cast);auto low=r.le(8),high=r.le(8);dest.CastID.SetRawValue(high,low);}
else dest.CastUnit.emplace(ObjectGuid::Empty);
}
checked.slots.push_back(change);
}
r.end();(void)forever_aura_update(checked); // Same bounded supported domain; independent original writer below.
auto out=packet.Write();return Bytes(out->data(),out->data()+out->size());
}
if(mode=="--guild-invite"){
Reader r(input);auto address=uint32_t(r.le(4));auto invite=turtle_guild_invitation(r.take(r.left()));
WorldPackets::Guild::GuildInvite packet;packet.InviterVirtualRealmAddress=address;packet.GuildVirtualRealmAddress=address;
packet.InviterName=invite.inviter;packet.GuildName=invite.name;
auto out=packet.Write();return Bytes(out->data(),out->data()+out->size());
}
if(mode=="--guild-command-result"){
Reader r(input);auto command=r.le(4);auto name=r.cstring(255);auto status=r.le(4);r.end();
if(command>255 || status>255)throw Error("guild result native field bound");
WorldPackets::Guild::GuildCommandResult packet;packet.Command=uint8_t(command);packet.Result=uint8_t(status);packet.Name=name;
auto out=packet.Write();return Bytes(out->data(),out->data()+out->size());
}
if(mode=="--guild-info"){
Reader r(input);RosterRealm realm;realm.realm_id=r.le(2);realm.virtual_address=r.le(4);auto g=turtle_guild_info(r.take(r.left()));auto raw=forever_guild_guid(g.id,realm.realm_id);Reader id(raw);auto low=id.le(8),high=id.le(8);ObjectGuid guild;guild.SetRawValue(high,low);
WorldPackets::Guild::QueryGuildInfoResponse packet;packet.GuildGuid=guild;packet.Info.emplace();auto& info=*packet.Info;info.GuildGUID=guild;info.VirtualRealmAddress=realm.virtual_address;info.GuildName=g.name;
for(unsigned i=0;i<g.ranks.size();++i)if(!g.ranks[i].empty())info.Ranks.emplace_back(i,i,g.ranks[i]);
info.EmblemStyle=g.emblem[0];info.EmblemColor=g.emblem[1];info.BorderStyle=g.emblem[2];info.BorderColor=g.emblem[3];info.BackgroundColor=g.emblem[4];auto out=packet.Write();return Bytes(out->data(),out->data()+out->size());
}
if(mode=="--spell-damage-log"){
Reader r(input);auto assign=[&](ObjectGuid& guid){auto raw=r.take(16);Reader id(raw);auto low=id.le(8),high=id.le(8);guid.SetRawValue(high,low);};
WorldPackets::CombatLog::SpellNonMeleeDamageLog packet;assign(packet.Me);assign(packet.CasterGUID);
auto parsed=turtle_spell_damage_log(r.take(r.left()));if(!parsed)throw Error("unsupported non-melee damage semantics");const auto& d=*parsed;
packet.SpellID=int32_t(d.spell);packet.Damage=int32_t(d.damage);packet.OriginalDamage=d.original;packet.Overkill=-1;
packet.SchoolMask=uint8_t(d.school);packet.Absorbed=int32_t(d.absorbed);packet.Resisted=d.resisted;packet.ShieldBlock=int32_t(d.blocked);packet.Flags=int32_t(d.flags);packet.Periodic=d.periodic;
auto out=packet.Write();return Bytes(out->data(),out->data()+out->size());
}
if(mode=="--periodic-aura-log"){
Reader r(input);auto assign=[&](ObjectGuid& guid){auto raw=r.take(16);Reader id(raw);auto low=id.le(8),high=id.le(8);guid.SetRawValue(high,low);};
WorldPackets::CombatLog::SpellPeriodicAuraLog packet;assign(packet.TargetGUID);assign(packet.CasterGUID);
auto parsed=turtle_periodic_aura_log(r.take(r.left()));if(!parsed)throw Error("unsupported periodic aura semantics");const auto& d=*parsed;
packet.SpellID=int32_t(d.spell);auto& effect=packet.Effects.emplace_back();effect.Effect=int32_t(d.type);effect.Amount=int32_t(d.amount);effect.OriginalDamage=d.original;effect.OverHealOrKill=-1;effect.SchoolMaskOrPower=int32_t(d.school);effect.AbsorbedOrAmplitude=int32_t(d.absorbed);effect.Resisted=d.resisted;
auto out=packet.Write();return Bytes(out->data(),out->data()+out->size());
}
if(mode=="--trainer-list"){
Reader r(input);auto raw=r.take(16);Reader id(raw);auto low=id.le(8),high=id.le(8);ObjectGuid guid;guid.SetRawValue(high,low);
auto list=turtle_trainer_list(r.take(r.left()));if(!prepare_trainer_offers(list))throw Error("unsupported trainer semantics");
WorldPackets::NPC::TrainerList packet;packet.TrainerGUID=guid;packet.TrainerType=native_trainer_type(list);packet.TrainerID=list.native_id;packet.Greeting=list.greeting;
for(const auto& row:list.spells){auto& spell=packet.Spells.emplace_back();spell.SpellID=int32_t(row.display_spell());spell.MoneyCost=row.cost;spell.ReqSkillLine=row.skill;spell.ReqSkillRank=row.skill_rank;spell.ReqLevel=row.level;spell.Usable=row.native_state();for(unsigned i=0;i<3;++i)spell.ReqAbility[i]=int32_t(row.requirements[i]);}
auto out=packet.Write();return Bytes(out->data(),out->data()+out->size());
}
if(mode=="--spell-learning"){
Reader r(input);auto opcode=r.le(2);
if(opcode==0x12b){auto spell=r.le(4);r.end();if(!spell || spell>0x7fffffff)throw Error("learned spell bound");WorldPackets::Spells::LearnedSpells packet;packet.SpecializationID=0;packet.MinActionBarSlot=0;packet.ClientLearnedSpellData.emplace_back().SpellID=int32_t(spell);auto out=packet.Write();return Bytes(out->data(),out->data()+out->size());}
if(opcode==0x203){auto spell=r.le(2);r.end();if(!spell)throw Error("removed spell bound");WorldPackets::Spells::UnlearnedSpells packet;packet.SpellID.push_back(uint32_t(spell));auto out=packet.Write();return Bytes(out->data(),out->data()+out->size());}
if(opcode==0x12c){auto old=r.le(2),next=r.le(2);r.end();if(!old || !next || old==next)throw Error("superceded spell bound");WorldPackets::Spells::SupercededSpells packet;auto& spell=packet.ClientLearnedSpellData.emplace_back();spell.SpellID=int32_t(next);spell.Superceded=int32_t(old);auto out=packet.Write();return Bytes(out->data(),out->data()+out->size());}
throw Error("unsupported spell learning opcode");
}
if(mode=="--buy-result"){
Reader r(input);auto kind=r.le(1);auto raw=r.take(16);Reader id(raw);auto low=id.le(8),high=id.le(8);ObjectGuid guid;guid.SetRawValue(high,low);
auto muid=r.le(4);
if(kind==0){auto stock=r.le(4),units=r.le(4);r.end();if(!muid || !units)throw Error("empty native buy result");WorldPackets::Item::BuySucceeded packet;packet.VendorGUID=guid;packet.Muid=uint32_t(muid);packet.NewQuantity=int32_t(stock);packet.QuantityBought=uint32_t(units);auto out=packet.Write();return Bytes(out->data(),out->data()+out->size());}
if(kind!=1)throw Error("unreviewed buy-result kind");auto 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");
WorldPackets::Item::BuyFailed packet;packet.VendorGUID=guid;packet.Muid=uint32_t(muid);packet.Reason=BuyResult(reason);auto out=packet.Write();return Bytes(out->data(),out->data()+out->size());
}
if(mode=="--sell-error"){
Reader r(input);auto vendor=r.take(16),item=r.take(16);auto reason=r.le(1);r.end();
if(reason<1 || reason>6)throw Error("unreviewed Turtle sell error");
auto guid=[](const Bytes& raw){Reader id(raw);auto low=id.le(8),high=id.le(8);ObjectGuid result;result.SetRawValue(high,low);return result;};
WorldPackets::Item::SellResponse packet;packet.VendorGUID=guid(vendor);packet.Reason=SellResult(reason);
if(std::any_of(item.begin(),item.end(),[](uint8_t b){return b!=0;}))packet.ItemGUIDs.push_back(guid(item));
auto out=packet.Write();return Bytes(out->data(),out->data()+out->size());
}
if(mode=="--item-appearance"){
Reader r(input);auto map=uint16_t(r.le(2)),realm=uint16_t(r.le(2));auto self=r.le(8);auto n=r.le(2);
if(!self || self>0xffffffff || !realm || realm>8191 || n>38)throw Error("owned appearance batch bound");
Bytes blocks;std::set<uint64_t> used;
for(unsigned i=0;i<n;++i){
auto id=r.le(8);auto appearance=r.le(4);
if((id>>48)!=0x4000 || !(id&0xffffffff) || !used.insert(id).second || appearance>0x7fffffff)
throw Error("owned appearance identity bound");
UF::ItemData item;UF::ItemData::Mask mask;mask.Set(0);mask.Set(17);
if(appearance){
UF::MutableFieldReference<UF::ItemData,true> ref{item};
auto modifiers=ref.ModifyValue(&UF::ItemData::Modifiers).ModifyValue(&UF::ItemModList::Values);
auto& value=UF::AddDynamicUpdateFieldValue(modifiers);value.Type=0;value.Value=int32_t(appearance);
}
ByteBuffer values;values<<uint8(1)<<uint8(0)<<uint8(3)<<uint32(1u<<TYPEID_ITEM);
item.WriteUpdate(mask,values,nullptr,nullptr,true);values.FlushBits();
ObjectGuid guid;guid.SetRawValue(uint64_t(3)<<58,id&0xffffffff);
Bytes block{0};append(block,pack_guid(guid.GetRawValue()));le(block,values.size(),4);
append(block,std::span(values.data(),values.size()));append(blocks,block);
}
auto flags=r.le(1);if((!n && !flags) || flags>19)throw Error("visible transmog flag bound");
UF::PlayerData player;UF::PlayerData::Mask mask;UF::MutableFieldReference<UF::PlayerData,true> ref{player};
std::set<uint8_t> slots;
for(unsigned i=0;i<flags;++i){
auto slot=uint8_t(r.le(1));auto active=r.le(1);
if(slot>=19 || active>1 || !slots.insert(slot).second)throw Error("visible transmog slot bound");
ref.ModifyValue(&UF::PlayerData::VisibleItems,slot).ModifyValue(&UF::VisibleItem::HasTransmog).SetValue(bool(active));
mask.Set(229);mask.Set(230+slot);
}
r.end();
if(flags){
ByteBuffer values;values<<uint8(1)<<uint8(0)<<uint8(3)<<uint32(1u<<TYPEID_PLAYER);
player.WriteUpdate(mask,values,nullptr,nullptr,false);values.FlushBits();
ObjectGuid owner;owner.SetRawValue((uint64_t(2)<<58)|(uint64_t(realm)<<42),self);
Bytes block{0};append(block,pack_guid(owner.GetRawValue()));le(block,values.size(),4);append(block,std::span(values.data(),values.size()));append(blocks,block);
}
Bytes out;le(out,map,2);le(out,n+(flags?1:0),4);le(out,128,1);le(out,blocks.size(),4);append(out,blocks);return out;
}
if(mode=="--inventory-objects"){
Reader r(input);auto self=r.le(8);auto realm=uint16_t(r.le(2));auto map=uint32_t(r.le(4));auto records=r.le(4);
if(!self || records>4096)throw Error("inventory context bound");
auto item_guid=[](uint64_t id){ObjectGuid result;if(id)result.SetRawValue(uint64_t(3)<<58,id&0xffffffff);return result;};
auto player_guid=[&](uint64_t id){ObjectGuid result;if(id)result.SetRawValue((uint64_t(2)<<58)|(uint64_t(realm)<<42),id);return result;};
Bytes blocks;uint32_t count=0;
for(unsigned record=0;record<records;++record){
auto id=r.le(8);auto type=r.le(1),kind=r.le(1),fields=r.le(2);
if(fields>8192 || (kind!=0 && kind!=2 && kind!=3))throw Error("inventory record bound");
std::map<uint16_t,uint32_t> f;
for(unsigned i=0;i<fields;++i){auto index=uint16_t(r.le(2));auto value=uint32_t(r.le(4));if(!f.emplace(index,value).second)throw Error("duplicate inventory field");}
auto value=[&](unsigned index){auto it=f.find(index);return it==f.end()?0u:it->second;};
auto pair=[&](unsigned index){return uint64_t(value(index))|(uint64_t(value(index+1))<<32);};
ByteBuffer values;Bytes block;
if(type==4){
if(id!=self || kind!=0)throw Error("inventory player identity");
UF::ActivePlayerData active;UF::ActivePlayerData::Mask am;UF::PlayerData player;UF::PlayerData::Mask pm;UF::UnitData unit;UF::UnitData::Mask um;
gateway::keyring_wire::View<ObjectGuid> keyring;
bool have_active=false,have_player=false,have_unit=false;
if(f.contains(Turtle::PLAYER_AMMO_ID)){
// Classic70334 repurposes PvpMedals as AmmoID. Apply
// only actual source updates, including explicit zero.
const_cast<uint32&>(*active.PvpMedals)=value(Turtle::PLAYER_AMMO_ID);
am.Set(102);am.Set(107);have_active=true;
}
auto slot=[&](unsigned legacy,unsigned modern){
if(!f.contains(legacy) && !f.contains(legacy+1))return;
const_cast<ObjectGuid&>(active.InvSlots[modern])=item_guid(pair(legacy));am.Set(163);am.Set(164+modern);have_active=true;
};
for(unsigned i=0;i<23;++i)slot(Turtle::PLAYER_FIELD_INV_SLOT_HEAD+2*i,i<19?i:30+i-19);
for(unsigned i=0;i<16;++i)slot(Turtle::PLAYER_FIELD_PACK_SLOT_1+2*i,35+i);
for(unsigned i=0;i<6;++i)slot(Turtle::PLAYER_FIELD_BANKBAG_SLOT_1+2*i,64+i);
for(unsigned i=0;i<gateway::keyring_slots::Count;++i){
auto first=Turtle::PLAYER_FIELD_VENDORBUYBACK_SLOT_1+24+2*i;
if(!f.contains(first) && !f.contains(first+1))continue;
keyring.guids[i]=item_guid(pair(first));keyring.changed|=uint32_t(1)<<i;have_active=true;
}
if(f.contains(Turtle::PLAYER_BYTES_2)){
auto purchased=(value(Turtle::PLAYER_BYTES_2)>>16)&255;
if(purchased>6)throw Error("unsupported source purchased bank bag count");
const_cast<uint8&>(*active.NumBankSlots)=uint8(purchased);am.Set(102);am.Set(132);have_active=true;
}
UF::ContainerData bank_data;UF::ContainerData::Mask bank_mask;bool bank_changed=false;
for(unsigned i=0;i<24;++i){
auto index=Turtle::PLAYER_FIELD_BANK_SLOT_1+2*i;
if(!f.contains(index) && !f.contains(index+1))continue;
const_cast<ObjectGuid&>(bank_data.Slots[i])=item_guid(pair(index));bank_mask.Set(2);bank_mask.Set(3+i);bank_changed=true;
}
if(bank_changed){
// Same adapter-owned container as full SELF. Only its
// presentation slots change; no backend item is created.
ObjectGuid bank;bank.SetRawValue(uint64_t(3)<<58,(uint64_t(1)<<63)|(self<<8)|1);
ByteBuffer bank_values;bank_values<<uint8(1)<<uint8(0)<<uint8(3)<<uint32(1u<<TYPEID_CONTAINER);
bank_data.WriteUpdate(bank_mask,bank_values,nullptr,nullptr,true);bank_values.FlushBits();
Bytes bank_block{0};append(bank_block,pack_guid(bank.GetRawValue()));le(bank_block,bank_values.size(),4);
append(bank_block,std::span(bank_values.data(),bank_values.size()));append(blocks,bank_block);++count;
}
// Pinned Forever Player.h uses72..83, Turtle uses69..80.
// Both timestamps are login-relative seconds+30h; only the
// destination field width changes (uint32 -> int64).
for(unsigned i=0;i<12;++i){
slot(Turtle::PLAYER_FIELD_VENDORBUYBACK_SLOT_1+2*i,72+i);
auto price=Turtle::PLAYER_FIELD_BUYBACK_PRICE_1+i;
if(f.contains(price)){const_cast<uint32&>(active.BuybackPrice[i])=value(price);am.Set(311);am.Set(312+i);have_active=true;}
auto time=Turtle::PLAYER_FIELD_BUYBACK_TIMESTAMP_1+i;
if(f.contains(time)){const_cast<int64&>(active.BuybackTimestamp[i])=int64_t(value(time));am.Set(311);am.Set(324+i);have_active=true;}
}
for(unsigned i=0;i<19;++i){
auto index=Turtle::PLAYER_VISIBLE_ITEM_1_0+12*i;
if(!f.contains(index))continue;
UF::MutableFieldReference<UF::PlayerData,true> player_ref{player};
auto visible=player_ref.ModifyValue(&UF::PlayerData::VisibleItems,i);
const auto displayed=forever_visible_item_id(value(Turtle::PLAYER_FLAGS),i,value(index));
visible.ModifyValue(&UF::VisibleItem::ItemID).SetValue(int32_t(displayed));
visible.ModifyValue(&UF::VisibleItem::ItemModifiedAppearanceID).SetValue(item_render_profile::modified_appearance(displayed));
const auto visual=displayed?item_enchantment_visual_profile::resolve(value(index+1),value(index+2)):0;
visible.ModifyValue(&UF::VisibleItem::ItemVisual).SetValue(uint16(visual));
pm.Set(229);pm.Set(230+i);have_player=true;
if(i>=15 && i<=17){auto& item=const_cast<UF::VisibleItem&>(unit.VirtualItems[i-15]);set(item.ItemID,int32_t(value(index)));set(item.ItemVisual,uint16(visual));um.Set(180);um.Set(181+i-15);have_unit=true;}
}
if(!have_active && !have_player)continue;
values<<uint8(1)<<uint8(0)<<uint8(3)<<uint32((have_active?(1u<<TYPEID_ACTIVE_PLAYER):0)|(have_player?(1u<<TYPEID_PLAYER):0)|(have_unit?(1u<<TYPEID_UNIT):0));
if(have_unit)unit.WriteUpdate(um,values,nullptr,nullptr,true);
// Sparse visible-item updates must not zero HasTransmog or
// other independently supplied item presentation state.
if(have_player)player.WriteUpdate(pm,values,nullptr,nullptr,false);
if(have_active){gateway::keyring_wire::Scope<ObjectGuid> keyring_scope(keyring);active.WriteUpdate(am,values,nullptr,nullptr,true);}
block.push_back(0);append(block,pack_guid(player_guid(id).GetRawValue()));
}else{
if((type!=1 && type!=2) || (id>>48)!=0x4000 || pair(Turtle::ITEM_FIELD_OWNER)!=self)throw Error("inventory item owner/category");
if(!value(Turtle::OBJECT_FIELD_ENTRY))throw Error("inventory item entry missing");
UF::ObjectData object;UF::ItemData item;UF::ContainerData container;
UF::ObjectData::Mask om;UF::ItemData::Mask im;UF::ContainerData::Mask cm;
changed(om,object.EntryID,int32_t(value(Turtle::OBJECT_FIELD_ENTRY)));changed(om,object.Scale,1.0f);
changed(im,item.Owner,player_guid(self));
auto contained=pair(Turtle::ITEM_FIELD_CONTAINED);
if(contained && contained!=self && (contained>>48)!=0x4000)throw Error("inventory container category");
changed(im,item.ContainedIn,contained==self?player_guid(self):item_guid(contained));
changed(im,item.Creator,player_guid(pair(Turtle::ITEM_FIELD_CREATOR)));
changed(im,item.GiftCreator,player_guid(pair(Turtle::ITEM_FIELD_GIFTCREATOR)));
changed(im,item.StackCount,value(Turtle::ITEM_FIELD_STACK_COUNT));changed(im,item.Expiration,value(Turtle::ITEM_FIELD_DURATION));
if(f.contains(Turtle::ITEM_FIELD_FLAGS))changed(im,item.DynamicFlags,forever_item_dynamic_flags(value(Turtle::ITEM_FIELD_FLAGS)));
changed(im,item.Durability,value(Turtle::ITEM_FIELD_DURABILITY));changed(im,item.MaxDurability,value(Turtle::ITEM_FIELD_MAXDURABILITY));
const_cast<WorldPackets::Item::ItemBonusKey&>(*item.ItemBonusKey).ItemID=int32_t(value(Turtle::OBJECT_FIELD_ENTRY));im.Set(0);im.Set(19);
// Source random property (ITEM_FIELD_RANDOM_PROPERTIES_ID, enchant
// slots 3..5) is presented as its packaged native ItemBonus list;
// those prop slots are then not repeated as native enchantments.
const auto random_list=item_random_property_profile::resolve(value(Turtle::OBJECT_FIELD_ENTRY),value(Turtle::ITEM_FIELD_RANDOM_PROPERTIES_ID));
if(random_list)const_cast<WorldPackets::Item::ItemBonusKey&>(*item.ItemBonusKey).BonusListIDs.push_back(int32_t(random_list));
for(unsigned i=0;i<5;++i){const_cast<int32&>(item.SpellCharges[i])=int32_t(value(Turtle::ITEM_FIELD_SPELL_CHARGES+i));im.Set(21);im.Set(22+i);}
for(unsigned i=0;i<7;++i){if(random_list && i>=3 && i<=5){im.Set(27);im.Set(28+i);continue;}auto& enchant=const_cast<UF::ItemEnchantment&>(item.Enchantment[i]);set(enchant.ID,int32_t(value(Turtle::ITEM_FIELD_ENCHANTMENT+3*i)));set(enchant.Duration,value(Turtle::ITEM_FIELD_ENCHANTMENT+3*i+1));set(enchant.Charges,int16_t(value(Turtle::ITEM_FIELD_ENCHANTMENT+3*i+2)));im.Set(27);im.Set(28+i);}
if(type==2){
auto slots=value(Turtle::CONTAINER_FIELD_NUM_SLOTS);if(slots>36)throw Error("Turtle container slot bound");changed(cm,container.NumSlots,slots);
for(unsigned i=0;i<slots;++i){const_cast<ObjectGuid&>(container.Slots[i])=item_guid(pair(Turtle::CONTAINER_FIELD_SLOT_1+2*i));cm.Set(2);cm.Set(3+i);}
}
if(kind==2 || kind==3){
auto owner=UF::UpdateFieldFlag::Owner;values<<uint8(owner)<<uint8(3)<<uint8(200);if(type==2)values<<uint8(201);values<<uint8(255)<<uint8(1);
object.WriteCreate(owner,values,nullptr,nullptr);item.WriteCreate(owner,values,nullptr,nullptr);if(type==2)container.WriteCreate(owner,values,nullptr,nullptr);
block.push_back(2);append(block,pack_guid(item_guid(id).GetRawValue()));le(block,type,1);le(block,0,3);le(block,0,4);
}else{
values<<uint8(1)<<uint8(0)<<uint8(3)<<uint32((1u<<TYPEID_OBJECT)|(1u<<TYPEID_ITEM)|(type==2?(1u<<TYPEID_CONTAINER):0));
object.WriteUpdate(om,values,nullptr,nullptr,true);item.WriteUpdate(im,values,nullptr,nullptr,true);if(type==2)container.WriteUpdate(cm,values,nullptr,nullptr,true);
block.push_back(0);append(block,pack_guid(item_guid(id).GetRawValue()));
}
}
values.FlushBits();le(block,values.size(),4);append(block,std::span(values.data(),values.size()));append(blocks,block);++count;
}
r.end();Bytes output;le(output,map,2);le(output,count,4);le(output,0x80,1);le(output,blocks.size(),4);append(output,blocks);return output;
}
if(mode=="--talent-commit"){
Reader r(input);
auto config=uint32_t(r.le(4)),points=uint32_t(r.le(4));auto count=r.le(4);if(count>4096)throw Error("talent known-spell bound");
std::set<uint32_t> known;for(unsigned i=0;i<count;++i)known.insert(uint32_t(r.le(4)));
auto requests=turtle_talent_commit(r.take(r.left()),config,points,known);Bytes out;le(out,requests.size(),4);for(const auto& request:requests)append(out,request);
return out;
}
if(mode=="--native-spell-cast") {
Reader r(input);auto kind=r.le(1);if(kind>9)throw Error("native cast event kind");
WorldPackets::Spells::SpellCastData cast;
auto guid=[&](){auto raw=r.take(16);Reader g(raw);auto low=g.le(8),high=g.le(8);ObjectGuid id;id.SetRawValue(high,low);return id;};
if(kind==4){
WorldPackets::Spells::SpellCooldown packet;packet.Caster=guid();auto count=r.le(2);if(!count || count>20480)throw Error("item cooldown count bound");
for(unsigned i=0;i<count;++i){auto spell=uint32_t(r.le(4)),duration=uint32_t(r.le(4));if(!spell || spell>0x7fffffff)throw Error("item cooldown spell bound");packet.SpellCooldowns.emplace_back(spell,duration);}
r.end();auto result=packet.Write();return Bytes(result->data(),result->data()+result->size());
}
if(kind==5){
WorldPackets::Spells::ClearCooldowns packet;auto count=r.le(2);if(!count || count>32768)throw Error("clear cooldown count bound");
for(unsigned i=0;i<count;++i){auto spell=uint32_t(r.le(4));if(!spell || spell>0x7fffffff)throw Error("clear cooldown identity bound");packet.SpellID.push_back(int32_t(spell));}
r.end();auto result=packet.Write();return Bytes(result->data(),result->data()+result->size());
}
if(kind==6){
WorldPackets::Spells::ClearCooldown packet;packet.SpellID=uint32_t(r.le(4));packet.ClearOnHold=true;r.end();
if(!packet.SpellID || packet.SpellID>0x7fffffff)throw Error("clear cooldown identity bound");
auto result=packet.Write();return Bytes(result->data(),result->data()+result->size());
}
if(kind>=2 && kind<=3){
auto id=guid(),unit=guid();auto spell=int32_t(r.le(4));auto visual=int32_t(r.le(4)),script=int32_t(r.le(4));auto reason=int32_t(r.le(4)),arg1=int32_t(r.le(4)),arg2=int32_t(r.le(4));r.end();
if(spell<=0 || reason<0 || reason>0xffff)throw Error("native cast failure bound");
WorldPackets::Spells::CastFailed failed;WorldPackets::Spells::SpellFailure interrupted;
failed.CastID=id;failed.SpellID=spell;failed.Visual.SpellXSpellVisualID=visual;failed.Visual.ScriptVisualID=script;failed.Reason=reason;failed.FailedArg1=arg1;failed.FailedArg2=arg2;
interrupted.CastID=id;interrupted.CasterUnit=unit;interrupted.SpellID=spell;interrupted.Visual=failed.Visual;interrupted.Reason=uint16_t(reason);
auto packet=kind==2?failed.Write():interrupted.Write();return Bytes(packet->data(),packet->data()+packet->size());
}
cast.CasterGUID=guid();cast.CasterUnit=guid();cast.CastID=guid();
cast.SpellID=int32_t(r.le(4));if(cast.SpellID<=0)throw Error("native cast spell bound");
cast.Visual.SpellXSpellVisualID=int32_t(r.le(4));cast.Visual.ScriptVisualID=int32_t(r.le(4));
const bool start_event=kind==0 || kind==8;
cast.CastFlags=start_event?2u:0x100u;
if(kind<=1)cast.CastFlags|=0x40000u; // Matched request from this client.
if(kind==7)cast.CastFlags|=1u; // Established triggered equipment GO.
cast.CastTime=uint32_t(r.le(4));
cast.Target.Flags=uint32_t(r.le(4));if((cast.Target.Flags&~0x872u) || ((cast.Target.Flags&0x802u)==0x802u))throw Error("native cast targets bound");
cast.Target.Unit=guid();cast.Target.Item=guid();
auto count=r.le(1);for(unsigned i=0;i<count;++i){cast.HitTargets.push_back(guid());cast.HitStatus.emplace_back(SPELL_MISS_NONE);}
count=r.le(1);for(unsigned i=0;i<count;++i){cast.MissTargets.push_back(guid());auto reason=r.le(1),reflect=r.le(1);if(reason>11 || reflect>11)throw Error("native cast miss bound");cast.MissStatus.emplace_back(SpellMissInfo(reason),SpellMissInfo(reflect));}
auto location=[&](){
WorldPackets::Spells::TargetLocation value{};
auto x=r.f32(),y=r.f32(),z=r.f32();
for(float coordinate:{x,y,z})if(!std::isfinite(coordinate) || std::abs(coordinate)>100000)throw Error("native spell location coordinate bound");
// Classic transmits absolute world XYZ and no transport GUID.
// The original native TargetLocation writer emits empty Transport.
value.Location=Position(x,y,z);return value;
};
if(cast.Target.Flags&0x20u)cast.Target.SrcLocation=location();
if(cast.Target.Flags&0x40u)cast.Target.DstLocation=location();
if(r.left()){
const auto display=uint32_t(r.le(4)),slot=uint32_t(r.le(4));
if(display>INT_MAX || slot>28)throw Error("native projectile appearance bound");
cast.CastFlags|=0x20u;
// GetSpellCastDataAmmo returns only the native display ID.
if(display){
if(const auto* route=item_render_profile::find(display,slot))
cast.AmmoDisplayID=int32_t(route->native_display);
else if(slot==24 && (display==5996 || display==5998))
cast.AmmoDisplayID=int32_t(display); // Both servers' fixed arrow/bullet.
}
}
r.end();
WorldPackets::Spells::SpellStart start;WorldPackets::Spells::SpellGo go;
if(start_event)start.Cast=std::move(cast);else go.Cast=std::move(cast);
auto packet=start_event?start.Write():go.Write();return Bytes(packet->data(),packet->data()+packet->size());
}
if((mode=="--spell-event" || mode=="--gateway-spell-event")) {
Reader r(input);auto kind=r.le(1);auto spell=uint32_t(r.le(4));uint32_t old=0;if(kind==2)old=uint32_t(r.le(4));r.end();if(kind>2)throw Error("spell event bound");
Bytes out;
if(mode=="--gateway-spell-event")out=kind==0?forever_learned_spell(spell):kind==1?forever_removed_spell(spell):forever_superceded_spell(old,spell);
else {
WorldPackets::Spells::LearnedSpellInfo learned;learned.SpellID=int32_t(spell);
if(kind==0){WorldPackets::Spells::LearnedSpells packet;packet.ClientLearnedSpellData.push_back(learned);auto p=packet.Write();out.assign(p->data(),p->data()+p->size());}
else if(kind==1){WorldPackets::Spells::UnlearnedSpells packet;packet.SpellID.push_back(spell);auto p=packet.Write();out.assign(p->data(),p->data()+p->size());}
else{WorldPackets::Spells::SupercededSpells packet;learned.Superceded=int32_t(old);packet.ClientLearnedSpellData.push_back(learned);auto p=packet.Write();out.assign(p->data(),p->data()+p->size());}
}
return out;
}
if(mode=="--trait-values") {
Reader r(input);
auto realm=uint16_t(r.le(2));auto map=uint16_t(r.le(4));auto self=r.le(8);auto points=uint32_t(r.le(4));auto count=r.le(4);if(count>4096)throw Error("trait spell context bound");
std::set<uint32_t> known;for(unsigned i=0;i<count;++i)known.insert(uint32_t(r.le(4)));r.end();
UF::ActivePlayerData active;trait_config(active,1491,uint32_t(self&0x7FFFFFFF),forever_talent_ranks(known));set(active.CharacterPoints,int32_t(points));
UF::ActivePlayerData::Mask mask;mask.Set(32);mask.Set(64);mask.Set(134);mask.Set(147);mask.Set(148);
ByteBuffer values;values<<uint8(1)<<uint8(0)<<uint8(3)<<uint32(1u<<TYPEID_ACTIVE_PLAYER);active.WriteUpdate(mask,values,nullptr,nullptr,true);values.FlushBits();
Bytes block{0};append(block,pack_guid(forever_player_guid(self,realm)));le(block,values.size(),4);append(block,std::span(values.data(),values.size()));
Bytes out;le(out,map,2);le(out,1,4);le(out,0x80,1);le(out,block.size(),4);append(out,block);return out;
}
if(mode=="--features") {
WorldPackets::System::FeatureSystemStatus features;
features.CfgRealmID=2;features.CfgRealmRecID=70;features.ContentSetID=137;
features.CommercePricePollTimeSeconds=300;features.MaxPlayerGuidLookupsPerRequest=50;
features.NameLookupTelemetryInterval=60;
// Original Classic club startup (CharacterHandler's pinned native
// feature contract) reads the retail RedeemForBalanceAvailable
// bit; CommunitiesEnabled alone lands two bits too late.
features.RedeemForBalanceAvailable=true;
features.CommunitiesEnabled=true;
features.BnetGroupsEnabled=false;
features.CharacterCommunitiesEnabled=false;
features.ClubPresenceAllowSubscribeAll=true;
features.ClubPresenceUnsubscribeDelay=60000;
// Original70334 PremadeGroupFinderStyleUtils requires active rule93.
// Native Classic server policy93=2 selects the Vanilla-style finder.
features.GameRules.push_back({93,2,0.0f});
// ShowQuestOffer reads rule200 as float (GameRules_C.cpp:141).
// Classic's provider sends 0.5f; absence asserts on item quest popups.
features.GameRules.push_back({200,0,0.5f});
// Official Classic 1.60 realm rules (advocaite/TrinityCore World.cpp list from the
// 70124/70205/70235/70338 sniffs), only those whose name is known (WowPacketParser
// GameRule.cs, TrinityCore DBCEnums, 70334 WowB.exe strings) and true for Tortoise:
features.GameRules.push_back({157,1,0.0f}); // LootMethodStyle: vanilla FFA/RR/ML/group/NBG party loot UI
features.GameRules.push_back({112,1,0.0f}); // SingleTargetComboPoints: points bound to UnitData.ClassicComboTarget (upstream 70338 rogue sniff)
features.GameRules.push_back({173,1,0.0f}); // UnflaggedPlayersCanAttackPvPFlaggedPlayers (vanilla PvP)
features.GameRules.push_back({177,1,0.0f}); // ammo slot (Lua slot 0) valid; Tortoise ammo is PvpMedals
features.GameRules.push_back({162,1,0.0f}); // DisableQuickJoin: no social-queue service
features.GameRules.push_back({114,1,0.0f}); // DisableCampsites
features.GameRules.push_back({102,1,0.0f}); // HousingDashboardDisabled
features.GameRules.push_back({154,0,0.0f}); // HousingEnabled = 0
auto packet=features.Write();return Bytes(packet->data(),packet->data()+packet->size());
}
if(mode=="--glue-features") {
Reader r(input);auto limit=uint32_t(r.le(4));r.end();
if(!limit || limit>10)throw Error("Turtle character-limit policy bound");
WorldPackets::System::FeatureSystemStatusGlueScreen features;
features.MaxCharactersOnThisRealm=int32_t(limit);
features.GameRules.push_back({93,2,0.0f});
auto packet=features.Write();return Bytes(packet->data(),packet->data()+packet->size());
}
if(mode=="--native-auth-success") {
// Serializer only. The native transport must gate this operation on
// genuine SRP/M2 AND an accepted Turtle world-auth response.
Reader r(input);auto address=uint32_t(r.le(4));auto clock=r.le(8);auto size=r.le(2);
if(!address || !size || size>127 || clock>uint64_t(std::numeric_limits<time_t>::max()))throw Error("invalid native realm presentation");
auto bytes=r.take(size);r.end();std::string name(bytes.begin(),bytes.end());
if(std::any_of(name.begin(),name.end(),[](unsigned char c){return c<32;}))throw Error("invalid native realm name");
auto normalized=name;normalized.erase(std::remove(normalized.begin(),normalized.end(),' '),normalized.end());
if(normalized.empty())throw Error("empty normalized realm name");
WorldPackets::Auth::AuthResponse response;
auto& success=response.SuccessInfo.emplace();
success.VirtualRealmAddress=address;success.Time=static_cast<time_t>(clock);
success.VirtualRealms.emplace_back(address,true,false,name,normalized);
// Verified matching Turtle/server CharBaseInfo BYTE rows, filtered
// by implemented native presentation profiles. An empty table
// disables existing-character login in the actual70334 engine.
// Classic has no expansion requirements; this grants no account
// entitlement and Turtle still authorizes the actual login.
std::vector<RaceClassAvailability> available;
for(auto pair:TurtleNativeCreationRaceClasses){
auto found=std::find_if(available.begin(),available.end(),[&](const auto& race){return race.RaceID==pair[0];});
if(found==available.end()){RaceClassAvailability race{};race.RaceID=pair[0];available.push_back(race);found=std::prev(available.end());}
found->Classes.push_back(ClassAvailability{pair[1],0,0,0});
}
success.AvailableClasses=&available;
auto packet=response.Write();return Bytes(packet->data(),packet->data()+packet->size());
}
if(mode=="--native-client-initialization") {
Reader r(input);auto address=uint32_t(r.le(4));auto phase=uint32_t(r.le(4));auto clock=r.le(8);
const uint64_t layout_time=phase==0 && r.left()==8?r.le(8):0;
r.end();
const auto max_time=uint64_t(std::numeric_limits<time_t>::max());
if(!address || phase>1 || clock>max_time || layout_time>max_time)throw Error("invalid native initialization phase");
// Turtle supplies no modern DB2 hotfix pushes or account-wide
// Warband appearance collection. Report unsupported/empty services;
// do not copy Forever database records or clear readiness flags.
WorldPackets::Hotfix::AvailableHotfixes available;
available.VirtualRealmAddress=int32_t(address);
for(auto const& push:item_sparse_compat::Pushes)available.Hotfixes.insert({push.id,1});
for(auto const& push:source_toy_compat::Pushes)available.Hotfixes.insert({push.id,1});
available.Hotfixes.insert({source_recipe_compat::PushID,1});
auto packet=available.Write();Bytes out;le(out,phase?1:2,4);
if(!phase){
le(out,0x4b0001,4);le(out,packet->size(),4);append(out,std::span(packet->data(),packet->size()));
// At character selection the local store supplies the account-wide Edit Mode timestamp.
constexpr size_t global_edit_mode_cache=13;
WorldPackets::ClientConfig::AccountDataTimes times;
times.ServerTime=static_cast<time_t>(clock);
times.AccountTimes[global_edit_mode_cache]=static_cast<time_t>(layout_time);
auto cache=times.Write();le(out,0x4701b6,4);le(out,cache->size(),4);
append(out,std::span(cache->data(),cache->size()));return out;}
// Actual70334 decoder140840800 and typed slot145e6ed18 prove
// collection is0x470363 with this10-byte empty payload. The older
// server's0x470361/four-byte stub silently hits an unused handler.
WorldPackets::Collections::AccountItemCollectionData collection;
collection.Type=ItemCollectionType::WarbandScene;
auto items=collection.Write();le(out,0x470363,4);le(out,items->size(),4);
append(out,std::span(items->data(),items->size()));return out;
}
if(mode=="--native-hotfix-reply") {
Reader r(input);auto build=r.le(4);r.le(4);auto count=r.le(4);
if(build!=70334 || count>4096)throw Error("invalid native hotfix query");
std::set<uint32_t> requested;
for(uint64_t i=0;i<count;++i)requested.insert(uint32_t(r.le(4)));
r.end();WorldPackets::Hotfix::HotfixConnect reply;
size_t bytes=8;
auto append_row = [&](int32_t push_id, uint32_t unique, const auto& row) {
bytes += 21 + row.data.size();
if (bytes > 1048576) throw Error("hotfix response bound; request pushes separately");
auto& hotfix = reply.Hotfixes.emplace_back();
hotfix.Record.ID = {push_id, unique};
hotfix.Record.TableHash = row.table;
hotfix.Record.RecordID = int32_t(row.id);
// Turtle-generated transmog templates are not items: remove any cached copy instead.
if (gateway::generated_transmog_items::row(row)) {
hotfix.Record.HotfixStatus = DB2Manager::HotfixRecord::Status::RecordRemoved;
hotfix.Size = 0;
bytes -= row.data.size();
return;
}
hotfix.Record.HotfixStatus = item_hotfix_status(row);
hotfix.Size = uint32_t(row.data.size());
if (!row.data.empty()) reply.HotfixContent.append(row.data.data(), row.data.size());
};
for (const auto& push : item_sparse_compat::Pushes) {
if (!requested.contains(uint32_t(push.id))) continue;
for (uint32_t offset = 0; offset < push.count; ++offset) {
const auto& row = item_sparse_compat::Records[push.first + offset];
// Keep each surviving row's original cache identity even when a sibling is superseded.
if (!source_recipe_compat::lookup(row.table, row.id))
append_row(push.id, offset + 1, row);
}
}
// Toy rows are served as removals: a Toy row hands its item's spell to the toy box, which the Turtle
// server never fills, so the client dropped those spells from the known list (MOLL-E, Brainwashing
// Device, illusions...). Toys stay ordinary known spells in the spellbook Toys tab (owner, 2026-11-22).
for (const auto& push : source_toy_compat::Pushes) {
if (!requested.contains(uint32_t(push.id))) continue;
for (uint32_t offset = 0; offset < push.count; ++offset) {
const auto& row = source_toy_compat::Records[push.first + offset];
auto& hotfix = reply.Hotfixes.emplace_back();
bytes += 21;
hotfix.Record.ID = {push.id, offset + 1};
hotfix.Record.TableHash = row.table;
hotfix.Record.RecordID = int32_t(row.id);
hotfix.Record.HotfixStatus = DB2Manager::HotfixRecord::Status::RecordRemoved;
hotfix.Size = 0;
}
}
if (requested.contains(source_recipe_compat::PushID)) {
uint32_t unique = 0;
for (const auto& row : source_recipe_compat::Records)
append_row(source_recipe_compat::PushID, ++unique, row);
}
auto packet=reply.Write();return Bytes(packet->data(),packet->data()+packet->size());
}
if(mode=="--native-db-reply-missing") {
Reader r(input);WorldPackets::Hotfix::DBReply reply;
reply.TableHash=uint32_t(r.le(4));reply.RecordID=uint32_t(r.le(4));reply.Timestamp=uint32_t(r.le(4));r.end();
if(!reply.TableHash)throw Error("invalid DB2 query table");
// Historical ABI name retained. Only reviewed, source-backed
// build70334 records are available; unknown tables/IDs retain the
// source HandleDBQueryBulk explicit Invalid result. No keys or
// schema identifiers are changed, and runtime has no SQL provider.
auto apply_hotfix = [&](const auto& row) {
if (gateway::generated_transmog_items::row(row)) {
reply.Status = DB2Manager::HotfixRecord::Status::RecordRemoved;
return;
}
reply.Status=item_hotfix_status(row);
if(!row.data.empty())reply.Data.append(row.data.data(),row.data.size());
};
if (const auto* recipe = source_recipe_compat::lookup(reply.TableHash, reply.RecordID)) {
apply_hotfix(*recipe);
} else if(reply.TableHash==broadcast_text::TableHash) {
// An explicit packaged hotfix/removal wins even if a future build
// introduces an ID already present in the NPC text catalogue.
static const auto overrides = [] {
std::vector<const item_sparse_compat::Record*> result;
for(const auto& row:item_sparse_compat::Records)
if(row.table==broadcast_text::TableHash)result.push_back(&row);
return result;
}();
auto override=std::find_if(overrides.begin(),overrides.end(),
[&](const auto* row) { return row->id==reply.RecordID; });
if(override!=overrides.end())apply_hotfix(**override);
else if(auto data=broadcast_text::lookup(reply.RecordID)) {
reply.Status=DB2Manager::HotfixRecord::Status::Valid;
reply.Data.append(data->data(),data->size());
}
} else {
bool found=false;
for(const auto& row:item_sparse_compat::Records)if(row.table==reply.TableHash && row.id==reply.RecordID){
apply_hotfix(row);
found=true;
break;
}
if(!found){
for(const auto& row:source_toy_compat::Records)if(row.table==reply.TableHash && row.id==reply.RecordID){
reply.Status=DB2Manager::HotfixRecord::Status::RecordRemoved; // see Toy note in the push writer
break;
}
}
}
auto packet=reply.Write();return Bytes(packet->data(),packet->data()+packet->size());
}
if(mode=="--native-exploration-experience"){
Reader r(input);auto area=r.le(4),xp=r.le(4);r.end();
if(area>0x7fffffff || xp>0x7fffffff)throw Error("native exploration experience bound");
WorldPackets::Misc::ExplorationExperience packet{int32_t(xp),int32_t(area)};
auto p=packet.Write();return Bytes(p->data(),p->data()+p->size());
}
if(mode=="--native-explored-zone-values"){
// Independent native typed-field oracle: input is32 destination
// uint64 words, not legacy source fields or their pairing helper.
Reader r(input);auto realm=uint16_t(r.le(2)),map=uint16_t(r.le(4));auto self=r.le(8);
UF::ActivePlayerData active;UF::MutableFieldReference<UF::ActivePlayerData,true> ref{active};
auto vector=ref.ModifyValue(&UF::ActivePlayerData::BitVectors)
.ModifyValue(&UF::BitVectors::Values,PLAYER_DATA_FLAG_EXPLORED_ZONES_INDEX);
for(unsigned i=0;i<32;++i)vector.ModifyValue(&UF::BitVector::Values,i).SetValue(uint64_t(r.le(8)));
r.end();ByteBuffer values;values<<uint8(1)<<uint8(0)<<uint8(3)<<uint32(1u<<TYPEID_ACTIVE_PLAYER);
active.WriteUpdate(active.GetChangesMask(),values,nullptr,nullptr,false);values.FlushBits();
Bytes block{0};append(block,pack_guid(forever_player_guid(self,realm)));le(block,values.size(),4);
append(block,std::span(values.data(),values.size()));Bytes result;le(result,map,2);le(result,1,4);le(result,0x80,1);le(result,block.size(),4);append(result,block);return result;
}
bool self_talents=mode=="--self-talents";
bool self_party_type=mode=="--self-party-type";
bool pet_stable=mode=="--pet-stable";
bool gameobjects=mode=="--gameobjects";
if(mode=="--companion-name"){
Reader reader(input);auto raw=reader.take(16);Reader id(raw);auto low=id.le(8),high=id.le(8);
if(!low || high>>58!=10)throw Error("companion name identity bound");
WorldPackets::Query::QueryPetNameResponse packet;packet.UnitGUID.SetRawValue(high,low);packet.Allow=true;
packet.Timestamp=uint32_t(reader.le(4));packet.Name=reader.cstring(255);reader.end();
if(packet.Name.empty())throw Error("empty Source companion name");
auto out=packet.Write();return Bytes(out->data(),out->data()+out->size());
}
bool owned_stat_pet=mode=="--owned-stat-pet";
bool companions=owned_stat_pet || mode=="--companions";
bool combat_npcs=mode=="--npcs-combat";
bool typed_npcs=companions || combat_npcs || mode=="--npcs-types";
bool npcs=typed_npcs || (mode=="--npcs");
bool creature_template=mode=="--creature-template";
bool gateway_monster=mode=="--gateway-monster-move";
bool monster_move=gateway_monster || (mode=="--monster-move");
bool melee_damage=mode=="--melee-damage";
bool owned_pet_values=mode=="--owned-stat-pet-values";
bool companion_values=owned_pet_values || mode=="--companion-values";
bool typed_unit_values=companion_values || mode=="--unit-values-profile";
bool unit_values=typed_unit_values || (mode=="--unit-values");
bool gossip_menu=mode=="--gossip-menu";
bool vendor_inventory=mode=="--vendor-inventory";
bool reputation_initial=mode=="--reputation-initial";
bool attack_error=mode=="--attack-error";
bool power_update=mode=="--power-update";
if(!mode.empty() && !self_talents && !self_party_type && !pet_stable && !npcs && !gameobjects && !creature_template && !monster_move && !vendor_inventory && !gossip_menu && !unit_values && !melee_damage && !reputation_initial && !attack_error && !power_update)throw Error("unknown serializer mode");
if(power_update){Reader r(input);auto realm=uint16_t(r.le(2));auto legacy=r.le(8);auto type=uint8_t(r.le(1));auto value=uint32_t(r.le(4));r.end();WorldPackets::Combat::PowerUpdate packet;auto raw=forever_player_guid(legacy,realm);Reader guid(raw);auto low=guid.le(8),high=guid.le(8);packet.Guid.SetRawValue(high,low);packet.Powers.emplace_back(int32_t(value),type);auto out=packet.Write();return Bytes(out->data(),out->data()+out->size());}
if(attack_error){Reader r(input);auto reason=r.le(1);r.end();if(reason>3)throw Error("native attack error bound");WorldPackets::Combat::AttackSwingError packet{AttackSwingErr(reason)};auto out=packet.Write();return Bytes(out->data(),out->data()+out->size());}
if(reputation_initial) {
Reader r(input);auto count=r.le(4);if(count>256)throw Error("native reputation oracle bound");
WorldPackets::Reputation::InitializeFactions packet;
for(unsigned i=0;i<count;++i){WorldPackets::Reputation::FactionData row;row.FactionID=int32_t(r.le(4));row.Flags=uint16_t(r.le(2));row.Standing=std::bit_cast<int32_t>(uint32_t(r.le(4)));packet.Factions.push_back(row);}
r.end();auto out=packet.Write();return Bytes(out->data(),out->data()+out->size());
}
if(melee_damage) {
Reader r(input);auto realm=uint16_t(r.le(2));auto map=uint32_t(r.le(4));auto self=r.le(8);auto d=turtle_melee_damage(r.take(r.left()));
WorldPackets::CombatLog::AttackerStateUpdate packet;packet.Flags=forever_hit_flags(d);
auto assign=[&](ObjectGuid& target,uint64_t id){auto raw=id==self?forever_player_guid(id,realm):forever_creature_guid(id,uint32_t(id>>24)&0xFFFFFF,realm,map);Reader v(raw);auto low=v.le(8),high=v.le(8);target.SetRawValue(high,low);};
assign(packet.AttackerGUID,d.attacker);assign(packet.VictimGUID,d.victim);packet.Damage=d.damage;packet.OriginalDamage=int64_t(d.damage)+d.absorbed+std::max(0,d.resisted)+d.blocked;
packet.VictimState=forever_melee_victim_state(d);packet.AttackerState=d.attacker_state;packet.MeleeSpellID=d.spell;packet.BlockAmount=d.blocked;
if(d.sub_damage){packet.SubDmg.emplace();packet.SubDmg->SchoolMask=d.school;packet.SubDmg->FDamage=float(d.damage);packet.SubDmg->Damage=d.damage;packet.SubDmg->Absorbed=d.absorbed;packet.SubDmg->Resisted=d.resisted;}
auto out=packet.Write();return Bytes(out->data(),out->data()+out->size());
}
if(unit_values) {
Reader r(input);auto realm=uint16_t(r.le(2));auto map=uint32_t(r.le(4));auto self=r.le(8);
unsigned self_class=0;std::map<uint64_t,uint8_t> power_types;
if(typed_unit_values){self_class=r.le(1);if(!self_class || self_class>=12)throw Error("self power class bound");auto count=r.le(2);if(count>4096)throw Error("power context count bound");for(unsigned i=0;i<count;++i){auto id=r.le(8);auto type=uint8_t(r.le(1));if(type>4 || !power_types.emplace(id,type).second)throw Error("invalid power context");}}
std::map<uint64_t,CompanionBinding> pets;if(companion_values)pets=companion_bindings(r,realm,map);
auto opcode=uint32_t(r.le(4));
auto updates=turtle_object_updates(opcode,r.take(r.left()));Bytes blocks;unsigned count=0;
for(const auto& u:updates)if(u.kind==0 && (companion_values?pets.contains(u.guid):(u.guid==self || (u.guid>>48)==0xF130))) {
UF::UnitData unit;UF::ObjectData object;UF::ActivePlayerData active;UF::PlayerData player;UF::PlayerData::Mask pm;UF::UnitData::Mask um;UF::ObjectData::Mask om;UF::ActivePlayerData::Mask am;bool have_unit=false,have_object=false,have_active=false,have_player=false;
if (u.guid == self && u.fields.contains(Turtle::PLAYER_BYTES) &&
u.fields.contains(Turtle::PLAYER_BYTES_2) && u.fields.contains(Turtle::UNIT_FIELD_BYTES_0)) {
player_customizations(player, u.fields.at(Turtle::UNIT_FIELD_BYTES_0),
u.fields.at(Turtle::PLAYER_BYTES), u.fields.at(Turtle::PLAYER_BYTES_2));
pm |= player.GetChangesMask();
have_player = true;
}
if(u.guid==self && std::any_of(u.fields.begin(),u.fields.end(),[](const auto& f){return source_explored_zone_field(f.first);})){
explored_zone_fields(active,u.fields,false);am|=active.GetChangesMask();have_active=true;
}
for(const auto& [index,value]:u.fields){bool handled=true;
if(u.guid==self && index==Turtle::PLAYER_GUILDID){auto raw=forever_guild_guid(value,realm);Reader id(raw);auto low=id.le(8),high=id.le(8);ObjectGuid guild;guild.SetRawValue(high,low);changed(um,unit.GuildGUID,guild);have_unit=true;continue;}
if(u.guid==self && index==Turtle::PLAYER_GUILDRANK){if(value>=10)throw Error("source guild rank bound");changed(pm,player.GuildRankID,value);have_player=true;continue;}
if(u.guid==self && index==Turtle::PLAYER_FLAGS){changed(pm,player.PlayerFlags,forever_player_flags(value));have_player=true;continue;}
if(u.guid==self && index==Turtle::PLAYER_BYTES_3){changed(pm,player.PvpTitle,uint8_t(value>>24));have_player=true;continue;}
if(u.guid==self && index>=Turtle::PLAYER_SKILL_INFO_1_1 && index<Turtle::PLAYER_SKILL_INFO_1_1+384){
// Tortoise Player.cpp PLAYER_SKILL_*_INDEX encodes128
// triples. Each received word independently identifies
// both native fields; absent words must stay untouched.
auto offset=index-Turtle::PLAYER_SKILL_INFO_1_1,slot=offset/3;
auto& skills=const_cast<UF::SkillInfo&>(*active.Skill);
if(offset%3==0){
const_cast<uint16&>(skills.SkillLineID[slot])=uint16(value);
const_cast<uint16&>(skills.SkillStep[slot])=uint16(value>>16);
// Match the established full SELF representation,
// including explicit removal of a source skill.
const_cast<uint16&>(skills.SkillStartingRank[slot])=uint16((value&0xffff)?1:0);
skills.MarkChanged(&UF::SkillInfo::SkillLineID,slot);
skills.MarkChanged(&UF::SkillInfo::SkillStep,slot);
skills.MarkChanged(&UF::SkillInfo::SkillStartingRank,slot);
}else if(offset%3==1){
const_cast<uint16&>(skills.SkillRank[slot])=uint16(value);
const_cast<uint16&>(skills.SkillMaxRank[slot])=uint16(value>>16);
skills.MarkChanged(&UF::SkillInfo::SkillRank,slot);
skills.MarkChanged(&UF::SkillInfo::SkillMaxRank,slot);
}else{
const_cast<int16&>(skills.SkillTempBonus[slot])=std::bit_cast<int16_t>(uint16_t(value));
// Source permanent bonus is signed16; the original
// destination wire field is uint16. Preserve bits.
const_cast<uint16&>(skills.SkillPermBonus[slot])=uint16(value>>16);
skills.MarkChanged(&UF::SkillInfo::SkillTempBonus,slot);
skills.MarkChanged(&UF::SkillInfo::SkillPermBonus,slot);
}
am.Set(32);am.Set(63);have_active=true;continue;
}
if (u.guid==self && index==Turtle::UNIT_MOD_CAST_SPEED) {
const float factor=player_cast_factor(value);
changed(um,unit.ModCastingSpeed,factor);
// Source can explicitly publish zero cast time. No finite haste represents that case.
changed(um,unit.ModSpellHaste,factor>0.0f ? factor : 1.0f);
have_unit=true;
continue;
}
if(u.guid==self && player_damage_modifier(active,index,value)){
am|=active.GetChangesMask();have_active=true;continue;
}
// Source sends the current, speed-modified attack period as integer milliseconds.
if(u.guid==self && index>=Turtle::UNIT_FIELD_BASEATTACKTIME && index<=Turtle::UNIT_FIELD_RANGEDATTACKTIME){
if(index==Turtle::UNIT_FIELD_RANGEDATTACKTIME)
changed(um,unit.RangedAttackRoundBaseTime,value);
else{
UF::MutableFieldReference<UF::UnitData,true> ref{unit};
ref.ModifyValue(&UF::UnitData::AttackRoundBaseTime,index-Turtle::UNIT_FIELD_BASEATTACKTIME).SetValue(value);
um|=unit.GetChangesMask();
}
have_unit=true;continue;
}
if(u.guid==self){bool owned=true;
auto number=[&](){auto v=std::bit_cast<float>(value);if(!std::isfinite(v))throw Error("nonfinite active combat statistic");return v;};
switch(index){
case Turtle::PLAYER_REST_STATE_EXPERIENCE:
{UF::MutableFieldReference<UF::ActivePlayerData,true> ref{active};
ref.ModifyValue(&UF::ActivePlayerData::RestInfo,0)
.ModifyValue(&UF::RestInfo::Threshold).SetValue(value);}
am|=active.GetChangesMask();break;
case Turtle::PLAYER_BYTES_2:
// A zero high byte leaves the active rest state and update mask untouched.
{const auto rest_state=source_xp_rest_state(value);
if (rest_state == 0) continue;
UF::MutableFieldReference<UF::ActivePlayerData,true> ref{active};
ref.ModifyValue(&UF::ActivePlayerData::RestInfo,0)
.ModifyValue(&UF::RestInfo::StateID).SetValue(rest_state);}
am|=active.GetChangesMask();break;
case Turtle::PLAYER_XP:changed(am,active.XP,int32_t(value));break;
case Turtle::PLAYER_NEXT_LEVEL_XP:changed(am,active.NextLevelXP,int32_t(value));break;
case Turtle::PLAYER_CHARACTER_POINTS1:changed(am,active.CharacterPoints,int32_t(value));break;
case Turtle::PLAYER_FIELD_COINAGE:changed(am,active.Coinage,uint64_t(value));break;
case Turtle::PLAYER_FIELD_BYTES:changed(am,active.LocalFlags,forever_player_local_flags(value));changed(am,active.LifetimeMaxRank,uint8_t(value>>24));
// Tortoise Player::SetComboPoints: byte 1 = points on PLAYER_FIELD_COMBO_TARGET -> native ComboPoints power.
if(auto slot=ForeverClassComboSlot[self_class];slot>=0){const_cast<int32&>(unit.Power[slot])=int32_t((value>>8)&255);um.Set(139);um.Set(140+slot);have_unit=true;}
break;
case Turtle::PLAYER_SELF_RES_SPELL:{
// Tortoise keeps one self-res spell; native ActivePlayerData.SelfResSpells is the list
// the death popup offers (TC Player::AddSelfResSpell / HandleSelfResOpcode).
if(value>0x7fffffff)throw Error("self-res spell bound");
UF::MutableFieldReference<UF::ActivePlayerData,true> ref{active};
auto list=ref.ModifyValue(&UF::ActivePlayerData::SelfResSpells);UF::ClearDynamicUpdateFieldValues(list);
if(value)UF::AddDynamicUpdateFieldValue(list)=int32_t(value);
am|=active.GetChangesMask();break;}
case Turtle::PLAYER_FIELD_SESSION_KILLS:changed(am,active.TodayHonorableKills,uint16_t(value));break;
case Turtle::PLAYER_FIELD_YESTERDAY_KILLS:changed(am,active.YesterdayHonorableKills,uint16_t(value));break;
case Turtle::PLAYER_FIELD_LIFETIME_HONORABLE_KILLS:changed(am,active.LifetimeHonorableKills,uint32_t(value));break;
case Turtle::PLAYER_FIELD_BYTES2:changed(am,active.AuraVision,forever_aura_vision(value));break;
case Turtle::PLAYER_BLOCK_PERCENTAGE:changed(am,active.BlockPercentage,number());break;
case Turtle::PLAYER_DODGE_PERCENTAGE:changed(am,active.DodgePercentage,number());break;
case Turtle::PLAYER_PARRY_PERCENTAGE:changed(am,active.ParryPercentage,number());break;
case Turtle::PLAYER_CRIT_PERCENTAGE:changed(am,active.CritPercentage,number());break;
case Turtle::PLAYER_RANGED_CRIT_PERCENTAGE:changed(am,active.RangedCritPercentage,number());break;
default:owned=false;
}
if(owned){have_active=true;continue;}
}
if(companion_values){
auto assign=[](const Guid128& raw){Reader id(raw);auto low=id.le(8),high=id.le(8);ObjectGuid out;out.SetRawValue(high,low);return out;};
const auto& pet=pets.at(u.guid);
if(owned_pet_values && ((self_class!=3 && self_class!=9) || pet.owner!=forever_player_guid(self,realm)))
throw Error("controlled pet values outside local owner");
if(index==SourcePetOwner || index==SourcePetOwner+1){changed(um,unit.SummonedBy,assign(pet.owner));have_unit=true;continue;}
if(index==SourcePetCreator || index==SourcePetCreator+1){changed(um,unit.CreatedBy,assign(pet.creator));have_unit=true;continue;}
if(index==SourcePetNumber){if(value!=(owned_pet_values?uint32_t(u.guid>>24)&0xffffff:0u))throw Error("source pet-number differs from bound role");changed(um,unit.PetNumber,value);have_unit=true;continue;}
if(index==SourcePetNameTimestamp){if(value && !owned_pet_values)throw Error("custom PetName outside companion profile");changed(um,unit.PetNameTimestamp,value);have_unit=true;continue;}
if(index==SourcePetCreatedBySpell){changed(um,unit.CreatedBySpell,int32_t(value));have_unit=true;continue;}
if(index==Turtle::OBJECT_FIELD_ENTRY){changed(om,object.EntryID,int32_t(value));have_object=true;continue;}
}
switch(index){
case Turtle::UNIT_FIELD_HEALTH:changed(um,unit.Health,int64_t(value));break;
case Turtle::UNIT_FIELD_MAXHEALTH:changed(um,unit.MaxHealth,int64_t(value));break;
case Turtle::UNIT_FIELD_AURASTATE:changed(um,unit.AuraState,translate_aura_states(value).native_flags);break;
case Turtle::UNIT_FIELD_LEVEL:changed(um,unit.Level,int32_t(value));changed(um,unit.EffectiveLevel,int32_t(value));break;
case Turtle::UNIT_FIELD_FACTIONTEMPLATE:changed(um,unit.FactionTemplate,int32_t(value));break;
case Turtle::UNIT_NPC_FLAGS:changed(um,unit.NpcFlags,forever_npc_flags(value));break;
case Turtle::UNIT_NPC_EMOTESTATE:changed(um,unit.EmoteState,int32_t(emote_profile::animation(value)));break;
case Turtle::UNIT_FIELD_FLAGS:changed(um,unit.Flags,forever_unit_flags(value));changed(um,unit.PvpFlags,uint8_t((value&0x1000)?1:0));break;
case Turtle::UNIT_FIELD_BYTES_1:changed(um,unit.StandState,uint8_t(value));changed(um,unit.ShapeshiftForm,uint8_t(value>>16));if(u.guid!=self)changed(um,unit.VisFlags,forever_unit_vis_flags(value));break;
case Turtle::UNIT_FIELD_BYTES_2:changed(um,unit.SheatheState,uint8_t(value));break;
case Turtle::UNIT_FIELD_DISPLAYID:changed(um,unit.DisplayID,int32_t(value));break;
case Turtle::UNIT_FIELD_MOUNTDISPLAYID:if(value>0x7fffffff)throw Error("invalid source mount display");changed(um,unit.MountDisplayID,int32_t(value));break;
case Turtle::UNIT_FIELD_BYTES_0:if((value>>24)<4)changed(um,unit.DisplayPower,uint8_t(value>>24));else handled=false;break;
case Turtle::UNIT_DYNAMIC_FLAGS:changed(om,object.DynamicFlags,forever_unit_dynamic_flags(value));have_object=true;handled=false;break;
case Turtle::UNIT_FIELD_ATTACK_POWER:changed(um,unit.AttackPower,int32_t(value));break;
case Turtle::UNIT_FIELD_RANGED_ATTACK_POWER:changed(um,unit.RangedAttackPower,int32_t(value));break;
case Turtle::UNIT_FIELD_BASE_HEALTH:changed(um,unit.BaseHealth,int32_t(value));break;
case Turtle::UNIT_FIELD_BASE_MANA:changed(um,unit.BaseMana,int32_t(value));break;
case Turtle::UNIT_FIELD_ATTACK_POWER_MODS:changed(um,unit.AttackPowerModPos,std::bit_cast<int16_t>(uint16_t(value)));changed(um,unit.AttackPowerModNeg,std::bit_cast<int16_t>(uint16_t(value>>16)));break;
case Turtle::UNIT_FIELD_RANGED_ATTACK_POWER_MODS:changed(um,unit.RangedAttackPowerModPos,std::bit_cast<int16_t>(uint16_t(value)));changed(um,unit.RangedAttackPowerModNeg,std::bit_cast<int16_t>(uint16_t(value>>16)));break;
default:
{
if(index>=Turtle::UNIT_FIELD_STAT0 && index<Turtle::UNIT_FIELD_STAT0+5){auto i=index-Turtle::UNIT_FIELD_STAT0;const_cast<int32&>(unit.Stats[i])=int32_t(value);um.Set(187);um.Set(188+i);break;}
if(index>=Turtle::UNIT_FIELD_RESISTANCES && index<Turtle::UNIT_FIELD_RESISTANCES+7){auto i=index-Turtle::UNIT_FIELD_RESISTANCES;const_cast<int32&>(unit.Resistances[i])=int32_t(value);um.Set(208);um.Set(209+i);break;}
auto number=[&](){auto v=std::bit_cast<float>(value);if(!std::isfinite(v))throw Error("nonfinite changed unit statistic");return v;};
if(index==Turtle::UNIT_FIELD_MINDAMAGE){changed(um,unit.MinDamage,number());break;}
if(index==Turtle::UNIT_FIELD_MAXDAMAGE){changed(um,unit.MaxDamage,number());break;}
if(index==Turtle::UNIT_FIELD_MINOFFHANDDAMAGE){changed(um,unit.MinOffHandDamage,number());break;}
if(index==Turtle::UNIT_FIELD_MAXOFFHANDDAMAGE){changed(um,unit.MaxOffHandDamage,number());break;}
if(index==Turtle::UNIT_FIELD_MINRANGEDDAMAGE){changed(um,unit.MinRangedDamage,number());break;}
if(index==Turtle::UNIT_FIELD_MAXRANGEDDAMAGE){changed(um,unit.MaxRangedDamage,number());break;}
bool maximum=index>=Turtle::UNIT_FIELD_MAXPOWER1 && index<Turtle::UNIT_FIELD_MAXPOWER1+5;
bool current=index>=Turtle::UNIT_FIELD_POWER1 && index<Turtle::UNIT_FIELD_POWER1+5;
if(!maximum && !current){handled=false;break;}
auto power=index-(maximum?Turtle::UNIT_FIELD_MAXPOWER1:Turtle::UNIT_FIELD_POWER1);int slot=-1;
// Legacy happiness4 is modern27, not combo points4. Pets are outside this profile.
if(power<4){if(u.guid==self)slot=ForeverClassPowerSlots[self_class][power];else if(auto found=power_types.find(u.guid);found!=power_types.end() && found->second==power)slot=0;}
if(slot<0){handled=false;break;}
if(maximum)const_cast<int32&>(unit.MaxPower[slot])=int32_t(value);else const_cast<int32&>(unit.Power[slot])=int32_t(value);
um.Set(139);um.Set((maximum?150:140)+slot);}
}
have_unit|=handled;
}
if(u.guid==self && u.fields.contains(Turtle::UNIT_FIELD_BYTES_1) && u.fields.contains(Turtle::PLAYER_FIELD_BYTES2)){
changed(um,unit.VisFlags,forever_unit_vis_flags(u.fields.at(Turtle::UNIT_FIELD_BYTES_1),u.fields.at(Turtle::PLAYER_FIELD_BYTES2)));have_unit=true;
}
if(!have_unit && !have_object && !have_active && !have_player)continue;
ByteBuffer values;values<<uint8(u.guid==self)<<uint8(0)<<uint8(3)<<uint32((have_object?(1u<<TYPEID_OBJECT):0)|(have_unit?(1u<<TYPEID_UNIT):0)|(have_active?(1u<<TYPEID_ACTIVE_PLAYER):0)|(have_player?(1u<<TYPEID_PLAYER):0));
if(have_object)object.WriteUpdate(om,values,nullptr,nullptr,false);
if(have_unit)unit.WriteUpdate(um,values,nullptr,nullptr,false);
if(have_player)player.WriteUpdate(pm,values,nullptr,nullptr,false);
if(have_active)active.WriteUpdate(am,values,nullptr,nullptr,false);
values.FlushBits();Bytes block{0};auto guid=companion_values?forever_pet_guid(u.guid,pets.at(u.guid).original_entry,realm,map):
u.guid==self?forever_player_guid(self,realm):forever_creature_guid(u.guid,uint32_t(u.guid>>24)&0xFFFFFF,realm,map);
append(block,pack_guid(guid));le(block,values.size(),4);append(block,std::span(values.data(),values.size()));append(blocks,block);++count;
}
Bytes out;le(out,map,2);le(out,count,4);le(out,0x80,1);le(out,blocks.size(),4);append(out,blocks);return out;
}
if(gossip_menu) {
Reader r(input);auto realm=uint16_t(r.le(2));auto map=uint32_t(r.le(4));auto menu=codec_gossip_menu(r.take(r.left()));
auto raw=forever_creature_guid(menu.guid,uint32_t(menu.guid>>24)&0xFFFFFF,realm,map);Reader id(raw);auto low=id.le(8),high=id.le(8);
WorldPackets::NPC::GossipMessage packet;packet.GossipGUID.SetRawValue(high,low);packet.GossipID=menu.text_id;
if (menu.broadcast_text.value_or(0)) packet.BroadcastTextID = *menu.broadcast_text;
for(const auto& o:menu.options){auto& target=packet.GossipOptions.emplace_back();target.GossipOptionID=o.index;target.OptionFlags=o.coded?1:0;target.OrderIndex=o.index;target.Text=o.text;}
for(const auto& q:menu.quests){auto& target=packet.GossipText.emplace_back();target.QuestID=q.id;target.QuestType=forever_quest_menu_icon(q.icon);target.QuestTitle=q.title;}
auto output=packet.Write();return Bytes(output->data(),output->data()+output->size());
}
if(vendor_inventory) {
Reader r(input);auto realm=uint16_t(r.le(2));auto map=uint32_t(r.le(4));auto inventory=turtle_vendor_inventory(r.take(r.left()));
auto raw=forever_creature_guid(inventory.guid,uint32_t(inventory.guid>>24)&0xFFFFFF,realm,map);Reader id(raw);auto low=id.le(8),high=id.le(8);
WorldPackets::NPC::VendorInventory packet;packet.Vendor.SetRawValue(high,low);packet.Reason=inventory.reason;
for(const auto& source:inventory.items) {WorldPackets::NPC::VendorItem item;item.MuID=source.slot;item.Type=1;item.Item.ItemID=source.item;item.Quantity=source.quantity;item.Price=source.price;item.StackCount=source.stack;packet.Items.push_back(item);}
auto output=packet.Write();return Bytes(output->data(),output->data()+output->size());
}
if(monster_move) {
Reader r(input);auto realm=uint16_t(r.le(2));auto map=uint32_t(r.le(4));auto move=turtle_monster_spline(r.take(r.left()));
auto raw=move.guid<=0xffffffffULL?forever_player_guid(move.guid,realm):forever_creature_guid(move.guid,uint32_t(move.guid>>24)&0xFFFFFF,realm,map);Reader id(raw);
if(gateway_monster) {auto output=forever_monster_spline(move,raw);return output;}
move=project_native_monster_spline(move);
auto low=id.le(8),high=id.le(8);WorldPackets::Movement::MonsterMove packet;packet.MoverGUID.SetRawValue(high,low);
packet.Pos=Position(move.start[0],move.start[1],move.start[2]);packet.SplineData.ID=move.id;
if(move.stop)packet.SplineData.StopSplineStyle=2;
else{
auto& spline=packet.SplineData.Move;spline.Flags=move.flying?0x400a00:0x400000;spline.MoveTime=move.duration;spline.Face=move.face==4?3:0;spline.FaceDirection=move.angle;
for(const auto& point:move.points)spline.Points.emplace_back(point[0],point[1],point[2]);
}
auto output=packet.Write();return Bytes(output->data(),output->data()+output->size());
}
if(creature_template) {
Reader r(input);auto unit_class=r.le(1);auto reply=turtle_creature_template(r.take(r.left()));
WorldPackets::Query::QueryCreatureResponse response;response.CreatureID=reply.entry;response.Allow=reply.found;
auto& stats=response.Stats;stats.Name=reply.names;stats.Title=reply.title;stats.Flags[0]=reply.flags;
stats.CreatureType=reply.type;stats.CreatureFamily=reply.family;stats.Classification=reply.rank;stats.Leader=reply.leader;
stats.Display.TotalProbability=1.0f;stats.Display.CreatureDisplay.push_back({reply.display,1.0f,1.0f});
stats.HpMulti=stats.EnergyMulti=1.0f;stats.Class=unit_class;stats.HealthScalingExpansion=-1;
auto packet=response.Write();return Bytes(packet->data(),packet->data()+packet->size());
}
Reader r(input);
uint8_t home_party_type = GROUP_TYPE_NONE;
std::optional<PetStableDto> initial_stable;
if (pet_stable) {
const auto kind = r.le(1);
if (kind == 1 || kind == 2) return stable_values(pet_stable_from_input(input));
if (kind != 0) throw Error("unknown pet stable operation");
home_party_type = uint8_t(r.le(1));
if (home_party_type > GROUP_TYPE_NORMAL) throw Error("invalid stable create party type");
initial_stable = read_pet_stable_snapshot(r);
}
if (self_party_type) {
auto kind = r.le(1);
home_party_type = uint8_t(r.le(1));
if (kind > 1 || home_party_type > GROUP_TYPE_NORMAL)
throw Error("invalid self party type");
if (kind == 1)
return self_party_type_values(r, home_party_type);
}
auto guid=r.le(8); auto realm=uint16_t(r.le(2)); auto address=uint32_t(r.le(4)); auto map=uint32_t(r.le(4));
auto zone=uint32_t(r.le(4));auto account=uint32_t(r.le(4)),bnet=uint32_t(r.le(4));auto name=r.cstring(63); auto race=r.le(1),cls=r.le(1),sex=r.le(1);
std::set<uint32_t> known_spells;
if(self_talents){auto count=r.le(4);if(count>4096)throw Error("self trait spell context bound");for(unsigned i=0;i<count;++i)known_spells.insert(uint32_t(r.le(4)));}
std::map<uint32_t,uint8_t> creature_types;
std::set<uint64_t> creature_guids;
std::map<uint64_t,Guid128> combat_victims;
std::map<uint64_t,CompanionBinding> pets;
if(typed_npcs) {
auto count=r.le(4);if(count>4096)throw Error("creature metadata count bound");
for(unsigned i=0;i<count;++i) {
auto entry=uint32_t(r.le(4));auto type=uint8_t(r.le(1));
if(!entry || entry>0x7FFFFF || type>15 || !creature_types.emplace(entry,type).second)
throw Error("creature metadata identity bound");
}
count=r.le(4);if(count>4096)throw Error("creature GUID count bound");
for(unsigned i=0;i<count;++i)if(!creature_guids.insert(r.le(8)).second)throw Error("duplicate creature GUID");
}
if(companions)pets=companion_bindings(r,realm,map);
if(combat_npcs){
auto count=r.le(4);if(count>creature_guids.size())throw Error("NPC combat owner count bound");
for(unsigned i=0;i<count;++i){
auto owner=r.le(8);auto bytes=r.take(16);Guid128 raw{};std::copy(bytes.begin(),bytes.end(),raw.begin());
Reader id(bytes);auto low=id.le(8),high=id.le(8);ObjectGuid victim;victim.SetRawValue(high,low);
// These are current authenticated presentation bindings, not
// identities inferred from raw source GUID category bits.
if(!creature_guids.contains(owner) || victim.IsEmpty() ||
(!victim.IsPlayer() && !victim.IsCreatureOrPet()) || !combat_victims.emplace(owner,raw).second)
throw Error("NPC combat binding identity bound");
}
}
auto opcode=uint32_t(r.le(4)); auto body=r.take(r.left());
if(!turtle_native_presentation_pair(race,cls) || sex>1 || map>65535) throw Error("unsupported create profile");
auto updates=turtle_object_updates(opcode,body);
if(gameobjects) {
Bytes blocks;uint32_t count=0;
for(const auto& u:updates)if(u.type==5 && (u.kind==2 || u.kind==3) && u.movement) {
auto value=[&](unsigned index){auto it=u.fields.find(index);return it==u.fields.end()?0:it->second;};
auto entry=value(Turtle::OBJECT_FIELD_ENTRY),type=value(Turtle::GAMEOBJECT_TYPE_ID);
if(!turtle_presentable_static_game_object(type,value(Turtle::GAMEOBJECT_DISPLAYID)))continue; // Interactions remain separate.
if(!turtle_static_game_object_state(value(Turtle::GAMEOBJECT_STATE)))continue;
if(!entry || entry>0x7FFFFF || map>8191)throw Error("game-object GUID field bound");
auto scale=std::bit_cast<float>(value(Turtle::OBJECT_FIELD_SCALE_X));
if(!std::isfinite(scale) || scale<=0 || scale>100)throw Error("game-object scale bound");
std::array<float,4> rotation;float norm=0;
for(unsigned i=0;i<4;++i) {rotation[i]=std::bit_cast<float>(value(Turtle::GAMEOBJECT_ROTATION+i));if(!std::isfinite(rotation[i]))throw Error("nonfinite game-object rotation");norm+=rotation[i]*rotation[i];}
if(!std::isfinite(norm))throw Error("game-object quaternion bound");
if(norm<0.000001f)rotation={0,0,std::sin(u.movement->position[3]/2),std::cos(u.movement->position[3]/2)};
else for(float& component:rotation)component/=std::sqrt(norm);
int sign=rotation[3]>=0?1:-1;
uint64_t x=uint32_t(int32_t(rotation[0]*2097152)*sign)&0x3FFFFF;
uint64_t y=uint32_t(int32_t(rotation[1]*1048576)*sign)&0x1FFFFF;
uint64_t z=uint32_t(int32_t(rotation[2]*1048576)*sign)&0x1FFFFF;
auto packed_rotation=z|(y<<21)|(x<<42);
auto id=forever_game_object_guid(u.guid,entry,realm,map);
UF::ObjectData object;UF::GameObjectData go;set(object.EntryID,int32_t(entry));set(object.Scale,scale);
// Original70334 empty state-animation sentinel. The extracted writer uses
// this raw field instead of the viewer-dependent GetEmptyAnimStateID().
// Zero is a real animation override and suppresses native door handles.
set(go.SpawnTrackingStateAnimID,uint32_t(1880));
set(go.DisplayID,int32_t(value(Turtle::GAMEOBJECT_DISPLAYID)));set(go.FactionTemplate,int32_t(value(Turtle::GAMEOBJECT_FACTION)));
set(go.Flags,turtle_static_game_object_flags(value(Turtle::GAMEOBJECT_FLAGS)));
set(go.State,int8_t(value(Turtle::GAMEOBJECT_STATE)));set(go.TypeID,int8_t(type));set(go.ArtKit,value(Turtle::GAMEOBJECT_ARTKIT));set(go.Level,int32_t(value(Turtle::GAMEOBJECT_LEVEL)));set(go.PercentHealth,uint8_t(100));
auto& parent=const_cast<QuaternionData&>(*go.ParentRotation);parent.x=parent.y=parent.z=0;parent.w=1;
ByteBuffer values;auto visibility=UF::UpdateFieldFlag::None;
values<<uint8(visibility)<<uint8(3)<<uint8(206)<<uint8(255)<<uint8(1);
object.WriteCreate(visibility,values,nullptr,nullptr);go.WriteCreate(visibility,values,nullptr,nullptr);values.FlushBits();
Bytes block{2};append(block,pack_guid(id));le(block,8,1);append(block,Bytes{0x81,0x08,0});le(block,0,4);
for(unsigned i=0;i<4;++i){auto value=i==3?forever_facing(u.movement->position[i]):u.movement->position[i];
if(!std::isfinite(value))throw Error("nonfinite game-object position");le(block,std::bit_cast<uint32_t>(value),4);}
le(block,packed_rotation,8);
le(block,values.size(),4);append(block,std::span(values.data(),values.size()));append(blocks,block);++count;
}
Bytes packet;le(packet,map,2);le(packet,count,4);le(packet,0x80,1);le(packet,blocks.size(),4);append(packet,blocks);
return packet;
}
if(npcs) {
Bytes blocks;uint32_t count=0;
for(const auto& u:updates)if(u.type==3 && (u.kind==2 || u.kind==3) && u.movement) {
auto value=[&](unsigned index){auto it=u.fields.find(index);return it==u.fields.end()?0:it->second;};
auto entry=value(Turtle::OBJECT_FIELD_ENTRY);
// General population uses live replies from this authenticated Turtle session.
if(typed_npcs ? (!creature_types.contains(entry) || !creature_guids.contains(u.guid)) : (entry!=6 && entry!=38 && entry!=197))continue;
if(!entry || entry>0x7FFFFF || map>8191)throw Error("NPC GUID field bound");
// A genuine Turtle template change preserves ObjectGuid.
// GUID identity and the live ObjectData.EntryID are distinct.
if(companions){
const bool accepted=owned_stat_pet
? ((cls==3 && creature_types.at(entry)==1) || (cls==9 && creature_types.at(entry)==3)) && source_owned_stat_pet(u.fields,guid,u.guid)
: source_passive_companion(u.fields);
if(!pets.contains(u.guid) || !accepted)throw Error("unqualified Source pet create");
const auto& binding=pets.at(u.guid);Reader owner(binding.owner);
if(binding.original_entry!=entry || owner.le(8)!=source_pet_guid(u.fields,SourcePetOwner))throw Error("companion Source ownership differs");
}
auto translated_id=companions?forever_pet_guid(u.guid,pets.at(u.guid).original_entry,realm,map):
forever_creature_guid(u.guid,uint32_t(u.guid>>24)&0xffffff,realm,map);
Reader raw_id{std::span<const uint8_t>(translated_id)};auto low=raw_id.le(8),high=raw_id.le(8);
ObjectGuid id;id.SetRawValue(high,low);
UF::ObjectData object;UF::UnitData unit;
if(companions){
auto assign=[](const Guid128& raw){Reader id(raw);auto low=id.le(8),high=id.le(8);ObjectGuid out;out.SetRawValue(high,low);return out;};
set(unit.SummonedBy,assign(pets.at(u.guid).owner));set(unit.CreatedBy,assign(pets.at(u.guid).creator));
set(unit.PetNumber,value(SourcePetNumber));set(unit.PetNameTimestamp,value(SourcePetNameTimestamp));set(unit.CreatedBySpell,int32_t(value(SourcePetCreatedBySpell)));
}
set(object.EntryID,int32_t(entry));set(object.Scale,std::bit_cast<float>(value(Turtle::OBJECT_FIELD_SCALE_X)));
set(object.DynamicFlags,forever_unit_dynamic_flags(value(Turtle::UNIT_DYNAMIC_FLAGS)));
set(unit.DisplayID,int32_t(value(Turtle::UNIT_FIELD_DISPLAYID)));set(unit.NativeDisplayID,int32_t(value(Turtle::UNIT_FIELD_NATIVEDISPLAYID)));
if(value(Turtle::UNIT_FIELD_MOUNTDISPLAYID)>0x7fffffff)throw Error("invalid source mount display");
set(unit.MountDisplayID,int32_t(value(Turtle::UNIT_FIELD_MOUNTDISPLAYID)));
set(unit.Health,int64_t(value(Turtle::UNIT_FIELD_HEALTH)));set(unit.MaxHealth,int64_t(value(Turtle::UNIT_FIELD_MAXHEALTH)));
set(unit.Level,int32_t(value(Turtle::UNIT_FIELD_LEVEL)));set(unit.EffectiveLevel,int32_t(value(Turtle::UNIT_FIELD_LEVEL)));
set(unit.FactionTemplate,int32_t(value(Turtle::UNIT_FIELD_FACTIONTEMPLATE)));
set(unit.NpcFlags,forever_npc_flags(value(Turtle::UNIT_NPC_FLAGS)));
set(unit.EmoteState,int32_t(emote_profile::animation(value(Turtle::UNIT_NPC_EMOTESTATE))));
set(unit.Flags,forever_unit_flags(value(Turtle::UNIT_FIELD_FLAGS)));
set(unit.PvpFlags,uint8_t((value(Turtle::UNIT_FIELD_FLAGS)&0x1000)?1:0));
set(unit.StandState,uint8_t(value(Turtle::UNIT_FIELD_BYTES_1)));set(unit.ShapeshiftForm,uint8_t(value(Turtle::UNIT_FIELD_BYTES_1)>>16));
set(unit.VisFlags,forever_unit_vis_flags(value(Turtle::UNIT_FIELD_BYTES_1)));
unit_combat_fields(unit,u);
auto traits=value(Turtle::UNIT_FIELD_BYTES_0);set(unit.Race,uint8_t(traits));set(unit.ClassId,uint8_t(traits>>8));set(unit.Sex,uint8_t(traits>>16));set(unit.DisplayPower,uint8_t(traits>>24));
if(auto power=uint8_t(traits>>24);power<4){const_cast<int32&>(unit.Power[0])=value(Turtle::UNIT_FIELD_POWER1+power);const_cast<int32&>(unit.MaxPower[0])=value(Turtle::UNIT_FIELD_MAXPOWER1+power);}
set(unit.BoundingRadius,std::bit_cast<float>(value(Turtle::UNIT_FIELD_BOUNDINGRADIUS)));set(unit.CombatReach,std::bit_cast<float>(value(Turtle::UNIT_FIELD_COMBATREACH)));
set(unit.CreatureType,typed_npcs?creature_types.at(entry):uint8_t(7));set(unit.DisplayScale,1.0f);set(unit.NativeXDisplayScale,1.0f);set(unit.ModTimeRate,1.0f);
// Creature::InitEntry establishes neutral rates and no active empower stage.
set(unit.ModCastingSpeed,1.0f);set(unit.ModSpellHaste,1.0f);set(unit.ModHaste,1.0f);
set(unit.ModRangedHaste,1.0f);set(unit.ModHasteRegen,1.0f);set(unit.SpellEmpowerStage,int8_t(-1));
ByteBuffer values;auto visibility=UF::UpdateFieldFlag::None;
values<<uint8(visibility)<<uint8(3)<<uint8(204)<<uint8(255)<<uint8(1);
object.WriteCreate(visibility,values,nullptr,nullptr);unit.WriteCreate(visibility,values,nullptr,nullptr);values.FlushBits();
bool combat_victim=combat_victims.contains(u.guid);
// Original BaseEntity::BuildMovementUpdate's ninth bit and
// packed victim follow MovementUpdate, before values size.
Bytes block{2};append(block,pack_guid(id.GetRawValue()));le(block,5,1);append(block,Bytes{0x84,uint8_t(combat_victim?0x80:0),0});le(block,0,4);
// The shared Forever movement writer normalizes Source facing.
auto movement=forever_ground_movement(GroundMovement{guid,u.movement->flags&movement_modes::SourceMask,u.movement->time,u.movement->position},realm);
Reader mover(movement);unpack_guid(mover,16);
append(block,pack_guid(id.GetRawValue()));append(block,mover.take(mover.left()));
for(float speed:{u.speeds[0],u.speeds[1],u.speeds[2],u.speeds[3],u.speeds[4],7.0f,4.5f,u.speeds[5],3.141593f})le(block,std::bit_cast<uint32_t>(speed),4);
le(block,0,4);le(block,std::bit_cast<uint32_t>(1.0f),4);for(unsigned i=0;i<17;++i)le(block,0,4);le(block,0,1);
if(combat_victim)append(block,pack_guid(combat_victims.at(u.guid)));
le(block,values.size(),4);append(block,std::span(values.data(),values.size()));append(blocks,block);++count;
}
Bytes packet;le(packet,map,2);le(packet,count,4);le(packet,0x80,1);le(packet,blocks.size(),4);append(packet,blocks);
return packet;
}
auto it=std::find_if(updates.begin(),updates.end(),[guid](auto& u){return u.guid==guid && u.type==4 && (u.update_flags&1);});
if(it==updates.end() || !it->movement) throw Error("no authoritative self player create");
auto& u=*it; auto value=[&](uint16_t index) { auto p=u.fields.find(index);return p==u.fields.end()?0:p->second; };
auto floating=[&](uint16_t index) { return std::bit_cast<float>(value(index)); };
ObjectGuid owner_guid;owner_guid.SetRawValue((uint64_t(2)<<58)|(uint64_t(realm)<<42),guid);
auto item_guid=[](uint64_t legacy) {ObjectGuid result;if(legacy)result.SetRawValue(uint64_t(3)<<58,legacy&0xFFFFFFFF);return result;};
auto field64=[&](unsigned index) {return uint64_t(value(index))|(uint64_t(value(index+1))<<32);};
Bytes item_blocks;uint32_t item_count=0;
auto append_item=[&](ObjectGuid id,uint32_t entry,uint32_t stack,uint32_t durability,uint32_t max_durability,const LegacyObjectUpdate* legacy,const UF::ContainerData* container) {
UF::ObjectData object_data;UF::ItemData item_data;set(object_data.EntryID,int32_t(entry));set(object_data.Scale,1.0f);
set(item_data.Owner,owner_guid);set(item_data.ContainedIn,owner_guid);set(item_data.StackCount,stack);
set(item_data.Durability,durability);set(item_data.MaxDurability,max_durability);
const_cast<WorldPackets::Item::ItemBonusKey&>(*item_data.ItemBonusKey).ItemID=int32_t(entry);
if(legacy) {
auto field=[&](unsigned index){auto p=legacy->fields.find(index);return p==legacy->fields.end()?0:p->second;};
set(item_data.Expiration,field(Turtle::ITEM_FIELD_DURATION));
set(item_data.DynamicFlags,forever_item_dynamic_flags(field(Turtle::ITEM_FIELD_FLAGS)));
for(unsigned i=0;i<5;++i)const_cast<int32&>(item_data.SpellCharges[i])=int32_t(field(Turtle::ITEM_FIELD_SPELL_CHARGES+i));
}
ByteBuffer values;auto visibility=UF::UpdateFieldFlag::Owner;
values<<uint8(visibility)<<uint8(3)<<uint8(200);
if(container)values<<uint8(201);
values<<uint8(255)<<uint8(1);
object_data.WriteCreate(visibility,values,nullptr,nullptr);item_data.WriteCreate(visibility,values,nullptr,nullptr);
if(container)container->WriteCreate(visibility,values,nullptr,nullptr);
Bytes block{2};append(block,pack_guid(id.GetRawValue()));le(block,container?2:1,1);le(block,0,3);le(block,0,4);
le(block,values.size(),4);append(block,std::span(values.data(),values.size()));append(item_blocks,block);++item_count;
};
for(const auto& item:updates)if(item.type==1 && (item.kind==2 || item.kind==3)) {
auto field=[&](unsigned index){auto p=item.fields.find(index);return p==item.fields.end()?0:p->second;};
if((uint64_t(field(Turtle::ITEM_FIELD_OWNER))|(uint64_t(field(Turtle::ITEM_FIELD_OWNER+1))<<32))!=guid)throw Error("inventory item owner mismatch");
append_item(item_guid(item.guid),field(Turtle::OBJECT_FIELD_ENTRY),field(Turtle::ITEM_FIELD_STACK_COUNT),field(Turtle::ITEM_FIELD_DURABILITY),field(Turtle::ITEM_FIELD_MAXDURABILITY),&item,nullptr);
}
UF::ObjectData object; UF::UnitData unit; UF::PlayerData player; UF::ActivePlayerData active;
if (initial_stable) {
if (!guid || guid > UINT32_MAX || !realm || realm > 8191 || map > UINT16_MAX)
throw Error("pet stable create identity");
set_stable_fields(active, &*initial_stable, realm, map);
}
if (self_party_type || initial_stable)
set_home_party_type(player, home_party_type);
apply_quest_log_projection(player,source_quest_log_create(u.fields));
explored_zone_fields(active,u.fields,true);
set(object.Scale,1.0f);
set(object.DynamicFlags,forever_unit_dynamic_flags(value(Turtle::UNIT_DYNAMIC_FLAGS)));
auto player_body_traits=value(Turtle::UNIT_FIELD_BYTES_0);
player_customizations(player, player_body_traits, value(Turtle::PLAYER_BYTES), value(Turtle::PLAYER_BYTES_2));
auto player_body_displays=forever_player_default_displays(player_body_traits&255,(player_body_traits>>16)&255,
value(Turtle::UNIT_FIELD_DISPLAYID),value(Turtle::UNIT_FIELD_NATIVEDISPLAYID));
set(unit.DisplayID,int32_t(player_body_displays.display)); set(unit.NativeDisplayID,int32_t(player_body_displays.native_display));
if(value(Turtle::UNIT_FIELD_MOUNTDISPLAYID)>0x7fffffff)throw Error("invalid source mount display");
set(unit.MountDisplayID,int32_t(value(Turtle::UNIT_FIELD_MOUNTDISPLAYID)));
set(unit.Race,uint8_t(race));set(unit.ClassId,uint8_t(cls));set(unit.PlayerClassId,uint8_t(cls));set(unit.Sex,uint8_t(sex));
set(unit.CreatureType,uint8_t(7));set(unit.DisplayPower,uint8_t(value(Turtle::UNIT_FIELD_BYTES_0)>>24));
set(unit.Health,int64_t(value(Turtle::UNIT_FIELD_HEALTH)));set(unit.MaxHealth,int64_t(value(Turtle::UNIT_FIELD_MAXHEALTH)));
set(unit.Level,int32_t(value(Turtle::UNIT_FIELD_LEVEL)));set(unit.EffectiveLevel,int32_t(value(Turtle::UNIT_FIELD_LEVEL)));
set(unit.FactionTemplate,int32_t(value(Turtle::UNIT_FIELD_FACTIONTEMPLATE)));
set(unit.EmoteState,int32_t(emote_profile::animation(value(Turtle::UNIT_NPC_EMOTESTATE))));
{auto raw=forever_guild_guid(value(Turtle::PLAYER_GUILDID),realm);Reader id(raw);auto low=id.le(8),high=id.le(8);ObjectGuid guild;guild.SetRawValue(high,low);set(unit.GuildGUID,guild);}
set(player.GuildClubMemberID,guild_club_member_id(guid,realm));
if(value(Turtle::PLAYER_GUILDRANK)>=10)throw Error("source self guild rank bound");
set(player.GuildRankID,value(Turtle::PLAYER_GUILDRANK));
set(player.PlayerFlags,forever_player_flags(value(Turtle::PLAYER_FLAGS)));
set(player.PvpTitle,uint8_t(value(Turtle::PLAYER_BYTES_3)>>24)); // current PvP rank (0 when Source ignores titles)
set(unit.Flags,forever_unit_flags(value(Turtle::UNIT_FIELD_FLAGS)));
set(unit.PvpFlags,uint8_t((value(Turtle::UNIT_FIELD_FLAGS)&0x1000)?1:0));
set(unit.StandState,uint8_t(value(Turtle::UNIT_FIELD_BYTES_1)));set(unit.ShapeshiftForm,uint8_t(value(Turtle::UNIT_FIELD_BYTES_1)>>16));
set(unit.VisFlags,forever_unit_vis_flags(value(Turtle::UNIT_FIELD_BYTES_1),value(Turtle::PLAYER_FIELD_BYTES2)));
set(active.AuraVision,forever_aura_vision(value(Turtle::PLAYER_FIELD_BYTES2)));
set(active.LocalFlags,forever_player_local_flags(value(Turtle::PLAYER_FIELD_BYTES)));
set(unit.SheatheState,uint8_t(value(Turtle::UNIT_FIELD_BYTES_2)));
unit_combat_fields(unit,u);
set(unit.BoundingRadius,floating(Turtle::UNIT_FIELD_BOUNDINGRADIUS));set(unit.CombatReach,floating(Turtle::UNIT_FIELD_COMBATREACH));
const auto cast_speed=u.fields.find(Turtle::UNIT_MOD_CAST_SPEED);
const float cast_factor=cast_speed==u.fields.end() ? 1.0f : player_cast_factor(cast_speed->second);
set(unit.DisplayScale,1.0f);set(unit.NativeXDisplayScale,1.0f);set(unit.ModCastingSpeed,cast_factor);set(unit.ModCastingSpeedNeg,1.0f);
set(unit.ModSpellHaste,cast_factor>0.0f ? cast_factor : 1.0f);set(unit.ModHaste,1.0f);set(unit.ModRangedHaste,1.0f);set(unit.ModHasteRegen,1.0f);set(unit.ModTimeRate,1.0f);
set(unit.MaxHealthModifier,1.0f);set(unit.ManaCostMultiplier,1.0f);set(unit.NameplateDistanceMod,1.0f);set(unit.CurrentAreaID,zone);
for(unsigned power=0;power<4;++power)if(auto slot=ForeverClassPowerSlots[cls][power];slot>=0){
const_cast<int32&>(unit.Power[slot])=value(Turtle::UNIT_FIELD_POWER1+power);
const_cast<int32&>(unit.MaxPower[slot])=value(Turtle::UNIT_FIELD_MAXPOWER1+power);
}
// Combo points (vanilla max 5) from PLAYER_FIELD_BYTES byte 1; native ComboPoints power slot.
if(auto slot=ForeverClassComboSlot[cls];slot>=0){
const_cast<int32&>(unit.Power[slot])=int32_t((value(Turtle::PLAYER_FIELD_BYTES)>>8)&255);
const_cast<int32&>(unit.MaxPower[slot])=5;
}
ObjectGuid wow_guid,bnet_guid;
if(account)wow_guid.SetRawValue(uint64(29)<<58,account);
if(bnet)bnet_guid.SetRawValue(uint64(30)<<58,bnet);
set(player.WowAccount,wow_guid);set(player.BnetAccount,bnet_guid);
set(active.NumBackpackSlots,uint8_t(16));set(active.MaxLevel,int32_t(60));set(active.WatchedFactionIndex,int32_t(-1));
set(active.Coinage,uint64_t(value(Turtle::PLAYER_FIELD_COINAGE)));set(active.ModHealingPercent,1.0f);
// Honor (Tortoise HonorMgr::Update): today/yesterday HK are the low u16 of the kill words (high u16 =
// dishonorable, no native slot); lifetime HK; highest rank = PLAYER_FIELD_BYTES byte 3 (vanilla rank index).
set(active.TodayHonorableKills,uint16_t(value(Turtle::PLAYER_FIELD_SESSION_KILLS)));
set(active.YesterdayHonorableKills,uint16_t(value(Turtle::PLAYER_FIELD_YESTERDAY_KILLS)));
set(active.LifetimeHonorableKills,uint32_t(value(Turtle::PLAYER_FIELD_LIFETIME_HONORABLE_KILLS)));
set(active.LifetimeMaxRank,uint8_t(value(Turtle::PLAYER_FIELD_BYTES)>>24));
// Original InitStatsForLevel defaults these additional native factors to
// one. Tortoise's final weapon ranges/times already enter unit_combat_fields;
// keep these destination-only factors neutral alongside those values.
set(active.ModPeriodicHealingDonePercent,1.0f);set(active.ModSpellPowerPercent,1.0f);
for(unsigned i=0;i<3;++i){const_cast<float&>(active.WeaponDmgMultipliers[i])=1.0f;const_cast<float&>(active.WeaponAtkSpeedMultipliers[i])=1.0f;}
set(active.BlockPercentage,floating(Turtle::PLAYER_BLOCK_PERCENTAGE));set(active.DodgePercentage,floating(Turtle::PLAYER_DODGE_PERCENTAGE));
set(active.ParryPercentage,floating(Turtle::PLAYER_PARRY_PERCENTAGE));set(active.CritPercentage,floating(Turtle::PLAYER_CRIT_PERCENTAGE));
set(active.RangedCritPercentage,floating(Turtle::PLAYER_RANGED_CRIT_PERCENTAGE));
for (auto const& [index, word] : u.fields) player_damage_modifier(active, index, word);
for(unsigned i=0;i<7;++i) const_cast<float&>(active.ModHealingDonePercent[i])=1.0f;
set(player.Name,name);set(player.NativeSex,uint8_t(sex));set(player.VirtualPlayerRealm,address);
auto& skills=const_cast<UF::SkillInfo&>(*active.Skill);unsigned skill_count=0;
for(unsigned slot=0;slot<128;++slot) {
auto id_step=value(Turtle::PLAYER_SKILL_INFO_1_1+3*slot);
auto rank_max=value(Turtle::PLAYER_SKILL_INFO_1_1+3*slot+1);
auto bonuses=value(Turtle::PLAYER_SKILL_INFO_1_1+3*slot+2);
if(!(id_step&0xFFFF))continue;
const_cast<uint16&>(skills.SkillLineID[slot])=uint16(id_step);
const_cast<uint16&>(skills.SkillStep[slot])=profession_skill_step(id_step,rank_max);
const_cast<uint16&>(skills.SkillRank[slot])=uint16(rank_max);
const_cast<uint16&>(skills.SkillStartingRank[slot])=1;
const_cast<uint16&>(skills.SkillMaxRank[slot])=uint16(rank_max>>16);
const_cast<int16&>(skills.SkillTempBonus[slot])=int16(bonuses);
const_cast<uint16&>(skills.SkillPermBonus[slot])=uint16(bonuses>>16);++skill_count;
}
// Original Player::SetSkill/_LoadSkills also initializes these separate
// slots. A populated SkillInfo alone does not own a profession context.
auto professions=primary_profession_lines(value,Turtle::PLAYER_SKILL_INFO_1_1);
for(unsigned i=0;i<professions.size();++i)const_cast<int32&>(active.ProfessionSkillLine[i])=professions[i];
profession_child_views(value,Turtle::PLAYER_SKILL_INFO_1_1,[&](const ProfessionChildView& v){
const_cast<uint16&>(skills.SkillLineID[v.slot])=v.id;
const_cast<uint16&>(skills.SkillStep[v.slot])=v.step;
const_cast<uint16&>(skills.SkillRank[v.slot])=v.rank;
const_cast<uint16&>(skills.SkillStartingRank[v.slot])=1;
const_cast<uint16&>(skills.SkillMaxRank[v.slot])=v.max_rank;
const_cast<int16&>(skills.SkillTempBonus[v.slot])=std::bit_cast<int16_t>(v.temp_bonus);
const_cast<uint16&>(skills.SkillPermBonus[v.slot])=v.perm_bonus;
});
set(active.XP,int32_t(value(Turtle::PLAYER_XP)));set(active.NextLevelXP,int32_t(value(Turtle::PLAYER_NEXT_LEVEL_XP)));
auto& xp_rest=const_cast<UF::RestInfo&>(active.RestInfo[0]);
set(xp_rest.Threshold,value(Turtle::PLAYER_REST_STATE_EXPERIENCE));
// A full CREATE can omit the word or carry an unspecified zero
// rest byte. Source's constructor initializes normal(2).
const auto source_rest=u.fields.contains(Turtle::PLAYER_BYTES_2)
? source_xp_rest_state(value(Turtle::PLAYER_BYTES_2)) : uint8_t(0);
set(xp_rest.StateID,source_rest ? source_rest : uint8_t(2));
for(unsigned slot=0;slot<23;++slot) {
auto legacy=field64(Turtle::PLAYER_FIELD_INV_SLOT_HEAD+2*slot);
unsigned modern=slot<19?slot:30+(slot-19);
const_cast<ObjectGuid&>(active.InvSlots[modern])=item_guid(legacy);
if(slot<19 && legacy) {
auto item=std::find_if(updates.begin(),updates.end(),[legacy](auto& item){return item.guid==legacy && item.type==1;});
if(item!=updates.end()) {auto f=item->fields.find(Turtle::OBJECT_FIELD_ENTRY);
if(f!=item->fields.end()){
// Source visible entry is already post-transmog. If it
// is nonzero but not yet resolved, do not substitute a
// base-item display and accidentally hide normal boots.
const auto visible_entry=value(Turtle::PLAYER_VISIBLE_ITEM_1_0+12*slot);
const auto displayed=forever_visible_item_id(value(Turtle::PLAYER_FLAGS),slot,f->second,
uint8_t(race),uint8_t(sex),race_slot_hide_profile::source_display(visible_entry?visible_entry:f->second));
set(const_cast<UF::VisibleItem&>(player.VisibleItems[slot]).ItemID,int32_t(displayed));
set(const_cast<UF::VisibleItem&>(player.VisibleItems[slot]).ItemModifiedAppearanceID,item_render_profile::modified_appearance(displayed));
const auto index=Turtle::PLAYER_VISIBLE_ITEM_1_0+12*slot;
const auto visual=displayed?item_enchantment_visual_profile::resolve(value(index+1),value(index+2)):0;
set(const_cast<UF::VisibleItem&>(player.VisibleItems[slot]).ItemVisual,visual);
if(slot>=15 && slot<=17){auto& visible=const_cast<UF::VisibleItem&>(unit.VirtualItems[slot-15]);set(visible.ItemID,int32_t(f->second));set(visible.ItemVisual,visual);}
}}
}
}
for(unsigned slot=0;slot<16;++slot)const_cast<ObjectGuid&>(active.InvSlots[35+slot])=item_guid(field64(Turtle::PLAYER_FIELD_PACK_SLOT_1+2*slot));
gateway::keyring_wire::View<ObjectGuid> keyring;
for(unsigned i=0;i<gateway::keyring_slots::Count;++i)
keyring.guids[i]=item_guid(field64(Turtle::PLAYER_FIELD_VENDORBUYBACK_SLOT_1+24+2*i));
// Vanilla's fixed bank becomes a virtual modern bank-tab container, never a backend item.
ObjectGuid bank;bank.SetRawValue(uint64_t(3)<<58,(uint64_t(1)<<63)|(guid<<8)|1);
UF::ContainerData bank_data;set(bank_data.NumSlots,uint32_t(24));
for(unsigned slot=0;slot<24;++slot)const_cast<ObjectGuid&>(bank_data.Slots[slot])=item_guid(field64(Turtle::PLAYER_FIELD_BANK_SLOT_1+2*slot));
append_item(bank,242709,1,0,0,nullptr,&bank_data);
const_cast<ObjectGuid&>(active.InvSlots[63])=bank;set(active.NumCharacterBankTabs,uint8_t(1));
auto purchased_bank_bags=(value(Turtle::PLAYER_BYTES_2)>>16)&255;
set(active.PvpMedals,value(Turtle::PLAYER_AMMO_ID));
if(purchased_bank_bags>6)throw Error("unsupported source purchased bank bag count");
set(active.NumBankSlots,uint8_t(purchased_bank_bags));
// Original Camelot BankFrame enumerates purchased tab settings, not
// the legacy bag count. Tab1 is the fixed bank; each bag adds a tab.
set(active.NumCharacterBankTabs,uint8_t(1+purchased_bank_bags));
for(unsigned i=0;i<6;++i)const_cast<ObjectGuid&>(active.InvSlots[64+i])=item_guid(field64(Turtle::PLAYER_FIELD_BANKBAG_SLOT_1+2*i));
UF::MutableFieldReference<UF::ActivePlayerData,true> active_ref{active};
set(active.CharacterPoints,int32_t(value(Turtle::PLAYER_CHARACTER_POINTS1)));
if(talent_experiment && (self_talents || (value(Turtle::UNIT_FIELD_LEVEL)<10 && !value(Turtle::PLAYER_CHARACTER_POINTS1)))){
// Bootstrap only a zero-talent, pre-talent-level backend character.
// Learned talent/rank mapping is a separate, explicitly unsupported step.
auto spec=ForeverClassDefaultSpec[cls];if(!spec)throw Error("no audited class specialization");
auto config_id=int32_t(guid&0x7FFFFFFF);if(!config_id)throw Error("empty virtual trait configuration ID");
set(player.CurrentSpecID,uint32_t(spec));trait_config(active,spec,uint32_t(config_id),forever_talent_ranks(known_spells));
}
if(auto self_res=value(Turtle::PLAYER_SELF_RES_SPELL)){
if(self_res>0x7fffffff)throw Error("self-res spell bound");
auto self_res_setter=active_ref.ModifyValue(&UF::ActivePlayerData::SelfResSpells);
UF::AddDynamicUpdateFieldValue(self_res_setter)=int32_t(self_res);
}
auto bank_setter=active_ref.ModifyValue(&UF::ActivePlayerData::CharacterBankTabSettings);
for(unsigned i=0;i<=purchased_bank_bags;++i){
auto tab=UF::AddDynamicUpdateFieldValue(bank_setter);
auto tab_name=tab.ModifyValue(&UF::BankTabSettings::Name);
tab_name.SetValue(i?std::string("Bank bag ")+std::to_string(i):std::string("Turtle bank"));
}
UF::UpdateFieldFlag visibility=UF::UpdateFieldFlag::Owner|UF::UpdateFieldFlag::PartyMember;
ByteBuffer values;values<<uint8(visibility)<<uint8(3)<<uint8(204)<<uint8(205)<<uint8(255)<<uint8(1);
object.WriteCreate(visibility,values,nullptr,nullptr);unit.WriteCreate(visibility,values,nullptr,nullptr);
player.WriteCreate(visibility,values,nullptr,nullptr);
{gateway::keyring_wire::Scope<ObjectGuid> keyring_scope(keyring);active.WriteCreate(visibility,values,nullptr,nullptr);}
values.FlushBits();
auto identity=forever_player_guid(guid,realm); Bytes block{2};append(block,pack_guid(identity));le(block,7,1);
// ThisIsYou, MovementUpdate, ActivePlayer, all other presence flags clear.
append(block,Bytes{0x8C,0,0x80});le(block,0,4);
auto move=*u.movement;move.flags&=movement_modes::SourceMask;move.time=0; // Preserve real modes, not historical directional input.
append(block,forever_ground_movement(move,realm));
for(float speed:{u.speeds[0],u.speeds[1],u.speeds[2],u.speeds[3],u.speeds[4],7.0f,4.5f,u.speeds[5],3.141593f}) le(block,std::bit_cast<uint32_t>(speed),4);
le(block,0,4);le(block,std::bit_cast<uint32_t>(1.0f),4);
for(unsigned i=0;i<17;++i) le(block,0,4);le(block,0,1); // advanced flying scalars, HasSpline
le(block,0,1); // ActivePlayer scene/rune presence
le(block,values.size(),4);append(block,std::span(values.data(),values.size()));
Bytes packet;le(packet,map,2);le(packet,item_count+1,4);le(packet,0x80,1);le(packet,item_blocks.size()+block.size(),4);append(packet,item_blocks);append(packet,block);
return packet;
}