RynthCore as of 2026-10-05 evening (internal 0a2043e): release 2026.10.5.20 - own dat reader, plugin manifests, UI/login hooks with Loot Editor drag-and-drop, server-message stream (API v78), raise attributes and skills (API v79), nameplate sizing and overlay opacity, engine reload held while a plugin is fighting, StatusAgent character sheet, world map and travel for DrakRemote
This commit is contained in:
parent
c3e15480e5
commit
913a2a00b6
110 changed files with 12560 additions and 1151 deletions
|
|
@ -104,6 +104,14 @@ internal sealed class AgentConfig
|
|||
/// /maps returns an empty list and /map 404s — no other feature is affected.</summary>
|
||||
[JsonPropertyName("MapsDirectory")] public string MapsDirectory { get; set; } = @"C:\Games\RynthSuite\RynthAi\Maps";
|
||||
|
||||
/// <summary>cell.dat the landscape map (GET /worldmap) is drawn from, once, then cached as worldmap-v1.jpg in
|
||||
/// <see cref="StatusDirectory"/>. Absent = no world map (capabilities.worldMap false); nothing else changes.</summary>
|
||||
[JsonPropertyName("CellDatPath")] public string CellDatPath { get; set; } = @"C:\Games\RynthCore\AcClient\client_cell_1.dat";
|
||||
|
||||
/// <summary>RynthNav's Atlas (NavData\locations.json), searched by GET /nav/search for the phone's Travel tab.
|
||||
/// Absent = no travel (capabilities.travel false). The travel itself also needs EnableRemoteControl.</summary>
|
||||
[JsonPropertyName("NavAtlasPath")] public string NavAtlasPath { get; set; } = @"C:\Games\RynthCore\NavData\locations.json";
|
||||
|
||||
public static string DefaultConfigPath => Path.Combine(
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
|
||||
"RynthCore", "statusagent.json");
|
||||
|
|
|
|||
|
|
@ -1,41 +1,89 @@
|
|||
// ============================================================================
|
||||
// RynthCore.StatusAgent - Dat/DatDatabase.cs
|
||||
// Read-only access to Asheron's Call .dat archives (the agent reads item
|
||||
// icons from client_portal.dat). Written for RynthCore (MIT) on 2026-10-05;
|
||||
// the same design as RynthSuite's Shared/RynthCore.TerrainData/DatDatabase.cs.
|
||||
//
|
||||
// Written from the dat container format as it is publicly documented, with
|
||||
// Chorizite's DatReaderWriter (MIT, notice below) used as the format reference:
|
||||
// - file header at byte 0x140: magic, block size, file size, data set,
|
||||
// subset, free head / tail / count, then the byte offset of the root
|
||||
// B-tree node (all little-endian uint32);
|
||||
// - storage is fixed-size blocks; a block's first uint32 is the byte offset
|
||||
// of the next block of the same chain (0 ends the chain), the remaining
|
||||
// BlockSize - 4 bytes are payload;
|
||||
// - the directory is a B-tree whose nodes are stored as block chains: 62
|
||||
// uint32 child offsets, a uint32 entry count (at most 61), then the
|
||||
// entries, 24 bytes each: flags/version, id, byte offset of the file's
|
||||
// first block, size, timestamp, iteration. Entries are sorted by id,
|
||||
// child i holds the ids between entry i-1 and entry i, and a node whose
|
||||
// first child offset is 0 is a leaf.
|
||||
//
|
||||
// Lookups descend the tree from the root; interior nodes are kept once read
|
||||
// and leaves go through a small LRU. Every call takes one lock, so a database
|
||||
// can be shared between threads.
|
||||
//
|
||||
// Chorizite DatReaderWriter notice (format reference):
|
||||
// Copyright 2024 ACClientLib
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a
|
||||
// copy of this software and associated documentation files (the
|
||||
// "Software"), to deal in the Software without restriction, including
|
||||
// without limitation the rights to use, copy, modify, merge, publish,
|
||||
// distribute, sublicense, and/or sell copies of the Software, and to permit
|
||||
// persons to whom the Software is furnished to do so, subject to the
|
||||
// following conditions: The above copyright notice and this permission
|
||||
// notice shall be included in all copies or substantial portions of the
|
||||
// Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
|
||||
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
|
||||
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
|
||||
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
|
||||
// USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Buffers.Binary;
|
||||
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
|
||||
/// A read-only .dat archive. <see cref="Open"/> reads the header, checks the
|
||||
/// root directory node and counts the files; files are then found by id by
|
||||
/// searching the on-disk B-tree. Methods return null / empty when the database
|
||||
/// isn't open or the file isn't there; nothing throws for a damaged file.
|
||||
/// </summary>
|
||||
public class DatDatabase : IDisposable
|
||||
{
|
||||
private FileStream? _stream;
|
||||
private readonly object _lock = new();
|
||||
private const long HeaderOffset = 0x140;
|
||||
private const int HeaderBytes = 9 * 4; // magic .. root offset
|
||||
private const int ChildSlots = 62;
|
||||
private const int MaxEntriesPerNode = 61;
|
||||
private const int EntryBytes = 24;
|
||||
private const int CountOffset = ChildSlots * 4; // 248
|
||||
private const int EntriesOffset = CountOffset + 4; // 252
|
||||
private const int NodeBytes = EntriesOffset + MaxEntriesPerNode * EntryBytes; // 1716
|
||||
private const int DepthLimit = 16; // real trees are 4 deep; stops a looping child pointer
|
||||
private const int LeafLruSize = 128;
|
||||
private const int InteriorCap = 4096;
|
||||
|
||||
private const uint DAT_HEADER_OFFSET = 0x140;
|
||||
private readonly object _gate = new();
|
||||
private FileStream? _file;
|
||||
private long _length;
|
||||
private readonly byte[] _nodeBuf = new byte[NodeBytes];
|
||||
private readonly Dictionary<uint, Node> _interior = new();
|
||||
private readonly Dictionary<uint, LinkedListNode<(uint At, Node Node)>> _leafMap = new();
|
||||
private readonly LinkedList<(uint At, Node Node)> _leafOrder = new();
|
||||
|
||||
// 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>
|
||||
/// <summary>Header word at 0x140 (the dat magic).</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>
|
||||
/// <summary>File size recorded in the header.</summary>
|
||||
public uint FileSize { get; private set; }
|
||||
/// <summary>DataSet field from header.</summary>
|
||||
/// <summary>The header's data set (database type) word.</summary>
|
||||
public uint DataSet { get; private set; }
|
||||
/// <summary>Byte offset of the root B-tree node.</summary>
|
||||
public uint BTreeRoot { get; private set; }
|
||||
|
|
@ -44,326 +92,75 @@ public class DatDatabase : IDisposable
|
|||
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>
|
||||
/// <summary>Number of files in the dat (counted at <see cref="Open"/>).</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();
|
||||
|
||||
private sealed class Node
|
||||
{
|
||||
public uint[]? Children; // entry count + 1 offsets; null for a leaf
|
||||
public DatBTreeEntry[] Entries = []; // ascending ObjectId
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- open / close
|
||||
|
||||
/// <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.
|
||||
/// Opens the .dat file at <paramref name="path"/> for read-only random access.
|
||||
/// Returns false on any failure.
|
||||
/// </summary>
|
||||
public bool Open(string path)
|
||||
{
|
||||
try
|
||||
lock (_gate)
|
||||
{
|
||||
if (!File.Exists(path))
|
||||
{
|
||||
Log($"File not found: {path}");
|
||||
return false;
|
||||
}
|
||||
|
||||
CloseLocked();
|
||||
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())
|
||||
try
|
||||
{
|
||||
Close();
|
||||
if (!File.Exists(path)) { Log($"Not found: {path}"); return false; }
|
||||
|
||||
// AC keeps its own handles on its dats: share everything,
|
||||
// including delete (the client's own open asks for it).
|
||||
_file = new FileStream(path, FileMode.Open, FileAccess.Read,
|
||||
FileShare.ReadWrite | FileShare.Delete, 4096, FileOptions.RandomAccess);
|
||||
_length = _file.Length;
|
||||
|
||||
Span<byte> h = stackalloc byte[HeaderBytes];
|
||||
if (!ReadAt(HeaderOffset, h)) { Log("Header is short"); CloseLocked(); return false; }
|
||||
FileType = BinaryPrimitives.ReadUInt32LittleEndian(h);
|
||||
BlockSize = BinaryPrimitives.ReadUInt32LittleEndian(h.Slice(4));
|
||||
FileSize = BinaryPrimitives.ReadUInt32LittleEndian(h.Slice(8));
|
||||
DataSet = BinaryPrimitives.ReadUInt32LittleEndian(h.Slice(12));
|
||||
BTreeRoot = BinaryPrimitives.ReadUInt32LittleEndian(h.Slice(32));
|
||||
|
||||
if (BlockSize <= 4 || BlockSize > 0x10000) { Log($"Bad block size {BlockSize}"); CloseLocked(); return false; }
|
||||
if (BTreeRoot == 0 || BTreeRoot >= _length) { Log($"Bad root offset 0x{BTreeRoot:X8}"); CloseLocked(); return false; }
|
||||
|
||||
IsLoaded = true;
|
||||
if (GetNode(BTreeRoot) == null)
|
||||
{
|
||||
Log($"Root node at 0x{BTreeRoot:X8} doesn't parse");
|
||||
CloseLocked();
|
||||
return false;
|
||||
}
|
||||
RecordCount = CountUnder(BTreeRoot, 0);
|
||||
Log($"Opened {Path.GetFileName(path)}: {RecordCount} files, block size {BlockSize}");
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log($"Open failed: {ex.Message}");
|
||||
CloseLocked();
|
||||
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>
|
||||
/// <summary>Closes the underlying file handle and drops the cached directory nodes.</summary>
|
||||
public void Close()
|
||||
{
|
||||
_stream?.Dispose();
|
||||
_stream = null;
|
||||
IsLoaded = false;
|
||||
_allFiles.Clear();
|
||||
lock (_gate) CloseLocked();
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
|
|
@ -373,15 +170,266 @@ public class DatDatabase : IDisposable
|
|||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
private void CloseLocked()
|
||||
{
|
||||
IsLoaded = false;
|
||||
_file?.Dispose();
|
||||
_file = null;
|
||||
_length = 0;
|
||||
RecordCount = 0;
|
||||
_interior.Clear();
|
||||
_leafMap.Clear();
|
||||
_leafOrder.Clear();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- lookups
|
||||
|
||||
/// <summary>The directory entry for <paramref name="fileId"/>, or null.</summary>
|
||||
public DatBTreeEntry? FindFile(uint fileId)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (!IsLoaded) return null;
|
||||
uint at = BTreeRoot;
|
||||
for (int depth = 0; depth < DepthLimit && at != 0; depth++)
|
||||
{
|
||||
Node? n = GetNode(at);
|
||||
if (n == null) return null;
|
||||
int i = LowerBound(n.Entries, fileId);
|
||||
if (i < n.Entries.Length && n.Entries[i].ObjectId == fileId) return n.Entries[i];
|
||||
if (n.Children == null) return null;
|
||||
at = n.Children[i];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The bytes of the file <paramref name="entry"/> describes, or null.</summary>
|
||||
public byte[]? ReadFileData(DatBTreeEntry? entry)
|
||||
{
|
||||
if (entry == null) return null;
|
||||
lock (_gate)
|
||||
{
|
||||
if (!IsLoaded) return null;
|
||||
if (entry.FileSize > _length) { Log($"0x{entry.ObjectId:X8}: size {entry.FileSize} exceeds the file"); return null; }
|
||||
var data = new byte[entry.FileSize];
|
||||
if (ReadChain(entry.FileOffset, data) != data.Length)
|
||||
{
|
||||
Log($"0x{entry.ObjectId:X8}: block chain at 0x{entry.FileOffset:X8} is broken");
|
||||
return null;
|
||||
}
|
||||
return data;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Convenience: find by id then read.</summary>
|
||||
public byte[]? GetFileData(uint fileId) => ReadFileData(FindFile(fileId));
|
||||
|
||||
/// <summary>
|
||||
/// (fileId, storedSize) for every file whose id is in [lo, hi], largest first
|
||||
/// (ties by ascending id).
|
||||
/// </summary>
|
||||
public List<(uint id, uint size)> EntriesInRange(uint lo, uint hi)
|
||||
{
|
||||
var found = new List<DatBTreeEntry>();
|
||||
lock (_gate)
|
||||
{
|
||||
if (IsLoaded && lo <= hi) Collect(BTreeRoot, lo, hi, found, 0);
|
||||
}
|
||||
var result = new List<(uint id, uint size)>(found.Count);
|
||||
foreach (var e in found) result.Add((e.ObjectId, e.FileSize));
|
||||
result.Sort((a, b) => a.size != b.size ? b.size.CompareTo(a.size) : a.id.CompareTo(b.id));
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The interior (EnvCell) ids 0xXXYY0100-0xXXYYFFFD of landblock
|
||||
/// <paramref name="landblockKey"/> (0xXXYY), ascending.
|
||||
/// </summary>
|
||||
public List<uint> GetLandblockCellIds(uint landblockKey)
|
||||
{
|
||||
var found = new List<DatBTreeEntry>();
|
||||
lock (_gate)
|
||||
{
|
||||
if (IsLoaded) Collect(BTreeRoot, (landblockKey << 16) | 0x0100, (landblockKey << 16) | 0xFFFD, found, 0);
|
||||
}
|
||||
var ids = new List<uint>(found.Count);
|
||||
foreach (var e in found) ids.Add(e.ObjectId);
|
||||
return ids;
|
||||
}
|
||||
|
||||
/// <summary>The lowest file ids in the dat (up to <paramref name="maxCount"/>), for diagnostics.</summary>
|
||||
public List<uint> GetSampleIds(int maxCount = 20)
|
||||
{
|
||||
var ids = new List<uint>();
|
||||
if (maxCount <= 0) return ids;
|
||||
var found = new List<DatBTreeEntry>();
|
||||
lock (_gate)
|
||||
{
|
||||
if (IsLoaded) Collect(BTreeRoot, 0, uint.MaxValue, found, 0, maxCount);
|
||||
}
|
||||
foreach (var e in found) ids.Add(e.ObjectId);
|
||||
return ids;
|
||||
}
|
||||
|
||||
// In-order walk of the subtree at `at`, adding the entries with ids in
|
||||
// [lo, hi] (stops once `into` holds `limit`). Caller holds _gate.
|
||||
private void Collect(uint at, uint lo, uint hi, List<DatBTreeEntry> into, int depth, int limit = int.MaxValue)
|
||||
{
|
||||
if (at == 0 || depth >= DepthLimit || into.Count >= limit) return;
|
||||
Node? n = GetNode(at);
|
||||
if (n == null) return;
|
||||
var e = n.Entries;
|
||||
for (int i = 0; i <= e.Length; i++)
|
||||
{
|
||||
if (n.Children != null)
|
||||
{
|
||||
// Child i holds the ids between e[i-1] and e[i].
|
||||
bool aboveLo = i == e.Length || e[i].ObjectId > lo;
|
||||
bool belowHi = i == 0 || e[i - 1].ObjectId < hi;
|
||||
if (aboveLo && belowHi) Collect(n.Children[i], lo, hi, into, depth + 1, limit);
|
||||
}
|
||||
if (i == e.Length || into.Count >= limit) break;
|
||||
uint id = e[i].ObjectId;
|
||||
if (id > hi) break;
|
||||
if (id >= lo) into.Add(e[i]);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- nodes
|
||||
|
||||
private static int LowerBound(DatBTreeEntry[] e, uint id)
|
||||
{
|
||||
int a = 0, b = e.Length;
|
||||
while (a < b)
|
||||
{
|
||||
int m = (a + b) >> 1;
|
||||
if (e[m].ObjectId < id) a = m + 1; else b = m;
|
||||
}
|
||||
return a;
|
||||
}
|
||||
|
||||
// Cached node: interior nodes kept (capped), leaves in a small LRU. Caller holds _gate.
|
||||
private Node? GetNode(uint at)
|
||||
{
|
||||
if (_interior.TryGetValue(at, out Node? n)) return n;
|
||||
if (_leafMap.TryGetValue(at, out var hit))
|
||||
{
|
||||
_leafOrder.Remove(hit);
|
||||
_leafOrder.AddFirst(hit);
|
||||
return hit.Value.Node;
|
||||
}
|
||||
n = ParseNode(at);
|
||||
if (n == null) return null;
|
||||
if (n.Children != null)
|
||||
{
|
||||
if (_interior.Count < InteriorCap) _interior[at] = n;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (_leafMap.Count >= LeafLruSize && _leafOrder.Last != null)
|
||||
{
|
||||
_leafMap.Remove(_leafOrder.Last.Value.At);
|
||||
_leafOrder.RemoveLast();
|
||||
}
|
||||
_leafMap[at] = _leafOrder.AddFirst((at, n));
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
private Node? ParseNode(uint at)
|
||||
{
|
||||
int got = ReadChain(at, _nodeBuf);
|
||||
if (got < EntriesOffset) return null;
|
||||
ReadOnlySpan<byte> s = _nodeBuf;
|
||||
int count = BinaryPrimitives.ReadInt32LittleEndian(s.Slice(CountOffset));
|
||||
if (count < 0 || count > MaxEntriesPerNode || got < EntriesOffset + count * EntryBytes) return null;
|
||||
|
||||
var entries = new DatBTreeEntry[count];
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
var r = s.Slice(EntriesOffset + i * EntryBytes, EntryBytes);
|
||||
entries[i] = new DatBTreeEntry
|
||||
{
|
||||
BitFlags = BinaryPrimitives.ReadUInt32LittleEndian(r),
|
||||
ObjectId = BinaryPrimitives.ReadUInt32LittleEndian(r.Slice(4)),
|
||||
FileOffset = BinaryPrimitives.ReadUInt32LittleEndian(r.Slice(8)),
|
||||
FileSize = BinaryPrimitives.ReadUInt32LittleEndian(r.Slice(12)),
|
||||
};
|
||||
}
|
||||
uint[]? children = null;
|
||||
if (BinaryPrimitives.ReadUInt32LittleEndian(s) != 0)
|
||||
{
|
||||
children = new uint[count + 1];
|
||||
for (int i = 0; i <= count; i++) children[i] = BinaryPrimitives.ReadUInt32LittleEndian(s.Slice(i * 4));
|
||||
}
|
||||
return new Node { Children = children, Entries = entries };
|
||||
}
|
||||
|
||||
// Entry counts under `at`, reading only each node's child table and count. Caller holds _gate.
|
||||
private int CountUnder(uint at, int depth)
|
||||
{
|
||||
if (at == 0 || depth >= DepthLimit) return 0;
|
||||
Span<byte> head = stackalloc byte[EntriesOffset];
|
||||
if (ReadChain(at, head) != EntriesOffset) return 0;
|
||||
int count = BinaryPrimitives.ReadInt32LittleEndian(head.Slice(CountOffset));
|
||||
if (count < 0 || count > MaxEntriesPerNode) return 0;
|
||||
int total = count;
|
||||
if (BinaryPrimitives.ReadUInt32LittleEndian(head) != 0)
|
||||
{
|
||||
Span<uint> kids = stackalloc uint[count + 1];
|
||||
for (int i = 0; i <= count; i++) kids[i] = BinaryPrimitives.ReadUInt32LittleEndian(head.Slice(i * 4));
|
||||
for (int i = 0; i <= count; i++) total += CountUnder(kids[i], depth + 1);
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- blocks
|
||||
|
||||
// Copies the block chain starting at byte offset `first` into `dest` and
|
||||
// returns how many bytes it filled: dest.Length, or less when the chain
|
||||
// ends (a 0 link) first; -1 when a link points outside the file.
|
||||
private int ReadChain(uint first, Span<byte> dest)
|
||||
{
|
||||
int payload = (int)BlockSize - 4;
|
||||
long block = first;
|
||||
int done = 0;
|
||||
Span<byte> link = stackalloc byte[4];
|
||||
while (done < dest.Length)
|
||||
{
|
||||
if (block == 0) return done;
|
||||
if (block + 4 > _length) return -1;
|
||||
int take = Math.Min(payload, dest.Length - done);
|
||||
if (!ReadAt(block, link) || !ReadAt(block + 4, dest.Slice(done, take))) return -1;
|
||||
done += take;
|
||||
block = BinaryPrimitives.ReadUInt32LittleEndian(link);
|
||||
}
|
||||
return done;
|
||||
}
|
||||
|
||||
private bool ReadAt(long offset, Span<byte> into)
|
||||
{
|
||||
if (_file == null || offset < 0 || offset + into.Length > _length) return false;
|
||||
_file.Position = offset;
|
||||
int got = 0;
|
||||
while (got < into.Length)
|
||||
{
|
||||
int n = _file.Read(into.Slice(got));
|
||||
if (n <= 0) return false;
|
||||
got += n;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private void Log(string msg)
|
||||
{
|
||||
string line = $"[DatDB] {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>
|
||||
/// <summary>One directory entry of a .dat archive.</summary>
|
||||
public class DatBTreeEntry
|
||||
{
|
||||
/// <summary>Raw flag bits from the B-tree.</summary>
|
||||
|
|
|
|||
|
|
@ -1,442 +1,172 @@
|
|||
// #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
|
||||
// ============================================================================
|
||||
// RynthCore.StatusAgent - Dat/DxtUtil.cs
|
||||
// DXT1 / DXT3 / DXT5 (BC1 / BC2 / BC3) block decompression to RGBA bytes.
|
||||
// Written for RynthCore (MIT) on 2026-10-05 from the public S3TC / DirectX
|
||||
// block-compression format description:
|
||||
//
|
||||
// Images are stored as 4 x 4 pixel blocks, left to right, top to bottom.
|
||||
// Colour block (8 bytes, the whole of a DXT1 block and the second half of
|
||||
// a DXT3/DXT5 block): two RGB565 end-point colours c0, c1 (uint16 each),
|
||||
// then 16 two-bit indices, one per pixel, row by row, low bits first.
|
||||
// DXT1, c0 > c1: index 2 = (2*c0 + c1) / 3, index 3 = (c0 + 2*c1) / 3
|
||||
// DXT1, c0 <= c1: index 2 = (c0 + c1) / 2, index 3 = transparent black
|
||||
// DXT3 / DXT5 always use the four-colour form.
|
||||
// DXT3 alpha (first 8 bytes): 16 explicit four-bit alphas, low nibble first.
|
||||
// DXT5 alpha (first 8 bytes): end points a0, a1 (one byte each), then 16
|
||||
// three-bit indices (48 bits, little-endian, low bits first):
|
||||
// a0 > a1: indices 2..7 = 6 interpolated values between a0 and a1
|
||||
// a0 <= a1: indices 2..5 = 4 interpolated values, 6 = 0, 7 = 255
|
||||
//
|
||||
// Used by the agent's IconDecoder and, linked, by the engine's
|
||||
// UI/ScriptWindows/AcIconDecoder.cs (and RynthSuite's ScriptWindows tests).
|
||||
// ============================================================================
|
||||
|
||||
namespace ACE.DatLoader
|
||||
using System;
|
||||
using System.IO;
|
||||
|
||||
namespace RynthCore.Imaging
|
||||
{
|
||||
using System.IO;
|
||||
|
||||
/// <summary>DXT1/3/5 decompression; output is width * height * 4 bytes, R, G, B, A.</summary>
|
||||
public static class DxtUtil
|
||||
{
|
||||
internal static byte[] DecompressDxt1(byte[] imageData, int width, int height)
|
||||
internal static byte[] DecompressDxt1(byte[] imageData, int width, int height) =>
|
||||
Decompress(imageData, width, height, BlockKind.Dxt1);
|
||||
|
||||
internal static byte[] DecompressDxt1(Stream imageStream, int width, int height) =>
|
||||
DecompressDxt1(ReadAll(imageStream), width, height);
|
||||
|
||||
internal static byte[] DecompressDxt3(byte[] imageData, int width, int height) =>
|
||||
Decompress(imageData, width, height, BlockKind.Dxt3);
|
||||
|
||||
internal static byte[] DecompressDxt3(Stream imageStream, int width, int height) =>
|
||||
DecompressDxt3(ReadAll(imageStream), width, height);
|
||||
|
||||
internal static byte[] DecompressDxt5(byte[] imageData, int width, int height) =>
|
||||
Decompress(imageData, width, height, BlockKind.Dxt5);
|
||||
|
||||
internal static byte[] DecompressDxt5(Stream imageStream, int width, int height) =>
|
||||
DecompressDxt5(ReadAll(imageStream), width, height);
|
||||
|
||||
private enum BlockKind { Dxt1, Dxt3, Dxt5 }
|
||||
|
||||
private static byte[] ReadAll(Stream s)
|
||||
{
|
||||
using (MemoryStream imageStream = new MemoryStream(imageData))
|
||||
return DecompressDxt1(imageStream, width, height);
|
||||
using var ms = new MemoryStream();
|
||||
s.CopyTo(ms);
|
||||
return ms.ToArray();
|
||||
}
|
||||
|
||||
internal static byte[] DecompressDxt1(Stream imageStream, int width, int height)
|
||||
private static byte[] Decompress(byte[] src, int width, int height, BlockKind kind)
|
||||
{
|
||||
byte[] imageData = new byte[width * height * 4];
|
||||
if (width <= 0 || height <= 0) return Array.Empty<byte>();
|
||||
var rgba = new byte[width * height * 4];
|
||||
int blockBytes = kind == BlockKind.Dxt1 ? 8 : 16;
|
||||
int blocksX = (width + 3) / 4, blocksY = (height + 3) / 4;
|
||||
|
||||
using (BinaryReader imageReader = new BinaryReader(imageStream))
|
||||
Span<byte> palette = stackalloc byte[16]; // 4 colours x RGBA
|
||||
Span<byte> alpha = stackalloc byte[16]; // per pixel (DXT3/5)
|
||||
Span<byte> alphaTable = stackalloc byte[8]; // DXT5 end points + interpolated
|
||||
int at = 0;
|
||||
for (int by = 0; by < blocksY; by++)
|
||||
{
|
||||
int blockCountX = (width + 3) / 4;
|
||||
int blockCountY = (height + 3) / 4;
|
||||
|
||||
for (int y = 0; y < blockCountY; y++)
|
||||
for (int bx = 0; bx < blocksX; bx++, at += blockBytes)
|
||||
{
|
||||
for (int x = 0; x < blockCountX; x++)
|
||||
if (at + blockBytes > src.Length) return rgba; // short data: the rest stays clear
|
||||
int colourAt = at;
|
||||
bool hasAlphaBlock = kind != BlockKind.Dxt1;
|
||||
if (kind == BlockKind.Dxt3)
|
||||
{
|
||||
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)
|
||||
for (int i = 0; i < 16; i++)
|
||||
{
|
||||
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 nibble = (src[at + (i >> 1)] >> ((i & 1) * 4)) & 0xF;
|
||||
alpha[i] = (byte)(nibble * 17);
|
||||
}
|
||||
colourAt += 8;
|
||||
}
|
||||
else if (kind == BlockKind.Dxt5)
|
||||
{
|
||||
byte a0 = src[at], a1 = src[at + 1];
|
||||
alphaTable[0] = a0;
|
||||
alphaTable[1] = a1;
|
||||
if (a0 > a1)
|
||||
{
|
||||
for (int i = 1; i <= 6; i++) alphaTable[i + 1] = (byte)(((7 - i) * a0 + i * a1) / 7);
|
||||
}
|
||||
else
|
||||
{
|
||||
for (int i = 1; i <= 4; i++) alphaTable[i + 1] = (byte)(((5 - i) * a0 + i * a1) / 5);
|
||||
alphaTable[6] = 0;
|
||||
alphaTable[7] = 255;
|
||||
}
|
||||
ulong bits = 0;
|
||||
for (int i = 0; i < 6; i++) bits |= (ulong)src[at + 2 + i] << (8 * i);
|
||||
for (int i = 0; i < 16; i++) alpha[i] = alphaTable[(int)((bits >> (3 * i)) & 7)];
|
||||
colourAt += 8;
|
||||
}
|
||||
|
||||
ushort c0 = (ushort)(src[colourAt] | (src[colourAt + 1] << 8));
|
||||
ushort c1 = (ushort)(src[colourAt + 2] | (src[colourAt + 3] << 8));
|
||||
Expand565(c0, palette.Slice(0, 4));
|
||||
Expand565(c1, palette.Slice(4, 4));
|
||||
if (kind != BlockKind.Dxt1 || c0 > c1)
|
||||
{
|
||||
for (int ch = 0; ch < 3; ch++)
|
||||
{
|
||||
palette[8 + ch] = (byte)((2 * palette[ch] + palette[4 + ch]) / 3);
|
||||
palette[12 + ch] = (byte)((palette[ch] + 2 * palette[4 + ch]) / 3);
|
||||
}
|
||||
palette[11] = 255;
|
||||
palette[15] = 255;
|
||||
}
|
||||
else
|
||||
{
|
||||
switch (index)
|
||||
for (int ch = 0; ch < 3; ch++)
|
||||
{
|
||||
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;
|
||||
palette[8 + ch] = (byte)((palette[ch] + palette[4 + ch]) / 2);
|
||||
palette[12 + ch] = 0;
|
||||
}
|
||||
palette[11] = 255;
|
||||
palette[15] = 0;
|
||||
}
|
||||
|
||||
uint indices = (uint)(src[colourAt + 4] | (src[colourAt + 5] << 8) | (src[colourAt + 6] << 16) | (src[colourAt + 7] << 24));
|
||||
for (int py = 0; py < 4; py++)
|
||||
{
|
||||
int y = by * 4 + py;
|
||||
if (y >= height) break;
|
||||
for (int px = 0; px < 4; px++)
|
||||
{
|
||||
int x = bx * 4 + px;
|
||||
if (x >= width) continue;
|
||||
int p = py * 4 + px;
|
||||
int idx = (int)((indices >> (2 * p)) & 3);
|
||||
int o = (y * width + x) * 4;
|
||||
rgba[o] = palette[idx * 4];
|
||||
rgba[o + 1] = palette[idx * 4 + 1];
|
||||
rgba[o + 2] = palette[idx * 4 + 2];
|
||||
rgba[o + 3] = hasAlphaBlock ? alpha[p] : palette[idx * 4 + 3];
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
return rgba;
|
||||
}
|
||||
|
||||
internal static byte[] DecompressDxt3(byte[] imageData, int width, int height)
|
||||
// RGB565 to 8-bit channels: v * 255 / max, rounded with the (t + t / 2^n) / 2^n
|
||||
// approximation (t = v * 255 + 2^(n-1)), so the output matches, bit for bit,
|
||||
// the decoder this file replaced.
|
||||
private static void Expand565(ushort c, Span<byte> rgba)
|
||||
{
|
||||
using (MemoryStream imageStream = new MemoryStream(imageData))
|
||||
return DecompressDxt3(imageStream, width, height);
|
||||
rgba[0] = Scale((c >> 11) & 0x1F, 5);
|
||||
rgba[1] = Scale((c >> 5) & 0x3F, 6);
|
||||
rgba[2] = Scale(c & 0x1F, 5);
|
||||
rgba[3] = 255;
|
||||
}
|
||||
|
||||
internal static byte[] DecompressDxt3(Stream imageStream, int width, int height)
|
||||
private static byte Scale(int v, int bits)
|
||||
{
|
||||
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);
|
||||
int t = v * 255 + (1 << (bits - 1));
|
||||
return (byte)(((t >> bits) + t) >> bits);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,14 +1,26 @@
|
|||
using ACE.DatLoader;
|
||||
// ============================================================================
|
||||
// RynthCore.StatusAgent - Dat/IconDecoder.cs
|
||||
// An item icon (a 0x06 Texture in client_portal.dat) as RGBA pixels, for the
|
||||
// phone remote. Written for RynthCore (MIT) on 2026-10-05.
|
||||
//
|
||||
// Written from the Texture file layout as Chorizite's DatReaderWriter (MIT,
|
||||
// see the notice in Dat/DatDatabase.cs) describes it (RenderSurface and
|
||||
// Palette) and the Direct3D pixel-format definitions:
|
||||
// Texture 0x06: id u32, data category u32, width i32, height i32,
|
||||
// format u32, length i32, data[length], and for the palette
|
||||
// formats (P8, INDEX16) the default palette id u32.
|
||||
// Palette 0x04: id u32, colour count i32, colours (u32 A8R8G8B8 each).
|
||||
// Formats in the retail portal dat: A8R8G8B8, R8G8B8, R5G6B5, A4R4G4B4, A8,
|
||||
// P8, INDEX16, the landscape R8G8B8 / alpha customs and DXT1/3/5 (DxtUtil.cs).
|
||||
// Raw JPEG textures are not decoded.
|
||||
// ============================================================================
|
||||
|
||||
using RynthCore.Imaging;
|
||||
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>
|
||||
/// <summary>Decodes an AC item icon (a 0x06 Texture in portal.dat) to RGBA pixels.</summary>
|
||||
internal sealed class IconDecoder
|
||||
{
|
||||
private readonly DatDatabase _portal;
|
||||
|
|
@ -22,94 +34,113 @@ internal sealed class IconDecoder
|
|||
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;
|
||||
}
|
||||
private const uint A8R8G8B8 = 0x15, R8G8B8 = 0x14, R5G6B5 = 0x17, A4R4G4B4 = 0x1A, A8 = 0x1C,
|
||||
P8 = 0x29, Index16 = 0x65, LscapeR8G8B8 = 0xF3, LscapeAlpha = 0xF4,
|
||||
Dxt1 = 0x31545844, Dxt3 = 0x33545844, Dxt5 = 0x35545844;
|
||||
|
||||
// Texture (0x06): Id(u32),Unknown(i32),Width(i32),Height(i32),Format(u32),Length(i32),Source[Length],
|
||||
// if INDEX16/P8: DefaultPaletteId(u32).
|
||||
/// <summary>The texture <paramref name="textureId"/> as RGBA, or null (missing, unsupported or damaged).</summary>
|
||||
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)
|
||||
try
|
||||
{
|
||||
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
|
||||
byte[]? file = _portal.GetFileData(textureId);
|
||||
if (file == null || file.Length < 24) return null;
|
||||
var r = new ReadOnlySpan<byte>(file);
|
||||
int w = I32(r, 8), h = I32(r, 12);
|
||||
uint format = U32(r, 16);
|
||||
int length = I32(r, 20);
|
||||
if (w <= 0 || h <= 0 || w > 4096 || h > 4096 || length < 0 || 24L + length > file.Length) return null;
|
||||
var src = r.Slice(24, length);
|
||||
int n = w * h;
|
||||
|
||||
switch (format)
|
||||
{
|
||||
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;
|
||||
case Dxt1: return Make(w, h, DxtUtil.DecompressDxt1(src.ToArray(), w, h));
|
||||
case Dxt3: return Make(w, h, DxtUtil.DecompressDxt3(src.ToArray(), w, h));
|
||||
case Dxt5: return Make(w, h, DxtUtil.DecompressDxt5(src.ToArray(), w, h));
|
||||
}
|
||||
default:
|
||||
return null; // unhandled format
|
||||
|
||||
var px = new byte[n * 4];
|
||||
switch (format)
|
||||
{
|
||||
case A8R8G8B8: // B, G, R, A in memory
|
||||
if (length < n * 4) return null;
|
||||
for (int i = 0; i < n; i++) Put(px, i, src[i * 4 + 2], src[i * 4 + 1], src[i * 4], src[i * 4 + 3]);
|
||||
break;
|
||||
case R8G8B8: // B, G, R
|
||||
if (length < n * 3) return null;
|
||||
for (int i = 0; i < n; i++) Put(px, i, src[i * 3 + 2], src[i * 3 + 1], src[i * 3], 255);
|
||||
break;
|
||||
case LscapeR8G8B8: // R, G, B
|
||||
if (length < n * 3) return null;
|
||||
for (int i = 0; i < n; i++) Put(px, i, src[i * 3], src[i * 3 + 1], src[i * 3 + 2], 255);
|
||||
break;
|
||||
case R5G6B5:
|
||||
if (length < n * 2) return null;
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
int v = src[i * 2] | (src[i * 2 + 1] << 8);
|
||||
// Top bits only (low bits left 0), as the decoder this replaced did.
|
||||
Put(px, i, (byte)(((v >> 11) & 0x1F) << 3), (byte)(((v >> 5) & 0x3F) << 2), (byte)((v & 0x1F) << 3), 255);
|
||||
}
|
||||
break;
|
||||
case A4R4G4B4:
|
||||
if (length < n * 2) return null;
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
int v = src[i * 2] | (src[i * 2 + 1] << 8);
|
||||
Put(px, i, (byte)(((v >> 8) & 0xF) * 17), (byte)(((v >> 4) & 0xF) * 17), (byte)((v & 0xF) * 17), (byte)(((v >> 12) & 0xF) * 17));
|
||||
}
|
||||
break;
|
||||
case A8: // one byte a pixel, shown as an opaque grey level
|
||||
case LscapeAlpha:
|
||||
if (length < n) return null;
|
||||
for (int i = 0; i < n; i++) Put(px, i, src[i], src[i], src[i], 255);
|
||||
break;
|
||||
case P8:
|
||||
case Index16:
|
||||
{
|
||||
int bpp = format == P8 ? 1 : 2;
|
||||
if (length < n * bpp || 24L + length + 4 > file.Length) return null;
|
||||
uint[]? palette = LoadPalette(U32(r, 24 + length));
|
||||
if (palette == null) return null;
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
int idx = bpp == 1 ? src[i] : src[i * 2] | (src[i * 2 + 1] << 8);
|
||||
uint argb = idx < palette.Length ? palette[idx] : 0;
|
||||
Put(px, i, (byte)(argb >> 16), (byte)(argb >> 8), (byte)argb, (byte)(argb >> 24));
|
||||
}
|
||||
break;
|
||||
}
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
return Make(w, h, px);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
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
|
||||
// A 0x04 Palette's colours (A8R8G8B8), or null.
|
||||
private uint[]? LoadPalette(uint paletteId)
|
||||
{
|
||||
byte[]? file = _portal.GetFileData(paletteId);
|
||||
if (file == null || file.Length < 8) return null;
|
||||
int count = I32(file, 4);
|
||||
if (count < 0 || 8L + count * 4L > file.Length) return null;
|
||||
var colours = new uint[count];
|
||||
for (int i = 0; i < count; i++) colours[i] = U32(file, 8 + i * 4);
|
||||
return colours;
|
||||
}
|
||||
|
||||
private static void Put(byte[] px, int i, byte r, byte g, byte b, byte a)
|
||||
{
|
||||
px[i * 4] = r; px[i * 4 + 1] = g; px[i * 4 + 2] = b; px[i * 4 + 3] = a;
|
||||
}
|
||||
|
||||
private static Rgba Make(int w, int h, byte[] rgba) => new() { Width = w, Height = h, Pixels = rgba };
|
||||
private static int I32(ReadOnlySpan<byte> s, int at) => System.Buffers.Binary.BinaryPrimitives.ReadInt32LittleEndian(s.Slice(at));
|
||||
private static uint U32(ReadOnlySpan<byte> s, int at) => System.Buffers.Binary.BinaryPrimitives.ReadUInt32LittleEndian(s.Slice(at));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -28,6 +28,11 @@ internal sealed class LocalStatusServer : IDisposable
|
|||
private readonly string? _statusDir; // GET /inventory reads RynthCore.<pid>.inventory.json from here
|
||||
private readonly IconService? _icons; // GET /icon?did=N (portal.dat → PNG); null = disabled
|
||||
private readonly MapService? _maps; // GET /maps + /map?lb&layer (baked dungeon .bin → PNG); null = disabled
|
||||
private readonly WorldMapService? _worldMap; // GET /worldmap (landscape map from cell.dat, JPEG); null = disabled
|
||||
private readonly NavAtlasService? _navAtlas; // GET /nav/search (RynthNav's Atlas, the Travel tab); null = disabled
|
||||
// pid -> the plugin reports raiseXp, from the last status cycle (UpdateRaiseClients). A raise is accepted only
|
||||
// for a client in here (POST /command action "raise"); everything else ignores it.
|
||||
private volatile IReadOnlyDictionary<int, bool> _raiseClients = new Dictionary<int, bool>();
|
||||
private volatile byte[] _latest =
|
||||
Encoding.UTF8.GetBytes("{\"schema\":\"rynthcore.status-agent/1\",\"clientCount\":0,\"clients\":[]}");
|
||||
private CancellationTokenSource? _cts;
|
||||
|
|
@ -43,7 +48,8 @@ internal sealed class LocalStatusServer : IDisposable
|
|||
bool enableStream = false, int streamQuality = 55, int streamIntervalMs = 400,
|
||||
WebRtcVideoService? video = null, VideoSocketService? videoSocket = null,
|
||||
RunArchive? runArchive = null, string? statusDirectory = null,
|
||||
IconService? icons = null, MapService? maps = null)
|
||||
IconService? icons = null, MapService? maps = null, WorldMapService? worldMap = null,
|
||||
NavAtlasService? navAtlas = null)
|
||||
{
|
||||
_prefix = prefix.EndsWith('/') ? prefix : prefix + "/";
|
||||
_token = string.IsNullOrWhiteSpace(token) ? null : token;
|
||||
|
|
@ -57,6 +63,8 @@ internal sealed class LocalStatusServer : IDisposable
|
|||
_statusDir = string.IsNullOrWhiteSpace(statusDirectory) ? null : statusDirectory;
|
||||
_icons = icons;
|
||||
_maps = maps;
|
||||
_worldMap = worldMap;
|
||||
_navAtlas = navAtlas;
|
||||
_listener.Prefixes.Add(_prefix);
|
||||
}
|
||||
|
||||
|
|
@ -73,6 +81,15 @@ internal sealed class LocalStatusServer : IDisposable
|
|||
}
|
||||
}
|
||||
|
||||
/// <summary>The clients the last cycle read, and which take the raise command (thread-safe swap).</summary>
|
||||
public void UpdateRaiseClients(IEnumerable<ClientStatus> clients)
|
||||
{
|
||||
var map = new Dictionary<int, bool>();
|
||||
foreach (var c in clients)
|
||||
if (c.Pid > 0 && c.Source == "status-file" && c.State != "dead") map[c.Pid] = c.RaiseXp;
|
||||
_raiseClients = map;
|
||||
}
|
||||
|
||||
public bool TryStart(out string error)
|
||||
{
|
||||
// Never serve without a token, loopback included: every route but /healthz is behind it.
|
||||
|
|
@ -285,7 +302,8 @@ internal sealed class LocalStatusServer : IDisposable
|
|||
foreach (var e in entries)
|
||||
payload.Maps.Add(new MapEntryDto
|
||||
{
|
||||
Landblock = e.Landblock.ToString("X8"),
|
||||
// Full "XXYY0000" form: what DrakRemote matches a client's landblock against.
|
||||
Landblock = RemoteParity.LandblockFull(e.Landblock.ToString("X8")),
|
||||
Layer = e.Layer, Bytes = e.Bytes, Mtime = e.MtimeUtc,
|
||||
W = e.W, H = e.H, XMin = e.XMin, YMin = e.YMin,
|
||||
Name = "Dungeon " + (e.Landblock & 0xFFFF).ToString("X4"),
|
||||
|
|
@ -380,8 +398,8 @@ internal sealed class LocalStatusServer : IDisposable
|
|||
{ Write(res, 405, "application/json", "{\"error\":\"method not allowed\"}"u8.ToArray()); return; }
|
||||
if (_token != null && !Authorized(req))
|
||||
{ Write(res, 401, "application/json", "{\"error\":\"unauthorized\"}"u8.ToArray()); return; }
|
||||
if (!uint.TryParse(req.QueryString["lb"], System.Globalization.NumberStyles.HexNumber,
|
||||
System.Globalization.CultureInfo.InvariantCulture, out uint lb)
|
||||
// lb in either form: "00005A48" (the file name) or "5A480000" (what /maps lists and the app sends).
|
||||
if (!RemoteParity.TryLandblockShort(req.QueryString["lb"], out uint lb)
|
||||
|| !int.TryParse(req.QueryString["layer"], out int layer))
|
||||
{ Write(res, 400, "application/json", "{\"error\":\"lb (hex) and layer required\"}"u8.ToArray()); return; }
|
||||
var r = _maps?.GetPng(lb, layer);
|
||||
|
|
@ -402,6 +420,68 @@ internal sealed class LocalStatusServer : IDisposable
|
|||
return;
|
||||
}
|
||||
|
||||
// ── Character sheet: GET /character?pid=N — attributes, vitals, skills (the phone's Skills tab) ──
|
||||
if (path == "/character" || path == "/character.json")
|
||||
{
|
||||
if (!string.Equals(method, "GET", StringComparison.OrdinalIgnoreCase))
|
||||
{ Write(res, 405, "application/json", "{\"error\":\"method not allowed\"}"u8.ToArray()); return; }
|
||||
if (_token != null && !Authorized(req))
|
||||
{ Write(res, 401, "application/json", "{\"error\":\"unauthorized\"}"u8.ToArray()); return; }
|
||||
int cpid = int.TryParse(req.QueryString["pid"], out int cp) ? cp : 0;
|
||||
if (cpid <= 0)
|
||||
{ Write(res, 400, "application/json", "{\"error\":\"pid required\"}"u8.ToArray()); return; }
|
||||
byte[]? sheet = ReadClientFile(cpid, "character");
|
||||
if (sheet == null)
|
||||
{ Write(res, 404, "application/json", "{\"error\":\"no character sheet from that client yet (needs the RynthRemote plugin 0.3)\"}"u8.ToArray()); return; }
|
||||
res.Headers["Cache-Control"] = "no-cache";
|
||||
Write(res, 200, "application/json", sheet);
|
||||
return;
|
||||
}
|
||||
|
||||
// ── Travel search: GET /nav/search?q=&type=&ns=&ew=&max= — RynthNav's Atlas, best matches first ──
|
||||
if (path == "/nav/search")
|
||||
{
|
||||
if (!string.Equals(method, "GET", StringComparison.OrdinalIgnoreCase))
|
||||
{ Write(res, 405, "application/json", "{\"error\":\"method not allowed\"}"u8.ToArray()); return; }
|
||||
if (_token != null && !Authorized(req))
|
||||
{ Write(res, 401, "application/json", "{\"error\":\"unauthorized\"}"u8.ToArray()); return; }
|
||||
if (_navAtlas == null || !_navAtlas.Available)
|
||||
{ Write(res, 404, "application/json", "{\"error\":\"RynthNav's Atlas (NavData locations.json) isn't on this PC\"}"u8.ToArray()); return; }
|
||||
var ci = System.Globalization.CultureInfo.InvariantCulture;
|
||||
double? fromNs = double.TryParse(req.QueryString["ns"], System.Globalization.NumberStyles.Float, ci, out double fn) ? fn : null;
|
||||
double? fromEw = double.TryParse(req.QueryString["ew"], System.Globalization.NumberStyles.Float, ci, out double fe) ? fe : null;
|
||||
int max = ClampQuery(req, "max", 40, 1, 100);
|
||||
Write(res, 200, "application/json", _navAtlas.SearchJson(req.QueryString["q"] ?? "", req.QueryString["type"], fromNs, fromEw, max));
|
||||
return;
|
||||
}
|
||||
|
||||
// ── Landscape map: GET /worldmap — Dereth from cell.dat, 2040 px square, 24 units a pixel, north up ──
|
||||
if (path == "/worldmap" || path == "/worldmap.jpg")
|
||||
{
|
||||
if (!string.Equals(method, "GET", StringComparison.OrdinalIgnoreCase))
|
||||
{ Write(res, 405, "application/json", "{\"error\":\"method not allowed\"}"u8.ToArray()); return; }
|
||||
if (_token != null && !Authorized(req))
|
||||
{ Write(res, 401, "application/json", "{\"error\":\"unauthorized\"}"u8.ToArray()); return; }
|
||||
if (_worldMap == null || !_worldMap.Available)
|
||||
{ Write(res, 404, "application/json", "{\"error\":\"world map unavailable (no cell.dat on this PC)\"}"u8.ToArray()); return; }
|
||||
byte[]? jpg = _worldMap.GetJpeg();
|
||||
if (jpg == null)
|
||||
{
|
||||
res.Headers["Retry-After"] = "5";
|
||||
Write(res, 503, "application/json", Encoding.UTF8.GetBytes("{\"error\":\"world map " + _worldMap.State + ", try again shortly\"}"));
|
||||
return;
|
||||
}
|
||||
string wmTag = "\"worldmap-v1-" + jpg.Length + "\"";
|
||||
res.Headers["X-Map-Size"] = WorldMapService.Size.ToString(System.Globalization.CultureInfo.InvariantCulture);
|
||||
res.Headers["X-Map-Units-Per-Pixel"] = WorldMapService.UnitsPerPixel.ToString(System.Globalization.CultureInfo.InvariantCulture);
|
||||
if (string.Equals(req.Headers["If-None-Match"], wmTag, StringComparison.Ordinal))
|
||||
{ res.Headers["ETag"] = wmTag; Write(res, 304, "image/jpeg", Array.Empty<byte>()); return; }
|
||||
res.Headers["Cache-Control"] = "public, max-age=604800";
|
||||
res.Headers["ETag"] = wmTag;
|
||||
Write(res, 200, "image/jpeg", jpg);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!string.Equals(method, "GET", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
Write(res, 405, "application/json", "{\"error\":\"method not allowed\"}"u8.ToArray());
|
||||
|
|
@ -431,10 +511,14 @@ internal sealed class LocalStatusServer : IDisposable
|
|||
"navProfile", "lootProfile", "metaProfile", "settingsProfile",
|
||||
"forceRebuff", "cancelRebuff", "clearBusy", "hideUi", "sendChat",
|
||||
"moveStart", "moveStop",
|
||||
"moveKeepAlive", // hold-to-move protocol 2 (RynthRemote 0.4+): {"dirs":[...]} every ~200 ms while held
|
||||
"setSetting", // change ONE advanced setting (value = {"key":..,"value":..}); RynthAi clamps + persists
|
||||
"click", // mouse click in the stream (value = {"u":..,"v":..,"button":..}); handled by the agent (PostMessage)
|
||||
|
||||
"travel", // RynthNav: go somewhere (value = {"name":..,"ns":..,"ew":..}); the plugin sends /rnav go
|
||||
"travelStop", // RynthNav: stop travelling (/rnav stop)
|
||||
"assess", // request an Assess/Identify of one item (value = item id) — fills inventory appraisal
|
||||
"raise", // spend XP / skill credits (value = {"kind","id","count","cost","nonce"}); known raise-capable pid only
|
||||
"closeClient",
|
||||
};
|
||||
|
||||
|
|
@ -488,12 +572,33 @@ internal sealed class LocalStatusServer : IDisposable
|
|||
}
|
||||
}
|
||||
catch { }
|
||||
bool clicked = ScreenCapture.TryClick(pid, u, v, button);
|
||||
Write(res, clicked ? 202 : 503, "application/json",
|
||||
clicked ? "{\"ok\":true}"u8.ToArray() : "{\"error\":\"click failed (window missing or minimized)\"}"u8.ToArray());
|
||||
var click = ScreenCapture.TryClick(pid, u, v, button);
|
||||
// One line per tap (no token, no query string): which window, where, and what happened, so a
|
||||
// tap that does nothing in game can be told apart from one that never reached the window.
|
||||
AgentLog.Info($"click pid={pid} u={u:0.###} v={v:0.###} {button} -> {click.Result} at {click.X},{click.Y} of {click.Width}x{click.Height}");
|
||||
if (click.Result == ScreenCapture.ClickResult.Posted)
|
||||
Write(res, 202, "application/json", Encoding.UTF8.GetBytes(
|
||||
"{\"ok\":true,\"x\":" + click.X + ",\"y\":" + click.Y + ",\"w\":" + click.Width + ",\"h\":" + click.Height + "}"));
|
||||
else
|
||||
Write(res, 503, "application/json", Encoding.UTF8.GetBytes("{\"error\":\"click failed: " + click.Reason + "\"}"));
|
||||
return;
|
||||
}
|
||||
|
||||
// Raise spends experience, which can't be undone: only for a client this agent reads whose plugin
|
||||
// takes it, and only in the fixed shape (the plugin and the engine check it all again).
|
||||
if (string.Equals(action, "raise", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
int code = RemoteParity.CheckRaise(pid, value, _raiseClients, out string normalized, out string why);
|
||||
if (code != 202)
|
||||
{
|
||||
AgentLog.Warn($"raise refused: pid={pid} {why}");
|
||||
Write(res, code, "application/json", Encoding.UTF8.GetBytes("{\"error\":\"" + why + "\"}"));
|
||||
return;
|
||||
}
|
||||
action = "raise";
|
||||
value = normalized;
|
||||
}
|
||||
|
||||
Directory.CreateDirectory(_commandDir!);
|
||||
PruneStaleCommands();
|
||||
|
||||
|
|
@ -507,7 +612,11 @@ internal sealed class LocalStatusServer : IDisposable
|
|||
File.WriteAllText(tmp, payload, Encoding.UTF8);
|
||||
File.Move(tmp, dest, overwrite: true);
|
||||
|
||||
AgentLog.Info($"command queued: pid={pid} {action}={value}");
|
||||
// Keep-alives arrive ~5 a second per held client: debug only, so the log keeps the presses and releases.
|
||||
if (string.Equals(action, "moveKeepAlive", StringComparison.OrdinalIgnoreCase))
|
||||
AgentLog.Debug($"command queued: pid={pid} {action}={value}");
|
||||
else
|
||||
AgentLog.Info($"command queued: pid={pid} {action}={value}");
|
||||
Write(res, 202, "application/json", "{\"ok\":true}"u8.ToArray());
|
||||
}
|
||||
catch (Exception ex)
|
||||
|
|
@ -571,7 +680,7 @@ internal sealed class LocalStatusServer : IDisposable
|
|||
{
|
||||
string path = Path.Combine(_statusDir, $"RynthCore.{pid}.inventory.json");
|
||||
if (!File.Exists(path)) return EmptyInventory;
|
||||
byte[] bytes = File.ReadAllBytes(path);
|
||||
byte[] bytes = StatusFileCache.ReadAllBytesShared(path); // let the plugin replace it meanwhile
|
||||
return bytes.Length >= 2 ? bytes : EmptyInventory;
|
||||
}
|
||||
catch { return EmptyInventory; }
|
||||
|
|
@ -586,12 +695,26 @@ internal sealed class LocalStatusServer : IDisposable
|
|||
{
|
||||
string path = Path.Combine(_statusDir, $"RynthCore.{pid}.settings.json");
|
||||
if (!File.Exists(path)) return "{}"u8.ToArray();
|
||||
byte[] bytes = File.ReadAllBytes(path);
|
||||
byte[] bytes = StatusFileCache.ReadAllBytesShared(path); // let the plugin replace it meanwhile
|
||||
return bytes.Length >= 2 ? bytes : "{}"u8.ToArray();
|
||||
}
|
||||
catch { return "{}"u8.ToArray(); }
|
||||
}
|
||||
|
||||
/// Read RynthCore.<pid>.<kind>.json (written atomically by the RynthRemote plugin); null when absent.
|
||||
private byte[]? ReadClientFile(int pid, string kind)
|
||||
{
|
||||
if (_statusDir == null) return null;
|
||||
try
|
||||
{
|
||||
string path = Path.Combine(_statusDir, $"RynthCore.{pid}.{kind}.json");
|
||||
if (!File.Exists(path)) return null;
|
||||
byte[] bytes = StatusFileCache.ReadAllBytesShared(path); // let the plugin replace it meanwhile
|
||||
return bytes.Length >= 2 ? bytes : null;
|
||||
}
|
||||
catch { return null; }
|
||||
}
|
||||
|
||||
private static int ClampQuery(HttpListenerRequest req, string key, int def, int lo, int hi)
|
||||
=> int.TryParse(req.QueryString[key], out int v) ? Math.Clamp(v, lo, hi) : def;
|
||||
|
||||
|
|
|
|||
|
|
@ -40,6 +40,107 @@ internal sealed class StatusFileModel
|
|||
[JsonPropertyName("lastIssue")] public string? LastIssue { get; set; }
|
||||
[JsonPropertyName("lastIssueAgeSec")] public long LastIssueAgeSec { get; set; } = -1;
|
||||
[JsonPropertyName("bot")] public BotSnapshot? Bot { get; set; }
|
||||
// Added by the RynthRemote plugin 0.3 (DrakRemote parity): the player's enchantments (ids + seconds
|
||||
// left; the agent adds names/icons from portal.dat) and where the character stands, outdoors too.
|
||||
[JsonPropertyName("enchantments")] public List<EnchantmentIn>? Enchantments { get; set; }
|
||||
[JsonPropertyName("opos")] public PositionIn? Opos { get; set; }
|
||||
// RynthRemote 0.3: the last travel the phone asked RynthNav for (destination, what the plugin did).
|
||||
[JsonPropertyName("travel")] public TravelIn? Travel { get; set; }
|
||||
// RynthRemote 0.4: the phone may raise attributes, vitals and skills on this client (engine API v79,
|
||||
// the client's raise senders bound, in the world). The costs ride the character sheet.
|
||||
[JsonPropertyName("raiseXp")] public bool RaiseXp { get; set; }
|
||||
// RynthRemote 0.4: the hold-to-move protocol it speaks (2 = moveStart {"dir","deadmanMs"} + moveKeepAlive).
|
||||
[JsonPropertyName("moveProto")] public int MoveProto { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>The plugin's record of the last phone travel: where to, and "sent" / "stopped" / "refused".</summary>
|
||||
internal sealed class TravelIn
|
||||
{
|
||||
[JsonPropertyName("dest")] public string Dest { get; set; } = "";
|
||||
[JsonPropertyName("ns")] public double? Ns { get; set; }
|
||||
[JsonPropertyName("ew")] public double? Ew { get; set; }
|
||||
[JsonPropertyName("state")] public string State { get; set; } = "";
|
||||
[JsonPropertyName("detail")] public string Detail { get; set; } = "";
|
||||
[JsonPropertyName("sentAt")] public DateTimeOffset? SentAt { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>The phone's travel status: the plugin's record, RynthNav's latest chat note, and how far is left.</summary>
|
||||
internal sealed class TravelOut
|
||||
{
|
||||
[JsonPropertyName("dest")] public string Dest { get; set; } = "";
|
||||
[JsonPropertyName("ns")] public double? Ns { get; set; }
|
||||
[JsonPropertyName("ew")] public double? Ew { get; set; }
|
||||
/// <summary>sent | arrived | stopped | refused (and "unavailable" when RynthNav isn't loaded).</summary>
|
||||
[JsonPropertyName("state")] public string State { get; set; } = "";
|
||||
[JsonPropertyName("detail")] public string Detail { get; set; } = "";
|
||||
[JsonPropertyName("sentAt")] public DateTimeOffset? SentAt { get; set; }
|
||||
/// <summary>RynthNav's latest "[RynthNav] ..." chat line, without the tag ("walking to Holtburg — ...").</summary>
|
||||
[JsonPropertyName("note")] public string Note { get; set; } = "";
|
||||
/// <summary>Straight-line distance left in RynthNav's units (yd); null indoors or with no target position.</summary>
|
||||
[JsonPropertyName("distance")] public double? Distance { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>One enchantment as the plugin writes it: spell id + seconds left (-1 = never lapses).</summary>
|
||||
internal sealed class EnchantmentIn
|
||||
{
|
||||
[JsonPropertyName("spellId")] public uint SpellId { get; set; }
|
||||
[JsonPropertyName("secondsRemaining")] public double SecondsRemaining { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>Where the character stands (plugin "opos"): absolute world units, the dungeon-map frame.</summary>
|
||||
internal sealed class PositionIn
|
||||
{
|
||||
[JsonPropertyName("cell")] public string Cell { get; set; } = "";
|
||||
[JsonPropertyName("indoor")] public bool Indoor { get; set; }
|
||||
[JsonPropertyName("wx")] public double Wx { get; set; }
|
||||
[JsonPropertyName("wy")] public double Wy { get; set; }
|
||||
[JsonPropertyName("z")] public double Z { get; set; }
|
||||
[JsonPropertyName("heading")] public double? Heading { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>One enchantment as the phone reads it (DrakBot Remote's "enchantments" entry).</summary>
|
||||
internal sealed class EnchantmentOut
|
||||
{
|
||||
[JsonPropertyName("spellId")] public uint SpellId { get; set; }
|
||||
[JsonPropertyName("name")] public string Name { get; set; } = "";
|
||||
[JsonPropertyName("family")] public uint Family { get; set; }
|
||||
[JsonPropertyName("tier")] public int Tier { get; set; }
|
||||
[JsonPropertyName("secondsRemaining")] public double SecondsRemaining { get; set; }
|
||||
[JsonPropertyName("beneficial")] public bool Beneficial { get; set; } = true;
|
||||
[JsonPropertyName("school")] public uint School { get; set; }
|
||||
[JsonPropertyName("iconId")] public uint IconId { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// What this agent can actually do, sent as "capabilities" so the phone hides what doesn't work here
|
||||
/// (without it the app assumes everything the old agent offered). Same names as DrakBot Remote's, plus
|
||||
/// "character" (GET /character, the Skills tab) and "worldMap" (GET /worldmap, the landscape map).
|
||||
/// </summary>
|
||||
internal sealed class AgentCapabilities
|
||||
{
|
||||
[JsonPropertyName("inventory")] public bool Inventory { get; set; }
|
||||
[JsonPropertyName("settings")] public bool Settings { get; set; }
|
||||
[JsonPropertyName("movement")] public bool Movement { get; set; }
|
||||
[JsonPropertyName("chat")] public bool Chat { get; set; }
|
||||
[JsonPropertyName("icons")] public bool Icons { get; set; }
|
||||
[JsonPropertyName("closeClient")] public bool CloseClient { get; set; }
|
||||
[JsonPropertyName("video")] public bool Video { get; set; }
|
||||
[JsonPropertyName("videoMinimized")] public bool VideoMinimized { get; set; }
|
||||
[JsonPropertyName("videoHd")] public bool VideoHd { get; set; }
|
||||
[JsonPropertyName("click")] public bool Click { get; set; }
|
||||
[JsonPropertyName("runs")] public bool Runs { get; set; }
|
||||
[JsonPropertyName("maps")] public bool Maps { get; set; }
|
||||
[JsonPropertyName("dungeon")] public bool Dungeon { get; set; }
|
||||
[JsonPropertyName("act")] public bool Act { get; set; }
|
||||
[JsonPropertyName("nearby")] public bool Nearby { get; set; }
|
||||
[JsonPropertyName("pick")] public bool Pick { get; set; }
|
||||
[JsonPropertyName("character")] public bool Character { get; set; }
|
||||
[JsonPropertyName("worldMap")] public bool WorldMap { get; set; }
|
||||
/// <summary>GET /nav/search + the travel / travelStop commands (RynthNav through the RynthRemote plugin).</summary>
|
||||
[JsonPropertyName("travel")] public bool Travel { get; set; }
|
||||
/// <summary>The raise command: spend unassigned XP (and skill credits) from the Skills tab. Needs remote
|
||||
/// control and a client whose RynthRemote plugin reports raiseXp (engine API v79).</summary>
|
||||
[JsonPropertyName("raiseXp")] public bool RaiseXp { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>The subset of the RynthAi snapshot the agent surfaces.</summary>
|
||||
|
|
@ -228,6 +329,17 @@ internal sealed class ClientStatus
|
|||
[JsonPropertyName("recentChat")] public List<ChatLine>? RecentChat { get; set; }
|
||||
[JsonPropertyName("lastIssue")] public string? LastIssue { get; set; }
|
||||
[JsonPropertyName("lastIssueAgeSec")] public long LastIssueAgeSec { get; set; } = -1;
|
||||
/// <summary>Every enchantment on the character, soonest to lapse first (null = the plugin doesn't say).</summary>
|
||||
[JsonPropertyName("enchantments")] public List<EnchantmentOut>? Enchantments { get; set; }
|
||||
/// <summary>Facing in degrees (0 = north, clockwise) when the plugin reports it, for the map's arrow.</summary>
|
||||
[JsonPropertyName("heading")] public double? Heading { get; set; }
|
||||
/// <summary>The last phone travel and how it stands (null when none this session).</summary>
|
||||
[JsonPropertyName("travel")] public TravelOut? Travel { get; set; }
|
||||
/// <summary>This client takes the raise command (its plugin says so and remote control is on).</summary>
|
||||
[JsonPropertyName("raiseXp")] public bool RaiseXp { get; set; }
|
||||
/// <summary>The hold-to-move protocol this client's plugin speaks: 2 = keep-alives and a dead-man
|
||||
/// (the phone then sends moveKeepAlive), 0 = the old repeated moveStart.</summary>
|
||||
[JsonPropertyName("moveProto")] public int MoveProto { get; set; }
|
||||
}
|
||||
|
||||
internal sealed class AggregatePayload
|
||||
|
|
@ -237,6 +349,7 @@ internal sealed class AggregatePayload
|
|||
[JsonPropertyName("agentVersion")] public string AgentVersion { get; set; } = "";
|
||||
[JsonPropertyName("generatedAtUtc")] public DateTimeOffset GeneratedAtUtc { get; set; }
|
||||
[JsonPropertyName("clientCount")] public int ClientCount { get; set; }
|
||||
[JsonPropertyName("capabilities")] public AgentCapabilities? Capabilities { get; set; }
|
||||
[JsonPropertyName("clients")] public List<ClientStatus> Clients { get; set; } = new();
|
||||
}
|
||||
|
||||
|
|
|
|||
218
src/RynthCore.StatusAgent/NavAtlasService.cs
Normal file
218
src/RynthCore.StatusAgent/NavAtlasService.cs
Normal file
|
|
@ -0,0 +1,218 @@
|
|||
using System.Globalization;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace RynthCore.StatusAgent;
|
||||
|
||||
/// <summary>
|
||||
/// The phone's destination search (GET /nav/search) over RynthNav's own Atlas file, NavData\locations.json
|
||||
/// (towns, dungeons, portals, lifestones, NPCs, vendors...), read here rather than copied: one file, the
|
||||
/// one the in-game Atlas searches. Ranking is RynthNav's (Atlas.MatchScore / TypeRank, copied), so the phone
|
||||
/// lists places in the order the in-game search does; "area" is the nearest town for a place on the map.
|
||||
/// Reloaded when the file changes (NavData updates). The travel itself goes to RynthNav as a /rnav "go"
|
||||
/// through the RynthRemote plugin - the agent never touches RynthNav.
|
||||
/// </summary>
|
||||
internal sealed class NavAtlasService
|
||||
{
|
||||
/// <summary>RynthNav's NavCoords.UnitsPerDegree: one degree of N/S or E/W is 240 units ("yd").</summary>
|
||||
public const double UnitsPerDegree = 240.0;
|
||||
|
||||
internal sealed record Place(int Id, string Name, string Type, string Where, bool OnMap, double Ns, double Ew, string Area,
|
||||
bool Closed, bool Quest, int MinLevel, string DestName);
|
||||
|
||||
private readonly string _path;
|
||||
private readonly object _gate = new();
|
||||
private List<Place>? _places;
|
||||
private DateTime _loadedMtime;
|
||||
private string _generated = "";
|
||||
|
||||
public NavAtlasService(string path) => _path = path;
|
||||
|
||||
public bool Available => File.Exists(_path);
|
||||
|
||||
// ── loading ─────────────────────────────────────────────────────────────
|
||||
|
||||
private List<Place> Places()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
DateTime mtime;
|
||||
try { mtime = File.GetLastWriteTimeUtc(_path); } catch { mtime = default; }
|
||||
if (_places != null && mtime == _loadedMtime) return _places;
|
||||
try
|
||||
{
|
||||
var (places, generated) = Parse(File.ReadAllText(_path));
|
||||
_places = places; _generated = generated; _loadedMtime = mtime;
|
||||
AgentLog.Info($"[nav] Atlas read: {places.Count:N0} places ({generated}).");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
AgentLog.Warn($"[nav] Atlas unreadable ({_path}): {ex.GetType().Name}: {ex.Message}");
|
||||
_places ??= new List<Place>();
|
||||
}
|
||||
return _places;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>locations.json -> places, each on-map one with its nearest town as the area.</summary>
|
||||
internal static (List<Place> Places, string Generated) Parse(string json)
|
||||
{
|
||||
using var doc = JsonDocument.Parse(json);
|
||||
var root = doc.RootElement;
|
||||
string generated = root.TryGetProperty("generated", out var g) && g.ValueKind == JsonValueKind.String ? g.GetString() ?? "" : "";
|
||||
var raw = new List<(int Id, string Name, string Type, string Where, bool OnMap, double Ns, double Ew, bool Closed, bool Quest, int MinLevel, string Dest)>();
|
||||
if (root.TryGetProperty("locations", out var arr) && arr.ValueKind == JsonValueKind.Array)
|
||||
{
|
||||
foreach (var e in arr.EnumerateArray())
|
||||
{
|
||||
bool onMap = TryNum(e, "ns", out double ns) & TryNum(e, "ew", out double ew);
|
||||
string dest = e.TryGetProperty("dest", out var d) && d.ValueKind == JsonValueKind.Object ? Str(d, "name") : "";
|
||||
raw.Add((Int(e, "id"), Str(e, "name"), Str(e, "type"), Str(e, "place"), onMap, ns, ew, Bool(e, "closed"), Bool(e, "quest"), Int(e, "minLevel"), dest));
|
||||
}
|
||||
}
|
||||
var towns = raw.Where(r => r.OnMap && r.Type == "Town").ToList();
|
||||
var places = new List<Place>(raw.Count);
|
||||
foreach (var r in raw)
|
||||
{
|
||||
string area = "";
|
||||
if (r.OnMap && towns.Count > 0)
|
||||
{
|
||||
var near = towns.MinBy(t => Distance(r.Ns, r.Ew, t.Ns, t.Ew));
|
||||
double dist = Distance(r.Ns, r.Ew, near.Ns, near.Ew);
|
||||
area = r.Type == "Town" && near.Name == r.Name ? "" : dist < 1200 ? "near " + near.Name : "";
|
||||
}
|
||||
places.Add(new Place(r.Id, r.Name, r.Type, r.Where, r.OnMap, r.Ns, r.Ew, area, r.Closed, r.Quest, r.MinLevel, r.Dest));
|
||||
}
|
||||
return (places, generated);
|
||||
}
|
||||
|
||||
// ── search ──────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>RynthNav's Atlas.MatchScore: 0 = not a match.</summary>
|
||||
public static int MatchScore(string name, string q)
|
||||
{
|
||||
if (q.Length == 0) return 1;
|
||||
if (name.Equals(q, StringComparison.OrdinalIgnoreCase)) return 100;
|
||||
int at = name.IndexOf(q, StringComparison.OrdinalIgnoreCase);
|
||||
if (at == 0) return 80;
|
||||
if (at > 0) return char.IsLetterOrDigit(name[at - 1]) ? 40 : 60;
|
||||
string[] words = q.Split(' ', StringSplitOptions.RemoveEmptyEntries);
|
||||
if (words.Length < 2) return 0;
|
||||
foreach (string w in words)
|
||||
if (name.IndexOf(w, StringComparison.OrdinalIgnoreCase) < 0) return 0;
|
||||
return 30;
|
||||
}
|
||||
|
||||
/// <summary>RynthNav's Atlas.TypeRank: places before people.</summary>
|
||||
public static int TypeRank(string type) => type switch
|
||||
{
|
||||
"Town" => 0, "Dungeon" => 1, "Landmark" => 2, "Lifestone" => 3, "Bindstone" => 4,
|
||||
"Portal" => 5, "Vendor" => 6, "NPC" => 7, _ => 8,
|
||||
};
|
||||
|
||||
public static double Distance(double ns1, double ew1, double ns2, double ew2)
|
||||
{
|
||||
double dn = (ns2 - ns1) * UnitsPerDegree, de = (ew2 - ew1) * UnitsPerDegree;
|
||||
return Math.Sqrt(dn * dn + de * de);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The best matches for <paramref name="query"/> (at least 2 characters), optionally of one type: best name
|
||||
/// match, then type, then nearest to (<paramref name="fromNs"/>, <paramref name="fromEw"/>) when given,
|
||||
/// then name. At most <paramref name="max"/>.
|
||||
/// </summary>
|
||||
internal static List<(Place Place, double? Distance)> Search(IReadOnlyList<Place> places, string query, string? type, double? fromNs, double? fromEw, int max)
|
||||
{
|
||||
string q = (query ?? "").Trim();
|
||||
var hits = new List<(Place P, int S, double? D)>();
|
||||
if (q.Length < 2) return new();
|
||||
foreach (var p in places)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(type) && !p.Type.Equals(type, StringComparison.OrdinalIgnoreCase)) continue;
|
||||
int s = MatchScore(p.Name, q);
|
||||
if (s == 0) continue;
|
||||
double? d = p.OnMap && fromNs is double fn && fromEw is double fe ? Distance(fn, fe, p.Ns, p.Ew) : null;
|
||||
hits.Add((p, s, d));
|
||||
}
|
||||
hits.Sort((a, b) =>
|
||||
{
|
||||
int c = b.S.CompareTo(a.S);
|
||||
if (c != 0) return c;
|
||||
c = TypeRank(a.P.Type).CompareTo(TypeRank(b.P.Type));
|
||||
if (c != 0) return c;
|
||||
c = (a.D ?? double.MaxValue).CompareTo(b.D ?? double.MaxValue);
|
||||
return c != 0 ? c : string.Compare(a.P.Name, b.P.Name, StringComparison.OrdinalIgnoreCase);
|
||||
});
|
||||
return hits.Take(Math.Clamp(max, 1, 100)).Select(h => (h.P, h.D)).ToList();
|
||||
}
|
||||
|
||||
/// <summary>GET /nav/search's body (schema rynthcore.nav-search/1).</summary>
|
||||
public byte[] SearchJson(string query, string? type, double? fromNs, double? fromEw, int max)
|
||||
{
|
||||
var places = Places();
|
||||
var hits = Search(places, query, type, fromNs, fromEw, max);
|
||||
return Encoding.UTF8.GetBytes(SearchJson(hits, query, places.Count, _generated));
|
||||
}
|
||||
|
||||
internal static string SearchJson(List<(Place Place, double? Distance)> hits, string query, int atlasCount, string generated)
|
||||
{
|
||||
var ci = CultureInfo.InvariantCulture;
|
||||
using var ms = new MemoryStream();
|
||||
using (var w = new Utf8JsonWriter(ms))
|
||||
{
|
||||
w.WriteStartObject();
|
||||
w.WriteString("schema", "rynthcore.nav-search/1");
|
||||
w.WriteString("query", query ?? "");
|
||||
w.WriteNumber("atlasCount", atlasCount);
|
||||
w.WriteString("generated", generated);
|
||||
w.WriteNumber("count", hits.Count);
|
||||
w.WriteStartArray("results");
|
||||
foreach (var (p, d) in hits)
|
||||
{
|
||||
w.WriteStartObject();
|
||||
w.WriteNumber("id", p.Id);
|
||||
w.WriteString("name", p.Name);
|
||||
w.WriteString("type", p.Type);
|
||||
w.WriteString("area", p.Area);
|
||||
w.WriteString("where", p.Where);
|
||||
w.WriteBoolean("onMap", p.OnMap);
|
||||
if (p.OnMap)
|
||||
{
|
||||
w.WriteNumber("ns", Math.Round(p.Ns, 2));
|
||||
w.WriteNumber("ew", Math.Round(p.Ew, 2));
|
||||
w.WriteString("coords", Fmt(p.Ns, p.Ew));
|
||||
}
|
||||
if (d is double dist) w.WriteNumber("distance", Math.Round(dist));
|
||||
if (p.DestName.Length > 0) w.WriteString("dest", p.DestName);
|
||||
if (p.MinLevel > 0) w.WriteNumber("minLevel", p.MinLevel);
|
||||
if (p.Quest) w.WriteBoolean("quest", true);
|
||||
if (p.Closed) w.WriteBoolean("closed", true);
|
||||
// RynthNav walks only to places with a map position; a place inside a dungeon has none.
|
||||
w.WriteBoolean("canTravel", p.OnMap && !p.Closed);
|
||||
w.WriteEndObject();
|
||||
}
|
||||
w.WriteEndArray();
|
||||
w.WriteEndObject();
|
||||
}
|
||||
return Encoding.UTF8.GetString(ms.ToArray());
|
||||
}
|
||||
|
||||
/// <summary>RynthNav's NavCoords.Fmt: "42.1N, 33.6E".</summary>
|
||||
public static string Fmt(double ns, double ew)
|
||||
{
|
||||
var ci = CultureInfo.InvariantCulture;
|
||||
return Math.Abs(ns).ToString("F1", ci) + (ns >= 0 ? "N" : "S") + ", " + Math.Abs(ew).ToString("F1", ci) + (ew >= 0 ? "E" : "W");
|
||||
}
|
||||
|
||||
/// <summary>The status frame's absolute world units to map coordinates (RynthNav's own conversion).</summary>
|
||||
public static (double Ns, double Ew) FromWorld(double wx, double wy) => ((wy / 24.0 - 1019.5) / 10.0, (wx / 24.0 - 1019.5) / 10.0);
|
||||
|
||||
private static string Str(JsonElement e, string n) => e.TryGetProperty(n, out var v) && v.ValueKind == JsonValueKind.String ? v.GetString() ?? "" : "";
|
||||
private static int Int(JsonElement e, string n) => e.TryGetProperty(n, out var v) && v.ValueKind == JsonValueKind.Number && v.TryGetInt32(out int i) ? i : 0;
|
||||
private static bool Bool(JsonElement e, string n) => e.TryGetProperty(n, out var v) && v.ValueKind == JsonValueKind.True;
|
||||
private static bool TryNum(JsonElement e, string n, out double d)
|
||||
{
|
||||
d = 0;
|
||||
return e.TryGetProperty(n, out var v) && v.ValueKind == JsonValueKind.Number && v.TryGetDouble(out d);
|
||||
}
|
||||
}
|
||||
|
|
@ -53,6 +53,13 @@ if (publisher.Enabled)
|
|||
else
|
||||
AgentLog.Info("No endpoint configured -> LOCAL PRINT-ONLY mode (nothing is sent anywhere).");
|
||||
|
||||
// The client's spell table (portal.dat), loaded once in the background: names + icons for the Buffs tab.
|
||||
var spells = new SpellTableService(cfg.IconDatPath);
|
||||
// The landscape map (cell.dat -> one cached JPEG), rendered on the first /worldmap request.
|
||||
var worldMap = new WorldMapService(cfg.CellDatPath, cfg.StatusDirectory);
|
||||
// RynthNav's Atlas (NavData\locations.json), searched for the phone's Travel tab.
|
||||
var navAtlas = new NavAtlasService(cfg.NavAtlasPath);
|
||||
|
||||
// Opt-in pull endpoint: an app can fetch status with no backend.
|
||||
LocalStatusServer? server = null;
|
||||
WebRtcVideoService? video = null; // HD WebRTC video mode (opt-in); disposed in finally
|
||||
|
|
@ -80,7 +87,7 @@ else if (cfg.ServeHttp)
|
|||
MapService maps = new MapService(cfg.MapsDirectory);
|
||||
server = new LocalStatusServer(cfg.ServePrefix, cfg.ServeToken, commandDir,
|
||||
cfg.EnableScreenStream, cfg.StreamQuality, cfg.StreamIntervalMs, video, videoSocket,
|
||||
runArchive, cfg.StatusDirectory, icons, maps);
|
||||
runArchive, cfg.StatusDirectory, icons, maps, worldMap, navAtlas);
|
||||
if (server.TryStart(out string serveErr))
|
||||
{
|
||||
AgentLog.Info($"Serving status at {cfg.ServePrefix}status (GET){(string.IsNullOrEmpty(cfg.ServeToken) ? "" : ", token required")}.");
|
||||
|
|
@ -159,7 +166,7 @@ return 0;
|
|||
// One status cycle: read all client status, roll it up, and serve / file / POST it.
|
||||
async Task RunCycleAsync()
|
||||
{
|
||||
List<ClientStatus> clients = StatusReader.ReadAll(cfg);
|
||||
List<ClientStatus> clients = StatusReader.ReadAll(cfg, spells);
|
||||
runArchive.Observe(clients); // fold this cycle into per-session run history (started/updated/finished)
|
||||
var payload = new AggregatePayload
|
||||
{
|
||||
|
|
@ -167,6 +174,14 @@ async Task RunCycleAsync()
|
|||
AgentVersion = version,
|
||||
GeneratedAtUtc = DateTimeOffset.UtcNow,
|
||||
ClientCount = clients.Count,
|
||||
// What works on this PC, so the phone stops assuming DrakBot-era "everything".
|
||||
Capabilities = RemoteParity.Capabilities(cfg,
|
||||
iconDat: File.Exists(cfg.IconDatPath),
|
||||
dungeonMaps: Directory.Exists(cfg.MapsDirectory),
|
||||
worldMap: worldMap.Available,
|
||||
characterSheets: clients.Any(c => File.Exists(Path.Combine(cfg.StatusDirectory, $"RynthCore.{c.Pid}.character.json"))),
|
||||
navAtlas: navAtlas.Available,
|
||||
raiseXp: clients.Any(c => c.RaiseXp)),
|
||||
Clients = clients,
|
||||
};
|
||||
|
||||
|
|
@ -178,6 +193,7 @@ async Task RunCycleAsync()
|
|||
AgentLog.Debug(System.Text.Encoding.UTF8.GetString(bytes));
|
||||
|
||||
server?.UpdateLatest(bytes);
|
||||
server?.UpdateRaiseClients(clients);
|
||||
|
||||
if (cfg.WriteAggregateFile)
|
||||
{
|
||||
|
|
|
|||
223
src/RynthCore.StatusAgent/RemoteParity.cs
Normal file
223
src/RynthCore.StatusAgent/RemoteParity.cs
Normal file
|
|
@ -0,0 +1,223 @@
|
|||
using System.Globalization;
|
||||
|
||||
namespace RynthCore.StatusAgent;
|
||||
|
||||
/// <summary>
|
||||
/// The pieces that make a RynthCore client look to DrakRemote the way a DrakBot client does
|
||||
/// (2026-10-05 parity work): landblock ids in the form the app matches on, the capabilities block,
|
||||
/// enchantments with names and icons, and the tap-to-click coordinate mapping. Pure functions, so the
|
||||
/// agent tests (tools\StatusAgentTests) cover them without a game running.
|
||||
/// </summary>
|
||||
internal static class RemoteParity
|
||||
{
|
||||
// ── landblocks ──────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// A landblock as DrakRemote matches it: the full cell-style id "XXYY0000". The engine (and the baked
|
||||
/// floor-plan file names) write the short form "0000XXYY"; DrakBot writes the full one, and since
|
||||
/// DrakRemote f87130c the app reads a short map id as full (shifts it) but takes the client's id as
|
||||
/// written - so a RynthCore client never matched its own dungeon's maps. Writing both full fixes it
|
||||
/// for the phone already installed. Empty or unparseable stays as it was.
|
||||
/// </summary>
|
||||
public static string LandblockFull(string? landblock)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(landblock)) return "";
|
||||
if (!uint.TryParse(landblock.Trim(), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out uint v)) return landblock;
|
||||
if (v == 0) return "";
|
||||
uint full = v <= 0xFFFF ? v << 16 : v & 0xFFFF0000u;
|
||||
return full.ToString("X8", CultureInfo.InvariantCulture);
|
||||
}
|
||||
|
||||
/// <summary>The short landblock (0xXXYY) from either form ("5A48", "00005A48", "5A480000", "5A48013F").</summary>
|
||||
public static bool TryLandblockShort(string? s, out uint lb)
|
||||
{
|
||||
lb = 0;
|
||||
if (string.IsNullOrWhiteSpace(s)
|
||||
|| !uint.TryParse(s.Trim(), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out uint v)) return false;
|
||||
lb = v > 0xFFFF ? v >> 16 : v;
|
||||
return lb != 0;
|
||||
}
|
||||
|
||||
// ── capabilities ────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>What the agent offers, from its config and what is on this box. act / nearby / pick /
|
||||
/// dungeon are DrakBot's (no RynthCore route for them yet), and a scraped window has no picture while
|
||||
/// minimized, so those stay off.</summary>
|
||||
public static AgentCapabilities Capabilities(AgentConfig cfg, bool iconDat, bool dungeonMaps, bool worldMap, bool characterSheets, bool navAtlas = false, bool raiseXp = false)
|
||||
{
|
||||
bool control = cfg.EnableRemoteControl;
|
||||
return new AgentCapabilities
|
||||
{
|
||||
Inventory = true,
|
||||
Settings = true,
|
||||
Movement = control,
|
||||
Chat = true,
|
||||
Icons = iconDat,
|
||||
CloseClient = control,
|
||||
Video = cfg.EnableScreenStream,
|
||||
VideoMinimized = false,
|
||||
VideoHd = cfg.EnableVideoStream,
|
||||
Click = control && cfg.EnableScreenStream,
|
||||
Runs = true,
|
||||
Maps = dungeonMaps || worldMap,
|
||||
Dungeon = false,
|
||||
Act = false,
|
||||
Nearby = false,
|
||||
Pick = false,
|
||||
Character = characterSheets,
|
||||
WorldMap = worldMap,
|
||||
// Searching needs the Atlas; going needs the command channel the travel rides on.
|
||||
Travel = navAtlas && control,
|
||||
// Spending XP rides the command channel and needs a client whose plugin can (engine API v79).
|
||||
RaiseXp = raiseXp && control && characterSheets,
|
||||
};
|
||||
}
|
||||
|
||||
// ── raise (spend XP / skill credits from the Skills tab) ────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Checks a phone raise before it becomes a command file and rewrites the value in a fixed shape:
|
||||
/// {"kind":"attribute|vital|skill|train","id":N or "health|stamina|mana","count":1..100,"cost":N,"nonce":".."}.
|
||||
/// The pid must be a client this agent reads whose plugin reports raiseXp (<paramref name="raiseClients"/>:
|
||||
/// pid -> raiseXp). Returns the HTTP status to answer with (202 = write the command) and why not.
|
||||
/// The plugin and the engine check everything again (the engine against fresh numbers and the cost).
|
||||
/// </summary>
|
||||
public static int CheckRaise(int pid, string? value, IReadOnlyDictionary<int, bool> raiseClients, out string normalized, out string error)
|
||||
{
|
||||
normalized = "";
|
||||
error = "";
|
||||
if (!raiseClients.TryGetValue(pid, out bool can)) { error = "unknown client"; return 404; }
|
||||
if (!can) { error = "raising isn't available on that client (needs the RynthRemote plugin 0.4 and a RynthCore engine with plugin API 79)"; return 409; }
|
||||
if (string.IsNullOrWhiteSpace(value)) { error = "bad raise"; return 400; }
|
||||
try
|
||||
{
|
||||
using var doc = System.Text.Json.JsonDocument.Parse(value);
|
||||
var r = doc.RootElement;
|
||||
if (r.ValueKind != System.Text.Json.JsonValueKind.Object) { error = "bad raise"; return 400; }
|
||||
string kind = r.TryGetProperty("kind", out var k) && k.ValueKind == System.Text.Json.JsonValueKind.String ? (k.GetString() ?? "").ToLowerInvariant() : "";
|
||||
if (kind is not ("attribute" or "vital" or "skill" or "train")) { error = "bad raise kind"; return 400; }
|
||||
|
||||
string id;
|
||||
if (!r.TryGetProperty("id", out var idEl)) { error = "bad raise id"; return 400; }
|
||||
if (idEl.ValueKind == System.Text.Json.JsonValueKind.Number && idEl.TryGetInt32(out int n))
|
||||
{
|
||||
bool ok = kind switch { "attribute" => n is >= 1 and <= 6, "vital" => n is 1 or 3 or 5, _ => n is >= 1 and <= 54 };
|
||||
if (!ok) { error = "bad raise id"; return 400; }
|
||||
id = n.ToString(CultureInfo.InvariantCulture);
|
||||
}
|
||||
else if (kind == "vital" && idEl.ValueKind == System.Text.Json.JsonValueKind.String
|
||||
&& (idEl.GetString() ?? "").ToLowerInvariant() is "health" or "stamina" or "mana")
|
||||
id = "\"" + idEl.GetString()!.ToLowerInvariant() + "\"";
|
||||
else { error = "bad raise id"; return 400; }
|
||||
|
||||
int count = 1;
|
||||
if (kind != "train" && r.TryGetProperty("count", out var c)
|
||||
&& (c.ValueKind != System.Text.Json.JsonValueKind.Number || !c.TryGetInt32(out count) || count < 1 || count > 100))
|
||||
{ error = "bad raise count"; return 400; }
|
||||
|
||||
if (!r.TryGetProperty("cost", out var costEl) || costEl.ValueKind != System.Text.Json.JsonValueKind.Number
|
||||
|| !costEl.TryGetInt64(out long cost) || cost <= 0 || cost > uint.MaxValue)
|
||||
{ error = "a raise needs the confirmed cost"; return 400; }
|
||||
|
||||
string nonce = "";
|
||||
if (r.TryGetProperty("nonce", out var nEl) && nEl.ValueKind == System.Text.Json.JsonValueKind.String)
|
||||
foreach (char ch in nEl.GetString() ?? "")
|
||||
if (nonce.Length < 40 && (char.IsAsciiLetterOrDigit(ch) || ch == '-' || ch == '_')) nonce += ch;
|
||||
|
||||
normalized = "{\"kind\":\"" + kind + "\",\"id\":" + id
|
||||
+ ",\"count\":" + count.ToString(CultureInfo.InvariantCulture)
|
||||
+ ",\"cost\":" + cost.ToString(CultureInfo.InvariantCulture)
|
||||
+ ",\"nonce\":\"" + nonce + "\"}";
|
||||
return 202;
|
||||
}
|
||||
catch (System.Text.Json.JsonException) { error = "bad raise"; return 400; }
|
||||
}
|
||||
|
||||
// ── travel ──────────────────────────────────────────────────────────────
|
||||
|
||||
private const string NavTag = "[RynthNav] ";
|
||||
|
||||
/// <summary>
|
||||
/// The phone's travel status: the plugin's record of what it sent, RynthNav's latest chat note (its
|
||||
/// "[RynthNav] ..." lines reach the status's recent chat), "arrived" when that note says so, and the
|
||||
/// straight-line distance left while outdoors. RynthNav's own progress line and ETA are not reachable
|
||||
/// from another plugin (its status export isn't a RynthPluginGet*Json), so the note stands in for them.
|
||||
/// </summary>
|
||||
public static TravelOut? Travel(TravelIn? t, IReadOnlyList<ChatLine>? recentChat, bool indoor, double wx, double wy)
|
||||
{
|
||||
if (t == null || string.IsNullOrEmpty(t.State)) return null;
|
||||
string note = "";
|
||||
if (recentChat != null)
|
||||
for (int i = recentChat.Count - 1; i >= 0; i--)
|
||||
{
|
||||
string line = recentChat[i].Text ?? "";
|
||||
if (line.StartsWith(NavTag, StringComparison.Ordinal)) { note = line[NavTag.Length..].Trim(); break; }
|
||||
}
|
||||
string state = t.State;
|
||||
if (state == "sent" && note.StartsWith("Arrived at ", StringComparison.Ordinal)
|
||||
&& (t.Dest.Length == 0 || note.Contains(t.Dest, StringComparison.OrdinalIgnoreCase)))
|
||||
state = "arrived";
|
||||
double? left = null;
|
||||
if (!indoor && (wx != 0 || wy != 0) && t.Ns is double dns && t.Ew is double dew)
|
||||
{
|
||||
var (ns, ew) = NavAtlasService.FromWorld(wx, wy);
|
||||
left = Math.Round(NavAtlasService.Distance(ns, ew, dns, dew));
|
||||
}
|
||||
return new TravelOut { Dest = t.Dest, Ns = t.Ns, Ew = t.Ew, State = state, Detail = t.Detail, SentAt = t.SentAt, Note = note, Distance = left };
|
||||
}
|
||||
|
||||
// ── enchantments ────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>The plugin's bare enchantments with the spell table's name, family, tier, school,
|
||||
/// beneficial flag and icon; "Spell N" (beneficial, no icon) for one the table doesn't know.</summary>
|
||||
public static List<EnchantmentOut>? Enchantments(List<EnchantmentIn>? input, Func<uint, SpellTableService.SpellInfo?> lookup)
|
||||
{
|
||||
if (input == null) return null;
|
||||
var list = new List<EnchantmentOut>(input.Count);
|
||||
foreach (var e in input)
|
||||
{
|
||||
if (e.SpellId == 0) continue;
|
||||
var info = lookup(e.SpellId);
|
||||
string name = info is { Name.Length: > 0 } i ? i.Name : "Spell " + e.SpellId.ToString(CultureInfo.InvariantCulture);
|
||||
list.Add(new EnchantmentOut
|
||||
{
|
||||
SpellId = e.SpellId,
|
||||
Name = name,
|
||||
Family = info?.Category ?? 0,
|
||||
Tier = SpellTableService.TierFromName(name),
|
||||
SecondsRemaining = double.IsFinite(e.SecondsRemaining) ? e.SecondsRemaining : -1,
|
||||
Beneficial = info?.Beneficial ?? true,
|
||||
School = info?.School ?? 0,
|
||||
IconId = info?.Icon ?? 0,
|
||||
});
|
||||
}
|
||||
// Soonest first; the never-lapsing ones (-1) last, as DrakBot orders them for the countdown.
|
||||
list.Sort(static (a, b) =>
|
||||
{
|
||||
bool ap = a.SecondsRemaining < 0, bp = b.SecondsRemaining < 0;
|
||||
if (ap != bp) return ap ? 1 : -1;
|
||||
int c = a.SecondsRemaining.CompareTo(b.SecondsRemaining);
|
||||
return c != 0 ? c : a.SpellId.CompareTo(b.SpellId);
|
||||
});
|
||||
return list;
|
||||
}
|
||||
|
||||
// ── tap-to-click ────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// The client-area pixel a phone tap lands on: (u, v) in 0..1 of the frame the stream shows (the
|
||||
/// window's client area, origin top-left, same aspect - a downscaled stream keeps it), so x = u * (w-1),
|
||||
/// y = v * (h-1), clamped. The app has already taken the letterbox out (rynthTap.normalize).
|
||||
/// </summary>
|
||||
public static (int X, int Y) ClickPoint(double u, double v, int clientWidth, int clientHeight)
|
||||
{
|
||||
if (!double.IsFinite(u)) u = 0;
|
||||
if (!double.IsFinite(v)) v = 0;
|
||||
int x = (int)Math.Round(Math.Clamp(u, 0, 1) * Math.Max(0, clientWidth - 1));
|
||||
int y = (int)Math.Round(Math.Clamp(v, 0, 1) * Math.Max(0, clientHeight - 1));
|
||||
return (x, y);
|
||||
}
|
||||
|
||||
/// <summary>A mouse message's lParam: y in the high word, x in the low.</summary>
|
||||
public static IntPtr MouseLParam(int x, int y) => (IntPtr)unchecked((int)(((uint)(y & 0xFFFF) << 16) | (uint)(x & 0xFFFF)));
|
||||
}
|
||||
|
|
@ -123,26 +123,49 @@ internal static class ScreenCapture
|
|||
/// Device::WndProc dispatches WM_LBUTTONDOWN/etc by lParam, never GetCursorPos), so this drives both the
|
||||
/// 2D UI and 3D-world hit-test WITHOUT moving the real cursor or stealing focus, even when the window is
|
||||
/// backgrounded/occluded — multibox-safe. Returns false if the window is missing or minimized.
|
||||
public static bool TryClick(int pid, double u, double v, string? button)
|
||||
public enum ClickResult { Posted, NotFound, Minimized, NoClientArea, PostFailed }
|
||||
|
||||
/// <summary>What one tap did: where it went in the client area (and how big that is), or why not.</summary>
|
||||
public readonly record struct ClickOutcome(ClickResult Result, int X, int Y, int Width, int Height)
|
||||
{
|
||||
public string Reason => Result switch
|
||||
{
|
||||
ClickResult.Posted => "posted",
|
||||
ClickResult.NotFound => "no game window for that pid",
|
||||
ClickResult.Minimized => "the game window is minimized",
|
||||
ClickResult.NoClientArea => "the game window has no client area",
|
||||
_ => "PostMessage failed",
|
||||
};
|
||||
}
|
||||
|
||||
// Give the game a frame between the move and the press, and between press and release: RynthCore
|
||||
// can throttle a background client (Background FPS, 5..60), and a move + press + release that all land
|
||||
// inside one frame can read to AC as a press at the old cursor spot, or as nothing at all.
|
||||
private const int MoveSettleMs = 60;
|
||||
private const int PressHoldMs = 90;
|
||||
|
||||
public static ClickOutcome TryClick(int pid, double u, double v, string? button)
|
||||
{
|
||||
EnsureDpiAware();
|
||||
if (!TryFindWindow(pid, out IntPtr hwnd, out bool minimized) || minimized || hwnd == IntPtr.Zero) return false;
|
||||
if (!GetClientRect(hwnd, out RECT cr)) return false;
|
||||
if (!TryFindWindow(pid, out IntPtr hwnd, out bool minimized) || hwnd == IntPtr.Zero)
|
||||
return new ClickOutcome(minimized ? ClickResult.Minimized : ClickResult.NotFound, 0, 0, 0, 0);
|
||||
if (!GetClientRect(hwnd, out RECT cr)) return new ClickOutcome(ClickResult.NoClientArea, 0, 0, 0, 0);
|
||||
int cw = cr.Right - cr.Left, ch = cr.Bottom - cr.Top;
|
||||
if (cw < 2 || ch < 2) return false;
|
||||
int x = (int)Math.Round(Math.Clamp(u, 0, 1) * (cw - 1));
|
||||
int y = (int)Math.Round(Math.Clamp(v, 0, 1) * (ch - 1));
|
||||
IntPtr lParam = (IntPtr)unchecked((uint)((y << 16) | (x & 0xFFFF)));
|
||||
if (cw < 2 || ch < 2) return new ClickOutcome(ClickResult.NoClientArea, 0, 0, cw, ch);
|
||||
var (x, y) = RemoteParity.ClickPoint(u, v, cw, ch);
|
||||
IntPtr lParam = RemoteParity.MouseLParam(x, y);
|
||||
bool right = string.Equals(button, "right", StringComparison.OrdinalIgnoreCase);
|
||||
IntPtr held = (IntPtr)(right ? MK_RBUTTON : MK_LBUTTON);
|
||||
try
|
||||
{
|
||||
PostMessage(hwnd, WM_MOUSEMOVE, IntPtr.Zero, lParam);
|
||||
PostMessage(hwnd, right ? WM_RBUTTONDOWN : WM_LBUTTONDOWN, (IntPtr)(right ? 0x0002 : 0x0001), lParam);
|
||||
System.Threading.Thread.Sleep(80); // brief down→up so AC registers a click, not a drag
|
||||
if (!PostMessage(hwnd, WM_MOUSEMOVE, IntPtr.Zero, lParam)) return new ClickOutcome(ClickResult.PostFailed, x, y, cw, ch);
|
||||
System.Threading.Thread.Sleep(MoveSettleMs);
|
||||
PostMessage(hwnd, right ? WM_RBUTTONDOWN : WM_LBUTTONDOWN, held, lParam);
|
||||
System.Threading.Thread.Sleep(PressHoldMs); // down→up apart so AC registers a click, not a drag
|
||||
PostMessage(hwnd, right ? WM_RBUTTONUP : WM_LBUTTONUP, IntPtr.Zero, lParam);
|
||||
return true;
|
||||
return new ClickOutcome(ClickResult.Posted, x, y, cw, ch);
|
||||
}
|
||||
catch { return false; }
|
||||
catch { return new ClickOutcome(ClickResult.PostFailed, x, y, cw, ch); }
|
||||
}
|
||||
|
||||
/// Pick the game window for this pid: the largest visible, non-minimized acclient-class window. The
|
||||
|
|
@ -198,6 +221,7 @@ internal static class ScreenCapture
|
|||
[DllImport("user32.dll")] private static extern bool GetClientRect(IntPtr hWnd, out RECT r);
|
||||
[DllImport("user32.dll")] private static extern bool PostMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
|
||||
private const uint WM_MOUSEMOVE = 0x0200, WM_LBUTTONDOWN = 0x0201, WM_LBUTTONUP = 0x0202, WM_RBUTTONDOWN = 0x0204, WM_RBUTTONUP = 0x0205;
|
||||
private const int MK_LBUTTON = 0x0001, MK_RBUTTON = 0x0002;
|
||||
[DllImport("user32.dll")] private static extern bool ClientToScreen(IntPtr hWnd, ref POINT p);
|
||||
private delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
|
||||
[DllImport("user32.dll")] private static extern bool EnumWindows(EnumWindowsProc cb, IntPtr lParam);
|
||||
|
|
|
|||
150
src/RynthCore.StatusAgent/SpellTableService.cs
Normal file
150
src/RynthCore.StatusAgent/SpellTableService.cs
Normal file
|
|
@ -0,0 +1,150 @@
|
|||
using RynthCore2.TerrainData;
|
||||
|
||||
namespace RynthCore.StatusAgent;
|
||||
|
||||
/// <summary>
|
||||
/// The client's spell table (portal.dat file 0x0E00000E), read once in the background so the agent can
|
||||
/// turn the plugin's bare enchantment ids into what the phone's Buffs tab shows: name, family (category),
|
||||
/// tier, school, beneficial or not, and the spell's icon. Same layout and parse as the engine's
|
||||
/// RynthCore.Engine/ImGui/MonsterHud/PortalSpellTable.cs (ACE.DatLoader SpellTable/SpellBase); this
|
||||
/// copy keeps every spell, not just the debuffs. Until it is loaded (or if portal.dat is missing) a
|
||||
/// lookup misses and the agent writes "Spell N" with no icon - the countdown still works.
|
||||
/// </summary>
|
||||
internal sealed class SpellTableService
|
||||
{
|
||||
private const uint SpellTableFileId = 0x0E00000E;
|
||||
private const uint FlagBeneficial = 0x4;
|
||||
private const uint MetaEnchantment = 1, MetaPortalSummon = 7, MetaFellowEnchantment = 12;
|
||||
|
||||
internal readonly record struct SpellInfo(uint Id, string Name, uint School, uint Icon, uint Category, uint Flags)
|
||||
{
|
||||
public bool Beneficial => (Flags & FlagBeneficial) != 0;
|
||||
}
|
||||
|
||||
private readonly string _datPath;
|
||||
private volatile Dictionary<uint, SpellInfo>? _table;
|
||||
private int _queued;
|
||||
|
||||
public SpellTableService(string portalDatPath) => _datPath = portalDatPath;
|
||||
|
||||
public bool Ready => _table != null;
|
||||
|
||||
/// <summary>A spell by id, once the table is in; queues the one-time load on first use. Any thread.</summary>
|
||||
public bool TryGet(uint spellId, out SpellInfo info)
|
||||
{
|
||||
var t = _table;
|
||||
if (t == null)
|
||||
{
|
||||
EnsureLoadQueued();
|
||||
info = default;
|
||||
return false;
|
||||
}
|
||||
return t.TryGetValue(spellId, out info);
|
||||
}
|
||||
|
||||
public void EnsureLoadQueued()
|
||||
{
|
||||
if (_table != null || Interlocked.Exchange(ref _queued, 1) == 1) return;
|
||||
_ = Task.Run(Load);
|
||||
}
|
||||
|
||||
private void Load()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!File.Exists(_datPath)) { AgentLog.Warn($"[spells] portal.dat not found at '{_datPath}'; buff names fall back to spell ids."); return; }
|
||||
using var db = new DatDatabase();
|
||||
if (!db.Open(_datPath)) { AgentLog.Warn($"[spells] could not open '{_datPath}'."); return; }
|
||||
byte[]? raw = db.GetFileData(SpellTableFileId);
|
||||
if (raw == null) { AgentLog.Warn("[spells] spell table 0x0E00000E not in portal.dat."); return; }
|
||||
var t = Parse(raw, out int total);
|
||||
_table = t;
|
||||
AgentLog.Info($"[spells] spell table read: {t.Count:N0} of {total:N0} spells.");
|
||||
}
|
||||
catch (Exception ex) { AgentLog.Warn($"[spells] spell table read failed: {ex.GetType().Name}: {ex.Message}"); }
|
||||
}
|
||||
|
||||
/// <summary>Parse the SpellTable file. Public for the agent tests (a hand-built table).</summary>
|
||||
internal static Dictionary<uint, SpellInfo> Parse(byte[] raw, out int total)
|
||||
{
|
||||
var t = new Dictionary<uint, SpellInfo>();
|
||||
var r = new SpanReader(raw);
|
||||
r.U32(); // file id
|
||||
total = r.U16();
|
||||
r.U16(); // bucket count
|
||||
for (int i = 0; i < total && r.Ok; i++)
|
||||
{
|
||||
uint id = r.U32();
|
||||
string name = r.ObfuscatedString();
|
||||
r.ObfuscatedString(); // description
|
||||
uint school = r.U32();
|
||||
uint icon = r.U32();
|
||||
uint category = r.U32();
|
||||
uint flags = r.U32();
|
||||
r.U32(); // base mana
|
||||
r.Skip(8); // range constant, range mod
|
||||
r.U32(); // power
|
||||
r.Skip(12); // economy mod, formula version, component loss
|
||||
uint meta = r.U32();
|
||||
r.U32(); // meta spell id
|
||||
if (meta == MetaEnchantment || meta == MetaFellowEnchantment) r.Skip(16); // duration f64, degrade mod, degrade limit
|
||||
else if (meta == MetaPortalSummon) r.Skip(8); // portal lifetime
|
||||
r.Skip(8 * 4 + 12 + 8 + 4 + 12); // components, effects, recovery, display order, target type, mana mod
|
||||
if (!r.Ok) break;
|
||||
t[id] = new SpellInfo(id, name, school, icon, category, flags);
|
||||
}
|
||||
return t;
|
||||
}
|
||||
|
||||
/// <summary>The spell's level 1-8 from its name: a Roman suffix ("... VII"), "Incantation of" = 8,
|
||||
/// otherwise 0 (unknown). Matches RynthAi's SpellInfo.ComputeLevel closely enough for display.</summary>
|
||||
internal static int TierFromName(string name)
|
||||
{
|
||||
if (string.IsNullOrEmpty(name)) return 0;
|
||||
if (name.StartsWith("Incantation of ", StringComparison.OrdinalIgnoreCase)) return 8;
|
||||
int sp = name.LastIndexOf(' ');
|
||||
string last = sp >= 0 ? name[(sp + 1)..] : name;
|
||||
return last switch
|
||||
{
|
||||
"I" => 1, "II" => 2, "III" => 3, "IV" => 4, "V" => 5, "VI" => 6, "VII" => 7, "VIII" => 8,
|
||||
_ => 0,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Bounds-checked little-endian reader; Ok turns false on overrun.</summary>
|
||||
private ref struct SpanReader
|
||||
{
|
||||
private readonly ReadOnlySpan<byte> _b;
|
||||
private int _p;
|
||||
public bool Ok;
|
||||
|
||||
public SpanReader(byte[] b) { _b = b; _p = 0; Ok = true; }
|
||||
|
||||
private bool Has(int n)
|
||||
{
|
||||
if (Ok && _p + n <= _b.Length) return true;
|
||||
Ok = false;
|
||||
return false;
|
||||
}
|
||||
|
||||
public uint U32() { if (!Has(4)) return 0; uint v = BitConverter.ToUInt32(_b.Slice(_p, 4)); _p += 4; return v; }
|
||||
public ushort U16() { if (!Has(2)) return 0; ushort v = BitConverter.ToUInt16(_b.Slice(_p, 2)); _p += 2; return v; }
|
||||
public void Skip(int n) { if (Has(n)) _p += n; }
|
||||
|
||||
/// <summary>u16 length + bytes with nibbles swapped, then aligned to 4 from the file start (as ACE does).</summary>
|
||||
public string ObfuscatedString()
|
||||
{
|
||||
int n = U16();
|
||||
if (!Has(n)) return "";
|
||||
var chars = new char[n];
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
byte x = _b[_p + i];
|
||||
chars[i] = (char)(byte)((x >> 4) | (x << 4)); // Latin-1: byte == code point
|
||||
}
|
||||
_p += n;
|
||||
_p = (_p + 3) & ~3;
|
||||
return new string(chars);
|
||||
}
|
||||
}
|
||||
}
|
||||
75
src/RynthCore.StatusAgent/StatusFileCache.cs
Normal file
75
src/RynthCore.StatusAgent/StatusFileCache.cs
Normal file
|
|
@ -0,0 +1,75 @@
|
|||
using System.Collections.Concurrent;
|
||||
using System.Text;
|
||||
|
||||
namespace RynthCore.StatusAgent;
|
||||
|
||||
/// <summary>
|
||||
/// Reading the per-client files the RynthRemote plugin rewrites several times a second, without ever
|
||||
/// dropping a client from a snapshot.
|
||||
///
|
||||
/// <para>Before (2026-10-05): while the agent was reading a status file, the plugin's atomic replace
|
||||
/// (File.Move over it) failed (Windows won't replace an open file), and RynthRemote 0.3 then fell back to
|
||||
/// overwriting the file in place; the next read caught it empty or half-written and the parse failed.
|
||||
/// That client was left out of that one snapshot (StatusAgent.log: "1 client(s)" for ~60 ms, several
|
||||
/// times a minute), and the phone's open deck for it unmounted and came back: the screen flashed and
|
||||
/// scrolled to the top. RynthRemote 0.4 skips such a write instead of overwriting in place.</para>
|
||||
///
|
||||
/// <para>Here: a status file that can't be read or parsed is answered with the last good parse of that
|
||||
/// file for up to <see cref="KeepLastGood"/> (its own timestamp stays in the model, so its age still shows
|
||||
/// honestly), and files are read with ReadWrite|Delete sharing so a reader never makes a writer fail.</para>
|
||||
/// </summary>
|
||||
internal static class StatusFileCache
|
||||
{
|
||||
public static readonly TimeSpan KeepLastGood = TimeSpan.FromSeconds(3);
|
||||
|
||||
private static readonly ConcurrentDictionary<string, (object Model, DateTime AtUtc)> LastGood = new(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>Read a whole file while letting the writer replace or rewrite it underneath.</summary>
|
||||
public static byte[] ReadAllBytesShared(string path)
|
||||
{
|
||||
using var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, 4096, FileOptions.SequentialScan);
|
||||
using var ms = new MemoryStream(fs.CanSeek ? (int)Math.Min(fs.Length, int.MaxValue) : 4096);
|
||||
fs.CopyTo(ms);
|
||||
return ms.ToArray();
|
||||
}
|
||||
|
||||
public static string ReadAllTextShared(string path) => Encoding.UTF8.GetString(ReadAllBytesShared(path)).TrimStart('');
|
||||
|
||||
/// <summary>
|
||||
/// Parse <paramref name="path"/> with <paramref name="parse"/>; on any read or parse failure (or a null
|
||||
/// parse) answer the last good result for that path if it is younger than <see cref="KeepLastGood"/>.
|
||||
/// <paramref name="read"/> is the file reader (tests pass their own).
|
||||
/// </summary>
|
||||
public static T? Read<T>(string path, Func<string, T?> parse, DateTime nowUtc, Func<string, string>? read = null) where T : class
|
||||
{
|
||||
try
|
||||
{
|
||||
T? model = parse((read ?? ReadAllTextShared)(path));
|
||||
if (model != null)
|
||||
{
|
||||
LastGood[path] = (model, nowUtc);
|
||||
return model;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
AgentLog.Debug($"status file '{path}' unreadable: {ex.GetType().Name}: {ex.Message}");
|
||||
}
|
||||
if (LastGood.TryGetValue(path, out var lg) && nowUtc - lg.AtUtc <= KeepLastGood && lg.Model is T t)
|
||||
return t;
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>Drop what is remembered for a file that is gone (a retired dead client) or for every file
|
||||
/// not in <paramref name="keep"/>.</summary>
|
||||
public static void Forget(string path) => LastGood.TryRemove(path, out _);
|
||||
|
||||
public static void ForgetAllBut(IReadOnlyCollection<string> keep)
|
||||
{
|
||||
var set = new HashSet<string>(keep, StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var k in LastGood.Keys)
|
||||
if (!set.Contains(k)) LastGood.TryRemove(k, out _);
|
||||
}
|
||||
|
||||
internal static int CountForTests => LastGood.Count;
|
||||
}
|
||||
|
|
@ -17,12 +17,12 @@ internal static partial class StatusReader
|
|||
[GeneratedRegex(@"hb #\d+ up=(\d+)s fps=(-?\d+) plug=(-?\d+)/s ws=(\d+)MB login=(\d+)")]
|
||||
private static partial Regex HeartbeatRegex();
|
||||
|
||||
public static List<ClientStatus> ReadAll(AgentConfig cfg)
|
||||
public static List<ClientStatus> ReadAll(AgentConfig cfg, SpellTableService? spells = null)
|
||||
{
|
||||
var clients = new List<ClientStatus>();
|
||||
var seenPids = new HashSet<int>();
|
||||
|
||||
ReadStatusFiles(cfg, clients, seenPids);
|
||||
ReadStatusFiles(cfg, clients, seenPids, spells);
|
||||
|
||||
if (cfg.UseHeartbeatLogFallback)
|
||||
ReadHeartbeatLogs(cfg, clients, seenPids);
|
||||
|
|
@ -33,27 +33,23 @@ internal static partial class StatusReader
|
|||
|
||||
// ── Rich source: per-client status JSON files ───────────────────────────
|
||||
|
||||
private static void ReadStatusFiles(AgentConfig cfg, List<ClientStatus> clients, HashSet<int> seenPids)
|
||||
private static void ReadStatusFiles(AgentConfig cfg, List<ClientStatus> clients, HashSet<int> seenPids, SpellTableService? spells)
|
||||
{
|
||||
string dir = cfg.StatusDirectory;
|
||||
if (!Directory.Exists(dir))
|
||||
return;
|
||||
|
||||
var listed = new List<string>();
|
||||
foreach (string path in SafeEnumerate(dir, "RynthCore.*.status.json"))
|
||||
{
|
||||
int pid = ParsePidFromName(Path.GetFileName(path), ".status.json");
|
||||
if (pid <= 0) continue;
|
||||
listed.Add(path);
|
||||
|
||||
StatusFileModel? model;
|
||||
try
|
||||
{
|
||||
model = JsonSerializer.Deserialize(File.ReadAllText(path), AgentJsonContext.Default.StatusFileModel);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
AgentLog.Debug($"status file '{path}' unreadable: {ex.Message}");
|
||||
continue;
|
||||
}
|
||||
// Shared read, and the last good parse when this one catches the file mid-write: a client is
|
||||
// never left out of a snapshot just because its file was being replaced (see StatusFileCache).
|
||||
StatusFileModel? model = StatusFileCache.Read(path,
|
||||
text => JsonSerializer.Deserialize(text, AgentJsonContext.Default.StatusFileModel), DateTime.UtcNow);
|
||||
if (model == null) continue;
|
||||
|
||||
double ageSec = AgeSeconds(model.Ts, path);
|
||||
|
|
@ -64,6 +60,7 @@ internal static partial class StatusReader
|
|||
if (!alive && ageSec > cfg.DropDeadAfterSeconds)
|
||||
{
|
||||
try { File.Delete(path); } catch { }
|
||||
StatusFileCache.Forget(path);
|
||||
continue;
|
||||
}
|
||||
|
||||
|
|
@ -149,8 +146,22 @@ internal static partial class StatusReader
|
|||
cs.XpSession = model.XpSession;
|
||||
cs.BurdenPct = model.BurdenPct;
|
||||
cs.Area = model.Area;
|
||||
cs.Landblock = model.Landblock; cs.Indoor = model.Indoor; // [status-export] live map-dot
|
||||
// [status-export] live map-dot. The landblock goes out in DrakBot's full form ("XXYY0000"), the
|
||||
// one DrakRemote matches against its floor plans (see RemoteParity.LandblockFull).
|
||||
cs.Landblock = RemoteParity.LandblockFull(model.Landblock); cs.Indoor = model.Indoor;
|
||||
cs.Wx = model.Wx; cs.Wy = model.Wy; cs.Pz = model.Pz;
|
||||
// The engine writes wx/wy indoors only; the plugin's "opos" has them outdoors too (world map dot).
|
||||
if (!model.Indoor && model.Opos is { } pos && (pos.Wx != 0 || pos.Wy != 0)) { cs.Wx = pos.Wx; cs.Wy = pos.Wy; }
|
||||
cs.Heading = model.Opos?.Heading;
|
||||
// The player's enchantments, named from portal.dat's spell table (the Buffs tab).
|
||||
cs.Enchantments = RemoteParity.Enchantments(model.Enchantments,
|
||||
id => spells != null && spells.TryGet(id, out var info) ? info : null);
|
||||
// The last phone travel (RynthNav) and how it stands.
|
||||
cs.Travel = RemoteParity.Travel(model.Travel, cs.RecentChat, cs.Indoor, cs.Wx, cs.Wy);
|
||||
// Raising from the Skills tab: what the plugin reports; Program clears it without remote control.
|
||||
cs.RaiseXp = model.RaiseXp && cfg.EnableRemoteControl;
|
||||
// RynthRemote 0.4+: the movement protocol it speaks (2 = keep-alives + dead-man); 0 when absent.
|
||||
cs.MoveProto = model.MoveProto;
|
||||
cs.LastIssue = model.LastIssue;
|
||||
cs.LastIssueAgeSec = model.LastIssueAgeSec;
|
||||
// Window state (for the app to show a "minimized — restore on PC" placeholder instead of a
|
||||
|
|
@ -160,6 +171,7 @@ internal static partial class StatusReader
|
|||
clients.Add(cs);
|
||||
seenPids.Add(pid);
|
||||
}
|
||||
StatusFileCache.ForgetAllBut(listed);
|
||||
}
|
||||
|
||||
// ── Basic fallback: tail each per-client heartbeat log ──────────────────
|
||||
|
|
|
|||
231
src/RynthCore.StatusAgent/WorldMapService.cs
Normal file
231
src/RynthCore.StatusAgent/WorldMapService.cs
Normal file
|
|
@ -0,0 +1,231 @@
|
|||
using System.Drawing;
|
||||
using System.Drawing.Imaging;
|
||||
using System.Runtime.InteropServices;
|
||||
using RynthCore2.TerrainData;
|
||||
|
||||
namespace RynthCore.StatusAgent;
|
||||
|
||||
/// <summary>
|
||||
/// A landscape map of Dereth for the phone (GET /worldmap): every outdoor landblock of the client's
|
||||
/// cell.dat (record 0xXXYYFFFF: 9x9 terrain words + height indices), one pixel per 24-unit terrain cell,
|
||||
/// coloured by terrain type, roads drawn, hills shaded from the height indices. 255 landblocks x 8 cells
|
||||
/// = 2040 pixels square, north up. Rendered once in the background on the first request (the world does
|
||||
/// not change) and cached as a JPEG next to the agent's other files, so later starts serve it at once.
|
||||
///
|
||||
/// Frame (shared with the status "wx"/"wy" and the dungeon floor plans): absolute world units, x west to
|
||||
/// east, y south to north, 192 units a landblock. Pixel = (wx / 24, 2040 - wy / 24).
|
||||
/// </summary>
|
||||
internal sealed class WorldMapService
|
||||
{
|
||||
public const int CellsPerLandblock = 8;
|
||||
public const int Landblocks = 255;
|
||||
public const int Size = Landblocks * CellsPerLandblock; // 2040
|
||||
public const double UnitsPerPixel = 24.0;
|
||||
private const string CacheName = "worldmap-v1.jpg";
|
||||
|
||||
private readonly string _cellDatPath;
|
||||
private readonly string _cacheDir;
|
||||
private volatile byte[]? _jpeg;
|
||||
private int _started;
|
||||
private volatile string _state = "idle";
|
||||
|
||||
public WorldMapService(string cellDatPath, string cacheDir)
|
||||
{
|
||||
_cellDatPath = cellDatPath;
|
||||
_cacheDir = cacheDir;
|
||||
}
|
||||
|
||||
/// <summary>True when a map can be made here at all (the cell.dat is on this box, or one is cached).</summary>
|
||||
public bool Available => _jpeg != null || File.Exists(_cellDatPath) || File.Exists(CachePath);
|
||||
|
||||
public string State => _state;
|
||||
|
||||
private string CachePath => Path.Combine(_cacheDir, CacheName);
|
||||
|
||||
/// <summary>The JPEG, or null while it is being made (the first call starts that). Any thread.</summary>
|
||||
public byte[]? GetJpeg()
|
||||
{
|
||||
var j = _jpeg;
|
||||
if (j != null) return j;
|
||||
if (Interlocked.Exchange(ref _started, 1) == 0)
|
||||
{
|
||||
_state = "being drawn";
|
||||
_ = Task.Run(LoadOrRender);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private void LoadOrRender()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (File.Exists(CachePath))
|
||||
{
|
||||
_jpeg = File.ReadAllBytes(CachePath);
|
||||
_state = "ready";
|
||||
AgentLog.Info($"[worldmap] served from cache {CachePath} ({_jpeg.Length / 1024:N0} KB).");
|
||||
return;
|
||||
}
|
||||
if (!File.Exists(_cellDatPath)) { _state = "no cell.dat"; AgentLog.Warn($"[worldmap] cell.dat not found at '{_cellDatPath}'."); return; }
|
||||
|
||||
_state = "being drawn";
|
||||
var sw = System.Diagnostics.Stopwatch.StartNew();
|
||||
byte[] rgb;
|
||||
int found;
|
||||
using (var db = new DatDatabase())
|
||||
{
|
||||
if (!db.Open(_cellDatPath)) { _state = "cell.dat unreadable"; AgentLog.Warn($"[worldmap] could not open '{_cellDatPath}'."); return; }
|
||||
rgb = Render(lb => db.GetFileData(((uint)lb << 16) | 0xFFFF), out found);
|
||||
}
|
||||
byte[] jpeg = EncodeJpeg(rgb, Size, Size, 88);
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(_cacheDir);
|
||||
string tmp = CachePath + ".tmp";
|
||||
File.WriteAllBytes(tmp, jpeg);
|
||||
File.Move(tmp, CachePath, overwrite: true);
|
||||
}
|
||||
catch (Exception ex) { AgentLog.Warn($"[worldmap] cache write failed: {ex.Message}"); }
|
||||
_jpeg = jpeg;
|
||||
_state = "ready";
|
||||
AgentLog.Info($"[worldmap] rendered {found:N0} landblocks in {sw.Elapsed.TotalSeconds:0.0}s ({jpeg.Length / 1024:N0} KB).");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_state = "failed";
|
||||
AgentLog.Warn($"[worldmap] render failed: {ex.GetType().Name}: {ex.Message}");
|
||||
Interlocked.Exchange(ref _started, 0); // let a later request try again
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Paint the whole map into a 24-bit RGB buffer (row 0 = north). <paramref name="readLandblock"/>
|
||||
/// returns the raw 0xXXYYFFFF record for a landblock id 0xXXYY, or null where there is none (open sea).
|
||||
/// Internal for the tests, which hand it made-up landblocks.
|
||||
/// </summary>
|
||||
internal static byte[] Render(Func<int, byte[]?> readLandblock, out int found)
|
||||
{
|
||||
var rgb = new byte[Size * Size * 3];
|
||||
Fill(rgb, Sea);
|
||||
found = 0;
|
||||
var terrain = new ushort[81];
|
||||
var heights = new byte[81];
|
||||
for (int lbx = 0; lbx < Landblocks; lbx++)
|
||||
{
|
||||
for (int lby = 0; lby < Landblocks; lby++)
|
||||
{
|
||||
byte[]? raw = readLandblock((lbx << 8) | lby);
|
||||
if (!TryParse(raw, terrain, heights)) continue;
|
||||
found++;
|
||||
for (int ix = 0; ix < CellsPerLandblock; ix++)
|
||||
{
|
||||
for (int iy = 0; iy < CellsPerLandblock; iy++)
|
||||
{
|
||||
int v = ix * 9 + iy;
|
||||
ushort word = terrain[v];
|
||||
int type = (word >> 2) & 0x1F;
|
||||
Rgb c = Palette(type);
|
||||
bool water = type is >= 16 and <= 20;
|
||||
if ((word & 0x3) != 0 && !water) c = Road;
|
||||
if (!water)
|
||||
{
|
||||
// Light from the north-west: a cell rising to the east and falling to the north is lit.
|
||||
int dzx = heights[(ix + 1) * 9 + iy] - heights[v];
|
||||
int dzy = heights[ix * 9 + iy + 1] - heights[v];
|
||||
double s = Math.Clamp(1.0 + 0.045 * (dzx - dzy), 0.62, 1.35);
|
||||
c = c.Scale(s);
|
||||
}
|
||||
int px = lbx * CellsPerLandblock + ix;
|
||||
int py = Size - 1 - (lby * CellsPerLandblock + iy);
|
||||
int o = (py * Size + px) * 3;
|
||||
rgb[o] = c.R; rgb[o + 1] = c.G; rgb[o + 2] = c.B;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return rgb;
|
||||
}
|
||||
|
||||
/// <summary>Record layout: u32 id, u32 hasObjects, u16 terrain[81], u8 height[81] (vertex = ix*9 + iy).</summary>
|
||||
internal static bool TryParse(byte[]? raw, ushort[] terrain, byte[] heights)
|
||||
{
|
||||
if (raw == null || raw.Length < 8 + 81 * 2 + 81) return false;
|
||||
for (int i = 0; i < 81; i++) terrain[i] = BitConverter.ToUInt16(raw, 8 + i * 2);
|
||||
Buffer.BlockCopy(raw, 8 + 81 * 2, heights, 0, 81);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Where a world position lands on the map, in pixels (may fall outside for bad input).</summary>
|
||||
public static (double X, double Y) ToPixel(double wx, double wy) => (wx / UnitsPerPixel, Size - wy / UnitsPerPixel);
|
||||
|
||||
// ── colours ─────────────────────────────────────────────────────────────
|
||||
|
||||
internal readonly record struct Rgb(byte R, byte G, byte B)
|
||||
{
|
||||
public Rgb Scale(double s) => new(Clamp(R * s), Clamp(G * s), Clamp(B * s));
|
||||
private static byte Clamp(double v) => (byte)Math.Clamp((int)Math.Round(v), 0, 255);
|
||||
}
|
||||
|
||||
private static readonly Rgb Sea = new(0x1F, 0x4A, 0x78);
|
||||
private static readonly Rgb Road = new(0xA8, 0x93, 0x6C);
|
||||
|
||||
/// <summary>ACE's LandDefs.TerrainType, 0..20; anything else (the reserved slots) a neutral grey.</summary>
|
||||
internal static Rgb Palette(int type) => type switch
|
||||
{
|
||||
0 => new(0x7A, 0x74, 0x66), // BarrenRock
|
||||
1 => new(0x6E, 0x8B, 0x3D), // Grassland
|
||||
2 => new(0xD8, 0xE8, 0xF0), // Ice
|
||||
3 => new(0x4F, 0x7A, 0x2A), // LushGrass
|
||||
4 => new(0x5A, 0x6B, 0x3A), // MarshSparseSwamp
|
||||
5 => new(0x6B, 0x52, 0x36), // MudRichDirt
|
||||
6 => new(0x2E, 0x2A, 0x30), // ObsidianPlain
|
||||
7 => new(0x8C, 0x75, 0x50), // PackedDirt
|
||||
8 => new(0x8A, 0x7B, 0x55), // PatchyDirt
|
||||
9 => new(0x7F, 0x8F, 0x48), // PatchyGrassland
|
||||
10 => new(0xD8, 0xC4, 0x8A), // SandYellow
|
||||
11 => new(0xB5, 0xAE, 0x98), // SandGrey
|
||||
12 => new(0xB8, 0xA4, 0x7A), // SandRockStrewn
|
||||
13 => new(0x9A, 0x84, 0x68), // SedimentaryRock
|
||||
14 => new(0x84, 0x7A, 0x63), // SemiBarrenRock
|
||||
15 => new(0xF0, 0xF4, 0xF7), // Snow
|
||||
16 => new(0x3C, 0x6E, 0x9E), // WaterRunning
|
||||
17 => new(0x3F, 0x78, 0xA8), // WaterStandingFresh
|
||||
18 => new(0x35, 0x6B, 0x9C), // WaterShallowSea
|
||||
19 => new(0x2F, 0x62, 0x93), // WaterShallowStillSea
|
||||
20 => new(0x1F, 0x4A, 0x78), // WaterDeepSea
|
||||
_ => new(0x80, 0x80, 0x80),
|
||||
};
|
||||
|
||||
private static void Fill(byte[] rgb, Rgb c)
|
||||
{
|
||||
for (int i = 0; i < rgb.Length; i += 3) { rgb[i] = c.R; rgb[i + 1] = c.G; rgb[i + 2] = c.B; }
|
||||
}
|
||||
|
||||
private static byte[] EncodeJpeg(byte[] rgb, int w, int h, int quality)
|
||||
{
|
||||
using var bmp = new Bitmap(w, h, PixelFormat.Format24bppRgb);
|
||||
var bd = bmp.LockBits(new Rectangle(0, 0, w, h), ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);
|
||||
try
|
||||
{
|
||||
var row = new byte[w * 3];
|
||||
for (int y = 0; y < h; y++)
|
||||
{
|
||||
// GDI+ 24bpp is B,G,R in memory.
|
||||
for (int x = 0; x < w; x++)
|
||||
{
|
||||
int s = (y * w + x) * 3;
|
||||
row[x * 3] = rgb[s + 2]; row[x * 3 + 1] = rgb[s + 1]; row[x * 3 + 2] = rgb[s];
|
||||
}
|
||||
Marshal.Copy(row, 0, bd.Scan0 + y * bd.Stride, row.Length);
|
||||
}
|
||||
}
|
||||
finally { bmp.UnlockBits(bd); }
|
||||
var enc = Array.Find(ImageCodecInfo.GetImageEncoders(), c => c.FormatID == ImageFormat.Jpeg.Guid)
|
||||
?? throw new InvalidOperationException("no jpeg encoder");
|
||||
using var ep = new EncoderParameters(1);
|
||||
ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)Math.Clamp(quality, 1, 100));
|
||||
using var ms = new MemoryStream();
|
||||
bmp.Save(ms, enc, ep);
|
||||
return ms.ToArray();
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue