mirror of
https://github.com/DarkflameUniverse/DarkflameServer.git
synced 2026-10-28 15:37:14 +00:00
feat: Raw reading on zone load and scene tools (#1910)
* feat: raw terrain parsing for scene data Replace old dNavigation/dTerrain raw parser with new Raw module in dZoneManager. Parse heightmaps, color maps, and scene maps from .raw files to determine which scene a position belongs to. Build scene adjacency graph from terrain data and scene transitions. Adds NiColor type, SceneColor lookup table, eSceneType enum, terrain mesh generation with OBJ export, and debug slash commands for scene visualization. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * refactor: deduplicate terrain grid lookup logic, remove unnecessary cast Add IsValidForSceneLookup(), GetSceneIDAtGrid(), and GridToWorldPos() to Raw::Chunk. Use them in GenerateTerrainMesh, GetSceneIDFromPosition, SpawnScenePoints, and SpawnAllScenePoints instead of duplicated inline math. Remove unnecessary static_cast in LoadSceneTransitionInfo. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix: add version < 32 support to raw terrain parser The parser was only correct for v32 files. For v<32: - colorMapResolution is width-1, not width - Color map reads width*width*4 bytes (BGRA per-pixel), not colorMapRes^2*4 - No DDS lightmap - No texture settings byte or blend DDS - Scene map: v31 reads (colorMapRes+1)^2 cells with border skip, v<31 skips 1 byte - No mesh data Verified against all 309 .raw files across multiple client versions. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix: log and reject legacy raw terrain format, clean up ReadRaw API Log a clear message and throw if the zone uses a legacy raw format (LUZ version < 30) since no known maps use it. Remove ReadLegacyRaw and the mapVersion parameter from ReadRaw. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix: revert v33 scene field renames to unknown1/unknown2 These fields are skipped by the client in every known build (ptr += 12 and ptr += 4). No client ever reads them into a struct. Keep the original unknown1/unknown2 names from main. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix: load the zone without scene lookups when its raw terrain is missing or unreadable Log at debug when it parses; build the terrain mesh only for the OBJ export; read the zone name and description only for version 31 and later, as the client does. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: look up the scene at a position as the client does, in constant time Chunk bounds span (width - 1) * scale; the nearest scene map cell is used and the far edge is kept one cell inside. Chunks are indexed by grid cell when they form a grid. Skipping reads instead of seeking, so a cut-off file can't seek past the end. Terrain mesh indices follow the vertex order. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * feat: scene point commands take a step and use brick LOTs from the BrickIDTable Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * chore: rename NiColor::ToXYZ to Luminance Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test: raw terrain reading, scene lookup, scene graph and scene commands Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test: close the OBJ file before removing it so the test passes on Windows Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: keep the zone boundary lines and read the luz scene count as the client does Each boundary line's destination is read as a map ID and an instance ID into a LWOZONEID. The scene count is a byte before version 37 and a u32 from it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: name the fourth flair colour byte padding The client never sets or reads it, so it holds leftover memory. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: keep the scene map of version 31 and older raws These files have a (resolution + 1)^2 scene map, kept in sceneMapLegacy. Version 31 uses its first resolution rows and columns; older versions are all scene 0, as in the client. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor: simplify the raw heightmap size check The dimensions are capped at kMaxResolution, so the product can't overflow. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * chore: remove the scene point spawn commands and send /getadjacentscenes as one message The spawn commands were only for testing. /getscene and /getadjacentscenes stay. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
set(DZONEMANAGER_SOURCES "dZoneManager.cpp"
|
||||
"Level.cpp"
|
||||
"Raw.cpp"
|
||||
"Spawner.cpp"
|
||||
"Zone.cpp")
|
||||
|
||||
@@ -14,6 +15,7 @@ target_include_directories(dZoneManager PUBLIC "."
|
||||
"${PROJECT_SOURCE_DIR}/dGame" # Entity.h
|
||||
"${PROJECT_SOURCE_DIR}/dGame/dEntity" # EntityInfo.h
|
||||
PRIVATE
|
||||
"${PROJECT_SOURCE_DIR}/dCommon/dClient" # SceneColor.h
|
||||
"${PROJECT_SOURCE_DIR}/dGame/dComponents" #InventoryComponent.h
|
||||
"${PROJECT_SOURCE_DIR}/dGame/dInventory" #InventoryComponent.h (transitive)
|
||||
"${PROJECT_SOURCE_DIR}/dGame/dBehaviors" #BehaviorSlot.h
|
||||
|
||||
573
dZoneManager/Raw.cpp
Normal file
573
dZoneManager/Raw.cpp
Normal file
@@ -0,0 +1,573 @@
|
||||
#include "Raw.h"
|
||||
#include "BinaryIO.h"
|
||||
#include "Logger.h"
|
||||
#include "SceneColor.h"
|
||||
#include <fstream>
|
||||
#include <algorithm>
|
||||
#include <limits>
|
||||
#include <cmath>
|
||||
|
||||
namespace {
|
||||
constexpr uint32_t kMaxResolution = 4096;
|
||||
constexpr size_t kMaxBlobBytes = 64ULL * 1024 * 1024; // 64 MiB
|
||||
constexpr uint32_t kMaxChunks = 1024;
|
||||
} // namespace
|
||||
|
||||
namespace Raw {
|
||||
|
||||
bool Chunk::IsValidForSceneLookup() const {
|
||||
return !sceneMap.empty() && colorMapResolution > 0 && !heightMap.empty()
|
||||
&& scaleFactor > 0.0f && width > 1 && height > 1;
|
||||
}
|
||||
|
||||
uint8_t Chunk::GetSceneIDAtLocal(float localX, float localZ) const {
|
||||
// The nearest scene map cell
|
||||
const auto toCell = [this](float cell) {
|
||||
return static_cast<uint32_t>(std::clamp(static_cast<int32_t>(std::floor(cell + 0.5f)), 0, static_cast<int32_t>(colorMapResolution) - 1));
|
||||
};
|
||||
const uint32_t sceneIndex = toCell(sceneCellsPerUnitX * localX) * colorMapResolution + toCell(sceneCellsPerUnitZ * localZ);
|
||||
if (sceneIndex >= sceneMap.size()) return 0;
|
||||
return sceneMap[sceneIndex];
|
||||
}
|
||||
|
||||
uint8_t Chunk::GetSceneIDAtGrid(uint32_t i, uint32_t j) const {
|
||||
return GetSceneIDAtLocal(static_cast<float>(i) * scaleFactor, static_cast<float>(j) * scaleFactor);
|
||||
}
|
||||
|
||||
NiPoint3 Chunk::GridToWorldPos(uint32_t i, uint32_t j) const {
|
||||
const uint32_t heightIndex = i * height + j;
|
||||
const float y = heightIndex < heightMap.size() ? heightMap[heightIndex] : 0.0f;
|
||||
return NiPoint3(offsetX + static_cast<float>(i) * scaleFactor, y, offsetZ + static_cast<float>(j) * scaleFactor);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Read flair attributes from stream
|
||||
*/
|
||||
static bool ReadFlairAttributes(std::istream& stream, FlairAttributes& flair) {
|
||||
try {
|
||||
BinaryIO::BinaryRead(stream, flair.id);
|
||||
BinaryIO::BinaryRead(stream, flair.scaleFactor);
|
||||
BinaryIO::BinaryRead(stream, flair.position.x);
|
||||
BinaryIO::BinaryRead(stream, flair.position.y);
|
||||
BinaryIO::BinaryRead(stream, flair.position.z);
|
||||
BinaryIO::BinaryRead(stream, flair.rotation.x);
|
||||
BinaryIO::BinaryRead(stream, flair.rotation.y);
|
||||
BinaryIO::BinaryRead(stream, flair.rotation.z);
|
||||
BinaryIO::BinaryRead(stream, flair.colorR);
|
||||
BinaryIO::BinaryRead(stream, flair.colorG);
|
||||
BinaryIO::BinaryRead(stream, flair.colorB);
|
||||
BinaryIO::BinaryRead(stream, flair.padding);
|
||||
return true;
|
||||
} catch (const std::exception&) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Read mesh triangle data from stream
|
||||
*/
|
||||
static bool ReadMeshTri(std::istream& stream, MeshTri& meshTri) {
|
||||
try {
|
||||
BinaryIO::BinaryRead(stream, meshTri.meshTriListSize);
|
||||
meshTri.meshTriList.resize(meshTri.meshTriListSize);
|
||||
for (uint16_t i = 0; i < meshTri.meshTriListSize; ++i) {
|
||||
BinaryIO::BinaryRead(stream, meshTri.meshTriList[i]);
|
||||
}
|
||||
return true;
|
||||
} catch (const std::exception&) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Read a chunk from stream
|
||||
*/
|
||||
static bool ReadChunkData(std::istream& stream, Chunk& chunk, uint16_t version) {
|
||||
try {
|
||||
// Read basic chunk info
|
||||
BinaryIO::BinaryRead(stream, chunk.id);
|
||||
if (stream.fail()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
BinaryIO::BinaryRead(stream, chunk.width);
|
||||
BinaryIO::BinaryRead(stream, chunk.height);
|
||||
BinaryIO::BinaryRead(stream, chunk.offsetX);
|
||||
BinaryIO::BinaryRead(stream, chunk.offsetZ);
|
||||
|
||||
if (stream.fail()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// For version < 32, shader ID comes before texture IDs
|
||||
if (version < 32) {
|
||||
BinaryIO::BinaryRead(stream, chunk.shaderId);
|
||||
}
|
||||
|
||||
// Read texture IDs (4 textures)
|
||||
chunk.textureIds.resize(4);
|
||||
for (int i = 0; i < 4; ++i) {
|
||||
BinaryIO::BinaryRead(stream, chunk.textureIds[i]);
|
||||
}
|
||||
|
||||
if (stream.fail()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Read scale factor
|
||||
BinaryIO::BinaryRead(stream, chunk.scaleFactor);
|
||||
|
||||
if (stream.fail()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Read heightmap: width * height floats, at most kMaxResolution^2 (64 MiB)
|
||||
if (chunk.width == 0 || chunk.height == 0 || chunk.width > kMaxResolution || chunk.height > kMaxResolution) {
|
||||
LOG("Chunk %u has invalid heightmap dimensions: width=%u, height=%u (max %u)", chunk.id, chunk.width, chunk.height, kMaxResolution);
|
||||
return false;
|
||||
}
|
||||
|
||||
const size_t heightMapSize = static_cast<size_t>(chunk.width) * chunk.height;
|
||||
chunk.heightMap.resize(heightMapSize);
|
||||
for (size_t i = 0; i < heightMapSize; ++i) {
|
||||
BinaryIO::BinaryRead(stream, chunk.heightMap[i]);
|
||||
}
|
||||
|
||||
if (stream.fail()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// ColorMap
|
||||
if (version >= 32) {
|
||||
BinaryIO::BinaryRead(stream, chunk.colorMapResolution);
|
||||
} else {
|
||||
chunk.colorMapResolution = chunk.width - 1;
|
||||
}
|
||||
|
||||
if (chunk.colorMapResolution > kMaxResolution) {
|
||||
LOG("Chunk colorMapResolution %u exceeds maximum %u", chunk.colorMapResolution, kMaxResolution);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (version >= 32) {
|
||||
const size_t colorMapPixelCount = static_cast<size_t>(chunk.colorMapResolution) * chunk.colorMapResolution * 4;
|
||||
if (colorMapPixelCount > kMaxBlobBytes) {
|
||||
LOG("Chunk colorMap size %zu exceeds maximum %zu bytes", colorMapPixelCount, kMaxBlobBytes);
|
||||
return false;
|
||||
}
|
||||
chunk.colorMap.resize(colorMapPixelCount);
|
||||
stream.read(reinterpret_cast<char*>(chunk.colorMap.data()), static_cast<std::streamsize>(colorMapPixelCount));
|
||||
} else {
|
||||
const size_t legacyColorBytes = static_cast<size_t>(chunk.width) * chunk.width * 4;
|
||||
if (legacyColorBytes > kMaxBlobBytes) {
|
||||
LOG("Chunk legacy colorMap size %zu exceeds maximum %zu bytes", legacyColorBytes, kMaxBlobBytes);
|
||||
return false;
|
||||
}
|
||||
chunk.colorMap.resize(legacyColorBytes);
|
||||
stream.read(reinterpret_cast<char*>(chunk.colorMap.data()), static_cast<std::streamsize>(legacyColorBytes));
|
||||
}
|
||||
|
||||
if (stream.fail()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// LightMap/diffusemap.dds (v>=32 only)
|
||||
if (version >= 32) {
|
||||
uint32_t lightMapSize;
|
||||
BinaryIO::BinaryRead(stream, lightMapSize);
|
||||
|
||||
if (lightMapSize > kMaxBlobBytes) {
|
||||
LOG("Chunk lightMap size %u exceeds maximum %zu bytes", lightMapSize, kMaxBlobBytes);
|
||||
return false;
|
||||
}
|
||||
chunk.lightMap.resize(lightMapSize);
|
||||
stream.read(reinterpret_cast<char*>(chunk.lightMap.data()), static_cast<std::streamsize>(lightMapSize));
|
||||
|
||||
if (stream.fail()) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Blend/texture map
|
||||
BinaryIO::BinaryRead(stream, chunk.textureMapResolution);
|
||||
|
||||
if (chunk.textureMapResolution > kMaxResolution) {
|
||||
LOG("Chunk textureMapResolution %u exceeds maximum %u", chunk.textureMapResolution, kMaxResolution);
|
||||
return false;
|
||||
}
|
||||
const size_t textureMapPixelCount = static_cast<size_t>(chunk.textureMapResolution) * chunk.textureMapResolution * 4;
|
||||
if (textureMapPixelCount > kMaxBlobBytes) {
|
||||
LOG("Chunk textureMap size %zu exceeds maximum %zu bytes", textureMapPixelCount, kMaxBlobBytes);
|
||||
return false;
|
||||
}
|
||||
chunk.textureMap.resize(textureMapPixelCount);
|
||||
stream.read(reinterpret_cast<char*>(chunk.textureMap.data()), static_cast<std::streamsize>(textureMapPixelCount));
|
||||
|
||||
if (stream.fail()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Texture settings + blend map DDS (v>=32 only)
|
||||
if (version >= 32) {
|
||||
BinaryIO::BinaryRead(stream, chunk.textureSettings);
|
||||
|
||||
uint32_t blendMapDDSSize;
|
||||
BinaryIO::BinaryRead(stream, blendMapDDSSize);
|
||||
|
||||
if (blendMapDDSSize > kMaxBlobBytes) {
|
||||
LOG("Chunk blendMap size %u exceeds maximum %zu bytes", blendMapDDSSize, kMaxBlobBytes);
|
||||
return false;
|
||||
}
|
||||
chunk.blendMap.resize(blendMapDDSSize);
|
||||
stream.read(reinterpret_cast<char*>(chunk.blendMap.data()), static_cast<std::streamsize>(blendMapDDSSize));
|
||||
|
||||
if (stream.fail()) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Read flairs
|
||||
uint32_t numFlairs;
|
||||
BinaryIO::BinaryRead(stream, numFlairs);
|
||||
|
||||
if (stream.fail()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const size_t flairBytes = static_cast<size_t>(numFlairs) * sizeof(FlairAttributes);
|
||||
if (flairBytes > kMaxBlobBytes) {
|
||||
LOG("Chunk %u flair count %u exceeds maximum (byte size %zu > %zu)", chunk.id, numFlairs, flairBytes, kMaxBlobBytes);
|
||||
return false;
|
||||
}
|
||||
chunk.flairs.resize(numFlairs);
|
||||
for (uint32_t i = 0; i < numFlairs; ++i) {
|
||||
if (!ReadFlairAttributes(stream, chunk.flairs[i])) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Scene map
|
||||
if (version >= 32) {
|
||||
const size_t sceneMapSize = static_cast<size_t>(chunk.colorMapResolution) * chunk.colorMapResolution;
|
||||
|
||||
if (sceneMapSize > kMaxBlobBytes) {
|
||||
LOG("Chunk sceneMap size %zu exceeds maximum %zu bytes", sceneMapSize, kMaxBlobBytes);
|
||||
return false;
|
||||
}
|
||||
chunk.sceneMap.resize(sceneMapSize);
|
||||
stream.read(reinterpret_cast<char*>(chunk.sceneMap.data()), static_cast<std::streamsize>(sceneMapSize));
|
||||
} else {
|
||||
const size_t sceneMapCells = static_cast<size_t>(chunk.colorMapResolution + 1) * (chunk.colorMapResolution + 1);
|
||||
if (sceneMapCells > kMaxBlobBytes) {
|
||||
LOG("Chunk legacy sceneMap size %zu exceeds maximum %zu bytes", sceneMapCells, kMaxBlobBytes);
|
||||
return false;
|
||||
}
|
||||
chunk.sceneMapLegacy.resize(sceneMapCells);
|
||||
stream.read(reinterpret_cast<char*>(chunk.sceneMapLegacy.data()), static_cast<std::streamsize>(sceneMapCells));
|
||||
// Like the client: version 31 uses the first colorMapResolution rows and columns, older versions are all scene 0
|
||||
chunk.sceneMap.assign(static_cast<size_t>(chunk.colorMapResolution) * chunk.colorMapResolution, 0);
|
||||
if (version == 31) {
|
||||
for (uint32_t row = 0; row < chunk.colorMapResolution; ++row) {
|
||||
for (uint32_t col = 0; col < chunk.colorMapResolution; ++col) {
|
||||
chunk.sceneMap[row * chunk.colorMapResolution + col] = chunk.sceneMapLegacy[row * (chunk.colorMapResolution + 1) + col];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (stream.fail()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Mesh data (v>=32 only)
|
||||
if (version < 32) {
|
||||
return true;
|
||||
}
|
||||
|
||||
BinaryIO::BinaryRead(stream, chunk.vertSize);
|
||||
|
||||
if (stream.fail()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (chunk.vertSize == 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const size_t vertBytes = static_cast<size_t>(chunk.vertSize) * sizeof(uint16_t);
|
||||
if (vertBytes > kMaxBlobBytes) {
|
||||
LOG("Chunk %u vertSize %u exceeds maximum (byte size %zu > %zu)", chunk.id, chunk.vertSize, vertBytes, kMaxBlobBytes);
|
||||
return false;
|
||||
}
|
||||
chunk.meshVertUsage.resize(chunk.vertSize);
|
||||
for (uint32_t i = 0; i < chunk.vertSize; ++i) {
|
||||
BinaryIO::BinaryRead(stream, chunk.meshVertUsage[i]);
|
||||
}
|
||||
|
||||
if (stream.fail()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
chunk.meshVertSize.resize(16);
|
||||
for (int i = 0; i < 16; ++i) {
|
||||
BinaryIO::BinaryRead(stream, chunk.meshVertSize[i]);
|
||||
}
|
||||
|
||||
if (stream.fail()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
chunk.meshTri.resize(16);
|
||||
for (int i = 0; i < 16; ++i) {
|
||||
if (!ReadMeshTri(stream, chunk.meshTri[i])) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
} catch (const std::exception&) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Read a chunk and work out its scene map cell sizes
|
||||
*/
|
||||
static bool ReadChunk(std::istream& stream, Chunk& chunk, uint16_t version) {
|
||||
if (!ReadChunkData(stream, chunk, version)) return false;
|
||||
|
||||
if (chunk.IsValidForSceneLookup()) {
|
||||
chunk.sceneCellSizeX = static_cast<float>(chunk.width - 1) * chunk.scaleFactor / static_cast<float>(chunk.colorMapResolution);
|
||||
chunk.sceneCellSizeZ = static_cast<float>(chunk.height - 1) * chunk.scaleFactor / static_cast<float>(chunk.colorMapResolution);
|
||||
chunk.sceneCellsPerUnitX = 1.0f / chunk.sceneCellSizeX;
|
||||
chunk.sceneCellsPerUnitZ = 1.0f / chunk.sceneCellSizeZ;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Index the chunks by grid cell when they form a regular grid of equal chunks
|
||||
*/
|
||||
static void BuildChunkGrid(Raw& raw) {
|
||||
raw.chunkGrid.clear();
|
||||
const auto& first = raw.chunks.front();
|
||||
const float spanX = first.GetMaxX() - first.offsetX;
|
||||
const float spanZ = first.GetMaxZ() - first.offsetZ;
|
||||
if (spanX <= 0.0f || spanZ <= 0.0f) return;
|
||||
|
||||
const auto countX = static_cast<uint32_t>(std::lround((raw.maxBoundsX - raw.minBoundsX) / spanX));
|
||||
const auto countZ = static_cast<uint32_t>(std::lround((raw.maxBoundsZ - raw.minBoundsZ) / spanZ));
|
||||
if (countX == 0 || countZ == 0 || static_cast<size_t>(countX) * countZ > kMaxChunks) return;
|
||||
|
||||
std::vector<int32_t> grid(static_cast<size_t>(countX) * countZ, -1);
|
||||
for (size_t i = 0; i < raw.chunks.size(); ++i) {
|
||||
const auto& chunk = raw.chunks[i];
|
||||
const float cellX = (chunk.offsetX - raw.minBoundsX) / spanX;
|
||||
const float cellZ = (chunk.offsetZ - raw.minBoundsZ) / spanZ;
|
||||
const long x = std::lround(cellX);
|
||||
const long z = std::lround(cellZ);
|
||||
const bool sameSize = chunk.width == first.width && chunk.height == first.height && chunk.scaleFactor == first.scaleFactor;
|
||||
if (!sameSize || std::abs(cellX - x) > 0.01f || std::abs(cellZ - z) > 0.01f || x < 0 || z < 0
|
||||
|| x >= static_cast<long>(countX) || z >= static_cast<long>(countZ)) {
|
||||
LOG("Raw chunks are not a regular grid (chunk %u); scene lookups check every chunk", chunk.id);
|
||||
return;
|
||||
}
|
||||
auto& cell = grid[static_cast<size_t>(x) * countZ + z];
|
||||
if (cell == -1) cell = static_cast<int32_t>(i); // the client takes the first chunk that matches
|
||||
}
|
||||
|
||||
raw.chunkGrid = std::move(grid);
|
||||
raw.chunkGridCountX = countX;
|
||||
raw.chunkGridCountZ = countZ;
|
||||
raw.chunkSpanX = spanX;
|
||||
raw.chunkSpanZ = spanZ;
|
||||
}
|
||||
|
||||
bool ReadRaw(std::istream& stream, Raw& outRaw) {
|
||||
// Get stream size
|
||||
stream.seekg(0, std::ios::end);
|
||||
auto streamSize = stream.tellg();
|
||||
stream.seekg(0, std::ios::beg);
|
||||
|
||||
if (streamSize <= 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
// Read header
|
||||
BinaryIO::BinaryRead(stream, outRaw.version);
|
||||
|
||||
if (stream.fail()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
BinaryIO::BinaryRead(stream, outRaw.dev);
|
||||
|
||||
if (stream.fail()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Only read chunks if dev == 0
|
||||
if (outRaw.dev == 0) {
|
||||
BinaryIO::BinaryRead(stream, outRaw.numChunks);
|
||||
BinaryIO::BinaryRead(stream, outRaw.numChunksWidth);
|
||||
BinaryIO::BinaryRead(stream, outRaw.numChunksHeight);
|
||||
|
||||
if (outRaw.numChunks > kMaxChunks) {
|
||||
LOG("Raw numChunks %u exceeds maximum %u", outRaw.numChunks, kMaxChunks);
|
||||
return false;
|
||||
}
|
||||
|
||||
// Read all chunks
|
||||
outRaw.chunks.resize(outRaw.numChunks);
|
||||
for (uint32_t i = 0; i < outRaw.numChunks; ++i) {
|
||||
if (!ReadChunk(stream, outRaw.chunks[i], outRaw.version)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate terrain bounds from all chunks
|
||||
if (!outRaw.chunks.empty()) {
|
||||
outRaw.minBoundsX = std::numeric_limits<float>::max();
|
||||
outRaw.minBoundsZ = std::numeric_limits<float>::max();
|
||||
outRaw.maxBoundsX = std::numeric_limits<float>::lowest();
|
||||
outRaw.maxBoundsZ = std::numeric_limits<float>::lowest();
|
||||
|
||||
for (const auto& chunk : outRaw.chunks) {
|
||||
outRaw.minBoundsX = std::min(outRaw.minBoundsX, chunk.offsetX);
|
||||
outRaw.minBoundsZ = std::min(outRaw.minBoundsZ, chunk.offsetZ);
|
||||
outRaw.maxBoundsX = std::max(outRaw.maxBoundsX, chunk.GetMaxX());
|
||||
outRaw.maxBoundsZ = std::max(outRaw.maxBoundsZ, chunk.GetMaxZ());
|
||||
}
|
||||
LOG_DEBUG("Raw terrain bounds: X[%.2f, %.2f], Z[%.2f, %.2f]",
|
||||
outRaw.minBoundsX, outRaw.maxBoundsX, outRaw.minBoundsZ, outRaw.maxBoundsZ);
|
||||
BuildChunkGrid(outRaw);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
} catch (const std::exception&) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// The client's TerrainManager::GetSceneAtPos: clamp to the terrain bounds, keep one scene cell inside the far edge,
|
||||
// find the chunk containing the position (edges moved in by 0.001) and take its nearest scene map cell
|
||||
std::optional<uint8_t> Raw::GetSceneIDAt(float x, float z) const {
|
||||
if (chunks.empty()) return std::nullopt;
|
||||
|
||||
constexpr float kEdgeEpsilon = 0.001f;
|
||||
const float posX = std::clamp(x, minBoundsX, maxBoundsX);
|
||||
const float posZ = std::clamp(z, minBoundsZ, maxBoundsZ);
|
||||
|
||||
const auto sceneInChunk = [&](const Chunk& chunk) -> std::optional<uint8_t> {
|
||||
if (!chunk.IsValidForSceneLookup()) return std::nullopt;
|
||||
const float chunkX = std::min(posX, maxBoundsX - chunk.sceneCellSizeX);
|
||||
const float chunkZ = std::min(posZ, maxBoundsZ - chunk.sceneCellSizeZ);
|
||||
if (chunk.offsetX - kEdgeEpsilon <= chunkX && chunkX < chunk.GetMaxX() - kEdgeEpsilon &&
|
||||
chunk.offsetZ - kEdgeEpsilon <= chunkZ && chunkZ < chunk.GetMaxZ() - kEdgeEpsilon) {
|
||||
return chunk.GetSceneIDAtLocal(chunkX - chunk.offsetX, chunkZ - chunk.offsetZ);
|
||||
}
|
||||
return std::nullopt;
|
||||
};
|
||||
|
||||
if (chunkGrid.empty()) {
|
||||
for (const auto& chunk : chunks) {
|
||||
if (const auto sceneID = sceneInChunk(chunk)) return sceneID;
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
// The grid cell the position falls in, checked with the client's test; for a position on a float edge the
|
||||
// neighbouring cells are checked too
|
||||
const auto toCell = [](float pos, float min, float span, uint32_t count) {
|
||||
const auto cell = static_cast<int32_t>(std::floor((pos + kEdgeEpsilon - min) / span));
|
||||
return std::clamp(cell, 0, static_cast<int32_t>(count) - 1);
|
||||
};
|
||||
const int32_t cellX = toCell(posX, minBoundsX, chunkSpanX, chunkGridCountX);
|
||||
const int32_t cellZ = toCell(posZ, minBoundsZ, chunkSpanZ, chunkGridCountZ);
|
||||
for (const int32_t offsetX : { 0, -1, 1 }) {
|
||||
for (const int32_t offsetZ : { 0, -1, 1 }) {
|
||||
const int32_t x = cellX + offsetX;
|
||||
const int32_t z = cellZ + offsetZ;
|
||||
if (x < 0 || z < 0 || x >= static_cast<int32_t>(chunkGridCountX) || z >= static_cast<int32_t>(chunkGridCountZ)) continue;
|
||||
const int32_t index = chunkGrid[static_cast<size_t>(x) * chunkGridCountZ + z];
|
||||
if (index < 0) continue;
|
||||
if (const auto sceneID = sceneInChunk(chunks[index])) return sceneID;
|
||||
}
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
void GenerateTerrainMesh(const Raw& raw, TerrainMesh& outMesh) {
|
||||
outMesh.vertices.clear();
|
||||
outMesh.triangles.clear();
|
||||
|
||||
if (raw.chunks.empty() || raw.version < 32) {
|
||||
return; // No scene data available
|
||||
}
|
||||
|
||||
LOG_DEBUG("GenerateTerrainMesh: Processing %zu chunks", raw.chunks.size());
|
||||
|
||||
uint32_t vertexOffset = 0;
|
||||
|
||||
for (const auto& chunk : raw.chunks) {
|
||||
if (!chunk.IsValidForSceneLookup()) continue;
|
||||
|
||||
// One vertex per heightmap point, in [i * height + j] order
|
||||
for (uint32_t i = 0; i < chunk.width; ++i) {
|
||||
for (uint32_t j = 0; j < chunk.height; ++j) {
|
||||
outMesh.vertices.emplace_back(chunk.GridToWorldPos(i, j), chunk.GetSceneIDAtGrid(i, j));
|
||||
if (i > 0 && j > 0) {
|
||||
const uint32_t currentVert = vertexOffset + chunk.height * i + j;
|
||||
const uint32_t leftVert = currentVert - 1;
|
||||
const uint32_t bottomLeftVert = vertexOffset + chunk.height * (i - 1) + j - 1;
|
||||
const uint32_t bottomVert = vertexOffset + chunk.height * (i - 1) + j;
|
||||
|
||||
// First triangle
|
||||
outMesh.triangles.push_back(currentVert);
|
||||
outMesh.triangles.push_back(leftVert);
|
||||
outMesh.triangles.push_back(bottomLeftVert);
|
||||
|
||||
// Second triangle
|
||||
outMesh.triangles.push_back(bottomLeftVert);
|
||||
outMesh.triangles.push_back(bottomVert);
|
||||
outMesh.triangles.push_back(currentVert);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
vertexOffset += chunk.width * chunk.height;
|
||||
}
|
||||
}
|
||||
|
||||
bool WriteTerrainMeshToOBJ(const TerrainMesh& mesh, const std::string& path) {
|
||||
try {
|
||||
std::ofstream file(path);
|
||||
if (!file.is_open()) {
|
||||
LOG("Failed to open OBJ file for writing: %s", path.c_str());
|
||||
return false;
|
||||
}
|
||||
|
||||
for (const auto& v : mesh.vertices) {
|
||||
const NiColor& color = SceneColor::Get(v.sceneID);
|
||||
file << "v " << v.position.x << ' ' << v.position.y << ' ' << v.position.z
|
||||
<< ' ' << color.m_Red << ' ' << color.m_Green << ' ' << color.m_Blue << '\n';
|
||||
}
|
||||
|
||||
for (size_t i = 0; i < mesh.triangles.size(); i += 3) {
|
||||
file << "f " << (mesh.triangles[i] + 1) << ' '
|
||||
<< (mesh.triangles[i + 1] + 1) << ' '
|
||||
<< (mesh.triangles[i + 2] + 1) << '\n';
|
||||
}
|
||||
|
||||
file.close();
|
||||
LOG("Successfully wrote terrain mesh to OBJ: %s (%zu vertices, %zu triangles)",
|
||||
path.c_str(), mesh.vertices.size(), mesh.triangles.size() / 3);
|
||||
return true;
|
||||
} catch (const std::exception& e) {
|
||||
LOG("Exception while writing OBJ file: %s", e.what());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace Raw
|
||||
194
dZoneManager/Raw.h
Normal file
194
dZoneManager/Raw.h
Normal file
@@ -0,0 +1,194 @@
|
||||
#pragma once
|
||||
|
||||
#ifndef __RAW_H__
|
||||
#define __RAW_H__
|
||||
|
||||
#include <cstdint>
|
||||
#include <optional>
|
||||
#include <vector>
|
||||
#include <string>
|
||||
#include <istream>
|
||||
#include "NiPoint3.h"
|
||||
#include "dCommonVars.h"
|
||||
|
||||
namespace Raw {
|
||||
|
||||
/**
|
||||
* @brief Flair attributes structure
|
||||
* Represents decorative elements on the terrain
|
||||
*/
|
||||
struct FlairAttributes {
|
||||
uint32_t id;
|
||||
float scaleFactor;
|
||||
NiPoint3 position;
|
||||
NiPoint3 rotation;
|
||||
uint8_t colorR;
|
||||
uint8_t colorG;
|
||||
uint8_t colorB;
|
||||
// Padding: never set when a flair is placed, so it holds leftover memory; nothing reads it
|
||||
uint8_t padding;
|
||||
};
|
||||
static_assert(sizeof(FlairAttributes) == 36, "a flair record in the .raw is 36 bytes");
|
||||
|
||||
/**
|
||||
* @brief Mesh triangle structure
|
||||
* Contains triangle indices for terrain mesh
|
||||
*/
|
||||
struct MeshTri {
|
||||
uint16_t meshTriListSize;
|
||||
std::vector<uint16_t> meshTriList;
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Vertex with scene ID
|
||||
* Used for the generated terrain mesh to enable fast scene lookups
|
||||
*/
|
||||
struct SceneVertex {
|
||||
NiPoint3 position;
|
||||
uint8_t sceneID;
|
||||
|
||||
SceneVertex() : position(), sceneID(0) {}
|
||||
SceneVertex(const NiPoint3& pos, uint8_t scene) : position(pos), sceneID(scene) {}
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Generated terrain mesh
|
||||
* Contains vertices with scene IDs for fast scene lookups at arbitrary positions
|
||||
*/
|
||||
struct TerrainMesh {
|
||||
std::vector<SceneVertex> vertices;
|
||||
std::vector<uint32_t> triangles; // Indices into vertices array (groups of 3)
|
||||
|
||||
TerrainMesh() = default;
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Terrain chunk structure
|
||||
* Represents a single chunk of terrain with heightmap, textures, flair, scene map and meshes
|
||||
*/
|
||||
struct Chunk {
|
||||
uint32_t id;
|
||||
uint32_t width;
|
||||
uint32_t height;
|
||||
float offsetX;
|
||||
float offsetZ;
|
||||
uint32_t shaderId = 0; // version < 32 only
|
||||
|
||||
// Texture IDs (4 textures per chunk)
|
||||
std::vector<uint32_t> textureIds;
|
||||
|
||||
// Terrain scale factor (world units between two heightmap points)
|
||||
float scaleFactor;
|
||||
|
||||
// Heightmap data (width * height floats)
|
||||
std::vector<float> heightMap;
|
||||
|
||||
// Color map: colorMapResolution^2 RGBA pixels (version < 32: width^2 pixels, resolution width - 1)
|
||||
uint32_t colorMapResolution = 0;
|
||||
std::vector<uint8_t> colorMap;
|
||||
std::vector<uint8_t> lightMap; // DDS, version 32+
|
||||
|
||||
uint32_t textureMapResolution = 0;
|
||||
std::vector<uint8_t> textureMap; // textureMapResolution^2 RGBA pixels
|
||||
uint8_t textureSettings = 0; // version 32+
|
||||
std::vector<uint8_t> blendMap; // DDS, version 32+
|
||||
|
||||
// Flair data
|
||||
std::vector<FlairAttributes> flairs;
|
||||
|
||||
// The scene map is colorMapResolution * colorMapResolution scene IDs, indexed [x cell * resolution + z cell]
|
||||
std::vector<uint8_t> sceneMap;
|
||||
// Version 31 and older: the file's (colorMapResolution + 1)^2 scene map. In version 31 sceneMap is its first
|
||||
// colorMapResolution rows and columns; older versions don't use it and every cell is scene 0
|
||||
std::vector<uint8_t> sceneMapLegacy;
|
||||
|
||||
// Mesh data (version 32+)
|
||||
uint32_t vertSize = 0;
|
||||
std::vector<uint16_t> meshVertUsage;
|
||||
std::vector<uint16_t> meshVertSize;
|
||||
std::vector<MeshTri> meshTri;
|
||||
|
||||
// Scene map cells per world unit, and the size of one cell, along X and Z (set once the chunk is read)
|
||||
float sceneCellsPerUnitX = 0.0f;
|
||||
float sceneCellsPerUnitZ = 0.0f;
|
||||
float sceneCellSizeX = 0.0f;
|
||||
float sceneCellSizeZ = 0.0f;
|
||||
|
||||
bool IsValidForSceneLookup() const;
|
||||
float GetMaxX() const { return offsetX + static_cast<float>(width - 1) * scaleFactor; }
|
||||
float GetMaxZ() const { return offsetZ + static_cast<float>(height - 1) * scaleFactor; }
|
||||
// The scene ID at a position relative to the chunk's offset, as the client looks it up
|
||||
uint8_t GetSceneIDAtLocal(float localX, float localZ) const;
|
||||
uint8_t GetSceneIDAtGrid(uint32_t i, uint32_t j) const;
|
||||
NiPoint3 GridToWorldPos(uint32_t i, uint32_t j) const;
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief RAW terrain file structure
|
||||
* Complete representation of a .raw terrain file
|
||||
*/
|
||||
struct Raw {
|
||||
uint16_t version = 0;
|
||||
uint8_t dev = 0;
|
||||
uint32_t numChunks = 0;
|
||||
uint32_t numChunksWidth = 0;
|
||||
uint32_t numChunksHeight = 0;
|
||||
std::vector<Chunk> chunks;
|
||||
|
||||
// Calculated bounds of the entire terrain
|
||||
float minBoundsX = 0.0f;
|
||||
float minBoundsZ = 0.0f;
|
||||
float maxBoundsX = 0.0f;
|
||||
float maxBoundsZ = 0.0f;
|
||||
|
||||
// Chunk lookup by position: the chunks of every client terrain form a regular grid, written X-major
|
||||
// ([x * chunks along Z + z]). chunkGrid holds the index into chunks per grid cell (-1 for none); it is empty when
|
||||
// the chunks don't form a grid, and lookups then check every chunk.
|
||||
std::vector<int32_t> chunkGrid;
|
||||
uint32_t chunkGridCountX = 0;
|
||||
uint32_t chunkGridCountZ = 0;
|
||||
float chunkSpanX = 0.0f;
|
||||
float chunkSpanZ = 0.0f;
|
||||
|
||||
/**
|
||||
* @brief The scene ID at a world position, looked up as the client's TerrainManager::GetSceneAtPos does
|
||||
* (height is ignored). Constant time on a chunk grid.
|
||||
*
|
||||
* @return The scene ID, or nullopt when there is no terrain with a scene map there
|
||||
*/
|
||||
std::optional<uint8_t> GetSceneIDAt(float x, float z) const;
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Read a RAW terrain file from an input stream
|
||||
*
|
||||
* @param stream Input stream containing RAW file data
|
||||
* @param outRaw Output RAW file structure
|
||||
* @return true if successfully read, false otherwise
|
||||
*/
|
||||
bool ReadRaw(std::istream& stream, Raw& outRaw);
|
||||
|
||||
/**
|
||||
* @brief Generate a terrain mesh from raw chunks
|
||||
* Similar to dTerrain's GenerateFinalMeshFromChunks but creates a mesh with scene IDs
|
||||
* per vertex for fast scene lookups at arbitrary positions.
|
||||
*
|
||||
* @param raw The RAW terrain data to generate mesh from
|
||||
* @param outMesh Output terrain mesh with vertices and scene IDs
|
||||
*/
|
||||
void GenerateTerrainMesh(const Raw& raw, TerrainMesh& outMesh);
|
||||
|
||||
/**
|
||||
* @brief Write terrain mesh to OBJ file for debugging/visualization
|
||||
* Merged from dTerrain's WriteFinalMeshToOBJ functionality
|
||||
* Vertices are colored based on their scene ID using a hash function
|
||||
*
|
||||
* @param mesh The terrain mesh to export
|
||||
* @param path Output path for the OBJ file
|
||||
* @return true if successfully written, false otherwise
|
||||
*/
|
||||
bool WriteTerrainMeshToOBJ(const TerrainMesh& mesh, const std::string& path);
|
||||
|
||||
} // namespace Raw
|
||||
|
||||
#endif // __RAW_H__
|
||||
@@ -8,6 +8,7 @@
|
||||
#include "GeneralUtils.h"
|
||||
#include "BinaryIO.h"
|
||||
#include "LUTriggers.h"
|
||||
#include "dConfig.h"
|
||||
|
||||
#include "AssetManager.h"
|
||||
#include "CDClientManager.h"
|
||||
@@ -20,6 +21,7 @@
|
||||
#include "eTriggerEventType.h"
|
||||
#include "eWaypointCommandType.h"
|
||||
#include "dNavMesh.h"
|
||||
#include "Raw.h"
|
||||
|
||||
Zone::Zone(const LWOZONEID zoneID) :
|
||||
m_ZoneID(zoneID) {
|
||||
@@ -68,7 +70,8 @@ void Zone::LoadZoneIntoMemory() {
|
||||
BinaryIO::BinaryRead(file, m_SpawnpointRotation);
|
||||
}
|
||||
|
||||
if (m_FileFormatVersion <= Zone::FileFormatVersion::LateAlpha) {
|
||||
// A byte before version 37 (LateAlpha), a u32 from it
|
||||
if (m_FileFormatVersion < Zone::FileFormatVersion::LateAlpha) {
|
||||
uint8_t sceneCount;
|
||||
BinaryIO::BinaryRead(file, sceneCount);
|
||||
m_SceneCount = sceneCount;
|
||||
@@ -78,11 +81,56 @@ void Zone::LoadZoneIntoMemory() {
|
||||
LoadScene(file);
|
||||
}
|
||||
|
||||
//Read generic zone info:
|
||||
BinaryIO::ReadString<uint8_t>(file, m_ZonePath, BinaryIO::ReadType::String);
|
||||
// Zone boundary lines: a count byte, then the lines
|
||||
uint8_t numBoundaries = 0;
|
||||
BinaryIO::BinaryRead(file, numBoundaries);
|
||||
m_Boundaries.resize(numBoundaries);
|
||||
for (auto& boundary : m_Boundaries) {
|
||||
LWOMAPID destMapID = 0;
|
||||
LWOINSTANCEID destInstanceID = 0;
|
||||
BinaryIO::BinaryRead(file, boundary.normal);
|
||||
BinaryIO::BinaryRead(file, boundary.point);
|
||||
BinaryIO::BinaryRead(file, destMapID);
|
||||
BinaryIO::BinaryRead(file, destInstanceID);
|
||||
boundary.destinationZone = LWOZONEID(destMapID, destInstanceID, 0);
|
||||
BinaryIO::BinaryRead(file, boundary.destinationSceneID);
|
||||
BinaryIO::BinaryRead(file, boundary.spawnLocation);
|
||||
}
|
||||
|
||||
BinaryIO::ReadString<uint8_t>(file, m_ZoneRawPath, BinaryIO::ReadType::String);
|
||||
BinaryIO::ReadString<uint8_t>(file, m_ZoneName, BinaryIO::ReadType::String);
|
||||
BinaryIO::ReadString<uint8_t>(file, m_ZoneDesc, BinaryIO::ReadType::String);
|
||||
if (m_FileFormatVersion > Zone::FileFormatVersion::PrePreAlpha) {
|
||||
BinaryIO::ReadString<uint8_t>(file, m_ZoneName, BinaryIO::ReadType::String);
|
||||
BinaryIO::ReadString<uint8_t>(file, m_ZoneDesc, BinaryIO::ReadType::String);
|
||||
}
|
||||
|
||||
// The terrain gives the scene at a position. Like the client, a missing or unreadable .raw is logged
|
||||
// and the zone loads without it.
|
||||
const auto rawPath = m_ZoneFilePath.substr(0, m_ZoneFilePath.rfind('/') + 1) + m_ZoneRawPath;
|
||||
if (m_FileFormatVersion < Zone::FileFormatVersion::PrePreAlpha) {
|
||||
LOG("Zone %s uses the legacy raw terrain format (version %u), which is not supported; no scene lookups", m_ZoneFilePath.c_str(), static_cast<uint32_t>(m_FileFormatVersion));
|
||||
} else if (!Game::assetManager->HasFile(rawPath)) {
|
||||
LOG("Failed to find %s; no scene lookups", rawPath.c_str());
|
||||
} else {
|
||||
auto rawFile = Game::assetManager->GetFile(rawPath);
|
||||
if (Raw::ReadRaw(rawFile, m_Raw)) {
|
||||
LOG_DEBUG("Successfully parsed %s", rawPath.c_str());
|
||||
} else {
|
||||
LOG("Failed to parse %s; no scene lookups", rawPath.c_str());
|
||||
m_Raw = Raw::Raw{};
|
||||
}
|
||||
}
|
||||
|
||||
// Optionally export terrain mesh to OBJ for debugging/visualization
|
||||
if (Game::config->GetValue("export_terrain_to_obj") == "1") {
|
||||
Raw::TerrainMesh terrainMesh;
|
||||
Raw::GenerateTerrainMesh(m_Raw, terrainMesh);
|
||||
LOG("Generated terrain mesh with %zu vertices and %zu triangles", terrainMesh.vertices.size(), terrainMesh.triangles.size() / 3);
|
||||
|
||||
const std::string objFileName = "terrain_" + std::to_string(m_ZoneID.GetMapID()) + ".obj";
|
||||
if (Raw::WriteTerrainMeshToOBJ(terrainMesh, objFileName)) {
|
||||
LOG("Exported terrain mesh to %s", objFileName.c_str());
|
||||
}
|
||||
}
|
||||
|
||||
if (m_FileFormatVersion >= Zone::FileFormatVersion::PreAlpha) {
|
||||
BinaryIO::BinaryRead(file, m_NumberOfSceneTransitionsLoaded);
|
||||
@@ -236,7 +284,8 @@ void Zone::LoadScene(std::istream& file) {
|
||||
}
|
||||
if (m_FileFormatVersion >= Zone::FileFormatVersion::LatePreAlpha) {
|
||||
BinaryIO::BinaryRead(file, scene.sceneType);
|
||||
lwoSceneID.SetLayerID(scene.sceneType);
|
||||
lwoSceneID.SetLayerID(static_cast<uint32_t>(scene.sceneType));
|
||||
|
||||
|
||||
BinaryIO::ReadString<uint8_t>(file, scene.name, BinaryIO::ReadType::String);
|
||||
}
|
||||
@@ -247,9 +296,11 @@ void Zone::LoadScene(std::istream& file) {
|
||||
}
|
||||
|
||||
if (m_FileFormatVersion >= Zone::FileFormatVersion::LatePreAlpha) {
|
||||
BinaryIO::BinaryRead(file, scene.color_r);
|
||||
BinaryIO::BinaryRead(file, scene.color_b);
|
||||
BinaryIO::BinaryRead(file, scene.color_g);
|
||||
uint8_t r, b, g;
|
||||
BinaryIO::BinaryRead(file, r);
|
||||
BinaryIO::BinaryRead(file, b);
|
||||
BinaryIO::BinaryRead(file, g);
|
||||
scene.color = NiColor(r / 255.0f, g / 255.0f, b / 255.0f);
|
||||
}
|
||||
|
||||
m_Scenes[lwoSceneID] = std::move(scene);
|
||||
@@ -350,7 +401,10 @@ void Zone::LoadSceneTransition(std::istream& file) {
|
||||
|
||||
SceneTransitionInfo Zone::LoadSceneTransitionInfo(std::istream& file) {
|
||||
SceneTransitionInfo info;
|
||||
BinaryIO::BinaryRead(file, info.sceneID);
|
||||
uint32_t sceneID, layerID;
|
||||
BinaryIO::BinaryRead(file, sceneID);
|
||||
BinaryIO::BinaryRead(file, layerID);
|
||||
info.sceneID = LWOSCENEID(sceneID, layerID);
|
||||
BinaryIO::BinaryRead(file, info.position);
|
||||
return info;
|
||||
}
|
||||
@@ -422,7 +476,6 @@ void Zone::LoadPath(std::istream& file) {
|
||||
BinaryIO::BinaryRead(file, waypoint.position.y);
|
||||
BinaryIO::BinaryRead(file, waypoint.position.z);
|
||||
|
||||
|
||||
if (path.pathType == PathType::Spawner || path.pathType == PathType::MovingPlatform || path.pathType == PathType::Race || path.pathType == PathType::Camera || path.pathType == PathType::Rail) {
|
||||
BinaryIO::BinaryRead(file, waypoint.rotation.w);
|
||||
BinaryIO::BinaryRead(file, waypoint.rotation.x);
|
||||
@@ -483,7 +536,7 @@ void Zone::LoadPath(std::istream& file) {
|
||||
}
|
||||
|
||||
// We verify the waypoint heights against the navmesh because in many movement paths,
|
||||
// the waypoint is located near 0 height,
|
||||
// the waypoint is located near 0 height,
|
||||
if (path.pathType == PathType::Movement) {
|
||||
if (dpWorld::IsLoaded()) {
|
||||
// 2000 should be large enough for every world.
|
||||
@@ -494,3 +547,9 @@ void Zone::LoadPath(std::istream& file) {
|
||||
}
|
||||
m_Paths.push_back(path);
|
||||
}
|
||||
|
||||
const SceneRef* Zone::GetScene(LWOSCENEID sceneID) const {
|
||||
auto it = m_Scenes.find(sceneID);
|
||||
if (it != m_Scenes.end()) return &it->second;
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
@@ -2,10 +2,12 @@
|
||||
|
||||
#include "dZMCommon.h"
|
||||
#include "LDFFormat.h"
|
||||
#include "NiColor.h"
|
||||
#include "tinyxml2.h"
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <map>
|
||||
#include "Raw.h"
|
||||
|
||||
namespace LUTriggers {
|
||||
struct Trigger;
|
||||
@@ -21,25 +23,37 @@ struct WaypointCommand {
|
||||
};
|
||||
|
||||
|
||||
enum class eSceneType : uint32_t {
|
||||
General = 0,
|
||||
Audio = 1,
|
||||
};
|
||||
|
||||
struct SceneRef {
|
||||
std::string filename;
|
||||
uint32_t id{};
|
||||
uint32_t sceneType{}; //0 = general, 1 = audio?
|
||||
eSceneType sceneType{};
|
||||
std::string name;
|
||||
NiPoint3 unknown1;
|
||||
float unknown2{};
|
||||
uint8_t color_r{};
|
||||
uint8_t color_g{};
|
||||
uint8_t color_b{};
|
||||
NiColor color;
|
||||
std::unique_ptr<Level> level;
|
||||
std::map<uint32_t, LUTriggers::Trigger*> triggers;
|
||||
};
|
||||
|
||||
struct SceneTransitionInfo {
|
||||
uint64_t sceneID{}; //id of the scene being transitioned to.
|
||||
LWOSCENEID sceneID;
|
||||
NiPoint3 position;
|
||||
};
|
||||
|
||||
// A zone boundary line from the .luz
|
||||
struct ZoneBoundary {
|
||||
NiPoint3 normal;
|
||||
NiPoint3 point;
|
||||
LWOZONEID destinationZone; // the clone ID is always 0
|
||||
uint32_t destinationSceneID{};
|
||||
NiPoint3 spawnLocation;
|
||||
};
|
||||
|
||||
struct SceneTransition {
|
||||
std::string name;
|
||||
std::vector<SceneTransitionInfo> points;
|
||||
@@ -228,6 +242,12 @@ public:
|
||||
void SetSpawnPos(const NiPoint3& pos) { m_Spawnpoint = pos; }
|
||||
void SetSpawnRot(const NiQuaternion& rot) { m_SpawnpointRotation = rot; }
|
||||
|
||||
const Raw::Raw& GetZoneRaw() const { return m_Raw; }
|
||||
const SceneRef* GetScene(LWOSCENEID sceneID) const;
|
||||
const std::vector<SceneTransition>& GetSceneTransitions() const { return m_SceneTransitions; }
|
||||
const std::vector<ZoneBoundary>& GetBoundaries() const { return m_Boundaries; }
|
||||
const std::map<LWOSCENEID, SceneRef>& GetScenes() const { return m_Scenes; }
|
||||
|
||||
private:
|
||||
LWOZONEID m_ZoneID;
|
||||
std::string m_ZoneFilePath;
|
||||
@@ -244,9 +264,11 @@ private:
|
||||
std::string m_ZoneName; //Name given to the zone by a level designer
|
||||
std::string m_ZoneDesc; //Description of the zone by a level designer
|
||||
std::string m_ZoneRawPath; //Path to the .raw file of this zone.
|
||||
Raw::Raw m_Raw; // The Raw data for this zone
|
||||
|
||||
std::map<LWOSCENEID, SceneRef> m_Scenes;
|
||||
std::vector<SceneTransition> m_SceneTransitions;
|
||||
std::vector<ZoneBoundary> m_Boundaries;
|
||||
|
||||
uint32_t m_PathDataLength;
|
||||
uint32_t m_PathChunkVersion;
|
||||
|
||||
@@ -10,9 +10,10 @@
|
||||
#include "VanityUtilities.h"
|
||||
#include "WorldConfig.h"
|
||||
#include "CDZoneTableTable.h"
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <set>
|
||||
#include "eObjectBits.h"
|
||||
#include "CDZoneTableTable.h"
|
||||
#include "AssetManager.h"
|
||||
#include <ranges>
|
||||
|
||||
@@ -62,6 +63,9 @@ void dZoneManager::Initialize(const LWOZONEID& zoneID) {
|
||||
|
||||
m_pZone->Initalize();
|
||||
|
||||
// Build the scene graph after zone is loaded
|
||||
BuildSceneGraph();
|
||||
|
||||
endTime = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now().time_since_epoch()).count();
|
||||
|
||||
LoadWorldConfig();
|
||||
@@ -298,3 +302,83 @@ void dZoneManager::LoadWorldConfig() {
|
||||
|
||||
LOG_DEBUG("Loaded WorldConfig into memory");
|
||||
}
|
||||
|
||||
LWOSCENEID dZoneManager::GetSceneIDFromPosition(const NiPoint3& position) const {
|
||||
if (!m_pZone) return LWOSCENEID_INVALID;
|
||||
|
||||
const auto sceneID = m_pZone->GetZoneRaw().GetSceneIDAt(position.x, position.z);
|
||||
return sceneID ? LWOSCENEID(*sceneID, 0) : LWOSCENEID_INVALID;
|
||||
}
|
||||
|
||||
void dZoneManager::BuildSceneGraph() {
|
||||
if (!m_pZone) return;
|
||||
|
||||
// Clear any existing adjacency list
|
||||
m_SceneAdjacencyList.clear();
|
||||
|
||||
// Initialize adjacency list with all scenes
|
||||
const auto& scenes = m_pZone->GetScenes();
|
||||
for (const auto& [sceneID, sceneRef] : scenes) {
|
||||
if (sceneRef.sceneType != eSceneType::General) continue;
|
||||
m_SceneAdjacencyList.try_emplace(sceneID, std::vector<LWOSCENEID>());
|
||||
}
|
||||
|
||||
// Build adjacency list from scene transitions
|
||||
const auto& transitions = m_pZone->GetSceneTransitions();
|
||||
for (const auto& transition : transitions) {
|
||||
// Each transition has multiple points, each pointing to a scene
|
||||
// We need to determine which scenes this transition connects
|
||||
|
||||
// Group transition points by their scene IDs to find unique connections
|
||||
std::set<LWOSCENEID> connectedScenes;
|
||||
for (const auto& point : transition.points) {
|
||||
if (point.sceneID != LWOSCENEID_INVALID && m_SceneAdjacencyList.contains(point.sceneID)) {
|
||||
connectedScenes.insert(point.sceneID);
|
||||
}
|
||||
}
|
||||
|
||||
// Create bidirectional edges between all scenes in this transition
|
||||
// (transitions typically connect two scenes, but can be more complex)
|
||||
std::vector<LWOSCENEID> sceneList(connectedScenes.begin(), connectedScenes.end());
|
||||
|
||||
for (size_t i = 0; i < sceneList.size(); ++i) {
|
||||
for (size_t j = 0; j < sceneList.size(); ++j) {
|
||||
if (i != j) {
|
||||
LWOSCENEID fromScene = sceneList[i];
|
||||
LWOSCENEID toScene = sceneList[j];
|
||||
|
||||
// Add edge if it doesn't already exist
|
||||
auto& adjacentScenes = m_SceneAdjacencyList[fromScene];
|
||||
if (std::find(adjacentScenes.begin(), adjacentScenes.end(), toScene) == adjacentScenes.end()) {
|
||||
adjacentScenes.push_back(toScene);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Scene 0 (global scene) is always loaded and adjacent to all other scenes
|
||||
LWOSCENEID globalScene = LWOSCENEID(0, 0);
|
||||
for (auto& [sceneID, adjacentScenes] : m_SceneAdjacencyList) {
|
||||
if (sceneID != globalScene) {
|
||||
// Add global scene to this scene's adjacency list if not already present
|
||||
if (std::find(adjacentScenes.begin(), adjacentScenes.end(), globalScene) == adjacentScenes.end()) {
|
||||
adjacentScenes.push_back(globalScene);
|
||||
}
|
||||
|
||||
// Add this scene to global scene's adjacency list if not already present
|
||||
auto& globalAdjacent = m_SceneAdjacencyList[globalScene];
|
||||
if (std::find(globalAdjacent.begin(), globalAdjacent.end(), sceneID) == globalAdjacent.end()) {
|
||||
globalAdjacent.push_back(sceneID);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<LWOSCENEID> dZoneManager::GetAdjacentScenes(LWOSCENEID sceneID) const {
|
||||
auto it = m_SceneAdjacencyList.find(sceneID);
|
||||
if (it != m_SceneAdjacencyList.end()) {
|
||||
return it->second;
|
||||
}
|
||||
return std::vector<LWOSCENEID>();
|
||||
}
|
||||
|
||||
@@ -53,6 +53,35 @@ public:
|
||||
uint32_t GetUniqueMissionIdStartingValue();
|
||||
bool CheckIfAccessibleZone(LWOMAPID zoneID);
|
||||
|
||||
/**
|
||||
* @brief Get the scene ID at a given position. Scenes do not care about height (Y coordinate).
|
||||
*
|
||||
* @param position The position to query
|
||||
* @return The scene ID at that position, or LWOSCENEID_INVALID if not found
|
||||
*/
|
||||
LWOSCENEID GetSceneIDFromPosition(const NiPoint3& position) const;
|
||||
|
||||
/**
|
||||
* @brief Get the adjacency list for the scene graph.
|
||||
* The adjacency list maps each scene ID to a list of scene IDs it can transition to.
|
||||
*
|
||||
* @return A reference to the scene adjacency list
|
||||
*/
|
||||
const std::map<LWOSCENEID, std::vector<LWOSCENEID>>& GetSceneAdjacencyList() const { return m_SceneAdjacencyList; }
|
||||
|
||||
/**
|
||||
* @brief Get all scenes adjacent to (connected to) a given scene.
|
||||
*
|
||||
* @param sceneID The scene ID to query
|
||||
* @return A vector of scene IDs that are directly connected to this scene, or empty vector if scene not found
|
||||
*/
|
||||
std::vector<LWOSCENEID> GetAdjacentScenes(LWOSCENEID sceneID) const;
|
||||
|
||||
/**
|
||||
* @brief (Re)builds the scene graph adjacency list from the loaded zone's scene transitions.
|
||||
*/
|
||||
void BuildSceneGraph();
|
||||
|
||||
// The world config should not be modified by a caller.
|
||||
const WorldConfig& GetWorldConfig() {
|
||||
if (!m_WorldConfig) LoadWorldConfig();
|
||||
@@ -75,4 +104,9 @@ private:
|
||||
std::optional<WorldConfig> m_WorldConfig = std::nullopt;
|
||||
|
||||
Entity* m_ZoneControlObject = nullptr;
|
||||
|
||||
/**
|
||||
* Scene graph adjacency list: maps each scene ID to a list of scenes it can transition to
|
||||
*/
|
||||
std::map<LWOSCENEID, std::vector<LWOSCENEID>> m_SceneAdjacencyList;
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user