diff --git a/README.md b/README.md index 26137e8b..c3c8b65f 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`, `"FollowCamera"` (`:SetFollowActor` / `:GetFollowActor`), `:SetLightType` / `:GetLightType`, `:SetLightVisible` / `:IsLightVisible`, `:SetLightDirection` / `:GetLightDirection`, `:SetLightPosition` / `:GetLightPosition`, `:SetLightAmbientColor` / `:GetLightAmbientColor`, `:SetLightDiffuseColor` / `:GetLightDiffuseColor`, `:SetFogColor` / `:GetFogColor`, `:SetFogNear` / `:GetFogNear`, `:SetFogFar` / `:GetFogFar`, `:ClearFog`, `:SetDrawLayer` / `:GetDrawLayer`, `:SetPaused`, `:GetSceneTime`, `:After`, `:NewTimer`, `:NewTicker`, `:SetAllowOverlappedModels` / `:GetAllowOverlappedModels`, `:SetGroundTerrain` / `:GetGroundTerrain`, `:SetWorldModel`, `:SetWorldModelByMapID`, `:ClearWorldModel`, `:SetPlayWorldModelSounds` / `:GetPlayWorldModelSounds`, `:TraceSegment`, `:GetLiquidAtPoint`, `:SweepCollider`, `:SetSoundListenerActor` / `:GetSoundListenerActor`, `:GetActorAtCursor`, `:GetCursorRay`, `:GetActorsInRadius`, `:SetMoveMarker` / `:ClearMoveMarker` / `:GetMoveMarker`, `OnActorEnter` / `OnActorLeave` | +| [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`, `"FollowCamera"` (`:SetFollowActor` / `:GetFollowActor`), `:SetLightType` / `:GetLightType`, `:SetLightVisible` / `:IsLightVisible`, `:SetLightDirection` / `:GetLightDirection`, `:SetLightPosition` / `:GetLightPosition`, `:SetLightAmbientColor` / `:GetLightAmbientColor`, `:SetLightDiffuseColor` / `:GetLightDiffuseColor`, `:SetFogColor` / `:GetFogColor`, `:SetFogNear` / `:GetFogNear`, `:SetFogFar` / `:GetFogFar`, `:ClearFog`, `:SetDrawLayer` / `:GetDrawLayer`, `:SetPaused`, `:GetSceneTime`, `:After`, `:NewTimer`, `:NewTicker`, `:SetAllowOverlappedModels` / `:GetAllowOverlappedModels`, `:SetGroundTerrain` / `:GetGroundTerrain`, `:SetWorldModel`, `:SetWorldModelByMapID`, `:ClearWorldModel`, `:SetWorldTerrain`, `:ClearWorldTerrain`, `:SetPlayWorldModelSounds` / `:GetPlayWorldModelSounds`, `:TraceSegment`, `:GetLiquidAtPoint`, `:SweepCollider`, `:SetSoundListenerActor` / `:GetSoundListenerActor`, `:GetActorAtCursor`, `:GetCursorRay`, `:GetActorsInRadius`, `:SetMoveMarker` / `:ClearMoveMarker` / `:GetMoveMarker`, `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`, `:StopSpellVisual`, `:PlaySound`, `:SetPlayAnimationSounds` / `:GetPlayAnimationSounds`, `:SetShadowShown` / `:IsShadowShown`, `:SetHighlight` / `:IsHighlighted`, `:SetSelectionCircle` / `:ClearSelectionCircle` / `:GetSelectionCircle`, `:SetNameText` / `:ClearNameText` / `:GetNameText`, `:GetNamePosition`, `:SetMovementEnabled` / `:IsMovementEnabled`, `:StartMovingForward`, `:StartMovingBackward`, `:StopMoving`, `:StartStrafingLeft`, `:StartStrafingRight`, `:StopStrafing`, `:StartTurningLeft`, `:StartTurningRight`, `:StopTurning`, `:Jump`, `:StartPitchingUp`, `:StartPitchingDown`, `:StopPitching`, `:IsFalling`, `:IsSwimming`, `:MoveTo`, `:SetWalking` / `:IsWalking`, `:GetCameraPivotHeight`, `OnLoad`, `OnUpdate`, `OnModelLoading`, `OnModelLoaded`, `OnModelCleared`, `OnAnimFinished`, `OnSpellVisualImpact`, `OnMoveFinished`, `` 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 131d1bcb..fcebf827 100644 --- a/docs/API.md +++ b/docs/API.md @@ -847,6 +847,8 @@ build instructions. - [`scene:SetWorldModel(path [, x, y, z [, yaw [, doodadSet [, mapID]]]])`](#scenesetworldmodelpath--x-y-z--yaw--doodadset--mapid) - [`scene:SetWorldModelByMapID(mapID)`](#scenesetworldmodelbymapidmapid) - [`scene:ClearWorldModel()`](#sceneclearworldmodel) + - [`scene:SetWorldTerrain(mapID, x, y [, radius])`](#scenesetworldterrainmapid-x-y--radius) + - [`scene:ClearWorldTerrain()`](#sceneclearworldterrain) - [`scene:SetPlayWorldModelSounds(enabled)` / `scene:GetPlayWorldModelSounds()`](#scenesetplayworldmodelsoundsenabled--scenegetplayworldmodelsounds) - [`scene:TraceSegment(startX, startY, startZ, endX, endY, endZ [, camera])`](#scenetracesegmentstartx-starty-startz-endx-endy-endz--camera) - [`scene:GetLiquidAtPoint(x, y, z)`](#scenegetliquidatpointx-y-z) @@ -19533,6 +19535,39 @@ onyxia:SetPosition(0.7, -211.97, -86.08) -- her place in the lair Removes the WMO of the scene and its props. This is a ClassicAPI extension. +### `scene:SetWorldTerrain(mapID, x, y [, radius])` + +Shows the ground of a map around a point and returns `true`. `mapID` is a +row of `Map.dbc`, for example `0` for Eastern Kingdoms. `x` and `y` are a +position on that map, so the positions in the scene are the positions on +the map. The scene shows each part of the ground that is less than +`radius` yards from the point. The default radius is 533.33 yards, the +width of one map tile. + +The ground looks as it does in the world: the same textures, the same +shadows and the same level of detail. The light of the scene stands in for +the sun, and the fog of the scene stands in for the fog of the zone. A +WMO from +[`scene:SetWorldModel`](#scenesetworldmodelpath--x-y-z--yaw--doodadset--mapid) +stands on the ground when you give it its position on the same map. + +The function returns `false` and shows no ground when the map has no +ground within the radius. A new call replaces the ground of the scene. +Actors do not stand on the ground yet, and the trees, grass and water of +the map are not shown. This is a ClassicAPI extension. + +```lua +-- The Gurubashi Arena: the arena WMO where the map puts it, on its ground. +scene:SetWorldModel("World\\wmo\\Azeroth\\Collidable Doodads\\Stranglethorn\\StranglethornArena\\StrangleGladiatorArena.wmo", + -13205.914, 271.832, 20.280, math.rad(64) + math.pi, 0, 0) +scene:SetWorldTerrain(0, -13205.914, 271.832, 250) +scene:SetCameraFarClip(500) +``` + +### `scene:ClearWorldTerrain()` + +Removes the ground of the scene. This is a ClassicAPI extension. + ### `scene:SetPlayWorldModelSounds(enabled)` / `scene:GetPlayWorldModelSounds()` Sets whether the props of the WMO play their sounds, for example the diff --git a/src/Offsets.h b/src/Offsets.h index 6876a5aa..baf8a0fa 100644 --- a/src/Offsets.h +++ b/src/Offsets.h @@ -16203,4 +16203,184 @@ enum Offsets { // q[3], const float dir[3])`, ret 4: from p to the line through q // along the unit dir. FUN_POINT_TO_LINE_DISTANCE_SQ = 0x00634F40, + + // ---- ADT terrain (Model::Scene::Terrain; benilla terrain/chunk, render, + // lod, cull, files; Ghidra decompiles 2026-11-11) --------------------------- + // A tile's chunks built and drawn by the world's own chunk functions on + // chunks the scene owns. CMapChunk::Load (0x006AF5F0) also links the + // global area table, the world's doodad hashes and map lights; the scene + // runs only its self-contained steps, in Load's order. + // CMapChunk::CMapChunk `__thiscall(chunk)` (0x006AF1D0; base 0x006C3020 + // touches only the object) and ~CMapChunk `__thiscall(chunk)` + // (0x006AF460, its own lists only); UnloadChunk `__thiscall(chunk)` + // (0x006A6B10): layers, neighbour back-links, textures, liquids, lists; + // a buffer not from the world's pool it nulls without freeing + // (ReleaseChunkBuffers 0x006AE9A0). The world's chunk list (0x00CA7D48, + // AllocChunk 0x006A06E0) is walked only by ReleaseAllChunkBuffers, + // before the world's pool is rebuilt (far clip, map unload). + FUN_CMAPCHUNK_CTOR = 0x006AF1D0, + FUN_CMAPCHUNK_DTOR = 0x006AF460, + FUN_UNLOAD_CHUNK = 0x006A6B10, + // FixupRecordPointers `__thiscall(chunk, record)` reads +0x168; + // BuildVertices / LoadNormals / CreateCombinedTexture `__thiscall(chunk)`; + // AddLayer `__thiscall(chunk, area, mcly entry, mcal data)`, ret 0xC; + // CreateShadowTexture `__thiscall(chunk, mcsh data)`; SelectMesh + // `__thiscall(chunk, uint draw)`: mesh, buffers, DrawLayers 0x006BEF30. + FUN_CMAPCHUNK_FIXUP_RECORD = 0x006AF970, + FUN_CMAPCHUNK_BUILD_VERTICES = 0x006B0E50, + FUN_CMAPCHUNK_LOAD_NORMALS = 0x006AFF10, + FUN_CMAPCHUNK_ADD_LAYER = 0x006AFF80, + FUN_CMAPCHUNK_CREATE_SHADOW = 0x006B0030, + FUN_CMAPCHUNK_CREATE_COMBINED = 0x006B00A0, + FUN_CMAPCHUNK_SELECT_MESH = 0x006BEB50, + // LoadAreaTextures `__thiscall(area, const char *names, uint size)`, + // ret 8: a LoadMapTexture handle per MTEX name at area +0xEC, count + // +0xE8, no bound; it touches only +0x9C, +0xE8 and the array, which + // ends at +0x26C (96 slots). UnloadArea (0x006A6A10) closes each with + // FUN_HANDLE_RELEASE. AddLayer reads only the area's slot. + FUN_LOAD_AREA_TEXTURES = 0x006C20E0, + CMAPAREA_SIZE = 0x6A8, + OFF_CMAPAREA_TEXTURE_COUNT = 0xE8, + OFF_CMAPAREA_TEXTURES = 0xEC, + CMAPAREA_TEXTURE_SLOTS = 96, + // A static buffer pool and its sub-buffers, as CreateChunkBufferPool + // (0x006AE640) makes CMapChunk_vtx / _idx: CreatePool `void + // *__fastcall(kind, usage, size, uint, const char *name)`, ret 0xC + // (kind 0 vertex, 1 index; usage 1; 3); PoolBuffer `void *__fastcall( + // pool, itemSize, count, offset)`, ret 8; FreeBuffer `__fastcall(buf)` + // (0x0058A040); GxBufferRelease `__fastcall(pool)`. SelectMesh takes the + // world's pool only for a buffer whose pool has usage 2 (pool +0x0C; + // the device's shared dynamic buffer, GxBufCreate 0x0058A140). + FUN_GX_CREATE_POOL = 0x0058A160, + FUN_GX_POOL_BUFFER = 0x00589F80, + FUN_GX_FREE_BUFFER = 0x0058A040, + FUN_GX_BUFFER_RELEASE = 0x0058A1A0, + GX_POOL_KIND_VERTEX = 0, + GX_POOL_KIND_INDEX = 1, + GX_POOL_USAGE_STATIC = 1, + GX_POOL_ARG = 3, + CHUNK_VERTEX_SIZE = 0x18, + CHUNK_INDEX_SIZE = 2, + // Per level, 8 bytes each: the count, the list (0x0086C290 vertices, + // 0x0086C2B0 indices; level 3 = 145 / 768 in the image). The pool's + // buffers hold the full level (AcquireChunkBuffers 0x006AE8A0). + VAR_CHUNK_LEVEL_VERTEX_LISTS = 0x0086C290, + VAR_CHUNK_LEVEL_INDEX_LISTS = 0x0086C2B0, + CHUNK_LEVEL_LIST_SIZE = 8, + CHUNK_LEVEL_FULL = 3, + // The chunk level (0x006AFAD0): maxLOD, or the far level when world + // flag 4 is on and the view depth is above lodDist (strictly). + VAR_CHUNK_LOD_DIST = 0x00867960, + VAR_CHUNK_MAX_LOD = 0x00867964, + VAR_CHUNK_FAR_LOD = 0x00867968, + // IsBoxCulled `uint __thiscall(const float box[6])`: nonzero when the + // top of the frustum stack rejects the box (0x00683C3C). + FUN_FRUSTUM_IS_BOX_CULLED = 0x00682F40, + // The world flags (benilla terrain/world.md): 2 chunks drawn, 4 lod, + // 0x40 map shadows, the sign anisotropic: the chunk pass then sets the + // mip bias of stages 0-3 (states 0x27-0x2A) to the immediate pushed at + // 0x00684527 (0.25). + VAR_WORLD_FLAGS = 0x00C7B2A4, + WORLD_FLAG_CHUNKS = 0x2, + WORLD_FLAG_LOD = 0x4, + WORLD_FLAG_MAP_SHADOWS = 0x40, + WORLD_FLAG_ANISOTROPIC = 0x80000000, + GXRS_MIP_BIAS_STAGE0 = 0x27, + MIP_BIAS_STAGES = 4, + VAR_CHUNK_MIP_BIAS_IMMEDIATE = 0x00684528, + // DrawLayers reads both: the camera (texgen matrices are camera-relative) + // and the fog end (beyond it, less the radius, a chunk draws flat; the + // light slot needs the depth less twice the radius under it, 0x006C0CC0). + VAR_CAMERA_POSITION = 0x00C7CF20, + VAR_FOG_END = 0x00C62964, + // The shader paths (0x006BEF30): the pixel-program flag (`_s` textures, + // 0x006C2104) and the second; shadowLevel (alpha size, 0x006AFFE2). A + // chunk's textures are made for the values it was built with. + VAR_TERRAIN_SHADER_FLAG = 0x00C9A31C, + VAR_TERRAIN_SHADER_FLAG_B = 0x00C89F44, + VAR_SHADOW_LEVEL = 0x00C63284, + // CMapChunk (0xF34 bytes, benilla terrain/chunk.md). + CMAPCHUNK_SIZE = 0xF34, + OFF_CMAPCHUNK_FLAGS = 0x0C, // word: 0x40 impassable, 1 lights, 0x80 filed + OFF_CMAPCHUNK_CENTRE = 0x5C, // 3 floats, then the radius + OFF_CMAPCHUNK_RADIUS = 0x68, + OFF_CMAPCHUNK_POSITION = 0x6C, // from MCNK +0x68 + OFF_CMAPCHUNK_VIEW_DEPTH = 0x78, + OFF_CMAPCHUNK_COLUMN = 0x7C, + OFF_CMAPCHUNK_ROW = 0x80, + OFF_CMAPCHUNK_COLUMN8 = 0x84, + OFF_CMAPCHUNK_ROW8 = 0x88, + OFF_CMAPCHUNK_GLOBAL_COLUMN = 0x8C, + OFF_CMAPCHUNK_GLOBAL_ROW = 0x90, + OFF_CMAPCHUNK_BOX = 0x94, // 6 floats, the culling copy + OFF_CMAPCHUNK_INDEX = 0xB4, + OFF_CMAPCHUNK_LEVEL = 0xB8, + OFF_CMAPCHUNK_NEIGHBOURS = 0xC4, // row - 1, column + 1, row + 1, column - 1 + OFF_CMAPCHUNK_VERTEX_BUFFER = 0x14C, + OFF_CMAPCHUNK_INDEX_BUFFER = 0x150, + OFF_CMAPCHUNK_RECORD = 0x168, + OFF_CMAPCHUNK_AREA_ID = 0x16C, + OFF_CMAPCHUNK_HEADER = 0xF08, + OFF_CMAPCHUNK_LOW_TEXTURES = 0xF0C, + OFF_CMAPCHUNK_DOODAD_MAP = 0xF10, + OFF_CMAPCHUNK_MCSH = 0xF1C, + OFF_CMAPCHUNK_MCLY = 0xF20, + OFF_CMAPCHUNK_MCAL = 0xF24, + // CMapChunk::Load 0x006AF6E5: with a shadow, +0x148 takes MCNK +0x30 and + // CreateShadowTexture keeps the map at +0x144; else both are zeroed. + OFF_CMAPCHUNK_SHADOW_MAP = 0x144, + OFF_CMAPCHUNK_SHADOW_WORD = 0x148, + CMAPCHUNK_FLAG_IMPASSABLE = 0x40, + CMAPCHUNK_FLAG_LIGHTS = 0x1, + CMAPCHUNK_FLAG_FILED = 0x80, + // An ADT as ParseAreaFile (0x006C2010) reads it: MHDR data at buffer + + // 0x10 + the MVER size (+0x04); its +0x04 MCIN and +0x08 MTEX offsets + // point 8 bytes before the data, the size the dword before it. MCIN: + // 256 x 16 bytes, +0 the MCNK record's file offset. MCNK header (record + // + 8): +0x00 flags (1 shadow, 2 impassable), +0x0C layers, +0x14 MCVT, + // +0x18 MCNR, +0x1C MCLY, +0x24 MCAL, +0x2C MCSH, +0x34 area, +0x3C holes, + // +0x40 / +0x50 maps, +0x68 position; each sub-record offset is from the + // record and lands 8 bytes before its data (FixupRecordPointers). MCLY + // entries are 16 bytes: +0 texture index, +4 flags (0x100 alpha map), +8 + // MCAL offset. + OFF_ADT_MVER_SIZE = 0x04, + ADT_MHDR_BASE = 0x10, + OFF_MHDR_MCIN = 0x04, + OFF_MHDR_MTEX = 0x08, + ADT_CHUNKS = 256, + MCIN_ENTRY_SIZE = 0x10, + MCNK_RECORD_HEADER = 8, + OFF_MCNK_FLAGS = 0x00, + OFF_MCNK_LAYER_COUNT = 0x0C, + OFF_MCNK_MCVT = 0x14, + OFF_MCNK_MCNR = 0x18, + OFF_MCNK_MCLY = 0x1C, + OFF_MCNK_MCAL = 0x24, + OFF_MCNK_MCSH = 0x2C, + OFF_MCNK_SHADOW_WORD = 0x30, + OFF_MCNK_AREA_ID = 0x34, + OFF_MCNK_HOLES = 0x3C, + OFF_MCNK_LOW_TEXTURES = 0x40, + OFF_MCNK_DOODAD_MAP = 0x50, + OFF_MCNK_POSITION = 0x68, + MCNK_HEADER_SIZE = 0x80, + MCNK_FLAG_SHADOW = 0x1, + MCNK_FLAG_IMPASSABLE = 0x2, + MCNK_HOLES_ALL = 0xFFFF, + MCNK_MAX_LAYERS = 4, + MCLY_ENTRY_SIZE = 0x10, + OFF_MCLY_FLAGS = 0x04, + OFF_MCLY_ALPHA = 0x08, + MCLY_FLAG_ALPHA = 0x100, + MCVT_SIZE = 145 * 4, + MCNR_SIZE = 145 * 3, + MCAL_MAP_SIZE = 0x800, + MCSH_SIZE = 0x200, + // Tiles fall from the map origin (17066.666, 0x007FFAB4) in steps of + // 533.33331 (0x0080654C): the row from x, the column from y; a tile is + // \__.adt (0x006C274D) of 16 x 16 chunks. + VAR_MAP_ORIGIN = 0x007FFAB4, + VAR_TILE_SIZE = 0x0080654C, + MAP_TILES = 64, + TILE_CHUNKS = 16, }; diff --git a/src/model/Scene.cpp b/src/model/Scene.cpp index 72d2aa2f..f5f54fd9 100644 --- a/src/model/Scene.cpp +++ b/src/model/Scene.cpp @@ -107,7 +107,9 @@ // SetWorldModelByMapID / ClearWorldModel: a WMO drawn by the world's own map // object draw after the animate pass, with its doodads as models of the // scene; Set/GetPlayWorldModelSounds: the doodads' sounds -// (model/SceneWorld.cpp). +// (model/SceneWorld.cpp). SetWorldTerrain / ClearWorldTerrain: a map's ADT +// chunks around a point, built and drawn by the world's own chunk functions +// before the WMO (model/SceneTerrain.cpp). #include "model/Scene.h" @@ -169,6 +171,7 @@ struct Fields { int32_t groundTerrain; // SetGroundTerrain: a TerrainType id, or -1 Actor *hovered; // the actor OnActorEnter last ran for, or null World::Backdrop *world; // SetWorldModel, owned, or null + Terrain::Land *terrain; // SetWorldTerrain, owned, or null bool playWorldModelSounds; // SetPlayWorldModelSounds Actor *listener; // SetSoundListenerActor, or null; the frame owns its actors // GetSceneTime: the seconds the M2 scene's clock has advanced since the @@ -736,6 +739,9 @@ void __fastcall Paint(void *frame) { PlaceActors(frame); void *scene = Model::Pane::Scene(frame); M2::AnimateScene(scene, eye); + // The world's frame draws its chunks before its map objects. + if (Terrain::Land *terrain = CameraOf(frame) != nullptr ? F(frame).terrain : nullptr) + Terrain::Draw(*terrain, frame, eye, F(frame).farClip); if (world != nullptr) World::Draw(*world, frame, eye); DrawGroundDecals(frame, eye); @@ -976,6 +982,8 @@ void Destroy(void *frame) { f.actors = nullptr; World::Free(f.world); f.world = nullptr; + Terrain::Free(f.terrain); + f.terrain = nullptr; Time::Timer::CancelOwned(frame); } @@ -1153,6 +1161,7 @@ void *__fastcall CreateModelScene(void *parent) { f.groundTerrain = -1; f.hovered = nullptr; f.world = nullptr; + f.terrain = nullptr; f.playWorldModelSounds = false; f.listener = nullptr; f.clock = 0.0; @@ -1588,6 +1597,39 @@ int __fastcall Script_ClearWorldModel(void *L) { return 0; } +// The scene's terrain (a ClassicAPI extension, model/SceneTerrain.cpp). A +// set that fails clears it, as SetWorldModel does. +void SetTerrain(void *frame, Terrain::Land *terrain) { + Terrain::Free(F(frame).terrain); + F(frame).terrain = terrain; +} + +constexpr char kUsageSetWorldTerrain[] = "SetWorldTerrain(mapID, x, y [, radius])"; + +int __fastcall Script_SetWorldTerrain(void *L) { + void *frame = Self(L); + if (frame == nullptr) + return 0; + const char *owner = Game::Lua::ObjectDisplayName(frame); + if (!NumberArgs(L, 2, 3, owner, kUsageSetWorldTerrain)) + return 0; + const bool hasRadius = Game::Lua::Type(L, 5) > Game::Lua::TYPE_NIL; + if (hasRadius && !NumberArgs(L, 5, 1, owner, kUsageSetWorldTerrain)) + return 0; + // One tile's width by default, the world's own unit of terrain. + const float radius = hasRadius ? FloatArg(L, 5) : Game::Read(Offsets::VAR_TILE_SIZE); + SetTerrain(frame, Terrain::Load(static_cast(Game::Lua::ToNumber(L, 2)), FloatArg(L, 3), + FloatArg(L, 4), radius)); + Game::Lua::PushBool(L, F(frame).terrain != nullptr); + return 1; +} + +int __fastcall Script_ClearWorldTerrain(void *L) { + if (void *frame = Self(L)) + SetTerrain(frame, nullptr); + return 0; +} + // The WMO's nearest face on a segment (a ClassicAPI extension): the hit // point, the face's normal toward the start, and the fraction. Nothing on a // miss or without a WMO. @@ -1876,6 +1918,8 @@ const Game::Lua::FrameMethodEntry g_methods[] = { {"SetWorldModel", &Script_SetWorldModel}, {"SetWorldModelByMapID", &Script_SetWorldModelByMapID}, {"ClearWorldModel", &Script_ClearWorldModel}, + {"SetWorldTerrain", &Script_SetWorldTerrain}, + {"ClearWorldTerrain", &Script_ClearWorldTerrain}, {"TraceSegment", &Script_TraceSegment}, {"GetLiquidAtPoint", &Script_GetLiquidAtPoint}, {"SweepCollider", &Script_SweepCollider}, @@ -2071,6 +2115,18 @@ const Game::Doc::Function kSetWorldModelByMapID{ "map's positions. Returns false, and shows no WMO, for any other map.", kWorldModelMapArg, kWorldModelRet, nullptr, true}; const Game::Doc::Function kClearWorldModel{"Removes the scene's WMO.", {}, {}, nullptr, true}; +const Game::Doc::Field kWorldTerrainArgs[] = { + Req("mapID", "number", "A Map.dbc row with terrain, for example 0 (Eastern Kingdoms)."), + Req("x", "number", "The map's x, as the map places its terrain."), + Req("y", "number"), + Opt("radius", "number", "533.33331", "Chunks within this distance of (x, y) are shown: one map tile by default."), +}; +const Game::Doc::Function kSetWorldTerrain{ + "Shows the map's ground around a point the way the world draws it, with its textures, shadows and " + "level of detail, in map coordinates. The scene's light stands in for the sun, and its fog for the " + "zone's. Returns false, and shows no terrain, when no ground lies within the radius.", + kWorldTerrainArgs, kWorldModelRet, nullptr, true}; +const Game::Doc::Function kClearWorldTerrain{"Removes the scene's terrain.", {}, {}, nullptr, true}; const Game::Doc::Field kTraceSegmentArgs[] = { Req("startX", "number"), Req("startY", "number"), Req("startZ", "number"), Req("endX", "number"), Req("endY", "number"), Req("endZ", "number"), @@ -2260,6 +2316,8 @@ const Game::Doc::Method g_methodDocs[] = { {"SetWorldModel", &kSetWorldModel}, {"SetWorldModelByMapID", &kSetWorldModelByMapID}, {"ClearWorldModel", &kClearWorldModel}, + {"SetWorldTerrain", &kSetWorldTerrain}, + {"ClearWorldTerrain", &kClearWorldTerrain}, {"TraceSegment", &kTraceSegment}, {"GetLiquidAtPoint", &kGetLiquidAtPoint}, {"SweepCollider", &kSweepCollider}, diff --git a/src/model/Scene.h b/src/model/Scene.h index 54f5f838..e259eca5 100644 --- a/src/model/Scene.h +++ b/src/model/Scene.h @@ -705,8 +705,28 @@ void DrawDecalOnPlane(const float (&box)[6], uint32_t argb, const float (&m)[16] // The scene's fog on the device, for a decal at `point` that the world draws // in its own fog: the WMO's, or the frame's without one. Inside a state push. void CommitDecalFog(const Backdrop *backdrop, void *frame, const float (&point)[3], const float (&eye)[3]); +// The scene's view volume in scene space (the device's view moved by -eye +// and its projection), as the world's camera builds its own. +void ViewVolume(uint8_t (&volume)[Offsets::FRUSTUM_VOLUME_SIZE], const float (&eye)[3]); +// The fog half of the frame's light callback: the scene's fog on a lighting +// record, nothing when the scene has none. +void FrameFog(void *record, void *frame); } // namespace World +// The scene's terrain (SetWorldTerrain; model/SceneTerrain.cpp). +namespace Terrain { +struct Land; +// The chunks of map `mapID`'s ADT tiles within `radius` of (x, y), in map +// coordinates; null when the map has no directory or no chunk in reach +// opens and reads. +Land *Load(uint32_t mapID, float x, float y, float radius); +void Free(Land *land); +// From the paint, after the animate pass and before the WMO: the chunks the +// scene's view shows, as the world's chunk pass draws them. `farClip` is the +// scene's, the fog end of a scene without fog. +void Draw(Land &land, void *frame, const float (&eye)[3], float farClip); +} // namespace Terrain + // The scene's WMO, or null. World::Backdrop *WorldOf(void *sceneFrame); diff --git a/src/model/SceneTerrain.cpp b/src/model/SceneTerrain.cpp new file mode 100644 index 00000000..aec9aa1d --- /dev/null +++ b/src/model/SceneTerrain.cpp @@ -0,0 +1,629 @@ +// 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 . + +// A ModelScene's terrain (scene:SetWorldTerrain, a ClassicAPI extension; +// research in docs/notes/model-scene.md "Extension 9"). +// +// The chunks are the world's CMapChunk objects, owned by the scene, built +// and drawn by the world's own functions: +// +// - Load. The ADT is read whole into the scene's buffer and its MHDR read +// as ParseAreaFile (0x006C2010) reads it. The tile's textures load into +// an area stand-in through LoadAreaTextures, which touches only the +// texture slots. Each chunk is constructed by CMapChunk's constructor +// and gets CreateAreaChunk's fields (0x006C2880) and the self-contained +// steps of CMapChunk::Load (0x006AF5F0) in its order: record fixup, +// header fields, vertices, normals, the impassable flag, layers, shadow +// texture, combined texture, flags. Load's other steps write world +// state and are left out: LinkNeighbours reads the global area table +// (the scene links its own chunks by the same rule), LoadReferences +// makes doodad and map object defs in the world's hashes, LinkLights +// takes the world's map lights, and the area is never filed in the +// global table. Liquids and sound emitters (a null callback in 1.12) +// are left out too. +// - Buffers. The world's chunk buffer pool is freed and rebuilt on a far +// clip change and a map unload (CreateChunkBufferPool 0x006AE640), and +// only the world's listed chunks give theirs back first. The scene's +// chunks take their buffers from a static pool of their own, made as +// the world makes its pool; SelectMesh goes to the world's pool only for +// a buffer of the device's dynamic pool (usage 2). +// - Draw. DrawChunkPass (0x00684510) for each chunk the scene's view +// shows: the chunk level and view depth (0x006AFAD0), the box against +// the scene's volume (CullSceneChunks 0x00683BF0, without the horizon), +// the world transform at the chunk less the eye, a lighting record at +// the chunk's centre with the scene's lights there, the fog and, nearer +// than the fog end by twice the radius, the light (the chunk's slots +// 0x006C0CC0: the scene light stands in for the sun, the scene fog for +// the zone's), then SelectMesh. DrawLayers reads the camera and the fog +// end from world globals, so both hold the scene's values while it draws. +// - Settings. A chunk's textures are made for the shader flags, the +// shadowLevel and the map shadows flag it was built with; when any +// changes (a world loads after the glue screen), the chunks are built +// again from the kept files. + +#include "model/Scene.h" + +#include "Game.h" +#include "Offsets.h" +#include "dbc/Lookup.h" +#include "gx/Device.h" +#include "gx/Matrix.h" +#include "model/M2.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Model::Scene::Terrain { + +namespace { + +using Gx::Identity; +using Gx::Matrix; +using Gx::Translate; + +constexpr int kWorldStack = 8; +constexpr char kVertexPoolName[] = "ModelScene_terrain_vtx"; +constexpr char kIndexPoolName[] = "ModelScene_terrain_idx"; + +struct alignas(16) ChunkMemory { + uint8_t bytes[Offsets::CMAPCHUNK_SIZE]; +}; + +struct alignas(16) AreaMemory { + uint8_t bytes[Offsets::CMAPAREA_SIZE]; +}; + +uint32_t U32(const uint8_t *at) { + uint32_t v; + std::memcpy(&v, at, sizeof v); + return v; +} + +float F32(const uint8_t *at) { + float v; + std::memcpy(&v, at, sizeof v); + return v; +} + +// The whole file, through SFile (a missing file opens nothing, no error). +bool ReadFile(const char *path, std::vector &out) { + using Open_t = int(__stdcall *)(const char *path, void **file); + using Size_t = uint32_t(__stdcall *)(void *file, uint32_t *high); + using Read_t = int(__stdcall *)(void *file, void *buffer, uint32_t size, uint32_t *read, void *overlapped, int); + using Close_t = uint32_t(__stdcall *)(void *file); + void *file = nullptr; + if (reinterpret_cast(Offsets::FUN_SFILE_OPEN)(path, &file) == 0 || file == nullptr) + return false; + const uint32_t size = reinterpret_cast(Offsets::FUN_SFILE_GET_FILE_SIZE)(file, nullptr); + bool ok = size != 0 && size != 0xFFFFFFFFu; + if (ok) { + out.resize(size); + uint32_t read = 0; + ok = reinterpret_cast(Offsets::FUN_SFILE_READ)(file, out.data(), size, &read, nullptr, 0) != 0 && + read == size; + } + reinterpret_cast(Offsets::FUN_SFILE_CLOSE)(file); + return ok; +} + +// What a chunk's textures were made for (AddLayer, CreateShadowTexture, +// CreateCombinedTexture, LoadAreaTextures). +struct Settings { + uint32_t shader = 0; + uint32_t shaderB = 0; + uint32_t shadowLevel = 0; + uint32_t mapShadows = 0; + + static Settings Current() { + Settings s; + s.shader = Game::Read(Offsets::VAR_TERRAIN_SHADER_FLAG); + s.shaderB = Game::Read(Offsets::VAR_TERRAIN_SHADER_FLAG_B); + s.shadowLevel = Game::Read(Offsets::VAR_SHADOW_LEVEL); + s.mapShadows = Game::Read(Offsets::VAR_WORLD_FLAGS) & Offsets::WORLD_FLAG_MAP_SHADOWS; + return s; + } + bool operator==(const Settings &o) const { + return shader == o.shader && shaderB == o.shaderB && shadowLevel == o.shadowLevel && + mapShadows == o.mapShadows; + } +}; + +// One ADT: its bytes (every chunk's record and the fill callbacks' alpha +// and shadow maps point into them), the MTEX names and the area stand-in +// that holds the tile's texture handles. +struct Tile { + std::vector file; + uint32_t column = 0; + uint32_t row = 0; + const char *names = nullptr; + uint32_t namesSize = 0; + std::unique_ptr area; + // The MCIN indices of the chunks inside the radius. + std::vector wanted; +}; + +struct Chunk { + std::unique_ptr memory; + Tile *tile = nullptr; + uint32_t index = 0; // row * 16 + column in the tile + void *object() { return memory->bytes; } +}; + +} // namespace + +struct Land { + std::vector> tiles; + std::vector chunks; + void *vertexPool = nullptr; + void *indexPool = nullptr; + std::vector> buffers; // one pair per chunk, in order + Settings built; +}; + +namespace { + +uint32_t LevelCount(uintptr_t lists, uint32_t level) { + return Game::Read(lists + level * Offsets::CHUNK_LEVEL_LIST_SIZE); +} + +uint32_t FullVertexCount() { return LevelCount(Offsets::VAR_CHUNK_LEVEL_VERTEX_LISTS, Offsets::CHUNK_LEVEL_FULL); } +uint32_t FullIndexCount() { return LevelCount(Offsets::VAR_CHUNK_LEVEL_INDEX_LISTS, Offsets::CHUNK_LEVEL_FULL); } + +// A byte of the file at an offset already checked to lie inside it. +const uint8_t *At(const std::vector &file, uint64_t offset) { + return file.data() + static_cast(offset); +} + +bool Inside(const std::vector &file, uint64_t offset, uint64_t size) { + return offset <= file.size() && size <= file.size() - offset; +} + +// MHDR as ParseAreaFile reads it; false when a table lies outside the file +// or the tile has more names than the area holds. +bool ParseHeader(Tile &t) { + const std::vector &f = t.file; + if (!Inside(f, Offsets::OFF_ADT_MVER_SIZE, 4)) + return false; + const uint64_t mhdr = uint64_t{Offsets::ADT_MHDR_BASE} + U32(At(f, Offsets::OFF_ADT_MVER_SIZE)); + if (!Inside(f, mhdr, Offsets::OFF_MHDR_MTEX + 4)) + return false; + const uint64_t mcin = mhdr + U32(At(f, mhdr + Offsets::OFF_MHDR_MCIN)) + Offsets::MCNK_RECORD_HEADER; + const uint64_t mtex = mhdr + U32(At(f, mhdr + Offsets::OFF_MHDR_MTEX)) + Offsets::MCNK_RECORD_HEADER; + if (!Inside(f, mcin, uint64_t{Offsets::ADT_CHUNKS} * Offsets::MCIN_ENTRY_SIZE) || mtex < 4 || !Inside(f, mtex, 0)) + return false; + const uint32_t size = U32(At(f, mtex - 4)); + if (!Inside(f, mtex, size)) + return false; + // LoadAreaTextures' walk: a name, then past its NUL, while inside the size. + uint32_t count = 0; + for (uint32_t i = 0; i < size; ++i) { + ++count; + while (i < size && *At(f, mtex + i) != 0) + ++i; + } + if (count > Offsets::CMAPAREA_TEXTURE_SLOTS || (size != 0 && *At(f, mtex + size - 1) != 0)) + return false; + t.names = reinterpret_cast(At(f, mtex)); + t.namesSize = size; + return true; +} + +const uint8_t *McinEntry(const Tile &t, uint32_t index) { + const uint64_t mhdr = uint64_t{Offsets::ADT_MHDR_BASE} + U32(At(t.file, Offsets::OFF_ADT_MVER_SIZE)); + const uint64_t mcin = mhdr + U32(At(t.file, mhdr + Offsets::OFF_MHDR_MCIN)) + Offsets::MCNK_RECORD_HEADER; + return At(t.file, mcin + uint64_t{index} * Offsets::MCIN_ENTRY_SIZE); +} + +// The MCNK record of a chunk, or null when the record or a sub-record the +// build reads lies outside the file, or a layer names a texture the tile +// does not have. +const uint8_t *CheckedRecord(const Tile &t, uint32_t index, uint32_t textures) { + const std::vector &f = t.file; + const uint32_t record = U32(McinEntry(t, index)); + if (!Inside(f, record, uint64_t{Offsets::MCNK_RECORD_HEADER} + Offsets::MCNK_HEADER_SIZE)) + return nullptr; + const uint8_t *header = At(f, record + Offsets::MCNK_RECORD_HEADER); + const auto sub = [&](uint32_t field, uint64_t size) { + return Inside(f, uint64_t{record} + U32(header + field) + Offsets::MCNK_RECORD_HEADER, size); + }; + const uint32_t layers = U32(header + Offsets::OFF_MCNK_LAYER_COUNT); + if (!sub(Offsets::OFF_MCNK_MCVT, Offsets::MCVT_SIZE) || !sub(Offsets::OFF_MCNK_MCNR, Offsets::MCNR_SIZE) || + layers > Offsets::MCNK_MAX_LAYERS || !sub(Offsets::OFF_MCNK_MCLY, uint64_t{layers} * Offsets::MCLY_ENTRY_SIZE)) + return nullptr; + if ((U32(header + Offsets::OFF_MCNK_FLAGS) & Offsets::MCNK_FLAG_SHADOW) != 0 && + !sub(Offsets::OFF_MCNK_MCSH, Offsets::MCSH_SIZE)) + return nullptr; + const uint64_t mcly = uint64_t{record} + U32(header + Offsets::OFF_MCNK_MCLY) + Offsets::MCNK_RECORD_HEADER; + const uint64_t mcal = uint64_t{record} + U32(header + Offsets::OFF_MCNK_MCAL) + Offsets::MCNK_RECORD_HEADER; + for (uint32_t i = 0; i < layers; ++i) { + const uint8_t *entry = At(f, mcly + uint64_t{i} * Offsets::MCLY_ENTRY_SIZE); + if (U32(entry) >= textures) + return nullptr; + if ((U32(entry + Offsets::OFF_MCLY_FLAGS) & Offsets::MCLY_FLAG_ALPHA) != 0 && + !Inside(f, mcal + U32(entry + Offsets::OFF_MCLY_ALPHA), Offsets::MCAL_MAP_SIZE)) + return nullptr; + } + return At(f, record); +} + +uint32_t TextureCount(const Tile &t) { + uint32_t count = 0; + for (uint32_t i = 0; i < t.namesSize; ++i) { + ++count; + while (i < t.namesSize && t.names[i] != 0) + ++i; + } + return count; +} + +void LoadTextures(Tile &t) { + t.area = std::make_unique(); + std::memset(t.area->bytes, 0, sizeof t.area->bytes); + using Load_t = void(__thiscall *)(void *area, const char *names, uint32_t size); + reinterpret_cast(Offsets::FUN_LOAD_AREA_TEXTURES)(t.area->bytes, t.names, t.namesSize); +} + +// UnloadArea's texture half (0x006A6AA0). +void CloseTextures(Tile &t) { + if (t.area == nullptr) + return; + uint8_t *area = t.area->bytes; + const uint32_t count = Game::Read(area, Offsets::OFF_CMAPAREA_TEXTURE_COUNT); + for (uint32_t i = 0; i < count; ++i) { + void *&handle = Game::Ref(area, Offsets::OFF_CMAPAREA_TEXTURES + i * 4); + if (handle != nullptr) { + reinterpret_cast(Offsets::FUN_HANDLE_RELEASE)(handle); + handle = nullptr; + } + } + Game::Ref(area, Offsets::OFF_CMAPAREA_TEXTURE_COUNT) = 0; + t.area.reset(); +} + +// CreateAreaChunk's fields, then CMapChunk::Load's self-contained steps. +void BuildChunk(Chunk &c) { + using This_t = void(__thiscall *)(void *); + void *o = c.object(); + std::memset(o, 0, Offsets::CMAPCHUNK_SIZE); + reinterpret_cast(Offsets::FUN_CMAPCHUNK_CTOR)(o); + Tile &t = *c.tile; + const uint32_t column = c.index % Offsets::TILE_CHUNKS; + const uint32_t row = c.index / Offsets::TILE_CHUNKS; + const uint32_t globalColumn = t.column * Offsets::TILE_CHUNKS + column; + const uint32_t globalRow = t.row * Offsets::TILE_CHUNKS + row; + Game::Ref(o, Offsets::OFF_CMAPCHUNK_COLUMN) = column; + Game::Ref(o, Offsets::OFF_CMAPCHUNK_ROW) = row; + Game::Ref(o, Offsets::OFF_CMAPCHUNK_FLAGS) = 0; + Game::Ref(o, Offsets::OFF_CMAPCHUNK_INDEX) = c.index; + Game::Ref(o, Offsets::OFF_CMAPCHUNK_GLOBAL_COLUMN) = globalColumn; + Game::Ref(o, Offsets::OFF_CMAPCHUNK_GLOBAL_ROW) = globalRow; + Game::Ref(o, Offsets::OFF_CMAPCHUNK_COLUMN8) = globalColumn * 8; + Game::Ref(o, Offsets::OFF_CMAPCHUNK_ROW8) = globalRow * 8; + + const uint8_t *record = At(t.file, U32(McinEntry(t, c.index))); + Game::Ref(o, Offsets::OFF_CMAPCHUNK_RECORD) = record; + reinterpret_cast(Offsets::FUN_CMAPCHUNK_FIXUP_RECORD)(o, record); + const uint8_t *header = Game::Read(o, Offsets::OFF_CMAPCHUNK_HEADER); + Game::Ref(o, Offsets::OFF_CMAPCHUNK_AREA_ID) = U32(header + Offsets::OFF_MCNK_AREA_ID); + std::memcpy(Game::Ptr(o, Offsets::OFF_CMAPCHUNK_POSITION), header + Offsets::OFF_MCNK_POSITION, 12); + Game::Ref(o, Offsets::OFF_CMAPCHUNK_LOW_TEXTURES) = header + Offsets::OFF_MCNK_LOW_TEXTURES; + Game::Ref(o, Offsets::OFF_CMAPCHUNK_DOODAD_MAP) = header + Offsets::OFF_MCNK_DOODAD_MAP; + reinterpret_cast(Offsets::FUN_CMAPCHUNK_BUILD_VERTICES)(o); + reinterpret_cast(Offsets::FUN_CMAPCHUNK_LOAD_NORMALS)(o); + + const uint32_t flags = U32(header + Offsets::OFF_MCNK_FLAGS); + Game::Ref(o, Offsets::OFF_CMAPCHUNK_FLAGS) = + (flags & Offsets::MCNK_FLAG_IMPASSABLE) != 0 ? Offsets::CMAPCHUNK_FLAG_IMPASSABLE : 0; + using AddLayer_t = void(__thiscall *)(void *, void *area, const void *entry, const void *alpha); + const uint8_t *entry = Game::Read(o, Offsets::OFF_CMAPCHUNK_MCLY); + const uint8_t *alpha = Game::Read(o, Offsets::OFF_CMAPCHUNK_MCAL); + const uint32_t layers = U32(header + Offsets::OFF_MCNK_LAYER_COUNT); + for (uint32_t i = 0; i < layers; ++i, entry += Offsets::MCLY_ENTRY_SIZE) + reinterpret_cast(Offsets::FUN_CMAPCHUNK_ADD_LAYER)(o, t.area->bytes, entry, alpha); + // Load 0x006AF6E5: the shadow needs the record's flag and map shadows. + if ((flags & Offsets::MCNK_FLAG_SHADOW) != 0 && + (Game::Read(Offsets::VAR_WORLD_FLAGS) & Offsets::WORLD_FLAG_MAP_SHADOWS) != 0) { + Game::Ref(o, Offsets::OFF_CMAPCHUNK_SHADOW_WORD) = U32(header + Offsets::OFF_MCNK_SHADOW_WORD); + reinterpret_cast(Offsets::FUN_CMAPCHUNK_CREATE_SHADOW)( + o, Game::Read(o, Offsets::OFF_CMAPCHUNK_MCSH)); + } else { + Game::Ref(o, Offsets::OFF_CMAPCHUNK_SHADOW_WORD) = 0; + Game::Ref(o, Offsets::OFF_CMAPCHUNK_SHADOW_MAP) = 0; + } + if (Game::Read(Offsets::VAR_TERRAIN_SHADER_FLAG_B) != 0 || + Game::Read(Offsets::VAR_TERRAIN_SHADER_FLAG) != 0) + reinterpret_cast(Offsets::FUN_CMAPCHUNK_CREATE_COMBINED)(o); + Game::Ref(o, Offsets::OFF_CMAPCHUNK_FLAGS) |= Offsets::CMAPCHUNK_FLAG_LIGHTS; + Game::Ref(o, Offsets::OFF_CMAPCHUNK_FLAGS) |= Offsets::CMAPCHUNK_FLAG_FILED; +} + +// LinkNeighbours' rule (0x006C29C0) over the scene's own chunks: a row +// before, a column after, a row after, a column before. +void LinkNeighbours(Land &land) { + std::map, void *> at; + for (Chunk &c : land.chunks) + at[{Game::Read(c.object(), Offsets::OFF_CMAPCHUNK_GLOBAL_ROW), + Game::Read(c.object(), Offsets::OFF_CMAPCHUNK_GLOBAL_COLUMN)}] = c.object(); + const int steps[4][2] = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}}; + for (Chunk &c : land.chunks) { + void *o = c.object(); + const uint32_t row = Game::Read(o, Offsets::OFF_CMAPCHUNK_GLOBAL_ROW); + const uint32_t column = Game::Read(o, Offsets::OFF_CMAPCHUNK_GLOBAL_COLUMN); + for (int i = 0; i < 4; ++i) { + const auto found = at.find({row + steps[i][0], column + steps[i][1]}); + Game::Ref(o, Offsets::OFF_CMAPCHUNK_NEIGHBOURS + i * 4) = + found != at.end() ? found->second : nullptr; + } + } +} + +void AttachBuffers(Land &land) { + for (size_t i = 0; i < land.chunks.size(); ++i) { + void *o = land.chunks[i].object(); + Game::Ref(o, Offsets::OFF_CMAPCHUNK_VERTEX_BUFFER) = land.buffers[i].first; + Game::Ref(o, Offsets::OFF_CMAPCHUNK_INDEX_BUFFER) = land.buffers[i].second; + } +} + +void BuildAll(Land &land) { + land.built = Settings::Current(); + for (auto &t : land.tiles) + LoadTextures(*t); + for (Chunk &c : land.chunks) + BuildChunk(c); + LinkNeighbours(land); + AttachBuffers(land); +} + +// UnloadChunk and the destructor, as DestroyChunk (0x006A6A00) does less +// the pool: the buffers are the scene's and stay; then each tile's +// textures. +void UnloadAll(Land &land) { + using This_t = void(__thiscall *)(void *); + for (Chunk &c : land.chunks) { + void *o = c.object(); + reinterpret_cast(Offsets::FUN_UNLOAD_CHUNK)(o); + reinterpret_cast(Offsets::FUN_CMAPCHUNK_DTOR)(o); + } + for (auto &t : land.tiles) + CloseTextures(*t); +} + +// The scene's pool, made as CreateChunkBufferPool makes the world's: one +// vertex and one index pool, a full-level pair of sub-buffers per chunk. +bool MakeBuffers(Land &land) { + using Pool_t = void *(__fastcall *)(uint32_t kind, uint32_t usage, uint32_t size, uint32_t arg, const char *name); + using Buffer_t = void *(__fastcall *)(void *pool, uint32_t itemSize, uint32_t count, uint32_t offset); + const uint32_t n = static_cast(land.chunks.size()); + const uint32_t vertexBytes = FullVertexCount() * Offsets::CHUNK_VERTEX_SIZE; + const uint32_t indexBytes = FullIndexCount() * Offsets::CHUNK_INDEX_SIZE; + land.vertexPool = reinterpret_cast(Offsets::FUN_GX_CREATE_POOL)( + Offsets::GX_POOL_KIND_VERTEX, Offsets::GX_POOL_USAGE_STATIC, n * vertexBytes, Offsets::GX_POOL_ARG, + kVertexPoolName); + land.indexPool = reinterpret_cast(Offsets::FUN_GX_CREATE_POOL)( + Offsets::GX_POOL_KIND_INDEX, Offsets::GX_POOL_USAGE_STATIC, n * indexBytes, Offsets::GX_POOL_ARG, + kIndexPoolName); + if (land.vertexPool == nullptr || land.indexPool == nullptr) + return false; + for (uint32_t i = 0; i < n; ++i) { + void *v = reinterpret_cast(Offsets::FUN_GX_POOL_BUFFER)( + land.vertexPool, Offsets::CHUNK_VERTEX_SIZE, FullVertexCount(), i * vertexBytes); + void *x = reinterpret_cast(Offsets::FUN_GX_POOL_BUFFER)( + land.indexPool, Offsets::CHUNK_INDEX_SIZE, FullIndexCount(), i * indexBytes); + land.buffers.emplace_back(v, x); + if (v == nullptr || x == nullptr) + return false; + } + return true; +} + +// FreeChunkBufferPool's order (0x006AE5C0): each sub-buffer, then the pools. +void FreeBuffers(Land &land) { + using Free_t = void(__fastcall *)(void *buffer); + for (auto &pair : land.buffers) { + if (pair.first != nullptr) + reinterpret_cast(Offsets::FUN_GX_FREE_BUFFER)(pair.first); + if (pair.second != nullptr) + reinterpret_cast(Offsets::FUN_GX_FREE_BUFFER)(pair.second); + } + land.buffers.clear(); + for (void *pool : {land.indexPool, land.vertexPool}) + if (pool != nullptr) + reinterpret_cast(Offsets::FUN_GX_BUFFER_RELEASE)(pool); + land.vertexPool = land.indexPool = nullptr; +} + +// The distance from a point to a chunk's square, its corner at the MCNK +// position and its sides one 16th of a tile toward the map's far side. +bool ChunkInRadius(const uint8_t *record, float x, float y, float radius, float side) { + const uint8_t *position = record + Offsets::MCNK_RECORD_HEADER + Offsets::OFF_MCNK_POSITION; + const float maxX = F32(position), maxY = F32(position + 4); + const float dx = x < maxX - side ? maxX - side - x : (x > maxX ? x - maxX : 0.0f); + const float dy = y < maxY - side ? maxY - side - y : (y > maxY ? y - maxY : 0.0f); + return dx * dx + dy * dy <= radius * radius; +} + +int TileIndex(float origin, float coordinate, float tile) { + return static_cast(std::floor((origin - coordinate) / tile)); +} + +} // namespace + +Land *Load(uint32_t mapID, float x, float y, float radius) { + if (!(radius >= 0.0f) || !std::isfinite(x) || !std::isfinite(y) || !std::isfinite(radius)) + return nullptr; + const char *dir = + DBC::StringField(Offsets::VAR_MAP_RECORDS, Offsets::VAR_MAP_COUNT, mapID, Offsets::OFF_MAP_DIRECTORY); + if (dir == nullptr || *dir == '\0') + return nullptr; + const float origin = Game::Read(Offsets::VAR_MAP_ORIGIN); + const float tile = Game::Read(Offsets::VAR_TILE_SIZE); + const float side = tile / static_cast(Offsets::TILE_CHUNKS); + const int last = Offsets::MAP_TILES - 1; + const auto clamp = [last](int v) { return v < 0 ? 0 : (v > last ? last : v); }; + const int rowFirst = clamp(TileIndex(origin, x + radius, tile)); + const int rowLast = clamp(TileIndex(origin, x - radius, tile)); + const int columnFirst = clamp(TileIndex(origin, y + radius, tile)); + const int columnLast = clamp(TileIndex(origin, y - radius, tile)); + auto land = std::make_unique(); + for (int row = rowFirst; row <= rowLast; ++row) { + for (int column = columnFirst; column <= columnLast; ++column) { + char path[260]; + std::snprintf(path, sizeof path, "World\\Maps\\%s\\%s_%d_%d.adt", dir, dir, column, row); + auto t = std::make_unique(); + t->column = static_cast(column); + t->row = static_cast(row); + if (!ReadFile(path, t->file) || !ParseHeader(*t)) + continue; + const uint32_t textures = TextureCount(*t); + for (uint32_t i = 0; i < Offsets::ADT_CHUNKS; ++i) { + const uint8_t *record = CheckedRecord(*t, i, textures); + if (record != nullptr && ChunkInRadius(record, x, y, radius, side)) + t->wanted.push_back(i); + } + if (t->wanted.empty()) + continue; + for (uint32_t i : t->wanted) { + Chunk c; + c.memory = std::make_unique(); + c.tile = t.get(); + c.index = i; + land->chunks.push_back(std::move(c)); + } + land->tiles.push_back(std::move(t)); + } + } + if (land->chunks.empty()) + return nullptr; + if (!MakeBuffers(*land)) { + FreeBuffers(*land); + return nullptr; + } + BuildAll(*land); + return land.release(); +} + +void Free(Land *land) { + if (land == nullptr) + return; + UnloadAll(*land); + FreeBuffers(*land); + delete land; +} + +void Draw(Land &land, void *frame, const float (&eye)[3], float farClip) { + const uint32_t worldFlags = Game::Read(Offsets::VAR_WORLD_FLAGS); + if ((worldFlags & Offsets::WORLD_FLAG_CHUNKS) == 0) + return; + if (!(Settings::Current() == land.built)) { + UnloadAll(land); + BuildAll(land); + } + + // The fog end the world's draw compares with: the scene's fog, else the + // far clip, past which nothing draws. + const bool fogged = + (Game::Read(frame, Offsets::OFF_SIMPLEMODEL_FOG_FLAGS) & Offsets::SIMPLEMODEL_FOG_ARMED) != 0; + const float fogEnd = fogged ? Game::Read(frame, Offsets::OFF_SIMPLEMODEL_FOG_FAR) : farClip; + + // The chunk update (0x006AFAD0) for every chunk: the sphere's view depth + // and the level, before any mesh is keyed (SelectMesh reads the + // neighbours' levels). The view looks from the origin, so its third + // column is the view axis for a point relative to the eye. + Matrix view; + Gx::GetView(view); + const bool lod = (worldFlags & Offsets::WORLD_FLAG_LOD) != 0; + const float lodDist = Game::Read(Offsets::VAR_CHUNK_LOD_DIST); + const uint32_t nearLevel = Game::Read(Offsets::VAR_CHUNK_MAX_LOD); + const uint32_t farLevel = Game::Read(Offsets::VAR_CHUNK_FAR_LOD); + for (Chunk &c : land.chunks) { + void *o = c.object(); + const float *centre = Game::Ptr(o, Offsets::OFF_CMAPCHUNK_CENTRE); + const float depth = (centre[0] - eye[0]) * view[2] + (centre[1] - eye[1]) * view[6] + + (centre[2] - eye[2]) * view[10] - Game::Read(o, Offsets::OFF_CMAPCHUNK_RADIUS); + Game::Ref(o, Offsets::OFF_CMAPCHUNK_VIEW_DEPTH) = depth; + Game::Ref(o, Offsets::OFF_CMAPCHUNK_LEVEL) = lod && depth > lodDist ? farLevel : nearLevel; + } + + alignas(16) uint8_t volume[Offsets::FRUSTUM_VOLUME_SIZE] = {}; + World::ViewVolume(volume, eye); + float &cameraX = Game::Ref(Offsets::VAR_CAMERA_POSITION); + float *camera = &cameraX; + float &worldFogEnd = Game::Ref(Offsets::VAR_FOG_END); + const float savedCamera[3] = {camera[0], camera[1], camera[2]}; + const float savedFogEnd = worldFogEnd; + camera[0] = eye[0]; + camera[1] = eye[1]; + camera[2] = eye[2]; + worldFogEnd = fogEnd; + + using Fn_t = void(__cdecl *)(); + const Gx::SavedStates states; + if ((worldFlags & Offsets::WORLD_FLAG_ANISOTROPIC) != 0) { + const float bias = Game::Read(Offsets::VAR_CHUNK_MIP_BIAS_IMMEDIATE); + for (int i = 0; i < Offsets::MIP_BIAS_STAGES; ++i) + Gx::SetStateFloat(Offsets::GXRS_MIP_BIAS_STAGE0 + i, bias); + } + reinterpret_cast(Offsets::FUN_FRUSTUM_PUSH)(); + reinterpret_cast(Offsets::FUN_FRUSTUM_STORE)(volume); + Gx::PushTransform(kWorldStack); + void *scene = Model::Pane::Scene(frame); + using Culled_t = uint32_t(__thiscall *)(const float *box); + using Init_t = void(__thiscall *)(void *record, void *unused, const float *sphere); + using Lights_t = void(__thiscall *)(void *scene, void *record); + using Commit_t = void(__thiscall *)(void *record, const float *origin, int fog); + using Callback_t = void(__fastcall *)(void *instance, void *record, void *frame); + using Mesh_t = void(__thiscall *)(void *chunk, uint32_t draw); + for (Chunk &c : land.chunks) { + void *o = c.object(); + const uint8_t *header = Game::Read(o, Offsets::OFF_CMAPCHUNK_HEADER); + if (Game::Read(header, Offsets::OFF_MCNK_HOLES) == Offsets::MCNK_HOLES_ALL || + reinterpret_cast(Offsets::FUN_FRUSTUM_IS_BOX_CULLED)( + Game::Ptr(o, Offsets::OFF_CMAPCHUNK_BOX)) != 0) + continue; + const float *position = Game::Ptr(o, Offsets::OFF_CMAPCHUNK_POSITION); + Matrix world; + Identity(world); + Translate(world, {position[0] - eye[0], position[1] - eye[1], position[2] - eye[2]}); + Gx::SetTransform(kWorldStack, world); + + alignas(16) uint8_t record[Offsets::M2_LIGHTING_RECORD_SIZE] = {}; + reinterpret_cast(Offsets::FUN_M2LIGHTING_INIT)(record, nullptr, + Game::Ptr(o, Offsets::OFF_CMAPCHUNK_CENTRE)); + reinterpret_cast(Offsets::FUN_M2SCENE_ADD_LIGHTS_FOR_POINT)(scene, record); + // The chunk's slots: the fog always, the light only nearer than the + // fog end by twice the radius (a NaN depth adds none). + const float reach = Game::Read(o, Offsets::OFF_CMAPCHUNK_VIEW_DEPTH) - + Game::Read(o, Offsets::OFF_CMAPCHUNK_RADIUS); + if (reach < fogEnd) + reinterpret_cast(Offsets::FUN_SIMPLEMODELFFX_LIGHT_FOG_CB)(nullptr, record, frame); + else + World::FrameFog(record, frame); + reinterpret_cast(Offsets::FUN_M2LIGHTING_SET_DEVICE_LIGHTS)(record, eye, 1); + reinterpret_cast(Offsets::FUN_CMAPCHUNK_SELECT_MESH)(o, 1); + } + Gx::PopTransform(kWorldStack); + reinterpret_cast(Offsets::FUN_FRUSTUM_POP)(); + camera[0] = savedCamera[0]; + camera[1] = savedCamera[1]; + camera[2] = savedCamera[2]; + worldFogEnd = savedFogEnd; +} + +} // namespace Model::Scene::Terrain diff --git a/src/model/SceneWorld.cpp b/src/model/SceneWorld.cpp index c37f749c..1478c34e 100644 --- a/src/model/SceneWorld.cpp +++ b/src/model/SceneWorld.cpp @@ -837,6 +837,12 @@ void ReleaseDoodad(Doodad &d) { } // namespace +void ViewVolume(uint8_t (&volume)[Offsets::FRUSTUM_VOLUME_SIZE], const float (&eye)[3]) { + BuildViewVolume(volume, eye); +} + +void FrameFog(void *record, void *frame) { SceneFog(record, frame); } + bool IsWmoPath(const char *path) { return path != nullptr && HasWmoSuffix(path); } Backdrop *Load(const char *path, const float (&placement)[16], uint32_t doodadSet, uint32_t mapID) {