Initial commit

A modern .NET 9 NativeAOT framework for Asheron's Call client modding.
Self-contained injection system that hooks D3D9 EndScene to render an
ImGui overlay inside the AC client process.
This commit is contained in:
tombohar 2026-04-10 18:38:07 -04:00
commit 80b71d295d
179 changed files with 52858 additions and 0 deletions

View file

@ -0,0 +1,143 @@
using System;
using System.Collections.Generic;
namespace NexSuite.Plugins.RynthAi.Raycasting
{
public class BlacklistManager
{
/// <summary>
/// Tracks consecutive failures for specific WorldObjects.
/// Incremented when an attack on a target produces no server feedback.
/// </summary>
private readonly Dictionary<int, int> _failureCounts = new Dictionary<int, int>();
/// <summary>
/// Tracks the expiration time for blacklisted targets.
/// Targets are temporarily ignored if they're stuck in walls or ghosts.
/// </summary>
private readonly Dictionary<int, DateTime> _blacklistExpirations = new Dictionary<int, DateTime>();
/// <summary>
/// Number of consecutive attack failures before a target is blacklisted.
/// Default: 3 attempts (adjustable for different difficulty settings).
/// </summary>
public int AttemptThreshold { get; set; } = 3;
/// <summary>
/// Duration in seconds that a target remains blacklisted after threshold is breached.
/// Default: 30 seconds (allows time for stuck/ghost detection to resolve).
/// </summary>
public int TimeoutSeconds { get; set; } = 30;
/// <summary>
/// Increments the failure count for a target.
/// Call this if an attack is launched but yields no server feedback (damage, XP, etc.).
/// If the failure count reaches the threshold, the target is automatically blacklisted.
/// </summary>
public void ReportFailure(int targetId)
{
if (!_failureCounts.ContainsKey(targetId))
_failureCounts[targetId] = 0;
_failureCounts[targetId]++;
// Log the failure for debugging
System.Diagnostics.Debug.WriteLine($"Target {targetId} failure count: {_failureCounts[targetId]}/{AttemptThreshold}");
// If the threshold is breached, blacklist the target
if (_failureCounts[targetId] >= AttemptThreshold)
{
BlacklistTarget(targetId);
}
}
/// <summary>
/// Immediately blacklists a target for the configured timeout duration.
/// </summary>
private void BlacklistTarget(int targetId)
{
DateTime expirationTime = DateTime.Now.AddSeconds(TimeoutSeconds);
_blacklistExpirations[targetId] = expirationTime;
System.Diagnostics.Debug.WriteLine($"Target {targetId} blacklisted until {expirationTime:HH:mm:ss}");
}
/// <summary>
/// Checks if a target should be ignored by the targeting system.
/// Returns true if the target is currently blacklisted (timeout not expired).
/// Returns false if the target is not blacklisted or if its timeout has expired.
/// </summary>
public bool IsBlacklisted(int targetId)
{
if (!_blacklistExpirations.TryGetValue(targetId, out var expiration))
return false; // Target not in blacklist
// Check if blacklist timeout has expired
if (DateTime.Now >= expiration)
{
// Timeout expired - remove from blacklist and allow re-evaluation
_blacklistExpirations.Remove(targetId);
_failureCounts.Remove(targetId);
System.Diagnostics.Debug.WriteLine($"Target {targetId} blacklist expired, re-evaluating");
return false;
}
// Target still blacklisted
return true;
}
/// <summary>
/// Clears the failure count and blacklist status for a target.
/// Call this when a target successfully takes damage or shows other server feedback.
/// This allows the target to be re-engaged if it becomes blocked again later.
/// </summary>
public void ClearFailure(int targetId)
{
_failureCounts.Remove(targetId);
_blacklistExpirations.Remove(targetId);
System.Diagnostics.Debug.WriteLine($"Target {targetId} failure cleared");
}
/// <summary>
/// Completely clears all blacklist and failure tracking data.
/// Useful when transitioning between combat zones or resetting the bot state.
/// </summary>
public void ClearAll()
{
_failureCounts.Clear();
_blacklistExpirations.Clear();
System.Diagnostics.Debug.WriteLine("All blacklist data cleared");
}
/// <summary>
/// Returns the number of currently blacklisted targets.
/// Useful for debugging and monitoring bot behavior.
/// </summary>
public int GetBlacklistCount()
{
int count = 0;
var expiredKeys = new List<int>();
foreach (var kvp in _blacklistExpirations)
{
if (DateTime.Now < kvp.Value)
{
count++;
}
else
{
expiredKeys.Add(kvp.Key);
}
}
// Clean up expired entries while we're here
foreach (var key in expiredKeys)
{
_blacklistExpirations.Remove(key);
_failureCounts.Remove(key);
}
return count;
}
}
}

View file

@ -0,0 +1,245 @@
using System;
namespace NexSuite.Plugins.RynthAi.Raycasting
{
/// <summary>
/// Bounding volume for collision detection
/// Supports ray-volume intersection testing for raycasting
/// </summary>
public class BoundingVolume
{
public enum VolumeType
{
Sphere = 1,
Cylinder = 2,
Ellipsoid = 3,
Polygon = 4,
AxisAlignedBox = 5,
Torus = 6
}
public VolumeType Type { get; set; }
public Vector3 Center { get; set; } // X, Y, Z
public Vector3 Dimensions { get; set; } // Radius, Height, etc
public Vector3[] Vertices { get; set; } // For polygons
// Additional properties for geometry loading
public Vector3 Min { get; set; } // Minimum bounds
public Vector3 Max { get; set; } // Maximum bounds
public bool IsDoor { get; set; } // Whether this is a door (passable)
public BoundingVolume()
{
Center = new Vector3(0, 0, 0);
Dimensions = new Vector3(0, 0, 0);
Min = new Vector3(0, 0, 0);
Max = new Vector3(0, 0, 0);
IsDoor = false;
}
/// <summary>
/// Test if a ray intersects this volume
/// Returns true if collision detected
/// </summary>
public bool RayIntersect(Vector3 rayStart, Vector3 rayDir, float maxDist, out float hitDist)
{
hitDist = float.MaxValue;
try
{
switch (Type)
{
case VolumeType.Sphere:
return RayIntersectSphere(rayStart, rayDir, maxDist, out hitDist);
case VolumeType.Cylinder:
return RayIntersectCylinder(rayStart, rayDir, maxDist, out hitDist);
case VolumeType.AxisAlignedBox:
return RayIntersectAABB(rayStart, rayDir, maxDist, out hitDist);
case VolumeType.Polygon:
return RayIntersectPolygon(rayStart, rayDir, maxDist, out hitDist);
default:
return false;
}
}
catch
{
return false;
}
}
/// <summary>
/// Overload to accept float arrays for backwards compatibility
/// </summary>
public bool RayIntersect(float[] rayStart, float[] rayDir, float maxDist, out float hitDist)
{
return RayIntersect(
Vector3.FromArray(rayStart),
Vector3.FromArray(rayDir),
maxDist,
out hitDist
);
}
/// <summary>
/// Ray-Sphere intersection
/// </summary>
private bool RayIntersectSphere(Vector3 rayStart, Vector3 rayDir, float maxDist, out float hitDist)
{
hitDist = float.MaxValue;
Vector3 oc = rayStart - Center;
float a = Vector3.Dot(rayDir, rayDir);
float b = 2.0f * Vector3.Dot(oc, rayDir);
float c = Vector3.Dot(oc, oc) - (Dimensions.X * Dimensions.X);
float discriminant = b * b - 4 * a * c;
if (discriminant < 0)
return false;
float sqrt_disc = (float)Math.Sqrt(discriminant);
float t1 = (-b - sqrt_disc) / (2 * a);
float t2 = (-b + sqrt_disc) / (2 * a);
if (t1 > 0 && t1 < maxDist)
{
hitDist = t1;
return true;
}
// Ray starts inside sphere (t1 < 0, t2 > 0)
if (t1 <= 0 && t2 > 0 && t2 < maxDist)
{
hitDist = 0;
return true;
}
return false;
}
/// <summary>
/// Ray-Cylinder intersection
/// </summary>
private bool RayIntersectCylinder(Vector3 rayStart, Vector3 rayDir, float maxDist, out float hitDist)
{
hitDist = float.MaxValue;
return false;
}
/// <summary>
/// Ray-AABB intersection
/// </summary>
private bool RayIntersectAABB(Vector3 rayStart, Vector3 rayDir, float maxDist, out float hitDist)
{
hitDist = float.MaxValue;
float tmin = 0, tmax = maxDist;
for (int i = 0; i < 3; i++)
{
float rayStartCoord = i == 0 ? rayStart.X : (i == 1 ? rayStart.Y : rayStart.Z);
float rayDirCoord = i == 0 ? rayDir.X : (i == 1 ? rayDir.Y : rayDir.Z);
float minCoord = i == 0 ? Min.X : (i == 1 ? Min.Y : Min.Z);
float maxCoord = i == 0 ? Max.X : (i == 1 ? Max.Y : Max.Z);
if (Math.Abs(rayDirCoord) < 0.00001f)
{
if (rayStartCoord < minCoord || rayStartCoord > maxCoord)
return false;
}
else
{
float t1 = (minCoord - rayStartCoord) / rayDirCoord;
float t2 = (maxCoord - rayStartCoord) / rayDirCoord;
if (t1 > t2)
{
float temp = t1;
t1 = t2;
t2 = temp;
}
tmin = Math.Max(tmin, t1);
tmax = Math.Min(tmax, t2);
if (tmin > tmax)
return false;
}
}
if (tmin > 0 && tmin < maxDist)
{
hitDist = tmin;
return true;
}
// Ray starts inside the box (tmin <= 0 but tmax > 0)
// This means the player is inside/overlapping the obstacle
if (tmin <= 0 && tmax > 0 && tmax < maxDist)
{
hitDist = 0;
return true;
}
return false;
}
/// <summary>
/// Ray-Polygon intersection
/// </summary>
private bool RayIntersectPolygon(Vector3 rayStart, Vector3 rayDir, float maxDist, out float hitDist)
{
hitDist = float.MaxValue;
if (Vertices == null || Vertices.Length < 3)
return false;
for (int i = 0; i < Vertices.Length - 2; i++)
{
if (RayIntersectTriangle(rayStart, rayDir, Vertices[0], Vertices[i + 1], Vertices[i + 2], out float t))
{
if (t >= 0 && t < maxDist && t < hitDist)
{
hitDist = t;
return true;
}
}
}
return false;
}
/// <summary>
/// Ray-Triangle intersection (Möller-Trumbore algorithm)
/// </summary>
private bool RayIntersectTriangle(Vector3 rayStart, Vector3 rayDir, Vector3 v0, Vector3 v1, Vector3 v2, out float t)
{
t = float.MaxValue;
const float EPSILON = 0.0000001f;
Vector3 edge1 = v1 - v0;
Vector3 edge2 = v2 - v0;
Vector3 h = Vector3.Cross(rayDir, edge2);
float a = Vector3.Dot(edge1, h);
if (a > -EPSILON && a < EPSILON)
return false;
float f = 1.0f / a;
Vector3 s = rayStart - v0;
float u = f * Vector3.Dot(s, h);
if (u < 0 || u > 1)
return false;
Vector3 q = Vector3.Cross(s, edge1);
float v = f * Vector3.Dot(rayDir, q);
if (v < 0 || u + v > 1)
return false;
t = f * Vector3.Dot(edge2, q);
return t >= 0;
}
}
}

View file

@ -0,0 +1,321 @@
using System;
using System.Collections.Generic;
using System.IO;
namespace NexSuite.Plugins.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;
_stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
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 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;
}
}

View file

