diff --git a/README.md b/README.md index dec37037..7131a286 100644 --- a/README.md +++ b/README.md @@ -89,7 +89,7 @@ In the Frame rows, a name that starts with `:` is a method of the widget that th | [Frame: StatusBar](docs/API.md#statusbarsetreversefillisreversefill--statusbargetreversefill) | `:SetReverseFill` / `:GetReverseFill`, `:SetRotatesTexture` / `:GetRotatesTexture`, `:SetFillStyle` / `:GetFillStyle`, `:SetColorFill`, `:SetStatusBarDesaturated` / `:IsStatusBarDesaturated`, `:SetStatusBarDesaturation` / `:GetStatusBarDesaturation`, `:SetTimerDuration` / `:GetTimerDuration`, `:SetValue` / `:SetMinMaxValues` with `interpolation`, `:GetInterpolatedValue`, `:IsInterpolating`, `:SetToTargetValue` | | [Frame: Slider](docs/API.md#sliderenable--sliderdisable--sliderisenabled) | `:Enable` / `:Disable` / `:IsEnabled` | | [Frame: Cooldown](docs/API.md#createframecooldown--name-parent-template) | `CreateFrame("Cooldown")`, `:SetCooldown`, `:SetCooldownDuration`, `:SetCooldownFromExpirationTime`, `:Clear`, `:GetCooldownTimes`, `:GetCooldownDuration`, `:GetCooldownDisplayDuration`, `:Pause` / `:Resume`, `:SetPaused` / `:IsPaused`, `:SetReverse` / `:GetReverse`, `:SetDrawEdge` / `:GetDrawEdge`, `:SetDrawSwipe` / `:GetDrawSwipe`, `:SetDrawBling` / `:GetDrawBling`, `:SetSwipeColor`, `:SetEdgeColor`, `:SetSwipeTexture`, `:SetEdgeTexture`, `:SetBlingTexture`, `:SetRotation` / `:GetRotation`, `:SetHideCountdownNumbers` / `:GetHideCountdownNumbers`, `:GetCountdownFontString`, `:SetCountdownAbbrevThreshold` / `:GetCountdownAbbrevThreshold`, `:SetCountdownMillisecondsThreshold` / `:GetCountdownMillisecondsThreshold`, `:SetMinimumCountdownDuration` / `:GetMinimumCountdownDuration`, `OnCooldownDone`, `CooldownFrame_Set`, `CooldownFrame_Clear`, `CooldownFrame_SetDisplayAsPercentage` | -| [Frame: ModelScene](docs/API.md#modelscene) | `CreateFrame("ModelScene")`, `` (`drawLayer`, `fogNear`, `fogFar`, ``, ``), `:CreateActor`, `:GetNumActors`, `:GetActorAtIndex`, `:SetCameraPosition` / `:GetCameraPosition`, `:SetCameraOrientationByYawPitchRoll`, `:SetCameraOrientationByAxisVectors`, `:GetCameraForward`, `:GetCameraRight`, `:GetCameraUp`, `:SetCameraFieldOfView` / `:GetCameraFieldOfView`, `:SetCameraNearClip` / `:GetCameraNearClip`, `:SetCameraFarClip` / `:GetCameraFarClip`, `:SetViewInsets` / `:GetViewInsets`, `:SetViewTranslation` / `:GetViewTranslation`, `:Project3DPointTo2D`, `:SetLightType` / `:GetLightType`, `:SetLightVisible` / `:IsLightVisible`, `:SetLightDirection` / `:GetLightDirection`, `:SetLightPosition` / `:GetLightPosition`, `:SetLightAmbientColor` / `:GetLightAmbientColor`, `:SetLightDiffuseColor` / `:GetLightDiffuseColor`, `:SetFogColor` / `:GetFogColor`, `:SetFogNear` / `:GetFogNear`, `:SetFogFar` / `:GetFogFar`, `:ClearFog`, `:SetDrawLayer` / `:GetDrawLayer`, `:SetPaused`, `:SetAllowOverlappedModels` / `:GetAllowOverlappedModels`, `:SetGroundTerrain` / `:GetGroundTerrain` | +| [Frame: ModelScene](docs/API.md#modelscene) | `CreateFrame("ModelScene")`, `` (`drawLayer`, `fogNear`, `fogFar`, ``, ``), `:CreateActor`, `:GetNumActors`, `:GetActorAtIndex`, `:SetCameraPosition` / `:GetCameraPosition`, `:SetCameraOrientationByYawPitchRoll`, `:SetCameraOrientationByAxisVectors`, `:GetCameraForward`, `:GetCameraRight`, `:GetCameraUp`, `:SetCameraFieldOfView` / `:GetCameraFieldOfView`, `:SetCameraNearClip` / `:GetCameraNearClip`, `:SetCameraFarClip` / `:GetCameraFarClip`, `:SetViewInsets` / `:GetViewInsets`, `:SetViewTranslation` / `:GetViewTranslation`, `:Project3DPointTo2D`, `:SetLightType` / `:GetLightType`, `:SetLightVisible` / `:IsLightVisible`, `:SetLightDirection` / `:GetLightDirection`, `:SetLightPosition` / `:GetLightPosition`, `:SetLightAmbientColor` / `:GetLightAmbientColor`, `:SetLightDiffuseColor` / `:GetLightDiffuseColor`, `:SetFogColor` / `:GetFogColor`, `:SetFogNear` / `:GetFogNear`, `:SetFogFar` / `:GetFogFar`, `:ClearFog`, `:SetDrawLayer` / `:GetDrawLayer`, `:SetPaused`, `:SetAllowOverlappedModels` / `:GetAllowOverlappedModels`, `:SetGroundTerrain` / `:GetGroundTerrain`, `:GetActorAtCursor`, `OnActorEnter` / `OnActorLeave` | | [Frame: ModelSceneActor](docs/API.md#actorsetmodelbycreaturedisplayiddisplayid--useactiveplayercustomizations) | `:SetModelByCreatureDisplayID`, `:SetModelByPath`, `:SetModelByUnit`, `:SetModelByUnitCreatureDisplayID`, `:GetModelUnitGUID`, `:Dress`, `:Undress`, `:UndressSlot`, `:TryOn`, `:DressPlayerSlot`, `:IsSlotAllowed` / `:IsSlotVisible`, `:GetItemTransmogInfo`, `:GetItemTransmogInfoList`, `:SetItemTransmogInfo`, `:SetSheathed` / `:GetSheathed`, `:SetSheathedCategory`, `:UseUnitSheatheCategory`, `:SetAutoDress` / `:GetAutoDress`, `:IsGeoReady`, `:ClearModel`, `:IsLoaded`, `:GetModelPath`, `:SetPosition` / `:GetPosition`, `:SetYaw` / `:GetYaw`, `:SetPitch` / `:GetPitch`, `:SetRoll` / `:GetRoll`, `:SetScale` / `:GetScale`, `:SetUseCenterForOrigin` / `:IsUsingCenterForOrigin`, `:GetActiveBoundingBox`, `:GetMaxBoundingBox`, `:Show` / `:Hide` / `:SetShown` / `:IsShown` / `:IsVisible`, `:SetAlpha` / `:GetAlpha`, `:SetAnimation` / `:GetAnimation`, `:GetAnimationVariation`, `:SetAnimationBlendOperation` / `:GetAnimationBlendOperation`, `:SetPaused` / `:GetPaused`, `:SetSpellVisualKit` / `:GetSpellVisualKit`, `:ApplySpellVisualKit`, `:PlayAnimationKit` / `:StopAnimationKit`, `:AttachToMount`, `:DetachFromMount`, `:CalculateMountScale`, `:GetAttachmentPosition`, `:AttachToActor`, `:DetachFromActor`, `:PlaySpellVisual`, `:SetPlayAnimationSounds` / `:GetPlayAnimationSounds`, `OnLoad`, `OnUpdate`, `OnModelLoading`, `OnModelLoaded`, `OnModelCleared`, `OnAnimFinished`, `` templates | | [Frame: ScrollingMessageFrame](docs/API.md#smfsethyperlinksenabledenabled--smfgethyperlinksenabled) | `:SetHyperlinksEnabled` / `:GetHyperlinksEnabled`, `:GetMessageInfo` (with the extra `:AddMessage` values), `:BackFillMessage` (adds a message as the oldest), `:RemoveMessagesByPredicate`, `:SetScrollOffset` / `:GetScrollOffset`, `:GetMaxScrollRange`, `:ScrollByAmount`, `:SetInsertMode` / `:GetInsertMode`, `:AddOnDisplayRefreshedCallback` | | [Frame: scripts](docs/API.md#onenable-and-ondisable-scripts) | `OnEnable`, `OnDisable`, `OnMinMaxChanged`, `OnAttributeChanged`, `OnCharComposition`, `OnTextChanged` (`userInput`), `PreClick`, `PostClick`, `SetModernScriptArgs` / `GetModernScriptArgs` | diff --git a/docs/API.md b/docs/API.md index 3fb6be57..15832676 100644 --- a/docs/API.md +++ b/docs/API.md @@ -841,6 +841,8 @@ build instructions. - [`scene:SetPaused(paused [, affectsGlobalPause])`](#scenesetpausedpaused--affectsglobalpause) - [`scene:SetAllowOverlappedModels(allow)` / `scene:GetAllowOverlappedModels()`](#scenesetallowoverlappedmodelsallow--scenegetallowoverlappedmodels) - [`scene:SetGroundTerrain([terrainTypeID])` / `scene:GetGroundTerrain()`](#scenesetgroundterrainterraintypeid--scenegetgroundterrain) + - [`scene:GetActorAtCursor()`](#scenegetactoratcursor) + - [`OnActorEnter` / `OnActorLeave`](#onactorenter--onactorleave) - [`actor:SetModelByCreatureDisplayID(displayID [, useActivePlayerCustomizations])`](#actorsetmodelbycreaturedisplayiddisplayid--useactiveplayercustomizations) - [`actor:SetModelByPath(path [, useMips])`](#actorsetmodelbypathpath--usemips) - [`actor:SetModelByUnit(unit [, sheatheWeapons, autoDress, hideWeapons, usePlayerNativeForm, holdBowString, customRaceID])`](#actorsetmodelbyunitunit--sheatheweapons-autodress-hideweapons-useplayernativeform-holdbowstring-customraceid) @@ -19298,6 +19300,46 @@ footsteps and no death thuds. This is the default. `scene:GetGroundTerrain()` returns the ID, or nothing when the scene has no ground. This is a ClassicAPI extension. +### `scene:GetActorAtCursor()` + +Returns the actor under the cursor, or nothing. The test uses the triangles +that the scene draws for each shown actor: its model, its held items and +its spell visual kit effects. A space between the arms of a model is not +part of the model. When actors overlap, the function returns the actor +that is nearest to the camera. A seated rider is its own actor, not part of +its mount. Missiles and impact models of `PlaySpellVisual` are not part of +an actor. + +The function returns nothing when the cursor is outside the frame, when +the frame is hidden, and before the scene draws the actor for the first +time. This is a ClassicAPI extension. + +### `OnActorEnter` / `OnActorLeave` + +Scripts of the scene, with the arguments `(self, actor)`. When the actor +under the cursor changes, `OnActorLeave` runs for the old actor, then +`OnActorEnter` runs for the new actor. The actor under the cursor is the +one that `GetActorAtCursor` returns. Set the scripts with `SetScript`, +`HookScript`, or the elements `` and `` in +``: + +```lua +scene:EnableMouse(true) +scene:SetScript("OnActorEnter", function(self, actor) + print("enter", actor:GetModelPath()) +end) +scene:SetScript("OnActorLeave", function(self, actor) + print("leave", actor:GetModelPath()) +end) +``` + +The scripts run only while the scene is the frame under the mouse (see +`GetMouseFocus`). Thus the scene must take mouse input, for example with +`EnableMouse(true)`. When the cursor leaves the scene, `OnActorLeave` runs +for the last actor. While the scene is hidden, no script runs. When it +shows again, the scripts tell of the changes. This is a ClassicAPI +extension. + ### `actor:SetModelByCreatureDisplayID(displayID [, useActivePlayerCustomizations])` Shows a creature by its display ID (a `CreatureDisplayInfo` ID) and returns diff --git a/src/Offsets.h b/src/Offsets.h index de0bb0e4..0a7a3142 100644 --- a/src/Offsets.h +++ b/src/Offsets.h @@ -13323,6 +13323,27 @@ enum Offsets { FUN_M2SCENE_COPY_MODEL = 0x00707400, // M2SceneDraw — `__thiscall(scene, pass)`; the bake draws 0 then 1. FUN_M2SCENE_DRAW = 0x00708900, + // The world's object pick (0x00480A50, Ghidra): EnableRayHits, then + // SetHitTestMode on each candidate and its children (0x00480D90), then + // RayHit with retry 1, the ray in view space (the device view of the + // last collect, from the camera's eye). EnableRayHits — `__fastcall(scene)` + // sets scene +0x12C, which RayHit clears. + FUN_M2SCENE_ENABLE_RAY_HITS = 0x007089B0, + // M2SceneRayHit — `uint __thiscall(scene, const float p0[3], const float + // p1[3], float *fraction, int retry)`, ret 0x10 (the pick's four pushes, + // 0x00480C11..0x00480C2E): the nearest triangle on p0..p1 (within + // *fraction of it) of the instances on the hit list, animated in the + // scene's latest collect (instance +0x40 == scene +0x10). Mode 1 skins + // each visible submesh on the CPU and skips alpha 0. Writes the hit's + // fraction and returns the instance's hit value, else 0; empties the hit + // list on every call. With `retry`, a miss reruns with fattened meshes. + FUN_M2SCENE_RAY_HIT = 0x007089C0, + // CM2Model::SetHitTestMode — `__thiscall(model, mode, priority, value)`, + // ret 0xC (0x00713CB0): a nonzero mode links the instance into its + // scene's hit list (+0x414/+0x418 into scene +0x130) and stores mode + // +0x410, priority +0x420, value +0x41C. Mode 1 is the world pick's. + FUN_M2MODEL_SET_HIT_TEST_MODE = 0x00713CB0, + M2_HIT_TEST_SKINNED = 1, // `__fastcall(model)`: drops one instance reference (HandleClose2). FUN_MODEL_INSTANCE_RELEASE = 0x007103A0, // CM2Model::IsReady — `__thiscall(model, wait, recurseChildren)`: diff --git a/src/model/M2.h b/src/model/M2.h index 17dce6c4..964bc3b5 100644 --- a/src/model/M2.h +++ b/src/model/M2.h @@ -206,6 +206,36 @@ inline void GetSequenceBounds(void *model, uint32_t animation, uint32_t variatio box[i] = Game::Read(record, Offsets::OFF_M2_SEQUENCE_INFO_BOUNDS + i * 4); } +// The world pick's steps (Offsets::FUN_M2SCENE_RAY_HIT): ray hits on, the +// candidates on the scene's hit list, then the ray. +inline void EnableRayHits(void *scene) { + using Fn = void(__fastcall *)(void *); + reinterpret_cast(Offsets::FUN_M2SCENE_ENABLE_RAY_HITS)(scene); +} + +// Puts the model on its scene's hit list (skinned triangles), with `value` +// for RayHit to return. +inline void SetHitTest(void *model, uintptr_t value) { + using Fn = void(__thiscall *)(void *, int, int, uintptr_t); + reinterpret_cast(Offsets::FUN_M2MODEL_SET_HIT_TEST_MODE)(model, Offsets::M2_HIT_TEST_SKINNED, + 0, value); +} + +// The hit value of the nearest triangle on p0..p1 (view space), else 0. +// Empties the hit list. +inline uintptr_t RayHit(void *scene, const float (&p0)[3], const float (&p1)[3]) { + using Fn = uintptr_t(__thiscall *)(void *, const float *, const float *, float *, int); + float fraction = 1.0f; + return reinterpret_cast(Offsets::FUN_M2SCENE_RAY_HIT)(scene, p0, p1, &fraction, 1); +} + +inline void *FirstChild(const void *model) { + return Game::Read(model, Offsets::OFF_MODEL_INSTANCE_CHILD_HEAD); +} +inline void *NextSibling(const void *model) { + return Game::Read(model, Offsets::OFF_MODEL_INSTANCE_CHILD_NEXT); +} + inline void SetAnimated(void *model, bool animated) { using Fn = void(__thiscall *)(void *, int); reinterpret_cast(Offsets::FUN_M2MODEL_SET_ANIMATED)(model, animated ? 1 : 0); diff --git a/src/model/Scene.cpp b/src/model/Scene.cpp index 04cd40f5..6b3bb0f4 100644 --- a/src/model/Scene.cpp +++ b/src/model/Scene.cpp @@ -93,14 +93,21 @@ // SetAllowOverlappedModels only stores its flag (retail's default false, // probed): 1.12 draws a model frame whatever overlaps it, so there is nothing // for the flag to allow. Project3DPointTo2D is under "projection" below. +// +// ClassicAPI extensions: GetActorAtCursor, and the scripts OnActorEnter / +// OnActorLeave (self, actor), which run from the update walk when the actor +// under the cursor changes while the scene is the mouse focus. Both use the +// world's own object pick, under "picking" below. #include "model/Scene.h" #include "Game.h" #include "Offsets.h" #include "api/Documentation.h" +#include "frame/ExtraScripts.h" #include "frame/LayerChange.h" #include "frame/Layout.h" +#include "frame/ScriptArgs.h" #include "frame/Subclass.h" #include "gx/Device.h" #include "model/Camera.h" @@ -143,6 +150,7 @@ struct Fields { float viewInsets[4]; float viewTranslation[2]; int32_t groundTerrain; // SetGroundTerrain: a TerrainType id, or -1 + Actor *hovered; // the actor OnActorEnter last ran for, or null }; constexpr size_t kObjectSize = Offsets::MODEL_FRAME_SIZE + sizeof(Fields); @@ -326,6 +334,18 @@ void FitProjection(const float rect[4], const float view[4]) { Gx::SetProjection(m); } +// The device projection and view the paint draws with: the camera framed +// over the view rect, placed in the frame's rect. +void CameraTransforms(void *frame, void *camera, const float (&rect)[4]) { + float viewRect[4]; + if (ViewRect(frame, rect, viewRect)) { + Model::Camera::SetDeviceTransforms(camera, viewRect); + FitProjection(rect, viewRect); + } else { + Model::Camera::SetDeviceTransforms(camera, rect); + } +} + void __fastcall Paint(void *frame) { using SetupOrtho_t = void(__fastcall *)(const float *rect, const float *point, int unused); using DdcToNdc_t = void(__fastcall *)(float *x, float *y, float inX, float inY); @@ -344,13 +364,7 @@ void __fastcall Paint(void *frame) { eye[0] = e.x; eye[1] = e.y; eye[2] = e.z; - float viewRect[4]; - if (ViewRect(frame, rect, viewRect)) { - Model::Camera::SetDeviceTransforms(camera, viewRect); - FitProjection(rect, viewRect); - } else { - Model::Camera::SetDeviceTransforms(camera, rect); - } + CameraTransforms(frame, camera, rect); } else { const float point[2] = {rect[1], rect[0]}; reinterpret_cast(Offsets::FUN_SETUP_ORTHO_TRANSFORMS)(rect, point, 0); @@ -436,6 +450,119 @@ bool Project(void *frame, const Vec3 &point, double out[3]) { return true; } +// ---- picking (GetActorAtCursor) --------------------------------------------------- + +// The world's object pick (0x00480A50) on the scene's own M2 scene: ray hits +// on, each candidate's model and its children on the hit list +// (SetHitTestMode, as 0x00480D90 does it), then the engine's ray, which +// skins each model on the CPU and returns the value of the nearest triangle +// (models/scene.md: Ray hits). So an actor is picked by what it draws, not +// by its bounding box. The ray is in view space and the models are where the +// scene's latest paint put them (RayHit skips a model that paint did not +// animate), so the pick is what the frame shows. +// +// The ray is the cursor through the paint's projection (CameraTransforms): +// the camera's rect aspect (CCamera::SetDeviceTransforms 0x007AC640 reads +// nothing else of the rect) in the viewport the paint sets, the frame's rect +// clamped to the screen. It runs from the near clip to the far clip, by view +// depth (w', which FitProjection does not change). + +// The view-space point at clip (x, y) and view depth `depth`: solves +// x' = x w', y' = y w', w' = depth for the row-vector projection `m`. +bool Unproject(const Gx::Matrix &m, float x, float y, float depth, float (&out)[3]) { + double a[3][3], b[3]; + for (int j = 0; j < 3; ++j) { + a[0][j] = m[j * 4 + 0] - x * m[j * 4 + 3]; + a[1][j] = m[j * 4 + 1] - y * m[j * 4 + 3]; + a[2][j] = m[j * 4 + 3]; + } + b[0] = x * m[15] - m[12]; + b[1] = y * m[15] - m[13]; + b[2] = depth - m[15]; + auto det = [](const double (&r)[3][3]) { + return r[0][0] * (r[1][1] * r[2][2] - r[1][2] * r[2][1]) - + r[0][1] * (r[1][0] * r[2][2] - r[1][2] * r[2][0]) + + r[0][2] * (r[1][0] * r[2][1] - r[1][1] * r[2][0]); + }; + const double d = det(a); + if (!(std::fabs(d) > 1e-12)) + return false; + for (int j = 0; j < 3; ++j) { + double c[3][3]; + for (int r = 0; r < 3; ++r) + for (int k = 0; k < 3; ++k) + c[r][k] = k == j ? b[r] : a[r][k]; + out[j] = static_cast(det(c) / d); + } + return true; +} + +// The cursor in the clip space of the paint's viewport, the frame's rect +// {bottom, left, top, right} in NDC clamped to the screen; false when the +// cursor is outside it or the paint draws nothing. +bool CursorClip(const float (&rect)[4], float &x, float &y) { + using DdcToNdc_t = void(__fastcall *)(float *x, float *y, float inX, float inY); + const uint8_t *ctx = Game::Read(Offsets::VAR_UI_CONTEXT_PTR); + if (ctx == nullptr) + return false; + const float *mouse = Game::Ptr(ctx, Offsets::OFF_UI_CONTEXT_MOUSE_POSITION); + float vp[4] = {rect[0], rect[1], rect[2], rect[3]}; + auto toNdc = reinterpret_cast(Offsets::FUN_COORD_DDC_TO_NDC); + toNdc(&vp[1], &vp[0], vp[1], vp[0]); + toNdc(&vp[3], &vp[2], vp[3], vp[2]); + for (float &edge : vp) + edge = ClampUnit(edge); + const float epsilon = Game::Read(Offsets::VAR_HAS_RANGE_EPSILON); + if (std::fabs(vp[1] - vp[3]) < epsilon || std::fabs(vp[0] - vp[2]) < epsilon) + return false; + if (!(mouse[0] >= vp[1] && mouse[0] <= vp[3] && mouse[1] >= vp[0] && mouse[1] <= vp[2])) + return false; + x = 2.0f * (mouse[0] - vp[1]) / (vp[3] - vp[1]) - 1.0f; + y = 2.0f * (mouse[1] - vp[0]) / (vp[2] - vp[0]) - 1.0f; + return true; +} + +// The model and its children (held items, kit effects) on the hit list as +// `actor`. A child that is another actor's model (a seated rider) is that +// actor's to add. +void AddHitTest(void *model, Actor *actor, const std::vector &actors) { + M2::SetHitTest(model, reinterpret_cast(actor)); + for (void *child = M2::FirstChild(model); child != nullptr; child = M2::NextSibling(child)) { + bool otherActor = false; + for (const Actor *a : actors) + otherActor = otherActor || a->model == child; + if (!otherActor) + AddHitTest(child, actor, actors); + } +} + +// The shown actor whose model is nearest under the cursor, or null. +Actor *ActorAtCursor(void *frame) { + void *camera = CameraOf(frame); + float rect[4] = {}; // {bottom, left, top, right} + if (camera == nullptr || !Model::Pane::IsVisible(frame) || !Frame::Layout::GetRect(frame, rect)) + return nullptr; + float x = 0.0f, y = 0.0f; + if (!CursorClip(rect, x, y)) + return nullptr; + Gx::Matrix projection; + { + const Gx::SavedTransforms saved; + CameraTransforms(frame, camera, rect); + Gx::GetProjection(projection); + } + const Fields &f = F(frame); + float p0[3], p1[3]; + if (!Unproject(projection, x, y, f.nearClip, p0) || !Unproject(projection, x, y, f.farClip, p1)) + return nullptr; + void *scene = Model::Pane::Scene(frame); + M2::EnableRayHits(scene); + for (Actor *actor : *f.actors) + if (actor->shown && actor->model != nullptr) + AddHitTest(actor->model, actor, *f.actors); + return reinterpret_cast(M2::RayHit(scene, p0, p1)); +} + // ---- the overrides ----------------------------------------------------------------- using SetFrameAlpha_t = void(__fastcall *)(void *self, void *edx, uint8_t alpha); @@ -464,6 +591,49 @@ Frame::Subclass::Class(Offsets::VAR_UI_CONTEXT_PTR); + return ctx != nullptr && Game::Read(ctx, Offsets::OFF_UI_CONTEXT_MOUSE_FOCUS) == frame; +} + +// Picks only while a script would hear of it. +void UpdateHover(void *frame) { + Fields &f = F(frame); + Actor *now = nullptr; + if ((HasScript(g_onActorEnter, frame) || HasScript(g_onActorLeave, frame)) && IsMouseFocus(frame)) + now = ActorAtCursor(frame); + Actor *was = f.hovered; + if (now == was) + return; + f.hovered = now; + if (was != nullptr) + RunActorScript(g_onActorLeave, frame, was); + // OnActorLeave may have moved on to another actor. + if (now != nullptr && f.hovered == now) + RunActorScript(g_onActorEnter, frame, now); +} + void __fastcall SetFrameAlpha(void *self, void *, uint8_t alpha) { g_class.Base(Offsets::VTBL_FRAME_SET_FRAME_ALPHA)(self, nullptr, alpha); for (Actor *actor : *F(self).actors) @@ -481,6 +651,7 @@ void __fastcall OnFrameUpdate(void *self, void *, float elapsedSec) { std::vector &actors = *F(self).actors; for (size_t i = 0; i < actors.size(); ++i) actors[i]->Update(elapsedSec); + UpdateHover(self); } void __fastcall EmitLayer(void *self, void *, void *batch, int layer) { @@ -552,6 +723,7 @@ void *__fastcall CreateModelScene(void *parent) { f.farClip = kDefaultFarClip; f.drawLayer = Offsets::DRAWLAYER_ARTWORK; f.groundTerrain = -1; + f.hovered = nullptr; InitLight(frame); InitFog(frame); InstallCamera(frame); @@ -751,6 +923,17 @@ int __fastcall Script_Project3DPointTo2D(void *L) { return 3; } +int __fastcall Script_GetActorAtCursor(void *L) { + void *frame = Self(L); + if (frame == nullptr) + return 0; + Actor *actor = ActorAtCursor(frame); + if (actor == nullptr) + return 0; + Animation::Push(L, actor); + return 1; +} + int __fastcall Script_SetViewInsets(void *L) { void *frame = Self(L); if (frame == nullptr || !NumberArgs(L, 2, 4, Game::Lua::ObjectDisplayName(frame), @@ -982,6 +1165,7 @@ const Game::Lua::FrameMethodEntry g_methods[] = { {"SetAllowOverlappedModels", &Script_SetAllowOverlappedModels}, {"GetAllowOverlappedModels", &Script_GetAllowOverlappedModels}, {"Project3DPointTo2D", &Script_Project3DPointTo2D}, + {"GetActorAtCursor", &Script_GetActorAtCursor}, {"SetViewInsets", &Script_SetViewInsets}, {"GetViewInsets", &Script_GetViewInsets}, {"SetViewTranslation", &Script_SetViewTranslation}, @@ -1128,6 +1312,11 @@ const Game::Doc::Function kProject3DPointTo2D{ "Returns where a scene point appears on the scene. Returns nothing before the scene has a size, " "or for a point in the camera's plane.", kProjectArgs, kProjectRets}; +const Game::Doc::Function kGetActorAtCursor{ + "Returns the shown actor that the scene draws nearest under the cursor. The test uses the " + "triangles of the model, its held items and its effects. Returns nothing when no actor is " + "under the cursor.", + {}, kActorRet, nullptr, true}; const Game::Doc::Field kInsetArgs[] = {Req("left", "number"), Req("right", "number"), Req("top", "number"), Req("bottom", "number")}; const Game::Doc::Field kInsetRets[] = {Req("left", "number"), Req("right", "number"), Req("top", "number"), @@ -1180,6 +1369,7 @@ const Game::Doc::Method g_methodDocs[] = { {"SetGroundTerrain", &kSetGroundTerrain}, {"GetGroundTerrain", &kGetGroundTerrain}, {"Project3DPointTo2D", &kProject3DPointTo2D}, + {"GetActorAtCursor", &kGetActorAtCursor}, {"SetViewInsets", &kSetViewInsets}, {"GetViewInsets", &kGetViewInsets}, {"SetViewTranslation", &kSetViewTranslation},