feat: port aelrynth 2026.9.27.2 snapshot onto GitHub history

Overlay upstream/main (9b5e276) onto BlankenshipG main without rewriting
history. Keep origin-only Decal/plugin/docs trees. Re-apply aelrynth.com
and sibling-fork URL fixes that aelrynth git still has as tombohar links.

Co-authored-by: BlankenshipG <BlankenshipG@users.noreply.github.com>
This commit is contained in:
Cursor Agent 2026-10-04 15:43:50 +00:00
commit 4ddbb52eb2
No known key found for this signature in database
244 changed files with 59710 additions and 3067 deletions

View file

@ -0,0 +1,395 @@
using System;
using System.Collections.Generic;
using System.IO;
namespace RynthCore2.TerrainData;
/// <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();
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
/// <summary>Dat header FileType field.</summary>
public uint FileType { get; private set; }
/// <summary>Block size in bytes (typical: 1024).</summary>
public uint BlockSize { get; private set; }
/// <summary>Total file size from header.</summary>
public uint FileSize { get; private set; }
/// <summary>DataSet field from header.</summary>
public uint DataSet { get; private set; }
/// <summary>Byte offset of the root B-tree node.</summary>
public uint BTreeRoot { get; private set; }
/// <summary>True once <see cref="Open"/> completes successfully.</summary>
public bool IsLoaded { get; private set; }
/// <summary>Source file path passed to <see cref="Open"/>.</summary>
public string? FilePath { get; private set; }
/// <summary>Number of files indexed from the B-tree.</summary>
public int RecordCount { get; private set; }
// All files indexed by ObjectId (populated during Open)
private readonly Dictionary<uint, DatBTreeEntry> _allFiles = new();
/// <summary>Most-recent diagnostic messages (capped at 100).</summary>
public List<string> DiagLog { get; } = new();
/// <summary>
/// Opens the .dat file at <paramref name="path"/> for read-only random access and
/// indexes every entry in the B-tree. Returns false on any failure.
/// </summary>
public bool Open(string path)
{
try
{
if (!File.Exists(path))
{
Log($"File not found: {path}");
return false;
}
FilePath = path;
// Plugin init runs *before* acclient.exe opens its own DAT files,
// so our handle is the first one Windows sees on the file. Our
// share-mode dictates what AC's subsequent open can request — if
// we omit FileShare.Delete, AC's open (which needs delete-rename
// semantics for DDD/patcher) fails with a sharing violation and
// the AC client errors out with "cannot access the data files."
//
// FileShare.ReadWrite | FileShare.Delete = permit other openers
// to read, write, and delete-mark the file. RandomAccess hint +
// 4 KB buffer keeps the .dat B-tree reads efficient.
_stream = new FileStream(
path,
FileMode.Open,
FileAccess.Read,
FileShare.ReadWrite | FileShare.Delete,
bufferSize: 4096,
options: FileOptions.RandomAccess);
Log($"File: {Path.GetFileName(path)}, Size: {_stream.Length:N0} bytes");
if (!ReadHeader())
{
Close();
return false;
}
// Read the entire B-tree directory and index all files
ReadDirectory(BTreeRoot);
RecordCount = _allFiles.Count;
IsLoaded = true;
Log($"SUCCESS: {RecordCount} files indexed, BlockSize={BlockSize}, Root=0x{BTreeRoot:X8}");
return true;
}
catch (Exception ex)
{
Log($"Error: {ex.Message}");
Close();
return false;
}
}
/// <summary>
/// Reads the dat header from offset 0x140.
/// Format matches ACE's DatDatabaseHeader.Unpack().
/// </summary>
private bool ReadHeader()
{
if (_stream == null) return false;
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();
_ = reader.ReadUInt32(); // dataSubset (unused)
_ = reader.ReadUInt32(); // freeHead (unused)
_ = reader.ReadUInt32(); // freeTail (unused)
_ = reader.ReadUInt32(); // freeCount (unused)
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 (_stream == null) return null;
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 (_stream == null) return;
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);
}
}
/// <summary>Convenience: find by id then read.</summary>
public byte[]? GetFileData(uint fileId)
{
var entry = FindFile(fileId);
return entry != null ? ReadFileData(entry) : null;
}
/// <summary>Returns (fileId, storedSize) for every indexed file whose id is in [lo, hi], sorted by size desc.</summary>
public List<(uint id, uint size)> EntriesInRange(uint lo, uint hi)
{
var list = new List<(uint, uint)>();
if (!IsLoaded) return list;
foreach (var kv in _allFiles)
if (kv.Key >= lo && kv.Key <= hi)
list.Add((kv.Key, kv.Value.FileSize));
list.Sort((a, b) => b.Item2.CompareTo(a.Item2));
return list;
}
/// <summary>
/// Returns all interior cell IDs (0x0100–0xFFFD) for a given landblock from the dat index.
/// This avoids the sequential scan gap cutoff that misses cells in large dungeons.
/// </summary>
public List<uint> GetLandblockCellIds(uint landblockKey)
{
var cellIds = new List<uint>();
if (!IsLoaded) return cellIds;
uint prefix = landblockKey << 16;
foreach (var id in _allFiles.Keys)
{
if ((id & 0xFFFF0000) != prefix) continue;
uint cell = id & 0xFFFF;
if (cell >= 0x0100 && cell <= 0xFFFD)
cellIds.Add(id);
}
return cellIds;
}
/// <summary>
/// Returns sample file IDs from the index for diagnostics.
/// </summary>
public List<uint> GetSampleIds(int maxCount = 20)
{
var ids = new List<uint>();
foreach (var kvp in _allFiles)
{
ids.Add(kvp.Key);
if (ids.Count >= maxCount) break;
}
return ids;
}
/// <summary>Closes the underlying file handle and clears the index.</summary>
public void Close()
{
_stream?.Dispose();
_stream = null;
IsLoaded = false;
_allFiles.Clear();
}
/// <inheritdoc/>
public void Dispose()
{
Close();
GC.SuppressFinalize(this);
}
private void Log(string msg)
{
string line = $"[DatDB] {msg}";
System.Diagnostics.Debug.WriteLine(line);
if (DiagLog.Count < 100) DiagLog.Add(line);
}
}
/// <summary>Indexed B-tree entry for one file inside a .dat archive.</summary>
public class DatBTreeEntry
{
/// <summary>Raw flag bits from the B-tree.</summary>
public uint BitFlags { get; set; }
/// <summary>Object ID (the file's key in the B-tree).</summary>
public uint ObjectId { get; set; }
/// <summary>Byte offset of the first block of the file's chain.</summary>
public uint FileOffset { get; set; }
/// <summary>Logical file size in bytes.</summary>
public uint FileSize { get; set; }
}

View file

@ -0,0 +1,442 @@
// #region License
// /*
// Microsoft Public License (Ms-PL)
// MonoGame - Copyright © 2009 The MonoGame Team
//
// All rights reserved.
//
// This license governs use of the accompanying software. If you use the software, you accept this license. If you do not
// accept the license, do not use the software.
//
// 1. Definitions
// The terms "reproduce," "reproduction," "derivative works," and "distribution" have the same meaning here as under
// U.S. copyright law.
//
// A "contribution" is the original software, or any additions or changes to the software.
// A "contributor" is any person that distributes its contribution under this license.
// "Licensed patents" are a contributor's patent claims that read directly on its contribution.
//
// 2. Grant of Rights
// (A) Copyright Grant- Subject to the terms of this license, including the license conditions and limitations in section 3,
// each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create.
// (B) Patent Grant- Subject to the terms of this license, including the license conditions and limitations in section 3,
// each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software.
//
// 3. Conditions and Limitations
// (A) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or trademarks.
// (B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software,
// your patent license from such contributor to the software ends automatically.
// (C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution
// notices that are present in the software.
// (D) If you distribute any portion of the software in source code form, you may do so only under this license by including
// a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object
// code form, you may only do so under a license that complies with this license.
// (E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees
// or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent
// permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular
// purpose and non-infringement.
// */
// #endregion License
//
namespace ACE.DatLoader
{
using System.IO;
public static class DxtUtil
{
internal static byte[] DecompressDxt1(byte[] imageData, int width, int height)
{
using (MemoryStream imageStream = new MemoryStream(imageData))
return DecompressDxt1(imageStream, width, height);
}
internal static byte[] DecompressDxt1(Stream imageStream, int width, int height)
{
byte[] imageData = new byte[width * height * 4];
using (BinaryReader imageReader = new BinaryReader(imageStream))
{
int blockCountX = (width + 3) / 4;
int blockCountY = (height + 3) / 4;
for (int y = 0; y < blockCountY; y++)
{
for (int x = 0; x < blockCountX; x++)
{
DecompressDxt1Block(imageReader, x, y, blockCountX, width, height, imageData);
}
}
}
return imageData;
}
private static void DecompressDxt1Block(BinaryReader imageReader, int x, int y, int blockCountX, int width, int height, byte[] imageData)
{
ushort c0 = imageReader.ReadUInt16();
ushort c1 = imageReader.ReadUInt16();
byte r0, g0, b0;
byte r1, g1, b1;
ConvertRgb565ToRgb888(c0, out r0, out g0, out b0);
ConvertRgb565ToRgb888(c1, out r1, out g1, out b1);
uint lookupTable = imageReader.ReadUInt32();
for (int blockY = 0; blockY < 4; blockY++)
{
for (int blockX = 0; blockX < 4; blockX++)
{
byte r = 0, g = 0, b = 0, a = 255;
uint index = (lookupTable >> 2 * (4 * blockY + blockX)) & 0x03;
if (c0 > c1)
{
switch (index)
{
case 0:
r = r0;
g = g0;
b = b0;
break;
case 1:
r = r1;
g = g1;
b = b1;
break;
case 2:
r = (byte)((2 * r0 + r1) / 3);
g = (byte)((2 * g0 + g1) / 3);
b = (byte)((2 * b0 + b1) / 3);
break;
case 3:
r = (byte)((r0 + 2 * r1) / 3);
g = (byte)((g0 + 2 * g1) / 3);
b = (byte)((b0 + 2 * b1) / 3);
break;
}
}
else
{
switch (index)
{
case 0:
r = r0;
g = g0;
b = b0;
break;
case 1:
r = r1;
g = g1;
b = b1;
break;
case 2:
r = (byte)((r0 + r1) / 2);
g = (byte)((g0 + g1) / 2);
b = (byte)((b0 + b1) / 2);
break;
case 3:
r = 0;
g = 0;
b = 0;
a = 0;
break;
}
}
int px = (x << 2) + blockX;
int py = (y << 2) + blockY;
if ((px < width) && (py < height))
{
int offset = ((py * width) + px) << 2;
imageData[offset] = r;
imageData[offset + 1] = g;
imageData[offset + 2] = b;
imageData[offset + 3] = a;
}
}
}
}
internal static byte[] DecompressDxt3(byte[] imageData, int width, int height)
{
using (MemoryStream imageStream = new MemoryStream(imageData))
return DecompressDxt3(imageStream, width, height);
}
internal static byte[] DecompressDxt3(Stream imageStream, int width, int height)
{
byte[] imageData = new byte[width * height * 4];
using (BinaryReader imageReader = new BinaryReader(imageStream))
{
int blockCountX = (width + 3) / 4;
int blockCountY = (height + 3) / 4;
for (int y = 0; y < blockCountY; y++)
{
for (int x = 0; x < blockCountX; x++)
{
DecompressDxt3Block(imageReader, x, y, blockCountX, width, height, imageData);
}
}
}
return imageData;
}
private static void DecompressDxt3Block(BinaryReader imageReader, int x, int y, int blockCountX, int width, int height, byte[] imageData)
{
byte a0 = imageReader.ReadByte();
byte a1 = imageReader.ReadByte();
byte a2 = imageReader.ReadByte();
byte a3 = imageReader.ReadByte();
byte a4 = imageReader.ReadByte();
byte a5 = imageReader.ReadByte();
byte a6 = imageReader.ReadByte();
byte a7 = imageReader.ReadByte();
ushort c0 = imageReader.ReadUInt16();
ushort c1 = imageReader.ReadUInt16();
byte r0, g0, b0;
byte r1, g1, b1;
ConvertRgb565ToRgb888(c0, out r0, out g0, out b0);
ConvertRgb565ToRgb888(c1, out r1, out g1, out b1);
uint lookupTable = imageReader.ReadUInt32();
int alphaIndex = 0;
for (int blockY = 0; blockY < 4; blockY++)
{
for (int blockX = 0; blockX < 4; blockX++)
{
byte r = 0, g = 0, b = 0, a = 0;
uint index = (lookupTable >> 2 * (4 * blockY + blockX)) & 0x03;
switch (alphaIndex)
{
case 0:
a = (byte)((a0 & 0x0F) | ((a0 & 0x0F) << 4));
break;
case 1:
a = (byte)((a0 & 0xF0) | ((a0 & 0xF0) >> 4));
break;
case 2:
a = (byte)((a1 & 0x0F) | ((a1 & 0x0F) << 4));
break;
case 3:
a = (byte)((a1 & 0xF0) | ((a1 & 0xF0) >> 4));
break;
case 4:
a = (byte)((a2 & 0x0F) | ((a2 & 0x0F) << 4));
break;
case 5:
a = (byte)((a2 & 0xF0) | ((a2 & 0xF0) >> 4));
break;
case 6:
a = (byte)((a3 & 0x0F) | ((a3 & 0x0F) << 4));
break;
case 7:
a = (byte)((a3 & 0xF0) | ((a3 & 0xF0) >> 4));
break;
case 8:
a = (byte)((a4 & 0x0F) | ((a4 & 0x0F) << 4));
break;
case 9:
a = (byte)((a4 & 0xF0) | ((a4 & 0xF0) >> 4));
break;
case 10:
a = (byte)((a5 & 0x0F) | ((a5 & 0x0F) << 4));
break;
case 11:
a = (byte)((a5 & 0xF0) | ((a5 & 0xF0) >> 4));
break;
case 12:
a = (byte)((a6 & 0x0F) | ((a6 & 0x0F) << 4));
break;
case 13:
a = (byte)((a6 & 0xF0) | ((a6 & 0xF0) >> 4));
break;
case 14:
a = (byte)((a7 & 0x0F) | ((a7 & 0x0F) << 4));
break;
case 15:
a = (byte)((a7 & 0xF0) | ((a7 & 0xF0) >> 4));
break;
}
++alphaIndex;
switch (index)
{
case 0:
r = r0;
g = g0;
b = b0;
break;
case 1:
r = r1;
g = g1;
b = b1;
break;
case 2:
r = (byte)((2 * r0 + r1) / 3);
g = (byte)((2 * g0 + g1) / 3);
b = (byte)((2 * b0 + b1) / 3);
break;
case 3:
r = (byte)((r0 + 2 * r1) / 3);
g = (byte)((g0 + 2 * g1) / 3);
b = (byte)((b0 + 2 * b1) / 3);
break;
}
int px = (x << 2) + blockX;
int py = (y << 2) + blockY;
if ((px < width) && (py < height))
{
int offset = ((py * width) + px) << 2;
imageData[offset] = r;
imageData[offset + 1] = g;
imageData[offset + 2] = b;
imageData[offset + 3] = a;
}
}
}
}
internal static byte[] DecompressDxt5(byte[] imageData, int width, int height)
{
using (MemoryStream imageStream = new MemoryStream(imageData))
return DecompressDxt5(imageStream, width, height);
}
internal static byte[] DecompressDxt5(Stream imageStream, int width, int height)
{
byte[] imageData = new byte[width * height * 4];
using (BinaryReader imageReader = new BinaryReader(imageStream))
{
int blockCountX = (width + 3) / 4;
int blockCountY = (height + 3) / 4;
for (int y = 0; y < blockCountY; y++)
{
for (int x = 0; x < blockCountX; x++)
{
DecompressDxt5Block(imageReader, x, y, blockCountX, width, height, imageData);
}
}
}
return imageData;
}
private static void DecompressDxt5Block(BinaryReader imageReader, int x, int y, int blockCountX, int width, int height, byte[] imageData)
{
byte alpha0 = imageReader.ReadByte();
byte alpha1 = imageReader.ReadByte();
ulong alphaMask = (ulong)imageReader.ReadByte();
alphaMask += (ulong)imageReader.ReadByte() << 8;
alphaMask += (ulong)imageReader.ReadByte() << 16;
alphaMask += (ulong)imageReader.ReadByte() << 24;
alphaMask += (ulong)imageReader.ReadByte() << 32;
alphaMask += (ulong)imageReader.ReadByte() << 40;
ushort c0 = imageReader.ReadUInt16();
ushort c1 = imageReader.ReadUInt16();
byte r0, g0, b0;
byte r1, g1, b1;
ConvertRgb565ToRgb888(c0, out r0, out g0, out b0);
ConvertRgb565ToRgb888(c1, out r1, out g1, out b1);
uint lookupTable = imageReader.ReadUInt32();
for (int blockY = 0; blockY < 4; blockY++)
{
for (int blockX = 0; blockX < 4; blockX++)
{
byte r = 0, g = 0, b = 0, a = 255;
uint index = (lookupTable >> 2 * (4 * blockY + blockX)) & 0x03;
uint alphaIndex = (uint)((alphaMask >> 3 * (4 * blockY + blockX)) & 0x07);
if (alphaIndex == 0)
{
a = alpha0;
}
else if (alphaIndex == 1)
{
a = alpha1;
}
else if (alpha0 > alpha1)
{
a = (byte)(((8 - alphaIndex) * alpha0 + (alphaIndex - 1) * alpha1) / 7);
}
else if (alphaIndex == 6)
{
a = 0;
}
else if (alphaIndex == 7)
{
a = 0xff;
}
else
{
a = (byte)(((6 - alphaIndex) * alpha0 + (alphaIndex - 1) * alpha1) / 5);
}
switch (index)
{
case 0:
r = r0;
g = g0;
b = b0;
break;
case 1:
r = r1;
g = g1;
b = b1;
break;
case 2:
r = (byte)((2 * r0 + r1) / 3);
g = (byte)((2 * g0 + g1) / 3);
b = (byte)((2 * b0 + b1) / 3);
break;
case 3:
r = (byte)((r0 + 2 * r1) / 3);
g = (byte)((g0 + 2 * g1) / 3);
b = (byte)((b0 + 2 * b1) / 3);
break;
}
int px = (x << 2) + blockX;
int py = (y << 2) + blockY;
if ((px < width) && (py < height))
{
int offset = ((py * width) + px) << 2;
imageData[offset] = r;
imageData[offset + 1] = g;
imageData[offset + 2] = b;
imageData[offset + 3] = a;
}
}
}
}
private static void ConvertRgb565ToRgb888(ushort color, out byte r, out byte g, out byte b)
{
int temp;
temp = (color >> 11) * 255 + 16;
r = (byte)((temp / 32 + temp) / 32);
temp = ((color & 0x07E0) >> 5) * 255 + 32;
g = (byte)((temp / 64 + temp) / 64);
temp = (color & 0x001F) * 255 + 16;
b = (byte)((temp / 32 + temp) / 32);
}
}
}

View file

@ -0,0 +1,115 @@
using ACE.DatLoader;
using RynthCore2.TerrainData;
namespace RynthCore.StatusAgent;
/// <summary>
/// Decodes an AC item ICON to RGBA pixels. An item's icon DID (PWD _iconID, range 0x06xxxxxx) points
/// straight at a 0x06 Texture in portal.dat, so this is the Texture path only — trimmed from
/// AcClientReborn's AcTextureDecoder (no Surface/SurfaceTexture/clothing). Format byte-layout + the
/// format constants are ported verbatim from ACEmulator's DatLoader.
/// </summary>
internal sealed class IconDecoder
{
private readonly DatDatabase _portal;
public IconDecoder(DatDatabase portal) { _portal = portal; }
/// <summary>Decoded RGBA bitmap (Pixels = w*h*4, bytes in R,G,B,A order).</summary>
public sealed class Rgba
{
public int Width;
public int Height;
public byte[] Pixels = System.Array.Empty<byte>();
}
// Palette (0x04): Id(u32), Colors(List<uint>: i32 count + u32[] ARGB).
private uint[]? LoadPalette(uint paletteId)
{
byte[]? data = _portal.GetFileData(paletteId);
if (data == null || data.Length < 8) return null;
using var ms = new MemoryStream(data);
using var r = new BinaryReader(ms);
r.ReadUInt32();
int n = r.ReadInt32();
if (n <= 0 || n > 100000) return null;
var pal = new uint[n];
for (int i = 0; i < n; i++)
{
if (ms.Position + 4 > ms.Length) { System.Array.Resize(ref pal, i); break; }
pal[i] = r.ReadUInt32();
}
return pal;
}
// Texture (0x06): Id(u32),Unknown(i32),Width(i32),Height(i32),Format(u32),Length(i32),Source[Length],
// if INDEX16/P8: DefaultPaletteId(u32).
public Rgba? Decode(uint textureId)
{
byte[]? data = _portal.GetFileData(textureId);
if (data == null || data.Length < 24) return null;
using var ms = new MemoryStream(data);
using var r = new BinaryReader(ms);
r.ReadUInt32(); r.ReadInt32();
int w = r.ReadInt32(), h = r.ReadInt32();
uint fmt = r.ReadUInt32();
int len = r.ReadInt32();
if (w <= 0 || h <= 0 || w > 4096 || h > 4096 || len < 0 || ms.Position + len > ms.Length) return null;
byte[] src = r.ReadBytes(len);
uint defPal = 0;
if (fmt == 101 /*INDEX16*/ || fmt == 41 /*P8*/) { if (ms.Position + 4 <= ms.Length) defPal = r.ReadUInt32(); }
var rgba = new byte[w * h * 4];
void Px(int i, int rr, int gg, int bb, int aa) { int o = i * 4; rgba[o] = (byte)rr; rgba[o + 1] = (byte)gg; rgba[o + 2] = (byte)bb; rgba[o + 3] = (byte)aa; }
switch (fmt)
{
case 827611204: return Wrap(DxtUtil.DecompressDxt1(src, w, h), w, h); // DXT1
case 861165636: return Wrap(DxtUtil.DecompressDxt3(src, w, h), w, h); // DXT3
case 894720068: return Wrap(DxtUtil.DecompressDxt5(src, w, h), w, h); // DXT5
case 20: // R8G8B8 (stored B,G,R)
for (int i = 0; i < w * h && i * 3 + 2 < src.Length; i++) Px(i, src[i * 3 + 2], src[i * 3 + 1], src[i * 3], 255);
break;
case 243: // CUSTOM_LSCAPE_R8G8B8 (stored R,G,B)
for (int i = 0; i < w * h && i * 3 + 2 < src.Length; i++) Px(i, src[i * 3], src[i * 3 + 1], src[i * 3 + 2], 255);
break;
case 21: // A8R8G8B8
case 22: // X8R8G8B8
for (int i = 0; i < w * h && i * 4 + 3 < src.Length; i++)
{ int b = src[i * 4], g = src[i * 4 + 1], rr = src[i * 4 + 2], a = fmt == 22 ? 255 : src[i * 4 + 3]; Px(i, rr, g, b, a); }
break;
case 23: // R5G6B5
for (int i = 0; i < w * h && i * 2 + 1 < src.Length; i++)
{ ushort v = (ushort)(src[i * 2] | (src[i * 2 + 1] << 8)); Px(i, ((v >> 11) & 0x1F) << 3, ((v >> 5) & 0x3F) << 2, (v & 0x1F) << 3, 255); }
break;
case 26: // A4R4G4B4
for (int i = 0; i < w * h && i * 2 + 1 < src.Length; i++)
{ ushort v = (ushort)(src[i * 2] | (src[i * 2 + 1] << 8)); Px(i, ((v >> 8) & 0xF) * 17, ((v >> 4) & 0xF) * 17, (v & 0xF) * 17, ((v >> 12) & 0xF) * 17); }
break;
case 28: // A8 (greyscale)
case 244: // LSCAPE_ALPHA
for (int i = 0; i < w * h && i < src.Length; i++) Px(i, src[i], src[i], src[i], 255);
break;
case 101: // INDEX16
case 41: // P8
{
uint[]? pal = LoadPalette(defPal);
if (pal == null || pal.Length == 0) return null;
bool p8 = fmt == 41;
for (int i = 0; i < w * h; i++)
{
int idx;
if (p8) { if (i >= src.Length) break; idx = src[i]; }
else { if (i * 2 + 1 >= src.Length) break; idx = (ushort)(src[i * 2] | (src[i * 2 + 1] << 8)); }
uint cc = pal[idx % pal.Length];
Px(i, (int)((cc >> 16) & 0xFF), (int)((cc >> 8) & 0xFF), (int)(cc & 0xFF), (int)((cc >> 24) & 0xFF));
}
break;
}
default:
return null; // unhandled format
}
return new Rgba { Width = w, Height = h, Pixels = rgba };
}
private static Rgba Wrap(byte[] rgba, int w, int h) => new Rgba { Width = w, Height = h, Pixels = rgba }; // DxtUtil already RGBA
}