RynthSuite as of 2026-09-05 (internal a5ff5c2)
A snapshot of the working tree for aelrynth.com/git/: the code, build files and public docs. Internal review notes and agent instructions are left out. MIT licensed; see LICENSE. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
0a4b611a90
166 changed files with 186537 additions and 0 deletions
357
Shared/RynthCore.TerrainData/DatDatabase.cs
Normal file
357
Shared/RynthCore.TerrainData/DatDatabase.cs
Normal file
|
|
@ -0,0 +1,357 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi.Raycasting
|
||||
{
|
||||
/// <summary>
|
||||
/// AC .dat file reader — ported directly from ACEmulator's DatLoader.
|
||||
///
|
||||
/// Key format details (from ACE source):
|
||||
/// - Header at file offset 0x140
|
||||
/// - Block chain: FIRST 4 bytes of each block = next block address (byte offset)
|
||||
/// Remaining (BlockSize - 4) bytes = data
|
||||
/// - B-tree node (DatDirectoryHeader): 62 branches, entry count, 61 entries × 24 bytes = 1716 total
|
||||
/// - All pointers (BTree root, chain pointers, file offsets) are byte offsets
|
||||
/// </summary>
|
||||
public class DatDatabase : IDisposable
|
||||
{
|
||||
private FileStream _stream;
|
||||
private readonly object _lock = new object();
|
||||
|
||||
private const uint DAT_HEADER_OFFSET = 0x140;
|
||||
|
||||
// B-tree geometry (from ACE DatDirectoryHeader.cs):
|
||||
// 0x3E (62) branches, 0x3D (61) max entries, each entry = 6 × uint32 = 24 bytes
|
||||
// ObjectSize = (4 * 62) + 4 + (24 * 61) = 248 + 4 + 1464 = 1716
|
||||
private const int BTREE_BRANCH_COUNT = 0x3E; // 62
|
||||
private const int BTREE_MAX_ENTRIES = 0x3D; // 61
|
||||
private const int BTREE_ENTRY_SIZE = 24; // 6 × uint32
|
||||
private const int BTREE_NODE_SIZE = (4 * BTREE_BRANCH_COUNT) + 4 + (BTREE_ENTRY_SIZE * BTREE_MAX_ENTRIES); // 1716
|
||||
|
||||
// Header fields
|
||||
public uint FileType { get; private set; }
|
||||
public uint BlockSize { get; private set; }
|
||||
public uint FileSize { get; private set; }
|
||||
public uint DataSet { get; private set; }
|
||||
public uint BTreeRoot { get; private set; } // Byte offset
|
||||
|
||||
public bool IsLoaded { get; private set; }
|
||||
public string FilePath { get; private set; }
|
||||
public int RecordCount { get; private set; }
|
||||
|
||||
// All files indexed by ObjectId (populated during Open)
|
||||
private readonly Dictionary<uint, DatBTreeEntry> _allFiles = new Dictionary<uint, DatBTreeEntry>();
|
||||
|
||||
public List<string> DiagLog { get; } = new List<string>();
|
||||
|
||||
public bool Open(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!File.Exists(path))
|
||||
{
|
||||
Log($"File not found: {path}");
|
||||
return false;
|
||||
}
|
||||
|
||||
FilePath = path;
|
||||
// Plugin init runs *before* acclient.exe opens its own DAT files,
|
||||
// so our handle is the first one Windows sees on the file. Our
|
||||
// share-mode dictates what AC's subsequent open can request — if
|
||||
// we omit FileShare.Delete, AC's open (which needs delete-rename
|
||||
// semantics for DDD/patcher) fails with a sharing violation and
|
||||
// the AC client errors out with "cannot access the data files."
|
||||
//
|
||||
// FileShare.ReadWrite | FileShare.Delete = permit other openers
|
||||
// to read, write, and delete-mark the file. RandomAccess hint +
|
||||
// 4 KB buffer keeps the .dat B-tree reads efficient.
|
||||
_stream = new FileStream(
|
||||
path,
|
||||
FileMode.Open,
|
||||
FileAccess.Read,
|
||||
FileShare.ReadWrite | FileShare.Delete,
|
||||
bufferSize: 4096,
|
||||
options: FileOptions.RandomAccess);
|
||||
|
||||
Log($"File: {Path.GetFileName(path)}, Size: {_stream.Length:N0} bytes");
|
||||
|
||||
if (!ReadHeader())
|
||||
{
|
||||
Close();
|
||||
return false;
|
||||
}
|
||||
|
||||
// Read the entire B-tree directory and index all files
|
||||
ReadDirectory(BTreeRoot);
|
||||
|
||||
RecordCount = _allFiles.Count;
|
||||
IsLoaded = true;
|
||||
|
||||
Log($"SUCCESS: {RecordCount} files indexed, BlockSize={BlockSize}, Root=0x{BTreeRoot:X8}");
|
||||
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log($"Error: {ex.Message}");
|
||||
Close();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the dat header from offset 0x140.
|
||||
/// Format matches ACE's DatDatabaseHeader.Unpack().
|
||||
/// </summary>
|
||||
private bool ReadHeader()
|
||||
{
|
||||
if (_stream.Length < DAT_HEADER_OFFSET + 64)
|
||||
{
|
||||
Log("File too small");
|
||||
return false;
|
||||
}
|
||||
|
||||
_stream.Seek(DAT_HEADER_OFFSET, SeekOrigin.Begin);
|
||||
using (var reader = new BinaryReader(_stream, System.Text.Encoding.Default, true))
|
||||
{
|
||||
FileType = reader.ReadUInt32();
|
||||
BlockSize = reader.ReadUInt32();
|
||||
FileSize = reader.ReadUInt32();
|
||||
DataSet = reader.ReadUInt32();
|
||||
uint dataSubset = reader.ReadUInt32();
|
||||
|
||||
uint freeHead = reader.ReadUInt32();
|
||||
uint freeTail = reader.ReadUInt32();
|
||||
uint freeCount = reader.ReadUInt32();
|
||||
BTreeRoot = reader.ReadUInt32();
|
||||
}
|
||||
|
||||
Log($"FileType=0x{FileType:X8}, BlockSize={BlockSize}, DataSet={DataSet}, BTree=0x{BTreeRoot:X8}");
|
||||
|
||||
if (BlockSize == 0 || BTreeRoot == 0 || BTreeRoot >= (uint)_stream.Length)
|
||||
{
|
||||
Log("Invalid header values");
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads data from the dat file following the block chain.
|
||||
/// Matches ACE's DatReader.ReadDat() exactly.
|
||||
///
|
||||
/// Block format:
|
||||
/// [4 bytes: next block address] [BlockSize - 4 bytes: data]
|
||||
///
|
||||
/// The FIRST 4 bytes of each block are the chain pointer (next block address).
|
||||
/// If 0, this is the last block.
|
||||
/// </summary>
|
||||
private byte[] ReadDatData(uint offset, int size)
|
||||
{
|
||||
if (offset + BlockSize > (uint)_stream.Length || size <= 0)
|
||||
return null;
|
||||
|
||||
byte[] buffer = new byte[size];
|
||||
|
||||
_stream.Seek(offset, SeekOrigin.Begin);
|
||||
|
||||
// Read first 4 bytes = next block address
|
||||
byte[] addrBuf = new byte[4];
|
||||
_stream.Read(addrBuf, 0, 4);
|
||||
uint nextAddress = BitConverter.ToUInt32(addrBuf, 0);
|
||||
|
||||
int bufferOffset = 0;
|
||||
int remaining = size;
|
||||
|
||||
while (remaining > 0)
|
||||
{
|
||||
if (nextAddress == 0)
|
||||
{
|
||||
// Last block — read remaining data directly
|
||||
int toRead = Math.Min(remaining, (int)(_stream.Length - _stream.Position));
|
||||
if (toRead <= 0) break;
|
||||
_stream.Read(buffer, bufferOffset, toRead);
|
||||
remaining = 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Read data portion of this block (BlockSize - 4 bytes)
|
||||
int dataInBlock = (int)BlockSize - 4;
|
||||
int toRead = Math.Min(dataInBlock, remaining);
|
||||
_stream.Read(buffer, bufferOffset, toRead);
|
||||
bufferOffset += toRead;
|
||||
remaining -= toRead;
|
||||
|
||||
if (remaining > 0)
|
||||
{
|
||||
// Follow chain to next block
|
||||
if (nextAddress >= (uint)_stream.Length) break;
|
||||
_stream.Seek(nextAddress, SeekOrigin.Begin);
|
||||
|
||||
// Read next block's chain pointer
|
||||
_stream.Read(addrBuf, 0, 4);
|
||||
nextAddress = BitConverter.ToUInt32(addrBuf, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return buffer;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Recursively reads the B-tree directory and indexes all files.
|
||||
/// Matches ACE's DatDirectory.Read() + AddFilesToList().
|
||||
/// </summary>
|
||||
private void ReadDirectory(uint sectorOffset)
|
||||
{
|
||||
if (sectorOffset == 0 || sectorOffset >= (uint)_stream.Length)
|
||||
return;
|
||||
|
||||
// Read the directory header (B-tree node)
|
||||
byte[] nodeData;
|
||||
lock (_lock)
|
||||
{
|
||||
nodeData = ReadDatData(sectorOffset, BTREE_NODE_SIZE);
|
||||
}
|
||||
|
||||
if (nodeData == null || nodeData.Length < BTREE_NODE_SIZE)
|
||||
return;
|
||||
|
||||
// Parse branches (62 × uint32)
|
||||
uint[] branches = new uint[BTREE_BRANCH_COUNT];
|
||||
for (int i = 0; i < BTREE_BRANCH_COUNT; i++)
|
||||
branches[i] = BitConverter.ToUInt32(nodeData, i * 4);
|
||||
|
||||
// Parse entry count
|
||||
int countOffset = BTREE_BRANCH_COUNT * 4; // 248
|
||||
uint entryCount = BitConverter.ToUInt32(nodeData, countOffset);
|
||||
|
||||
if (entryCount > BTREE_MAX_ENTRIES)
|
||||
return; // Invalid node
|
||||
|
||||
// Parse entries
|
||||
int entriesOffset = countOffset + 4; // 252
|
||||
var entries = new DatBTreeEntry[entryCount];
|
||||
|
||||
for (int i = 0; i < entryCount; i++)
|
||||
{
|
||||
int eOff = entriesOffset + i * BTREE_ENTRY_SIZE;
|
||||
entries[i] = new DatBTreeEntry
|
||||
{
|
||||
BitFlags = BitConverter.ToUInt32(nodeData, eOff),
|
||||
ObjectId = BitConverter.ToUInt32(nodeData, eOff + 4),
|
||||
FileOffset = BitConverter.ToUInt32(nodeData, eOff + 8),
|
||||
FileSize = BitConverter.ToUInt32(nodeData, eOff + 12)
|
||||
};
|
||||
}
|
||||
|
||||
// Recurse into child directories (if branches[0] != 0, node has children)
|
||||
if (branches[0] != 0)
|
||||
{
|
||||
for (int i = 0; i < entryCount + 1 && i < BTREE_BRANCH_COUNT; i++)
|
||||
{
|
||||
if (branches[i] != 0)
|
||||
ReadDirectory(branches[i]);
|
||||
}
|
||||
}
|
||||
|
||||
// Add entries to the file index
|
||||
for (int i = 0; i < entryCount; i++)
|
||||
{
|
||||
if (entries[i].ObjectId != 0)
|
||||
_allFiles[entries[i].ObjectId] = entries[i];
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Finds a file by ID. O(1) lookup from the pre-built index.
|
||||
/// </summary>
|
||||
public DatBTreeEntry FindFile(uint fileId)
|
||||
{
|
||||
if (!IsLoaded) return null;
|
||||
_allFiles.TryGetValue(fileId, out var entry);
|
||||
return entry;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads file data for a given entry.
|
||||
/// </summary>
|
||||
public byte[] ReadFileData(DatBTreeEntry entry)
|
||||
{
|
||||
if (!IsLoaded || entry == null || entry.FileSize == 0 || _stream == null)
|
||||
return null;
|
||||
|
||||
lock (_lock)
|
||||
{
|
||||
return ReadDatData(entry.FileOffset, (int)entry.FileSize);
|
||||
}
|
||||
}
|
||||
|
||||
public byte[] GetFileData(uint fileId)
|
||||
{
|
||||
var entry = FindFile(fileId);
|
||||
return entry != null ? ReadFileData(entry) : null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns all interior cell IDs (0x0100–0xFFFD) for a given landblock from the dat index.
|
||||
/// This avoids the sequential scan gap cutoff that misses cells in large dungeons.
|
||||
/// </summary>
|
||||
public List<uint> GetLandblockCellIds(uint landblockKey)
|
||||
{
|
||||
var cellIds = new List<uint>();
|
||||
if (!IsLoaded) return cellIds;
|
||||
|
||||
uint prefix = landblockKey << 16;
|
||||
foreach (var id in _allFiles.Keys)
|
||||
{
|
||||
if ((id & 0xFFFF0000) != prefix) continue;
|
||||
uint cell = id & 0xFFFF;
|
||||
if (cell >= 0x0100 && cell <= 0xFFFD)
|
||||
cellIds.Add(id);
|
||||
}
|
||||
return cellIds;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns sample file IDs from the index for diagnostics.
|
||||
/// </summary>
|
||||
public List<uint> GetSampleIds(int maxCount = 20)
|
||||
{
|
||||
var ids = new List<uint>();
|
||||
foreach (var kvp in _allFiles)
|
||||
{
|
||||
ids.Add(kvp.Key);
|
||||
if (ids.Count >= maxCount) break;
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
public void Close()
|
||||
{
|
||||
_stream?.Dispose();
|
||||
_stream = null;
|
||||
IsLoaded = false;
|
||||
_allFiles.Clear();
|
||||
}
|
||||
|
||||
public void Dispose() { Close(); }
|
||||
|
||||
private void Log(string msg)
|
||||
{
|
||||
string line = $"[DatDB] {msg}";
|
||||
System.Diagnostics.Debug.WriteLine(line);
|
||||
if (DiagLog.Count < 100) DiagLog.Add(line);
|
||||
}
|
||||
}
|
||||
|
||||
public class DatBTreeEntry
|
||||
{
|
||||
public uint BitFlags;
|
||||
public uint ObjectId;
|
||||
public uint FileOffset; // Byte offset into file
|
||||
public uint FileSize;
|
||||
}
|
||||
}
|
||||
336
Shared/RynthCore.TerrainData/LandblockData.cs
Normal file
336
Shared/RynthCore.TerrainData/LandblockData.cs
Normal file
|
|
@ -0,0 +1,336 @@
|
|||
using System;
|
||||
using System.IO;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi.Raycasting
|
||||
{
|
||||
/// <summary>
|
||||
/// Parsed CellLandblock (0xXXYYFFFF) — terrain heightmap and terrain-type words for one 192×192 m landblock.
|
||||
///
|
||||
/// File layout (cell.dat 0xXXYYFFFF):
|
||||
/// uint Id (0xXXYYFFFF)
|
||||
/// uint HasObjects (nonzero if matching 0xXXYYFFFE LandblockInfo exists)
|
||||
/// ushort Terrain[81] 9×9 grid, (terrainType << 2 | roadMask) | (sceneType << 11)
|
||||
/// byte Height[81] 9×9 grid, indices into RegionDesc.LandHeightTable
|
||||
///
|
||||
/// Vertex indexing: idx = ix * 9 + iy, where ix = 0..8 (west→east) and iy = 0..8 (south→north).
|
||||
/// </summary>
|
||||
public class LandblockData
|
||||
{
|
||||
public const int VertexDim = 9;
|
||||
public const int BlockSide = 8;
|
||||
public const float CellLength = 24.0f;
|
||||
public const float BlockLength = 192.0f;
|
||||
|
||||
public uint LandblockKey { get; private set; }
|
||||
public bool HasObjects { get; private set; }
|
||||
|
||||
/// <summary>81 terrain words, row-major (ix, iy) via idx = ix*9 + iy.</summary>
|
||||
public ushort[] TerrainWords { get; private set; }
|
||||
|
||||
/// <summary>81 raw height indices (into LandHeightTable).</summary>
|
||||
public byte[] HeightIndices { get; private set; }
|
||||
|
||||
/// <summary>Decoded world-space Z for every vertex. Indexed as HeightsZ[ix, iy].</summary>
|
||||
public float[,] HeightsZ { get; private set; }
|
||||
|
||||
/// <summary>World-space X of vertex (0, 0) — the SW corner of the landblock.</summary>
|
||||
public float WorldOriginX { get; private set; }
|
||||
|
||||
/// <summary>World-space Y of vertex (0, 0) — the SW corner of the landblock.</summary>
|
||||
public float WorldOriginY { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Loads and parses the 0xXXYYFFFF CellLandblock for the given landblock key.
|
||||
/// Returns null if the file is missing, too short, or the height table hasn't been loaded yet.
|
||||
/// </summary>
|
||||
public static LandblockData Load(DatDatabase cellDat, uint landblockKey, float[] landHeightTable)
|
||||
{
|
||||
if (cellDat == null || landHeightTable == null) return null;
|
||||
|
||||
uint cellId = (landblockKey << 16) | 0xFFFF;
|
||||
byte[] data = cellDat.GetFileData(cellId);
|
||||
// 4 (Id) + 4 (HasObjects) + 81*2 (terrain) + 81 (heights) = 251
|
||||
if (data == null || data.Length < 251) return null;
|
||||
|
||||
var terrain = new ushort[81];
|
||||
var heights = new byte[81];
|
||||
bool hasObjects;
|
||||
|
||||
try
|
||||
{
|
||||
using (var ms = new MemoryStream(data))
|
||||
using (var reader = new BinaryReader(ms))
|
||||
{
|
||||
reader.ReadUInt32(); // Id
|
||||
hasObjects = reader.ReadUInt32() != 0; // HasObjects
|
||||
for (int i = 0; i < 81; i++)
|
||||
terrain[i] = reader.ReadUInt16();
|
||||
for (int i = 0; i < 81; i++)
|
||||
heights[i] = reader.ReadByte();
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var heightsZ = new float[VertexDim, VertexDim];
|
||||
for (int ix = 0; ix < VertexDim; ix++)
|
||||
{
|
||||
for (int iy = 0; iy < VertexDim; iy++)
|
||||
{
|
||||
byte h = heights[ix * VertexDim + iy];
|
||||
heightsZ[ix, iy] = h < landHeightTable.Length ? landHeightTable[h] : 0f;
|
||||
}
|
||||
}
|
||||
|
||||
float originX = ((landblockKey >> 8) & 0xFF) * BlockLength;
|
||||
float originY = (landblockKey & 0xFF) * BlockLength;
|
||||
|
||||
return new LandblockData
|
||||
{
|
||||
LandblockKey = landblockKey,
|
||||
HasObjects = hasObjects,
|
||||
TerrainWords = terrain,
|
||||
HeightIndices = heights,
|
||||
HeightsZ = heightsZ,
|
||||
WorldOriginX = originX,
|
||||
WorldOriginY = originY,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Z of the nearest grid vertex for a local position in [0, 192) on each axis.
|
||||
/// Coords outside the landblock are clamped to the edge.
|
||||
/// </summary>
|
||||
public float GetNearestVertexHeightLocal(float lx, float ly)
|
||||
{
|
||||
int ix = (int)Math.Round(lx / CellLength);
|
||||
int iy = (int)Math.Round(ly / CellLength);
|
||||
if (ix < 0) ix = 0; else if (ix > BlockSide) ix = BlockSide;
|
||||
if (iy < 0) iy = 0; else if (iy > BlockSide) iy = BlockSide;
|
||||
return HeightsZ[ix, iy];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Z of the nearest grid vertex at a world-space (X, Y). Returns NaN if (X, Y) is not inside this landblock.
|
||||
/// </summary>
|
||||
public float GetNearestVertexHeightWorld(float worldX, float worldY)
|
||||
{
|
||||
float lx = worldX - WorldOriginX;
|
||||
float ly = worldY - WorldOriginY;
|
||||
if (lx < 0f || ly < 0f || lx >= BlockLength || ly >= BlockLength)
|
||||
return float.NaN;
|
||||
return GetNearestVertexHeightLocal(lx, ly);
|
||||
}
|
||||
|
||||
/// <summary>Min and max decoded vertex Z across the whole landblock.</summary>
|
||||
public void GetHeightRange(out float min, out float max)
|
||||
{
|
||||
min = float.PositiveInfinity;
|
||||
max = float.NegativeInfinity;
|
||||
for (int ix = 0; ix < VertexDim; ix++)
|
||||
{
|
||||
for (int iy = 0; iy < VertexDim; iy++)
|
||||
{
|
||||
float z = HeightsZ[ix, iy];
|
||||
if (z < min) min = z;
|
||||
if (z > max) max = z;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Convenience: vertex Z at integer grid coords (0..8, 0..8).</summary>
|
||||
public float GetVertexZ(int ix, int iy)
|
||||
{
|
||||
if ((uint)ix > BlockSide || (uint)iy > BlockSide) return 0f;
|
||||
return HeightsZ[ix, iy];
|
||||
}
|
||||
|
||||
// ===================================================================
|
||||
// Triangle-exact terrain Z
|
||||
//
|
||||
// Each 24 m cell is split by the SW→NE diagonal into two triangles
|
||||
// (matching the fixed split ScatterSystem uses for passability checks):
|
||||
// SE triangle (below diagonal, fy ≤ fx): SW, SE, NE
|
||||
// NW triangle (above diagonal, fy > fx): SW, NE, NW
|
||||
// AC's client uses a per-cell PRNG to pick between SE/NW and NE/SW diagonals;
|
||||
// we don't hash yet, so expect a few cm of divergence from the client's exact Z
|
||||
// in cells where the PRNG would have picked NE/SW.
|
||||
// ===================================================================
|
||||
|
||||
/// <summary>
|
||||
/// Plane-interpolated Z at a landblock-local (lx, ly) ∈ [0, 192]². Clamps to the interior.
|
||||
/// </summary>
|
||||
public float GetTerrainZLocal(float lx, float ly)
|
||||
{
|
||||
if (lx < 0f) lx = 0f; else if (lx > BlockLength) lx = BlockLength;
|
||||
if (ly < 0f) ly = 0f; else if (ly > BlockLength) ly = BlockLength;
|
||||
|
||||
int cx = (int)(lx / CellLength);
|
||||
int cy = (int)(ly / CellLength);
|
||||
if (cx >= BlockSide) cx = BlockSide - 1;
|
||||
if (cy >= BlockSide) cy = BlockSide - 1;
|
||||
|
||||
float fx = lx - cx * CellLength;
|
||||
float fy = ly - cy * CellLength;
|
||||
float u = fx / CellLength;
|
||||
float v = fy / CellLength;
|
||||
|
||||
float hSW = HeightsZ[cx, cy];
|
||||
float hSE = HeightsZ[cx + 1, cy];
|
||||
float hNW = HeightsZ[cx, cy + 1];
|
||||
float hNE = HeightsZ[cx + 1, cy + 1];
|
||||
|
||||
if (fy <= fx)
|
||||
return hSW + u * (hSE - hSW) + v * (hNE - hSE);
|
||||
return hSW + v * (hNW - hSW) - u * (hNW - hNE);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Plane-interpolated Z at a world (X, Y). NaN if (X, Y) is not in this landblock.
|
||||
/// </summary>
|
||||
public float GetTerrainZWorld(float worldX, float worldY)
|
||||
{
|
||||
float lx = worldX - WorldOriginX;
|
||||
float ly = worldY - WorldOriginY;
|
||||
if (lx < 0f || ly < 0f || lx >= BlockLength || ly >= BlockLength)
|
||||
return float.NaN;
|
||||
return GetTerrainZLocal(lx, ly);
|
||||
}
|
||||
|
||||
// ===================================================================
|
||||
// Landscape raycast (per landblock)
|
||||
// ===================================================================
|
||||
|
||||
/// <summary>
|
||||
/// Ray vs. terrain-mesh test inside this landblock. <paramref name="localOrigin"/> is in
|
||||
/// landblock-local XY (world – <see cref="WorldOriginX"/>/<see cref="WorldOriginY"/>; Z unchanged).
|
||||
/// Walks the 8×8 cell grid via 2D DDA, tests both triangles per cell with Möller-Trumbore.
|
||||
/// Returns the nearest hit within <paramref name="maxDist"/>; <paramref name="hitNormal"/>
|
||||
/// is the unit upward-facing normal of the triangle hit.
|
||||
/// </summary>
|
||||
public bool RaycastTerrainLocal(Vector3 localOrigin, Vector3 dir, float maxDist,
|
||||
out float hitDist, out Vector3 hitNormal)
|
||||
{
|
||||
hitDist = 0f;
|
||||
hitNormal = Vector3.Zero;
|
||||
|
||||
float px = localOrigin.X;
|
||||
float py = localOrigin.Y;
|
||||
float vx = dir.X;
|
||||
float vy = dir.Y;
|
||||
|
||||
int cx = (int)Math.Floor(px / CellLength);
|
||||
int cy = (int)Math.Floor(py / CellLength);
|
||||
if (cx < 0) cx = 0; else if (cx > BlockSide - 1) cx = BlockSide - 1;
|
||||
if (cy < 0) cy = 0; else if (cy > BlockSide - 1) cy = BlockSide - 1;
|
||||
|
||||
int stepX = vx > 0 ? 1 : (vx < 0 ? -1 : 0);
|
||||
int stepY = vy > 0 ? 1 : (vy < 0 ? -1 : 0);
|
||||
|
||||
float tMaxX = float.PositiveInfinity, tDeltaX = float.PositiveInfinity;
|
||||
float tMaxY = float.PositiveInfinity, tDeltaY = float.PositiveInfinity;
|
||||
if (stepX != 0)
|
||||
{
|
||||
float nextX = (stepX > 0 ? (cx + 1) : cx) * CellLength;
|
||||
tMaxX = (nextX - px) / vx;
|
||||
tDeltaX = CellLength / Math.Abs(vx);
|
||||
}
|
||||
if (stepY != 0)
|
||||
{
|
||||
float nextY = (stepY > 0 ? (cy + 1) : cy) * CellLength;
|
||||
tMaxY = (nextY - py) / vy;
|
||||
tDeltaY = CellLength / Math.Abs(vy);
|
||||
}
|
||||
|
||||
float bestT = maxDist;
|
||||
Vector3 bestNormal = Vector3.Zero;
|
||||
bool found = false;
|
||||
|
||||
// Enough steps to traverse the block diagonally plus a small safety margin.
|
||||
int iterLimit = BlockSide * 2 + 4;
|
||||
|
||||
while (iterLimit-- > 0)
|
||||
{
|
||||
if (cx < 0 || cy < 0 || cx >= BlockSide || cy >= BlockSide)
|
||||
break;
|
||||
|
||||
float x0 = cx * CellLength, x1 = x0 + CellLength;
|
||||
float y0 = cy * CellLength, y1 = y0 + CellLength;
|
||||
Vector3 vSW = new Vector3(x0, y0, HeightsZ[cx, cy]);
|
||||
Vector3 vSE = new Vector3(x1, y0, HeightsZ[cx + 1, cy]);
|
||||
Vector3 vNE = new Vector3(x1, y1, HeightsZ[cx + 1, cy + 1]);
|
||||
Vector3 vNW = new Vector3(x0, y1, HeightsZ[cx, cy + 1]);
|
||||
|
||||
if (RayTriangle(localOrigin, dir, vSW, vSE, vNE, out float tSE) && tSE < bestT)
|
||||
{
|
||||
bestT = tSE;
|
||||
bestNormal = TriangleUpNormal(vSW, vSE, vNE);
|
||||
found = true;
|
||||
}
|
||||
if (RayTriangle(localOrigin, dir, vSW, vNE, vNW, out float tNW) && tNW < bestT)
|
||||
{
|
||||
bestT = tNW;
|
||||
bestNormal = TriangleUpNormal(vSW, vNE, vNW);
|
||||
found = true;
|
||||
}
|
||||
|
||||
float tNext = Math.Min(tMaxX, tMaxY);
|
||||
// If we already have a closer hit than the nearest cell boundary, we're done.
|
||||
if (found && tNext >= bestT) break;
|
||||
if (tNext > maxDist) break;
|
||||
if (stepX == 0 && stepY == 0) break; // vertical ray: single-cell only
|
||||
|
||||
if (tMaxX < tMaxY)
|
||||
{
|
||||
tMaxX += tDeltaX;
|
||||
cx += stepX;
|
||||
}
|
||||
else
|
||||
{
|
||||
tMaxY += tDeltaY;
|
||||
cy += stepY;
|
||||
}
|
||||
}
|
||||
|
||||
if (found)
|
||||
{
|
||||
hitDist = bestT;
|
||||
hitNormal = bestNormal;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Möller-Trumbore. Local copy to keep LandblockData self-contained
|
||||
// (BoundingVolume has the same routine privately).
|
||||
private static bool RayTriangle(Vector3 origin, Vector3 dir,
|
||||
Vector3 v0, Vector3 v1, Vector3 v2, out float t)
|
||||
{
|
||||
t = 0f;
|
||||
const float EPSILON = 1e-7f;
|
||||
Vector3 edge1 = v1 - v0;
|
||||
Vector3 edge2 = v2 - v0;
|
||||
Vector3 h = Vector3.Cross(dir, edge2);
|
||||
float a = Vector3.Dot(edge1, h);
|
||||
if (a > -EPSILON && a < EPSILON) return false;
|
||||
float f = 1f / a;
|
||||
Vector3 s = origin - v0;
|
||||
float u = f * Vector3.Dot(s, h);
|
||||
if (u < 0f || u > 1f) return false;
|
||||
Vector3 q = Vector3.Cross(s, edge1);
|
||||
float v = f * Vector3.Dot(dir, q);
|
||||
if (v < 0f || u + v > 1f) return false;
|
||||
t = f * Vector3.Dot(edge2, q);
|
||||
return t >= 0f;
|
||||
}
|
||||
|
||||
private static Vector3 TriangleUpNormal(Vector3 a, Vector3 b, Vector3 c)
|
||||
{
|
||||
// Winding is chosen so this points up (+Z) — see LandblockData docs.
|
||||
Vector3 n = Vector3.Cross(b - a, c - a);
|
||||
return n.Normalize();
|
||||
}
|
||||
}
|
||||
}
|
||||
11
Shared/RynthCore.TerrainData/RynthCore.TerrainData.csproj
Normal file
11
Shared/RynthCore.TerrainData/RynthCore.TerrainData.csproj
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
<RootNamespace>RynthCore.TerrainData</RootNamespace>
|
||||
<AssemblyName>RynthCore.TerrainData</AssemblyName>
|
||||
</PropertyGroup>
|
||||
|
||||
</Project>
|
||||
273
Shared/RynthCore.TerrainData/TerrainSampler.cs
Normal file
273
Shared/RynthCore.TerrainData/TerrainSampler.cs
Normal file
|
|
@ -0,0 +1,273 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using RynthCore.Plugin.RynthAi.Raycasting;
|
||||
|
||||
namespace RynthCore.TerrainData;
|
||||
|
||||
/// <summary>
|
||||
/// Self-contained terrain-data provider for AC landblocks: opens the client's
|
||||
/// portal/cell .dat files, parses the 256-entry land-height table from RegionDesc,
|
||||
/// and exposes per-landblock heights, slope passability, and terrain-type/water
|
||||
/// lookups. Reuses the shared DatDatabase/LandblockData parsers; the slope math
|
||||
/// and height-table prefix parse are reimplemented here so this carries no
|
||||
/// dependency on RynthAi's raycasting engine.
|
||||
/// </summary>
|
||||
public sealed class TerrainSampler : IDisposable
|
||||
{
|
||||
// AC's actual walkable threshold from ACE PhysicsGlobals.FloorZ — anything
|
||||
// with normal.Z below this value is blocked by is_valid_walkable. The visual
|
||||
// overlay must match the game's blocker, not a tuned-for-scatter looser
|
||||
// value, or moderate slopes the game blocks render as walkable.
|
||||
// (RynthAi's ScatterSystem.FloorZ is intentionally looser to suppress
|
||||
// gentle-slope false positives on vegetation placement and is unrelated.)
|
||||
public const float FloorZ = 0.66417414618662751f;
|
||||
|
||||
private const float CellLength = 24.0f;
|
||||
|
||||
private readonly DatDatabase _portalDat = new();
|
||||
private readonly DatDatabase _cellDat = new();
|
||||
private float[]? _landHeightTable;
|
||||
private bool _ready;
|
||||
|
||||
// Deep-audit finding #6 (2026-06-18): RynthVision's /rv watertypes ->
|
||||
// InspectTerrain runs synchronously on the Avalonia UI thread and calls
|
||||
// LoadLandblock, while the same call hits from the AC tick thread hundreds
|
||||
// of times per Submit via the slope/water overlays. Two threads mutating
|
||||
// one plain Dictionary (with a periodic Clear() at MaxCache=30) is classic
|
||||
// bucket-array corruption on whichever thread lands on it — frequently
|
||||
// AC's own main thread. Guard every access with this gate.
|
||||
private readonly object _cacheGate = new();
|
||||
private readonly Dictionary<uint, LandblockData?> _cache = new();
|
||||
private const int MaxCache = 30;
|
||||
|
||||
public bool IsReady => _ready;
|
||||
public string Status { get; private set; } = "uninitialized";
|
||||
|
||||
/// <summary>
|
||||
/// Opens the AC .dat files and loads the land-height table. Idempotent. When
|
||||
/// acFolderPath is null, uses the running process's directory — inside an
|
||||
/// injected plugin that's acclient.exe's folder, where the active client's
|
||||
/// .dat files live.
|
||||
/// </summary>
|
||||
public bool Initialize(string? acFolderPath = null)
|
||||
{
|
||||
if (_ready) return true;
|
||||
try
|
||||
{
|
||||
string? folder = acFolderPath;
|
||||
if (string.IsNullOrEmpty(folder))
|
||||
{
|
||||
string? exe = Environment.ProcessPath;
|
||||
folder = string.IsNullOrEmpty(exe) ? null : Path.GetDirectoryName(exe);
|
||||
}
|
||||
if (string.IsNullOrEmpty(folder) || !Directory.Exists(folder))
|
||||
{
|
||||
Status = $"AC folder not found ({folder ?? "null"})";
|
||||
return false;
|
||||
}
|
||||
|
||||
string? portalPath = FindDat(folder, "client_portal.dat", "portal.dat");
|
||||
string? cellPath = FindDat(folder, "client_cell_1.dat", "cell.dat");
|
||||
if (portalPath == null || cellPath == null)
|
||||
{
|
||||
Status = $"portal/cell .dat not found in {folder}";
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!_portalDat.Open(portalPath) || !_cellDat.Open(cellPath))
|
||||
{
|
||||
Status = "failed to open .dat files";
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!LoadLandHeightTable())
|
||||
{
|
||||
Status = "RegionDesc land-height table parse failed";
|
||||
return false;
|
||||
}
|
||||
|
||||
_ready = true;
|
||||
Status = "ready";
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Status = ex.Message;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Parsed landblock (heights + terrain words), cached. Null if unavailable.</summary>
|
||||
public LandblockData? LoadLandblock(uint landblockKey)
|
||||
{
|
||||
if (!_ready || _landHeightTable == null) return null;
|
||||
lock (_cacheGate)
|
||||
{
|
||||
if (_cache.TryGetValue(landblockKey, out var cached)) return cached;
|
||||
}
|
||||
|
||||
LandblockData? data = LandblockData.Load(_cellDat, landblockKey, _landHeightTable);
|
||||
lock (_cacheGate)
|
||||
{
|
||||
if (_cache.Count >= MaxCache) _cache.Clear();
|
||||
_cache[landblockKey] = data;
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// AC's per-cell diagonal-split PRNG (ACE LandblockStruct.ConstructPolygons /
|
||||
/// FSplitNESW). When true the cell is cut SW→NE (triangles SW-SE-NE and
|
||||
/// SW-NE-NW); when false it's cut SE→NW (triangles SW-SE-NW and SE-NE-NW).
|
||||
/// Roughly 50/50 across cells. Slope and Z-interpolation queries must agree
|
||||
/// with this or they describe the wrong triangle pair.
|
||||
///
|
||||
/// The PRNG inputs are the cell's *vertex-grid* coordinates (landblock
|
||||
/// index × 8 + cell index within landblock), NOT raw landblock indices —
|
||||
/// this matches ACE's <c>blockid_to_lcoord</c>, which shifts the byte
|
||||
/// landblock index left by <c>LandblockShift</c> (= 3, i.e. ×8) before
|
||||
/// feeding it to the seed multiplications. Getting this wrong gives the
|
||||
/// wrong diagonal on most cells and paints the wrong triangle half.
|
||||
/// </summary>
|
||||
public static bool SwToNeCut(uint landblockKey, int cellX, int cellY)
|
||||
{
|
||||
int lbX = (int)((landblockKey >> 8) & 0xFF);
|
||||
int lbY = (int)(landblockKey & 0xFF);
|
||||
int vertexX = (lbX << 3) + cellX; // lbX * 8 + cellX (ACE LandblockShift = 3)
|
||||
int vertexY = (lbY << 3) + cellY;
|
||||
unchecked
|
||||
{
|
||||
uint seedA = (uint)vertexX * 214614067u;
|
||||
uint seedB = (uint)vertexX * 1109124029u;
|
||||
uint magicA = seedA + 1813693831u;
|
||||
uint magicB = seedB;
|
||||
uint splitDir = (uint)vertexY * magicA - magicB - 1369149221u;
|
||||
return (splitDir & 0x80000000u) != 0;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Per-triangle walkability for cell (cx,cy) in landblock <paramref name="lb"/>.
|
||||
/// The tri1/tri2 identity depends on <paramref name="swToNeCut"/>:
|
||||
/// swToNeCut=true → tri1 = SE half (SW,SE,NE); tri2 = NW half (SW,NE,NW)
|
||||
/// swToNeCut=false → tri1 = SW half (SW,SE,NW); tri2 = NE half (SE,NE,NW)
|
||||
/// <paramref name="floorZ"/> overrides the default walkable-normal threshold
|
||||
/// (defaults to <see cref="FloorZ"/>); the visual overlay exposes it as a
|
||||
/// slider so the user can match what AC actually blocks in their environment.
|
||||
/// </summary>
|
||||
public static void GetTrianglePassability(LandblockData lb, int cx, int cy, bool swToNeCut,
|
||||
out bool tri1Passable, out bool tri2Passable, float floorZ = FloorZ)
|
||||
{
|
||||
float h00 = lb.GetVertexZ(cx, cy);
|
||||
float h10 = lb.GetVertexZ(cx + 1, cy);
|
||||
float h01 = lb.GetVertexZ(cx, cy + 1);
|
||||
float h11 = lb.GetVertexZ(cx + 1, cy + 1);
|
||||
|
||||
float nzSquare = CellLength * CellLength;
|
||||
|
||||
float n1x, n1y, n2x, n2y;
|
||||
if (swToNeCut)
|
||||
{
|
||||
// tri1 (SE): SW(0,0,h00), SE(24,0,h10), NE(24,24,h11)
|
||||
n1x = -CellLength * (h10 - h00);
|
||||
n1y = -CellLength * (h11 - h10);
|
||||
// tri2 (NW): SW(0,0,h00), NE(24,24,h11), NW(0,24,h01)
|
||||
n2x = -CellLength * (h11 - h01);
|
||||
n2y = -CellLength * (h01 - h00);
|
||||
}
|
||||
else
|
||||
{
|
||||
// tri1 (SW): SW(0,0,h00), SE(24,0,h10), NW(0,24,h01)
|
||||
n1x = -CellLength * (h10 - h00);
|
||||
n1y = -CellLength * (h01 - h00);
|
||||
// tri2 (NE): SE(24,0,h10), NE(24,24,h11), NW(0,24,h01)
|
||||
n2x = -CellLength * (h11 - h01);
|
||||
n2y = -CellLength * (h11 - h10);
|
||||
}
|
||||
|
||||
float z1 = nzSquare / (float)Math.Sqrt(n1x * n1x + n1y * n1y + nzSquare * nzSquare);
|
||||
float z2 = nzSquare / (float)Math.Sqrt(n2x * n2x + n2y * n2y + nzSquare * nzSquare);
|
||||
tri1Passable = z1 >= floorZ;
|
||||
tri2Passable = z2 >= floorZ;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Convenience overload that looks up the cell's split direction itself.
|
||||
/// </summary>
|
||||
public static void GetTrianglePassability(LandblockData lb, int cx, int cy,
|
||||
out bool tri1Passable, out bool tri2Passable)
|
||||
=> GetTrianglePassability(lb, cx, cy, SwToNeCut(lb.LandblockKey, cx, cy),
|
||||
out tri1Passable, out tri2Passable);
|
||||
|
||||
/// <summary>
|
||||
/// AC terrain-type index (0–31) at vertex (ix,iy), 0–8. Decoded from the
|
||||
/// CellLandblock terrain word: bits 0–1 road, 2–10 terrain type, 11+ scene.
|
||||
/// Returns -1 if unavailable.
|
||||
/// </summary>
|
||||
public static int GetTerrainType(LandblockData lb, int ix, int iy)
|
||||
{
|
||||
var words = lb.TerrainWords;
|
||||
if (words == null) return -1;
|
||||
int idx = ix * 9 + iy;
|
||||
if ((uint)idx >= 81) return -1;
|
||||
return (words[idx] >> 2) & 0x1F;
|
||||
}
|
||||
|
||||
private static string? FindDat(string folder, params string[] names)
|
||||
{
|
||||
foreach (var n in names)
|
||||
{
|
||||
string p = Path.Combine(folder, n);
|
||||
if (File.Exists(p)) return p;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private bool LoadLandHeightTable()
|
||||
{
|
||||
byte[]? data = _portalDat.GetFileData(0x13000000);
|
||||
// 12 (header) + >=2 (PString) + 32 (LandDefs prefix) + 256*4 (table)
|
||||
if (data == null || data.Length < 12 + 2 + 32 + 256 * 4) return false;
|
||||
|
||||
using var ms = new MemoryStream(data);
|
||||
using var r = new BinaryReader(ms);
|
||||
|
||||
r.ReadUInt32(); // id 0x13000000
|
||||
r.ReadUInt32(); // regionNumber
|
||||
r.ReadUInt32(); // version
|
||||
SkipPString(r, ms); // RegionName
|
||||
|
||||
// LandDefs prefix (8 scalar fields) precedes the height table.
|
||||
r.ReadInt32(); // NumBlockLength
|
||||
r.ReadInt32(); // NumBlockWidth
|
||||
r.ReadSingle(); // SquareLength
|
||||
r.ReadInt32(); // LBlockLength
|
||||
r.ReadInt32(); // VertexPerCell
|
||||
r.ReadSingle(); // MaxObjHeight
|
||||
r.ReadSingle(); // SkyHeight
|
||||
r.ReadSingle(); // RoadWidth
|
||||
|
||||
var table = new float[256];
|
||||
for (int i = 0; i < 256; i++) table[i] = r.ReadSingle();
|
||||
_landHeightTable = table;
|
||||
return true;
|
||||
}
|
||||
|
||||
// PString: ushort length, that many bytes, padded to a 4-byte boundary.
|
||||
private static void SkipPString(BinaryReader reader, MemoryStream ms)
|
||||
{
|
||||
ushort len = reader.ReadUInt16();
|
||||
if (len > 0 && ms.Position + len <= ms.Length)
|
||||
ms.Seek(len, SeekOrigin.Current);
|
||||
long aligned = (ms.Position + 3) & ~3L;
|
||||
if (aligned <= ms.Length) ms.Position = aligned;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_portalDat.Dispose();
|
||||
_cellDat.Dispose();
|
||||
_ready = false;
|
||||
}
|
||||
}
|
||||
143
Shared/RynthCore.TerrainData/Vector3Helper.cs
Normal file
143
Shared/RynthCore.TerrainData/Vector3Helper.cs
Normal file
|
|
@ -0,0 +1,143 @@
|
|||
using System;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi.Raycasting
|
||||
{
|
||||
/// <summary>
|
||||
/// Custom Vector3 for the raycasting system.
|
||||
///
|
||||
/// IMPORTANT: This replaces System.Numerics.Vector3 in the Raycasting namespace.
|
||||
/// All Raycasting/*.cs files must NOT import System.Numerics to avoid type conflicts.
|
||||
/// </summary>
|
||||
public struct Vector3
|
||||
{
|
||||
public float X { get; set; }
|
||||
public float Y { get; set; }
|
||||
public float Z { get; set; }
|
||||
|
||||
public static readonly Vector3 Zero = new Vector3(0, 0, 0);
|
||||
public static readonly Vector3 One = new Vector3(1, 1, 1);
|
||||
public static readonly Vector3 Up = new Vector3(0, 0, 1);
|
||||
|
||||
public Vector3(float x, float y, float z)
|
||||
{
|
||||
X = x;
|
||||
Y = y;
|
||||
Z = z;
|
||||
}
|
||||
|
||||
// --- Conversion ---
|
||||
|
||||
public static Vector3 FromNumerics(System.Numerics.Vector3 v)
|
||||
=> new Vector3(v.X, v.Y, v.Z);
|
||||
|
||||
public System.Numerics.Vector3 ToNumerics()
|
||||
=> new System.Numerics.Vector3(X, Y, Z);
|
||||
|
||||
public float[] ToArray()
|
||||
=> new float[] { X, Y, Z };
|
||||
|
||||
public static Vector3 FromArray(float[] arr)
|
||||
{
|
||||
if (arr == null || arr.Length < 3) return Zero;
|
||||
return new Vector3(arr[0], arr[1], arr[2]);
|
||||
}
|
||||
|
||||
// --- Arithmetic operators ---
|
||||
|
||||
public static Vector3 operator +(Vector3 a, Vector3 b)
|
||||
=> new Vector3(a.X + b.X, a.Y + b.Y, a.Z + b.Z);
|
||||
|
||||
public static Vector3 operator -(Vector3 a, Vector3 b)
|
||||
=> new Vector3(a.X - b.X, a.Y - b.Y, a.Z - b.Z);
|
||||
|
||||
public static Vector3 operator -(Vector3 v)
|
||||
=> new Vector3(-v.X, -v.Y, -v.Z);
|
||||
|
||||
public static Vector3 operator *(Vector3 v, float s)
|
||||
=> new Vector3(v.X * s, v.Y * s, v.Z * s);
|
||||
|
||||
public static Vector3 operator *(float s, Vector3 v)
|
||||
=> new Vector3(v.X * s, v.Y * s, v.Z * s);
|
||||
|
||||
public static Vector3 operator /(Vector3 v, float s)
|
||||
{
|
||||
float inv = 1.0f / s;
|
||||
return new Vector3(v.X * inv, v.Y * inv, v.Z * inv);
|
||||
}
|
||||
|
||||
// --- Vector math ---
|
||||
|
||||
public static float Dot(Vector3 a, Vector3 b)
|
||||
=> a.X * b.X + a.Y * b.Y + a.Z * b.Z;
|
||||
|
||||
public static Vector3 Cross(Vector3 a, Vector3 b)
|
||||
=> new Vector3(
|
||||
a.Y * b.Z - a.Z * b.Y,
|
||||
a.Z * b.X - a.X * b.Z,
|
||||
a.X * b.Y - a.Y * b.X
|
||||
);
|
||||
|
||||
public float Length()
|
||||
=> (float)Math.Sqrt(X * X + Y * Y + Z * Z);
|
||||
|
||||
public float LengthSquared()
|
||||
=> X * X + Y * Y + Z * Z;
|
||||
|
||||
public Vector3 Normalize()
|
||||
{
|
||||
float len = Length();
|
||||
if (len < 1e-8f) return Zero;
|
||||
return this * (1.0f / len);
|
||||
}
|
||||
|
||||
public float Distance(Vector3 other)
|
||||
=> (this - other).Length();
|
||||
|
||||
public static Vector3 Min(Vector3 a, Vector3 b)
|
||||
=> new Vector3(Math.Min(a.X, b.X), Math.Min(a.Y, b.Y), Math.Min(a.Z, b.Z));
|
||||
|
||||
public static Vector3 Max(Vector3 a, Vector3 b)
|
||||
=> new Vector3(Math.Max(a.X, b.X), Math.Max(a.Y, b.Y), Math.Max(a.Z, b.Z));
|
||||
|
||||
public static Vector3 Lerp(Vector3 a, Vector3 b, float t)
|
||||
=> a + (b - a) * t;
|
||||
|
||||
public float Length2D()
|
||||
=> (float)Math.Sqrt(X * X + Y * Y);
|
||||
|
||||
// --- Equality ---
|
||||
|
||||
public override bool Equals(object obj)
|
||||
{
|
||||
if (obj is Vector3 other)
|
||||
return X == other.X && Y == other.Y && Z == other.Z;
|
||||
return false;
|
||||
}
|
||||
|
||||
public override int GetHashCode()
|
||||
=> X.GetHashCode() ^ (Y.GetHashCode() << 8) ^ (Z.GetHashCode() << 16);
|
||||
|
||||
public static bool operator ==(Vector3 a, Vector3 b)
|
||||
=> a.X == b.X && a.Y == b.Y && a.Z == b.Z;
|
||||
|
||||
public static bool operator !=(Vector3 a, Vector3 b)
|
||||
=> !(a == b);
|
||||
|
||||
public override string ToString()
|
||||
=> $"({X:F3}, {Y:F3}, {Z:F3})";
|
||||
|
||||
public float this[int i]
|
||||
{
|
||||
get
|
||||
{
|
||||
switch (i)
|
||||
{
|
||||
case 0: return X;
|
||||
case 1: return Y;
|
||||
case 2: return Z;
|
||||
default: throw new IndexOutOfRangeException();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue