diff --git a/src/Offsets.h b/src/Offsets.h index c41236d9..e7648e8e 100644 --- a/src/Offsets.h +++ b/src/Offsets.h @@ -4160,6 +4160,74 @@ enum Offsets { // The Model frame's per-paint update — `__thiscall(frame)`, slot 38. FUN_SIMPLEMODEL_UPDATE_MODEL = 0x0076D1A0, + // ---- Subclassing CSimpleModel (Model::Scene, the ModelScene frame) ------ + // The "Model" factory (0x006EECF0) is SMemAlloc(MODEL_FRAME_SIZE) then + // CSimpleModel::CSimpleModel — `__thiscall(frame, parent)`, `ret 4` — which + // builds the light with M2LightInitialize, zeroes the model fields and + // stores VTBL_SIMPLEMODEL at +0 and VTBL_SIMPLEMODEL_LAYOUT at + // OFF_FRAME_LAYOUT_SUBOBJECT (benilla-re ui/modelview "Model frame + // fields"). Its vtables are 40 and 11 slots (dumped from the exe: slots + // 40.. of the main one are float constants). Slot 0, the deleting + // destructor (0x0076CA20), runs FUN_SIMPLEMODEL_DESTROY, which releases the + // camera (+0x31C), the model (+0x318) and the scene (+0x314). Model's own + // overrides of CSimpleFrame's slots: +0x08 its method hash then Frame's, + // +0x0C its two script names, +0x10/+0x18/+0x1C its type, +0x28 alpha to + // the model, +0x38 the scene clock (CSimpleFrame's update, then + // M2SceneAdvance by the truncated ms; a null +0x318 skips only the model + // half), +0x44 EmitLayer (Frame's, then the paint callback on ARTWORK when + // +0x318 is set), +0x90..+0x9C SetModel / UpdateModel / model ready. + MODEL_FRAME_SIZE = 0x3DC, + FUN_SIMPLEMODEL_CONSTRUCTOR = 0x0076C8E0, + VTBL_SIMPLEMODEL = 0x0081C608, + VTBL_SIMPLEMODEL_SLOTS = 40, + VTBL_SIMPLEMODEL_LAYOUT = 0x0081C5D8, + VTBL_SIMPLEMODEL_LAYOUT_SLOTS = 11, + // The frame's light (an M2Light, 0x6C bytes) and, inside it, the ambient + // and diffuse colours (3 floats each, +0x354 / +0x360 of the frame). + // PlayerModel's constructor (0x00505680) writes both directly and sets the + // rest through M2LightSetType `__thiscall(light, int type)` (0 directional, + // 1 point), M2LightSetDirection `__thiscall(light, const float v[3])` + // (normalized) and M2LightSetEnabled `__thiscall(light, int)`. The light + // callback (FUN_SIMPLEMODELFFX_LIGHT_FOG_CB) adds it to a model's lighting + // only while it is enabled. + OFF_SIMPLEMODEL_LIGHT = 0x324, + OFF_M2LIGHT_AMBIENT = 0x30, + OFF_M2LIGHT_DIFFUSE = 0x3C, + FUN_M2LIGHT_SET_TYPE = 0x0071B620, + FUN_M2LIGHT_SET_DIRECTION = 0x0071B6A0, + FUN_M2LIGHT_SET_ENABLED = 0x0071B780, + // SimpleModelInstallCamera — `__thiscall(frame, camera)`, `ret 4`: takes a + // handle reference, releases the old camera, stores +0x31C and sets the + // pending camera index (+0x320) to -1. CameraCreate — `void *__cdecl()`: + // a new camera handle the caller owns one reference on (release with + // FUN_HANDLE_RELEASE); the pane fallback (0x00505890) makes, installs and + // releases one this way. + FUN_SIMPLEMODEL_INSTALL_CAMERA = 0x0076CE80, + FUN_CAMERA_CREATE = 0x007AC930, + // CM2Model::SetBaseTransformTRS — `__thiscall(model, const float pos[3], + // float angle, const float axis[3], const float scale[3])`, `ret 0x10`: the + // placement matrix at OFF_M2MODEL_BASE_MATRIX = identity, then + // TranslateMatrix, RotateMatrix(angle, axis, 1), ScaleMatrixRows. Each of + // the three pre-multiplies (row vectors: a point is scaled, then rotated, + // then translated). TranslateMatrix — `__thiscall(m, const float t[3])`, + // `ret 4`: row 3 += t·rows 0..2. RotateMatrix — `__thiscall(m, float + // angle, const float axis[3], int)`, `ret 0xC`. The animate pass places + // every unattached instance with this matrix (models/scene "Animate pass"). + FUN_M2MODEL_SET_BASE_TRS = 0x00710650, + FUN_MATRIX_TRANSLATE = 0x007BDC40, + FUN_MATRIX_ROTATE = 0x007BDD60, + OFF_M2MODEL_BASE_MATRIX = 0xBC, + // CM2Model::GetBoundingBox — `__thiscall(model, float out[6])`: the + // model's bounds {min xyz, max xyz} (MD20 +0xB4); waits for the file when + // not loaded. GetSequenceInfo — `__thiscall(model, animID, variation, + // record[0x3C])`, `ret 0xC`: the sequence's flags, length, speed, bounds + // (+0x0C, the same six floats) and radius; zeroes them for an id the model + // has no sequence for (benilla-re models/model "Sequence info"). + FUN_M2MODEL_GET_BOUNDING_BOX = 0x00713640, + FUN_M2MODEL_GET_SEQUENCE_INFO = 0x00711A20, + M2_SEQUENCE_INFO_SIZE = 0x3C, + OFF_M2_SEQUENCE_INFO_BOUNDS = 0x0C, + // ---- PlayerModel / DressUpModel / TabardModel (benilla ui/playermodel) -- // CGCharacterModelBase: a Model frame (0x3F8 bytes) that shows a copy of a // unit's model or a creature display. DressUpModel and TabardModel extend @@ -4366,12 +4434,20 @@ enum Offsets { // ---- Camera properties (benilla camera#properties) ------------------- // Get/SetVectorProperty `__fastcall(camera, id, float[3] [, keep])`, // Get/SetScalarProperty `__fastcall(camera, id [, float])`. Ids: 7 eye, - // 8 target, 4 field of view. + // 8 target, 4 field of view, 3 near clip, 2 far clip, 5 roll, 6 yaw + // (CameraCreate's registrations, benilla-re camera "Properties"; all + // angles in radians). The view looks along target − eye from the origin + // with up (sin yaw·sin roll, −cos yaw·sin roll, cos roll); the projection + // takes the field of view, near and far (0x007AC640). FUN_CAMERA_GET_VECTOR = 0x007ABF80, FUN_CAMERA_GET_SCALAR = 0x007AC0B0, FUN_CAMERA_SET_VECTOR = 0x007AC250, FUN_CAMERA_SET_SCALAR = 0x007AC3A0, + CAMERA_PROP_FAR_CLIP = 2, + CAMERA_PROP_NEAR_CLIP = 3, CAMERA_PROP_FOV = 4, + CAMERA_PROP_ROLL = 5, + CAMERA_PROP_YAW = 6, CAMERA_PROP_EYE = 7, CAMERA_PROP_TARGET = 8, diff --git a/src/embed/AddOns/!!!ClassicAPI/Compat.lua b/src/embed/AddOns/!!!ClassicAPI/Compat.lua index edf041fb..37a9e5b7 100644 --- a/src/embed/AddOns/!!!ClassicAPI/Compat.lua +++ b/src/embed/AddOns/!!!ClassicAPI/Compat.lua @@ -24,3 +24,17 @@ end function C_AutoComplete.GetAutoCompleteRealms() return {} end + +-- C_ModelInfo's getters come from the DLL. Retail's active-scene bookkeeping +-- "does nothing in public clients" (its own documentation). +function C_ModelInfo.AddActiveModelScene(modelSceneFrame, modelSceneID) +end + +function C_ModelInfo.AddActiveModelSceneActor(modelSceneFrameActor, modelSceneActorID) +end + +function C_ModelInfo.ClearActiveModelScene(modelSceneFrame) +end + +function C_ModelInfo.ClearActiveModelSceneActor(modelSceneFrameActor) +end diff --git a/src/frame/Cooldown.cpp b/src/frame/Cooldown.cpp index 433f3d8e..d7be6632 100644 --- a/src/frame/Cooldown.cpp +++ b/src/frame/Cooldown.cpp @@ -86,6 +86,7 @@ #include "frame/Region.h" #include "frame/RenderBatch.h" #include "frame/ScriptArgs.h" +#include "frame/Subclass.h" #include "text/NumericFormatter.h" #include "texture/Load.h" #include "time/Clock.h" @@ -185,9 +186,7 @@ struct Rect { }; const Rect &RectOf(void *frame) { return *Game::Ptr(frame, Offsets::OFF_REGION_RECT); } -void *FrameOfLayout(void *layout) { - return static_cast(layout) - Offsets::OFF_FRAME_LAYOUT_SUBOBJECT; -} +using Frame::Subclass::FrameOfLayout; // The alpha the frame draws with — 4.3.4's m_alpha * m_parentAlpha / 255. // 1.12's alpha setter copies one byte down the tree instead of multiplying. @@ -226,24 +225,17 @@ uint32_t ColorByte(double c) { // ---- vtables ---------------------------------------------------------------- -// An MSVC vtable with its RTTI locator in front, as the engine's are laid out. -template -struct VTable { - const void *locator; - const void *slots[N]; -}; - -VTable g_vtable; -VTable g_layoutVtable; +Frame::Subclass::VTable g_vtable; +Frame::Subclass::VTable g_layoutVtable; // CSimpleFrame's own slot, for the base call of an override. template Fn Base(uintptr_t slot) { - return Game::Read(reinterpret_cast(Offsets::VTBL_SIMPLEFRAME), slot); + return Frame::Subclass::Slot(Offsets::VTBL_SIMPLEFRAME, slot); } template Fn LayoutBase(uintptr_t slot) { - return Game::Read(reinterpret_cast(Offsets::VTBL_SIMPLEFRAME_LAYOUT), slot); + return Frame::Subclass::Slot(Offsets::VTBL_SIMPLEFRAME_LAYOUT, slot); } // 1.12's CSimpleFrame::Show / Hide, as Script Show / Hide make them. @@ -643,10 +635,8 @@ using EmitLayer_t = void(__fastcall *)(void *self, void *edx, void *batch, int l using OnFrameSizeChanged_t = void(__fastcall *)(void *layout, void *edx, const float *oldRect); using LoadXML_t = uintptr_t(__fastcall *)(void *layout, void *edx, const void *node, void *status); -using PushMethod_t = int(__fastcall *)(void *L, const char *name, void *hash); - // The class's method hash and type id (Offsets.h "Per-class method hashes"). -uint32_t g_hash[Offsets::METHOD_HASH_SIZE / 4]; +Frame::Subclass::MethodHash g_hash; int g_typeId = 0; uintptr_t TypeIdVar() { return reinterpret_cast(&g_typeId); } @@ -684,7 +674,7 @@ void *__fastcall LayoutDeletingDestructor(void *layout, void *, uint32_t flags) } int __fastcall GetScriptMethod(void *self, void *, void *L, const char *name) { - if (reinterpret_cast(Offsets::FUN_FRAMESCRIPT_PUSH_METHOD)(L, name, g_hash)) + if (g_hash.PushMethod(L, name)) return 1; return Base(Offsets::VTBL_FRAME_GET_SCRIPT_METHOD)(self, nullptr, L, name); } @@ -862,29 +852,22 @@ uintptr_t __fastcall LoadXML(void *layout, void *, const void *node, void *statu } void BuildVTables() { - if (g_vtable.slots[0] != nullptr) + if (g_vtable.Built()) return; - std::memcpy(&g_vtable, reinterpret_cast(Offsets::VTBL_SIMPLEFRAME - 4), - sizeof(g_vtable)); - std::memcpy(&g_layoutVtable, - reinterpret_cast(Offsets::VTBL_SIMPLEFRAME_LAYOUT - 4), - sizeof(g_layoutVtable)); - auto set = [](const void **slots, uintptr_t slot, const void *fn) { slots[slot / 4] = fn; }; - const void **v = g_vtable.slots; - set(v, Offsets::VTBL_FRAME_DELETING_DESTRUCTOR, reinterpret_cast(&DeletingDestructor)); - set(v, Offsets::VTBL_FRAME_GET_SCRIPT_METHOD, reinterpret_cast(&GetScriptMethod)); - set(v, Offsets::VTBL_FRAME_IS_A, reinterpret_cast(&IsA)); - set(v, Offsets::VTBL_FRAME_IS_OBJECT_TYPE, reinterpret_cast(&IsObjectType)); - set(v, Offsets::VTBL_FRAME_GET_OBJECT_TYPE, reinterpret_cast(&GetObjectType)); - set(v, Offsets::VTBL_FRAME_SET_FRAME_ALPHA, reinterpret_cast(&SetFrameAlpha)); - set(v, Offsets::VTBL_FRAME_ON_FRAME_UPDATE, reinterpret_cast(&OnFrameUpdate)); - set(v, Offsets::VTBL_FRAME_EMIT_LAYER, reinterpret_cast(&EmitLayer)); - const void **l = g_layoutVtable.slots; - set(l, Offsets::VTBL_LAYOUT_ON_FRAME_SIZE_CHANGED, - reinterpret_cast(&OnFrameSizeChanged)); - set(l, Offsets::VTBL_LAYOUT_DELETING_DESTRUCTOR, - reinterpret_cast(&LayoutDeletingDestructor)); - set(l, Offsets::VTBL_XML_NODE_LOADER, reinterpret_cast(&LoadXML)); + g_vtable.CopyFrom(Offsets::VTBL_SIMPLEFRAME); + g_layoutVtable.CopyFrom(Offsets::VTBL_SIMPLEFRAME_LAYOUT); + auto fn = [](auto f) { return reinterpret_cast(f); }; + g_vtable.Set(Offsets::VTBL_FRAME_DELETING_DESTRUCTOR, fn(&DeletingDestructor)); + g_vtable.Set(Offsets::VTBL_FRAME_GET_SCRIPT_METHOD, fn(&GetScriptMethod)); + g_vtable.Set(Offsets::VTBL_FRAME_IS_A, fn(&IsA)); + g_vtable.Set(Offsets::VTBL_FRAME_IS_OBJECT_TYPE, fn(&IsObjectType)); + g_vtable.Set(Offsets::VTBL_FRAME_GET_OBJECT_TYPE, fn(&GetObjectType)); + g_vtable.Set(Offsets::VTBL_FRAME_SET_FRAME_ALPHA, fn(&SetFrameAlpha)); + g_vtable.Set(Offsets::VTBL_FRAME_ON_FRAME_UPDATE, fn(&OnFrameUpdate)); + g_vtable.Set(Offsets::VTBL_FRAME_EMIT_LAYER, fn(&EmitLayer)); + g_layoutVtable.Set(Offsets::VTBL_LAYOUT_ON_FRAME_SIZE_CHANGED, fn(&OnFrameSizeChanged)); + g_layoutVtable.Set(Offsets::VTBL_LAYOUT_DELETING_DESTRUCTOR, fn(&LayoutDeletingDestructor)); + g_layoutVtable.Set(Offsets::VTBL_XML_NODE_LOADER, fn(&LoadXML)); } // OFFSET (4.3.4): 0x008C6390 (CGCooldown::Create) — the "Cooldown" factory. @@ -1561,17 +1544,6 @@ const Game::Doc::Method g_methodDocs[] = { {"GetCountdownFormatter", &kGetCountdownFormatter}, }; -// The engine's static initializer for a class hash (Model's 0x0076F5F0). -void InitMethodHash() { - if (g_hash[0] != 0) - return; - g_hash[0] = Offsets::VTBL_METHOD_HASH_ALLOCATOR; - g_hash[1] = 0xC; // node link offset - g_hash[2] = reinterpret_cast(&g_hash[2]); - g_hash[3] = reinterpret_cast(&g_hash[2]) | 1; - g_hash[9] = 0xFFFFFFFF; // no buckets yet -} - void RegisterLuaFunctions() { using RegisterFactory_t = int(__fastcall *)(const char *type, void *(__fastcall *)(void *), int unique); @@ -1580,36 +1552,18 @@ void RegisterLuaFunctions() { // pass runs before FrameXML loads (CGGameUI::Initialize calls // LoadScriptFunctions first), like the engine's own game-UI list // FUN_00495940, where 4.3.4 registers "Cooldown". - InitMethodHash(); g_countdownForCooldowns = CVar::Factory::Register( "countdownForCooldowns", "Whether to use number countdown instead of radial swipe for action button cooldowns or not.", Offsets::CVAR_CATEGORY_GAME, "0"); reinterpret_cast(Offsets::FUN_FRAMEXML_REGISTER_FACTORY)( "Cooldown", &CreateCooldown, 0); - Api::Documentation::NameWidgetSystem(g_hash, "FrameAPICooldown"); - Game::Lua::RegisterFrameMethods(g_hash, g_methods, g_methodDocs); + Api::Documentation::NameWidgetSystem(g_hash.Registry(), "FrameAPICooldown"); + Game::Lua::RegisterFrameMethods(g_hash.Registry(), g_methods, g_methodDocs); } const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions}; -// The hash's functions are references into the game Lua state, so they are -// released with the engine's own class hashes, at the end of the game UI's -// unregister pass while that state is still open. -using UnregisterScriptFunctions_t = void(__cdecl *)(); -using UnregisterMethods_t = void(__fastcall *)(void *hash); -UnregisterScriptFunctions_t UnregisterScriptFunctions_o = nullptr; - -void __cdecl UnregisterScriptFunctions_h() { - UnregisterScriptFunctions_o(); - reinterpret_cast(Offsets::FUN_FRAMESCRIPT_UNREGISTER_METHODS)(g_hash); -} - -const Game::HookAutoRegister _unregisterHook{ - Offsets::FUN_GAMEUI_UNREGISTER_SCRIPT_FUNCTIONS, - reinterpret_cast(&UnregisterScriptFunctions_h), - reinterpret_cast(&UnregisterScriptFunctions_o)}; - } // namespace } // namespace Frame::Cooldown diff --git a/src/frame/Subclass.cpp b/src/frame/Subclass.cpp new file mode 100644 index 00000000..d9434c00 --- /dev/null +++ b/src/frame/Subclass.cpp @@ -0,0 +1,61 @@ +// This file is part of ClassicAPI. +// +// ClassicAPI is free software: you can redistribute it and/or modify it under the terms +// of the GNU General Public License as published by the Free Software Foundation, either +// version 3 of the License, or (at your option) any later version. +// +// ClassicAPI is distributed in the hope that it will be useful, but WITHOUT ANY +// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +// PURPOSE. See the GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along with +// ClassicAPI. If not, see . + +#include "frame/Subclass.h" + +namespace Frame::Subclass { + +namespace { + +// Constant-initialized, so every MethodHash's constructor can link in during +// static initialization whatever the order of the translation units. +MethodHash *g_hashes = nullptr; + +using PushMethod_t = int(__fastcall *)(void *L, const char *name, void *hash); +using UnregisterMethods_t = void(__fastcall *)(void *hash); +using UnregisterScriptFunctions_t = void(__cdecl *)(); +UnregisterScriptFunctions_t UnregisterScriptFunctions_o = nullptr; + +// The hashes' functions are references into the game Lua state. +void __cdecl UnregisterScriptFunctions_h() { + UnregisterScriptFunctions_o(); + MethodHash::ReleaseAll(); +} + +const Game::HookAutoRegister _unregisterHook{ + Offsets::FUN_GAMEUI_UNREGISTER_SCRIPT_FUNCTIONS, + reinterpret_cast(&UnregisterScriptFunctions_h), + reinterpret_cast(&UnregisterScriptFunctions_o)}; + +} // namespace + +MethodHash::MethodHash() : words_{}, next_(g_hashes) { + words_[0] = Offsets::VTBL_METHOD_HASH_ALLOCATOR; + words_[1] = 0xC; // node link offset + words_[2] = reinterpret_cast(&words_[2]); + words_[3] = reinterpret_cast(&words_[2]) | 1; + words_[9] = 0xFFFFFFFF; // no buckets yet + g_hashes = this; +} + +bool MethodHash::PushMethod(void *L, const char *name) { + return reinterpret_cast(Offsets::FUN_FRAMESCRIPT_PUSH_METHOD)(L, name, words_) != + 0; +} + +void MethodHash::ReleaseAll() { + for (MethodHash *h = g_hashes; h != nullptr; h = h->next_) + reinterpret_cast(Offsets::FUN_FRAMESCRIPT_UNREGISTER_METHODS)(h->words_); +} + +} // namespace Frame::Subclass diff --git a/src/frame/Subclass.h b/src/frame/Subclass.h new file mode 100644 index 00000000..e8821c82 --- /dev/null +++ b/src/frame/Subclass.h @@ -0,0 +1,80 @@ +// This file is part of ClassicAPI. +// +// ClassicAPI is free software: you can redistribute it and/or modify it under the terms +// of the GNU General Public License as published by the Free Software Foundation, either +// version 3 of the License, or (at your option) any later version. +// +// ClassicAPI is distributed in the hope that it will be useful, but WITHOUT ANY +// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +// PURPOSE. See the GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along with +// ClassicAPI. If not, see . + +#pragma once + +// The parts every frame class this DLL adds shares: copied engine vtables with +// overrides in place, and a method hash of the class's own (Offsets.h +// "Subclassing CSimpleFrame", "Per-class method hashes"). Frame::Cooldown and +// Model::Scene are built on it. + +#include "Game.h" +#include "Offsets.h" + +#include +#include +#include + +namespace Frame::Subclass { + +// An MSVC vtable with its RTTI locator in front, as the engine's are laid out. +template +struct VTable { + const void *locator; + const void *slots[N]; + + bool Built() const { return slots[0] != nullptr; } + // A copy of the engine vtable at `address` (its first slot). + void CopyFrom(uintptr_t address) { + std::memcpy(this, reinterpret_cast(address - 4), sizeof(*this)); + } + // `slot` is a byte offset (Offsets::VTBL_*). + void Set(uintptr_t slot, const void *fn) { slots[slot / 4] = fn; } +}; + +// The frame a layout sub-object (layout-vtable `this`) belongs to. +inline void *FrameOfLayout(void *layout) { + return static_cast(layout) - Offsets::OFF_FRAME_LAYOUT_SUBOBJECT; +} + +// The function in byte offset `slot` of the engine vtable at `address`, for +// an override's base call. +template +Fn Slot(uintptr_t address, uintptr_t slot) { + return Game::Read(reinterpret_cast(address), slot); +} + +// A frame class's method hash, built the way the engine's static initializer +// builds one (Model's 0x0076F5F0). Every hash is released where the engine +// releases its own class hashes, at the end of CGGameUI::UnregisterScriptFunctions, +// while the game Lua state is still open. Declare one at file scope. +class MethodHash { + public: + MethodHash(); + MethodHash(const MethodHash &) = delete; + MethodHash &operator=(const MethodHash &) = delete; + + // What Game::Lua::RegisterFrameMethods and the documentation take. + void *Registry() { return words_; } + // FrameScriptPushMethod: pushes the method and answers true when the + // hash has it. + bool PushMethod(void *L, const char *name); + + static void ReleaseAll(); + + private: + uint32_t words_[Offsets::METHOD_HASH_SIZE / 4]; + MethodHash *next_; +}; + +} // namespace Frame::Subclass diff --git a/src/model/Camera.cpp b/src/model/Camera.cpp index f697d956..cf00afdb 100644 --- a/src/model/Camera.cpp +++ b/src/model/Camera.cpp @@ -84,8 +84,6 @@ Vec3 GetVector(void *camera, uint32_t id) { return v; } -namespace { - void SetVector(void *camera, uint32_t id, const Vec3 &v) { reinterpret_cast(Offsets::FUN_CAMERA_SET_VECTOR)(camera, id, &v.x, 0); } @@ -98,6 +96,8 @@ void SetScalar(void *camera, uint32_t id, float value) { reinterpret_cast(Offsets::FUN_CAMERA_SET_SCALAR)(camera, id, value); } +namespace { + // ConfigureCamera's own evaluation pass: facing 0, rebuild the root // transform, animate the scene, restore the facing. void AnimateUnrotated(void *pane, void *model) { diff --git a/src/model/Camera.h b/src/model/Camera.h index d82c63c8..8ff516d1 100644 --- a/src/model/Camera.h +++ b/src/model/Camera.h @@ -21,7 +21,11 @@ struct Vec3 { // The M2 model's camera with id `id` (0 = portrait), or null when it has none. void *CameraById(void *model, uint32_t id); -// A camera's vector property (Offsets::CAMERA_PROP_EYE / _TARGET). +// A camera's properties (Offsets::CAMERA_PROP_*): vectors (eye, target) and +// scalars (clips, field of view, roll, yaw). Vec3 GetVector(void *camera, uint32_t id); +void SetVector(void *camera, uint32_t id, const Vec3 &v); +float GetScalar(void *camera, uint32_t id); +void SetScalar(void *camera, uint32_t id, float value); } // namespace Model::Camera diff --git a/src/model/DisplayInfo.cpp b/src/model/DisplayInfo.cpp index 5a7657cf..6090e2b2 100644 --- a/src/model/DisplayInfo.cpp +++ b/src/model/DisplayInfo.cpp @@ -301,6 +301,28 @@ const uint8_t *DressRecord(uint32_t displayID) { return bake != nullptr && bake[0] != '\0' ? extraRec : nullptr; } +void *CreateDisplayModel(void *scene, uint32_t displayID, const char **path) { + using ApplyDisplay_t = void(__fastcall *)(void *model, const uint8_t *display, + const uint8_t *modelData); + const uint8_t *display = DBC::Record(Offsets::VAR_CREATUREDISPLAYINFO_RECORDS, + Offsets::VAR_CREATUREDISPLAYINFO_COUNT, displayID); + if (display == nullptr) + return nullptr; + const uint8_t *modelData = DBC::Record( + Offsets::VAR_CREATUREMODELDATA_RECORDS, Offsets::VAR_CREATUREMODELDATA_COUNT, + Game::Read(display, Offsets::OFF_CREATUREDISPLAYINFO_MODEL_ID)); + if (modelData == nullptr) + return nullptr; + const char *file = Game::Read(modelData, Offsets::OFF_CREATUREMODELDATA_MODEL_PATH); + if (path != nullptr) + *path = file; + void *model = M2::CreateModel(scene, file); + if (model != nullptr) + reinterpret_cast(Offsets::FUN_APPLY_CREATURE_DISPLAY)(model, display, + modelData); + return model; +} + // Configure + feed equipment, the engine's order: SetInfo, then the 10 Extra // equipment slots. Field-for-field mirror of FUN_005fb200's NPC branch. void *CreateDresser(void *instance, const uint8_t *extraRec) { diff --git a/src/model/DisplayInfo.h b/src/model/DisplayInfo.h index 2d726d72..ff017efe 100644 --- a/src/model/DisplayInfo.h +++ b/src/model/DisplayInfo.h @@ -18,6 +18,14 @@ namespace Model::DisplayInfo { // null when the display gets no character customization. const uint8_t *DressRecord(uint32_t displayID); +// A new model of the display in `scene`, skinned as AttachDisplayModel skins +// one (CreateModelFromPath on the CreatureModelData path, then +// ApplyCreatureDisplay), that the caller owns one reference on. Null for a +// display with no CreatureDisplayInfo or CreatureModelData row. Undressed: a +// DressRecord display still needs CreateDresser once it has loaded. `path`, +// when given, receives the model's file path (DBC memory). +void *CreateDisplayModel(void *scene, uint32_t displayID, const char **path = nullptr); + // The engine character compositor, configured to dress the LOADED model // `instance` from `extraRec` (a DressRecord) and fed its equipment, or null // when the engine pool is empty or rejects the info. It holds a reference on diff --git a/src/model/M2.h b/src/model/M2.h index a05d3fb5..74268389 100644 --- a/src/model/M2.h +++ b/src/model/M2.h @@ -69,6 +69,34 @@ inline void SetVisible(void *model, bool visible) { reinterpret_cast(Offsets::FUN_M2MODEL_SET_VISIBLE)(model, visible ? 1 : 0); } +inline void SetAlpha(void *model, float alpha) { + using Fn = void(__thiscall *)(void *, float); + reinterpret_cast(Offsets::FUN_M2MODEL_SET_ALPHA)(model, alpha); +} + +// The model this one is attached to, or null. +inline void *Parent(const void *model) { + return Game::Read(model, Offsets::OFF_M2MODEL_PARENT); +} + +// The model's overall bounds {min xyz, max xyz}. Waits for an unloaded file. +inline void GetBoundingBox(void *model, float (&box)[6]) { + using Fn = void(__thiscall *)(void *, float *); + reinterpret_cast(Offsets::FUN_M2MODEL_GET_BOUNDING_BOX)(model, box); +} + +// The bounds of the animation's sequence, all zero when the model has none. +// Waits for an unloaded file. +inline void GetSequenceBounds(void *model, uint32_t animation, uint32_t variation, + float (&box)[6]) { + using Fn = void(__thiscall *)(void *, uint32_t, uint32_t, void *); + uint8_t record[Offsets::M2_SEQUENCE_INFO_SIZE]; + reinterpret_cast(Offsets::FUN_M2MODEL_GET_SEQUENCE_INFO)(model, animation, variation, + record); + for (int i = 0; i < 6; ++i) + box[i] = Game::Read(record, Offsets::OFF_M2_SEQUENCE_INFO_BOUNDS + i * 4); +} + inline void SetAnimated(void *model, bool animated) { using Fn = void(__thiscall *)(void *, int); reinterpret_cast(Offsets::FUN_M2MODEL_SET_ANIMATED)(model, animated ? 1 : 0); diff --git a/src/model/ModelInfo.cpp b/src/model/ModelInfo.cpp new file mode 100644 index 00000000..e43c0917 --- /dev/null +++ b/src/model/ModelInfo.cpp @@ -0,0 +1,258 @@ +// This file is part of ClassicAPI. +// +// ClassicAPI is free software: you can redistribute it and/or modify it under the terms +// of the GNU General Public License as published by the Free Software Foundation, either +// version 3 of the License, or (at your option) any later version. +// +// ClassicAPI is distributed in the hope that it will be useful, but WITHOUT ANY +// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +// PURPOSE. See the GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along with +// ClassicAPI. If not, see . + +// `C_ModelInfo.GetModelSceneInfoByID(modelSceneID)` -> modelSceneType, +// modelCameraIDs, modelActorsIDs, flags +// `C_ModelInfo.GetModelSceneCameraInfoByID(modelSceneCameraID)` -> UIModelSceneCameraInfo +// `C_ModelInfo.GetModelSceneActorInfoByID(modelActorID)` -> UIModelSceneActorInfo +// `C_ModelInfo.GetModelSceneActorDisplayInfoByID(modelActorDisplayID)` -> UIModelSceneActorDisplayInfo +// +// Retail's getters read its UiModelScene DB2s; these read the rows embedded +// in model/SceneData.h, shaped as retail returns them. An unknown ID returns +// nothing, as retail's do (MayReturnNothing). The vector3 fields are +// Vector3DMixin objects (CreateVector3D, Util/Vector3D.lua). From a retail +// probe (docs/notes/model-scene.md § Data): the actor flags split into the +// three useCenterForOrigin booleans, and a NormalizedScale of 0 is a nil +// normalizeScaleAggressiveness; a display ID of 0 is likewise nil. Retail's +// active-scene bookkeeping (Add/ClearActiveModelScene[Actor]) does nothing in +// public clients and is the embedded addon's (Compat.lua). + +#include "Game.h" +#include "model/SceneData.h" + +#include + +namespace Model::ModelInfo { + +namespace { + +using namespace Model::SceneData; + +// Enum.UIModelSceneActorFlag. +constexpr uint32_t kUseCenterForOriginX = 0x2; +constexpr uint32_t kUseCenterForOriginY = 0x4; +constexpr uint32_t kUseCenterForOriginZ = 0x8; + +template +const Row *Find(const Row (&rows)[N], uint32_t id) { + for (const Row &row : rows) + if (row.id == id) + return &row; + return nullptr; +} + +bool IdArg(void *L, uint32_t &id) { + if (!Game::Lua::IsNumber(L, 1)) + return false; + id = static_cast(Game::Lua::ToNumber(L, 1)); + return true; +} + +// `t[key] = CreateVector3D(v)` on the table at the top of the stack. +void SetFieldVector3D(void *L, const char *key, const Vec3 &v) { + Game::Lua::PushString(L, key); + Game::Lua::PushString(L, "CreateVector3D"); + Game::Lua::GetTable(L, Game::Lua::GLOBALS_INDEX); + Game::Lua::PushNumber(L, v.x); + Game::Lua::PushNumber(L, v.y); + Game::Lua::PushNumber(L, v.z); + Game::Lua::Call(L, 3, 1); + Game::Lua::SetTable(L, -3); +} + +// An array of the IDs of every row of `rows` in `sceneID`, in ID order. +template +void PushSceneIDs(void *L, const Row (&rows)[N], uint32_t sceneID) { + Game::Lua::NewTable(L); + int n = 0; + for (const Row &row : rows) { + if (row.sceneID != sceneID) + continue; + Game::Lua::PushNumber(L, row.id); + Game::Lua::RawSetI(L, -2, ++n); + } +} + +int __fastcall Script_GetModelSceneInfoByID(void *L) { + uint32_t id = 0; + const SceneRow *scene = IdArg(L, id) ? Find(kScenes, id) : nullptr; + if (scene == nullptr) + return 0; + Game::Lua::PushNumber(L, scene->uiSystemType); + PushSceneIDs(L, kCameras, id); + PushSceneIDs(L, kActors, id); + Game::Lua::PushNumber(L, scene->flags); + return 4; +} + +int __fastcall Script_GetModelSceneCameraInfoByID(void *L) { + uint32_t id = 0; + const CameraRow *camera = IdArg(L, id) ? Find(kCameras, id) : nullptr; + if (camera == nullptr) + return 0; + Game::Lua::NewTable(L); + Game::Lua::SetFieldNumber(L, "modelSceneCameraID", camera->id); + Game::Lua::SetFieldString(L, "scriptTag", camera->scriptTag); + Game::Lua::SetFieldString(L, "cameraType", "OrbitCamera"); + SetFieldVector3D(L, "target", camera->target); + Game::Lua::SetFieldNumber(L, "yaw", camera->yaw); + Game::Lua::SetFieldNumber(L, "pitch", camera->pitch); + Game::Lua::SetFieldNumber(L, "roll", camera->roll); + Game::Lua::SetFieldNumber(L, "zoomDistance", camera->zoomDistance); + Game::Lua::SetFieldNumber(L, "minZoomDistance", camera->minZoomDistance); + Game::Lua::SetFieldNumber(L, "maxZoomDistance", camera->maxZoomDistance); + SetFieldVector3D(L, "zoomedTargetOffset", camera->zoomedTargetOffset); + Game::Lua::SetFieldNumber(L, "zoomedYawOffset", camera->zoomedYawOffset); + Game::Lua::SetFieldNumber(L, "zoomedPitchOffset", camera->zoomedPitchOffset); + Game::Lua::SetFieldNumber(L, "zoomedRollOffset", camera->zoomedRollOffset); + Game::Lua::SetFieldNumber(L, "flags", camera->flags); + return 1; +} + +int __fastcall Script_GetModelSceneActorInfoByID(void *L) { + uint32_t id = 0; + const ActorRow *actor = IdArg(L, id) ? Find(kActors, id) : nullptr; + if (actor == nullptr) + return 0; + Game::Lua::NewTable(L); + Game::Lua::SetFieldNumber(L, "modelActorID", actor->id); + Game::Lua::SetFieldString(L, "scriptTag", actor->scriptTag); + SetFieldVector3D(L, "position", actor->position); + Game::Lua::SetFieldNumber(L, "yaw", actor->yaw); + Game::Lua::SetFieldNumber(L, "pitch", actor->pitch); + Game::Lua::SetFieldNumber(L, "roll", actor->roll); + if (actor->normalizedScale != 0.0f) + Game::Lua::SetFieldNumber(L, "normalizeScaleAggressiveness", actor->normalizedScale); + Game::Lua::SetFieldBool(L, "useCenterForOriginX", (actor->flags & kUseCenterForOriginX) != 0); + Game::Lua::SetFieldBool(L, "useCenterForOriginY", (actor->flags & kUseCenterForOriginY) != 0); + Game::Lua::SetFieldBool(L, "useCenterForOriginZ", (actor->flags & kUseCenterForOriginZ) != 0); + if (actor->displayID != 0) + Game::Lua::SetFieldNumber(L, "modelActorDisplayID", actor->displayID); + return 1; +} + +int __fastcall Script_GetModelSceneActorDisplayInfoByID(void *L) { + uint32_t id = 0; + const ActorDisplayRow *display = IdArg(L, id) ? Find(kActorDisplays, id) : nullptr; + if (display == nullptr) + return 0; + Game::Lua::NewTable(L); + Game::Lua::SetFieldNumber(L, "animation", display->animation); + Game::Lua::SetFieldNumber(L, "animationVariation", display->animationVariation); + Game::Lua::SetFieldNumber(L, "animSpeed", display->animSpeed); + if (display->animKitID != 0) + Game::Lua::SetFieldNumber(L, "animationKitID", display->animKitID); + if (display->spellVisualKitID != 0) + Game::Lua::SetFieldNumber(L, "spellVisualKitID", display->spellVisualKitID); + Game::Lua::SetFieldNumber(L, "alpha", display->alpha); + Game::Lua::SetFieldNumber(L, "scale", display->scale); + return 1; +} + +// --- Documentation ---------------------------------------------------------- + +const Game::Doc::Field kActorDisplayInfoFields[] = { + Game::Doc::Req("animation", "number"), + Game::Doc::Req("animationVariation", "number"), + Game::Doc::Req("animSpeed", "number"), + Game::Doc::Opt("animationKitID", "number"), + Game::Doc::Opt("spellVisualKitID", "number"), + Game::Doc::Req("alpha", "number"), + Game::Doc::Req("scale", "number"), +}; +const Game::Doc::Structure kActorDisplayInfo{"UIModelSceneActorDisplayInfo", "ModelInfo", + kActorDisplayInfoFields}; + +const Game::Doc::Field kActorInfoFields[] = { + Game::Doc::Req("modelActorID", "number"), + Game::Doc::Req("scriptTag", "cstring"), + Game::Doc::Req("position", "vector3"), + Game::Doc::Req("yaw", "number"), + Game::Doc::Req("pitch", "number"), + Game::Doc::Req("roll", "number"), + Game::Doc::Opt("normalizeScaleAggressiveness", "number"), + Game::Doc::Req("useCenterForOriginX", "bool"), + Game::Doc::Req("useCenterForOriginY", "bool"), + Game::Doc::Req("useCenterForOriginZ", "bool"), + Game::Doc::Opt("modelActorDisplayID", "number"), +}; +const Game::Doc::Structure kActorInfo{"UIModelSceneActorInfo", "ModelInfo", kActorInfoFields}; + +const Game::Doc::Field kCameraInfoFields[] = { + Game::Doc::Req("modelSceneCameraID", "number"), + Game::Doc::Req("scriptTag", "cstring"), + Game::Doc::Req("cameraType", "cstring"), + Game::Doc::Req("target", "vector3"), + Game::Doc::Req("yaw", "number"), + Game::Doc::Req("pitch", "number"), + Game::Doc::Req("roll", "number"), + Game::Doc::Req("zoomDistance", "number"), + Game::Doc::Req("minZoomDistance", "number"), + Game::Doc::Req("maxZoomDistance", "number"), + Game::Doc::Req("zoomedTargetOffset", "vector3"), + Game::Doc::Req("zoomedYawOffset", "number"), + Game::Doc::Req("zoomedPitchOffset", "number"), + Game::Doc::Req("zoomedRollOffset", "number"), + Game::Doc::Req("flags", "ModelSceneSetting"), +}; +const Game::Doc::Structure kCameraInfo{"UIModelSceneCameraInfo", "ModelInfo", kCameraInfoFields}; + +const Game::Doc::Field kSceneIDArg[] = {Game::Doc::Req("modelSceneID", "number")}; +const Game::Doc::Field kSceneInfoRets[] = { + Game::Doc::Req("modelSceneType", "ModelSceneType"), + Game::Doc::Req("modelCameraIDs", "table"), + Game::Doc::Req("modelActorsIDs", "table"), + Game::Doc::Req("flags", "number"), +}; +const Game::Doc::Function kGetModelSceneInfoByID{ + "Returns a model scene's type and the IDs of its cameras and actors.", kSceneIDArg, + kSceneInfoRets}; + +const Game::Doc::Field kCameraIDArg[] = {Game::Doc::Req("modelSceneCameraID", "number")}; +const Game::Doc::Field kCameraInfoRet[] = { + Game::Doc::Req("modelSceneCameraInfo", "UIModelSceneCameraInfo")}; +const Game::Doc::Function kGetModelSceneCameraInfoByID{"Returns a model scene camera's settings.", + kCameraIDArg, kCameraInfoRet}; + +const Game::Doc::Field kActorIDArg[] = {Game::Doc::Req("modelActorID", "number")}; +const Game::Doc::Field kActorInfoRet[] = {Game::Doc::Req("actorInfo", "UIModelSceneActorInfo")}; +const Game::Doc::Function kGetModelSceneActorInfoByID{ + "Returns where a model scene actor stands and how it is scaled.", kActorIDArg, + kActorInfoRet}; + +const Game::Doc::Field kActorDisplayIDArg[] = {Game::Doc::Req("modelActorDisplayID", "number")}; +const Game::Doc::Field kActorDisplayInfoRet[] = { + Game::Doc::Req("actorDisplayInfo", "UIModelSceneActorDisplayInfo")}; +const Game::Doc::Function kGetModelSceneActorDisplayInfoByID{ + "Returns the animation, alpha and scale a model scene actor starts with.", + kActorDisplayIDArg, kActorDisplayInfoRet}; + +void RegisterLuaFunctions() { + Game::Lua::RegisterTableFunction("C_ModelInfo", "GetModelSceneInfoByID", + &Script_GetModelSceneInfoByID, &kGetModelSceneInfoByID); + Game::Lua::RegisterTableFunction("C_ModelInfo", "GetModelSceneCameraInfoByID", + &Script_GetModelSceneCameraInfoByID, + &kGetModelSceneCameraInfoByID); + Game::Lua::RegisterTableFunction("C_ModelInfo", "GetModelSceneActorInfoByID", + &Script_GetModelSceneActorInfoByID, + &kGetModelSceneActorInfoByID); + Game::Lua::RegisterTableFunction("C_ModelInfo", "GetModelSceneActorDisplayInfoByID", + &Script_GetModelSceneActorDisplayInfoByID, + &kGetModelSceneActorDisplayInfoByID); +} + +const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions}; + +} // namespace + +} // namespace Model::ModelInfo diff --git a/src/model/Portrait.cpp b/src/model/Portrait.cpp index e98dfb1d..7703adaa 100644 --- a/src/model/Portrait.cpp +++ b/src/model/Portrait.cpp @@ -51,7 +51,6 @@ #include "Game.h" #include "Offsets.h" -#include "dbc/Lookup.h" #include "model/Camera.h" #include "model/DisplayInfo.h" #include "model/M2.h" @@ -73,8 +72,6 @@ constexpr uint32_t kTexels = kSize * kSize; using CreateScene_t = void *(__cdecl *)(); using ReleaseScene_t = void(__thiscall *)(void *scene); using CopyModel_t = void *(__thiscall *)(void *scene, void *source, uint32_t flags); -using ApplyDisplay_t = void(__fastcall *)(void *model, const uint8_t *display, - const uint8_t *modelData); using DetachAll_t = void(__fastcall *)(void *model); using DrawScene_t = void(__thiscall *)(void *scene, uint32_t pass); using SetTransforms_t = void(__fastcall *)(void *camera, const float *rect, uint32_t unused); @@ -270,27 +267,14 @@ Portrait *Acquire(uint32_t displayID) { auto found = g_portraits.find(displayID); if (found != g_portraits.end()) return found->second.get(); - const uint8_t *display = DBC::Record(Offsets::VAR_CREATUREDISPLAYINFO_RECORDS, - Offsets::VAR_CREATUREDISPLAYINFO_COUNT, displayID); - if (display == nullptr) - return nullptr; - const uint8_t *modelData = DBC::Record( - Offsets::VAR_CREATUREMODELDATA_RECORDS, Offsets::VAR_CREATUREMODELDATA_COUNT, - Game::Read(display, Offsets::OFF_CREATUREDISPLAYINFO_MODEL_ID)); - if (modelData == nullptr) - return nullptr; - void *scene = reinterpret_cast(Offsets::FUN_M2_CREATE_SCENE)(); if (scene == nullptr) return nullptr; - void *model = M2::CreateModel( - scene, Game::Read(modelData, Offsets::OFF_CREATUREMODELDATA_MODEL_PATH)); + void *model = Model::DisplayInfo::CreateDisplayModel(scene, displayID); if (model == nullptr) { reinterpret_cast(Offsets::FUN_M2SCENE_RELEASE)(scene); return nullptr; } - reinterpret_cast(Offsets::FUN_APPLY_CREATURE_DISPLAY)(model, display, - modelData); // The bake's own texture: 64x64, one mip, ARGB8888, flags (1, 0, 0, 0, 0, // 0, 1, 0), "Portrait1" (0x005257D3). diff --git a/src/model/Scene.cpp b/src/model/Scene.cpp new file mode 100644 index 00000000..39a916d6 --- /dev/null +++ b/src/model/Scene.cpp @@ -0,0 +1,640 @@ +// This file is part of ClassicAPI. +// +// ClassicAPI is free software: you can redistribute it and/or modify it under the terms +// of the GNU General Public License as published by the Free Software Foundation, either +// version 3 of the License, or (at your option) any later version. +// +// ClassicAPI is distributed in the hope that it will be useful, but WITHOUT ANY +// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +// PURPOSE. See the GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along with +// ClassicAPI. If not, see . + +// `ModelScene` frame type: retail's 3D stage of model actors with an explicit +// camera (FrameAPIModelSceneFrameDocumentation.lua's contract; plan, data +// and probes in docs/notes/model-scene.md). No older client has it, so it is +// built on 1.12's own Model frame, which already is a stage: each Model frame +// has an M2 scene and clock of its own, its paint (SimpleModelDraw 0x0076D240) +// animates and draws that WHOLE scene, and every unattached model in it is +// drawn with its own placement matrix (model-scene.md A1). The stock frame +// just only ever places one model. +// +// So a ModelScene is a CSimpleModel (one SMemAlloc block of the Model size +// plus the fields below, CSimpleModel's constructor, then our copies of its +// two vtables), whose Model half Lua never sees: +// +// slot override +// +0x00 deleting destructor destroys the actors, then Model's (which +// frees the camera and the scene) +// +0x08 GetScriptMethod our hash, then CSimpleFrame's, skipping +// Model's (0x0076F870 only adds that hash) +// +0x0C script names CSimpleFrame's: no OnUpdateModel +// +0x10 / +0x18 / +0x1C ModelScene, then Frame's answers: retail's +// IsObjectType("Model") is false +// +0x28 SetFrameAlpha Model's, then each actor's model +// +0x38 OnFrameUpdate Model's clock, then each actor's update +// +0x44 EmitLayer Model's, then our paint on the draw layer +// +0x98 UpdateModel places every actor +// layout +0x04 / +0x08 our destructor / CSimpleFrame's XML loader +// +// The paint mirrors SimpleModelDraw call for call: the device projection, +// view and viewport saved; the camera's projection and view over the frame's +// raw rect (CameraSetDeviceTransforms); the viewport the rect clamped to the +// screen, nothing drawn under 2^-22 of it; a depth clear; the placement (slot +// 0x98, here every actor's); the scene animated from the camera's eye and +// drawn in passes 0 and 1; the three states restored. It has no model gate: +// the collect pass queues only ready models. +// +// The camera is a fixed CCamera made the way the PlayerModel pane makes its +// fallback one (0x00505890) and installed at +0x31C, so the paint's camera leg +// is the engine's. Retail's camera is a position and three axes; the CCamera's +// eye is the position and its target the position plus forward. 1.12's view +// builds its up vector from the camera's yaw and roll properties as (sin yaw +// sin roll, -cos yaw sin roll, cos roll), which can name any unit vector, so +// both are set to name retail's up exactly (the retail probe matched this up +// at every orientation it read). Retail's projection convention is 1.12's own +// (the probe matched 0x005C3CC0 to 0.02%), so retail's field of view and clip +// planes go in unchanged, and so do its defaults: FOV 0.9424778, near 0.2, +// far 100, at the origin looking along +X. +// +// The light is retail's default, set the way PlayerModel's constructor sets +// its own (0x00505680): directional along (0, 1, 0), ambient 178/255, diffuse +// (204, 204, 163)/255, enabled. Each actor's model is lit by it through the +// frame's light callback, as a Model frame's model is. + +#include "model/Scene.h" + +#include "Game.h" +#include "Offsets.h" +#include "api/Documentation.h" +#include "frame/Subclass.h" +#include "model/Camera.h" +#include "model/M2.h" + +#include +#include +#include +#include + +namespace Model::Scene { + +namespace { + +using Frame::Subclass::FrameOfLayout; +using Model::Camera::Vec3; + +// Retail's camera defaults (probe, docs/notes/model-scene.md). +constexpr float kDefaultFieldOfView = 0.9424778f; +constexpr float kDefaultNearClip = 0.2f; +constexpr float kDefaultFarClip = 100.0f; + +struct Fields { + std::vector *actors; // owned, in creation order + Vec3 position; + Vec3 forward, right, up; + float fieldOfView; + float nearClip; + float farClip; + int drawLayer; +}; + +constexpr size_t kObjectSize = Offsets::MODEL_FRAME_SIZE + sizeof(Fields); + +Fields &F(void *frame) { return *Game::Ptr(frame, Offsets::MODEL_FRAME_SIZE); } + +// ---- the camera ------------------------------------------------------------------ + +void *CameraOf(void *frame) { return Game::Read(frame, Offsets::OFF_SIMPLEMODEL_CAMERA); } + +// Writes the scene's camera into its CCamera. +void ApplyCamera(void *frame) { + void *camera = CameraOf(frame); + if (camera == nullptr) + return; + const Fields &f = F(frame); + using namespace Model::Camera; + SetVector(camera, Offsets::CAMERA_PROP_EYE, f.position); + SetVector(camera, Offsets::CAMERA_PROP_TARGET, + {f.position.x + f.forward.x, f.position.y + f.forward.y, f.position.z + f.forward.z}); + // up = (sin yaw sin roll, -cos yaw sin roll, cos roll), roll in [0, pi]. + const float upLength = std::sqrt(f.up.x * f.up.x + f.up.y * f.up.y + f.up.z * f.up.z); + const float cosRoll = upLength > 0.0f ? f.up.z / upLength : 1.0f; + const float roll = std::acos(cosRoll < -1.0f ? -1.0f : (cosRoll > 1.0f ? 1.0f : cosRoll)); + const float yaw = (f.up.x != 0.0f || f.up.y != 0.0f) ? std::atan2(f.up.x, -f.up.y) : 0.0f; + SetScalar(camera, Offsets::CAMERA_PROP_ROLL, roll); + SetScalar(camera, Offsets::CAMERA_PROP_YAW, yaw); + SetScalar(camera, Offsets::CAMERA_PROP_FOV, f.fieldOfView); + SetScalar(camera, Offsets::CAMERA_PROP_NEAR_CLIP, f.nearClip); + SetScalar(camera, Offsets::CAMERA_PROP_FAR_CLIP, f.farClip); +} + +// Retail's axes from yaw, pitch and roll (Vector3D_CalculateNormalFromYawPitch: +// forward = (cos p cos y, cos p sin y, -sin p), positive pitch looking down; +// the retail probe: right = (0, 1, 0) and up = (0, 0, 1) at rest, and roll +// turns both about forward). +void SetOrientation(Fields &f, float yaw, float pitch, float roll) { + const float cy = std::cos(yaw), sy = std::sin(yaw); + const float cp = std::cos(pitch), sp = std::sin(pitch); + const float cr = std::cos(roll), sr = std::sin(roll); + const Vec3 right0{-sy, cy, 0.0f}; + const Vec3 up0{sp * cy, sp * sy, cp}; + f.forward = {cp * cy, cp * sy, -sp}; + f.right = {cr * right0.x + sr * up0.x, cr * right0.y + sr * up0.y, cr * right0.z + sr * up0.z}; + f.up = {cr * up0.x - sr * right0.x, cr * up0.y - sr * right0.y, cr * up0.z - sr * right0.z}; +} + +void InstallCamera(void *frame) { + using CameraCreate_t = void *(__cdecl *)(); + using Install_t = void(__thiscall *)(void *frame, void *camera); + using Release_t = void(__fastcall *)(void *handle); + void *camera = reinterpret_cast(Offsets::FUN_CAMERA_CREATE)(); + if (camera == nullptr) + return; + reinterpret_cast(Offsets::FUN_SIMPLEMODEL_INSTALL_CAMERA)(frame, camera); + reinterpret_cast(Offsets::FUN_HANDLE_RELEASE)(camera); + ApplyCamera(frame); +} + +// PlayerModel's light (0x00505680) with retail's values. +void InitLight(void *frame) { + using SetInt_t = void(__thiscall *)(void *light, int value); + using SetDirection_t = void(__thiscall *)(void *light, const float *v); + void *light = Game::Ptr(frame, Offsets::OFF_SIMPLEMODEL_LIGHT); + reinterpret_cast(Offsets::FUN_M2LIGHT_SET_TYPE)(light, 0); + const float direction[3] = {0.0f, 1.0f, 0.0f}; + reinterpret_cast(Offsets::FUN_M2LIGHT_SET_DIRECTION)(light, direction); + float *ambient = Game::Ptr(light, Offsets::OFF_M2LIGHT_AMBIENT); + float *diffuse = Game::Ptr(light, Offsets::OFF_M2LIGHT_DIFFUSE); + ambient[0] = ambient[1] = ambient[2] = 178.0f / 255.0f; + diffuse[0] = diffuse[1] = 204.0f / 255.0f; + diffuse[2] = 163.0f / 255.0f; + reinterpret_cast(Offsets::FUN_M2LIGHT_SET_ENABLED)(light, 1); +} + +// ---- the paint (SimpleModelDraw) ----------------------------------------------- + +void PlaceActors(void *frame) { + for (Actor *actor : *F(frame).actors) + actor->Place(); +} + +// SimpleModelDraw's clamp: at or past 1 (and NaN) is 1, at or below 0 is 0. +float ClampUnit(float v) { + if (!(v < 1.0f)) + return 1.0f; + return v > 0.0f ? v : 0.0f; +} + +void __fastcall Paint(void *frame) { + using GetRect_t = int(__thiscall *)(void *layout, float *rect); + using Matrix_t = void(__fastcall *)(float *m); + using GetViewport_t = void(__fastcall *)(float *, float *, float *, float *, float *, float *); + using SetViewport_t = void(__stdcall *)(float, float, float, float, float, float); + using SetTransforms_t = void(__fastcall *)(void *camera, const float *rect, uint32_t unused); + using SetupOrtho_t = void(__fastcall *)(const float *rect, const float *point, int unused); + using DdcToNdc_t = void(__fastcall *)(float *x, float *y, float inX, float inY); + using Clear_t = void(__fastcall *)(uint32_t mask); + using Draw_t = void(__thiscall *)(void *scene, uint32_t pass); + + // {bottom, left, top, right} + float rect[4] = {}; + if (!reinterpret_cast(Offsets::FUN_REGION_GET_RECT)( + Game::Ptr(frame, Offsets::OFF_FRAME_LAYOUT_SUBOBJECT), rect)) + return; + float projection[16]; + float view[16]; + float vp[6]; // minX, maxX, minY, maxY, minZ, maxZ + reinterpret_cast(Offsets::FUN_GX_GET_PROJECTION)(projection); + reinterpret_cast(Offsets::FUN_GX_GET_VIEW)(view); + reinterpret_cast(Offsets::FUN_GX_GET_VIEWPORT)(&vp[0], &vp[1], &vp[2], &vp[3], + &vp[4], &vp[5]); + float eye[3] = {0.0f, 0.0f, 0.0f}; + if (void *camera = CameraOf(frame)) { + const Vec3 e = Model::Camera::GetVector(camera, Offsets::CAMERA_PROP_EYE); + eye[0] = e.x; + eye[1] = e.y; + eye[2] = e.z; + reinterpret_cast(Offsets::FUN_CAMERA_SET_DEVICE_TRANSFORMS)(camera, rect, 0); + } else { + const float point[2] = {rect[1], rect[0]}; + reinterpret_cast(Offsets::FUN_SETUP_ORTHO_TRANSFORMS)(rect, point, 0); + } + auto toNdc = reinterpret_cast(Offsets::FUN_COORD_DDC_TO_NDC); + toNdc(&rect[1], &rect[0], rect[1], rect[0]); + toNdc(&rect[3], &rect[2], rect[3], rect[2]); + for (float &edge : rect) + edge = ClampUnit(edge); + const float epsilon = Game::Read(Offsets::VAR_HAS_RANGE_EPSILON); // 2^-22 + if (!(std::fabs(rect[1] - rect[3]) < epsilon) && !(std::fabs(rect[0] - rect[2]) < epsilon)) { + reinterpret_cast(Offsets::FUN_GX_SET_VIEWPORT)( + rect[1] * vp[1], rect[3] * vp[1], rect[0] * vp[3], rect[2] * vp[3], 0.0f, 1.0f); + reinterpret_cast(Offsets::FUN_GX_CLEAR)(2); + PlaceActors(frame); + void *scene = Model::Pane::Scene(frame); + M2::AnimateScene(scene, eye); + auto draw = reinterpret_cast(Offsets::FUN_M2SCENE_DRAW); + draw(scene, 0); + draw(scene, 1); + } + reinterpret_cast(Offsets::FUN_GX_SET_PROJECTION)(projection); + reinterpret_cast(Offsets::FUN_GX_SET_VIEW)(view); + reinterpret_cast(Offsets::FUN_GX_SET_VIEWPORT)(vp[0], vp[1], vp[2], vp[3], vp[4], + vp[5]); +} + +// ---- the overrides ----------------------------------------------------------------- + +using DeletingDestructor_t = void *(__fastcall *)(void *self, void *edx, uint32_t flags); +using GetScriptMethod_t = int(__fastcall *)(void *self, void *edx, void *L, const char *name); +using IsA_t = bool(__fastcall *)(void *self, void *edx, int typeId); +using IsObjectType_t = bool(__fastcall *)(void *self, void *edx, const char *name); +using SetFrameAlpha_t = void(__fastcall *)(void *self, void *edx, uint8_t alpha); +using OnFrameUpdate_t = void(__fastcall *)(void *self, void *edx, float elapsedSec); +using EmitLayer_t = void(__fastcall *)(void *self, void *edx, void *batch, int layer); +using Callback_t = void(__fastcall *)(void *arg); +using AddCallback_t = void(__fastcall *)(void *batch, void *edx, Callback_t fn, void *arg); + +Frame::Subclass::VTable g_vtable; +Frame::Subclass::VTable g_layoutVtable; +Frame::Subclass::MethodHash g_hash; +int g_typeId = 0; + +uintptr_t TypeIdVar() { return reinterpret_cast(&g_typeId); } + +template +Fn ModelBase(uintptr_t slot) { + return Frame::Subclass::Slot(Offsets::VTBL_SIMPLEMODEL, slot); +} +template +Fn FrameBase(uintptr_t slot) { + return Frame::Subclass::Slot(Offsets::VTBL_SIMPLEFRAME, slot); +} + +void *__fastcall DeletingDestructor(void *self, void *, uint32_t flags) { + Fields &f = F(self); + for (Actor *actor : *f.actors) + delete actor; + delete f.actors; + f.actors = nullptr; + return ModelBase(Offsets::VTBL_FRAME_DELETING_DESTRUCTOR)(self, nullptr, + flags); +} + +void *__fastcall LayoutDeletingDestructor(void *layout, void *, uint32_t flags) { + return DeletingDestructor(FrameOfLayout(layout), nullptr, flags); +} + +int __fastcall GetScriptMethod(void *self, void *, void *L, const char *name) { + if (g_hash.PushMethod(L, name)) + return 1; + return FrameBase(Offsets::VTBL_FRAME_GET_SCRIPT_METHOD)(self, nullptr, L, + name); +} + +bool __fastcall IsA(void *self, void *, int typeId) { + return (g_typeId != 0 && typeId == g_typeId) || + FrameBase(Offsets::VTBL_FRAME_IS_A)(self, nullptr, typeId); +} + +bool __fastcall IsObjectType(void *self, void *, const char *name) { + return (name != nullptr && Game::StrCmpI(name, "ModelScene") == 0) || + FrameBase(Offsets::VTBL_FRAME_IS_OBJECT_TYPE)(self, nullptr, name); +} + +const char *__fastcall GetObjectType(void *, void *) { return "ModelScene"; } + +void __fastcall SetFrameAlpha(void *self, void *, uint8_t alpha) { + ModelBase(Offsets::VTBL_FRAME_SET_FRAME_ALPHA)(self, nullptr, alpha); + for (Actor *actor : *F(self).actors) + actor->ApplyAlpha(); +} + +void __fastcall OnFrameUpdate(void *self, void *, float elapsedSec) { + ModelBase(Offsets::VTBL_FRAME_ON_FRAME_UPDATE)(self, nullptr, elapsedSec); + // By index: an actor's script may create another. + std::vector &actors = *F(self).actors; + for (size_t i = 0; i < actors.size(); ++i) + actors[i]->Update(elapsedSec); +} + +void __fastcall EmitLayer(void *self, void *, void *batch, int layer) { + ModelBase(Offsets::VTBL_FRAME_EMIT_LAYER)(self, nullptr, batch, layer); + if (layer == F(self).drawLayer) + reinterpret_cast(Offsets::FUN_RENDERBATCH_ADD_CALLBACK)(batch, nullptr, + &Paint, self); +} + +void __fastcall UpdateModel(void *self) { PlaceActors(self); } + +void BuildVTables() { + if (g_vtable.Built()) + return; + g_vtable.CopyFrom(Offsets::VTBL_SIMPLEMODEL); + g_layoutVtable.CopyFrom(Offsets::VTBL_SIMPLEMODEL_LAYOUT); + auto fn = [](auto f) { return reinterpret_cast(f); }; + g_vtable.Set(Offsets::VTBL_FRAME_DELETING_DESTRUCTOR, fn(&DeletingDestructor)); + g_vtable.Set(Offsets::VTBL_FRAME_GET_SCRIPT_METHOD, fn(&GetScriptMethod)); + g_vtable.Set(Offsets::VTBL_FRAME_SCRIPT_RESOLVER, + FrameBase(Offsets::VTBL_FRAME_SCRIPT_RESOLVER)); + g_vtable.Set(Offsets::VTBL_FRAME_IS_A, fn(&IsA)); + g_vtable.Set(Offsets::VTBL_FRAME_IS_OBJECT_TYPE, fn(&IsObjectType)); + g_vtable.Set(Offsets::VTBL_FRAME_GET_OBJECT_TYPE, fn(&GetObjectType)); + g_vtable.Set(Offsets::VTBL_FRAME_SET_FRAME_ALPHA, fn(&SetFrameAlpha)); + g_vtable.Set(Offsets::VTBL_FRAME_ON_FRAME_UPDATE, fn(&OnFrameUpdate)); + g_vtable.Set(Offsets::VTBL_FRAME_EMIT_LAYER, fn(&EmitLayer)); + g_vtable.Set(Offsets::VTBL_SIMPLEMODEL_UPDATE_MODEL, fn(&UpdateModel)); + g_layoutVtable.Set(Offsets::VTBL_LAYOUT_DELETING_DESTRUCTOR, fn(&LayoutDeletingDestructor)); + g_layoutVtable.Set(Offsets::VTBL_XML_NODE_LOADER, + Frame::Subclass::Slot(Offsets::VTBL_SIMPLEFRAME_LAYOUT, + Offsets::VTBL_XML_NODE_LOADER)); +} + +// The "ModelScene" factory, shaped like the engine's "Model" one (0x006EECF0). +void *__fastcall CreateModelScene(void *parent) { + using SMemAlloc_t = void *(__stdcall *)(size_t size, const char *file, int line, int flags); + using Constructor_t = void(__fastcall *)(void *self, void *edx, void *parent); + BuildVTables(); + void *frame = reinterpret_cast(Offsets::FUN_STORM_SMEM_ALLOC)( + kObjectSize, __FILE__, __LINE__, 0x08); + if (frame == nullptr) + return nullptr; + reinterpret_cast(Offsets::FUN_SIMPLEMODEL_CONSTRUCTOR)(frame, nullptr, parent); + Game::Ref(frame, 0) = g_vtable.slots; + Game::Ref(frame, Offsets::OFF_FRAME_LAYOUT_SUBOBJECT) = g_layoutVtable.slots; + Fields &f = F(frame); + f.actors = new std::vector; + f.position = {0.0f, 0.0f, 0.0f}; + SetOrientation(f, 0.0f, 0.0f, 0.0f); + f.fieldOfView = kDefaultFieldOfView; + f.nearClip = kDefaultNearClip; + f.farClip = kDefaultFarClip; + f.drawLayer = Offsets::DRAWLAYER_ARTWORK; + InitLight(frame); + InstallCamera(frame); + return frame; +} + +// ---- the methods ------------------------------------------------------------------ + +void *Self(void *L) { return Game::Lua::ResolveTypedObject(L, 1, TypeIdVar()); } + +bool NumberArgs(void *L, int first, int count, void *frame, const char *usage) { + for (int i = 0; i < count; ++i) { + if (!Game::Lua::IsNumber(L, first + i)) { + Game::Lua::Error(L, "Usage: %s:%s", Game::Lua::ObjectDisplayName(frame), usage); + return false; + } + } + return true; +} + +float FloatArg(void *L, int index) { return static_cast(Game::Lua::ToNumber(L, index)); } + +int PushVec3(void *L, const Vec3 &v) { + Game::Lua::PushNumber(L, v.x); + Game::Lua::PushNumber(L, v.y); + Game::Lua::PushNumber(L, v.z); + return 3; +} + +Vec3 Vec3Args(void *L, int first) { + return {FloatArg(L, first), FloatArg(L, first + 1), FloatArg(L, first + 2)}; +} + +int __fastcall Script_CreateActor(void *L) { + void *frame = Self(L); + if (frame == nullptr) + return 0; + const char *name = Game::Lua::IsString(L, 2) ? Game::Lua::ToString(L, 2) : nullptr; + if (Game::Lua::IsString(L, 3)) { + // Actor templates are XML; no loads yet. + Game::Lua::Error(L, "%s:CreateActor(): Couldn't find inherited node \"%s\"", + Game::Lua::ObjectDisplayName(frame), Game::Lua::ToString(L, 3)); + return 0; + } + Actor *actor = new Actor(frame, name); + F(frame).actors->push_back(actor); + Animation::Push(L, actor); + return 1; +} + +int __fastcall Script_GetNumActors(void *L) { + void *frame = Self(L); + if (frame == nullptr) + return 0; + Game::Lua::PushNumber(L, static_cast(F(frame).actors->size())); + return 1; +} + +int __fastcall Script_GetActorAtIndex(void *L) { + void *frame = Self(L); + if (frame == nullptr || !NumberArgs(L, 2, 1, frame, "GetActorAtIndex(index)")) + return 0; + const std::vector &actors = *F(frame).actors; + const double index = Game::Lua::ToNumber(L, 2); + if (!(index >= 1.0 && index <= static_cast(actors.size()))) + return 0; + Animation::Push(L, actors[static_cast(index) - 1]); + return 1; +} + +int __fastcall Script_SetCameraPosition(void *L) { + void *frame = Self(L); + if (frame == nullptr || !NumberArgs(L, 2, 3, frame, "SetCameraPosition(x, y, z)")) + return 0; + F(frame).position = Vec3Args(L, 2); + ApplyCamera(frame); + return 0; +} + +int __fastcall Script_GetCameraPosition(void *L) { + void *frame = Self(L); + return frame != nullptr ? PushVec3(L, F(frame).position) : 0; +} + +int __fastcall Script_SetCameraOrientationByYawPitchRoll(void *L) { + void *frame = Self(L); + if (frame == nullptr || + !NumberArgs(L, 2, 3, frame, "SetCameraOrientationByYawPitchRoll(yaw, pitch, roll)")) + return 0; + SetOrientation(F(frame), FloatArg(L, 2), FloatArg(L, 3), FloatArg(L, 4)); + ApplyCamera(frame); + return 0; +} + +int __fastcall Script_SetCameraOrientationByAxisVectors(void *L) { + void *frame = Self(L); + if (frame == nullptr || + !NumberArgs(L, 2, 9, frame, + "SetCameraOrientationByAxisVectors(forwardX, forwardY, forwardZ, rightX, " + "rightY, rightZ, upX, upY, upZ)")) + return 0; + Fields &f = F(frame); + f.forward = Vec3Args(L, 2); + f.right = Vec3Args(L, 5); + f.up = Vec3Args(L, 8); + ApplyCamera(frame); + return 0; +} + +int __fastcall Script_GetCameraForward(void *L) { + void *frame = Self(L); + return frame != nullptr ? PushVec3(L, F(frame).forward) : 0; +} + +int __fastcall Script_GetCameraRight(void *L) { + void *frame = Self(L); + return frame != nullptr ? PushVec3(L, F(frame).right) : 0; +} + +int __fastcall Script_GetCameraUp(void *L) { + void *frame = Self(L); + return frame != nullptr ? PushVec3(L, F(frame).up) : 0; +} + +// The one-number camera setters and getters. +constexpr char kSetFieldOfView[] = "SetCameraFieldOfView(fov)"; +constexpr char kSetNearClip[] = "SetCameraNearClip(nearClip)"; +constexpr char kSetFarClip[] = "SetCameraFarClip(farClip)"; + +template +int __fastcall SetCameraScalar(void *L) { + void *frame = Self(L); + if (frame == nullptr || !NumberArgs(L, 2, 1, frame, Usage)) + return 0; + F(frame).*Field = FloatArg(L, 2); + ApplyCamera(frame); + return 0; +} + +template +int __fastcall GetCameraScalar(void *L) { + void *frame = Self(L); + if (frame == nullptr) + return 0; + Game::Lua::PushNumber(L, F(frame).*Field); + return 1; +} + +const Game::Lua::FrameMethodEntry g_methods[] = { + {"CreateActor", &Script_CreateActor}, + {"GetNumActors", &Script_GetNumActors}, + {"GetActorAtIndex", &Script_GetActorAtIndex}, + {"SetCameraPosition", &Script_SetCameraPosition}, + {"GetCameraPosition", &Script_GetCameraPosition}, + {"SetCameraOrientationByYawPitchRoll", &Script_SetCameraOrientationByYawPitchRoll}, + {"SetCameraOrientationByAxisVectors", &Script_SetCameraOrientationByAxisVectors}, + {"GetCameraForward", &Script_GetCameraForward}, + {"GetCameraRight", &Script_GetCameraRight}, + {"GetCameraUp", &Script_GetCameraUp}, + {"SetCameraFieldOfView", &SetCameraScalar<&Fields::fieldOfView, kSetFieldOfView>}, + {"GetCameraFieldOfView", &GetCameraScalar<&Fields::fieldOfView>}, + {"SetCameraNearClip", &SetCameraScalar<&Fields::nearClip, kSetNearClip>}, + {"GetCameraNearClip", &GetCameraScalar<&Fields::nearClip>}, + {"SetCameraFarClip", &SetCameraScalar<&Fields::farClip, kSetFarClip>}, + {"GetCameraFarClip", &GetCameraScalar<&Fields::farClip>}, +}; + +// ---- documentation -------------------------------------------------------------- + +using Game::Doc::Opt; +using Game::Doc::Req; + +const Game::Doc::Field kCreateActorArgs[] = { + Opt("name", "cstring", nullptr, "A global name for the actor; \"$parent\" stands for the scene's."), + Opt("template", "cstring"), +}; +const Game::Doc::Field kActorRet[] = {Req("actor", "ModelSceneFrameActor")}; +const Game::Doc::Field kNumActorsRet[] = {Req("numActors", "number")}; +const Game::Doc::Field kIndexArg[] = {Req("index", "luaIndex")}; +const Game::Doc::Field kPositionArgs[] = {Req("positionX", "number"), Req("positionY", "number"), + Req("positionZ", "number")}; +const Game::Doc::Field kPositionRets[] = {Req("positionX", "number"), Req("positionY", "number"), + Req("positionZ", "number")}; +const Game::Doc::Field kYawPitchRollArgs[] = { + Req("yaw", "number", "Radians about the up axis."), + Req("pitch", "number", "Radians; positive looks down."), + Req("roll", "number", "Radians about the forward axis."), +}; +const Game::Doc::Field kAxisArgs[] = { + Req("forwardX", "number"), Req("forwardY", "number"), Req("forwardZ", "number"), + Req("rightX", "number"), Req("rightY", "number"), Req("rightZ", "number"), + Req("upX", "number"), Req("upY", "number"), Req("upZ", "number"), +}; +const Game::Doc::Field kForwardRets[] = {Req("forwardX", "number"), Req("forwardY", "number"), + Req("forwardZ", "number")}; +const Game::Doc::Field kRightRets[] = {Req("rightX", "number"), Req("rightY", "number"), + Req("rightZ", "number")}; +const Game::Doc::Field kUpRets[] = {Req("upX", "number"), Req("upY", "number"), + Req("upZ", "number")}; +const Game::Doc::Field kFovArg[] = {Req("fov", "number", "Radians.")}; +const Game::Doc::Field kFovRet[] = {Req("fov", "number")}; +const Game::Doc::Field kNearArg[] = {Req("nearClip", "number")}; +const Game::Doc::Field kNearRet[] = {Req("nearClip", "number")}; +const Game::Doc::Field kFarArg[] = {Req("farClip", "number")}; +const Game::Doc::Field kFarRet[] = {Req("farClip", "number")}; + +const Game::Doc::Function kCreateActor{"Adds an actor to the scene.", kCreateActorArgs, kActorRet}; +const Game::Doc::Function kGetNumActors{"Returns how many actors the scene has.", {}, + kNumActorsRet}; +const Game::Doc::Function kGetActorAtIndex{"Returns an actor, in creation order.", kIndexArg, + kActorRet}; +const Game::Doc::Function kSetCameraPosition{"Moves the camera.", kPositionArgs, {}}; +const Game::Doc::Function kGetCameraPosition{"Returns where the camera is.", {}, kPositionRets}; +const Game::Doc::Function kSetCameraOrientationByYawPitchRoll{ + "Points the camera by yaw, pitch and roll.", kYawPitchRollArgs, {}}; +const Game::Doc::Function kSetCameraOrientationByAxisVectors{ + "Points the camera by its forward, right and up axes.", kAxisArgs, {}}; +const Game::Doc::Function kGetCameraForward{"Returns the direction the camera looks.", {}, + kForwardRets}; +const Game::Doc::Function kGetCameraRight{"Returns the camera's right axis.", {}, kRightRets}; +const Game::Doc::Function kGetCameraUp{"Returns the camera's up axis.", {}, kUpRets}; +const Game::Doc::Function kSetCameraFieldOfView{"Sets the camera's field of view.", kFovArg, {}}; +const Game::Doc::Function kGetCameraFieldOfView{"Returns the camera's field of view.", {}, + kFovRet}; +const Game::Doc::Function kSetCameraNearClip{"Sets the nearest distance the camera draws.", + kNearArg, {}}; +const Game::Doc::Function kGetCameraNearClip{"Returns the nearest distance the camera draws.", {}, + kNearRet}; +const Game::Doc::Function kSetCameraFarClip{"Sets the farthest distance the camera draws.", + kFarArg, {}}; +const Game::Doc::Function kGetCameraFarClip{"Returns the farthest distance the camera draws.", {}, + kFarRet}; + +const Game::Doc::Method g_methodDocs[] = { + {"CreateActor", &kCreateActor}, + {"GetNumActors", &kGetNumActors}, + {"GetActorAtIndex", &kGetActorAtIndex}, + {"SetCameraPosition", &kSetCameraPosition}, + {"GetCameraPosition", &kGetCameraPosition}, + {"SetCameraOrientationByYawPitchRoll", &kSetCameraOrientationByYawPitchRoll}, + {"SetCameraOrientationByAxisVectors", &kSetCameraOrientationByAxisVectors}, + {"GetCameraForward", &kGetCameraForward}, + {"GetCameraRight", &kGetCameraRight}, + {"GetCameraUp", &kGetCameraUp}, + {"SetCameraFieldOfView", &kSetCameraFieldOfView}, + {"GetCameraFieldOfView", &kGetCameraFieldOfView}, + {"SetCameraNearClip", &kSetCameraNearClip}, + {"GetCameraNearClip", &kGetCameraNearClip}, + {"SetCameraFarClip", &kSetCameraFarClip}, + {"GetCameraFarClip", &kGetCameraFarClip}, +}; + +void RegisterLuaFunctions() { + using RegisterFactory_t = int(__fastcall *)(const char *type, void *(__fastcall *)(void *), + int unique); + // The engine's frame-type table outlives the Lua state, so on a /reload + // the name is already there and the registrar keeps the first one. + reinterpret_cast(Offsets::FUN_FRAMEXML_REGISTER_FACTORY)( + "ModelScene", &CreateModelScene, 0); + Api::Documentation::NameWidgetSystem(g_hash.Registry(), "FrameAPIModelSceneFrame"); + Game::Lua::RegisterFrameMethods(g_hash.Registry(), g_methods, g_methodDocs); + RegisterActorClass(); +} + +const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions}; + +} // namespace + +} // namespace Model::Scene diff --git a/src/model/Scene.h b/src/model/Scene.h new file mode 100644 index 00000000..1583ca6d --- /dev/null +++ b/src/model/Scene.h @@ -0,0 +1,72 @@ +// This file is part of ClassicAPI. +// +// ClassicAPI is free software: you can redistribute it and/or modify it under the terms +// of the GNU General Public License as published by the Free Software Foundation, either +// version 3 of the License, or (at your option) any later version. +// +// ClassicAPI is distributed in the hope that it will be useful, but WITHOUT ANY +// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +// PURPOSE. See the GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along with +// ClassicAPI. If not, see . + +#pragma once + +#include "animation/Object.h" + +#include +#include + +// The ModelScene frame (model/Scene.cpp) and its actors (model/SceneActor.cpp). +// docs/notes/model-scene.md has the plan, the retail contract and the probes. +namespace Model::Scene { + +// A ModelSceneActor: one model in its scene frame's M2 scene, placed by the +// scene's paint. A script object (Animation::Object) whose parent is the scene +// frame, which owns it. +class Actor : public Animation::Object { + public: + static Animation::Class s_class; + + Actor(void *scene, const char *name); + ~Actor(); + + void *SceneFrame() const { return parent; } + + // From the scene frame's update walk: load and dress state, scripts. + void Update(float elapsedSec); + // From the scene's paint, before the scene animates: the model's + // placement matrix. + void Place(); + // The scene frame's alpha changed. + void ApplyAlpha(); + + // Shows `model` (one reference, which the actor takes over), or nothing. + void SetModel(void *model, const char *path, const uint8_t *dressRecord); + void ClearModel(); + void PlayAnimation(); + + void *model = nullptr; + std::string modelPath; + const uint8_t *dressRecord = nullptr; // CreatureDisplayInfoExtra, until dressed + void *dresser = nullptr; + bool loaded = false; // OnModelLoaded has run for the model + bool animFinished = false; + + float position[3] = {0.0f, 0.0f, 0.0f}; + float yaw = 0.0f, pitch = 0.0f, roll = 0.0f; + float scale = 1.0f; + float alpha = 1.0f; + bool shown = true; + bool useCenterForOrigin[3] = {false, false, false}; + uint32_t animation = 0; + int variation = -1; + float animSpeed = 1.0f; + float animOffsetSec = 0.0f; +}; + +// Registers the actor class in the current Lua state. +void RegisterActorClass(); + +} // namespace Model::Scene diff --git a/src/model/SceneActor.cpp b/src/model/SceneActor.cpp new file mode 100644 index 00000000..4f90f6f8 --- /dev/null +++ b/src/model/SceneActor.cpp @@ -0,0 +1,631 @@ +// This file is part of ClassicAPI. +// +// ClassicAPI is free software: you can redistribute it and/or modify it under the terms +// of the GNU General Public License as published by the Free Software Foundation, either +// version 3 of the License, or (at your option) any later version. +// +// ClassicAPI is distributed in the hope that it will be useful, but WITHOUT ANY +// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +// PURPOSE. See the GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along with +// ClassicAPI. If not, see . + +// `ModelSceneActor`: one model in a ModelScene (FrameAPIModelSceneFrameActorBase- +// Documentation.lua's contract, defaults from the retail probe in +// docs/notes/model-scene.md). +// +// An actor is a script object (Animation::Object) holding one CM2Model in its +// scene frame's own M2 scene (FUN_SIMPLEMODEL_GET_SCENE). The model is built +// the way a Model frame builds its own and lit by the frame's light the same +// way: SetModelInstance (0x0076CD30) gives its model the frame's alpha, the +// done callback and the light/fog callback with the frame as user data, and +// the actor does the same for each of its models. The frame's clock +// (0x0076D7F0) links a ready model into the scene's animate list and makes it +// visible; the actor does that from the scene's update for its own. The +// scene's paint places every actor (Place) where a Model frame rebuilds its one +// root transform (slot 0x98), with CM2Model::SetBaseTransformTRS, so the +// placement is the engine's: scale, then rotate, then translate. +// +// - Scale is the actor's own: the scene's projection already scales the +// picture with the frame (model-scene.md A6), so the Model frame's +// root-scale factors are not applied. +// - Yaw turns about +Z, the axis SetBaseTransformTRS rotates a Model's +// facing about. Pitch (about +Y) and roll (about +X) follow it in that +// order; no retail scene this DLL embeds uses either, and the order is not +// probed. +// - useCenterForOrigin moves the model so the centre of its active bounding +// box on that axis is at the actor's position, before the scale and the +// rotation. +// - The active bounding box is the current animation's sequence bounds and +// the max one the model's overall bounds (MD20 +0xB4), both in model space: +// the retail probe saw the active box change with the animation and +// neither move with the actor. +// +// Loading, dressing and the scripts run from the scene frame's update walk, +// where the engine runs OnUpdate, never from the paint or an engine callback: +// the load is polled (IsLoaded), and the done callback only sets a flag. +// A creature display with a CreatureDisplayInfoExtra record is dressed through +// the engine compositor once it loads, as Model::DisplayInfo dresses a +// PlayerModel; OnModelLoaded runs once it is dressed. A finished animation +// plays again (an actor keeps its animation, as PlayerModel re-arms Stand) +// after OnAnimFinished. + +#include "model/Scene.h" + +#include "Game.h" +#include "Offsets.h" +#include "api/Documentation.h" +#include "model/DisplayInfo.h" +#include "model/M2.h" + +#include +#include + +namespace Model::Scene { + +namespace { + +// Script indexes (kScripts order). +enum ActorScript { S_ONLOAD, S_ONUPDATE, S_ONMODELCLEARED, S_ONMODELLOADING, S_ONMODELLOADED, + S_ONANIMFINISHED }; +const char *const kScripts[] = {"onload", "onupdate", "onmodelcleared", + "onmodelloading", "onmodelloaded", "onanimfinished"}; + +// The engine's done callback: a whole sequence ended (reason 0) — the test +// the Model frame's own (0x0076CDC0) makes before it runs OnAnimFinished. +void __fastcall OnAnimDone(void * /*model*/, uint32_t /*keyBone*/, uint32_t /*animID*/, + uint32_t reason, uint32_t /*overshoot*/, uint32_t userLow, + uint32_t /*userHigh*/) { + if (reason == 0) + reinterpret_cast(static_cast(userLow))->animFinished = true; +} + +// Releases the model without scripts (a destroyed actor runs none). +void ReleaseModel(Actor &actor) { + if (actor.model == nullptr) + return; + M2::SetAnimDoneCallback(actor.model, nullptr, 0, 0); + M2::SetVisible(actor.model, false); + Model::DisplayInfo::DestroyDresser(actor.dresser); + M2::Release(actor.model); + actor.model = nullptr; + actor.dresser = nullptr; + actor.dressRecord = nullptr; + actor.loaded = false; + actor.animFinished = false; + actor.modelPath.clear(); +} + +} // namespace + +Actor::Actor(void *scene, const char *name) : Object(s_class, scene, name) {} + +Actor::~Actor() { ReleaseModel(*this); } + +void Actor::SetModel(void *newModel, const char *path, const uint8_t *newDressRecord) { + ClearModel(); + if (newModel == nullptr) + return; + model = newModel; + modelPath = path != nullptr ? path : ""; + dressRecord = newDressRecord; + const auto user = static_cast(reinterpret_cast(this)); + M2::SetAnimDoneCallback(model, reinterpret_cast(&OnAnimDone), user, 0); + M2::SetRenderCallback(model, reinterpret_cast(Offsets::FUN_SIMPLEMODELFFX_LIGHT_FOG_CB), + SceneFrame()); + ApplyAlpha(); + PlayAnimation(); + RunScript(S_ONMODELLOADING, 0); +} + +void Actor::ClearModel() { + if (model == nullptr) + return; + ReleaseModel(*this); + RunScript(S_ONMODELCLEARED, 0); +} + +void Actor::PlayAnimation() { + if (model == nullptr) + return; + const int offsetMs = static_cast(animOffsetSec * 1000.0f); + M2::PlayAnimation(model, -1, animation, variation, offsetMs, animSpeed, 1, 1); +} + +void Actor::ApplyAlpha() { + if (model == nullptr) + return; + const float frameAlpha = Game::Read(SceneFrame(), Offsets::OFF_FRAME_ALPHA) / 255.0f; + M2::SetAlpha(model, alpha * frameAlpha); +} + +void Actor::Update(float elapsedSec) { + if (model != nullptr && !loaded) { + bool ready = M2::IsLoaded(model, 0, 0); + if (ready && dressRecord != nullptr) { + if (dresser == nullptr) { + // A dress the engine rejects shows the model undressed, as a + // unit with no compositor shows. + dresser = Model::DisplayInfo::CreateDresser(model, dressRecord); + if (dresser == nullptr) + dressRecord = nullptr; + else + Model::DisplayInfo::LightChildren(SceneFrame(), model); + } + if (dresser != nullptr && !Model::DisplayInfo::PumpDresser(dresser)) + ready = false; + } + if (ready && M2::IsLoaded(model, 0, 1)) { + loaded = true; + RunScript(S_ONMODELLOADED, 0); + } + } + if (model != nullptr && M2::IsReady(model, 0, 1)) { + M2::SetAnimated(model, true); + M2::SetVisible(model, shown); + } + if (model != nullptr && animFinished) { + animFinished = false; + PlayAnimation(); + RunScript(S_ONANIMFINISHED, 0); + } + if (HasScript(S_ONUPDATE)) { + void *L = Game::Lua::State(); + if (L != nullptr) { + Game::Lua::PushNumber(L, elapsedSec); + RunScript(S_ONUPDATE, 1); + } + } +} + +void Actor::Place() { + if (model == nullptr || M2::Parent(model) != nullptr) + return; + using SetTRS_t = void(__thiscall *)(void *model, const float *pos, float angle, + const float *axis, const float *scale); + using Rotate_t = void(__thiscall *)(float *m, float angle, const float *axis, int); + using Translate_t = void(__thiscall *)(float *m, const float *t); + const float axisX[3] = {1.0f, 0.0f, 0.0f}; + const float axisY[3] = {0.0f, 1.0f, 0.0f}; + const float axisZ[3] = {0.0f, 0.0f, 1.0f}; + const float scales[3] = {scale, scale, scale}; + reinterpret_cast(Offsets::FUN_M2MODEL_SET_BASE_TRS)(model, position, yaw, axisZ, + scales); + float *matrix = Game::Ptr(model, Offsets::OFF_M2MODEL_BASE_MATRIX); + auto rotate = reinterpret_cast(Offsets::FUN_MATRIX_ROTATE); + if (pitch != 0.0f) + rotate(matrix, pitch, axisY, 1); + if (roll != 0.0f) + rotate(matrix, roll, axisX, 1); + if (!loaded || !(useCenterForOrigin[0] || useCenterForOrigin[1] || useCenterForOrigin[2])) + return; + float box[6]; + M2::GetSequenceBounds(model, animation, variation < 0 ? 0u : static_cast(variation), + box); + float offset[3]; + for (int i = 0; i < 3; ++i) + offset[i] = useCenterForOrigin[i] ? -(box[i] + box[i + 3]) * 0.5f : 0.0f; + reinterpret_cast(Offsets::FUN_MATRIX_TRANSLATE)(matrix, offset); +} + +// ---- the methods --------------------------------------------------------------- + +namespace { + +Actor *Self(void *L) { return static_cast(Animation::Resolve(L, 1, Actor::s_class)); } + +bool NumberArgs(void *L, int first, int count, const char *usage, const Actor *actor) { + for (int i = 0; i < count; ++i) { + if (!Game::Lua::IsNumber(L, first + i)) { + Game::Lua::Error(L, "Usage: %s:%s", actor->DisplayName(), usage); + return false; + } + } + return true; +} + +float FloatArg(void *L, int index) { return static_cast(Game::Lua::ToNumber(L, index)); } + +int __fastcall Script_SetModelByCreatureDisplayID(void *L) { + Actor *actor = Self(L); + if (actor == nullptr || + !NumberArgs(L, 2, 1, "SetModelByCreatureDisplayID(creatureDisplayID)", actor)) + return 0; + const auto displayID = static_cast(Game::Lua::ToNumber(L, 2)); + const char *path = nullptr; + void *model = Model::DisplayInfo::CreateDisplayModel(Model::Pane::Scene(actor->SceneFrame()), + displayID, &path); + actor->SetModel(model, path, Model::DisplayInfo::DressRecord(displayID)); + Game::Lua::PushBool(L, model != nullptr); + return 1; +} + +int __fastcall Script_SetModelByPath(void *L) { + Actor *actor = Self(L); + if (actor == nullptr) + return 0; + if (!Game::Lua::IsString(L, 2)) { + Game::Lua::Error(L, "Usage: %s:SetModelByPath(asset)", actor->DisplayName()); + return 0; + } + const char *path = Game::Lua::ToString(L, 2); + void *model = M2::CreateModel(Model::Pane::Scene(actor->SceneFrame()), path); + actor->SetModel(model, path, nullptr); + Game::Lua::PushBool(L, model != nullptr); + return 1; +} + +int __fastcall Script_ClearModel(void *L) { + if (Actor *actor = Self(L)) + actor->ClearModel(); + return 0; +} + +int __fastcall Script_IsLoaded(void *L) { + Actor *actor = Self(L); + if (actor == nullptr) + return 0; + Game::Lua::PushBool(L, actor->loaded); + return 1; +} + +int __fastcall Script_GetModelPath(void *L) { + Actor *actor = Self(L); + if (actor == nullptr) + return 0; + Game::Lua::PushString(L, actor->modelPath.c_str()); + return 1; +} + +int __fastcall Script_SetPosition(void *L) { + Actor *actor = Self(L); + if (actor == nullptr || !NumberArgs(L, 2, 3, "SetPosition(x, y, z)", actor)) + return 0; + for (int i = 0; i < 3; ++i) + actor->position[i] = FloatArg(L, 2 + i); + return 0; +} + +int __fastcall Script_GetPosition(void *L) { + Actor *actor = Self(L); + if (actor == nullptr) + return 0; + for (float v : actor->position) + Game::Lua::PushNumber(L, v); + return 3; +} + +// The one-number setters and getters. +constexpr char kUsageSetYaw[] = "SetYaw(yaw)"; +constexpr char kUsageSetPitch[] = "SetPitch(pitch)"; +constexpr char kUsageSetRoll[] = "SetRoll(roll)"; +constexpr char kUsageSetScale[] = "SetScale(scale)"; + +template +int __fastcall SetFloat(void *L) { + Actor *actor = Self(L); + if (actor == nullptr || !NumberArgs(L, 2, 1, Usage, actor)) + return 0; + actor->*Field = FloatArg(L, 2); + return 0; +} + +template +int __fastcall GetFloat(void *L) { + Actor *actor = Self(L); + if (actor == nullptr) + return 0; + Game::Lua::PushNumber(L, actor->*Field); + return 1; +} + +int __fastcall Script_SetAlpha(void *L) { + Actor *actor = Self(L); + if (actor == nullptr || !NumberArgs(L, 2, 1, "SetAlpha(alpha)", actor)) + return 0; + const float a = FloatArg(L, 2); + actor->alpha = a < 0.0f ? 0.0f : (a > 1.0f ? 1.0f : a); + actor->ApplyAlpha(); + return 0; +} + +int __fastcall Script_SetUseCenterForOrigin(void *L) { + Actor *actor = Self(L); + if (actor == nullptr) + return 0; + for (int i = 0; i < 3; ++i) + actor->useCenterForOrigin[i] = Game::Lua::ToBoolean(L, 2 + i) != 0; + return 0; +} + +int __fastcall Script_IsUsingCenterForOrigin(void *L) { + Actor *actor = Self(L); + if (actor == nullptr) + return 0; + for (bool b : actor->useCenterForOrigin) + Game::Lua::PushBool(L, b); + return 3; +} + +void SetShown(Actor &actor, bool shown) { + actor.shown = shown; + if (actor.model != nullptr && !shown) + M2::SetVisible(actor.model, false); +} + +int __fastcall Script_Show(void *L) { + if (Actor *actor = Self(L)) + SetShown(*actor, true); + return 0; +} + +int __fastcall Script_Hide(void *L) { + if (Actor *actor = Self(L)) + SetShown(*actor, false); + return 0; +} + +int __fastcall Script_SetShown(void *L) { + if (Actor *actor = Self(L)) + SetShown(*actor, Game::Lua::ToBoolean(L, 2) != 0); + return 0; +} + +int __fastcall Script_IsShown(void *L) { + Actor *actor = Self(L); + if (actor == nullptr) + return 0; + Game::Lua::PushBool(L, actor->shown); + return 1; +} + +int __fastcall Script_IsVisible(void *L) { + Actor *actor = Self(L); + if (actor == nullptr) + return 0; + Game::Lua::PushBool(L, actor->shown && Game::Read(actor->SceneFrame(), + Offsets::OFF_FRAME_VISIBLE) != 0); + return 1; +} + +int __fastcall Script_SetAnimation(void *L) { + Actor *actor = Self(L); + if (actor == nullptr || !NumberArgs(L, 2, 1, "SetAnimation(animation [, variation, animSpeed, animOffsetSeconds])", actor)) + return 0; + actor->animation = static_cast(Game::Lua::ToNumber(L, 2)); + actor->variation = Game::Lua::IsNumber(L, 3) ? static_cast(Game::Lua::ToNumber(L, 3)) : -1; + actor->animSpeed = Game::Lua::IsNumber(L, 4) ? FloatArg(L, 4) : 1.0f; + actor->animOffsetSec = Game::Lua::IsNumber(L, 5) ? FloatArg(L, 5) : 0.0f; + actor->PlayAnimation(); + return 0; +} + +int __fastcall Script_GetAnimation(void *L) { + Actor *actor = Self(L); + if (actor == nullptr) + return 0; + Game::Lua::PushNumber(L, actor->animation); + return 1; +} + +// Retail pushes the variation unsigned: -1 reads 4294967295. +int __fastcall Script_GetAnimationVariation(void *L) { + Actor *actor = Self(L); + if (actor == nullptr) + return 0; + Game::Lua::PushNumber(L, static_cast(static_cast(actor->variation))); + return 1; +} + +// Six numbers, bottom x, y, z then top x, y, z (what the retail getters +// return and ModelSceneActorMixin reads); nothing until the model loads. +int PushBox(void *L, const float (&box)[6]) { + for (float v : box) + Game::Lua::PushNumber(L, v); + return 6; +} + +int __fastcall Script_GetActiveBoundingBox(void *L) { + Actor *actor = Self(L); + if (actor == nullptr || !actor->loaded) + return 0; + float box[6]; + M2::GetSequenceBounds(actor->model, actor->animation, + actor->variation < 0 ? 0u : static_cast(actor->variation), box); + return PushBox(L, box); +} + +int __fastcall Script_GetMaxBoundingBox(void *L) { + Actor *actor = Self(L); + if (actor == nullptr || !actor->loaded) + return 0; + float box[6]; + M2::GetBoundingBox(actor->model, box); + return PushBox(L, box); +} + +const Game::Lua::FrameMethodEntry kMethods[] = { + {"GetObjectType", &Animation::Script_GetObjectType}, + {"IsObjectType", &Animation::Script_IsObjectType}, + {"GetName", &Animation::Script_GetName}, + {"GetParent", &Animation::Script_GetParent}, + {"HasScript", &Animation::Script_HasScript}, + {"GetScript", &Animation::Script_GetScript}, + {"SetScript", &Animation::Script_SetScript}, + {"HookScript", &Animation::Script_HookScript}, + {"SetModelByCreatureDisplayID", &Script_SetModelByCreatureDisplayID}, + {"SetModelByPath", &Script_SetModelByPath}, + {"ClearModel", &Script_ClearModel}, + {"IsLoaded", &Script_IsLoaded}, + {"GetModelPath", &Script_GetModelPath}, + {"SetPosition", &Script_SetPosition}, + {"GetPosition", &Script_GetPosition}, + {"SetYaw", &SetFloat<&Actor::yaw, kUsageSetYaw>}, + {"GetYaw", &GetFloat<&Actor::yaw>}, + {"SetPitch", &SetFloat<&Actor::pitch, kUsageSetPitch>}, + {"GetPitch", &GetFloat<&Actor::pitch>}, + {"SetRoll", &SetFloat<&Actor::roll, kUsageSetRoll>}, + {"GetRoll", &GetFloat<&Actor::roll>}, + {"SetScale", &SetFloat<&Actor::scale, kUsageSetScale>}, + {"GetScale", &GetFloat<&Actor::scale>}, + {"SetAlpha", &Script_SetAlpha}, + {"GetAlpha", &GetFloat<&Actor::alpha>}, + {"SetUseCenterForOrigin", &Script_SetUseCenterForOrigin}, + {"IsUsingCenterForOrigin", &Script_IsUsingCenterForOrigin}, + {"Show", &Script_Show}, + {"Hide", &Script_Hide}, + {"SetShown", &Script_SetShown}, + {"IsShown", &Script_IsShown}, + {"IsVisible", &Script_IsVisible}, + {"SetAnimation", &Script_SetAnimation}, + {"GetAnimation", &Script_GetAnimation}, + {"GetAnimationVariation", &Script_GetAnimationVariation}, + {"GetActiveBoundingBox", &Script_GetActiveBoundingBox}, + {"GetMaxBoundingBox", &Script_GetMaxBoundingBox}, +}; + +// ---- documentation -------------------------------------------------------------- + +using Game::Doc::Opt; +using Game::Doc::Req; + +const Game::Doc::Field kDisplayArgs[] = { + Req("creatureDisplayID", "number", "A CreatureDisplayInfo ID."), + Opt("useActivePlayerCustomizations", "bool", "false", "Has no effect."), +}; +const Game::Doc::Field kPathArgs[] = { + Req("asset", "FileAsset", "A model file path."), + Opt("useMips", "bool", "false", "Has no effect."), +}; +const Game::Doc::Field kSuccessRet[] = { + Req("success", "bool", "False when the actor shows no model."), +}; +const Game::Doc::Field kLoadedRet[] = {Req("isLoaded", "bool")}; +const Game::Doc::Field kPathRet[] = {Req("path", "string")}; +const Game::Doc::Field kXYZArgs[] = {Req("positionX", "number"), Req("positionY", "number"), + Req("positionZ", "number")}; +const Game::Doc::Field kXYZRets[] = {Req("positionX", "number"), Req("positionY", "number"), + Req("positionZ", "number")}; +const Game::Doc::Field kYawArg[] = {Req("yaw", "number", "Radians about the up axis.")}; +const Game::Doc::Field kYawRet[] = {Req("yaw", "number")}; +const Game::Doc::Field kPitchArg[] = {Req("pitch", "number", "Radians.")}; +const Game::Doc::Field kPitchRet[] = {Req("pitch", "number")}; +const Game::Doc::Field kRollArg[] = {Req("roll", "number", "Radians.")}; +const Game::Doc::Field kRollRet[] = {Req("roll", "number")}; +const Game::Doc::Field kScaleArg[] = {Req("scale", "number")}; +const Game::Doc::Field kScaleRet[] = {Req("scale", "number")}; +const Game::Doc::Field kAlphaArg[] = {Req("alpha", "number", "0 to 1.")}; +const Game::Doc::Field kAlphaRet[] = {Req("alpha", "number")}; +const Game::Doc::Field kCenterArgs[] = {Opt("x", "bool", "false"), Opt("y", "bool", "false"), + Opt("z", "bool", "false")}; +const Game::Doc::Field kCenterRets[] = {Req("x", "bool"), Req("y", "bool"), Req("z", "bool")}; +const Game::Doc::Field kShowArg[] = {Opt("show", "bool", "false")}; +const Game::Doc::Field kShownRet[] = {Req("isShown", "bool")}; +const Game::Doc::Field kVisibleRet[] = {Req("isVisible", "bool")}; +const Game::Doc::Field kAnimationArgs[] = { + Req("animation", "AnimationDataEnum"), + Opt("variation", "number", nullptr, "Nil plays any variation."), + Opt("animSpeed", "number", "1"), + Opt("animOffsetSeconds", "number", "0"), +}; +const Game::Doc::Field kAnimationRet[] = {Req("animation", "AnimationDataEnum")}; +const Game::Doc::Field kVariationRet[] = { + Req("variation", "number", "4294967295 when any variation plays."), +}; +const Game::Doc::Field kBoxRets[] = { + Req("bottomX", "number"), Req("bottomY", "number"), Req("bottomZ", "number"), + Req("topX", "number"), Req("topY", "number"), Req("topZ", "number"), +}; + +const Game::Doc::Function kSetModelByCreatureDisplayID{ + "Shows a creature display, dressed like the creature.", kDisplayArgs, kSuccessRet}; +const Game::Doc::Function kSetModelByPath{"Shows a model file.", kPathArgs, kSuccessRet}; +const Game::Doc::Function kClearModel{"Removes the model.", {}, {}}; +const Game::Doc::Function kIsLoaded{"Returns whether the model has loaded.", {}, kLoadedRet}; +const Game::Doc::Function kGetModelPath{"Returns the file of the model.", {}, kPathRet}; +const Game::Doc::Function kSetPosition{"Moves the actor in the scene.", kXYZArgs, {}}; +const Game::Doc::Function kGetPosition{"Returns where the actor stands.", {}, kXYZRets}; +const Game::Doc::Function kSetYaw{"Turns the actor about the up axis.", kYawArg, {}}; +const Game::Doc::Function kGetYaw{"Returns the yaw.", {}, kYawRet}; +const Game::Doc::Function kSetPitch{"Tilts the actor.", kPitchArg, {}}; +const Game::Doc::Function kGetPitch{"Returns the pitch.", {}, kPitchRet}; +const Game::Doc::Function kSetRoll{"Rolls the actor.", kRollArg, {}}; +const Game::Doc::Function kGetRoll{"Returns the roll.", {}, kRollRet}; +const Game::Doc::Function kSetScale{"Sets the size.", kScaleArg, {}}; +const Game::Doc::Function kGetScale{"Returns the size.", {}, kScaleRet}; +const Game::Doc::Function kSetAlpha{"Sets the opacity.", kAlphaArg, {}}; +const Game::Doc::Function kGetAlpha{"Returns the opacity.", {}, kAlphaRet}; +const Game::Doc::Function kSetUseCenterForOrigin{ + "Sets on which axes the centre of the model stands at the actor position.", kCenterArgs, + {}}; +const Game::Doc::Function kIsUsingCenterForOrigin{ + "Returns on which axes the centre of the model stands at the actor position.", {}, + kCenterRets}; +const Game::Doc::Function kShow{"Shows the actor.", {}, {}}; +const Game::Doc::Function kHide{"Hides the actor.", {}, {}}; +const Game::Doc::Function kSetShown{"Shows or hides the actor.", kShowArg, {}}; +const Game::Doc::Function kIsShown{"Returns whether the actor is set to show.", {}, kShownRet}; +const Game::Doc::Function kIsVisible{ + "Returns whether the actor is shown and its scene is visible.", {}, kVisibleRet}; +const Game::Doc::Function kSetAnimation{ + "Plays an animation on the actor, again each time it ends.", kAnimationArgs, {}}; +const Game::Doc::Function kGetAnimation{"Returns the animation.", {}, kAnimationRet}; +const Game::Doc::Function kGetAnimationVariation{"Returns the animation variation.", {}, + kVariationRet}; +const Game::Doc::Function kGetActiveBoundingBox{ + "Returns the bounds of the model in its current animation. Nothing until it loads.", {}, + kBoxRets}; +const Game::Doc::Function kGetMaxBoundingBox{ + "Returns the overall bounds of the model. Nothing until it loads.", {}, kBoxRets}; + +const Game::Doc::Method kMethodDocs[] = { + {"SetModelByCreatureDisplayID", &kSetModelByCreatureDisplayID}, + {"SetModelByPath", &kSetModelByPath}, + {"ClearModel", &kClearModel}, + {"IsLoaded", &kIsLoaded}, + {"GetModelPath", &kGetModelPath}, + {"SetPosition", &kSetPosition}, + {"GetPosition", &kGetPosition}, + {"SetYaw", &kSetYaw}, + {"GetYaw", &kGetYaw}, + {"SetPitch", &kSetPitch}, + {"GetPitch", &kGetPitch}, + {"SetRoll", &kSetRoll}, + {"GetRoll", &kGetRoll}, + {"SetScale", &kSetScale}, + {"GetScale", &kGetScale}, + {"SetAlpha", &kSetAlpha}, + {"GetAlpha", &kGetAlpha}, + {"SetUseCenterForOrigin", &kSetUseCenterForOrigin}, + {"IsUsingCenterForOrigin", &kIsUsingCenterForOrigin}, + {"Show", &kShow}, + {"Hide", &kHide}, + {"SetShown", &kSetShown}, + {"IsShown", &kIsShown}, + {"IsVisible", &kIsVisible}, + {"SetAnimation", &kSetAnimation}, + {"GetAnimation", &kGetAnimation}, + {"GetAnimationVariation", &kGetAnimationVariation}, + {"GetActiveBoundingBox", &kGetActiveBoundingBox}, + {"GetMaxBoundingBox", &kGetMaxBoundingBox}, +}; + +} // namespace + +Animation::Class Actor::s_class{"ModelSceneActor", + nullptr, + kScripts, + static_cast(sizeof(kScripts) / sizeof(kScripts[0])), + kMethods, + static_cast(sizeof(kMethods) / sizeof(kMethods[0])), + 0, + 0}; + +void RegisterActorClass() { + Animation::RegisterClass(Actor::s_class); + Api::Documentation::NameWidgetSystem(&Actor::s_class, "FrameAPIModelSceneFrameActor"); + Api::Documentation::RecordFrameMethods(&Actor::s_class, kMethods, kMethodDocs); +} + +} // namespace Model::Scene diff --git a/src/model/SceneData.h b/src/model/SceneData.h new file mode 100644 index 00000000..ce086e4c --- /dev/null +++ b/src/model/SceneData.h @@ -0,0 +1,147 @@ +// This file is part of ClassicAPI. +// +// ClassicAPI is free software: you can redistribute it and/or modify it under the terms +// of the GNU General Public License as published by the Free Software Foundation, either +// version 3 of the License, or (at your option) any later version. +// +// ClassicAPI is distributed in the hope that it will be useful, but WITHOUT ANY +// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +// PURPOSE. See the GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along with +// ClassicAPI. If not, see . + +#pragma once + +#include + +// The UiModelScene rows behind C_ModelInfo. Retail keeps them in four DB2s +// that 1.12 has no counterpart for; only the scenes a ClassicAPI UI shows are +// embedded: 4 (the default mount scene), 44 (the Qiraji battle tanks) and 596 +// (the dressing room). Grow the list scene by scene, never the whole tables. +// Column meanings are retail's (docs/notes/model-scene.md § Data): +// - an actor's flags are Enum.UIModelSceneActorFlag (2/4/8 use the centre +// of the model for the X/Y/Z origin, 1 is deprecated); +// - a camera's type 0 is "OrbitCamera", the only type any row uses, and its +// flags are Enum.ModelSceneSetting; +// - a scene's system type is what GetModelSceneInfoByID returns as +// modelSceneType. +namespace Model::SceneData { + +struct Vec3 { + float x, y, z; +}; + +struct SceneRow { + uint32_t id; + uint32_t uiSystemType; + uint32_t flags; +}; + +struct CameraRow { + uint32_t id; + uint32_t sceneID; + const char *scriptTag; + Vec3 target; + float yaw, pitch, roll; + float zoomDistance, minZoomDistance, maxZoomDistance; + Vec3 zoomedTargetOffset; + float zoomedYawOffset, zoomedPitchOffset, zoomedRollOffset; + uint32_t flags; +}; + +struct ActorRow { + uint32_t id; + uint32_t sceneID; + const char *scriptTag; + Vec3 position; + float yaw, pitch, roll; + float normalizedScale; + uint32_t flags; + uint32_t displayID; // a kActorDisplays row, 0 for none +}; + +struct ActorDisplayRow { + uint32_t id; + uint32_t animation; + uint32_t animationVariation; + float animSpeed; + uint32_t animKitID; // 0 for none + uint32_t spellVisualKitID; // 0 for none + float alpha; + float scale; +}; + +// Generated from the retail 12.1.7.70740 UiModelScene, UiModelSceneCamera, +// UiModelSceneActor and UiModelSceneActorDisplay exports (wago.tools CSV), +// keeping only the scenes ClassicAPI uses: 4, 44, 596. + +// clang-format off +const SceneRow kScenes[] = { + {4, 0, 0}, + {44, 0, 0}, + {596, 12, 0}, +}; + +const CameraRow kCameras[] = { + {1, 4, "primary", {0.0f, 0.0f, 2.20000004768f}, 2.61999988556f, 0.0f, 0.0f, 14.0f, 8.0f, 18.0f, {0.0f, 0.0f, -1.5f}, 0.17453292012f, 0.0f, 0.0f, 0}, + {48, 44, "primary", {0.0f, 0.0f, 2.20000004768f}, 2.61799383163f, 0.0f, 0.0f, 14.0f, 8.0f, 18.0f, {0.0f, 0.0f, -1.5f}, 0.17453292012f, 0.0f, 0.0f, 1}, + {582, 596, "primary", {0.0f, 0.0f, 1.01999998093f}, 1.83000004292f, 0.0f, 0.0f, 3.90000009537f, 2.0f, 3.90000009537f, {0.0f, 0.0f, 0.0f}, 0.0f, 0.0f, 0.0f, 1}, +}; + +const ActorRow kActors[] = { + {1, 4, "unwrapped", {0.0f, 0.0f, 0.0f}, 0.0f, 0.0f, 0.0f, 0.25f, 8, 6}, + {2, 4, "wrapped", {0.0f, 0.0f, -0.5f}, 0.0f, 0.0f, 0.0f, 0.0f, 0, 1}, + {60, 44, "unwrapped", {0.0f, 0.0f, 0.0f}, 0.0f, 0.0f, 0.0f, 0.40000000596f, 9, 6}, + {61, 44, "wrapped", {0.0f, 0.0f, -0.5f}, 0.0f, 0.0f, 0.0f, 0.0f, 0, 1}, + {400, 4, "player-rider", {0.0f, 0.0f, 0.0f}, 0.0f, 0.0f, 0.0f, 0.0f, 0, 170}, + {408, 44, "player-rider", {0.0f, 0.0f, 0.0f}, 0.0f, 0.0f, 0.0f, 0.0f, 0, 170}, + {1620, 596, "player", {0.0f, 0.0f, 0.0f}, -0.95999997854f, 0.0f, 0.0f, 1.0f, 2, 170}, + {1621, 596, "tauren-male", {0.0f, 0.0f, 0.10000000149f}, -0.95999997854f, 0.0f, 0.0f, 0.28999999166f, 2, 170}, + {1622, 596, "gnome", {0.0f, 0.0f, 0.02999999933f}, -0.95999997854f, 0.0f, 0.0f, 2.04999995232f, 2, 170}, + {1623, 596, "dwarf-male", {0.0f, 0.0f, 0.03999999911f}, -0.95999997854f, 0.0f, 0.0f, 4.80000019073f, 2, 174}, + {1624, 596, "scourge-male", {0.0f, 0.0f, 0.0f}, -0.95999997854f, 0.0f, 0.0f, 19.0f, 2, 174}, + {1625, 596, "pandaren", {0.0f, 0.0f, 0.0700000003f}, -0.95999997854f, 0.0f, 0.0f, 0.37000000477f, 2, 170}, + {1626, 596, "worgen-male", {0.0f, 0.0f, -0.03999999911f}, -0.95999997854f, 0.0f, 0.0f, 0.20000000298f, 2, 170}, + {1627, 596, "draenei-male", {0.0f, 0.0f, 0.1400000006f}, -0.95999997854f, 0.0f, 0.0f, 0.49000000954f, 0, 170}, + {1628, 596, "goblin-male", {0.0f, 0.0f, 0.01999999955f}, -0.95999997854f, 0.0f, 0.0f, 6.30000019073f, 2, 170}, + {1629, 596, "goblin-female", {0.0f, 0.0f, 0.03999999911f}, -0.95999997854f, 0.0f, 0.0f, 4.0f, 2, 170}, + {1630, 596, "orc", {0.0f, 0.0f, 0.05999999866f}, -0.95999997854f, 0.0f, 0.0f, 0.33000001311f, 2, 170}, + {1631, 596, "tauren-female", {0.0f, 0.0f, 0.10000000149f}, -0.95999997854f, 0.0f, 0.0f, 0.41999998689f, 2, 170}, + {1632, 596, "troll-male", {0.0f, 0.0f, -0.05999999866f}, -0.95999997854f, 0.0f, 0.0f, 0.07999999821f, 2, 170}, + {1633, 596, "troll-female", {0.0f, 0.0f, 0.0f}, -0.95999997854f, 0.0f, 0.0f, 0.64999997616f, 2, 170}, + {1634, 596, "scourge-female", {0.0f, 0.0f, -0.00999999978f}, -0.95999997854f, 0.0f, 0.0f, 3.29999995232f, 2, 170}, + {1635, 596, "lightforgeddraenei-male", {0.0f, 0.0f, 0.12999999523f}, -0.95999997854f, 0.0f, 0.0f, 0.49000000954f, 0, 170}, + {1636, 596, "lightforgeddraenei-female", {0.0f, 0.0f, 0.03999999911f}, -0.95999997854f, 0.0f, 0.0f, 0.80000001192f, 2, 170}, + {1637, 596, "highmountaintauren-male", {0.0f, 0.0f, 0.10000000149f}, -0.95999997854f, 0.0f, 0.0f, 0.28999999166f, 2, 170}, + {1638, 596, "highmountaintauren-female", {0.0f, 0.0f, 0.10000000149f}, -0.95999997854f, 0.0f, 0.0f, 0.41999998689f, 2, 170}, + {1639, 596, "zandalaritroll", {0.0f, 0.0f, 0.05000000075f}, -0.95999997854f, 0.0f, 0.0f, 0.86000001431f, 2, 170}, + {1640, 596, "kultiran-male", {0.0f, 0.0f, 0.01999999955f}, -0.95999997854f, 0.0f, 0.0f, 0.49000000954f, 2, 170}, + {1641, 596, "magharorc-male", {0.0f, 0.0f, 0.1099999994f}, -0.95999997854f, 0.0f, 0.0f, 0.33000001311f, 2, 170}, + {1642, 596, "kultiran-female", {0.0f, 0.0f, 0.0f}, -0.95999997854f, 0.0f, 0.0f, 1.12000000477f, 2, 170}, + {1643, 596, "magharorc-female", {0.0f, 0.0f, 0.05000000075f}, -0.95999997854f, 0.0f, 0.0f, 0.18000000715f, 2, 170}, + {1644, 596, "darkirondwarf-male", {0.0f, 0.0f, 0.0700000003f}, -0.95999997854f, 0.0f, 0.0f, 4.94999980927f, 2, 174}, + {1645, 596, "worgen-female", {0.0f, 0.0f, 0.0f}, -0.95999997854f, 0.0f, 0.0f, 1.20000004768f, 2, 170}, + {1646, 596, "draenei-female", {0.0f, 0.0f, 0.05000000075f}, -0.95999997854f, 0.0f, 0.0f, 1.00999999046f, 2, 170}, + {1647, 596, "vulpera-female", {-0.12999999523f, 0.20000000298f, 0.03999999911f}, -0.95999997854f, 0.0f, 0.0f, 8.0f, 2, 174}, + {1648, 596, "vulpera-male", {-0.12999999523f, 0.20000000298f, 0.03999999911f}, -0.95999997854f, 0.0f, 0.0f, 5.0f, 2, 174}, + {1649, 596, "mechagnome-male", {0.0f, 0.0f, 0.07999999821f}, -0.95999997854f, 0.0f, 0.0f, 1.39999997616f, 2, 170}, + {1650, 596, "mechagnome-female", {0.0f, 0.0f, 0.07999999821f}, -0.95999997854f, 0.0f, 0.0f, 1.20000004768f, 2, 170}, + {1651, 596, "druid-bear-form", {0.10000000149f, 0.0f, 0.25f}, -0.95999997854f, 0.0f, 0.0f, 0.44999998808f, 0, 170}, + {1652, 596, "druid-cat-form", {1.0f, 0.0f, 0.5f}, -0.95999997854f, 0.0f, 0.0f, 0.28999999166f, 0, 170}, + {1653, 596, "dracthyr", {-0.5f, 0.80000001192f, -0.10000000149f}, -0.95999997854f, 0.0f, 0.0f, 0.12999999523f, 2, 170}, + {1654, 596, "dracthyr-alt", {0.0f, 0.0f, 0.0f}, -0.95999997854f, 0.0f, 0.0f, 1.0f, 2, 170}, + {2152, 596, "earthendwarf-male", {0.0f, 0.0f, 0.03999999911f}, -0.95999997854f, 0.0f, 0.0f, 2.70000004768f, 2, 174}, + {3606, 596, "harronir", {0.0f, 0.0f, 0.0f}, -1.08210408688f, 0.0f, 0.0f, 1.0f, 0, 0}, + {3619, 596, "harronir-female", {0.0f, 0.0f, 0.0f}, -1.08210408688f, 0.0f, 0.0f, 1.29999995232f, 0, 0}, +}; + +const ActorDisplayRow kActorDisplays[] = { + {1, 0, 0, 1.0f, 0, 0, 1.0f, 4.0f}, + {6, 0, 0, 1.0f, 0, 0, 1.0f, 3.5f}, + {170, 0, 0, 1.0f, 0, 0, 1.0f, 1.0f}, + {174, 0, 0, 1.0f, 0, 0, 1.0f, 2.0f}, +}; +// clang-format on + +} // namespace Model::SceneData