From f8a49dec332d4e82e38a1c94e1cb6701e7dbf7fd Mon Sep 17 00:00:00 2001 From: Brues <5278969+brues-code@users.noreply.github.com> Date: Fri, 6 Nov 2026 19:10:30 -0600 Subject: [PATCH] feat(model): run retail's ModelScene Lua on the scene frame Retail's camera registry, camera base, orbit camera, scene mixin and actor mixin come over verbatim, with their XML templates, so a scene built with SetFromModelSceneID frames, scales and orbits its actors the way retail's does. What they need from the client: Actor templates. 1.12's XML loader registers every virtual top-level node whatever its tag, so is a template that Xml::Template finds. CreateActor(name, template) loads it the way an animation group loads its own: the whole inherits chain's mixins first, then each node from the base up, then OnLoad. The parentKey, parentArray, and readers move out of the animation loader so both use them. Scene state. Light setters write the frame's M2Light through the engine's own setters (M2LightSetType 0x0071B620, SetDirection 0x0071B6A0, SetPosition 0x0071B650, SetEnabled 0x0071B780). Fog uses the Model frame's fields (+0x3A4..+0x3B0), stored as Model's own SetFogColor, SetFogNear, SetFogFar and ClearFog store them, and starts at retail's values. The draw layer goes through the engine's layer-name functions (0x006F18B0, 0x006F1900) and marks both layers changed. SetPaused keeps the frame update but skips Model's M2SceneAdvance. The XML loader adds drawLayer, fogNear, fogFar and after the frame's own loader. Actor state. A blend operation for PlayAnimation. Spell visual kits use the routine behind PlayerModel:ApplySpellVisualKit, which now takes a model instead of a pane; the actor applies a kit once its model loads and takes the effects off when the kit changes. 1.12 has no animation kits, so PlayAnimationKit and StopAnimationKit change nothing. GetCursorDelta, which the orbit camera drags with, samples the top's cursor (+0x1118) once a frame at the head of the UI render callback and converts it the way GetCursorPosition (0x0048B820) does, so the delta is the difference of two GetCursorPosition values. C_PlayerInfo. GetAlternateFormInfo answers false, false: 1.12 has no alternate forms. --- src/Offsets.h | 17 + src/animation/Xml.cpp | 4 + src/animation/Xml.h | 10 + .../AddOns/!!!ClassicAPI/!!!ClassicAPI.toc | 7 + src/embed/AddOns/!!!ClassicAPI/Compat.lua | 5 + .../FrameXML/ModelScene/CameraBaseMixin.lua | 103 +++ .../FrameXML/ModelScene/CameraRegistry.lua | 18 + .../ModelScene/ModelSceneActorMixin.lua | 144 ++++ .../ModelScene/ModelSceneActorMixin.xml | 10 + .../FrameXML/ModelScene/ModelSceneMixin.lua | 566 ++++++++++++++++ .../FrameXML/ModelScene/ModelSceneMixin.xml | 28 + .../FrameXML/ModelScene/OrbitCameraMixin.lua | 640 ++++++++++++++++++ .../AddOns/!!!ClassicAPI/Util/InputUtil.lua | 6 + src/input/CursorDelta.cpp | 97 +++ src/model/Scene.cpp | 433 +++++++++++- src/model/Scene.h | 9 + src/model/SceneActor.cpp | 171 ++++- src/model/VisualKit.cpp | 32 +- src/model/VisualKit.h | 33 + 19 files changed, 2293 insertions(+), 40 deletions(-) create mode 100644 src/embed/AddOns/!!!ClassicAPI/FrameXML/ModelScene/CameraBaseMixin.lua create mode 100644 src/embed/AddOns/!!!ClassicAPI/FrameXML/ModelScene/CameraRegistry.lua create mode 100644 src/embed/AddOns/!!!ClassicAPI/FrameXML/ModelScene/ModelSceneActorMixin.lua create mode 100644 src/embed/AddOns/!!!ClassicAPI/FrameXML/ModelScene/ModelSceneActorMixin.xml create mode 100644 src/embed/AddOns/!!!ClassicAPI/FrameXML/ModelScene/ModelSceneMixin.lua create mode 100644 src/embed/AddOns/!!!ClassicAPI/FrameXML/ModelScene/ModelSceneMixin.xml create mode 100644 src/embed/AddOns/!!!ClassicAPI/FrameXML/ModelScene/OrbitCameraMixin.lua create mode 100644 src/input/CursorDelta.cpp create mode 100644 src/model/VisualKit.h diff --git a/src/Offsets.h b/src/Offsets.h index 5339d9ca..4ce78146 100644 --- a/src/Offsets.h +++ b/src/Offsets.h @@ -4195,6 +4195,20 @@ enum Offsets { FUN_M2LIGHT_SET_TYPE = 0x0071B620, FUN_M2LIGHT_SET_DIRECTION = 0x0071B6A0, FUN_M2LIGHT_SET_ENABLED = 0x0071B780, + // M2LightSetPosition — `__thiscall(light, const float v[3])`. + FUN_M2LIGHT_SET_POSITION = 0x0071B650, + // The frame's fog (benilla-re ui/modelanim "Fog"): bit 0 of the flags arms + // it (Script SetFogColor ors it in at 0x0076F059, ClearFog clears only it), + // the colour is 0xAARRGGBB with each byte trunc(c * 255 + 0.5) of the + // component clamped to [0, 1], near and far are stored as given; the + // light callback fogs only while armed, and only for far > near. Model's + // LoadXML clamps the fogNear / fogFar attributes at 0 and reads + // with FUN_XML_READ_COLOR, which arms it too. + OFF_SIMPLEMODEL_FOG_FLAGS = 0x3A4, + OFF_SIMPLEMODEL_FOG_COLOR = 0x3A8, + OFF_SIMPLEMODEL_FOG_NEAR = 0x3AC, + OFF_SIMPLEMODEL_FOG_FAR = 0x3B0, + SIMPLEMODEL_FOG_ARMED = 0x1, // 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()`: @@ -12753,6 +12767,9 @@ enum Offsets { // `bool __fastcall(const char *name, int *outLayer)`: case-insensitive // BACKGROUND..HIGHLIGHT -> 0..4; leaves *outLayer alone on a miss. FUN_XML_DRAW_LAYER_FROM_NAME = 0x006F18B0, + // DrawLayerIdToName — `const char *__fastcall(int layer)`: the inverse, + // what the regions' GetDrawLayer pushes. + FUN_DRAW_LAYER_TO_NAME = 0x006F1900, // "Frame %s: Unknown child node in %s element: %s" STR_XML_FRAME_UNKNOWN_CHILD = 0x008786E0, // Builds a node's children. `__thiscall(frame, node, status)`, diff --git a/src/animation/Xml.cpp b/src/animation/Xml.cpp index 93e595f1..04461944 100644 --- a/src/animation/Xml.cpp +++ b/src/animation/Xml.cpp @@ -59,6 +59,8 @@ bool FloatAttr(const void *node, const char *name, float &out) { return true; } +} // namespace + // object[parentKey] = child, as 4.3.4's LoadXML does for both. void BindParentKey(void *object, Object *child, const char *key) { if (key == nullptr || *key == '\0') @@ -145,6 +147,8 @@ void LoadKeyValues(Object *object, const void *node, void *status) { Game::Lua::SetTop(L, top); } +namespace { + // LoadXML_AnimOrigin: . void LoadOrigin(Anim *anim, const void *node) { const void *origin = FindChild(node, "Origin"); diff --git a/src/animation/Xml.h b/src/animation/Xml.h index 52e94379..7541ac99 100644 --- a/src/animation/Xml.h +++ b/src/animation/Xml.h @@ -21,6 +21,7 @@ // (RegisterXMLTemplate), whatever its tag, so `inherits` resolves through // Xml::Template as 4.3.4's XMLHashNodeRef does. namespace Animation { +class Object; class Group; class Anim; class ControlPoint; @@ -39,4 +40,13 @@ void LoadControlPoint(ControlPoint *point, const void *node, void *status); // The template node `name` resolves to, or nullptr. const void *Template(const char *name); +// What every script object's element shares (Model::Scene's actors too): +// object[key] = child for parentKey, an append to object[key] for +// parentArray, the (a body, a `function` global or a `method` +// field) and the . +void BindParentKey(void *object, Object *child, const char *key); +void BindParentArray(void *object, Object *child, const char *key); +void LoadScripts(Object *object, const void *node); +void LoadKeyValues(Object *object, const void *node, void *status); + } // namespace Animation::Xml diff --git a/src/embed/AddOns/!!!ClassicAPI/!!!ClassicAPI.toc b/src/embed/AddOns/!!!ClassicAPI/!!!ClassicAPI.toc index 57301a8b..b882d91d 100644 --- a/src/embed/AddOns/!!!ClassicAPI/!!!ClassicAPI.toc +++ b/src/embed/AddOns/!!!ClassicAPI/!!!ClassicAPI.toc @@ -145,6 +145,13 @@ FrameXML\ColorSwatch.xml FrameXML\ScriptErrorsFrame.lua FrameXML\ScriptErrorsFrame.xml FrameXML\DressUpFrame.lua +FrameXML\ModelScene\CameraRegistry.lua +FrameXML\ModelScene\CameraBaseMixin.lua +FrameXML\ModelScene\OrbitCameraMixin.lua +FrameXML\ModelScene\ModelSceneMixin.lua +FrameXML\ModelScene\ModelSceneMixin.xml +FrameXML\ModelScene\ModelSceneActorMixin.lua +FrameXML\ModelScene\ModelSceneActorMixin.xml Menu\MenuConstants.lua Menu\Classic\MenuConstants.lua diff --git a/src/embed/AddOns/!!!ClassicAPI/Compat.lua b/src/embed/AddOns/!!!ClassicAPI/Compat.lua index 37a9e5b7..38ddc0c6 100644 --- a/src/embed/AddOns/!!!ClassicAPI/Compat.lua +++ b/src/embed/AddOns/!!!ClassicAPI/Compat.lua @@ -38,3 +38,8 @@ end function C_ModelInfo.ClearActiveModelSceneActor(modelSceneFrameActor) end + +-- This client has no alternate player forms. +function C_PlayerInfo.GetAlternateFormInfo() + return false, false +end diff --git a/src/embed/AddOns/!!!ClassicAPI/FrameXML/ModelScene/CameraBaseMixin.lua b/src/embed/AddOns/!!!ClassicAPI/FrameXML/ModelScene/CameraBaseMixin.lua new file mode 100644 index 00000000..594361fb --- /dev/null +++ b/src/embed/AddOns/!!!ClassicAPI/FrameXML/ModelScene/CameraBaseMixin.lua @@ -0,0 +1,103 @@ +-- Verbatim backport of retail's Blizzard_SharedXML/Shared/ModelSceneCameras/CameraBaseMixin.lua. + + +CameraBaseMixin = {}; + +function CameraBaseMixin:SetOwningScene(owningScene) + if self.owningScene ~= owningScene then + if self.owningScene then + self:OnRemoved(); + end + + self.owningScene = owningScene; + + if self.owningScene then + self:OnAdded(); + end + end +end + +function CameraBaseMixin:GetOwningScene() + return self.owningScene; +end + +CAMERA_TRANSITION_TYPE_IMMEDIATE = 1; -- Switch to the camera view instantly +CAMERA_TRANSITION_TYPE_INTERPOLATION = 2; -- Switch to the camera view by interpolating from the current view + +CAMERA_MODIFICATION_TYPE_DISCARD = 1; -- Discard any modifications performed to the view by script +CAMERA_MODIFICATION_TYPE_MAINTAIN = 2; -- Retain any modifications performed to the view by script + +-- Override this to handle transitions to a modelSceneCamera data set +function CameraBaseMixin:ApplyFromModelSceneCameraInfo(modelSceneCameraInfo, transitionType, modificationType) + +end + +-- Common accessors from the owning scene +function CameraBaseMixin:IsLeftMouseButtonDown() + return self:GetOwningScene():IsLeftMouseButtonDown(); +end + +function CameraBaseMixin:IsRightMouseButtonDown() + return self:GetOwningScene():IsRightMouseButtonDown(); +end + +function CameraBaseMixin:SetPosition(x, y, z) + self:GetOwningScene():SetCameraPosition(x, y, z); +end + +function CameraBaseMixin:GetPosition() + return self:GetOwningScene():GetCameraPosition(); +end + +function CameraBaseMixin:GetForwardVector() + return self:GetOwningScene():GetCameraForward(); +end + +function CameraBaseMixin:GetRightVector() + return self:GetOwningScene():GetCameraRight(); +end + +function CameraBaseMixin:GetUpVector() + return self:GetOwningScene():GetCameraUp(); +end + +-- Override this with a uniquely identifying name for the camera type +function CameraBaseMixin:GetCameraType() + return "UnknownCamera"; +end + +-- Override this to perform any per-frame updates +function CameraBaseMixin:OnUpdate(elapsed) +end + +-- Override this with code to synchronize the camera state with the model scene API, may be called by the ModelScene to synchronize deferred camera state in case it needs to be queried +function CameraBaseMixin:SynchronizeCamera() +end + +-- Override this to be notified when the mouse is down on the model scene +function CameraBaseMixin:OnMouseDown(button) +end + +-- Override this to be notified when the mouse is up on the model scene +function CameraBaseMixin:OnMouseUp(button) +end + +-- Override this to be notified when the mouse wheel is changed on the model scene +function CameraBaseMixin:OnMouseWheel(delta) +end + +-- Override this to be notified when the camera is added to a scene +function CameraBaseMixin:OnAdded() +end + +-- Override this to be notified when the camera is remove from a scene +function CameraBaseMixin:OnRemoved() +end + +-- Override this to be notified when the camera becomes activated +function CameraBaseMixin:OnActivated() +end + +-- Override this to be notified when the camera becomes deactivated +function CameraBaseMixin:OnDeactivated() +end \ No newline at end of file diff --git a/src/embed/AddOns/!!!ClassicAPI/FrameXML/ModelScene/CameraRegistry.lua b/src/embed/AddOns/!!!ClassicAPI/FrameXML/ModelScene/CameraRegistry.lua new file mode 100644 index 00000000..5d8871e5 --- /dev/null +++ b/src/embed/AddOns/!!!ClassicAPI/FrameXML/ModelScene/CameraRegistry.lua @@ -0,0 +1,18 @@ +-- Verbatim backport of retail's Blizzard_SharedXML/Shared/ModelSceneCameras/CameraRegistry.lua. + + +CameraRegistry = { cameraTypeToFactoryFunction = {}, }; + +function CameraRegistry:AddCameraFactory(cameraTypeName, factoryFunction) + self.cameraTypeToFactoryFunction[cameraTypeName] = factoryFunction; +end + +function CameraRegistry:AddCameraFactoryFromMixin(cameraTypeName, mixin) + self:AddCameraFactory(cameraTypeName, function() return CreateFromMixins(mixin); end); +end + +function CameraRegistry:CreateCameraByType(cameraTypeName) + if self.cameraTypeToFactoryFunction[cameraTypeName] then + return self.cameraTypeToFactoryFunction[cameraTypeName](); + end +end \ No newline at end of file diff --git a/src/embed/AddOns/!!!ClassicAPI/FrameXML/ModelScene/ModelSceneActorMixin.lua b/src/embed/AddOns/!!!ClassicAPI/FrameXML/ModelScene/ModelSceneActorMixin.lua new file mode 100644 index 00000000..d8dfed33 --- /dev/null +++ b/src/embed/AddOns/!!!ClassicAPI/FrameXML/ModelScene/ModelSceneActorMixin.lua @@ -0,0 +1,144 @@ +-- Verbatim backport of retail's Blizzard_SharedXML/ModelSceneActorMixin.lua. + + +ModelSceneActorMixin = {}; + +-- "public" methods +function ModelSceneActorMixin:ApplyFromModelSceneActorInfo(actorInfo) + self:SetUseCenterForOrigin(actorInfo.useCenterForOriginX, actorInfo.useCenterForOriginY, actorInfo.useCenterForOriginZ); + + self:SetPosition(actorInfo.position:GetXYZ()); + self:SetYaw(actorInfo.yaw); + self:SetPitch(actorInfo.pitch); + self:SetRoll(actorInfo.roll); + + self.requestedScale = nil; + + local actorDisplayInfo = actorInfo.modelActorDisplayID and C_ModelInfo.GetModelSceneActorDisplayInfoByID(actorInfo.modelActorDisplayID); + if actorDisplayInfo then + if actorDisplayInfo.animationKitID then + self:PlayAnimationKit(actorDisplayInfo.animationKitID); + else + self:SetAnimation(actorDisplayInfo.animation, actorDisplayInfo.animationVariation, actorDisplayInfo.animSpeed); + end + + self:SetSpellVisualKit(actorDisplayInfo.spellVisualKitID); + + self:SetAlpha(actorDisplayInfo.alpha); + self:SetRequestedScale(actorDisplayInfo.scale); + else + self:StopAnimationKit(); + self:SetSpellVisualKit(nil); + self:SetAnimation(0, 0, 1.0); + self:SetAlpha(1.0); + self:SetRequestedScale(1.0); + end + + self:SetNormalizedScaleAggressiveness(actorInfo.normalizeScaleAggressiveness or 0.0); + + self:MarkScaleDirty(); + self:UpdateScale(); + + C_ModelInfo.AddActiveModelSceneActor(self, actorInfo.modelActorID); +end + +function ModelSceneActorMixin:OnModelCleared() + C_ModelInfo.ClearActiveModelSceneActor(self); +end + +function ModelSceneActorMixin:SetOnSizeChangedCallback(onSizeChangedCallback) + self.onSizeChangedCallback = onSizeChangedCallback; +end + +function ModelSceneActorMixin:GetOnSizeChangedCallback() + return self.onSizeChangedCallback; +end + +function ModelSceneActorMixin:SetOnModelLoadedCallback(onModelLoadedCallback) + self.onModelLoadedCallback = onModelLoadedCallback; +end + +function ModelSceneActorMixin:GetOnModelLoadedCallback() + return self.onModelLoadedCallback; +end + +function ModelSceneActorMixin:SetNormalizedScaleAggressiveness(normalizedScaleAggressiveness) + if self.normalizedScaleAggressiveness ~= normalizedScaleAggressiveness then + self.normalizedScaleAggressiveness = normalizedScaleAggressiveness; + self:MarkScaleDirty(); + end +end + +function ModelSceneActorMixin:GetNormalizedScaleAggressiveness() + return self.normalizedScaleAggressiveness or 0; +end + +function ModelSceneActorMixin:SetRequestedScale(requestedScale) + if self.requestedScale ~= requestedScale then + self.requestedScale = requestedScale; + self:MarkScaleDirty(); + end +end + +function ModelSceneActorMixin:GetRequestedScale() + return self.requestedScale or self:GetScale(); +end + +MODEL_SCENE_ACTOR_DIMENSIONS_FOR_NORMALIZATION = { width = .9984, depth = 1.121, height = 2.118 }; -- Roughly the dimensions of a human male model (but why male models?) +function ModelSceneActorMixin:CalculateNormalizedScale(normalizedScaleAggressiveness) + if self:IsLoaded() and normalizedScaleAggressiveness > 0.0 then + local bottomX, bottomY, bottomZ, topX, topY, topZ = self:GetActiveBoundingBox(); -- Could be nil for invisible models + if bottomX and bottomY and bottomZ and topX and topY and topZ then + local width = topX - bottomX; + local depth = topY - bottomY; + local height = topZ - bottomZ; + + local widthScale = width / MODEL_SCENE_ACTOR_DIMENSIONS_FOR_NORMALIZATION.width; + local depthScale = depth / MODEL_SCENE_ACTOR_DIMENSIONS_FOR_NORMALIZATION.depth; + local heightScale = height / MODEL_SCENE_ACTOR_DIMENSIONS_FOR_NORMALIZATION.height; + + local maxScale = math.max(widthScale, math.max(depthScale, heightScale)); + if maxScale == 0 then + return 1.0; + end + + return 1 / Lerp(1.0, maxScale, normalizedScaleAggressiveness); + end + end + + return 1.0; +end + +-- "private" methods +function ModelSceneActorMixin:OnReleased() + self:SetOnSizeChangedCallback(nil); + self:SetOnModelLoadedCallback(nil); +end + +function ModelSceneActorMixin:OnUpdate() + self:UpdateScale(); +end + +function ModelSceneActorMixin:OnModelLoaded() + self:MarkScaleDirty(); + + if self.onModelLoadedCallback then + self.onModelLoadedCallback(self); + end +end + +function ModelSceneActorMixin:UpdateScale() + if self.scaleDirty and self:IsLoaded() then + self.scaleDirty = nil; + local effectiveScale = self:GetRequestedScale() * self:CalculateNormalizedScale(self:GetNormalizedScaleAggressiveness()); + self:SetScale(effectiveScale); + + if self.onSizeChangedCallback then + self.onSizeChangedCallback(self); + end + end +end + +function ModelSceneActorMixin:MarkScaleDirty() + self.scaleDirty = true; +end \ No newline at end of file diff --git a/src/embed/AddOns/!!!ClassicAPI/FrameXML/ModelScene/ModelSceneActorMixin.xml b/src/embed/AddOns/!!!ClassicAPI/FrameXML/ModelScene/ModelSceneActorMixin.xml new file mode 100644 index 00000000..adfa876c --- /dev/null +++ b/src/embed/AddOns/!!!ClassicAPI/FrameXML/ModelScene/ModelSceneActorMixin.xml @@ -0,0 +1,10 @@ + + + + + + + + + diff --git a/src/embed/AddOns/!!!ClassicAPI/FrameXML/ModelScene/ModelSceneMixin.lua b/src/embed/AddOns/!!!ClassicAPI/FrameXML/ModelScene/ModelSceneMixin.lua new file mode 100644 index 00000000..8669e0e5 --- /dev/null +++ b/src/embed/AddOns/!!!ClassicAPI/FrameXML/ModelScene/ModelSceneMixin.lua @@ -0,0 +1,566 @@ +-- Verbatim backport of retail's Blizzard_SharedXML/ModelSceneMixin.lua. + + +ModelSceneMixin = {} + +-- "public" functions +function ModelSceneMixin:OnLoad() + self.cameras = {}; + self.actorTemplate = "ModelSceneActorTemplate"; + self.tagToActor = {}; + self.tagToCamera = {}; + + if self.allowOverlappedModels then + self:SetAllowOverlappedModels(true); + end +end + +function ModelSceneMixin:ClearScene() + self.modelSceneID = nil; + + self:ReleaseAllActors(); + self:ReleaseAllCameras(); + + C_ModelInfo.ClearActiveModelScene(self); +end + +function ModelSceneMixin:GetModelSceneID() + return self.modelSceneID; +end + +-- Adjusts this scene to mirror a model scene from static data without transition +function ModelSceneMixin:SetFromModelSceneID(modelSceneID, forceEvenIfSame, noAutoCreateActors) + local modelSceneType, cameraIDs, actorIDs = C_ModelInfo.GetModelSceneInfoByID(modelSceneID); + if not modelSceneType then + return; + end + + if self.modelSceneID ~= modelSceneID or forceEvenIfSame then + self.modelSceneID = modelSceneID; + self:ReleaseAllActors(); + self:ReleaseAllCameras(); + + if not noAutoCreateActors then + for actorIndex, actorID in ipairs(actorIDs) do + self:CreateActorFromScene(actorID); + end + end + + for cameraIndex, cameraID in ipairs(cameraIDs) do + self:CreateCameraFromScene(cameraID); + end + end + + C_ModelInfo.AddActiveModelScene(self, self.modelSceneID); + EventRegistry:TriggerEvent("ModelScene.SetFromModelSceneID", self, self.modelSceneID); +end + +function ModelSceneMixin:SetResetCallback(callback) + self.resetCallback = callback; +end + +function ModelSceneMixin:Reset() + if self.modelSceneID then + self:TransitionToModelSceneID(self.modelSceneID, self.cameraTransitionType, self.cameraModificationType, self.forceEvenIfSame); + if self.resetCallback then + self.resetCallback(self); + end + end +end + +-- Adjusts this scene to mirror a model scene from static data but with transition effects +-- Only actors/cameras with script tags will be transitioned +function ModelSceneMixin:TransitionToModelSceneID(modelSceneID, cameraTransitionType, cameraModificationType, forceEvenIfSame) + local modelSceneType, cameraIDs, actorIDs = C_ModelInfo.GetModelSceneInfoByID(modelSceneID); + if not modelSceneType or #cameraIDs == 0 or #actorIDs == 0 then + return; + end + + if self.modelSceneID ~= modelSceneID or forceEvenIfSame then + self.modelSceneID = modelSceneID; + self.cameraTransitionType = cameraTransitionType; + self.cameraModificationType = cameraModificationType; + self.forceEvenIfSame = forceEvenIfSame; + + local actorsToRelease = {}; + for actor in self:EnumerateActiveActors() do + actorsToRelease[actor] = true; + end + + local oldTagToActor = self.tagToActor; + self.tagToActor = {}; + + for actorIndex, actorID in ipairs(actorIDs) do + local actor = self:CreateOrTransitionActorFromScene(oldTagToActor, actorID); + if actor then + actorsToRelease[actor] = nil; + end + end + + for actor in pairs(actorsToRelease) do + self.actorPool:Release(actor); + end + + local oldTagToCamera = self.tagToCamera; + self.tagToCamera = {}; + + self.cameras = {}; + + local needsNewCamera = true; + for cameraIndex, cameraID in ipairs(cameraIDs) do + local camera = self:CreateOrTransitionCameraFromScene(oldTagToCamera, cameraTransitionType, cameraModificationType, cameraID); + if camera == self.activeCamera then + needsNewCamera = false; + end + end + + if needsNewCamera then + self:SetActiveCamera(self.cameras[1]); + end + end + + C_ModelInfo.AddActiveModelScene(self, self.modelSceneID); + EventRegistry:TriggerEvent("ModelScene.TransitionToModelSceneID", self, self.modelSceneID); +end + +-- There may be inactive (pooled) actors maintained by this scene, these function only returns the active actors +function ModelSceneMixin:GetNumActiveActors() + return self.actorPool and self.actorPool:GetNumActive() or 0; +end + +function ModelSceneMixin:EnumerateActiveActors() + if self.actorPool then + return self.actorPool:EnumerateActive(); + end + return nop; +end + +function ModelSceneMixin:GetActorByTag(tag) + return self.tagToActor[tag]; +end + +function ModelSceneMixin:AttachPlayerToMount(mountActor, animID, isSelfMount, disablePlayerMountPreview, spellVisualKitID, usePlayerNativeForm, optionalPlayerRiderTag) + local playerRiderTag = optionalPlayerRiderTag or "player-rider"; + local playerActor = self:GetPlayerActor(playerRiderTag); + if (playerActor) then + if disablePlayerMountPreview or isSelfMount then + playerActor:ClearModel(); + else + local sheatheWeapons = true; + local autoDress = true; + local hideWeapons = true; + + if C_Glue.IsOnGlueScreen() then + local characterIndex = nil; -- defaults to selected character. + playerActor:SetPlayerModelFromGlues(characterIndex, sheatheWeapons, autoDress, hideWeapons, usePlayerNativeForm); + else + playerActor:SetModelByUnit("player", sheatheWeapons, autoDress, hideWeapons, usePlayerNativeForm); + end + local calcMountScale = mountActor:CalculateMountScale(playerActor); + local inverseScale = 1 / calcMountScale; + playerActor:SetRequestedScale( inverseScale ); + mountActor:AttachToMount(playerActor, animID, spellVisualKitID); + end + end +end + +function GetPlayerActorLabelTag(forceAlternateForm, overrideRaceFilename, overrideGender) + local playerRaceName = overrideRaceFilename; + local playerGender = overrideGender; + local playerRaceNameActorTag = nil; + local hasAlternateForm, inAlternateForm = false, false; + if not overrideRaceFilename or not overrideGender then + if C_Glue.IsOnGlueScreen() then + local characterGuid = GetCharacterGUID(GetCharacterSelection()); + if characterGuid then + local basicCharacterInfo = GetBasicCharacterInfo(characterGuid); + playerRaceName = overrideRaceFilename or basicCharacterInfo.raceFilename; + playerGender = overrideGender or basicCharacterInfo.genderEnum; + end + else + hasAlternateForm, inAlternateForm = C_PlayerInfo.GetAlternateFormInfo(); + local _, raceFilename = UnitRace("player"); + playerRaceName = overrideRaceFilename or raceFilename; + playerGender = overrideGender or UnitSex("player"); + end + end + if not playerRaceName or not playerGender then + return playerRaceName, playerRaceNameActorTag; + end + playerRaceName = playerRaceName:lower(); + if hasAlternateForm and (inAlternateForm or forceAlternateForm) then + playerRaceName = playerRaceName.."-alt"; + end + playerGender = (playerGender == 2) and "male" or "female"; + playerRaceNameActorTag = playerRaceName.."-"..playerGender; + return playerRaceName, playerRaceNameActorTag; +end + +function ModelSceneMixin:GetPlayerActor(overrideActorName, forceAlternateForm, overrideRaceFilename, overrideGender) + local actor; + if overrideActorName then + actor = self:GetActorByTag(overrideActorName); + else + local playerRaceName, playerRaceNameActorTag = GetPlayerActorLabelTag(forceAlternateForm, overrideRaceFilename, overrideGender); + actor = self:GetActorByTag(playerRaceNameActorTag); + if not actor then + actor = self:GetActorByTag(playerRaceName); + if not actor then + actor = self:GetActorByTag("player"); + if not actor then + actor = self:GetActorByTag("player-rider"); + end + end + end + end + return actor; +end + +function ModelSceneMixin:ReleaseAllActors() + if self.actorPool then + self.actorPool:ReleaseAll(); + + if self.dropShadowPool then + self.dropShadowPool:ReleaseAll(); + end + + self.tagToActor = {}; + end +end + +local function OnReleased(actorPool, actor) + actor:OnReleased(); + ActorPool_HideAndClearModel(actorPool, actor); +end + +function ModelSceneMixin:AcquireActor() + if not self.actorPool then + self.actorPool = CreateActorPool(self, self.actorTemplate, OnReleased); + end + return self.actorPool:Acquire(); +end + +function ModelSceneMixin:ReleaseActor(actor) + if not actor or not self.actorPool then + return; + end + + for tag, taggedActor in pairs(self.tagToActor) do + if actor == taggedActor then + self.tagToActor[tag] = nil; + break; + end + end + + if actor.dropShadowTexture then + self.dropShadowPool:Release(actor.dropShadowTexture); + end + + return self.actorPool:Release(actor); +end + +function ModelSceneMixin:AcquireAndInitializeActor(actorInfo) + local actor = self:AcquireActor(); + self:InitializeActor(actor, actorInfo); + return actor; +end + +function ModelSceneMixin:ReleaseAllCameras() + self:SetActiveCamera(nil); + for i = #self.cameras, 1, -1 do + self.cameras[i]:SetOwningScene(nil); + self.cameras[i] = nil; + end + self.tagToCamera = {}; +end + +function ModelSceneMixin:GetCameraByTag(tag) + return self.tagToCamera[tag]; +end + +function ModelSceneMixin:AddCamera(camera) + table.insert(self.cameras, camera); + + camera:SetOwningScene(self); + + if not self:HasActiveCamera() then + self:SetActiveCamera(camera); + end + + return camera; +end + +function ModelSceneMixin:HasActiveCamera() + return self.activeCamera ~= nil; +end + +function ModelSceneMixin:GetActiveCamera() + return self.activeCamera; +end + +function ModelSceneMixin:SetActiveCamera(camera) + if camera ~= self.activeCamera then + if self.activeCamera then + self.activeCamera:OnDeactivated(); + end + + self.activeCamera = camera; + + if self.activeCamera then + self.activeCamera:OnActivated(); + end + end +end + +function ModelSceneMixin:IsLeftMouseButtonDown() + return self.isLeftButtonDown; +end + +function ModelSceneMixin:IsRightMouseButtonDown() + return self.isRightButtonDown; +end + +function ModelSceneMixin:Transform3DPointTo2D(x, y, z) + self:SynchronizeActiveCamera(); + return self:Project3DPointTo2D(x, y, z); +end + +-- "private" functions +function ModelSceneMixin:OnUpdate(elapsed) + if self.activeCamera then + local yawDirection = self.yawDirection; + local increment = self.increment; + if yawDirection == "left" then + self.activeCamera:AdjustYaw(-1, -1, increment); + elseif yawDirection == "right" then + self.activeCamera:AdjustYaw(1, 1, increment); + end + + self.activeCamera:OnUpdate(elapsed); + end +end + +function ModelSceneMixin:SynchronizeActiveCamera() + if self.activeCamera then + self.activeCamera:SynchronizeCamera(); + end +end + +function ModelSceneMixin:OnEnter(button) + if self.ControlFrame then + self.ControlFrame:Show(); + end +end + +function ModelSceneMixin:OnLeave(button) + if self.ControlFrame then + if not self.ControlFrame:IsMouseOver()then + self.ControlFrame:Hide(); + end + end +end + +function ModelSceneMixin:OnMouseDown(button) + if button == "LeftButton" then + self.isLeftButtonDown = true; + elseif button == "RightButton" then + self.isRightButtonDown = true; + end + + if self.activeCamera then + self.activeCamera:OnMouseDown(button); + end +end + +function ModelSceneMixin:OnMouseUp(button) + if button == "LeftButton" then + self.isLeftButtonDown = false; + elseif button == "RightButton" then + self.isRightButtonDown = false; + end + + if self.activeCamera then + self.activeCamera:OnMouseUp(button); + end +end + +function ModelSceneMixin:OnMouseWheel(delta) + if self.activeCamera then + self.activeCamera:OnMouseWheel(delta); + end +end + +function ModelSceneMixin:AdjustCameraYaw(direction, increment) + if self.activeCamera then + self.yawDirection = direction; + self.increment = increment; + end +end + +function ModelSceneMixin:StopCameraYaw() + self.yawDirection = nil; + self.increment = nil; +end + +function ModelSceneMixin:InitializeActor(actor, actorInfo) + if actorInfo.scriptTag then + self.tagToActor[actorInfo.scriptTag] = actor; + end + + actor:ApplyFromModelSceneActorInfo(actorInfo); + + actor:Show(); +end + +function ModelSceneMixin:CreateActorFromScene(actorID) + local actorInfo = C_ModelInfo.GetModelSceneActorInfoByID(actorID); + return self:AcquireAndInitializeActor(actorInfo); +end + +function ModelSceneMixin:CreateOrTransitionActorFromScene(oldTagToActor, actorID) + local actorInfo = C_ModelInfo.GetModelSceneActorInfoByID(actorID); + local existingActor = oldTagToActor[actorInfo.scriptTag]; + if existingActor then + self:InitializeActor(existingActor, actorInfo); + return existingActor; + end + + return self:AcquireAndInitializeActor(actorInfo); +end + +function ModelSceneMixin:CreateCameraFromScene(modelSceneCameraID) + local modelSceneCameraInfo = C_ModelInfo.GetModelSceneCameraInfoByID(modelSceneCameraID); + if modelSceneCameraInfo then + local camera = CameraRegistry:CreateCameraByType(modelSceneCameraInfo.cameraType); + if camera then + if modelSceneCameraInfo.scriptTag then + self.tagToCamera[modelSceneCameraInfo.scriptTag] = camera; + end + self:AddCamera(camera); + camera:ApplyFromModelSceneCameraInfo(modelSceneCameraInfo, CAMERA_TRANSITION_TYPE_IMMEDIATE, CAMERA_MODIFICATION_TYPE_DISCARD); + return camera; + end + end +end + +function ModelSceneMixin:CreateOrTransitionCameraFromScene(oldTagToCamera, cameraTransitionType, cameraModificationType, modelSceneCameraID) + local modelSceneCameraInfo = C_ModelInfo.GetModelSceneCameraInfoByID(modelSceneCameraID); + if modelSceneCameraInfo then + local existingCamera = oldTagToCamera[modelSceneCameraInfo.scriptTag]; + if existingCamera and existingCamera:GetCameraType() == modelSceneCameraInfo.cameraType then + self.tagToCamera[modelSceneCameraInfo.scriptTag] = existingCamera; + + self:AddCamera(existingCamera); + existingCamera:ApplyFromModelSceneCameraInfo(modelSceneCameraInfo, cameraTransitionType, cameraModificationType); + return existingCamera; + end + + return self:CreateCameraFromScene(modelSceneCameraID); + end +end + +-- actorSettings = { +-- "actorTag" = { startDelay = 0, duration = 0, speed = 1 } -- duration 0 means no automatic stoppage +-- } +function ModelSceneMixin:ShowAndAnimateActors(actorSettings, onFinishedCallback) + self:Show(); + local totalTime = 0; + for actorTag, actorInfo in pairs(actorSettings) do + local actor = self:GetActorByTag(actorTag); + if actor then + local runningTime = actorInfo.startDelay + actorInfo.duration; + if actorInfo.startDelay > 0 then + actor:SetAnimation(0, 0, 0, 0); + C_Timer.After(actorInfo.startDelay, + function() + actor:SetAnimation(0, 0, actorInfo.speed, 0); + end + ); + else + actor:SetAnimation(0, 0, actorInfo.speed, 0); + end + if actorInfo.duration > 0 then + C_Timer.After(runningTime, + function() + actor:SetAnimation(0, 0, 0, 0); + end + ); + end + if runningTime > totalTime then + totalTime = runningTime; + end + end + end + + if onFinishedCallback and totalTime > 0 then + C_Timer.After(totalTime, onFinishedCallback); + end +end + +function ModelSceneMixin:GetOrAcquireDropShadow(actor) + if actor.dropShadowTexture then + return actor.dropShadowTexture; + end + + if not self.dropShadowPool then + self.dropShadowPool = CreateTexturePool(self, "BORDER", 1, "ModelSceneDropShadowTemplate"); + end + + actor.dropShadowTexture = self.dropShadowPool:Acquire(); + return actor.dropShadowTexture; +end + +function ModelSceneMixin:AddOrUpdateDropShadow(actor, baseShadowScale) + baseShadowScale = baseShadowScale or 1.0; + + local dropShadowTexture = self:GetOrAcquireDropShadow(actor); + local positionVector = CreateVector3D(actor:GetPosition()); + positionVector:ScaleBy(actor:GetScale()); + local x, y, depthScale = self:Transform3DPointTo2D(positionVector:GetXYZ()); + + if not x or not y or not depthScale then + dropShadowTexture:Hide(); + return; + end + + dropShadowTexture:ClearAllPoints(); + depthScale = baseShadowScale * Lerp(.05, 1, ClampedPercentageBetween(depthScale, .8, 1)) + -- Scales down the texture depending on it's depthScale. + dropShadowTexture:SetScale(depthScale); + + -- Need to apply the effective scale to account for UI Scaling. + local inverseScale = self:GetEffectiveScale() * depthScale; + -- The position of the character can be found by the offset on the screen. + dropShadowTexture:SetPoint("CENTER", self, "BOTTOMLEFT", (x / inverseScale) + 2, (y / inverseScale) - 4); + dropShadowTexture:Show(); +end + + +PanningModelSceneMixin = CreateFromMixins(ModelSceneMixin); +function PanningModelSceneMixin:TransitionToModelSceneID(modelSceneID, cameraTransitionType, cameraModificationType, forceEvenIfSame) + ModelSceneMixin.TransitionToModelSceneID(self, modelSceneID, cameraTransitionType, cameraModificationType, forceEvenIfSame); + + local camera = self:GetActiveCamera(); + if camera then + camera:SetRightMouseButtonXMode(ORBIT_CAMERA_MOUSE_PAN_HORIZONTAL, true); + camera:SetRightMouseButtonYMode(ORBIT_CAMERA_MOUSE_PAN_VERTICAL, true); + end +end + + +NoCameraControlModelSceneMixin = CreateFromMixins(ModelSceneMixin); +function NoCameraControlModelSceneMixin:OnMouseDown(button) + self.isLeftButtonDown = false; + self.isRightButtonDown = false; +end + +function NoCameraControlModelSceneMixin:OnMouseUp(button) + self.isLeftButtonDown = false; + self.isRightButtonDown = false; +end + +function NoCameraControlModelSceneMixin:OnMouseWheel(delta) +end +NoZoomModelSceneMixin = CreateFromMixins(ModelSceneMixin); +function NoZoomModelSceneMixin:OnMouseWheel(delta) +end diff --git a/src/embed/AddOns/!!!ClassicAPI/FrameXML/ModelScene/ModelSceneMixin.xml b/src/embed/AddOns/!!!ClassicAPI/FrameXML/ModelScene/ModelSceneMixin.xml new file mode 100644 index 00000000..1888d0c1 --- /dev/null +++ b/src/embed/AddOns/!!!ClassicAPI/FrameXML/ModelScene/ModelSceneMixin.xml @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/embed/AddOns/!!!ClassicAPI/FrameXML/ModelScene/OrbitCameraMixin.lua b/src/embed/AddOns/!!!ClassicAPI/FrameXML/ModelScene/OrbitCameraMixin.lua new file mode 100644 index 00000000..6a398b2b --- /dev/null +++ b/src/embed/AddOns/!!!ClassicAPI/FrameXML/ModelScene/OrbitCameraMixin.lua @@ -0,0 +1,640 @@ +-- Verbatim backport of retail's Blizzard_SharedXML/Shared/ModelSceneCameras/OrbitCameraMixin.lua. + +--[[ + OrbitCameraMixin - A simple camera that can orbit a target point at a fixed distance. + + The orbit is represented using a distance from a target point in world space and yaw, pitch and roll. + The yaw, pitch and roll represent the camera's orientation, or inversely the direction of the camera from the target point. + + Optionally, the target, orientation and zoom can have splines that are added to the respective axes. The splines are fed the zoom percentage to calculate the point on the spline. + This is ideal for changing view points based on zoom distance from the target. For example, target model's face on zoom in and center on the model on zoom out. +]] + +OrbitCameraMixin = CreateFromMixins(CameraBaseMixin); + +local CAMERA_NAME = "OrbitCamera"; +CameraRegistry:AddCameraFactoryFromMixin(CAMERA_NAME, OrbitCameraMixin); + +-- "public" functions +function OrbitCameraMixin:GetCameraType() -- override + return CAMERA_NAME; +end + +local function TryCreateZoomSpline(x, y, z, existingSpline) + if x and y and z and (x ~= 0 or y ~= 0 or z ~= 0) then + local spline = existingSpline or CreateCatmullRomSpline(3); + spline:ClearPoints(); + spline:AddPoint(0, 0, 0); + spline:AddPoint(x, y, z); + + return spline; + end + return nil; +end + +function OrbitCameraMixin:ApplyFromModelSceneCameraInfo(modelSceneCameraInfo, transitionType, modificationType) -- override + self.panningXOffset = 0; + self.panningYOffset = 0; + + local transitionalCameraInfo = self:CalculateTransitionalValues(self.modelSceneCameraInfo, modelSceneCameraInfo, modificationType); + + self.modelSceneCameraInfo = modelSceneCameraInfo; + + self:SetTarget(transitionalCameraInfo.target:GetXYZ()); + self:SetTargetSpline(TryCreateZoomSpline(transitionalCameraInfo.zoomedTargetOffset:GetXYZ()), self:GetTargetSpline()); + self:SetOrientationSpline(TryCreateZoomSpline(transitionalCameraInfo.zoomedYawOffset, transitionalCameraInfo.zoomedPitchOffset, transitionalCameraInfo.zoomedRollOffset), self:GetOrientationSpline()); + + self:SetMinZoomDistance(transitionalCameraInfo.minZoomDistance); + self:SetMaxZoomDistance(transitionalCameraInfo.maxZoomDistance); + + self:SetZoomDistance(transitionalCameraInfo.zoomDistance); + + self:SetYaw(transitionalCameraInfo.yaw); + self:SetPitch(transitionalCameraInfo.pitch); + self:SetRoll(transitionalCameraInfo.roll); + + if transitionType == CAMERA_TRANSITION_TYPE_IMMEDIATE then + self:SnapAllInterpolatedValues(); + end + self:UpdateCameraOrientationAndPosition(); +end + +function OrbitCameraMixin:SetTarget(x, y, z) + self.targetX, self.targetY, self.targetZ = x, y, z; +end + +function OrbitCameraMixin:GetTarget(x, y, z) + return self.targetX, self.targetY, self.targetZ; +end + +function OrbitCameraMixin:SetYaw(yaw) + self.yaw = yaw; +end + +function OrbitCameraMixin:GetYaw() + return self.yaw; +end + +function OrbitCameraMixin:SetPitch(pitch) + self.pitch = pitch; +end + +function OrbitCameraMixin:GetPitch() + return self.pitch; +end + +function OrbitCameraMixin:SetRoll(roll) + self.roll = roll; +end + +function OrbitCameraMixin:GetRoll() + return self.roll; +end + +-- where 100% is fully zoomed out +function OrbitCameraMixin:GetZoomPercent() + return self.zoomPercent; +end + +function OrbitCameraMixin:SetZoomPercent(zoomPercent) + self.zoomPercent = Saturate(zoomPercent); +end + +function OrbitCameraMixin:ZoomByPercent(percent) + self:SetZoomPercent(self:GetZoomPercent() - percent); +end + +function OrbitCameraMixin:SetMaxZoomDistance(distance) + self.maxZoomDistance = distance; + if self:GetZoomPercent() then + self:SetZoomDistance(self:GetZoomDistance()); + end +end + +function OrbitCameraMixin:GetMaxZoomDistance() + return self.maxZoomDistance; +end + +function OrbitCameraMixin:SetMinZoomDistance(distance) + self.minZoomDistance = distance; + if self:GetZoomPercent() then + self:SetZoomDistance(self:GetZoomDistance()); + end +end + +function OrbitCameraMixin:GetMinZoomDistance() + return self.minZoomDistance; +end + +function OrbitCameraMixin:SetZoomDistance(distance) + self:SetZoomPercent(self:CalculateZoomPercentFromDistance(distance)); +end + +function OrbitCameraMixin:CalculateZoomPercentFromDistance(distance) + if self:GetMinZoomDistance() and self:GetMaxZoomDistance() then + return PercentageBetween(distance, self:GetMinZoomDistance(), self:GetMaxZoomDistance()); + end + return 0.0; +end + +function OrbitCameraMixin:CalculateZoomDistanceFromPercent(percent) + if self:GetMinZoomDistance() and self:GetMaxZoomDistance() then + return Lerp(self:GetMinZoomDistance(), self:GetMaxZoomDistance(), percent); + end + return 0.0; +end + +function OrbitCameraMixin:GetZoomDistance() + return self:CalculateZoomDistanceFromPercent(self:GetZoomPercent()); +end + +-- If min and max values are the same, zoom cannot really happen. +function OrbitCameraMixin:GetZoomAvailable() + if self:GetMinZoomDistance() and self:GetMaxZoomDistance() then + return self:GetMinZoomDistance() ~= self:GetMaxZoomDistance(); + end + return false; +end + +function OrbitCameraMixin:ZoomBy(distance) + self:SetZoomDistance(self:GetZoomDistance() - distance); +end + +-- Expects a three dimensional spline where a point of the curve represents a target position +function OrbitCameraMixin:SetTargetSpline(targetSpline) + self.targetSpline = targetSpline; +end + +function OrbitCameraMixin:GetTargetSpline() + return self.targetSpline; +end + +-- Expects a three dimensional spline where a point of the curve represents the camera yaw, pitch, roll +function OrbitCameraMixin:SetOrientationSpline(orientationSpline) + self.orientationSpline = orientationSpline; +end + +function OrbitCameraMixin:GetOrientationSpline() + return self.orientationSpline; +end + +-- Expects an one dimensional spline where a point of the curve represents the camera's distance from the target +function OrbitCameraMixin:SetZoomSpline(zoomSpline) + self.zoomSpline = zoomSpline; +end + +function OrbitCameraMixin:GetZoomSpline() + return self.zoomSpline; +end + +--[[ These return the simple + spline values ]]-- +function OrbitCameraMixin:GetDerivedTarget() + local targetX, targetY, targetZ = self:GetTarget(); + + local targetSpline = self:GetTargetSpline(); + if targetSpline then + return Vector3D_Add(targetX, targetY, targetZ, targetSpline:CalculatePointOnGlobalCurve(1.0 - self:GetZoomPercent())); + end + + return targetX, targetY, targetZ; +end + +function OrbitCameraMixin:GetDerivedOrientation() + local yaw, pitch, roll = self:GetYaw(), self:GetPitch(), self:GetRoll(); + + local orientationSpline = self:GetOrientationSpline(); + if orientationSpline then + return Vector3D_Add(yaw, pitch, roll, orientationSpline:CalculatePointOnGlobalCurve(1.0 - self:GetZoomPercent())); + end + + return yaw, pitch, roll; +end + +function OrbitCameraMixin:GetDerivedZoomDistance() + local zoomDistance = self:GetZoomDistance(); + + local zoomSpline = self:GetZoomSpline(); + if zoomSpline then + return zoomDistance + zoomSpline:CalculatePointOnGlobalCurve(1.0 - self:GetZoomPercent()); + end + + return zoomDistance; +end + +function OrbitCameraMixin:SetAlignLightToOrbitDelta(alignLightToOrbitDelta) + if alignLightToOrbitDelta then + self.modelSceneCameraInfo.flags = bit.bor(self.modelSceneCameraInfo.flags, Enum.ModelSceneSetting.AlignLightToOrbitDelta); + else + self.modelSceneCameraInfo.flags = bit.band(self.modelSceneCameraInfo.flags, bit.bnot(Enum.ModelSceneSetting.AlignLightToOrbitDelta)); + end +end + +function OrbitCameraMixin:ShouldAlignLightToOrbitDelta() + return bit.band(self.modelSceneCameraInfo.flags, Enum.ModelSceneSetting.AlignLightToOrbitDelta) == Enum.ModelSceneSetting.AlignLightToOrbitDelta; +end + +--[[ + Interpolation API + For each API, "amount" is the percentage to approach in an "ideal" frame (60 fps), such that setting the value to >= 1 would snap to the desired target and <= 0 would freeze the interpolation. + Setting to nil will disable the interpolation. +]] + +function OrbitCameraMixin:SetYawInterpolationAmount(yawInterpolationAmount) + self.yawInterpolationAmount = yawInterpolationAmount; +end + +function OrbitCameraMixin:GetYawInterpolationAmount() + return self.yawInterpolationAmount; +end + +function OrbitCameraMixin:SetPitchInterpolationAmount(pitchInterpolationAmount) + self.pitchInterpolationAmount = pitchInterpolationAmount; +end + +function OrbitCameraMixin:GetPitchInterpolationAmount() + return self.pitchInterpolationAmount; +end + +function OrbitCameraMixin:SetRollInterpolationAmount(rollInterpolationAmount) + self.rollInterpolationAmount = rollInterpolationAmount; +end + +function OrbitCameraMixin:GetRollInterpolationAmount() + return self.rollInterpolationAmount; +end + +function OrbitCameraMixin:SetTargetInterpolationAmount(targetInterpolationAmount) + self.targetInterpolationAmount = targetInterpolationAmount; +end + +function OrbitCameraMixin:GetTargetInterpolationAmount() + return self.targetInterpolationAmount; +end + +function OrbitCameraMixin:SetZoomInterpolationAmount(zoomInterpolationAmount) + self.zoomInterpolationAmount = zoomInterpolationAmount; +end + +function OrbitCameraMixin:GetZoomInterpolationAmount() + return self.zoomInterpolationAmount; +end + +function OrbitCameraMixin:GetInterpolatedTarget() + if self.interpolatedTargetX then + return self.interpolatedTargetX, self.interpolatedTargetY, self.interpolatedTargetZ; + end + return self:GetDerivedTarget(); +end + +function OrbitCameraMixin:GetInterpolatedOrientation() + if self.interpolatedYaw then + return self.interpolatedYaw, self.interpolatedPitch, self.interpolatedRoll; + end + return self:GetDerivedOrientation(); +end + +function OrbitCameraMixin:GetInterpolatedZoomDistance() + if self.interpolatedZoomDistance then + return self.interpolatedZoomDistance; + end + return self:GetDerivedZoomDistance(); +end + +function OrbitCameraMixin:SnapToTargetInterpolationYaw() + self.interpolatedYaw = nil; +end + +function OrbitCameraMixin:SnapToTargetInterpolationPitch() + self.interpolatedPitch = nil; +end + +function OrbitCameraMixin:SnapToTargetInterpolationRoll() + self.interpolatedRoll = nil; +end + +function OrbitCameraMixin:SnapToTargetInterpolationZoom() + self.interpolatedZoomDistance = nil; +end + +function OrbitCameraMixin:SnapToTargetInterpolationTarget() + self.interpolatedTargetX = nil; + self.interpolatedTargetY = nil; + self.interpolatedTargetZ = nil; +end + +function OrbitCameraMixin:SnapAllInterpolatedValues() + self:SnapToTargetInterpolationYaw(); + self:SnapToTargetInterpolationPitch(); + self:SnapToTargetInterpolationRoll(); + + self:SnapToTargetInterpolationZoom(); + + self:SnapToTargetInterpolationTarget(); +end + +ORBIT_CAMERA_MOUSE_MODE_NOTHING = 0; +ORBIT_CAMERA_MOUSE_MODE_YAW_ROTATION = 1; +ORBIT_CAMERA_MOUSE_MODE_PITCH_ROTATION = 2; +ORBIT_CAMERA_MOUSE_MODE_ROLL_ROTATION = 3; +ORBIT_CAMERA_MOUSE_MODE_TARGET_HORIZONTAL = 4; +ORBIT_CAMERA_MOUSE_MODE_TARGET_VERTICAL = 5; +ORBIT_CAMERA_MOUSE_MODE_ZOOM = 6; +ORBIT_CAMERA_MOUSE_PAN_HORIZONTAL = 7; +ORBIT_CAMERA_MOUSE_PAN_VERTICAL = 8; + +function OrbitCameraMixin:SetLeftMouseButtonXMode(mouseMode, snap) + self.buttonModes.leftX = mouseMode; + self.buttonModes.leftXinterpolate = not snap; +end + +function OrbitCameraMixin:GetLeftMouseButtonXMode() + return self.buttonModes.leftX, not self.buttonModes.leftXinterpolate; +end + +function OrbitCameraMixin:SetLeftMouseButtonYMode(mouseMode, snap) + self.buttonModes.leftY = mouseMode; + self.buttonModes.leftYinterpolate = not snap; +end + +function OrbitCameraMixin:GetLeftYMouseButtonYMode() + return self.buttonModes.leftY, not self.buttonModes.leftYinterpolate; +end + +function OrbitCameraMixin:SetRightMouseButtonXMode(mouseMode, snap) + self.buttonModes.rightX = mouseMode; + self.buttonModes.rightXinterpolate = not snap; +end + +function OrbitCameraMixin:GetRightMouseButtonXMode() + return self.buttonModes.rightX, not self.buttonModes.rightXinterpolate; +end + +function OrbitCameraMixin:SetRightMouseButtonYMode(mouseMode, snap) + self.buttonModes.rightY = mouseMode; + self.buttonModes.rightYinterpolate = not snap; +end + +function OrbitCameraMixin:GetRightMouseButtonYMode() + return self.buttonModes.rightY, not self.buttonModes.rightYinterpolate; +end + +function OrbitCameraMixin:SetMouseWheelMode(mouseMode, snap) + self.buttonModes.wheel = mouseMode; + self.buttonModes.wheelInterpolate = not snap; +end + +function OrbitCameraMixin:GetMouseWheelMode() + return self.buttonModes.wheel, not self.buttonModes.wheelInterpolate; +end + +function OrbitCameraMixin:HandleMouseMovement(mode, delta, snapToValue) + if mode == ORBIT_CAMERA_MOUSE_MODE_YAW_ROTATION then + self:SetYaw(self:GetYaw() - delta); + if snapToValue then + self:SnapToTargetInterpolationYaw(); + end + elseif mode == ORBIT_CAMERA_MOUSE_MODE_PITCH_ROTATION then + self:SetPitch(self:GetPitch() - delta); + if snapToValue then + self:SnapToTargetInterpolationPitch(); + end + elseif mode == ORBIT_CAMERA_MOUSE_MODE_ROLL_ROTATION then + self:SetRoll(self:GetRoll() - delta); + if snapToValue then + self:SnapToTargetInterpolationRoll(); + end + elseif mode == ORBIT_CAMERA_MOUSE_MODE_ZOOM then + self:ZoomByPercent(delta); + if snapToValue then + self:SnapToTargetInterpolationZoom(); + end + elseif mode == ORBIT_CAMERA_MOUSE_MODE_TARGET_HORIZONTAL then + local rightX, rightY, rightZ = Vector3D_ScaleBy(delta, self:GetRightVector()); + self:SetTarget(Vector3D_Add(rightX, rightY, rightZ, self:GetTarget())); + + if snapToValue then + self:SnapToTargetInterpolationTarget(); + end + elseif mode == ORBIT_CAMERA_MOUSE_MODE_TARGET_VERTICAL then + local upX, upY, upZ = Vector3D_ScaleBy(delta, self:GetUpVector()); + self:SetTarget(Vector3D_Add(upX, upY, upZ, self:GetTarget())); + + if snapToValue then + self:SnapToTargetInterpolationTarget(); + end + elseif mode == ORBIT_CAMERA_MOUSE_PAN_HORIZONTAL then + self.panningXOffset = self.panningXOffset + delta; + elseif mode == ORBIT_CAMERA_MOUSE_PAN_VERTICAL then + self.panningYOffset = self.panningYOffset + delta; + end +end + +function OrbitCameraMixin:ResetDefaultInputModes() + self:SetLeftMouseButtonXMode(ORBIT_CAMERA_MOUSE_MODE_YAW_ROTATION, true); + self:SetLeftMouseButtonYMode(ORBIT_CAMERA_MOUSE_MODE_NOTHING); + self:SetRightMouseButtonXMode(ORBIT_CAMERA_MOUSE_MODE_NOTHING); + self:SetRightMouseButtonYMode(ORBIT_CAMERA_MOUSE_MODE_NOTHING); + self:SetMouseWheelMode(ORBIT_CAMERA_MOUSE_MODE_ZOOM, false); +end + +-- "private" function +function OrbitCameraMixin:OnAdded() -- override + self.buttonModes = {}; + + self:SetTarget(0, 0, 0); + + local targetSpline = CreateCatmullRomSpline(3); + targetSpline:AddPoint(0, 0, 0); + targetSpline:AddPoint(0, 0, .5); + + self:SetTargetSpline(targetSpline); + + self:SetMinZoomDistance(6); + self:SetMaxZoomDistance(10); + + self:SetZoomDistance(8); + + self:SetYaw(math.pi); + self:SetPitch(0); + self:SetRoll(0); + + self:SetZoomInterpolationAmount(.15); + self:SetYawInterpolationAmount(.15); + self:SetPitchInterpolationAmount(.15); + self:SetRollInterpolationAmount(.15); + self:SetTargetInterpolationAmount(.15); + + self:ResetDefaultInputModes(); +end + +function OrbitCameraMixin:GetDeltaModifierForCameraMode(mode) + if mode == ORBIT_CAMERA_MOUSE_MODE_YAW_ROTATION then + return .008; + elseif mode == ORBIT_CAMERA_MOUSE_MODE_PITCH_ROTATION then + return .008; + elseif mode == ORBIT_CAMERA_MOUSE_MODE_ROLL_ROTATION then + return .008; + elseif mode == ORBIT_CAMERA_MOUSE_MODE_ZOOM then + return .1; + elseif mode == ORBIT_CAMERA_MOUSE_MODE_TARGET_HORIZONTAL then + return .05; + elseif mode == ORBIT_CAMERA_MOUSE_MODE_TARGET_VERTICAL then + return .05; + elseif mode == ORBIT_CAMERA_MOUSE_PAN_HORIZONTAL then + return 0.93; + elseif mode == ORBIT_CAMERA_MOUSE_PAN_VERTICAL then + return 0.93; + end + return 0.0; +end + +function OrbitCameraMixin:OnUpdate(elapsed) -- override + if self:IsLeftMouseButtonDown() then + local deltaX, deltaY = InputUtil.GetCursorDelta(GetAppropriateTopLevelParent()); + self:HandleMouseMovement(self.buttonModes.leftX, deltaX * self:GetDeltaModifierForCameraMode(self.buttonModes.leftX), not self.buttonModes.leftXinterpolate); + self:HandleMouseMovement(self.buttonModes.leftY, -deltaY * self:GetDeltaModifierForCameraMode(self.buttonModes.leftY), not self.buttonModes.leftYinterpolate); + end + + if self:IsRightMouseButtonDown() then + local deltaX, deltaY = InputUtil.GetCursorDelta(GetAppropriateTopLevelParent()); + self:HandleMouseMovement(self.buttonModes.rightX, deltaX * self:GetDeltaModifierForCameraMode(self.buttonModes.rightX), not self.buttonModes.rightXinterpolate); + self:HandleMouseMovement(self.buttonModes.rightY, -deltaY * self:GetDeltaModifierForCameraMode(self.buttonModes.rightY), not self.buttonModes.rightYinterpolate); + end + + self:UpdateInterpolationTargets(elapsed); + self:SynchronizeCamera(); +end + +function OrbitCameraMixin:SynchronizeCamera() -- override + self:UpdateCameraOrientationAndPosition(); + self:UpdateLight(); +end + +local function InterpolateDimension(lastValue, targetValue, amount, elapsed) + return lastValue and amount and DeltaLerp(lastValue, targetValue, amount, elapsed) or targetValue; +end + +function OrbitCameraMixin:UpdateInterpolationTargets(elapsed) + local yaw, pitch, roll = self:GetDerivedOrientation(); + local targetX, targetY, targetZ = self:GetDerivedTarget(); + local zoomDistance = self:GetDerivedZoomDistance(); + + self.interpolatedYaw = InterpolateDimension(self.interpolatedYaw, yaw, self.yawInterpolationAmount, elapsed); + self.interpolatedPitch = InterpolateDimension(self.interpolatedPitch, pitch, self.pitchInterpolationAmount, elapsed); + self.interpolatedRoll = InterpolateDimension(self.interpolatedRoll, roll, self.rollInterpolationAmount, elapsed); + + self.interpolatedZoomDistance = InterpolateDimension(self.interpolatedZoomDistance, zoomDistance, self.zoomInterpolationAmount, elapsed); + + self.interpolatedTargetX = InterpolateDimension(self.interpolatedTargetX, targetX, self.targetInterpolationAmount, elapsed); + self.interpolatedTargetY = InterpolateDimension(self.interpolatedTargetY, targetY, self.targetInterpolationAmount, elapsed); + self.interpolatedTargetZ = InterpolateDimension(self.interpolatedTargetZ, targetZ, self.targetInterpolationAmount, elapsed); +end + +function OrbitCameraMixin:UpdateCameraOrientationAndPosition() + local yaw, pitch, roll = self:GetInterpolatedOrientation(); + local axisAngleX, axisAngleY, axisAngleZ = Vector3D_CalculateNormalFromYawPitch(yaw, pitch); + + local targetX, targetY, targetZ = self:GetInterpolatedTarget(); + + local zoomDistance = self:GetInterpolatedZoomDistance(); + + -- Panning start -- + -- We want the model to move 1-to-1 with the mouse. + -- Panning formula: dx / hypotenuse * (zoomDistance - 1 / zoomDistance^3) + -- It was experimentally determined that adding the additional fudge factor 1/z^3 resulted in better tracking. + + local width = self:GetOwningScene():GetWidth(); + local height = self:GetOwningScene():GetHeight(); + local scaleFactor = (width ~= 0 and height ~= 0) and math.sqrt(width * width + height * height) or 1; + local zoomFactor = 1; + if zoomDistance > 1 then + zoomFactor = zoomDistance - (1 / (zoomDistance * zoomDistance * zoomDistance)); + if zoomFactor < 1 then + zoomFactor = 1; + end + end + + local rightX, rightY, rightZ = Vector3D_ScaleBy((self.panningXOffset / scaleFactor) * zoomFactor, self:GetRightVector()); + local upX, upY, upZ = Vector3D_ScaleBy((self.panningYOffset / scaleFactor) * zoomFactor, self:GetUpVector()); + + -- Panning end -- + + targetX, targetY, targetZ = Vector3D_Add(targetX, targetY, targetZ, rightX, rightY, rightZ); + targetX, targetY, targetZ = Vector3D_Add(targetX, targetY, targetZ, upX, upY, upZ); + + self:SetPosition(self:CalculatePositionByDistanceFromTarget(targetX, targetY, targetZ, zoomDistance, axisAngleX, axisAngleY, axisAngleZ)); + self:GetOwningScene():SetCameraOrientationByYawPitchRoll(yaw, pitch, roll); +end + +function OrbitCameraMixin:UpdateLight() + if self:ShouldAlignLightToOrbitDelta() then + local owningScene = self:GetOwningScene(); + owningScene:SetLightDirection(self:GetForwardVector()); + end +end + +function OrbitCameraMixin:CalculatePositionByDistanceFromTarget(targetX, targetY, targetZ, zoomDistance, axisAngleX, axisAngleY, axisAngleZ) + local towardsPosX, towardsPosY, towardsPosZ = Vector3D_ScaleBy(-zoomDistance, axisAngleX, axisAngleY, axisAngleZ); + return Vector3D_Add(towardsPosX, towardsPosY, towardsPosZ, targetX, targetY, targetZ); +end + +function OrbitCameraMixin:CalculateTransitionalValues(fromModelSceneCameraInfo, toModelSceneCameraInfo, modificationType) + if fromModelSceneCameraInfo and modificationType == CAMERA_MODIFICATION_TYPE_MAINTAIN then + local zoomedTargetOffsetX, zoomedTargetOffsetY, zoomedTargetOffsetZ = 0, 0, 0; + + local targetSpline = self:GetTargetSpline(); + if targetSpline and targetSpline:GetNumPoints() > 0 then + zoomedTargetOffsetX, zoomedTargetOffsetY, zoomedTargetOffsetZ = targetSpline:GetPoint(targetSpline:GetNumPoints()); + end + + local zoomedYawOffset, zoomedPitchOffset, zoomedRollOffset = 0, 0, 0; + local orientationSpline = self:GetOrientationSpline(); + if orientationSpline and orientationSpline:GetNumPoints() > 0 then + zoomedYawOffset, zoomedPitchOffset, zoomedRollOffset = orientationSpline:GetPoint(orientationSpline:GetNumPoints()); + end + + local fromZoomDistancePercent = PercentageBetween(fromModelSceneCameraInfo.zoomDistance, fromModelSceneCameraInfo.minZoomDistance, fromModelSceneCameraInfo.maxZoomDistance); + local toZoomDistancePercent = PercentageBetween(toModelSceneCameraInfo.zoomDistance, toModelSceneCameraInfo.minZoomDistance, toModelSceneCameraInfo.maxZoomDistance); + -- Maintain any modifications made by applying the scene delta + return { + target = CreateVector3D( + (self.targetX - fromModelSceneCameraInfo.target.x) + toModelSceneCameraInfo.target.x, + (self.targetY - fromModelSceneCameraInfo.target.y) + toModelSceneCameraInfo.target.y, + (self.targetZ - fromModelSceneCameraInfo.target.z) + toModelSceneCameraInfo.target.z + ), + + yaw = (self.yaw - fromModelSceneCameraInfo.yaw) + toModelSceneCameraInfo.yaw, + pitch = (self.pitch - fromModelSceneCameraInfo.pitch) + toModelSceneCameraInfo.pitch, + roll = (self.roll - fromModelSceneCameraInfo.roll) + toModelSceneCameraInfo.roll, + + zoomDistance = Lerp(toModelSceneCameraInfo.minZoomDistance, toModelSceneCameraInfo.maxZoomDistance, (self.zoomPercent - fromZoomDistancePercent) + toZoomDistancePercent), + minZoomDistance = (self.minZoomDistance - fromModelSceneCameraInfo.minZoomDistance) + toModelSceneCameraInfo.minZoomDistance, + maxZoomDistance = (self.maxZoomDistance - fromModelSceneCameraInfo.maxZoomDistance) + toModelSceneCameraInfo.maxZoomDistance, + + zoomedTargetOffset = CreateVector3D( + (zoomedTargetOffsetX - fromModelSceneCameraInfo.zoomedTargetOffset.x) + toModelSceneCameraInfo.zoomedTargetOffset.x, + (zoomedTargetOffsetY - fromModelSceneCameraInfo.zoomedTargetOffset.y) + toModelSceneCameraInfo.zoomedTargetOffset.y, + (zoomedTargetOffsetZ - fromModelSceneCameraInfo.zoomedTargetOffset.z) + toModelSceneCameraInfo.zoomedTargetOffset.z + ), + + zoomedYawOffset = (zoomedYawOffset - fromModelSceneCameraInfo.zoomedYawOffset) + toModelSceneCameraInfo.zoomedYawOffset, + zoomedPitchOffset = (zoomedPitchOffset - fromModelSceneCameraInfo.zoomedPitchOffset) + toModelSceneCameraInfo.zoomedPitchOffset, + zoomedRollOffset = (zoomedRollOffset - fromModelSceneCameraInfo.zoomedRollOffset) + toModelSceneCameraInfo.zoomedRollOffset; + }; + end + + -- Nothing to transition from, just go directly to the values + return toModelSceneCameraInfo; +end + +function OrbitCameraMixin:OnMouseWheel(delta) -- override + self:HandleMouseMovement(self.buttonModes.wheel, delta * self:GetDeltaModifierForCameraMode(self.buttonModes.wheel), not self.buttonModes.wheelInterpolate); +end + +function OrbitCameraMixin:AdjustYaw(deltaX, deltaY, rotationScalar) + local xRotation = rotationScalar or self:GetDeltaModifierForCameraMode(self.buttonModes.leftX); + self:HandleMouseMovement(self.buttonModes.leftX, deltaX * xRotation, not self.buttonModes.leftXinterpolate); + + local yRotatation = rotationScalar or self:GetDeltaModifierForCameraMode(self.buttonModes.leftY); + self:HandleMouseMovement(self.buttonModes.leftY, -deltaY * yRotatation, not self.buttonModes.leftYinterpolate); +end \ No newline at end of file diff --git a/src/embed/AddOns/!!!ClassicAPI/Util/InputUtil.lua b/src/embed/AddOns/!!!ClassicAPI/Util/InputUtil.lua index 23314189..d00eaa95 100644 --- a/src/embed/AddOns/!!!ClassicAPI/Util/InputUtil.lua +++ b/src/embed/AddOns/!!!ClassicAPI/Util/InputUtil.lua @@ -8,6 +8,12 @@ function InputUtil.GetCursorPosition(parent) return x / scale, y / scale; end +function InputUtil.GetCursorDelta(parent) + local x, y = GetCursorDelta(); + local scale = parent:GetEffectiveScale(); + return x / scale, y / scale; +end + function InputUtil.AnchorRegionToCursor(region, point) local parent = GetAppropriateTopLevelParent(); local x, y = InputUtil.GetCursorPosition(parent); diff --git a/src/input/CursorDelta.cpp b/src/input/CursorDelta.cpp new file mode 100644 index 00000000..b309337c --- /dev/null +++ b/src/input/CursorDelta.cpp @@ -0,0 +1,97 @@ +// 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 . + +// `GetCursorDelta()` -> deltaX, deltaY +// +// Retail's: how far the cursor moved since the last frame, zero when it did +// not, in GetCursorPosition's units (independent of the UI scale; InputUtil. +// GetCursorDelta divides by a frame's effective scale). The orbit camera of +// a ModelScene drags with it. +// +// The cursor is sampled once a frame, at the head of the UI render callback, +// before any OnUpdate runs, the way the in-game GetCursorPosition (0x0048B820) +// reads it: the top's NDC position (OFF_UI_CONTEXT_MOUSE_POSITION) through +// NDCToDDC, then the engine's script push (Game::InternalToPixel). The delta is +// this frame's sample less the last frame's, so every OnUpdate of a frame sees +// the same value. + +#include "Game.h" +#include "Offsets.h" +#include "tick/FrameTick.h" + +namespace Input::CursorDelta { + +namespace { + +struct Position { + double x = 0.0; + double y = 0.0; +}; + +Position g_previous; +Position g_current; +bool g_sampled = false; + +// What GetCursorPosition pushes now, or false before the UI top exists. +bool ReadCursor(Position &out) { + using NdcToDdc_t = void(__fastcall *)(float *outX, float *outY, float x, float y); + const void *top = Game::Read(Offsets::VAR_UI_CONTEXT_PTR); + if (top == nullptr) + return false; + const float ndcX = Game::Read(top, Offsets::OFF_UI_CONTEXT_MOUSE_POSITION); + const float ndcY = Game::Read(top, Offsets::OFF_UI_CONTEXT_MOUSE_POSITION + 4); + float ddcX = 0.0f; + float ddcY = 0.0f; + reinterpret_cast(Offsets::FUN_COORD_NDC_TO_DDC)(&ddcX, &ddcY, ndcX, ndcY); + out = {Game::InternalToPixel(ddcX), Game::InternalToPixel(ddcY)}; + return true; +} + +void Sample() { + Position now; + if (!ReadCursor(now)) + return; + g_previous = g_sampled ? g_current : now; + g_current = now; + g_sampled = true; +} + +const Tick::FrameTick::AutoSubscribeBefore _tick{&Sample}; + +int __fastcall Script_GetCursorDelta(void *L) { + Game::Lua::PushNumber(L, g_current.x - g_previous.x); + Game::Lua::PushNumber(L, g_current.y - g_previous.y); + return 2; +} + +const Game::Doc::Field kRets[] = { + Game::Doc::Req("deltaX", "number"), + Game::Doc::Req("deltaY", "number"), +}; +const Game::Doc::Function kDoc{"Returns how far the cursor moved since the last frame.", {}, + kRets, "Input"}; + +void RegisterInGame() { + Game::Lua::RegisterGlobalFunction("GetCursorDelta", &Script_GetCursorDelta, &kDoc); +} + +void RegisterGlue() { + Game::Lua::RegisterGlueFunction("GetCursorDelta", &Script_GetCursorDelta, &kDoc); +} + +const Game::ModuleAutoRegister _autoreg{&RegisterInGame}; +const Game::GlueModuleAutoRegister _autoregGlue{&RegisterGlue}; + +} // namespace + +} // namespace Input::CursorDelta diff --git a/src/model/Scene.cpp b/src/model/Scene.cpp index 39a916d6..bb776e76 100644 --- a/src/model/Scene.cpp +++ b/src/model/Scene.cpp @@ -61,7 +61,22 @@ // 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. +// frame's light callback, as a Model frame's model is, so the light setters +// write the frame's M2Light through the engine's own light setters. +// +// Fog is the Model frame's own (+0x3A4..+0x3B0), stored the way Model's +// SetFogColor / SetFogNear / SetFogFar / ClearFog store it (0x0076EE60.. +// 0x0076F5C5): the colour arms it, ClearFog disarms it only. It starts with +// retail's values (near 1e7, far 1e8, white), which fog nothing. SetPaused +// stops the scene clock: the frame's update runs without Model's +// M2SceneAdvance, so every actor holds its pose. +// +// XML: `drawLayer`, `fogNear` and `fogFar` (clamped at 0, as Model's loader +// clamps them) and (FUN_XML_READ_COLOR, which arms the fog), after +// the frame's own loader. Retail's and children are not +// read; no retail UI uses them. Not ported, as no UI this DLL targets uses +// them and their exact effect is unprobed: view insets and translation, +// desaturation, overlapped models, TakeActor and Project3DPointTo2D. #include "model/Scene.h" @@ -71,6 +86,7 @@ #include "frame/Subclass.h" #include "model/Camera.h" #include "model/M2.h" +#include "xml/FrameLoad.h" #include #include @@ -97,6 +113,12 @@ struct Fields { float nearClip; float farClip; int drawLayer; + // What the light setters were given, for the getters. + uint32_t lightType; + uint32_t lightVisible; + Vec3 lightDirection; + Vec3 lightPosition; + uint32_t paused; }; constexpr size_t kObjectSize = Offsets::MODEL_FRAME_SIZE + sizeof(Fields); @@ -156,20 +178,72 @@ void InstallCamera(void *frame) { ApplyCamera(frame); } -// PlayerModel's light (0x00505680) with retail's values. +// ---- the light and fog --------------------------------------------------------------- + +using LightInt_t = void(__thiscall *)(void *light, int value); +using LightVector_t = void(__thiscall *)(void *light, const float *v); + +void *LightOf(void *frame) { return Game::Ptr(frame, Offsets::OFF_SIMPLEMODEL_LIGHT); } +float *AmbientOf(void *frame) { return Game::Ptr(LightOf(frame), Offsets::OFF_M2LIGHT_AMBIENT); } +float *DiffuseOf(void *frame) { return Game::Ptr(LightOf(frame), Offsets::OFF_M2LIGHT_DIFFUSE); } + +void SetLightType(void *frame, uint32_t type) { + F(frame).lightType = type; + reinterpret_cast(Offsets::FUN_M2LIGHT_SET_TYPE)(LightOf(frame), static_cast(type)); +} + +void SetLightVisible(void *frame, bool visible) { + F(frame).lightVisible = visible ? 1 : 0; + reinterpret_cast(Offsets::FUN_M2LIGHT_SET_ENABLED)(LightOf(frame), visible ? 1 : 0); +} + +void SetLightDirection(void *frame, const Vec3 &v) { + F(frame).lightDirection = v; + reinterpret_cast(Offsets::FUN_M2LIGHT_SET_DIRECTION)(LightOf(frame), &v.x); +} + +void SetLightPosition(void *frame, const Vec3 &v) { + F(frame).lightPosition = v; + reinterpret_cast(Offsets::FUN_M2LIGHT_SET_POSITION)(LightOf(frame), &v.x); +} + +void SetColor(float *color, const Vec3 &v) { + color[0] = v.x; + color[1] = v.y; + color[2] = v.z; +} + +// Retail's light, set the way PlayerModel's constructor sets its own +// (0x00505680). 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); + SetLightType(frame, 0); + SetLightDirection(frame, {0.0f, 1.0f, 0.0f}); + SetColor(AmbientOf(frame), {178.0f / 255.0f, 178.0f / 255.0f, 178.0f / 255.0f}); + SetColor(DiffuseOf(frame), {204.0f / 255.0f, 204.0f / 255.0f, 163.0f / 255.0f}); + SetLightVisible(frame, true); +} + +// Model's SetFogColor byte: clamped to [0, 1] (NaN to 1), trunc(c * 255 + 0.5). +uint32_t FogByte(float c) { + if (!(c < 1.0f)) + c = 1.0f; + else if (!(c > 0.0f)) + c = 0.0f; + return static_cast(c * 255.0f + 0.5f); +} + +uint32_t &FogFlags(void *frame) { return Game::Ref(frame, Offsets::OFF_SIMPLEMODEL_FOG_FLAGS); } + +void SetFogColor(void *frame, const Vec3 &c) { + FogFlags(frame) |= Offsets::SIMPLEMODEL_FOG_ARMED; + Game::Ref(frame, Offsets::OFF_SIMPLEMODEL_FOG_COLOR) = + 0xFF000000u | (FogByte(c.x) << 16) | (FogByte(c.y) << 8) | FogByte(c.z); +} + +void InitFog(void *frame) { + Game::Ref(frame, Offsets::OFF_SIMPLEMODEL_FOG_COLOR) = 0xFFFFFFFFu; + Game::Ref(frame, Offsets::OFF_SIMPLEMODEL_FOG_NEAR) = 1.0e7f; + Game::Ref(frame, Offsets::OFF_SIMPLEMODEL_FOG_FAR) = 1.0e8f; } // ---- the paint (SimpleModelDraw) ----------------------------------------------- @@ -311,7 +385,10 @@ void __fastcall SetFrameAlpha(void *self, void *, uint8_t alpha) { } void __fastcall OnFrameUpdate(void *self, void *, float elapsedSec) { - ModelBase(Offsets::VTBL_FRAME_ON_FRAME_UPDATE)(self, nullptr, elapsedSec); + if (F(self).paused) + FrameBase(Offsets::VTBL_FRAME_ON_FRAME_UPDATE)(self, nullptr, elapsedSec); + else + 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) @@ -327,6 +404,34 @@ void __fastcall EmitLayer(void *self, void *, void *batch, int layer) { void __fastcall UpdateModel(void *self) { PlaceActors(self); } +using LoadXML_t = uintptr_t(__fastcall *)(void *layout, void *edx, const void *node, void *status); + +// The frame's own loader, then ModelSceneType's attributes and . +uintptr_t __fastcall LoadXML(void *layout, void *, const void *node, void *status) { + using LayerFromName_t = int(__fastcall *)(const char *name, int *layer); + using ReadColor_t = int(__fastcall *)(const void *node, uint32_t *bgra, void *status); + const uintptr_t result = Frame::Subclass::Slot( + Offsets::VTBL_SIMPLEFRAME_LAYOUT, Offsets::VTBL_XML_NODE_LOADER)(layout, nullptr, node, status); + if (node == nullptr) + return result; + void *frame = FrameOfLayout(layout); + if (const char *layer = Xml::Attr(node, "drawLayer"); layer != nullptr && *layer != '\0') + reinterpret_cast(Offsets::FUN_XML_DRAW_LAYER_FROM_NAME)(layer, &F(frame).drawLayer); + float value = 0.0f; + if (Xml::FloatAttr(node, "fogNear", value)) + Game::Ref(frame, Offsets::OFF_SIMPLEMODEL_FOG_NEAR) = value < 0.0f ? 0.0f : value; + if (Xml::FloatAttr(node, "fogFar", value)) + Game::Ref(frame, Offsets::OFF_SIMPLEMODEL_FOG_FAR) = value < 0.0f ? 0.0f : value; + for (const void *c = Xml::FirstChild(node); c != nullptr; c = Xml::NextSibling(c)) { + if (!Xml::TagIs(c, "FogColor")) + continue; + reinterpret_cast(Offsets::FUN_XML_READ_COLOR)( + c, Game::Ptr(frame, Offsets::OFF_SIMPLEMODEL_FOG_COLOR), status); + FogFlags(frame) |= Offsets::SIMPLEMODEL_FOG_ARMED; + } + return result; +} + void BuildVTables() { if (g_vtable.Built()) return; @@ -345,9 +450,7 @@ void BuildVTables() { 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)); + g_layoutVtable.Set(Offsets::VTBL_XML_NODE_LOADER, fn(&LoadXML)); } // The "ModelScene" factory, shaped like the engine's "Model" one (0x006EECF0). @@ -371,6 +474,7 @@ void *__fastcall CreateModelScene(void *parent) { f.farClip = kDefaultFarClip; f.drawLayer = Offsets::DRAWLAYER_ARTWORK; InitLight(frame); + InitFog(frame); InstallCamera(frame); return frame; } @@ -407,14 +511,20 @@ int __fastcall Script_CreateActor(void *L) { if (frame == nullptr) return 0; const char *name = Game::Lua::IsString(L, 2) ? Game::Lua::ToString(L, 2) : nullptr; + const void *templateNode = 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; + const char *inherits = Game::Lua::ToString(L, 3); + templateNode = Xml::Template(inherits); + if (templateNode == nullptr) { + Game::Lua::Error(L, "%s:CreateActor(): Couldn't find inherited node \"%s\"", + Game::Lua::ObjectDisplayName(frame), inherits); + return 0; + } } Actor *actor = new Actor(frame, name); F(frame).actors->push_back(actor); + if (templateNode != nullptr) + actor->LoadXml(templateNode, nullptr); Animation::Push(L, actor); return 1; } @@ -494,9 +604,9 @@ int __fastcall Script_GetCameraUp(void *L) { } // The one-number camera setters and getters. -constexpr char kSetFieldOfView[] = "SetCameraFieldOfView(fov)"; -constexpr char kSetNearClip[] = "SetCameraNearClip(nearClip)"; -constexpr char kSetFarClip[] = "SetCameraFarClip(farClip)"; +constexpr char kUsageSetFieldOfView[] = "SetCameraFieldOfView(fov)"; +constexpr char kUsageSetNearClip[] = "SetCameraNearClip(nearClip)"; +constexpr char kUsageSetFarClip[] = "SetCameraFarClip(farClip)"; template int __fastcall SetCameraScalar(void *L) { @@ -517,6 +627,176 @@ int __fastcall GetCameraScalar(void *L) { return 1; } +void NotifyLayerChanged(void *frame, int layer) { + using Fn_t = void(__fastcall *)(void *self, void *edx, int layer); + reinterpret_cast(Offsets::FUN_FRAME_NOTIFY_LAYER_CHANGED)(frame, nullptr, layer); +} + +int __fastcall Script_SetDrawLayer(void *L) { + using LayerFromName_t = int(__fastcall *)(const char *name, int *layer); + void *frame = Self(L); + if (frame == nullptr) + return 0; + int layer = 0; + if (!Game::Lua::IsString(L, 2) || + !reinterpret_cast(Offsets::FUN_XML_DRAW_LAYER_FROM_NAME)( + Game::Lua::ToString(L, 2), &layer)) { + Game::Lua::Error(L, "Usage: %s:SetDrawLayer(layer)", Game::Lua::ObjectDisplayName(frame)); + return 0; + } + Fields &f = F(frame); + if (layer == f.drawLayer) + return 0; + const int old = f.drawLayer; + f.drawLayer = layer; + NotifyLayerChanged(frame, old); + NotifyLayerChanged(frame, layer); + return 0; +} + +int __fastcall Script_GetDrawLayer(void *L) { + using LayerToName_t = const char *(__fastcall *)(int layer); + void *frame = Self(L); + if (frame == nullptr) + return 0; + Game::Lua::PushString( + L, reinterpret_cast(Offsets::FUN_DRAW_LAYER_TO_NAME)(F(frame).drawLayer)); + Game::Lua::PushNumber(L, 0); + return 2; +} + +int __fastcall Script_SetPaused(void *L) { + void *frame = Self(L); + if (frame == nullptr) + return 0; + F(frame).paused = Game::Lua::ToBoolean(L, 2) != 0 ? 1 : 0; + return 0; +} + +int __fastcall Script_SetLightType(void *L) { + void *frame = Self(L); + if (frame == nullptr || !NumberArgs(L, 2, 1, frame, "SetLightType(lightType)")) + return 0; + SetLightType(frame, Game::Lua::ToNumber(L, 2) != 0.0 ? 1u : 0u); + return 0; +} + +int __fastcall Script_GetLightType(void *L) { + void *frame = Self(L); + if (frame == nullptr) + return 0; + Game::Lua::PushNumber(L, F(frame).lightType); + return 1; +} + +int __fastcall Script_SetLightVisible(void *L) { + if (void *frame = Self(L)) + SetLightVisible(frame, Game::Lua::ToBoolean(L, 2) != 0); + return 0; +} + +int __fastcall Script_IsLightVisible(void *L) { + void *frame = Self(L); + if (frame == nullptr) + return 0; + Game::Lua::PushBool(L, F(frame).lightVisible != 0); + return 1; +} + +int __fastcall Script_SetLightDirection(void *L) { + void *frame = Self(L); + if (frame == nullptr || !NumberArgs(L, 2, 3, frame, "SetLightDirection(x, y, z)")) + return 0; + SetLightDirection(frame, Vec3Args(L, 2)); + return 0; +} + +int __fastcall Script_GetLightDirection(void *L) { + void *frame = Self(L); + return frame != nullptr ? PushVec3(L, F(frame).lightDirection) : 0; +} + +int __fastcall Script_SetLightPosition(void *L) { + void *frame = Self(L); + if (frame == nullptr || !NumberArgs(L, 2, 3, frame, "SetLightPosition(x, y, z)")) + return 0; + SetLightPosition(frame, Vec3Args(L, 2)); + return 0; +} + +int __fastcall Script_GetLightPosition(void *L) { + void *frame = Self(L); + return frame != nullptr ? PushVec3(L, F(frame).lightPosition) : 0; +} + +int SetLightColor(void *L, float *(*color)(void *), const char *usage) { + void *frame = Self(L); + if (frame == nullptr || !NumberArgs(L, 2, 3, frame, usage)) + return 0; + SetColor(color(frame), Vec3Args(L, 2)); + return 0; +} + +int GetLightColor(void *L, float *(*color)(void *)) { + void *frame = Self(L); + if (frame == nullptr) + return 0; + const float *c = color(frame); + return PushVec3(L, {c[0], c[1], c[2]}); +} + +int __fastcall Script_SetLightAmbientColor(void *L) { + return SetLightColor(L, &AmbientOf, "SetLightAmbientColor(colorR, colorG, colorB)"); +} +int __fastcall Script_GetLightAmbientColor(void *L) { return GetLightColor(L, &AmbientOf); } +int __fastcall Script_SetLightDiffuseColor(void *L) { + return SetLightColor(L, &DiffuseOf, "SetLightDiffuseColor(colorR, colorG, colorB)"); +} +int __fastcall Script_GetLightDiffuseColor(void *L) { return GetLightColor(L, &DiffuseOf); } + +int __fastcall Script_SetFogColor(void *L) { + void *frame = Self(L); + if (frame == nullptr || !NumberArgs(L, 2, 3, frame, "SetFogColor(colorR, colorG, colorB)")) + return 0; + SetFogColor(frame, Vec3Args(L, 2)); + return 0; +} + +int __fastcall Script_GetFogColor(void *L) { + void *frame = Self(L); + if (frame == nullptr) + return 0; + const uint32_t c = Game::Read(frame, Offsets::OFF_SIMPLEMODEL_FOG_COLOR); + return PushVec3(L, {((c >> 16) & 0xFF) / 255.0f, ((c >> 8) & 0xFF) / 255.0f, (c & 0xFF) / 255.0f}); +} + +template +int __fastcall SetFogDistance(void *L) { + void *frame = Self(L); + if (frame == nullptr || !NumberArgs(L, 2, 1, frame, Usage)) + return 0; + Game::Ref(frame, Offset) = FloatArg(L, 2); + return 0; +} + +template +int __fastcall GetFogDistance(void *L) { + void *frame = Self(L); + if (frame == nullptr) + return 0; + Game::Lua::PushNumber(L, Game::Read(frame, Offset)); + return 1; +} + +constexpr char kUsageSetFogNear[] = "SetFogNear(near)"; +constexpr char kUsageSetFogFar[] = "SetFogFar(far)"; + +int __fastcall Script_ClearFog(void *L) { + if (void *frame = Self(L)) + FogFlags(frame) &= ~static_cast(Offsets::SIMPLEMODEL_FOG_ARMED); + return 0; +} + const Game::Lua::FrameMethodEntry g_methods[] = { {"CreateActor", &Script_CreateActor}, {"GetNumActors", &Script_GetNumActors}, @@ -528,12 +808,34 @@ const Game::Lua::FrameMethodEntry g_methods[] = { {"GetCameraForward", &Script_GetCameraForward}, {"GetCameraRight", &Script_GetCameraRight}, {"GetCameraUp", &Script_GetCameraUp}, - {"SetCameraFieldOfView", &SetCameraScalar<&Fields::fieldOfView, kSetFieldOfView>}, + {"SetCameraFieldOfView", &SetCameraScalar<&Fields::fieldOfView, kUsageSetFieldOfView>}, {"GetCameraFieldOfView", &GetCameraScalar<&Fields::fieldOfView>}, - {"SetCameraNearClip", &SetCameraScalar<&Fields::nearClip, kSetNearClip>}, + {"SetCameraNearClip", &SetCameraScalar<&Fields::nearClip, kUsageSetNearClip>}, {"GetCameraNearClip", &GetCameraScalar<&Fields::nearClip>}, - {"SetCameraFarClip", &SetCameraScalar<&Fields::farClip, kSetFarClip>}, + {"SetCameraFarClip", &SetCameraScalar<&Fields::farClip, kUsageSetFarClip>}, {"GetCameraFarClip", &GetCameraScalar<&Fields::farClip>}, + {"SetDrawLayer", &Script_SetDrawLayer}, + {"GetDrawLayer", &Script_GetDrawLayer}, + {"SetPaused", &Script_SetPaused}, + {"SetLightType", &Script_SetLightType}, + {"GetLightType", &Script_GetLightType}, + {"SetLightVisible", &Script_SetLightVisible}, + {"IsLightVisible", &Script_IsLightVisible}, + {"SetLightDirection", &Script_SetLightDirection}, + {"GetLightDirection", &Script_GetLightDirection}, + {"SetLightPosition", &Script_SetLightPosition}, + {"GetLightPosition", &Script_GetLightPosition}, + {"SetLightAmbientColor", &Script_SetLightAmbientColor}, + {"GetLightAmbientColor", &Script_GetLightAmbientColor}, + {"SetLightDiffuseColor", &Script_SetLightDiffuseColor}, + {"GetLightDiffuseColor", &Script_GetLightDiffuseColor}, + {"SetFogColor", &Script_SetFogColor}, + {"GetFogColor", &Script_GetFogColor}, + {"SetFogNear", &SetFogDistance}, + {"GetFogNear", &GetFogDistance}, + {"SetFogFar", &SetFogDistance}, + {"GetFogFar", &GetFogDistance}, + {"ClearFog", &Script_ClearFog}, }; // ---- documentation -------------------------------------------------------------- @@ -602,7 +904,82 @@ const Game::Doc::Function kSetCameraFarClip{"Sets the farthest distance the came const Game::Doc::Function kGetCameraFarClip{"Returns the farthest distance the camera draws.", {}, kFarRet}; +const Game::Doc::Field kLayerArg[] = {Req("layer", "DrawLayer")}; +const Game::Doc::Field kLayerRets[] = {Req("layer", "DrawLayer"), Req("sublevel", "number")}; +const Game::Doc::Field kPausedArgs[] = { + Req("paused", "bool"), + Opt("affectsGlobalPause", "bool", "true", "Has no effect."), +}; +const Game::Doc::Field kLightTypeArg[] = {Req("lightType", "ModelLightType")}; +const Game::Doc::Field kLightTypeRet[] = {Req("lightType", "ModelLightType")}; +const Game::Doc::Field kVisibleArg[] = {Opt("visible", "bool", "false")}; +const Game::Doc::Field kVisibleRet[] = {Req("isVisible", "bool")}; +const Game::Doc::Field kDirectionArgs[] = {Req("directionX", "number"), Req("directionY", "number"), + Req("directionZ", "number")}; +const Game::Doc::Field kDirectionRets[] = {Req("directionX", "number"), Req("directionY", "number"), + Req("directionZ", "number")}; +const Game::Doc::Field kColorArgs[] = {Req("colorR", "number"), Req("colorG", "number"), + Req("colorB", "number")}; +const Game::Doc::Field kColorRets[] = {Req("colorR", "number"), Req("colorG", "number"), + Req("colorB", "number")}; +const Game::Doc::Field kNearFogArg[] = {Req("near", "number")}; +const Game::Doc::Field kNearFogRet[] = {Req("near", "number")}; +const Game::Doc::Field kFarFogArg[] = {Req("far", "number")}; +const Game::Doc::Field kFarFogRet[] = {Req("far", "number")}; + +const Game::Doc::Function kSetDrawLayer{"Sets the layer the scene draws in.", kLayerArg, {}}; +const Game::Doc::Function kGetDrawLayer{"Returns the layer the scene draws in.", {}, kLayerRets}; +const Game::Doc::Function kSetPaused{"Stops or restarts the actors' animations.", kPausedArgs, {}}; +const Game::Doc::Function kSetLightType{"Makes the light directional or a point light.", + kLightTypeArg, {}}; +const Game::Doc::Function kGetLightType{"Returns the light's type.", {}, kLightTypeRet}; +const Game::Doc::Function kSetLightVisible{"Turns the light on or off.", kVisibleArg, {}}; +const Game::Doc::Function kIsLightVisible{"Returns whether the light is on.", {}, kVisibleRet}; +const Game::Doc::Function kSetLightDirection{"Sets the direction of a directional light.", + kDirectionArgs, {}}; +const Game::Doc::Function kGetLightDirection{"Returns the light's direction.", {}, kDirectionRets}; +const Game::Doc::Function kSetLightPosition{"Sets the position of a point light.", kPositionArgs, + {}}; +const Game::Doc::Function kGetLightPosition{"Returns the light's position.", {}, kPositionRets}; +const Game::Doc::Function kSetLightAmbientColor{"Sets the light's ambient colour.", kColorArgs, {}}; +const Game::Doc::Function kGetLightAmbientColor{"Returns the light's ambient colour.", {}, + kColorRets}; +const Game::Doc::Function kSetLightDiffuseColor{"Sets the light's diffuse colour.", kColorArgs, {}}; +const Game::Doc::Function kGetLightDiffuseColor{"Returns the light's diffuse colour.", {}, + kColorRets}; +const Game::Doc::Function kSetFogColor{"Sets the fog colour and turns the fog on.", kColorArgs, {}}; +const Game::Doc::Function kGetFogColor{"Returns the fog colour.", {}, kColorRets}; +const Game::Doc::Function kSetFogNear{"Sets the distance where the fog starts.", kNearFogArg, {}}; +const Game::Doc::Function kGetFogNear{"Returns the distance where the fog starts.", {}, + kNearFogRet}; +const Game::Doc::Function kSetFogFar{"Sets the distance where the fog is full.", kFarFogArg, {}}; +const Game::Doc::Function kGetFogFar{"Returns the distance where the fog is full.", {}, + kFarFogRet}; +const Game::Doc::Function kClearFog{"Turns the fog off.", {}, {}}; + const Game::Doc::Method g_methodDocs[] = { + {"SetDrawLayer", &kSetDrawLayer}, + {"GetDrawLayer", &kGetDrawLayer}, + {"SetPaused", &kSetPaused}, + {"SetLightType", &kSetLightType}, + {"GetLightType", &kGetLightType}, + {"SetLightVisible", &kSetLightVisible}, + {"IsLightVisible", &kIsLightVisible}, + {"SetLightDirection", &kSetLightDirection}, + {"GetLightDirection", &kGetLightDirection}, + {"SetLightPosition", &kSetLightPosition}, + {"GetLightPosition", &kGetLightPosition}, + {"SetLightAmbientColor", &kSetLightAmbientColor}, + {"GetLightAmbientColor", &kGetLightAmbientColor}, + {"SetLightDiffuseColor", &kSetLightDiffuseColor}, + {"GetLightDiffuseColor", &kGetLightDiffuseColor}, + {"SetFogColor", &kSetFogColor}, + {"GetFogColor", &kGetFogColor}, + {"SetFogNear", &kSetFogNear}, + {"GetFogNear", &kGetFogNear}, + {"SetFogFar", &kSetFogFar}, + {"GetFogFar", &kGetFogFar}, + {"ClearFog", &kClearFog}, {"CreateActor", &kCreateActor}, {"GetNumActors", &kGetNumActors}, {"GetActorAtIndex", &kGetActorAtIndex}, diff --git a/src/model/Scene.h b/src/model/Scene.h index 1583ca6d..46c5161e 100644 --- a/src/model/Scene.h +++ b/src/model/Scene.h @@ -17,6 +17,7 @@ #include #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. @@ -46,6 +47,10 @@ class Actor : public Animation::Object { void SetModel(void *model, const char *path, const uint8_t *dressRecord); void ClearModel(); void PlayAnimation(); + // Shows the kit (0 for none) on the model, replacing the one shown. + void SetSpellVisualKit(uint32_t kitID, bool oneShot); + // Loads the actor's XML element (an template), then runs OnLoad. + void LoadXml(const void *node, void *status); void *model = nullptr; std::string modelPath; @@ -64,6 +69,10 @@ class Actor : public Animation::Object { int variation = -1; float animSpeed = 1.0f; float animOffsetSec = 0.0f; + uint32_t blendOperation = 1; // Enum.ModelBlendOperation: 0 None, 1 Anim + uint32_t spellVisualKit = 0; + bool spellVisualKitOneShot = false; + std::vector kitEffects; // the kit's effect models, one reference each }; // Registers the actor class in the current Lua state. diff --git a/src/model/SceneActor.cpp b/src/model/SceneActor.cpp index 4f90f6f8..81789c40 100644 --- a/src/model/SceneActor.cpp +++ b/src/model/SceneActor.cpp @@ -50,14 +50,33 @@ // PlayerModel; OnModelLoaded runs once it is dressed. A finished animation // plays again (an actor keeps its animation, as PlayerModel re-arms Stand) // after OnAnimFinished. +// +// A spell visual kit is Model::VisualKit's routine (PlayerModel: +// ApplySpellVisualKit) on the actor's model, applied once the model has +// loaded (attaching waits for the file) and again on each new model; a new +// kit takes the old one's effects off first and resets its tint. 1.12 has no +// animation kits (AnimKit data is a later client's), so PlayAnimationKit and +// StopAnimationKit change nothing. +// +// XML: an element is a template CreateActor names (1.12's file loader +// registers every virtual top-level node whatever its tag), loaded the way an +// animation group is: the mixins of the whole inherits chain first, then each +// node from the base up: parentKey / parentArray on the scene, `alpha`, +// `scale`, `file`, and ; then OnLoad. `fileID` and +// `desaturation` load nothing: 1.12 has no file IDs and no model +// desaturation. #include "model/Scene.h" #include "Game.h" #include "Offsets.h" +#include "animation/Xml.h" #include "api/Documentation.h" #include "model/DisplayInfo.h" #include "model/M2.h" +#include "model/VisualKit.h" +#include "xml/FrameLoad.h" +#include "xml/Mixin.h" #include #include @@ -81,10 +100,36 @@ void __fastcall OnAnimDone(void * /*model*/, uint32_t /*keyBone*/, uint32_t /*an reinterpret_cast(static_cast(userLow))->animFinished = true; } +// Takes the kit's effects off the model and undoes its tint. +void DropKitEffects(Actor &actor) { + using Detach_t = void(__fastcall *)(void *model); + using SetDiffuse_t = void(__thiscall *)(void *model, const float *rgb); + for (void *effect : actor.kitEffects) { + if (M2::Parent(effect) != nullptr) + reinterpret_cast(Offsets::FUN_M2MODEL_DETACH)(effect); + M2::Release(effect); + } + actor.kitEffects.clear(); + if (actor.model != nullptr) { + const float white[3] = {1.0f, 1.0f, 1.0f}; + reinterpret_cast(Offsets::FUN_M2MODEL_SET_DIFFUSE_COLOR)(actor.model, white); + actor.ApplyAlpha(); + } +} + +void ApplyKit(Actor &actor) { + if (actor.model == nullptr || !actor.loaded || actor.spellVisualKit == 0) + return; + if (const uint8_t *kit = Model::VisualKit::Record(actor.spellVisualKit)) + Model::VisualKit::Apply(actor.SceneFrame(), actor.model, kit, actor.spellVisualKitOneShot, + &actor.kitEffects); +} + // Releases the model without scripts (a destroyed actor runs none). void ReleaseModel(Actor &actor) { if (actor.model == nullptr) return; + DropKitEffects(actor); M2::SetAnimDoneCallback(actor.model, nullptr, 0, 0); M2::SetVisible(actor.model, false); Model::DisplayInfo::DestroyDresser(actor.dresser); @@ -130,7 +175,54 @@ 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); + M2::PlayAnimation(model, -1, animation, variation, offsetMs, animSpeed, + static_cast(blendOperation), 1); +} + +void Actor::SetSpellVisualKit(uint32_t kitID, bool oneShot) { + DropKitEffects(*this); + spellVisualKit = kitID; + spellVisualKitOneShot = oneShot; + ApplyKit(*this); +} + +namespace { + +// LoadXml re-enters LoadNode for each inherited template; the mixins of the +// whole chain go in once, first (Xml::Mixin). +void LoadNode(Actor &actor, const void *node, void *status) { + if (const char *inherits = ::Xml::Attr(node, "inherits"); inherits != nullptr && *inherits != '\0') { + if (const void *base = ::Xml::Template(inherits)) + LoadNode(actor, base, status); + else + ::Xml::Warn(status, "Couldn't find inherited node: %s", inherits); + } + Animation::Xml::BindParentKey(actor.SceneFrame(), &actor, ::Xml::Attr(node, "parentKey")); + Animation::Xml::BindParentArray(actor.SceneFrame(), &actor, ::Xml::Attr(node, "parentArray")); + float value = 0.0f; + if (::Xml::FloatAttr(node, "alpha", value)) { + actor.alpha = value < 0.0f ? 0.0f : (value > 1.0f ? 1.0f : value); + actor.ApplyAlpha(); + } + if (::Xml::FloatAttr(node, "scale", value)) + actor.scale = value; + if (const char *file = ::Xml::Attr(node, "file"); file != nullptr && *file != '\0') + actor.SetModel(M2::CreateModel(Model::Pane::Scene(actor.SceneFrame()), file), file, nullptr); + Animation::Xml::LoadScripts(&actor, node); + Animation::Xml::LoadKeyValues(&actor, node, status); +} + +} // namespace + +void Actor::LoadXml(const void *node, void *status) { + if (void *L = Game::Lua::State()) { + const int top = Game::Lua::GetTop(L); + Animation::Push(L, this); + ::Xml::Mixin::ApplyChain(L, top + 1, node, status, DisplayName(), false); + Game::Lua::SetTop(L, top); + } + LoadNode(*this, node, status); + RunScript(S_ONLOAD, 0); } void Actor::ApplyAlpha() { @@ -158,6 +250,7 @@ void Actor::Update(float elapsedSec) { } if (ready && M2::IsLoaded(model, 0, 1)) { loaded = true; + ApplyKit(*this); RunScript(S_ONMODELLOADED, 0); } } @@ -418,6 +511,47 @@ int __fastcall Script_GetAnimationVariation(void *L) { return 1; } +int __fastcall Script_SetAnimationBlendOperation(void *L) { + Actor *actor = Self(L); + if (actor == nullptr || + !NumberArgs(L, 2, 1, "SetAnimationBlendOperation(blendOperation)", actor)) + return 0; + actor->blendOperation = Game::Lua::ToNumber(L, 2) != 0.0 ? 1u : 0u; + return 0; +} + +int __fastcall Script_GetAnimationBlendOperation(void *L) { + Actor *actor = Self(L); + if (actor == nullptr) + return 0; + Game::Lua::PushNumber(L, actor->blendOperation); + return 1; +} + +int __fastcall Script_SetSpellVisualKit(void *L) { + Actor *actor = Self(L); + if (actor == nullptr) + return 0; + const auto kitID = + Game::Lua::IsNumber(L, 2) ? static_cast(Game::Lua::ToNumber(L, 2)) : 0u; + actor->SetSpellVisualKit(kitID, Game::Lua::ToBoolean(L, 3) != 0); + return 0; +} + +int __fastcall Script_GetSpellVisualKit(void *L) { + Actor *actor = Self(L); + if (actor == nullptr) + return 0; + Game::Lua::PushNumber(L, actor->spellVisualKit); + return 1; +} + +// No animation kits in this client: nothing to play or stop. +int __fastcall Script_AnimationKit(void *L) { + Self(L); + return 0; +} + // 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]) { @@ -483,6 +617,12 @@ const Game::Lua::FrameMethodEntry kMethods[] = { {"GetAnimationVariation", &Script_GetAnimationVariation}, {"GetActiveBoundingBox", &Script_GetActiveBoundingBox}, {"GetMaxBoundingBox", &Script_GetMaxBoundingBox}, + {"SetAnimationBlendOperation", &Script_SetAnimationBlendOperation}, + {"GetAnimationBlendOperation", &Script_GetAnimationBlendOperation}, + {"SetSpellVisualKit", &Script_SetSpellVisualKit}, + {"GetSpellVisualKit", &Script_GetSpellVisualKit}, + {"PlayAnimationKit", &Script_AnimationKit}, + {"StopAnimationKit", &Script_AnimationKit}, }; // ---- documentation -------------------------------------------------------------- @@ -538,6 +678,29 @@ const Game::Doc::Field kBoxRets[] = { Req("topX", "number"), Req("topY", "number"), Req("topZ", "number"), }; +const Game::Doc::Field kBlendArg[] = {Req("blendOperation", "ModelBlendOperation")}; +const Game::Doc::Field kBlendRet[] = {Req("blendOperation", "ModelBlendOperation")}; +const Game::Doc::Field kKitArgs[] = { + Opt("spellVisualKitID", "number", "0", "A SpellVisualKit ID; 0 removes the kit."), + Opt("oneShot", "bool", "false", "True plays the effects once."), +}; +const Game::Doc::Field kKitRet[] = {Req("spellVisualKitID", "number")}; +const Game::Doc::Field kAnimKitArgs[] = { + Req("animationKit", "number"), + Opt("isLooping", "bool", "false"), +}; +const Game::Doc::Function kSetAnimationBlendOperation{ + "Sets whether a new animation blends from the one playing.", kBlendArg, {}}; +const Game::Doc::Function kGetAnimationBlendOperation{ + "Returns whether a new animation blends from the one playing.", {}, kBlendRet}; +const Game::Doc::Function kSetSpellVisualKit{ + "Shows a spell visual kit on the model, in place of the one shown.", kKitArgs, {}}; +const Game::Doc::Function kGetSpellVisualKit{"Returns the spell visual kit shown.", {}, kKitRet}; +const Game::Doc::Function kPlayAnimationKit{ + "Has no effect: this client has no animation kits.", kAnimKitArgs, {}}; +const Game::Doc::Function kStopAnimationKit{ + "Has no effect: this client has no animation kits.", {}, {}}; + 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}; @@ -609,6 +772,12 @@ const Game::Doc::Method kMethodDocs[] = { {"GetAnimationVariation", &kGetAnimationVariation}, {"GetActiveBoundingBox", &kGetActiveBoundingBox}, {"GetMaxBoundingBox", &kGetMaxBoundingBox}, + {"SetAnimationBlendOperation", &kSetAnimationBlendOperation}, + {"GetAnimationBlendOperation", &kGetAnimationBlendOperation}, + {"SetSpellVisualKit", &kSetSpellVisualKit}, + {"GetSpellVisualKit", &kGetSpellVisualKit}, + {"PlayAnimationKit", &kPlayAnimationKit}, + {"StopAnimationKit", &kStopAnimationKit}, }; } // namespace diff --git a/src/model/VisualKit.cpp b/src/model/VisualKit.cpp index 6eb59410..c8381aa3 100644 --- a/src/model/VisualKit.cpp +++ b/src/model/VisualKit.cpp @@ -52,6 +52,7 @@ #include "model/DisplayInfo.h" #include "model/M2.h" #include "model/Teardown.h" +#include "model/VisualKit.h" #include "tick/FrameTick.h" #include @@ -164,11 +165,18 @@ void ApplyProcedures(void *model, const uint8_t *kit) { } } -void Apply(void *pane, const uint8_t *kit, bool oneShot) { - void *model = Pane::Model(pane); +} // namespace + +const uint8_t *Record(uint32_t kitID) { + return DBC::Record(Offsets::VAR_SPELLVISUALKIT_RECORDS, Offsets::VAR_SPELLVISUALKIT_COUNT, + kitID); +} + +void Apply(void *frame, void *model, const uint8_t *kit, bool oneShot, + std::vector *effects) { if (model == nullptr) return; - void *scene = Pane::Scene(pane); + void *scene = Pane::Scene(frame); for (int i = 0; i < static_cast(sizeof(kAttachments) / sizeof(kAttachments[0])); ++i) { const uint8_t *effect = DBC::Record( Offsets::VAR_SPELLVISUALEFFECTNAME_RECORDS, Offsets::VAR_SPELLVISUALEFFECTNAME_COUNT, @@ -183,16 +191,21 @@ void Apply(void *pane, const uint8_t *kit, bool oneShot) { continue; if (oneShot) M2::SetAnimDoneCallback(child, reinterpret_cast(&OnEffectDone), - static_cast(reinterpret_cast(pane)), 0); + static_cast(reinterpret_cast(frame)), 0); else M2::SetAnimDoneCallback(child, reinterpret_cast(&OnEffectLoop), 0, 0); reinterpret_cast(Offsets::FUN_M2MODEL_ATTACH)(child, model, kAttachments[i]); - M2::Release(child); + if (effects != nullptr) + effects->push_back(child); // our reference, handed over + else + M2::Release(child); } - Model::DisplayInfo::LightChildren(pane, model); + Model::DisplayInfo::LightChildren(frame, model); ApplyProcedures(model, kit); } +namespace { + int __fastcall Script_ApplySpellVisualKit(void *L) { void *pane = Game::Lua::ResolvePlayerModel(L); if (pane == nullptr) @@ -201,11 +214,8 @@ int __fastcall Script_ApplySpellVisualKit(void *L) { Game::Lua::Error(L, "Usage: ApplySpellVisualKit(spellVisualKitID [, oneShot])"); return 0; } - const uint8_t *kit = - DBC::Record(Offsets::VAR_SPELLVISUALKIT_RECORDS, Offsets::VAR_SPELLVISUALKIT_COUNT, - static_cast(Game::Lua::ToNumber(L, 2))); - if (kit != nullptr) - Apply(pane, kit, Game::Lua::ToBoolean(L, 3) != 0); + if (const uint8_t *kit = Record(static_cast(Game::Lua::ToNumber(L, 2)))) + Apply(pane, Pane::Model(pane), kit, Game::Lua::ToBoolean(L, 3) != 0); return 0; } diff --git a/src/model/VisualKit.h b/src/model/VisualKit.h new file mode 100644 index 00000000..c9d82367 --- /dev/null +++ b/src/model/VisualKit.h @@ -0,0 +1,33 @@ +// 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 +#include + +// A spell visual kit on a model in a Model frame's scene (model/VisualKit.cpp). +namespace Model::VisualKit { + +// The SpellVisualKit record, or null. +const uint8_t *Record(uint32_t kitID); + +// Hangs the kit's effect models on `model`, a model in `frame`'s scene, lit +// by the frame's light, and applies its tint and alpha procedures. A oneShot +// effect stops when its sequence ends; the others loop. When `effects` is +// given, each attached effect model is appended to it with one reference the +// caller then owns; otherwise the effects live as long as `model` holds them. +void Apply(void *frame, void *model, const uint8_t *kit, bool oneShot, + std::vector *effects = nullptr); + +} // namespace Model::VisualKit