@ -0,0 +1,658 @@
using System;
using System.Collections.Generic;
using System.IO;
namespace NexSuite.Plugins.RynthAi.Raycasting
{
/// <summary>
/// Extracts dungeon wall geometry from cell.dat Environment files for raycasting.
///
/// Pipeline:
/// EnvCell (0xXXYY01nn) → EnvironmentId (0x0Dxxxx) + CellStructure index
/// Environment (0x0Dxxxx) → CellStruct at index → Vertices + Polygons
/// Transform polygon vertices by cell position → BoundingVolumes for raycasting
///
/// Binary formats (from ACE source):
/// SWVertex: ushort numUVs, float3 Origin, float3 Normal, Vec2Duv[numUVs]
/// CVertexArray: int32 type=1, uint32 count, (ushort key + SWVertex)[count]
/// Polygon: byte numPts, byte stippling, int32 sidesType, short posSurf, short negSurf,
/// short[numPts] vertexIds, byte[numPts] posUV (if !NoPos), byte[numPts] negUV (if clockwise+!NoNeg)
/// CellStruct: uint32 numPolygons, uint32 numPhysicsPolygons, uint32 numPortals,
/// CVertexArray, Dictionary{ushort,Polygon}[numPolygons], ...
/// </summary>
public class DungeonLOS
{
private DatDatabase _portalDat;
private DatDatabase _cellDat;
// Cache: EnvironmentId → parsed CellStruct geometry per structure index
private readonly Dictionary<uint, Dictionary<uint, CellGeometry>> _envCache =
new Dictionary<uint, Dictionary<uint, CellGeometry>>();
// Cache: landblock → dungeon wall volumes
private readonly Dictionary<uint, List<BoundingVolume>> _wallCache =
new Dictionary<uint, List<BoundingVolume>>();
private const int MAX_ENV_CACHE = 50;
private const int MAX_WALL_CACHE = 20;
public void Initialize(DatDatabase portalDat, DatDatabase cellDat)
{
_portalDat = portalDat;
_cellDat = cellDat;
}
/// <summary>
/// Gets dungeon wall collision volumes for a landblock.
/// Returns empty list for outdoor-only landblocks.
/// </summary>
public List<BoundingVolume> GetDungeonWalls(uint landblockKey)
{
if (_wallCache.TryGetValue(landblockKey, out var cached))
return cached;
var walls = LoadDungeonWalls(landblockKey);
if (_wallCache.Count >= MAX_WALL_CACHE)
{
foreach (var key in _wallCache.Keys) { _wallCache.Remove(key); break; }
}
_wallCache[landblockKey] = walls;
return walls;
}
private List<BoundingVolume> LoadDungeonWalls(uint landblockKey)
{
var volumes = new List<BoundingVolume>();
if (_cellDat == null || _portalDat == null) return volumes;
uint baseId = landblockKey << 16;
float globalOffsetX = ((landblockKey >> 8) & 0xFF) * 192.0f;
float globalOffsetY = (landblockKey & 0xFF) * 192.0f;
int consecutiveMisses = 0;
for (uint cellNum = 0x0100; cellNum <= 0xFFFD; cellNum++)
{
uint cellId = baseId | cellNum;
byte[] cellData = _cellDat.GetFileData(cellId);
if (cellData == null)
{
consecutiveMisses++;
if (consecutiveMisses > 10) break;
continue;
}
consecutiveMisses = 0;
if (cellData.Length < 20) continue;
try
{
var envCell = ParseEnvCellHeader(cellData);
if (envCell == null) continue;
var cellGeo = GetCellGeometry(envCell.EnvironmentId, envCell.CellStructureIndex);
if (cellGeo == null || cellGeo.Polygons.Count == 0) continue;
foreach (var poly in cellGeo.Polygons)
{
if (poly.Vertices.Count < 3) continue;
// Transform vertices to world space
var worldVerts = new List<Vector3>();
foreach (var localVert in poly.Vertices)
worldVerts.Add(TransformVertex(localVert, envCell, globalOffsetX, globalOffsetY));
// Compute AABB from all vertices of the polygon
var min = new Vector3(float.MaxValue, float.MaxValue, float.MaxValue);
var max = new Vector3(float.MinValue, float.MinValue, float.MinValue);
foreach (var wv in worldVerts)
{
min = Vector3.Min(min, wv);
max = Vector3.Max(max, wv);
}
var size = max - min;
if (size.X < 0.01f && size.Y < 0.01f && size.Z < 0.01f) continue;
// Thicken walls to seal corner gaps. Where two perpendicular walls meet,
// we may be missing one wall's geometry (unparsed CellStruct).
// 0.5 yards ensures the existing walls overlap at corners.
// Portal polygons are excluded so doorways stay open.
// 1.0 yard skin on thin axes — creates 2 yard total thickness.
// Seals corner jut-outs where perpendicular walls meet.
// Portal polygons are excluded so doorways stay open.
float wallSkin = 0.5f;
if (size.X < wallSkin) { min.X -= wallSkin; max.X += wallSkin; }
if (size.Y < wallSkin) { min.Y -= wallSkin; max.Y += wallSkin; }
volumes.Add(new BoundingVolume
{
Type = BoundingVolume.VolumeType.AxisAlignedBox,
Center = (min + max) * 0.5f,
Dimensions = max - min,
Min = min,
Max = max,
IsDoor = false
});
}
}
catch { }
}
if (volumes.Count > 0)
Log($"Landblock 0x{landblockKey:X4}: {volumes.Count} dungeon wall volumes");
return volumes;
}
private Vector3 TransformVertex(Vector3 local, EnvCellHeader cell, float gx, float gy)
{
Vector3 rotated = RotateByQuat(local, cell.RotW, cell.RotX, cell.RotY, cell.RotZ);
return new Vector3(
rotated.X + cell.PosX + gx,
rotated.Y + cell.PosY + gy,
rotated.Z + cell.PosZ
);
}
private Vector3 RotateByQuat(Vector3 v, float qw, float qx, float qy, float qz)
{
float cx = qy * v.Z - qz * v.Y;
float cy = qz * v.X - qx * v.Z;
float cz = qx * v.Y - qy * v.X;
float cx2 = qy * cz - qz * cy;
float cy2 = qz * cx - qx * cz;
float cz2 = qx * cy - qy * cx;
return new Vector3(
v.X + 2f * (qw * cx + cx2),
v.Y + 2f * (qw * cy + cy2),
v.Z + 2f * (qw * cz + cz2)
);
}
// ===================================================================
// EnvCell header parsing
// ===================================================================
private class EnvCellHeader
{
public uint EnvironmentId;
public uint CellStructureIndex;
public float PosX, PosY, PosZ;
public float RotW, RotX, RotY, RotZ;
}
private EnvCellHeader ParseEnvCellHeader(byte[] data)
{
try
{
using (var ms = new MemoryStream(data))
using (var reader = new BinaryReader(ms))
{
uint id = reader.ReadUInt32();
uint flags = reader.ReadUInt32();
reader.ReadUInt32(); // duplicate CellId
byte numSurfaces = reader.ReadByte();
byte numPortals = reader.ReadByte();
ushort numVisibleCells = reader.ReadUInt16();
ms.Seek(numSurfaces * 2, SeekOrigin.Current);
ushort envIdShort = reader.ReadUInt16();
ushort cellStructure = reader.ReadUInt16();
return new EnvCellHeader
{
EnvironmentId = 0x0D000000u | envIdShort,
CellStructureIndex = cellStructure,
PosX = reader.ReadSingle(),
PosY = reader.ReadSingle(),
PosZ = reader.ReadSingle(),
RotW = reader.ReadSingle(),
RotX = reader.ReadSingle(),
RotY = reader.ReadSingle(),
RotZ = reader.ReadSingle()
};
}
}
catch { return null; }
}
// ===================================================================
// Environment + CellStruct parsing
// ===================================================================
private class CellGeometry
{
public List<CellPolygon> Polygons = new List<CellPolygon>();
}
private class CellPolygon
{
public List<Vector3> Vertices = new List<Vector3>();
}
private CellGeometry GetCellGeometry(uint environmentId, uint cellStructIndex)
{
if (_envCache.TryGetValue(environmentId, out var envCells))
{
if (envCells.TryGetValue(cellStructIndex, out var cached))
return cached;
}
byte[] envData = _portalDat.GetFileData(environmentId);
if (envData == null || envData.Length < 8) return null;
if (envCells == null)
{
envCells = ParseEnvironment(envData);
if (_envCache.Count >= MAX_ENV_CACHE)
{
foreach (var key in _envCache.Keys) { _envCache.Remove(key); break; }
}
_envCache[environmentId] = envCells;
}
envCells.TryGetValue(cellStructIndex, out var result);
return result;
}
private Dictionary<uint, CellGeometry> ParseEnvironment(byte[] data)
{
var result = new Dictionary<uint, CellGeometry>();
try
{
using (var ms = new MemoryStream(data))
using (var reader = new BinaryReader(ms))
{
uint id = reader.ReadUInt32();
// Dictionary<uint, CellStruct>
uint numCells = reader.ReadUInt32();
if (numCells > 200) return result;
for (uint i = 0; i < numCells; i++)
{
if (ms.Position + 4 > ms.Length) break;
uint key = reader.ReadUInt32();
var geo = ParseCellStruct(reader, ms);
if (geo != null)
result[key] = geo;
else
{
Log($"Environment 0x{id:X8}: failed parsing CellStruct {i} (key={key}), stopping");
break; // Stream position unknown — can't continue
}
}
}
}
catch (Exception ex)
{
Log($"Environment parse error: {ex.Message}");
}
if (result.Count > 0)
Log($"Environment: parsed {result.Count} CellStructs successfully");
return result;
}
/// <summary>
/// Parses CellStruct: vertices + rendering polygons + portal indices.
/// NOW ALSO SKIPS BSP trees so we can continue to the next CellStruct.
/// </summary>
private CellGeometry ParseCellStruct(BinaryReader reader, MemoryStream ms)
{
var geo = new CellGeometry();
try
{
uint numPolygons = reader.ReadUInt32();
uint numPhysicsPolygons = reader.ReadUInt32();
uint numPortals = reader.ReadUInt32();
if (numPolygons > 5000 || numPhysicsPolygons > 5000) return null;
var vertices = ParseVertexArray(reader, ms);
if (vertices == null) return null;
var polygons = ParsePolygons(reader, ms, numPolygons);
if (polygons == null) return null;
// Read portal polygon indices
var portalIndices = new HashSet<ushort>();
for (uint p = 0; p < numPortals && ms.Position + 2 <= ms.Length; p++)
portalIndices.Add(reader.ReadUInt16());
// Align to 4-byte boundary
long aligned = (ms.Position + 3) & ~3L;
if (aligned <= ms.Length) ms.Position = aligned;
// BUILD polygon geometry NOW, before BSP skip attempt.
// If BSP skip fails we still have the wall data.
for (int i = 0; i < polygons.Count; i++)
{
var poly = polygons[i];
if (portalIndices.Contains(poly.Key)) continue;
if (poly.VertexIds == null || poly.VertexIds.Count < 3) continue;
var cellPoly = new CellPolygon();
foreach (var vid in poly.VertexIds)
{
if (vertices.ContainsKey(vid))
cellPoly.Vertices.Add(vertices[vid]);
}
if (cellPoly.Vertices.Count >= 3)
geo.Polygons.Add(cellPoly);
}
// Now attempt to skip BSP trees so ParseEnvironment can read the next CellStruct.
// If this fails, we still have this CellStruct's geometry — we just can't parse further.
bool canContinue = true;
// Skip CellBSP
if (!SkipBSPTree(reader, ms, BSPTreeType.Cell))
canContinue = false;
// Skip PhysicsPolygons
if (canContinue && !SkipPolygons(reader, ms, numPhysicsPolygons))
canContinue = false;
// Skip PhysicsBSP
if (canContinue && !SkipBSPTree(reader, ms, BSPTreeType.Physics))
canContinue = false;
// Skip optional DrawingBSP
if (canContinue && ms.Position + 4 <= ms.Length)
{
uint hasDrawingBSP = reader.ReadUInt32();
if (hasDrawingBSP != 0)
{
if (!SkipBSPTree(reader, ms, BSPTreeType.Drawing))
canContinue = false;
}
}
// Final alignment
if (canContinue)
{
aligned = (ms.Position + 3) & ~3L;
if (aligned <= ms.Length) ms.Position = aligned;
}
// Return geometry. If canContinue is false, ParseEnvironment will break
// at the next iteration (stream position wrong), but we keep this CellStruct's data.
return geo;
}
catch
{
return geo.Polygons.Count > 0 ? geo : null;
}
}
// ===================================================================
// BSP Tree Skipping — matches ACE BSPNode/BSPLeaf exactly
// ===================================================================
private enum BSPTreeType { Cell, Physics, Drawing }
// ACE's uint32 constants for BSP node types (read as LE uint32, stored reversed in file)
private const uint BSP_PORT = 0x504F5254;
private const uint BSP_LEAF = 0x4C454146;
private const uint BSP_BPnn = 0x42506E6E;
private const uint BSP_BPIn = 0x4250496E;
private const uint BSP_BpIN = 0x4270494E;
private const uint BSP_BpnN = 0x42706E4E;
private const uint BSP_BPIN = 0x4250494E;
private const uint BSP_BPnN = 0x42506E4E;
private bool SkipBSPTree(BinaryReader reader, MemoryStream ms, BSPTreeType treeType)
{
return SkipBSPNode(reader, ms, treeType);
}
private bool SkipBSPNode(BinaryReader reader, MemoryStream ms, BSPTreeType treeType)
{
if (ms.Position + 4 > ms.Length) return false;
uint typeTag = reader.ReadUInt32();
if (typeTag == BSP_LEAF)
{
return SkipBSPLeaf(reader, ms, treeType);
}
if (typeTag == BSP_PORT)
{
// Portal node — same as leaf for our purposes
return SkipBSPLeaf(reader, ms, treeType);
}
// Internal node: read splitting plane (float3 normal + float dist = 16 bytes)
if (ms.Position + 16 > ms.Length) return false;
ms.Seek(16, SeekOrigin.Current);
// Read children based on type — matches ACE's switch exactly
switch (typeTag)
{
case BSP_BPnn:
case BSP_BPIn:
// Pos child only
if (!SkipBSPNode(reader, ms, treeType)) return false;
break;
case BSP_BpIN:
case BSP_BpnN:
// Neg child only
if (!SkipBSPNode(reader, ms, treeType)) return false;
break;
case BSP_BPIN:
case BSP_BPnN:
// Both children: Pos then Neg
if (!SkipBSPNode(reader, ms, treeType)) return false;
if (!SkipBSPNode(reader, ms, treeType)) return false;
break;
default:
return false; // Unknown type
}
// Cell BSP internal nodes have NO sphere — done
if (treeType == BSPTreeType.Cell)
return true;
// Physics and Drawing: read Sphere (float3 center + float radius = 16 bytes)
if (ms.Position + 16 > ms.Length) return false;
ms.Seek(16, SeekOrigin.Current);
// Physics: done after sphere
if (treeType == BSPTreeType.Physics)
return true;
// Drawing: also read InPolys (uint32 count + ushort[count])
if (ms.Position + 4 > ms.Length) return false;
uint numPolys = reader.ReadUInt32();
if (numPolys > 100000) return false;
long skip = numPolys * 2L; // ushort per poly
if (ms.Position + skip > ms.Length) return false;
ms.Seek(skip, SeekOrigin.Current);
return true;
}
/// <summary>
/// BSPLeaf: uint32 type + int32 leafIndex + (Physics only: int32 solid + Sphere(16) + uint32 numPolys + ushort[numPolys])
/// Note: Physics leaf ALWAYS reads Sphere even when solid=0 (per ACE source).
/// Cell and Drawing leaves are just type + leafIndex.
/// </summary>
private bool SkipBSPLeaf(BinaryReader reader, MemoryStream ms, BSPTreeType treeType)
{
// Type tag already read by caller. Read leafIndex.
if (ms.Position + 4 > ms.Length) return false;
reader.ReadInt32(); // leafIndex
if (treeType == BSPTreeType.Physics)
{
// int32 Solid
if (ms.Position + 4 > ms.Length) return false;
reader.ReadInt32();
// Sphere: ALWAYS read (16 bytes), even when solid=0
if (ms.Position + 16 > ms.Length) return false;
ms.Seek(16, SeekOrigin.Current);
// uint32 numPolys + ushort[numPolys]
if (ms.Position + 4 > ms.Length) return false;
uint numPolys = reader.ReadUInt32();
if (numPolys > 100000) return false;
long skip = numPolys * 2L;
if (ms.Position + skip > ms.Length) return false;
ms.Seek(skip, SeekOrigin.Current);
}
// Cell and Drawing leaves: nothing more after leafIndex
return true;
}
/// <summary>
/// Skips a Dictionary{ushort, Polygon} block — same format as ParsePolygons
/// but doesn't store results.
/// </summary>
private bool SkipPolygons(BinaryReader reader, MemoryStream ms, uint count)
{
for (uint i = 0; i < count; i++)
{
if (ms.Position + 12 > ms.Length) return false;
ushort polyKey = reader.ReadUInt16();
byte numPts = reader.ReadByte();
byte stippling = reader.ReadByte();
int sidesType = reader.ReadInt32();
ms.Seek(4, SeekOrigin.Current); // posSurf + negSurf
if (numPts == 0 || numPts > 50) return false;
// Vertex IDs
long vertBytes = numPts * 2L;
if (ms.Position + vertBytes > ms.Length) return false;
ms.Seek(vertBytes, SeekOrigin.Current);
// PosUV
if ((stippling & 0x04) == 0)
{
if (ms.Position + numPts > ms.Length) return false;
ms.Seek(numPts, SeekOrigin.Current);
}
// NegUV
if (sidesType == 2 && (stippling & 0x08) == 0)
{
if (ms.Position + numPts > ms.Length) return false;
ms.Seek(numPts, SeekOrigin.Current);
}
}
return true;
}
/// <summary>
/// CVertexArray: int32 type(=1) + uint32 count + (ushort key + SWVertex)[count]
/// SWVertex: ushort numUVs + float3 Origin(12) + float3 Normal(12) + numUVs × 8 bytes
/// </summary>
private Dictionary<ushort, Vector3> ParseVertexArray(BinaryReader reader, MemoryStream ms)
{
var verts = new Dictionary<ushort, Vector3>();
int vertexType = reader.ReadInt32();
if (vertexType != 1) return null;
uint numVerts = reader.ReadUInt32();
if (numVerts > 50000) return null;
for (uint i = 0; i < numVerts; i++)
{
if (ms.Position + 28 > ms.Length) break; // key(2) + numUVs(2) + origin(12) + normal(12)
ushort key = reader.ReadUInt16();
ushort numUVs = reader.ReadUInt16();
float ox = reader.ReadSingle();
float oy = reader.ReadSingle();
float oz = reader.ReadSingle();
reader.ReadSingle(); reader.ReadSingle(); reader.ReadSingle(); // normal
long uvBytes = numUVs * 8L;
if (uvBytes > 0 && ms.Position + uvBytes <= ms.Length)
ms.Seek(uvBytes, SeekOrigin.Current);
verts[key] = new Vector3(ox, oy, oz);
}
return verts.Count > 0 ? verts : null;
}
/// <summary>
/// Dictionary{ushort, Polygon}: count × (ushort key + Polygon)
/// Polygon: byte numPts, byte stippling, int32 sidesType, short posSurf, short negSurf,
/// short[numPts] vertexIds, optional UV index arrays
/// </summary>
private List<ParsedPolygon> ParsePolygons(BinaryReader reader, MemoryStream ms, uint count)
{
var polys = new List<ParsedPolygon>();
for (uint i = 0; i < count; i++)
{
if (ms.Position + 12 > ms.Length) return polys; // key(2) + header(10 min)
ushort polyKey = reader.ReadUInt16();
byte numPts = reader.ReadByte();
byte stippling = reader.ReadByte();
int sidesType = reader.ReadInt32();
short posSurf = reader.ReadInt16();
short negSurf = reader.ReadInt16();
if (numPts == 0 || numPts > 50) return polys;
var poly = new ParsedPolygon { Key = polyKey, VertexIds = new List<ushort>() };
for (int v = 0; v < numPts; v++)
{
if (ms.Position + 2 > ms.Length) return polys;
poly.VertexIds.Add((ushort)reader.ReadInt16());
}
// Skip PosUVIndices (byte per point) unless NoPos flag (0x04)
if ((stippling & 0x04) == 0)
{
if (ms.Position + numPts > ms.Length) return polys;
ms.Seek(numPts, SeekOrigin.Current);
}
// Skip NegUVIndices if Clockwise(2) and not NoNeg(0x08)
if (sidesType == 2 && (stippling & 0x08) == 0)
{
if (ms.Position + numPts > ms.Length) return polys;
ms.Seek(numPts, SeekOrigin.Current);
}
polys.Add(poly);
}
return polys;
}
private class ParsedPolygon
{
public ushort Key;
public List<ushort> VertexIds;
}
public void FlushCache()
{
_wallCache.Clear();
_envCache.Clear();
}
private static void Log(string msg)
{
System.Diagnostics.Debug.WriteLine($"[DungeonLOS] {msg}");
}
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,751 @@
using System;
using System.Collections.Generic;
using System.IO;
namespace NexSuite.Plugins.RynthAi.Raycasting
{
/// <summary>
/// A position + rotation in AC's 3D world.
/// Position is in local landblock meters (0-192 for outdoors).
/// Rotation is a quaternion (W, X, Y, Z).
/// </summary>
public class Frame
{
public float OriginX, OriginY, OriginZ;
public float RotW, RotX, RotY, RotZ;
public Frame()
{
RotW = 1.0f; // Identity quaternion
}
public void Unpack(BinaryReader reader)
{
OriginX = reader.ReadSingle();
OriginY = reader.ReadSingle();
OriginZ = reader.ReadSingle();
RotW = reader.ReadSingle();
RotX = reader.ReadSingle();
RotY = reader.ReadSingle();
RotZ = reader.ReadSingle();
}
/// <summary>
/// Rotates a point by this frame's quaternion.
/// q * v * q^-1 (for unit quaternion, q^-1 = conjugate)
/// </summary>
public Vector3 RotatePoint(Vector3 point)
{
// Quaternion rotation: v' = q * v * q*
float qw = RotW, qx = RotX, qy = RotY, qz = RotZ;
// Cross product of quaternion xyz with point
float cx = qy * point.Z - qz * point.Y;
float cy = qz * point.X - qx * point.Z;
float cz = qx * point.Y - qy * point.X;
// Result = point + 2 * (qw * cross + qxyz x cross)
float cx2 = qy * cz - qz * cy;
float cy2 = qz * cx - qx * cz;
float cz2 = qx * cy - qy * cx;
return new Vector3(
point.X + 2.0f * (qw * cx + cx2),
point.Y + 2.0f * (qw * cy + cy2),
point.Z + 2.0f * (qw * cz + cz2)
);
}
/// <summary>
/// Transforms a point: rotate then translate.
/// </summary>
public Vector3 TransformPoint(Vector3 localPoint)
{
Vector3 rotated = RotatePoint(localPoint);
return new Vector3(
rotated.X + OriginX,
rotated.Y + OriginY,
rotated.Z + OriginZ
);
}
public override string ToString()
{
return $"Pos({OriginX:F2}, {OriginY:F2}, {OriginZ:F2}) Rot({RotW:F3}, {RotX:F3}, {RotY:F3}, {RotZ:F3})";
}
}
/// <summary>
/// A static object placed on a landblock (building, tree, rock, structure, etc.)
/// </summary>
public class StaticObject
{
public uint InstanceId; // Unique placement ID
public uint SetupId; // Reference to 0x02xxxxxx Setup in portal.dat
public Frame Placement; // Position and rotation in landblock space
public StaticObject()
{
Placement = new Frame();
}
}
/// <summary>
/// Parsed landblock info from cell.dat (file ID = 0xXXYYFFFE).
/// Contains static object placements (Stabs) and building info for an outdoor landblock.
///
/// Format (from ACE.DatLoader.FileTypes.LandblockInfo):
/// uint32 Id
/// uint32 NumCells
/// uint32 NumObjects (List&lt;Stab&gt; count)
/// Stab[NumObjects]:
/// uint32 Id (model/setup reference, 0x01xx or 0x02xx)
/// Frame (7 floats: pos.xyz + rot.wxyz = 28 bytes)
/// ushort NumBuildings
/// ushort PackMask
/// BuildInfo[NumBuildings]:
/// uint32 ModelId
/// Frame (28 bytes)
/// uint32 NumLeaves
/// List&lt;CBldPortal&gt; Portals
/// if (PackMask &amp; 1):
/// PackedHashTable RestrictionTables
/// </summary>
public class LandblockInfo
{
public uint Id;
public uint NumCells;
public List<StaticObject> StaticObjects = new List<StaticObject>();
public bool HasObjects;
/// <summary>
/// Parse landblock info from raw .dat file data using the ACE format.
/// </summary>
public bool Unpack(byte[] data)
{
if (data == null || data.Length < 12)
return false;
try
{
using (var ms = new MemoryStream(data))
using (var reader = new BinaryReader(ms))
{
Id = reader.ReadUInt32();
NumCells = reader.ReadUInt32();
// Read List<Stab> — uint32 count + count × Stab entries
uint numObjects = reader.ReadUInt32();
if (numObjects > 5000) numObjects = 5000; // Sanity
for (uint i = 0; i < numObjects; i++)
{
if (ms.Position + 32 > ms.Length) break; // Need 4 (Id) + 28 (Frame)
var obj = new StaticObject();
obj.SetupId = reader.ReadUInt32();
obj.Placement.Unpack(reader);
StaticObjects.Add(obj);
}
HasObjects = StaticObjects.Count > 0;
Log($"Landblock 0x{Id:X8}: {StaticObjects.Count} static objects");
return true;
}
}
catch (Exception ex)
{
Log($"Error parsing landblock 0x{Id:X8}: {ex.Message}");
return false;
}
}
private static void Log(string msg)
{
System.Diagnostics.Debug.WriteLine($"[LandblockInfo] {msg}");
}
}
/// <summary>
/// Parsed environment cell from cell.dat (file ID = 0xXXYY0001 to 0xXXYYFFFE).
/// Represents an indoor dungeon room with walls, portals, and static objects.
/// </summary>
public class EnvCellInfo
{
public uint Id;
public uint Flags;
public List<Vector3> Vertices = new List<Vector3>();
public List<CellPolygon> Polygons = new List<CellPolygon>();
public List<ushort> PortalPolygonIndices = new List<ushort>();
public List<StaticObject> StaticObjects = new List<StaticObject>();
public List<uint> ConnectedCells = new List<uint>();
public uint EnvironmentId; // Reference to portal.dat environment
public uint StructureId; // Reference to portal.dat cell structure
/// <summary>
/// Parse environment cell from raw data.
///
/// Format (simplified):
/// uint32 id
/// uint32 flags
/// uint32 environmentId (0x0Dxxxxxx)
/// uint16 cellStructId
/// uint16 position (index into structure)
/// Frame placement
/// uint32 numPortals
/// for each portal:
/// uint16 polygonId (portal polygon index)
/// uint16 flags
/// uint32 connectedCell
/// uint32 numStaticObjects
/// for each static object:
/// uint32 setupId
/// Frame placement
/// </summary>
public bool Unpack(byte[] data)
{
if (data == null || data.Length < 12)
return false;
try
{
using (var ms = new MemoryStream(data))
using (var reader = new BinaryReader(ms))
{
Id = reader.ReadUInt32();
Flags = reader.ReadUInt32();
// Read environment/structure references
if (ms.Position + 8 > ms.Length) return false;
// The exact format depends on flags, but typically:
EnvironmentId = reader.ReadUInt32();
if (ms.Position + 4 > ms.Length) return false;
StructureId = reader.ReadUInt32();
// Read cell frame (position + rotation)
if ((Flags & 0x02) != 0 && ms.Position + 28 <= ms.Length)
{
var frame = new Frame();
frame.Unpack(reader);
}
// Read portals
if ((Flags & 0x04) != 0 || ms.Position + 4 <= ms.Length)
{
if (ms.Position + 4 <= ms.Length)
{
uint numPortals = reader.ReadUInt32();
if (numPortals > 1000) numPortals = 0; // Sanity
for (uint i = 0; i < numPortals && ms.Position + 8 <= ms.Length; i++)
{
ushort polyId = reader.ReadUInt16();
ushort portalFlags = reader.ReadUInt16();
uint connCell = reader.ReadUInt32();
PortalPolygonIndices.Add(polyId);
ConnectedCells.Add(connCell);
}
}
}
// Read static objects
if (ms.Position + 4 <= ms.Length)
{
uint numObjects = reader.ReadUInt32();
if (numObjects > 10000) numObjects = 0;
for (uint i = 0; i < numObjects && ms.Position + 32 <= ms.Length; i++)
{
var obj = new StaticObject();
obj.SetupId = reader.ReadUInt32();
obj.Placement.Unpack(reader);
StaticObjects.Add(obj);
}
}
Log($"EnvCell 0x{Id:X8}: {StaticObjects.Count} objects, " +
$"{PortalPolygonIndices.Count} portals");
return true;
}
}
catch (Exception ex)
{
Log($"Error parsing EnvCell 0x{Id:X8}: {ex.Message}");
return false;
}
}
private static void Log(string msg)
{
System.Diagnostics.Debug.WriteLine($"[EnvCell] {msg}");
}
}
/// <summary>
/// A polygon in a cell structure (wall, floor, ceiling).
/// </summary>
public class CellPolygon
{
public ushort[] VertexIndices;
public bool IsPortal; // Portal polygons are openings, not solid walls
}
/// <summary>
/// Parsed Setup file from portal.dat (file ID = 0x02xxxxxx).
/// Matches ACE.DatLoader.FileTypes.SetupModel.Unpack() exactly.
///
/// Format:
/// uint32 Id
/// uint32 Flags (SetupFlags)
/// uint32 numParts
/// uint32[numParts] Parts (GfxObj references, 0x01xxxxxx)
/// if (Flags & 0x01): uint32[numParts] ParentIndex
/// if (Flags & 0x02): Vector3[numParts] DefaultScale
/// Dictionary&lt;int,LocationType&gt; HoldingLocations (uint32 count + entries)
/// Dictionary&lt;int,LocationType&gt; ConnectionPoints (uint32 count + entries)
/// int32 placementsCount
/// PlacementType[placementsCount]: key(int32) + AnimFrame(numParts × Frame(28) + uint32 numHooks + hooks)
/// List&lt;CylSphere&gt; CylSpheres (uint32 count + count × 20 bytes)
/// List&lt;Sphere&gt; Spheres (uint32 count + count × 16 bytes)
/// float Height, Radius, StepUpHeight, StepDownHeight
/// Sphere SortingSphere (Vector3 + float = 16 bytes)
/// Sphere SelectionSphere (16 bytes)
/// Dictionary&lt;int,LightInfo&gt; Lights
/// uint32 × 5 defaults
/// </summary>
public class SetupInfo
{
public uint Id;
public uint Flags;
public int NumParts;
public uint[] PartIds;
// Bounding sphere (from SortingSphere)
public float BoundingSphereRadius;
public Vector3 BoundingSphereCenter;
// Physics dimensions
public float Height;
public float Radius; // Physics collision radius
// Collision spheres
public List<CollisionSphere> Spheres = new List<CollisionSphere>();
// Collision cylinders
public List<CollisionCylinder> Cylinders = new List<CollisionCylinder>();
public bool HasBounds;
public bool Unpack(byte[] data)
{
if (data == null || data.Length < 16)
return false;
try
{
using (var ms = new MemoryStream(data))
using (var reader = new BinaryReader(ms))
{
// --- Header ---
Id = reader.ReadUInt32();
Flags = reader.ReadUInt32();
uint numParts = reader.ReadUInt32();
if (numParts > 500) return false;
NumParts = (int)numParts;
PartIds = new uint[numParts];
for (int i = 0; i < numParts; i++)
PartIds[i] = reader.ReadUInt32();
// --- Optional arrays based on flags ---
// HasParent = 0x01
if ((Flags & 0x01) != 0)
ms.Seek(numParts * 4, SeekOrigin.Current);
// HasDefaultScale = 0x02
if ((Flags & 0x02) != 0)
ms.Seek(numParts * 12, SeekOrigin.Current); // Vector3 = 12 bytes
// --- Skip HoldingLocations: uint32 count + count × (key(4) + PartId(4) + Frame(28)) ---
if (!SkipHashTable(reader, ms, 36)) return TryFallbackParse(data);
// --- Skip ConnectionPoints: same format ---
if (!SkipHashTable(reader, ms, 36)) return TryFallbackParse(data);
// --- Skip PlacementFrames ---
if (ms.Position + 4 > ms.Length) return TryFallbackParse(data);
int placementsCount = reader.ReadInt32();
if (placementsCount < 0 || placementsCount > 100) return TryFallbackParse(data);
for (int p = 0; p < placementsCount; p++)
{
if (ms.Position + 4 > ms.Length) return TryFallbackParse(data);
reader.ReadInt32(); // key
// AnimationFrame: numParts × Frame(28 bytes) + uint32 numHooks
for (int part = 0; part < numParts; part++)
{
if (ms.Position + 28 > ms.Length) return TryFallbackParse(data);
ms.Seek(28, SeekOrigin.Current); // Skip Frame
}
if (ms.Position + 4 > ms.Length) return TryFallbackParse(data);
uint numHooks = reader.ReadUInt32();
if (numHooks > 0)
{
// AnimationHooks are variable-size; can't easily skip
// Fall back to tail scanning
return TryFallbackParse(data);
}
}
// --- NOW we're at the good stuff! ---
return ReadBoundsData(reader, ms, data);
}
}
catch
{
return TryFallbackParse(data);
}
}
/// <summary>
/// Reads CylSpheres, Spheres, Height, Radius, SortingSphere from current position.
/// </summary>
private bool ReadBoundsData(BinaryReader reader, MemoryStream ms, byte[] data)
{
try
{
// CylSpheres: uint32 count + count × (Vector3 origin(12) + float radius(4) + float height(4) = 20)
if (ms.Position + 4 > ms.Length) return false;
uint numCylSpheres = reader.ReadUInt32();
if (numCylSpheres > 50) return TryFallbackParse(data);
for (uint i = 0; i < numCylSpheres; i++)
{
if (ms.Position + 20 > ms.Length) break;
var cyl = new CollisionCylinder();
cyl.BottomCenter = new Vector3(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle());
cyl.Radius = reader.ReadSingle();
cyl.Height = reader.ReadSingle();
if (cyl.Radius > 0 && cyl.Height > 0 && !float.IsNaN(cyl.Radius))
Cylinders.Add(cyl);
}
// Spheres: uint32 count + count × (Vector3 origin(12) + float radius(4) = 16)
if (ms.Position + 4 > ms.Length) return false;
uint numSpheres = reader.ReadUInt32();
if (numSpheres > 50) return TryFallbackParse(data);
for (uint i = 0; i < numSpheres; i++)
{
if (ms.Position + 16 > ms.Length) break;
var sphere = new CollisionSphere();
sphere.Center = new Vector3(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle());
sphere.Radius = reader.ReadSingle();
if (sphere.Radius > 0 && !float.IsNaN(sphere.Radius))
Spheres.Add(sphere);
}
// Height, Radius, StepUpHeight, StepDownHeight
if (ms.Position + 16 > ms.Length) return false;
Height = reader.ReadSingle();
Radius = reader.ReadSingle();
float stepUp = reader.ReadSingle();
float stepDown = reader.ReadSingle();
// SortingSphere: Vector3 center + float radius
if (ms.Position + 16 > ms.Length) return false;
float sx = reader.ReadSingle(), sy = reader.ReadSingle(), sz = reader.ReadSingle();
float sr = reader.ReadSingle();
BoundingSphereCenter = new Vector3(sx, sy, sz);
BoundingSphereRadius = sr;
HasBounds = sr > 0.001f || Radius > 0.001f;
// If SortingSphere radius is 0, use the physics Radius
if (BoundingSphereRadius < 0.001f && Radius > 0.001f)
BoundingSphereRadius = Radius;
Log($"Setup 0x{Id:X8}: bounds OK — radius={BoundingSphereRadius:F2}, height={Height:F2}, " +
$"{Cylinders.Count} cyls, {Spheres.Count} spheres");
return true;
}
catch
{
return TryFallbackParse(data);
}
}
/// <summary>
/// Skip a hash table: uint32 count + count × entries of entrySize bytes.
/// </summary>
private bool SkipHashTable(BinaryReader reader, MemoryStream ms, int entrySize)
{
if (ms.Position + 4 > ms.Length) return false;
uint count = reader.ReadUInt32();
if (count > 1000) return false;
long skip = (long)count * entrySize;
if (ms.Position + skip > ms.Length) return false;
ms.Seek(skip, SeekOrigin.Current);
return true;
}
/// <summary>
/// Fallback: scan from the end of the file for the known tail structure.
/// The tail is always:
/// ... SortingSphere(16) + SelectionSphere(16) + Lights(uint32 count + entries) + 5×uint32(20)
/// If Lights is empty (count=0 → 4 bytes), tail is 56 bytes from end.
/// </summary>
private bool TryFallbackParse(byte[] data)
{
try
{
// Read header to get PartIds at minimum
if (PartIds == null && data.Length >= 16)
{
using (var ms2 = new MemoryStream(data))
using (var r2 = new BinaryReader(ms2))
{
Id = r2.ReadUInt32();
Flags = r2.ReadUInt32();
uint np = r2.ReadUInt32();
if (np <= 500)
{
NumParts = (int)np;
PartIds = new uint[np];
for (int i = 0; i < np && ms2.Position + 4 <= ms2.Length; i++)
PartIds[i] = r2.ReadUInt32();
}
}
}
// Try to find SortingSphere by scanning from end
// Known tail (if Lights empty): 5×uint32(20) + Lights(4) + SelectionSphere(16) + SortingSphere(16) + 4×float(16)
// = 72 bytes from end for start of Height/Radius/StepUp/StepDown
int[] tailOffsets = { 72, 78, 84 }; // Try different Lights sizes (4, 10, 16 bytes)
foreach (int tailOff in tailOffsets)
{
int offset = data.Length - tailOff;
if (offset < 16 || offset + 48 > data.Length) continue;
float h = BitConverter.ToSingle(data, offset);
float r = BitConverter.ToSingle(data, offset + 4);
float sx = BitConverter.ToSingle(data, offset + 16);
float sy = BitConverter.ToSingle(data, offset + 20);
float sz = BitConverter.ToSingle(data, offset + 24);
float sr = BitConverter.ToSingle(data, offset + 28);
// Validate: Height and Radius should be positive, sphere radius positive, center reasonable
if (h >= 0 && h < 100 && r > 0 && r < 200 &&
sr > 0 && sr < 500 &&
!float.IsNaN(h) && !float.IsNaN(r) && !float.IsNaN(sr) &&
Math.Abs(sx) < 1000 && Math.Abs(sy) < 1000 && Math.Abs(sz) < 1000)
{
Height = h;
Radius = r;
BoundingSphereCenter = new Vector3(sx, sy, sz);
BoundingSphereRadius = sr;
HasBounds = true;
Log($"Setup 0x{Id:X8}: FALLBACK found bounds at tailOff={tailOff} — radius={sr:F2}, height={h:F2}");
return true;
}
}
Log($"Setup 0x{Id:X8}: FALLBACK failed, no valid bounds found");
return false;
}
catch
{
return false;
}
}
private static void Log(string msg)
{
System.Diagnostics.Debug.WriteLine($"[Setup] {msg}");
}
}
/// <summary>
/// Parsed GfxObj from portal.dat (file ID = 0x01xxxxxx).
/// Contains 3D mesh data. We extract the bounding sphere and AABB.
/// </summary>
public class GfxObjInfo
{
public uint Id;
public uint Flags;
// Bounding data (what we need for raycasting)
public Vector3 SortingCenter;
public float SortingRadius;
public Vector3 BoundsMin;
public Vector3 BoundsMax;
public bool HasBounds;
// Vertex data (for precise bounds calculation)
public List<Vector3> Vertices = new List<Vector3>();
/// <summary>
/// Parse GfxObj to extract bounding information.
/// We don't need the full mesh/texture data for raycasting.
///
/// Format (simplified):
/// uint32 id
/// uint32 flags
/// -- surface data (skip) --
/// uint32 numVertices
/// for each vertex:
/// float3 position
/// float3 normal
/// (optional UV data based on flags)
/// -- polygon data (skip) --
/// -- BSP data (skip for now) --
/// float3 sortingCenter
/// float sortingRadius
/// </summary>
public bool Unpack(byte[] data)
{
if (data == null || data.Length < 12)
return false;
try
{
using (var ms = new MemoryStream(data))
using (var reader = new BinaryReader(ms))
{
Id = reader.ReadUInt32();
Flags = reader.ReadUInt32();
// Skip surface references
if (ms.Position + 4 > ms.Length) return false;
uint numSurfaces = reader.ReadUInt32();
if (numSurfaces > 10000) return false;
ms.Seek(numSurfaces * 4, SeekOrigin.Current); // uint32 per surface
// Read vertex count
if (ms.Position + 4 > ms.Length) return false;
uint numVertices = reader.ReadUInt32();
if (numVertices > 100000) return false;
// Read vertices and compute AABB
float minX = float.MaxValue, minY = float.MaxValue, minZ = float.MaxValue;
float maxX = float.MinValue, maxY = float.MinValue, maxZ = float.MinValue;
for (uint i = 0; i < numVertices; i++)
{
if (ms.Position + 12 > ms.Length) break;
float x = reader.ReadSingle();
float y = reader.ReadSingle();
float z = reader.ReadSingle();
if (float.IsNaN(x) || float.IsNaN(y) || float.IsNaN(z)) continue;
Vertices.Add(new Vector3(x, y, z));
minX = Math.Min(minX, x); maxX = Math.Max(maxX, x);
minY = Math.Min(minY, y); maxY = Math.Max(maxY, y);
minZ = Math.Min(minZ, z); maxZ = Math.Max(maxZ, z);
// Skip normal (3 floats) + UV data
if (ms.Position + 12 <= ms.Length)
ms.Seek(12, SeekOrigin.Current); // Skip normal
// UV data varies; skip based on flags
if ((Flags & 0x04) != 0 && ms.Position + 8 <= ms.Length)
ms.Seek(8, SeekOrigin.Current); // Skip UV
}
if (Vertices.Count > 0)
{
BoundsMin = new Vector3(minX, minY, minZ);
BoundsMax = new Vector3(maxX, maxY, maxZ);
HasBounds = true;
// Compute bounding sphere from AABB
SortingCenter = new Vector3(
(minX + maxX) * 0.5f,
(minY + maxY) * 0.5f,
(minZ + maxZ) * 0.5f
);
SortingRadius = (BoundsMax - SortingCenter).Length();
}
// Also try to find the explicit sorting sphere at the end of file
TryReadSortingSphere(data);
Log($"GfxObj 0x{Id:X8}: {Vertices.Count} verts, radius={SortingRadius:F2}");
return true;
}
}
catch (Exception ex)
{
Log($"Error parsing GfxObj 0x{Id:X8}: {ex.Message}");
return false;
}
}
/// <summary>
/// Scans the end of the file for the sorting sphere data.
/// The sorting center + radius are typically near the end of the GfxObj.
/// </summary>
private void TryReadSortingSphere(byte[] data)
{
// The last 16 bytes before any trailing data often contain the sorting sphere
if (data.Length < 20) return;
// Try reading from the last 16 bytes
for (int offset = data.Length - 16; offset >= Math.Max(0, data.Length - 64); offset -= 4)
{
if (offset + 16 > data.Length) continue;
float cx = BitConverter.ToSingle(data, offset);
float cy = BitConverter.ToSingle(data, offset + 4);
float cz = BitConverter.ToSingle(data, offset + 8);
float r = BitConverter.ToSingle(data, offset + 12);
if (r > 0.01f && r < 500f && !float.IsNaN(r) && !float.IsInfinity(r) &&
!float.IsNaN(cx) && !float.IsNaN(cy) && !float.IsNaN(cz) &&
Math.Abs(cx) < 1000 && Math.Abs(cy) < 1000 && Math.Abs(cz) < 1000)
{
SortingCenter = new Vector3(cx, cy, cz);
SortingRadius = r;
break;
}
}
}
private static void Log(string msg)
{
System.Diagnostics.Debug.WriteLine($"[GfxObj] {msg}");
}
}
/// <summary>
/// A spherical collision volume from a Setup file.
/// </summary>
public class CollisionSphere
{
public Vector3 Center;
public float Radius;
}
/// <summary>
/// A cylindrical collision volume from a Setup file.
/// </summary>
public class CollisionCylinder
{
public Vector3 BottomCenter;
public float Radius;
public float Height;
}
}

View file

@ -0,0 +1,98 @@
using System;
using Decal.Adapter;
namespace NexSuite.Plugins.RynthAi.Raycasting
{
/// <summary>
/// Main integration point for the raycasting system.
/// Initializes the .dat file parsers, geometry loader, and targeting FSM.
///
/// Usage:
/// var raycast = new MainLogic();
/// raycast.Initialize(acFolderPath); // Call once at startup
///
/// // During combat:
/// bool blocked = raycast.IsTargetBlocked(core, targetWorldObject, attackType);
/// </summary>
public class MainLogic : IDisposable
{
private GeometryLoader _geoLoader;
private BlacklistManager _blacklist;
private TargetingFSM _targetingFSM;
private bool _disposed;
public GeometryLoader GeometryLoader => _geoLoader;
public BlacklistManager Blacklist => _blacklist;
public TargetingFSM TargetingFSM => _targetingFSM;
public bool IsInitialized => _geoLoader?.IsInitialized ?? false;
public string StatusMessage => _geoLoader?.StatusMessage ?? "Not created";
public MainLogic()
{
_geoLoader = new GeometryLoader();
_blacklist = new BlacklistManager();
_targetingFSM = new TargetingFSM(_geoLoader, _blacklist);
}
/// <summary>
/// Initializes the raycasting system by loading portal.dat and cell.dat.
///
/// acFolderPath: Optional explicit path to AC installation folder.
/// If null, will search common installation paths automatically.
///
/// Returns true if initialization succeeded (both .dat files loaded).
/// </summary>
public bool Initialize(string acFolderPath = null)
{
try
{
bool result = _geoLoader.Initialize(acFolderPath);
if (result)
{
System.Diagnostics.Debug.WriteLine("[Raycast] MainLogic initialized successfully");
}
else
System.Diagnostics.Debug.WriteLine($"[Raycast] MainLogic init failed: {_geoLoader.StatusMessage}");
return result;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"[Raycast] MainLogic init error: {ex.Message}");
return false;
}
}
/// <summary>
/// Quick check: is a specific target blocked by geometry?
/// Call this from CombatManager before engaging a target.
/// </summary>
public bool IsTargetBlocked(CoreManager core, Decal.Adapter.Wrappers.WorldObject target,
TargetingFSM.AttackType attackType)
{
if (!IsInitialized || _targetingFSM == null)
return false;
return _targetingFSM.IsTargetBlocked(core, target, attackType);
}
/// <summary>
/// Determines the attack type from the currently wielded weapon.
/// </summary>
public TargetingFSM.AttackType GetAttackType(CoreManager core)
{
return _targetingFSM?.DetermineAttackType(core) ?? TargetingFSM.AttackType.Linear;
}
public void Dispose()
{
if (_disposed) return;
_geoLoader?.Dispose();
_blacklist?.ClearAll();
_disposed = true;
System.Diagnostics.Debug.WriteLine("[Raycast] MainLogic disposed");
}
}
}

View file

@ -0,0 +1,235 @@
using System;
using System.Collections.Generic;
namespace NexSuite.Plugins.RynthAi.Raycasting
{
/// <summary>
/// Core raycasting engine for line-of-sight checks.
/// Tests linear (spell/bolt) and parabolic (bow/thrown) trajectories
/// against the loaded collision geometry.
///
/// NOTE: Uses custom Vector3 from this namespace, NOT System.Numerics.
/// </summary>
public static class RaycastEngine
{
/// <summary>
/// Gravity constant for parabolic trajectory calculations.
/// AC's gravity is approximately 9.81 m/s² but may need empirical tuning.
/// </summary>
private const float GRAVITY = 9.81f;
/// <summary>
/// Number of sample points along an arc trajectory for collision testing.
/// Higher = more accurate but slower. 10 is a good balance.
/// </summary>
private const int ARC_SAMPLE_COUNT = 10;
/// <summary>
/// Tests if a straight-line path (magic spells, crossbow bolts) is blocked
/// by any collision geometry.
///
/// Returns true if the path IS blocked (an obstacle exists between origin and target).
/// Returns false if the path is clear.
/// </summary>
public static bool IsLinearPathBlocked(Vector3 origin, Vector3 target, List<BoundingVolume> geometry)
{
if (geometry == null || geometry.Count == 0)
return false;
// Validate inputs
if (float.IsNaN(origin.X) || float.IsNaN(origin.Y) || float.IsNaN(origin.Z) ||
float.IsNaN(target.X) || float.IsNaN(target.Y) || float.IsNaN(target.Z))
return false;
// Calculate direction and distance
Vector3 delta = target - origin;
float distanceToTarget = delta.Length();
// Origin and target are the same point — no obstruction possible
if (distanceToTarget < 1e-4f)
return false;
// Normalize direction
Vector3 direction = delta / distanceToTarget;
// Test ray against each bounding volume
foreach (var volume in geometry)
{
// Skip doors (state is unreliable, as per VTank's approach)
if (volume.IsDoor)
continue;
// Test intersection
float hitDist;
if (volume.RayIntersect(origin, direction, distanceToTarget, out hitDist))
{
// Ignore geometry within 2m of the player — prevents false blocks
// from walls/floors the player is standing on or touching.
// Only count geometry that's actually BETWEEN the player and target.
if (hitDist >= 2.0f && hitDist < distanceToTarget)
{
return true; // Path is blocked
}
}
}
return false; // Path is clear
}
/// <summary>
/// Tests if a parabolic arc path (bows, thrown weapons) is blocked by geometry.
///
/// This allows attacks to arc over low obstacles like walls and rocks.
/// The arc is sampled at discrete points and each segment is tested for
/// intersection with geometry.
///
/// Returns true if the arc IS blocked.
/// Returns false if the arc clears all obstacles.
/// </summary>
public static bool IsArcPathBlocked(Vector3 origin, Vector3 target, float initialVelocity,
List<BoundingVolume> geometry)
{
if (geometry == null || geometry.Count == 0)
return false;
if (initialVelocity <= 0)
return true; // Can't fire with no velocity
// Validate inputs
if (float.IsNaN(origin.X) || float.IsNaN(target.X))
return true;
Vector3 delta = target - origin;
float horizontalDist = delta.Length2D();
float verticalDist = delta.Z;
// Check maximum range: v² / g
float maxRange = (initialVelocity * initialVelocity) / GRAVITY;
if (horizontalDist > maxRange)
return true; // Out of range
if (horizontalDist < 0.1f)
return false; // Basically on top of target
// Calculate launch angle for the desired range
// Using the optimal angle that clears obstacles
// θ = 0.5 * arcsin(g * d / v²) for flat terrain
float sinArg = (GRAVITY * horizontalDist) / (initialVelocity * initialVelocity);
sinArg = Math.Min(sinArg, 1.0f); // Clamp for float precision
// Use the high arc (π/2 - θ) for better obstacle clearance
float launchAngle = (float)(0.5 * Math.Asin(sinArg));
if (launchAngle < 0.1f)
launchAngle = (float)(Math.PI / 4); // Default to 45° if calculation fails
float cosAngle = (float)Math.Cos(launchAngle);
float sinAngle = (float)Math.Sin(launchAngle);
// Calculate time of flight
float vHorizontal = initialVelocity * cosAngle;
float vVertical = initialVelocity * sinAngle;
if (vHorizontal < 0.01f)
return true; // Basically firing straight up
float totalTime = horizontalDist / vHorizontal;
// Horizontal direction (unit vector in XY plane)
float hdx = delta.X / horizontalDist;
float hdy = delta.Y / horizontalDist;
// Sample the arc at discrete points and test each segment
Vector3 prevPoint = origin;
for (int i = 1; i <= ARC_SAMPLE_COUNT; i++)
{
float t = (float)i / ARC_SAMPLE_COUNT;
float time = t * totalTime;
// Kinematic equations
float hDist = vHorizontal * time;
float height = origin.Z + vVertical * time - 0.5f * GRAVITY * time * time;
// Adjust height to interpolate between origin.Z and target.Z
// (accounts for height difference between origin and target)
float heightAdjust = verticalDist * t;
Vector3 arcPoint = new Vector3(
origin.X + hdx * hDist,
origin.Y + hdy * hDist,
height + heightAdjust * (1.0f - t) // Blend in height difference
);
// Test this segment for collisions
if (IsSegmentBlocked(prevPoint, arcPoint, geometry))
return true;
prevPoint = arcPoint;
}
// Test final segment to target
if (IsSegmentBlocked(prevPoint, target, geometry))
return true;
return false; // Arc clears all obstacles
}
/// <summary>
/// Tests if a line segment between two points intersects any geometry.
/// Used internally for arc sampling.
/// </summary>
private static bool IsSegmentBlocked(Vector3 start, Vector3 end, List<BoundingVolume> geometry)
{
Vector3 delta = end - start;
float dist = delta.Length();
if (dist < 0.01f) return false;
Vector3 dir = delta / dist;
foreach (var volume in geometry)
{
if (volume.IsDoor) continue;
float hitDist;
if (volume.RayIntersect(start, dir, dist, out hitDist))
{
if (hitDist > 0.05f && hitDist < dist - 0.05f)
return true;
}
}
return false;
}
/// <summary>
/// Quick distance-based pre-filter: checks if ANY geometry exists near the line
/// between origin and target. Used to skip the full raycast for wide-open areas.
/// Returns true if there is nearby geometry worth testing.
/// </summary>
public static bool HasNearbyGeometry(Vector3 origin, Vector3 target, List<BoundingVolume> geometry, float margin = 5.0f)
{
if (geometry == null || geometry.Count == 0)
return false;
// Compute a rough bounding box for the path
Vector3 pathMin = Vector3.Min(origin, target) - new Vector3(margin, margin, margin);
Vector3 pathMax = Vector3.Max(origin, target) + new Vector3(margin, margin, margin);
foreach (var vol in geometry)
{
if (vol.IsDoor) continue;
// Quick AABB overlap test
if (vol.Max.X >= pathMin.X && vol.Min.X <= pathMax.X &&
vol.Max.Y >= pathMin.Y && vol.Min.Y <= pathMax.Y &&
vol.Max.Z >= pathMin.Z && vol.Min.Z <= pathMax.Z)
{
return true;
}
}
return false;
}
}
}

View file

@ -0,0 +1,948 @@
using System;
using System.Collections.Generic;
using System.IO;
namespace NexSuite.Plugins.RynthAi.Raycasting
{
/// <summary>
/// Implements AC's deterministic scatter placement system for terrain objects (trees, rocks, etc).
/// Ported from ACE's Landblock.get_land_scenes() + ObjectDesc.Displace/Rotate/Scale.
///
/// Pipeline:
/// 1. Parse RegionDesc (0x13000000) from portal.dat → terrain-to-scene mapping tables
/// 2. Parse CellLandblock (0xXXYYFFFF) from cell.dat → 81 terrain values + 81 heights
/// 3. For each terrain cell, deterministically select and place scatter objects
/// 4. Look up bounding volumes for each placed object
/// </summary>
public class ScatterSystem
{
// LandDefs constants (from ACE)
private const int VertexDim = 9; // 9×9 vertices per landblock
private const int BlockSide = 8; // 8×8 cells per landblock
private const float CellLength = 24.0f; // Each cell is 24m
private const float BlockLength = 192.0f;
// RegionDesc data (parsed once)
private List<ScatterTerrainType> _terrainTypes;
private List<ScatterSceneType> _sceneTypes;
private float[] _landHeightTable;
private bool _initialized;
// Scene cache (portal.dat scenes)
private Dictionary<uint, List<ScatterObjectDesc>> _sceneCache = new Dictionary<uint, List<ScatterObjectDesc>>();
// Reference to dat files
private DatDatabase _portalDat;
private DatDatabase _cellDat;
public bool IsInitialized => _initialized;
public List<string> DiagLog { get; } = new List<string>();
public bool Initialize(DatDatabase portalDat, DatDatabase cellDat)
{
_portalDat = portalDat;
_cellDat = cellDat;
try
{
// Parse RegionDesc (0x13000000) from portal.dat
byte[] regionData = portalDat.GetFileData(0x13000000);
if (regionData == null || regionData.Length < 100)
{
Log($"RegionDesc 0x13000000 not found in portal.dat (data={regionData?.Length ?? 0})");
return false;
}
Log($"RegionDesc: {regionData.Length} bytes loaded");
// Dump first few uint32s for debugging
string header = "RegionDesc header: ";
for (int i = 0; i < Math.Min(32, regionData.Length); i += 4)
header += $"0x{BitConverter.ToUInt32(regionData, i):X8} ";
Log(header);
if (!ParseRegionDesc(regionData))
{
Log("Failed to parse RegionDesc");
return false;
}
_initialized = true;
Log($"Scatter system ready: {_terrainTypes?.Count ?? 0} terrain types, {_sceneTypes?.Count ?? 0} scene types");
return true;
}
catch (Exception ex)
{
Log($"Scatter init error: {ex.Message}");
return false;
}
}
/// <summary>
/// Generates scatter object bounding volumes for a landblock.
/// Replicates ACE's Landblock.get_land_scenes() algorithm.
/// </summary>
public List<BoundingVolume> GetScatterVolumes(uint landblockKey, GeometryLoader geoLoader)
{
var volumes = new List<BoundingVolume>();
if (!_initialized || _terrainTypes == null || _sceneTypes == null)
return volumes;
try
{
// Read CellLandblock (0xXXYYFFFF) from cell.dat
uint cellLandblockId = (landblockKey << 16) | 0xFFFF;
byte[] data = _cellDat.GetFileData(cellLandblockId);
if (data == null || data.Length < 170) // Minimum: 4+4+81*2+81*1 = 255
return volumes;
// Parse terrain and height arrays
ushort[] terrain = new ushort[81];
byte[] height = new byte[81];
using (var ms = new MemoryStream(data))
using (var reader = new BinaryReader(ms))
{
uint id = reader.ReadUInt32();
uint hasObjects = reader.ReadUInt32();
for (int i = 0; i < 81; i++)
terrain[i] = reader.ReadUInt16();
for (int i = 0; i < 81; i++)
height[i] = reader.ReadByte();
}
// Compute block offsets (global cell coordinates)
uint blockX = ((landblockKey >> 8) & 0xFF) * 8;
uint blockY = (landblockKey & 0xFF) * 8;
float globalOffsetX = ((landblockKey >> 8) & 0xFF) * BlockLength;
float globalOffsetY = (landblockKey & 0xFF) * BlockLength;
int scatterCount = 0;
// Iterate all 81 terrain cells (matching ACE's get_land_scenes)
for (uint i = 0; i < 81; i++)
{
ushort t = terrain[i];
int terrainType = (t >> 2) & 0x1F; // 5 bits, 0-31
int sceneType = t >> 11; // 5 bits, 0-31
if (terrainType >= _terrainTypes.Count) continue;
var tt = _terrainTypes[terrainType];
if (sceneType >= tt.SceneTypeIndices.Count) continue;
int sceneInfoIdx = (int)tt.SceneTypeIndices[sceneType];
if (sceneInfoIdx >= _sceneTypes.Count) continue;
var scenes = _sceneTypes[sceneInfoIdx].SceneFileIds;
if (scenes.Count == 0) continue;
uint cellX = i / (uint)VertexDim;
uint cellY = i % (uint)VertexDim;
uint globalCellX = (uint)(cellX + blockX);
uint globalCellY = (uint)(cellY + blockY);
// Deterministic scene selection — uses uint32 overflow arithmetic
// matching AC client's C++ unsigned int behavior
uint cellMat = (uint)((long)globalCellY * (712977289L * globalCellX + 1813693831L) - 1109124029L * globalCellX + 2139937281L);
double offset = cellMat * 2.3283064e-10;
int sceneIdx = (int)(scenes.Count * offset);
if (sceneIdx < 0 || sceneIdx >= scenes.Count) sceneIdx = 0;
uint sceneId = scenes[sceneIdx];
// Load the Scene file
var sceneObjects = LoadScene(sceneId);
if (sceneObjects == null || sceneObjects.Count == 0) continue;
// Per-object noise seeds — uint32 overflow
uint cellXMat = (uint)(-1109124029L * globalCellX);
uint cellYMat = (uint)(1813693831L * globalCellY);
uint cellMat2 = (uint)(1360117743L * globalCellX * globalCellY + 1888038839L);
for (uint j = 0; j < sceneObjects.Count; j++)
{
var obj = sceneObjects[(int)j];
// Frequency check — uint32 overflow
double noise = (uint)(cellXMat + cellYMat - cellMat2 * (23399 + j)) * 2.3283064e-10;
if (noise >= obj.Freq || obj.WeenieObj != 0)
continue;
// Displace
var position = Displace(obj, globalCellX, globalCellY, j);
float lx = cellX * CellLength + position.X;
float ly = cellY * CellLength + position.Y;
// Bounds check
if (lx < 0 || ly < 0 || lx >= BlockLength || ly >= BlockLength)
continue;
// Get terrain height at this position
float z = GetTerrainHeight(height, lx, ly);
// World coordinates
float worldX = globalOffsetX + lx;
float worldY = globalOffsetY + ly;
// Get bounding volume for this object
var setupVolumes = geoLoader.GetSetupBoundingVolumesPublic(obj.ObjId);
foreach (var vol in setupVolumes)
{
// Create a frame for the scatter object
var frame = new Frame
{
OriginX = lx, OriginY = ly, OriginZ = z,
RotW = 1, RotX = 0, RotY = 0, RotZ = 0
};
// Apply rotation from scatter algorithm
ApplyScatterRotation(frame, obj, globalCellX, globalCellY, j);
var transformed = TransformScatterVolume(vol, frame, globalOffsetX, globalOffsetY);
if (transformed != null)
{
// Extend scatter volumes vertically to account for:
// 1. Terrain height imprecision (nearest-vertex vs polygon, can be 10-15m off)
// 2. Trees/rocks extend upward from ground level
// Use generous range to ensure ray intersection works
float extendBelow = 20.0f;
float extendAbove = 20.0f;
transformed.Min = new Vector3(transformed.Min.X, transformed.Min.Y, transformed.Min.Z - extendBelow);
transformed.Max = new Vector3(transformed.Max.X, transformed.Max.Y, transformed.Max.Z + extendAbove);
transformed.Center = new Vector3(transformed.Center.X, transformed.Center.Y,
(transformed.Min.Z + transformed.Max.Z) * 0.5f);
// Force AABB type so Min/Max Z extension is used by ray intersection
transformed.Type = BoundingVolume.VolumeType.AxisAlignedBox;
transformed.Dimensions = transformed.Max - transformed.Min;
volumes.Add(transformed);
}
}
scatterCount++;
}
}
if (scatterCount > 0)
Log($"Landblock 0x{landblockKey:X4}: {scatterCount} scatter objects -> {volumes.Count} volumes");
}
catch (Exception ex)
{
Log($"Scatter error for 0x{landblockKey:X4}: {ex.Message}");
}
return volumes;
}
// ===================================================================
// ObjectDesc.Displace — pseudo-random placement from ACE
// ===================================================================
private Vector3 Displace(ScatterObjectDesc obj, uint ix, uint iy, uint iq)
{
float x, y, z;
float locX = obj.BaseLocX, locY = obj.BaseLocY, locZ = obj.BaseLocZ;
// uint32 overflow arithmetic matching AC client C++ unsigned int
if (obj.DisplaceX <= 0)
x = locX;
else
x = (float)((uint)(1813693831L * iy - (iq + 45773) * (1360117743L * iy * ix + 1888038839L) - 1109124029L * ix)
* 2.3283064e-10 * obj.DisplaceX + locX);
if (obj.DisplaceY <= 0)
y = locY;
else
y = (float)((uint)(1813693831L * iy - (iq + 72719) * (1360117743L * iy * ix + 1888038839L) - 1109124029L * ix)
* 2.3283064e-10 * obj.DisplaceY + locY);
z = locZ;
double quadrant = (uint)(1813693831L * iy - ix * (1870387557L * iy + 1109124029L) - 402451965L) * 2.3283064e-10;
if (quadrant >= 0.75) return new Vector3(y, -x, z);
if (quadrant >= 0.5) return new Vector3(-x, -y, z);
if (quadrant >= 0.25) return new Vector3(-y, x, z);
return new Vector3(x, y, z);
}
private void ApplyScatterRotation(Frame frame, ScatterObjectDesc obj, uint x, uint y, uint k)
{
if (obj.MaxRotation > 0.0f)
{
float degrees = (float)((uint)(1813693831L * y - (k + 63127) * (1360117743L * y * x + 1888038839L) - 1109124029L * x) * 2.3283064e-10 * obj.MaxRotation);
float radians = degrees * (float)(Math.PI / 180.0);
float halfRad = radians * 0.5f;
frame.RotW = (float)Math.Cos(halfRad);
frame.RotZ = (float)Math.Sin(halfRad);
}
}
private float GetTerrainHeight(byte[] heights, float lx, float ly)
{
// Bilinear interpolation of height values
// LandHeightTable already contains actual in-game Z heights
// (the *2 factor from CellLandblock comments refers to raw bytes, not table values)
int ix = Math.Min((int)(lx / CellLength), BlockSide);
int iy = Math.Min((int)(ly / CellLength), BlockSide);
int idx = ix * VertexDim + iy;
if (idx >= 0 && idx < 81 && _landHeightTable != null)
{
byte h = heights[idx];
if (h < _landHeightTable.Length)
return _landHeightTable[h];
}
return 0;
}
private BoundingVolume TransformScatterVolume(BoundingVolume localVol, Frame placement,
float globalOffsetX, float globalOffsetY)
{
if (localVol == null) return null;
try
{
Vector3 worldCenter = placement.TransformPoint(localVol.Center);
worldCenter.X += globalOffsetX;
worldCenter.Y += globalOffsetY;
if (localVol.Type == BoundingVolume.VolumeType.Sphere)
{
float r = localVol.Dimensions.X;
return new BoundingVolume
{
Type = BoundingVolume.VolumeType.Sphere,
Center = worldCenter,
Dimensions = localVol.Dimensions,
Min = worldCenter - new Vector3(r, r, r),
Max = worldCenter + new Vector3(r, r, r),
IsDoor = false
};
}
// For non-sphere: transform corners to get new AABB
Vector3[] corners = {
new Vector3(localVol.Min.X, localVol.Min.Y, localVol.Min.Z),
new Vector3(localVol.Max.X, localVol.Min.Y, localVol.Min.Z),
new Vector3(localVol.Min.X, localVol.Max.Y, localVol.Min.Z),
new Vector3(localVol.Max.X, localVol.Max.Y, localVol.Min.Z),
new Vector3(localVol.Min.X, localVol.Min.Y, localVol.Max.Z),
new Vector3(localVol.Max.X, localVol.Min.Y, localVol.Max.Z),
new Vector3(localVol.Min.X, localVol.Max.Y, localVol.Max.Z),
new Vector3(localVol.Max.X, localVol.Max.Y, localVol.Max.Z),
};
Vector3 newMin = new Vector3(float.MaxValue, float.MaxValue, float.MaxValue);
Vector3 newMax = new Vector3(float.MinValue, float.MinValue, float.MinValue);
for (int c = 0; c < 8; c++)
{
Vector3 w = placement.TransformPoint(corners[c]);
w.X += globalOffsetX;
w.Y += globalOffsetY;
newMin = Vector3.Min(newMin, w);
newMax = Vector3.Max(newMax, w);
}
return new BoundingVolume
{
Type = BoundingVolume.VolumeType.AxisAlignedBox,
Center = (newMin + newMax) * 0.5f,
Dimensions = newMax - newMin,
Min = newMin,
Max = newMax,
IsDoor = false
};
}
catch { return null; }
}
// ===================================================================
// Scene loading
// ===================================================================
private List<ScatterObjectDesc> LoadScene(uint sceneId)
{
if (_sceneCache.TryGetValue(sceneId, out var cached))
return cached;
var objects = new List<ScatterObjectDesc>();
try
{
byte[] data = _portalDat.GetFileData(sceneId);
if (data == null || data.Length < 8)
{
_sceneCache[sceneId] = objects;
return objects;
}
using (var ms = new MemoryStream(data))
using (var reader = new BinaryReader(ms))
{
uint id = reader.ReadUInt32(); // Scene ID
// List<ObjectDesc>: uint32 count + count × ObjectDesc
uint numObjects = reader.ReadUInt32();
if (numObjects > 200) numObjects = 200;
for (uint i = 0; i < numObjects; i++)
{
if (ms.Position + 72 > ms.Length) break; // ObjectDesc is 72 bytes
var obj = new ScatterObjectDesc();
obj.ObjId = reader.ReadUInt32();
// Frame (BaseLoc): 7 floats
obj.BaseLocX = reader.ReadSingle();
obj.BaseLocY = reader.ReadSingle();
obj.BaseLocZ = reader.ReadSingle();
obj.BaseLocW = reader.ReadSingle();
obj.BaseLocRX = reader.ReadSingle();
obj.BaseLocRY = reader.ReadSingle();
obj.BaseLocRZ = reader.ReadSingle();
obj.Freq = reader.ReadSingle();
obj.DisplaceX = reader.ReadSingle();
obj.DisplaceY = reader.ReadSingle();
obj.MinScale = reader.ReadSingle();
obj.MaxScale = reader.ReadSingle();
obj.MaxRotation = reader.ReadSingle();
obj.MinSlope = reader.ReadSingle();
obj.MaxSlope = reader.ReadSingle();
obj.Align = reader.ReadUInt32();
obj.Orient = reader.ReadUInt32();
obj.WeenieObj = reader.ReadUInt32();
objects.Add(obj);
}
}
}
catch (Exception ex)
{
Log($"Scene 0x{sceneId:X8} parse error: {ex.Message}");
}
_sceneCache[sceneId] = objects;
return objects;
}
// ===================================================================
// RegionDesc parsing (0x13000000)
// ===================================================================
private bool ParseRegionDesc(byte[] data)
{
try
{
using (var ms = new MemoryStream(data))
using (var reader = new BinaryReader(ms))
{
uint id = reader.ReadUInt32(); // 0x13000000
uint regionNumber = reader.ReadUInt32();
uint version = reader.ReadUInt32();
Log($"RegionDesc: id=0x{id:X8}, region={regionNumber}, version={version}");
// PString RegionName ("Dereth")
SkipPString(reader, ms);
Log($"After RegionName: pos={ms.Position}");
// LandDefs
if (!ParseLandDefs(reader, ms))
{
Log($"LandDefs parse failed at pos={ms.Position}");
return ScanForTables(data);
}
Log($"After LandDefs: pos={ms.Position}");
// GameTime
if (!SkipGameTime(reader, ms))
{
Log($"GameTime skip failed at pos={ms.Position}");
return ScanForTables(data);
}
Log($"After GameTime: pos={ms.Position}");
// PartsMask
uint partsMask = reader.ReadUInt32();
Log($"PartsMask=0x{partsMask:X8}, pos={ms.Position}");
// Skip SkyDesc if present
if ((partsMask & 0x10) != 0)
{
Log("Skipping SkyDesc...");
if (!SkipSkyDesc(reader, ms))
{
Log($"SkyDesc skip failed at pos={ms.Position}, trying fallback");
return ScanForTables(data);
}
Log($"After SkyDesc: pos={ms.Position}");
}
// Skip SoundDesc if present
if ((partsMask & 0x01) != 0)
{
Log("Skipping SoundDesc...");
if (!SkipSoundDesc(reader, ms))
{
Log($"SoundDesc skip failed at pos={ms.Position}, trying fallback");
return ScanForTables(data);
}
Log($"After SoundDesc: pos={ms.Position}");
}
// Parse SceneDesc
if ((partsMask & 0x02) != 0)
{
Log("Parsing SceneDesc...");
if (!ParseSceneDesc(reader, ms))
{
Log($"SceneDesc parse failed at pos={ms.Position}, trying fallback");
return ScanForTables(data);
}
Log($"After SceneDesc: pos={ms.Position}");
}
// Parse TerrainDesc
Log("Parsing TerrainDesc...");
if (!ParseTerrainDesc(reader, ms))
{
Log($"TerrainDesc parse failed at pos={ms.Position}, trying fallback");
return ScanForTables(data);
}
Log($"RegionDesc parsed: {_terrainTypes?.Count} terrainTypes, {_sceneTypes?.Count} sceneTypes");
return _terrainTypes != null && _sceneTypes != null;
}
}
catch (Exception ex)
{
Log($"RegionDesc parse error at unknown pos: {ex.Message}");
return ScanForTables(data);
}
}
private bool ParseLandDefs(BinaryReader reader, MemoryStream ms)
{
if (ms.Position + 1056 > ms.Length) return false;
reader.ReadInt32(); // NumBlockLength
reader.ReadInt32(); // NumBlockWidth
reader.ReadSingle(); // SquareLength
reader.ReadInt32(); // LBlockLength
reader.ReadInt32(); // VertexPerCell
reader.ReadSingle(); // MaxObjHeight
reader.ReadSingle(); // SkyHeight
reader.ReadSingle(); // RoadWidth
_landHeightTable = new float[256];
for (int i = 0; i < 256; i++)
_landHeightTable[i] = reader.ReadSingle();
return true;
}
private bool SkipGameTime(BinaryReader reader, MemoryStream ms)
{
try
{
reader.ReadDouble(); // ZeroTimeOfYear
reader.ReadUInt32(); // ZeroYear
reader.ReadSingle(); // DayLength
reader.ReadUInt32(); // DaysPerYear
SkipPString(reader, ms); // YearSpec
// List<TimeOfDay> — uint32 count + entries
uint numTOD = reader.ReadUInt32();
if (numTOD > 100) return false;
for (uint i = 0; i < numTOD; i++)
{
reader.ReadSingle(); // Begin time
reader.ReadUInt32(); // IsNight flag
SkipPString(reader, ms); // Name
}
// DaysOfTheWeek — uint32 count + PStrings
uint numDays = reader.ReadUInt32();
if (numDays > 20) return false;
for (uint i = 0; i < numDays; i++)
SkipPString(reader, ms);
// List<Season> — uint32 count + entries
uint numSeasons = reader.ReadUInt32();
if (numSeasons > 20) return false;
for (uint i = 0; i < numSeasons; i++)
{
reader.ReadUInt32(); // StartDate
SkipPString(reader, ms); // Name
}
return true;
}
catch
{
return false;
}
}
private bool SkipSkyDesc(BinaryReader reader, MemoryStream ms)
{
// SkyDesc is complex (sky objects, colors, etc). Skip by searching for next recognizable section.
// Store position and try to skip it.
try
{
// SkyDesc format: TickSize(double) + LightTickSize(double) + DayGroup(SkyObjectReplace) + NightGroup + ...
// This is very complex. We'll use a heuristic: skip forward looking for SceneDesc signature.
// For now, try to skip a known minimum size
reader.ReadDouble(); // TickSize
reader.ReadDouble(); // LightTickSize
// DayGroup
SkipSkyObjectGroup(reader, ms);
// NightGroup
SkipSkyObjectGroup(reader, ms);
return true;
}
catch
{
return false;
}
}
private void SkipSkyObjectGroup(BinaryReader reader, MemoryStream ms)
{
// SkyObjectReplace: uint32 count + entries
uint count = reader.ReadUInt32();
for (uint i = 0; i < count && ms.Position < ms.Length; i++)
{
reader.ReadUInt32(); // object index
reader.ReadUInt32(); // GfxObj ID
reader.ReadSingle(); // rotate
reader.ReadSingle(); // transparent
reader.ReadSingle(); // luminosity
reader.ReadSingle(); // max bright
}
}
private bool SkipSoundDesc(BinaryReader reader, MemoryStream ms)
{
try
{
// SoundDesc: List<AmbientSoundDesc>
uint count = reader.ReadUInt32();
if (count > 200) return false;
for (uint i = 0; i < count && ms.Position < ms.Length; i++)
{
reader.ReadUInt32(); // SType
reader.ReadSingle(); // Volume
reader.ReadSingle(); // BaseChance
reader.ReadSingle(); // MinRate
reader.ReadSingle(); // MaxRate
}
return true;
}
catch
{
return false;
}
}
private bool ParseSceneDesc(BinaryReader reader, MemoryStream ms)
{
try
{
// SceneDesc: List<SceneType>
uint numSceneTypes = reader.ReadUInt32();
if (numSceneTypes > 500) return false;
_sceneTypes = new List<ScatterSceneType>();
for (uint i = 0; i < numSceneTypes; i++)
{
var st = new ScatterSceneType();
st.StbIndex = reader.ReadUInt32();
// List<uint> Scenes
uint numScenes = reader.ReadUInt32();
if (numScenes > 500) return false;
st.SceneFileIds = new List<uint>();
for (uint s = 0; s < numScenes; s++)
st.SceneFileIds.Add(reader.ReadUInt32());
_sceneTypes.Add(st);
}
Log($"SceneDesc: {_sceneTypes.Count} scene types parsed");
return true;
}
catch
{
return false;
}
}
private bool ParseTerrainDesc(BinaryReader reader, MemoryStream ms)
{
try
{
// TerrainDesc: List<TerrainType> + LandSurf
uint numTerrainTypes = reader.ReadUInt32();
if (numTerrainTypes > 100) return false;
_terrainTypes = new List<ScatterTerrainType>();
for (uint i = 0; i < numTerrainTypes; i++)
{
var tt = new ScatterTerrainType();
// PString TerrainName
SkipPString(reader, ms);
// uint32 TerrainColor
reader.ReadUInt32();
// List<uint> SceneTypes
uint numSceneTypes = reader.ReadUInt32();
if (numSceneTypes > 200) return false;
tt.SceneTypeIndices = new List<uint>();
for (uint s = 0; s < numSceneTypes; s++)
tt.SceneTypeIndices.Add(reader.ReadUInt32());
_terrainTypes.Add(tt);
}
Log($"TerrainDesc: {_terrainTypes.Count} terrain types parsed");
return true;
}
catch
{
return false;
}
}
// ===================================================================
// Fallback: scan RegionDesc data for recognizable table patterns
// ===================================================================
private bool ScanForTables(byte[] data)
{
Log("Attempting fallback scan for scatter tables...");
// Strategy: Scan for SceneDesc (uint32 count followed by entries with 0x12xxxxxx scene IDs)
// The real AC SceneDesc has ~89 entries. We require at least 20 to avoid false positives.
// TerrainDesc (~32 entries with PString names) follows right after SceneDesc.
for (int pos = 100; pos < data.Length - 100; pos += 4)
{
uint count = BitConverter.ToUInt32(data, pos);
if (count < 20 || count > 200) continue;
// Validate: try to read all entries as SceneType { uint32 StbIndex, uint32 numScenes, uint32[] sceneIds }
bool valid = true;
int scanPos = pos + 4;
int totalSceneIds = 0;
for (int i = 0; i < count && valid; i++)
{
if (scanPos + 8 > data.Length) { valid = false; break; }
uint stbIndex = BitConverter.ToUInt32(data, scanPos);
scanPos += 4;
uint numScenes = BitConverter.ToUInt32(data, scanPos);
scanPos += 4;
if (numScenes > 200) { valid = false; break; }
for (int s = 0; s < numScenes && valid; s++)
{
if (scanPos + 4 > data.Length) { valid = false; break; }
uint sceneId = BitConverter.ToUInt32(data, scanPos);
scanPos += 4;
// Scene files are 0x12xxxxxx
if ((sceneId & 0xFF000000) != 0x12000000) { valid = false; break; }
totalSceneIds++;
}
}
if (!valid || totalSceneIds < 10) continue;
// We found a candidate SceneDesc! Parse it fully.
_sceneTypes = new List<ScatterSceneType>();
int fullPos = pos + 4;
for (int i = 0; i < count; i++)
{
if (fullPos + 8 > data.Length) break;
uint stbIdx = BitConverter.ToUInt32(data, fullPos);
fullPos += 4;
uint nScenes = BitConverter.ToUInt32(data, fullPos);
fullPos += 4;
var st = new ScatterSceneType { StbIndex = stbIdx, SceneFileIds = new List<uint>() };
for (int s = 0; s < nScenes; s++)
{
if (fullPos + 4 > data.Length) break;
st.SceneFileIds.Add(BitConverter.ToUInt32(data, fullPos));
fullPos += 4;
}
_sceneTypes.Add(st);
}
Log($"Fallback found SceneDesc at offset {pos}: {_sceneTypes.Count} types, {totalSceneIds} total scene IDs");
// Now parse TerrainDesc starting right after SceneDesc
if (fullPos + 4 < data.Length)
{
if (ParseTerrainDescFromOffset(data, fullPos))
{
Log($"Fallback TerrainDesc succeeded: {_terrainTypes.Count} terrain types");
return true;
}
else
{
Log($"TerrainDesc failed at offset {fullPos}, continuing scan...");
_sceneTypes = null;
continue; // Try finding another SceneDesc
}
}
}
Log("Fallback scan failed to find scatter tables");
return false;
}
private bool ParseTerrainDescFromOffset(byte[] data, int startPos)
{
try
{
_terrainTypes = new List<ScatterTerrainType>();
int pos = startPos;
if (pos + 4 > data.Length) { _terrainTypes = null; return false; }
uint count = BitConverter.ToUInt32(data, pos);
pos += 4;
if (count < 5 || count > 100) { _terrainTypes = null; return false; }
for (int i = 0; i < count; i++)
{
var tt = new ScatterTerrainType();
// PString: ushort length + chars + align to 4
if (pos + 2 > data.Length) { _terrainTypes = null; return false; }
ushort strLen = BitConverter.ToUInt16(data, pos);
pos += 2;
if (strLen > 200 || pos + strLen > data.Length) { _terrainTypes = null; return false; }
// Verify it looks like a text string (ASCII printable)
if (i < 3 && strLen > 0)
{
bool isPrintable = true;
for (int c = 0; c < Math.Min((int)strLen, 10); c++)
{
byte b = data[pos + c];
if (b < 32 || b > 126) { isPrintable = false; break; }
}
if (!isPrintable) { _terrainTypes = null; return false; }
string name = System.Text.Encoding.ASCII.GetString(data, pos, strLen);
Log($" TerrainType[{i}]: \"{name}\"");
}
pos += strLen;
pos = (pos + 3) & ~3; // Align to 4
// uint32 TerrainColor
if (pos + 4 > data.Length) { _terrainTypes = null; return false; }
pos += 4;
// List<uint> SceneTypes
if (pos + 4 > data.Length) { _terrainTypes = null; return false; }
uint numST = BitConverter.ToUInt32(data, pos);
pos += 4;
if (numST > 200) { _terrainTypes = null; return false; }
tt.SceneTypeIndices = new List<uint>();
for (int s = 0; s < numST; s++)
{
if (pos + 4 > data.Length) { _terrainTypes = null; return false; }
tt.SceneTypeIndices.Add(BitConverter.ToUInt32(data, pos));
pos += 4;
}
_terrainTypes.Add(tt);
}
return _terrainTypes.Count >= 5;
}
catch
{
_terrainTypes = null;
return false;
}
}
// ===================================================================
// Helpers
// ===================================================================
private void SkipPString(BinaryReader reader, MemoryStream ms)
{
ushort len = reader.ReadUInt16();
if (len > 0 && ms.Position + len <= ms.Length)
ms.Seek(len, SeekOrigin.Current);
// Align to 4 bytes
long alignedPos = (ms.Position + 3) & ~3L;
if (alignedPos <= ms.Length)
ms.Position = alignedPos;
}
private void Log(string msg)
{
string line = $"[Scatter] {msg}";
System.Diagnostics.Debug.WriteLine(line);
if (DiagLog.Count < 100) DiagLog.Add(msg);
}
}
// ===================================================================
// Data structures for scatter system
// ===================================================================
public class ScatterTerrainType
{
public List<uint> SceneTypeIndices = new List<uint>();
}
public class ScatterSceneType
{
public uint StbIndex;
public List<uint> SceneFileIds = new List<uint>();
}
public class ScatterObjectDesc
{
public uint ObjId;
public float BaseLocX, BaseLocY, BaseLocZ;
public float BaseLocW, BaseLocRX, BaseLocRY, BaseLocRZ;
public float Freq;
public float DisplaceX, DisplaceY;
public float MinScale, MaxScale;
public float MaxRotation;
public float MinSlope, MaxSlope;
public uint Align, Orient, WeenieObj;
}
}

View file

@ -0,0 +1,364 @@
using Decal.Adapter;
using Decal.Adapter.Wrappers;
using System;
using System.Collections.Generic;
namespace NexSuite.Plugins.RynthAi.Raycasting
{
/// <summary>
/// Provides line-of-sight checking for the combat system.
/// Converts Decal API coordinates to global meter space and
/// performs raycasting against loaded landblock geometry.
///
/// Coordinate system:
/// AC uses a landblock grid where each block is 192×192 meters.
/// Landcell ID format: 0xXXYYnnnn where XX=east-west block, YY=north-south block.
/// LocationX/Y are local offsets within the landblock (0-192 meters).
///
/// We convert everything to "global meters" for raycasting:
/// GlobalX = (XX * 192) + LocationX
/// GlobalY = (YY * 192) + LocationY
/// GlobalZ = LocationZ (altitude, 0 = sea level)
/// </summary>
public class TargetingFSM
{
private readonly GeometryLoader _geoLoader;
private readonly BlacklistManager _blacklist;
// Attack type determines which raycast to use
public enum AttackType
{
Linear, // Bolts, streaks, crossbow bolts, melee
BowArc, // Bows — moderate arc, arrows go higher than you'd think
ThrownArc, // Thrown weapons, atlatls — similar arc to bows
MagicArc // War/Void magic Arc spells — same trajectory as missile weapons
}
// AC arrows arc noticeably — they go HIGH. A lower velocity = higher arc.
// At 70 yard range, arrows visibly arc 3-4 meters above the direct line.
// This must match the actual game trajectory to detect ceiling hits in dungeons.
public float BowArcVelocity { get; set; } = 25.0f;
// Thrown weapons arc similarly to bows
public float ThrownArcVelocity { get; set; } = 22.0f;
// Magic arc spells (War/Void Arc) have the same trajectory as missile weapons
public float MagicArcVelocity { get; set; } = 25.0f;
// If true, use arc checks for missile weapons. If false, treat all as linear.
public bool UseArcs { get; set; } = true;
// Max scan distance in meters. Only check LOS for targets within this range.
// Set from CombatManager based on MonsterRange + buffer.
public float MaxScanDistanceMeters { get; set; } = 120.0f;
public TargetingFSM(GeometryLoader geoLoader, BlacklistManager blacklist)
{
_geoLoader = geoLoader ?? throw new ArgumentNullException(nameof(geoLoader));
_blacklist = blacklist ?? throw new ArgumentNullException(nameof(blacklist));
}
/// <summary>
/// Checks if line-of-sight to a target is blocked by geometry.
///
/// Returns true if the target IS blocked (should skip this target).
/// Returns false if the target is clear to attack.
/// </summary>
public bool IsTargetBlocked(CoreManager core, WorldObject target, AttackType attackType)
{
if (core == null || target == null)
return false;
if (!_geoLoader.IsInitialized)
return false;
try
{
Vector3 origin = GetPlayerPosition(core);
if (origin == Vector3.Zero)
return false;
Vector3 targetPos = GetObjectPosition(target, core);
if (targetPos == Vector3.Zero)
return false;
// Early-out: skip raycast if target is beyond scan distance
float dx = targetPos.X - origin.X;
float dy = targetPos.Y - origin.Y;
float flatDist = (float)Math.Sqrt(dx * dx + dy * dy);
if (flatDist > MaxScanDistanceMeters)
return false; // Too far to bother checking, let combat handle range
// Offset to chest height
origin.Z += 1.0f;
targetPos.Z += 1.0f;
uint landcell = GetPlayerLandcell(core);
uint cellPart = landcell & 0xFFFF;
bool isDungeon = cellPart >= 0x0100;
// Force linear checks indoors — arc trajectories hit ceilings
if (isDungeon)
attackType = AttackType.Linear;
var geometry = _geoLoader.GetLandblockGeometry(landcell);
if (geometry == null || geometry.Count == 0)
return false;
// Pre-filter: skip full ray test if no geometry near the path
float margin = Math.Min(flatDist * 0.3f, 15.0f);
margin = Math.Max(margin, 3.0f);
if (!RaycastEngine.HasNearbyGeometry(origin, targetPos, geometry, margin))
return false;
switch (attackType)
{
case AttackType.Linear:
return RaycastEngine.IsLinearPathBlocked(origin, targetPos, geometry);
case AttackType.BowArc:
if (UseArcs)
{
if (!RaycastEngine.IsArcPathBlocked(origin, targetPos, BowArcVelocity, geometry))
return false;
return RaycastEngine.IsLinearPathBlocked(origin, targetPos, geometry);
}
return RaycastEngine.IsLinearPathBlocked(origin, targetPos, geometry);
case AttackType.ThrownArc:
if (UseArcs)
{
if (!RaycastEngine.IsArcPathBlocked(origin, targetPos, ThrownArcVelocity, geometry))
return false;
return RaycastEngine.IsLinearPathBlocked(origin, targetPos, geometry);
}
return RaycastEngine.IsLinearPathBlocked(origin, targetPos, geometry);
case AttackType.MagicArc:
// Magic Arc spells have the same trajectory as missile weapons
if (UseArcs && !isDungeon) // Don't arc-check in dungeons (ceiling clips)
{
if (!RaycastEngine.IsArcPathBlocked(origin, targetPos, MagicArcVelocity, geometry))
return false;
return RaycastEngine.IsLinearPathBlocked(origin, targetPos, geometry);
}
return RaycastEngine.IsLinearPathBlocked(origin, targetPos, geometry);
default:
return false;
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"[Targeting] Error checking LOS: {ex.Message}");
return false;
}
}
/// <summary>
/// Finds the best unblocked target from a list of candidates.
/// Returns the target ID, or 0 if no clear target is found.
/// </summary>
public int FindBestTarget(CoreManager core, List<WorldObject> candidates, AttackType attackType)
{
if (core == null || candidates == null || candidates.Count == 0)
return 0;
foreach (var candidate in candidates)
{
try
{
int id = candidate.Id;
// Skip blacklisted targets
if (_blacklist.IsBlacklisted(id))
continue;
// Skip blocked targets
if (IsTargetBlocked(core, candidate, attackType))
{
System.Diagnostics.Debug.WriteLine($"[Targeting] Target {id} blocked by geometry, skipping");
continue;
}
return id; // Found a clear target
}
catch
{
continue;
}
}
return 0; // No clear targets
}
/// <summary>
/// Gets the player's position in global meter coordinates.
/// Uses Decal's HooksWrapper (accessed via CoreManager.Actions).
///
/// Landcell format: 0xXXYYnnnn
/// XX = east-west block index (0-254)
/// YY = north-south block index (0-254)
///
/// LocationX/Y = offset within landblock (0-192 meters for outdoors)
/// LocationZ = altitude in meters (0 = sea level)
///
/// Global conversion:
/// GlobalX = XX * 192 + LocationX
/// GlobalY = YY * 192 + LocationY
/// GlobalZ = LocationZ
/// </summary>
private Vector3 GetPlayerPosition(CoreManager core)
{
try
{
uint landcell = (uint)core.Actions.Landcell;
uint blockX = (landcell >> 24) & 0xFF;
uint blockY = (landcell >> 16) & 0xFF;
float localX = (float)core.Actions.LocationX;
float localY = (float)core.Actions.LocationY;
float localZ = (float)core.Actions.LocationZ;
float globalX = blockX * 192.0f + localX;
float globalY = blockY * 192.0f + localY;
return new Vector3(globalX, globalY, localZ);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"[Targeting] Error getting player pos: {ex.Message}");
return Vector3.Zero;
}
}
/// <summary>
/// Gets a world object's position in global meter coordinates.
/// Uses Decal's CoordsObject (EastWest/NorthSouth) and converts to meters.
///
/// From Decal docs:
/// EW = ((Landcell >> 24) + LocationX / 24.0 - 1019.5) / 10.0
/// NS = (((Landcell >> 16) & 0xFF) + LocationY / 24.0 - 1019.5) / 10.0
///
/// Reverse conversion (EW/NS → global meters):
/// GlobalX = (EW * 10.0 + 1019.5) * 24.0
/// GlobalY = (NS * 10.0 + 1019.5) * 24.0
/// </summary>
private Vector3 GetObjectPosition(WorldObject obj, CoreManager core)
{
try
{
var coords = obj.Coordinates();
if (coords == null)
return Vector3.Zero;
double ew = coords.EastWest;
double ns = coords.NorthSouth;
float globalX = (float)((ew * 10.0 + 1019.5) * 24.0);
float globalY = (float)((ns * 10.0 + 1019.5) * 24.0);
// Z coordinate: MUST come from RawCoordinates.
// If unavailable, return Zero to skip LOS (safer than guessing wrong Z).
float z = 0;
try
{
var raw = obj.RawCoordinates();
if (raw != null)
z = (float)raw.Z;
else
return Vector3.Zero; // Can't determine Z — skip LOS
}
catch
{
return Vector3.Zero; // Can't determine Z — skip LOS
}
return new Vector3(globalX, globalY, z);
}
catch
{
return Vector3.Zero;
}
}
/// <summary>
/// Gets the player's current Landcell value for geometry lookup.
/// </summary>
private uint GetPlayerLandcell(CoreManager core)
{
try
{
return (uint)core.Actions.Landcell;
}
catch
{
return 0;
}
}
/// <summary>
/// Determines the attack type based on combat mode and wielded weapon.
/// Magic mode ALWAYS returns Linear (spells travel straight).
/// Bows get a flat arc (high velocity). Thrown weapons arc more.
/// Melee and crossbows are Linear.
/// </summary>
public AttackType DetermineAttackType(CoreManager core)
{
try
{
// MAGIC MODE: Always linear — spells (bolts, streaks, arcs, rings)
// all use straight-line LOS in AC, regardless of equipped weapon
if (core.Actions.CombatMode == CombatState.Magic)
return AttackType.Linear;
// PEACE MODE: Default to linear
if (core.Actions.CombatMode == CombatState.Peace)
return AttackType.Linear;
// MELEE MODE: Linear (range check only, no projectile arc)
if (core.Actions.CombatMode == CombatState.Melee)
return AttackType.Linear;
// MISSILE MODE: Check the actual weapon for bow vs crossbow vs thrown
foreach (var wo in core.WorldFilter.GetInventory())
{
if (wo.Values((LongValueKey)10, 0) > 0) // CurrentWieldedLocation
{
if (wo.ObjectClass == ObjectClass.MissileWeapon)
{
string name = wo.Name?.ToLower() ?? "";
// Crossbows fire bolts in a straight line
if (name.Contains("crossbow"))
return AttackType.Linear;
// Atlatls and thrown weapons arc more
if (name.Contains("atlatl") || name.Contains("thrown") || name.Contains("dart"))
return UseArcs ? AttackType.ThrownArc : AttackType.Linear;
// Regular bows — fast, flat arc
if (name.Contains("bow"))
return UseArcs ? AttackType.BowArc : AttackType.Linear;
// Unknown missile weapon — treat as bow arc
return UseArcs ? AttackType.BowArc : AttackType.Linear;
}
// Wand in missile mode? Shouldn't happen, but treat as linear
if (wo.ObjectClass == ObjectClass.WandStaffOrb)
return AttackType.Linear;
}
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"[Targeting] Error determining attack type: {ex.Message}");
}
return AttackType.Linear; // Default to linear
}
}
}

View file

@ -0,0 +1,143 @@
using System;
namespace NexSuite.Plugins.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();
}
}
}
}
}