Snapshot for release 2026.10.15.6 (internal eca8fa0)

This commit is contained in:
Tom Bohar 2026-10-15 23:44:40 -04:00
commit 8cf68da453
43 changed files with 4133 additions and 94 deletions

View file

@ -625,6 +625,15 @@ public sealed partial class RynthAiPlugin
return;
}
// ── Mana tapping: an item looted to tap is drained before the next pickup or corpse ──
// (2026-10-15: the looter went on opening corpses over the drain; a pickup still in
// flight finishes first, since its answer is what lets the drain go.)
if (!_currentLootItemMovePending && _manaStoneManager?.HoldsLootForDrain() == true)
{
FreezeCorpseTimeout(CorpseNowMs);
return;
}
// ── Combat takes priority over claiming NEW corpses ───────────────
// But if we already have an opened container, finish looting it
// (no movement, no conflict with combat).
@ -1688,7 +1697,7 @@ public sealed partial class RynthAiPlugin
// confirming it, and the item may still land in the pack. If it never
// does, ManaStoneManager prunes the id.
if (matchActionLabel == ManaTapActionLabel)
_manaStoneManager?.MarkLootedForTap(firstMatchId);
_manaStoneManager?.MarkLootedForTap(firstMatchId, arrived: false);
// Same for salvage: the confirm below can be lost the same ways, and an
// unconfirmed salvage item used to sit in the pack for good. The salvage
// manager's sweep queues it once it shows up in the pack.
@ -2156,9 +2165,9 @@ public sealed partial class RynthAiPlugin
if (_currentLootItemIsSalvage)
_salvageManager?.EnqueueItem(unchecked((uint)_currentLootItemId));
// Refresh the loot-for-tap record so its arrival grace counts from now.
// It is in the pack: the drain may go (and the arrival grace counts from now).
if (_currentLootItemActionLabel == ManaTapActionLabel)
_manaStoneManager?.MarkLootedForTap(_currentLootItemId);
_manaStoneManager?.MarkLootedForTap(_currentLootItemId, arrived: true);
ResetCurrentLootItem();
_lastLootActionAt = now;
@ -2774,9 +2783,8 @@ public sealed partial class RynthAiPlugin
return true;
}
// Quota: each ManaTap pickup consumes one empty stone. Don't loot more
// candidates than we have free empty-stone slots, otherwise we end up
// with a pile of mana items the bot can't drain.
// Quota: one item at a time (FreeEmptyStoneSlots is 1 with an empty stone in the pack and
// no tap item waiting for its drain), so the pack never fills with items it can't drain.
int freeSlots = _manaStoneManager.FreeEmptyStoneSlots() - _pendingManaTapIds.Count;
if (freeSlots <= 0) return false;

View file

@ -158,7 +158,9 @@ public sealed partial class RynthAiPlugin
}
}
if (doorId == 0 && settings.OpenDoors)
doorId = FindNearestClosedDoor(settings.OpenDoorRange, now);
doorId = settings.OpenDoorsOnPathOnly
? FindClosedDoorOnPath(settings.OpenDoorRange, now)
: FindNearestClosedDoor(settings.OpenDoorRange, now);
if (doorId == 0) return false;
string why = _doorTargetRequested ? " (asked for by the nav detour)" : "";
@ -311,6 +313,7 @@ public sealed partial class RynthAiPlugin
? $"try {_doorAttempts + 1}: still closed after the last use"
: _doorPicks > 0 ? "open after the lockpick"
: _doorTargetRequested ? "the nav detour asked to open this door"
: settings.OpenDoorsOnPathOnly ? $"Open Doors: closed door on the path, within {settings.OpenDoorRange:0} yd"
: $"Open Doors: closed door within {settings.OpenDoorRange:0} yd";
sent = Host.UseFor(unchecked((uint)_doorTargetId), "Door", reason);
if (sent) _doorState = DoorState.Opening;
@ -508,6 +511,101 @@ public sealed partial class RynthAiPlugin
return bestId;
}
// ── Only doors on the path of travel ─────────────────────────────────────
/// <summary>A door counts as on the path when it stands this close (world units, about yards) to it.</summary>
private const double PathDoorCorridorYd = 1.5;
private const int PathDoorMaxPoints = 12;
/// <summary>
/// The path of travel from the character, in world units, as far as <paramref name="rangeYd"/> yards:
/// along the route's next points when the macro is navigating a route (in the direction it is walking it),
/// else straight ahead along the character's heading (a RynthNav walk, or no nav at all).
/// </summary>
private System.Collections.Generic.List<(double X, double Y)> PathAhead(RynthCore.Plugin.RynthAi.LegacyUi.LegacyUiSettings s, double ax, double ay, float qw, float qz, double rangeYd)
{
var path = new System.Collections.Generic.List<(double X, double Y)> { (ax, ay) };
var route = s.CurrentRoute;
if (s.EnableNavigation && route != null && route.Points.Count > 0 && route.RouteType != NavRouteType.Follow)
{
int n = route.Points.Count, idx = s.ActiveNavIndex;
int dir = route.RouteType == NavRouteType.Linear ? (_navigationEngine?.GetStateSnapshot().LinearDir ?? 1) : 1;
double used = 0, cx = ax, cy = ay;
for (int k = 0; k < PathDoorMaxPoints && idx >= 0 && idx < n && used < rangeYd; k++)
{
var pt = route.Points[idx];
if (pt.NS != 0 || pt.EW != 0)
{
double wx = (pt.EW * 10.0 + 1019.5) * 24.0, wy = (pt.NS * 10.0 + 1019.5) * 24.0; // nav coordinates to world units
double leg = Math.Sqrt((wx - cx) * (wx - cx) + (wy - cy) * (wy - cy));
path.Add((wx, wy)); used += leg; cx = wx; cy = wy;
}
idx = route.RouteType == NavRouteType.Circular ? (idx + 1) % n : idx + dir;
}
if (path.Count > 1) return path;
}
// Straight ahead (physics yaw is counter-clockwise from north).
double yaw = 2.0 * Math.Atan2(qz, qw);
path.Add((ax - Math.Sin(yaw) * rangeYd, ay + Math.Cos(yaw) * rangeYd));
return path;
}
/// <summary>
/// Open Doors with "Only Doors On My Path": the closed door nearest the character along the path of
/// travel (<see cref="PathAhead"/>), within <paramref name="rangeYards"/> of path, never one that merely
/// stands within range. Same door rules as the proximity scan (static BF_DOOR objects, none opened or
/// found locked a moment ago, none already open, about the character's height).
/// </summary>
private int FindClosedDoorOnPath(float rangeYards, long now)
{
var s = _dashboard?.Settings;
if (s == null || _objectCache == null || !Host.HasGetObjectPosition) return 0;
if (!Host.TryGetPlayerPose(out uint cell, out float lx, out float ly, out float lz, out float qw, out _, out _, out float qz)) return 0;
double ax = ((cell >> 24) & 0xFF) * 192.0 + lx, ay = ((cell >> 16) & 0xFF) * 192.0 + ly;
var path = PathAhead(s, ax, ay, qw, qz, rangeYards);
bool hasBitfield = Host.HasGetObjectBitfield;
int bestId = 0;
double bestAlong = double.MaxValue;
foreach (var wo in _objectCache.GetLandscapeObjects())
{
uint uid = unchecked((uint)wo.Id);
if (uid >= 0x80000000u) continue;
if (hasBitfield)
{
if (!Host.TryGetObjectBitfield(uid, out uint bf) || (bf & 0x1000u) == 0) continue;
}
else
{
string nl = (wo.Name ?? string.Empty).ToLowerInvariant();
if (!nl.Contains("door") && !nl.Contains("gate") && !nl.Contains("hatch") && !nl.Contains("portcullis")) continue;
}
if (_doorOpenedRecently.TryGetValue(wo.Id, out long openedAt) && (now - openedAt) < DoorOpenedSkipMs) continue;
if (_doorLockedRecently.ContainsKey(wo.Id)) continue;
if (IsDoorOpen(wo.Id)) continue;
if (!Host.TryGetObjectPosition(uid, out uint dcell, out float x, out float y, out float oz)) continue;
if (Math.Abs(oz - lz) > 4.0) continue;
double px = ((dcell >> 24) & 0xFF) * 192.0 + x, py = ((dcell >> 16) & 0xFF) * 192.0 + y;
double along = 0;
for (int i = 0; i + 1 < path.Count; i++)
{
double x1 = path[i].X, y1 = path[i].Y, dx = path[i + 1].X - x1, dy = path[i + 1].Y - y1;
double len2 = dx * dx + dy * dy, len = Math.Sqrt(len2);
double t = len2 < 1e-6 ? 0.0 : Math.Clamp(((px - x1) * dx + (py - y1) * dy) / len2, 0.0, 1.0);
double ex = x1 + dx * t - px, ey = y1 + dy * t - py;
if (ex * ex + ey * ey <= PathDoorCorridorYd * PathDoorCorridorYd)
{
double a = along + len * t;
if (a <= rangeYards + PathDoorCorridorYd && a < bestAlong) { bestAlong = a; bestId = wo.Id; }
break;
}
along += len;
}
}
return bestId;
}
private int FindNearestClosedDoor(float rangeYards, long now)
{
if (_objectCache == null || _playerId == 0) return 0;

View file

@ -728,6 +728,10 @@ internal sealed class LegacyAdvancedSettingsUi
ImGui.SetNextItemWidth(180);
ImGui.SliderFloat("Door Detection Range (yd)", ref _settings.OpenDoorRange, 0.1f, 70.0f, "%.1f");
ImGui.Checkbox("Only Doors On My Path", ref _settings.OpenDoorsOnPathOnly);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Open only a closed door that is on the way: within the range along the route's next legs (or straight ahead when not on a route).\nOff: every closed door within the range is opened.");
ImGui.Checkbox("Auto-Unlock Doors", ref _settings.AutoUnlockDoors);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("If a door is locked, try to use a lockpick from your Consumable Items list.");

View file

@ -1097,6 +1097,7 @@ internal sealed partial class LegacyDashboardRenderer
NavResumeNearest = s.NavResumeNearest,
OpenDoors = s.OpenDoors,
OpenDoorRange = s.OpenDoorRange,
OpenDoorsOnPathOnly = s.OpenDoorsOnPathOnly,
AutoUnlockDoors = s.AutoUnlockDoors,
MovementMode = s.MovementMode,
NavStopTurnAngle = s.NavStopTurnAngle,
@ -1336,6 +1337,7 @@ internal sealed partial class LegacyDashboardRenderer
if (p.NavResumeNearest is bool resumeNearest) s.NavResumeNearest = resumeNearest; // absent = unchanged
s.OpenDoors = p.OpenDoors;
s.OpenDoorRange = p.OpenDoorRange;
if (p.OpenDoorsOnPathOnly is bool doorsOnPath) s.OpenDoorsOnPathOnly = doorsOnPath; // absent = unchanged
s.AutoUnlockDoors = p.AutoUnlockDoors;
s.MovementMode = p.MovementMode is 1 or 2 ? 0 : p.MovementMode; // Tier 1/2 off for now
s.NavStopTurnAngle = p.NavStopTurnAngle;
@ -1823,6 +1825,7 @@ internal sealed partial class LegacyDashboardRenderer
dst.BoostLootPriority = tmp.BoostLootPriority;
dst.OpenDoors = tmp.OpenDoors;
dst.OpenDoorRange = tmp.OpenDoorRange;
dst.OpenDoorsOnPathOnly = tmp.OpenDoorsOnPathOnly;
dst.AutoUnlockDoors = tmp.AutoUnlockDoors;
dst.LootOwnership = tmp.LootOwnership;
dst.LootOwnCorpse = tmp.LootOwnCorpse;

View file

@ -255,6 +255,8 @@ public sealed class LegacyUiSettings
public bool BoostLootPriority;
public bool OpenDoors;
public float OpenDoorRange = 5.0f;
/// <summary>Open Doors opens only a closed door on the path of travel (the route's next legs, or straight ahead when not on a route), not every door within OpenDoorRange.</summary>
public bool OpenDoorsOnPathOnly;
public bool AutoUnlockDoors;
public int LootOwnership;
/// <summary>
@ -1098,6 +1100,7 @@ public sealed class SettingsBridgePayload
public bool? NavResumeNearest { get; set; }
public bool OpenDoors { get; set; }
public float OpenDoorRange { get; set; }
public bool? OpenDoorsOnPathOnly { get; set; } // absent (an older profile or plugin) = unchanged
public bool AutoUnlockDoors { get; set; }
public int MovementMode { get; set; }
public float NavStopTurnAngle { get; set; }

View file

@ -353,7 +353,7 @@ internal sealed class RynthRadarUi
}
if (_objectCache != null && _host.HasGetObjectPosition && landblock != 0)
AddMarkers(payload, landblock, gxLB, gyLB);
AddMarkers(payload, landblock, isIndoor);
return payload;
}
@ -363,7 +363,21 @@ internal sealed class RynthRadarUi
// decided once and kept (per object id and name) wherever the answer is settled, because
// this runs on every radar poll (10-30 Hz) over every creature and world object nearby.
private void AddMarkers(RadarSnapshotPayload payload, uint landblock, float gxLB, float gyLB)
/// <summary>
/// Where an object's landblock puts it in world space. Outdoors every landblock counts: the client has the
/// neighbours loaded and an object's position is local to its own landblock, so it is offset by that one
/// (2026-10-15: objects over the border used to show only once you crossed it). In a dungeon only the
/// player's own landblock counts (the neighbours' cells are other places).
/// </summary>
private static bool TryLandblockOffset(uint cell, uint playerLandblock, bool indoor, out float gx, out float gy)
{
uint lb = cell >> 16;
gx = ((lb >> 8) & 0xFF) * 192f;
gy = (lb & 0xFF) * 192f;
return lb != 0 && (!indoor || lb == playerLandblock);
}
private void AddMarkers(RadarSnapshotPayload payload, uint landblock, bool indoor)
{
var cache = _objectCache!;
if (_creatureNpcLandblock != (int)landblock)
@ -382,9 +396,9 @@ internal sealed class RynthRadarUi
{
if (!_host.TryGetObjectPosition((uint)wo.Id, out uint cCellId,
out float cox, out float coy, out float coz)) continue;
if ((cCellId >> 16) != landblock) continue;
if (!TryLandblockOffset(cCellId, landblock, indoor, out float cgx, out float cgy)) continue;
_drawnCreatures.Add(wo.Id);
AddCreature(payload, wo, petPrefix, cox + gxLB, coy + gyLB, coz);
AddCreature(payload, wo, petPrefix, cox + cgx, coy + cgy, coz);
}
foreach (var wo in cache.GetLandscapeObjects())
@ -399,20 +413,20 @@ internal sealed class RynthRadarUi
{
if (wo.ObjectClass == AcObjectClass.Monster || _drawnCreatures.Contains(wo.Id)) continue;
if (!_host.TryGetObjectPosition(uid, out uint cc, out float cx, out float cy, out float cz)) continue;
if ((cc >> 16) != landblock) continue;
AddCreature(payload, wo, petPrefix, cx + gxLB, cy + gyLB, cz);
if (!TryLandblockOffset(cc, landblock, indoor, out float rgx, out float rgy)) continue;
AddCreature(payload, wo, petPrefix, cx + rgx, cy + rgy, cz);
continue;
}
if (wo.ObjectClass == AcObjectClass.Corpse)
{
if (!_host.TryGetObjectPosition(uid, out uint kc, out float kx, out float ky, out float kz)) continue;
if ((kc >> 16) != landblock) continue;
if (!TryLandblockOffset(kc, landblock, indoor, out float kgx, out float kgy)) continue;
bool own = IsOwnCorpse(wo, woName, me, myCorpse, now);
payload.Markers.Add(new RadarMarker
{
Kind = own ? KindOwnCorpse : KindCorpse,
X = kx + gxLB, Y = ky + gyLB, Z = kz,
X = kx + kgx, Y = ky + kgy, Z = kz,
Label = woName,
Id = uid,
});
@ -421,7 +435,7 @@ internal sealed class RynthRadarUi
if (uid >= 0x80000000u)
{
AddDynamicObject(payload, wo, woName, landblock, gxLB, gyLB);
AddDynamicObject(payload, wo, woName, landblock, indoor);
continue;
}
@ -431,7 +445,7 @@ internal sealed class RynthRadarUi
if (!_host.TryGetObjectPosition(uid, out uint oCellId,
out float oox, out float ooy, out float ooz)) continue;
if ((oCellId >> 16) != landblock) continue;
if (!TryLandblockOffset(oCellId, landblock, indoor, out float ogx, out float ogy)) continue;
byte kind;
string label;
@ -459,7 +473,7 @@ internal sealed class RynthRadarUi
payload.Markers.Add(new RadarMarker
{
Kind = kind,
X = oox + gxLB, Y = ooy + gyLB, Z = ooz,
X = oox + ogx, Y = ooy + ogy, Z = ooz,
Label = label,
Id = uid,
});
@ -525,7 +539,7 @@ internal sealed class RynthRadarUi
}
/// <summary>A summoned portal, a lifestone or an item on the ground; other dynamic objects aren't drawn.</summary>
private void AddDynamicObject(RadarSnapshotPayload payload, WorldObject wo, string woName, uint landblock, float gxLB, float gyLB)
private void AddDynamicObject(RadarSnapshotPayload payload, WorldObject wo, string woName, uint landblock, bool indoor)
{
byte kind;
if (_dynamicKinds.TryGetValue(wo.Id, out var known) && known.Name == woName)
@ -545,11 +559,11 @@ internal sealed class RynthRadarUi
_dynamicKinds[wo.Id] = (woName, kind);
}
if (!_host.TryGetObjectPosition((uint)wo.Id, out uint cell, out float x, out float y, out float z)) return;
if ((cell >> 16) != landblock) return;
if (!TryLandblockOffset(cell, landblock, indoor, out float dgx, out float dgy)) return;
payload.Markers.Add(new RadarMarker
{
Kind = kind,
X = x + gxLB, Y = y + gyLB, Z = z,
X = x + dgx, Y = y + dgy, Z = z,
Label = kind == KindPortal ? GetPortalLabel(wo) : woName,
Id = (uint)wo.Id,
});

View file

@ -42,10 +42,9 @@ internal sealed class ManaStoneManager
private readonly Dictionary<int, long> _stoneUseOnPlayerCooldownUntil = new();
private const long StoneUseOnPlayerCooldownMs = 5 * 60 * 1000;
// Same idea for tap targets: an item that won't drain (wielded server-side,
// already at 0 mana, etc.) gets shelved for 5 minutes so we move on.
// Same idea for tap targets: an item whose drain never completed waits TapTargetRetryMs
// before it is tried again (with the next stone).
private readonly Dictionary<int, long> _tapTargetCooldownUntil = new();
private const long TapTargetCooldownMs = 5 * 60 * 1000;
// And for the stone half of the pair: a "stone" that AC silently refuses
// to use (often because it's actually charged but our cache reads its
@ -140,6 +139,34 @@ internal sealed class ManaStoneManager
private const long LootedForTapPruneIntervalMs = 1_000;
private long _lootedForTapPrunedAt;
// When each tap item's pickup was confirmed (it is in the pack). A drain is only sent for an
// item that has arrived: one went out 30 ms before its pickup was confirmed (2026-10-15) and
// the server never answered it. An item whose confirm was lost counts as arrived once it is
// owned and TapArrivalFallbackMs have passed since the pickup was sent.
private readonly Dictionary<int, long> _tapArrivedAt = new();
private const long TapArrivalSettleMs = 500;
private const long TapArrivalFallbackMs = 5_000;
// Drains that never completed, per item and per stone. An item gets TapTargetMaxTries (each
// with the next stone), then it is given up: it stays in the pack as ordinary loot. A stone
// that failed twice is parked for StoneTapLongCooldownMs. Before this a failed item was
// shelved for 5 minutes and stopped counting against the stones, so the looter took another
// item in its place, and the pack filled with undrained tap items (9 in 10 drains timed out).
private readonly Dictionary<int, int> _tapTargetFailures = new();
private readonly Dictionary<int, int> _stoneTapFailures = new();
private const int TapTargetMaxTries = 3;
private const long TapTargetRetryMs = 20_000;
private const long StoneTapLongCooldownMs = 30 * 60 * 1000;
// The server's lines while a drain is out, logged so a drain that never completes shows why.
private int _tapChatLogged;
private const int TapChatLogMax = 4;
// HoldsLootForDrain's answer, worked out at most every HoldCheckMs (the finders walk the cache).
private bool _holdLoot;
private long _holdLootAt = -HoldCheckMs;
private const long HoldCheckMs = 250;
public ManaStoneManager(RynthCoreHost host, LegacyUiSettings settings, WorldObjectCache objectCache)
{
_host = host;
@ -176,7 +203,7 @@ internal sealed class ManaStoneManager
if (itemGone || stoneGone)
{
_host.Log($"[RynthAi] ManaStone: tap completion detected (itemGone={itemGone} stoneGone={stoneGone}).");
if (itemGone) _lootedForTap.Remove(_activeItemId); // drained and destroyed
if (itemGone) ForgetTapItem(_activeItemId); // drained and destroyed
GoIdle();
}
}
@ -211,8 +238,11 @@ internal sealed class ManaStoneManager
// failing on every tap target. Park the stone, not the item.
if (_state == TapState.TappingItem && _activeStoneId != 0)
{
_stoneTapCooldownUntil[_activeStoneId] = now + StoneTapCooldownMs;
_host.Log($"[RynthAi] ManaStone: blacklisting stone 0x{(uint)_activeStoneId:X8} for tap ({StoneTapCooldownMs / 1000}s cooldown).");
int stoneFails = _stoneTapFailures.TryGetValue(_activeStoneId, out int sf) ? sf + 1 : 1;
_stoneTapFailures[_activeStoneId] = stoneFails;
long park = stoneFails >= 2 ? StoneTapLongCooldownMs : StoneTapCooldownMs;
_stoneTapCooldownUntil[_activeStoneId] = now + park;
_host.Log($"[RynthAi] ManaStone: blacklisting stone 0x{(uint)_activeStoneId:X8} for tap ({park / 1000}s cooldown, {stoneFails} failed drain(s)).");
}
// ALSO shelve the TARGET item. A target that never completes a drain
// (server can't resolve the stone guid, item is retained/undrainable,
@ -223,10 +253,19 @@ internal sealed class ManaStoneManager
// bot's own casts) out of movement/combat. Shelving only the stone
// (above) does NOT break this loop because the WAND keeps getting
// selected. See [rynthai_respawn_blind_wedge] / 2026-06-22 wedge.
// It keeps its place against the stones meanwhile (FreeEmptyStoneSlots), so no other
// item is looted to tap while it waits; after TapTargetMaxTries it is given up.
if (_state == TapState.TappingItem && _activeItemId != 0)
{
_tapTargetCooldownUntil[_activeItemId] = now + TapTargetCooldownMs;
_host.Log($"[RynthAi] ManaStone: shelving tap target 0x{(uint)_activeItemId:X8} for {TapTargetCooldownMs / 1000}s (drain never completed).");
int fails = _tapTargetFailures.TryGetValue(_activeItemId, out int f) ? f + 1 : 1;
_tapTargetFailures[_activeItemId] = fails;
if (fails >= TapTargetMaxTries)
GiveUpTapTarget(_activeItemId, fails);
else
{
_tapTargetCooldownUntil[_activeItemId] = now + TapTargetRetryMs;
_host.Log($"[RynthAi] ManaStone: tap target 0x{(uint)_activeItemId:X8} did not drain (try {fails} of {TapTargetMaxTries}); trying again in {TapTargetRetryMs / 1000}s.");
}
}
Reset();
return; // let things settle before starting a new action this tick
@ -277,8 +316,12 @@ internal sealed class ManaStoneManager
|| text.Contains("has been destroyed"))
{
// The stone is charged now; its read still shows it empty until it is appraised again.
if (text.Contains("The Mana Stone drains")) MarkStoneCharged(_activeStoneId);
if (_activeItemId != 0) _lootedForTap.Remove(_activeItemId); // drained and destroyed
if (text.Contains("The Mana Stone drains"))
{
MarkStoneCharged(_activeStoneId);
_host.Log($"[RynthAi] ManaStone: drained 0x{(uint)_activeItemId:X8} into stone 0x{(uint)_activeStoneId:X8}.");
}
if (_activeItemId != 0) ForgetTapItem(_activeItemId); // drained and destroyed
GoIdle();
return;
}
@ -306,6 +349,11 @@ internal sealed class ManaStoneManager
GoIdle();
return;
}
if (_tapChatLogged < TapChatLogMax)
{
_tapChatLogged++;
_host.Log($"[RynthAi] ManaStone: while draining 0x{(uint)_activeItemId:X8} with 0x{(uint)_activeStoneId:X8} the server said '{text.Trim()}'.");
}
return;
}
@ -407,9 +455,36 @@ internal sealed class ManaStoneManager
/// rule matched, it holds enough mana and an empty stone is free): when the pickup
/// is sent, and again when it is confirmed. Only these items are ever drained.
/// </summary>
public void MarkLootedForTap(int itemId)
/// <param name="arrived">The pickup is confirmed: the item is in the pack (false: just sent).</param>
public void MarkLootedForTap(int itemId, bool arrived = true)
{
if (itemId != 0) _lootedForTap[itemId] = NowMs;
if (itemId == 0) return;
_lootedForTap[itemId] = NowMs;
if (arrived) _tapArrivedAt[itemId] = NowMs;
}
private void ForgetTapItem(int itemId)
{
_lootedForTap.Remove(itemId);
_tapArrivedAt.Remove(itemId);
_tapTargetFailures.Remove(itemId);
_tapTargetCooldownUntil.Remove(itemId);
}
/// <summary>Drains of this item never completed: it stays in the pack as ordinary loot.</summary>
private void GiveUpTapTarget(int itemId, int tries)
{
string name = _objectCache[itemId]?.Name ?? $"0x{(uint)itemId:X8}";
_host.Log($"[RynthAi] ManaStone: giving up on tap target 0x{(uint)itemId:X8} '{name}' after {tries} drains that never completed.");
_host.WriteToChat($"[RynthAi] Mana tapping: {name} would not drain after {tries} tries; it stays in your pack.", 1);
ForgetTapItem(itemId);
}
/// <summary>The pickup is confirmed and has settled, or its confirm was lost and it has long since been sent.</summary>
private bool TapItemArrived(int itemId, long now)
{
if (_tapArrivedAt.TryGetValue(itemId, out long at)) return now - at >= TapArrivalSettleMs;
return _lootedForTap.TryGetValue(itemId, out long sent) && now - sent >= TapArrivalFallbackMs;
}
/// <summary>The looter picked this item up as "ManaTap" this session (it is waiting to be drained).</summary>
@ -445,7 +520,7 @@ internal sealed class ManaStoneManager
}
if (drop == null) return;
foreach (int id in drop)
_lootedForTap.Remove(id);
ForgetTapItem(id);
_host.Log($"[RynthAi] ManaStone: {drop.Count} looted-for-tap item(s) left the pack or were kept by the player; {_lootedForTap.Count} left to drain.");
}
@ -497,6 +572,7 @@ internal sealed class ManaStoneManager
private void IssueTapItem(int stoneId, int itemId)
{
_tapChatLogged = 0;
_state = TapState.TappingItem;
_actionIssuedAt = NowMs;
_host.UseOnFor(unchecked((uint)stoneId), unchecked((uint)itemId), "ManaStone", "tap an item into a mana stone");
@ -564,39 +640,6 @@ internal sealed class ManaStoneManager
return count;
}
/// <summary>
/// Items looted for tapping that are in the player's inventory and match the
/// tap-target criteria (mana ≥ threshold, not equipped, not on the Weapons tab,
/// not loot-kept, not blacklisted). Each one
/// will eventually consume one empty stone, so they count against the
/// "free slots" quota that CorpseOpenController uses for ManaTap pickup.
/// </summary>
public int CountPendingDrainItems()
{
if (!_host.HasGetObjectIntProperty) return 0;
int threshold = _settings.ManaTapMinMana;
if (threshold <= 0) return 0;
int playerId = unchecked((int)_host.GetPlayerId());
long now = NowMs;
int count = 0;
foreach (int id in _lootedForTap.Keys) // keep in sync with FindTapTarget
{
WorldObject? item = _objectCache[id];
if (item == null) continue;
if (IsManaStone(item)) continue;
if (!IsOwnedByPlayer(item, playerId)) continue;
if (_tapTargetCooldownUntil.TryGetValue(item.Id, out long until) && now < until) continue;
if (_host.TryGetObjectIntProperty(unchecked((uint)item.Id), (uint)AcIntProperty.WieldedSlot, out int wield)
&& wield != 0) continue;
if (!_host.TryGetObjectIntProperty(unchecked((uint)item.Id), (uint)AcIntProperty.CurrentMana, out int curMana)
|| curMana < threshold) continue;
if (IsProtectedFromTap(item, playerId)) continue; // keep in sync with FindTapTarget
count++;
}
return count;
}
/// <summary>
/// Items a drain must never touch (the drain destroys the item): gear the player
/// is wearing or wielding, weapons and wands on the Weapons tab (the bow sits in
@ -619,11 +662,35 @@ internal sealed class ManaStoneManager
}
/// <summary>
/// Free empty-stone slots = empty stones in inventory minus drain candidates
/// already in inventory waiting to be tapped. CorpseOpenController only
/// looks for new ManaTap pickups when this is &gt; 0.
/// How many items the looter may pick up to tap: 1 when an empty stone is in the pack and
/// no item looted to tap is waiting for its drain, else 0. One at a time (2026-10-15): the
/// stone first, then one item, drained before the next is looted. An item whose drain is
/// retrying still holds its place (it used to stop counting once shelved, and the looter
/// took another in its place). CorpseOpenController only looks for new ManaTap pickups when
/// this is &gt; 0.
/// </summary>
public int FreeEmptyStoneSlots() => Math.Max(0, CountEmptyStones() - CountPendingDrainItems());
public int FreeEmptyStoneSlots()
{
if (_lootedForTap.Count > 0) return 0;
return CountEmptyStones() > 0 ? 1 : 0;
}
/// <summary>
/// True while a drain is out, or an item looted to tap is in the pack with an empty stone
/// ready for it: the looter waits (no next item, no next corpse) so the drain goes first.
/// An item waiting to retry a failed drain does not hold the looter.
/// </summary>
public bool HoldsLootForDrain()
{
if (_state == TapState.TappingItem) return true;
if (_lootedForTap.Count == 0) return false;
if (!_settings.EnableManaTapping || !_settings.IsMacroRunning || !_host.HasUseObjectOn) return false;
long now = NowMs;
if (now - _holdLootAt < HoldCheckMs) return _holdLoot;
_holdLootAt = now;
_holdLoot = FindEmptyStone() != 0 && FindTapTarget(_settings.ManaTapMinMana) != 0;
return _holdLoot;
}
/// <summary>
/// True when the item is a mana stone.
@ -893,6 +960,7 @@ internal sealed class ManaStoneManager
WorldObject? item = _objectCache[id];
if (item == null) continue;
if (IsManaStone(item)) continue;
if (!TapItemArrived(id, now)) continue; // its pickup is still on the way
if (!IsOwnedByPlayer(item, playerId)) continue;
// Wands, staves and orbs drain like any other item (ACE's ManaStone only refuses

View file

@ -25,12 +25,27 @@ public sealed partial class RynthAiPlugin
{
private static readonly string[] MeleeHeightNames = { "Low", "Medium", "High" };
/// <summary>
/// /ra videopatch and /ub videopatch [enable|disable|off|world|unfocused|all|fps &lt;n&gt;|status]: the
/// engine's video patch (stop drawing AC's 3D world to save CPU and GPU, like UtilityBelt's), run as
/// /rc videopatch. <paramref name="argsFrom"/>: the index in <paramref name="parts"/> the arguments start at.
/// </summary>
internal void ForwardVideoPatch(string[] parts, int argsFrom)
{
string args = parts.Length > argsFrom ? string.Join(" ", parts, argsFrom, parts.Length - argsFrom) : "";
string command = "/rc videopatch" + (args.Length > 0 ? " " + args : "");
if (!Host.HasInvokeChatParser || !Host.InvokeChatParser(command))
ChatLine("[RynthAi] The video patch is RynthCore's: type " + command + " (this engine can't run it for RynthAi).");
}
/// <summary>The VTank-style /ra commands; false when <paramref name="cmd"/> isn't one of them.</summary>
private bool TryHandleVTankHotkeyCommand(string cmd, string[] parts)
{
switch (cmd)
{
case "vtkeys": VTankKeysHelp(); return true;
case "videopatch":
case "video": ForwardVideoPatch(parts, 2); return true;
case "setmetastate":
case "metastate": HandleSetMetaStateCommand(parts); return true;
case "targetlock": HandleTargetLockCommand(parts); return true;

View file

@ -93,6 +93,13 @@ public sealed partial class RynthAiPlugin
return true;
}
// /ub videopatch [enable|disable|...] (UtilityBelt's video patch) is the engine's: /rc videopatch.
if (cmd is "videopatch" or "video")
{
ForwardVideoPatch(parts, 2);
return true;
}
// /ub bc, /ub bct, /ub netclients (UtilityBelt's networking) belong to the RynthNet plugin.
if (cmd is "bc" or "bct" or "netclients")
{

View file

@ -0,0 +1,98 @@
using System;
using System.Collections.Generic;
using System.IO;
using DotRecast.Core;
using DotRecast.Detour;
using DotRecast.Detour.Io;
namespace RynthNav.Routing;
/// <summary>
/// A dungeon's navmesh, one file (NavData\dun_LLLL.tile) holding all its Detour tiles.
///
/// A dungeon's cells are not kept inside their landblock: they run into negative landblock-local x/y
/// (down to about -360 m) and out past 192 m (to about 390 m), over 190 m tiles that are no real
/// landblocks. So a dungeon is its own navmesh, laid out in the landblock-local frame shifted by
/// (ShiftX, ShiftY) metres, a multiple of 192 that makes every coordinate positive:
///
/// mesh position = landblock-local position + shift (x east, up, y north; the pose's x, y, z)
///
/// Tiles are 192 m squares on that frame (tile index = floor(mesh / 192), in each tile's header).
///
/// File: "RNDG" (0x47444E52), version 1, int shiftX, int shiftY, int count, then per tile
/// int length and the tile as DotRecast's DtMeshDataWriter writes it (little endian).
/// Host-free: the plugin, the baker and the tests share it.
/// </summary>
internal sealed class DungeonTileFile
{
public const string Prefix = "dun_";
public const string Extension = ".tile";
private const uint Magic = 0x47444E52; // "RNDG"
private const int Version = 1;
public const float TileSize = 192f;
public int ShiftX { get; }
public int ShiftY { get; }
public IReadOnlyList<DtMeshData> Tiles { get; }
public DungeonTileFile(int shiftX, int shiftY, IReadOnlyList<DtMeshData> tiles) { ShiftX = shiftX; ShiftY = shiftY; Tiles = tiles; }
public static string FileName(uint lb) => $"{Prefix}{lb:X4}{Extension}";
public static void Write(string path, int shiftX, int shiftY, IReadOnlyList<DtMeshData> tiles)
{
string tmp = path + ".tmp";
using (var fs = File.Create(tmp))
using (var bw = new BinaryWriter(fs))
{
bw.Write(Magic); bw.Write(Version); bw.Write(shiftX); bw.Write(shiftY); bw.Write(tiles.Count);
foreach (DtMeshData md in tiles)
{
using var ms = new MemoryStream();
using (var tw = new BinaryWriter(ms, System.Text.Encoding.UTF8, leaveOpen: true))
new DtMeshDataWriter().Write(tw, md, RcByteOrder.LITTLE_ENDIAN, false);
bw.Write((int)ms.Length);
bw.Write(ms.GetBuffer(), 0, (int)ms.Length);
}
}
File.Move(tmp, path, overwrite: true); // a bake stopped half way never leaves a truncated file
}
/// <summary>Reads a dungeon file; null when it isn't one (or is cut short).</summary>
public static DungeonTileFile? Read(string path, int vertsPerPoly = 6)
{
try
{
using var fs = File.OpenRead(path);
using var br = new BinaryReader(fs);
if (br.ReadUInt32() != Magic || br.ReadInt32() != Version) return null;
int sx = br.ReadInt32(), sy = br.ReadInt32(), n = br.ReadInt32();
if (n < 0 || n > 4096) return null;
var tiles = new List<DtMeshData>(n);
for (int i = 0; i < n; i++)
{
int len = br.ReadInt32();
if (len <= 0 || len > fs.Length - fs.Position) return null;
using var ms = new MemoryStream(br.ReadBytes(len));
using var tr = new BinaryReader(ms);
tiles.Add(new DtMeshDataReader().Read(tr, vertsPerPoly));
}
return new DungeonTileFile(sx, sy, tiles);
}
catch (Exception ex) when (ex is IOException or EndOfStreamException or InvalidDataException or ArgumentException) { return null; }
}
/// <summary>A Detour navmesh of just these tiles (mesh frame: tile (x, y) at x * 192, y * 192).</summary>
public DtNavMesh BuildNavMesh()
{
var nav = new DtNavMesh();
var p = new DtNavMeshParams
{
orig = new DotRecast.Core.Numerics.RcVec3f(0, 0, 0), tileWidth = TileSize, tileHeight = TileSize,
maxTiles = Math.Max(1, Tiles.Count), maxPolys = 1 << 16,
};
nav.Init(ref p, 6);
foreach (DtMeshData md in Tiles) nav.AddTile(md, 0, 0, out _);
return nav;
}
}

View file

@ -0,0 +1,327 @@
using System;
using System.Collections.Generic;
using DotRecast.Detour;
using RynthCore.Plugin.Shared;
namespace RynthNav.Routing;
/// <summary>
/// The navmesh drawn in the world: where you can walk, and where the mesh ends.
///
/// - Floor: the walkable ground, as translucent triangles lying on it (the tile's detail mesh,
/// so they follow the terrain and the building floors).
/// - Walls: every polygon edge with no neighbour, as an upright strip of triangles. Those edges are
/// exactly where the baker said "not here": buildings, trees, rocks, cliffs, steep slopes, water,
/// and the body-width margin round them. Where there is no green and a red wall stands, nav
/// will not take you.
///
/// Host-free (it writes to an <see cref="INav3DSink"/>), so the tests cover it. Tick thread only.
/// The tiles are registered as the plugin loads them (just a reference); a tile's triangles are
/// worked out the first time it is within range. The engine's Nav3D buffer holds 8192 triangles
/// for every plugin, so a draw is capped (<see cref="Options.MaxTriangles"/>), nearest first.
/// </summary>
internal sealed class NavMeshView
{
public const float TileSize = 192f;
/// <summary>One tile's triangles, relative to the tile's south-west corner (precise in float at any landblock).</summary>
internal sealed class Tile
{
public int OriginX, OriginY; // world metres of the corner (landblock x/y * 192)
public float[] Floor = Array.Empty<float>(); // 9 per triangle: (east, up, north) x3
public float[] Walls = Array.Empty<float>(); // 6 per edge: (east, up, north) of its two ends
public int FloorCount => Floor.Length / 9;
public int WallCount => Walls.Length / 6;
}
internal readonly struct Options
{
public readonly float Radius; // metres from the character
public readonly int MaxTriangles; // for floor and walls together (a wall strip is two)
public readonly bool Floor, Walls;
public readonly float Lift; // floor and wall bottoms above the mesh, so they don't fight the ground
public readonly float WallHeight;
public readonly float MaxUpDown; // ignore mesh further above/below the character than this (other levels)
public readonly uint FloorColor, WallColor;
public readonly int Layer; // 0 = the outdoor tiles, 1 = the dungeon's: only one is drawn
public readonly double FrameX, FrameY; // world metres of the landblock whose local frame Nav3D is in; NaN = the one the character stands in (outdoors)
public Options(float radius, int maxTriangles, bool floor, bool walls, float lift = 0.15f, float wallHeight = 1.5f,
float maxUpDown = 20f, uint floorColor = DefaultFloorColor, uint wallColor = DefaultWallColor,
int layer = 0, double frameX = double.NaN, double frameY = double.NaN)
{
Radius = radius; MaxTriangles = maxTriangles; Floor = floor; Walls = walls; Lift = lift;
WallHeight = wallHeight; MaxUpDown = maxUpDown; FloorColor = floorColor; WallColor = wallColor;
Layer = layer; FrameX = frameX; FrameY = frameY;
}
}
public const uint DefaultFloorColor = 0x3A30E060; // translucent green
public const uint DefaultWallColor = 0x78FF3A2A; // translucent red
// A wall counts as nearer than it is when choosing what to keep under the cap: a wall is what
// you most want to see, and one strip costs two triangles.
private const float WallPriority = 0.25f;
// The pick is kept until the character moves this far (or a tile comes or goes).
private const float RepickMetres = 1.5f;
// One registered tile: its data, where its corner is on the mesh's own frame (what the vertices are
// measured from) and in the world, and which layer it is drawn in.
private sealed class Reg
{
public DtMeshData Md = null!;
public int MeshOx, MeshOy, WorldOx, WorldOy, Layer;
}
private const uint DungeonKeyBase = 0x100000;
private readonly Dictionary<uint, Reg> _data = new();
private readonly Dictionary<uint, Tile?> _built = new();
private readonly List<uint> _dungeonKeys = new();
private int _version;
private int _pickLayer = -1;
private readonly struct Pick
{
public readonly Tile T; public readonly int Index; public readonly bool Wall; public readonly float Key;
public Pick(Tile t, int index, bool wall, float key) { T = t; Index = index; Wall = wall; Key = key; }
}
private readonly List<Pick> _picks = new();
private readonly List<Pick> _cands = new();
private int _pickVersion = -1;
private double _pickX = double.NaN, _pickY;
private float _pickRadius;
private int _pickBudget;
private bool _pickFloor, _pickWalls;
private float _pickUp = float.NaN;
/// <summary>Triangles / wall strips submitted by the last <see cref="Emit"/>.</summary>
public int LastTriangles { get; private set; }
public int TileCount => _data.Count;
/// <summary>An outdoor tile (nav_LLLL.tile): its vertices are world metres, its corner is the landblock's.</summary>
public void Register(uint lb, DtMeshData md)
{
int ox = (int)((lb >> 8) & 0xFF) * (int)TileSize, oy = (int)(lb & 0xFF) * (int)TileSize;
_data[lb] = new Reg { Md = md, MeshOx = ox, MeshOy = oy, WorldOx = ox, WorldOy = oy, Layer = 0 };
_built.Remove(lb); _version++;
}
public void Unregister(uint lb)
{
if (_data.Remove(lb)) { _built.Remove(lb); _version++; }
}
/// <summary>The landblock whose dungeon is registered (0 = none).</summary>
public uint DungeonLandblock { get; private set; }
/// <summary>
/// A dungeon's tiles (dun_LLLL.tile), replacing any dungeon registered before. Their vertices are on the
/// file's shifted frame (landblock-local + shift); the world corner of a tile is the landblock's plus the
/// tile's mesh corner minus the shift.
/// </summary>
public void RegisterDungeon(uint lb, DungeonTileFile f)
{
UnregisterDungeon();
double lbX = ((lb >> 8) & 0xFF) * (double)TileSize, lbY = (lb & 0xFF) * (double)TileSize;
for (int i = 0; i < f.Tiles.Count; i++)
{
DtMeshData md = f.Tiles[i];
int mx = md.header.x * (int)TileSize, my = md.header.y * (int)TileSize;
uint key = DungeonKeyBase + (uint)i;
_data[key] = new Reg { Md = md, MeshOx = mx, MeshOy = my, WorldOx = (int)(lbX + mx - f.ShiftX), WorldOy = (int)(lbY + my - f.ShiftY), Layer = 1 };
_built.Remove(key); _dungeonKeys.Add(key);
}
DungeonLandblock = lb; _version++;
}
public void UnregisterDungeon()
{
foreach (uint k in _dungeonKeys) { _data.Remove(k); _built.Remove(k); }
if (_dungeonKeys.Count > 0 || DungeonLandblock != 0) _version++;
_dungeonKeys.Clear(); DungeonLandblock = 0;
}
public void Clear()
{
_data.Clear(); _built.Clear(); _dungeonKeys.Clear(); DungeonLandblock = 0; _picks.Clear(); _cands.Clear(); _version++; LastTriangles = 0;
}
// ── Reading a tile ───────────────────────────────────────────────────────
/// <summary>The floor triangles and wall edges of one baked tile.</summary>
internal static Tile BuildTile(uint lb, DtMeshData md)
{
int ox = (int)((lb >> 8) & 0xFF) * (int)TileSize, oy = (int)(lb & 0xFF) * (int)TileSize;
return BuildTile(md, ox, oy, ox, oy);
}
/// <summary>Vertices are measured from the tile's corner on the mesh's frame; the tile itself sits at its world corner.</summary>
internal static Tile BuildTile(DtMeshData md, int meshOx, int meshOy, int worldOx, int worldOy)
{
var t = new Tile { OriginX = worldOx, OriginY = worldOy };
float ox = meshOx, oy = meshOy;
var floor = new List<float>(md.header.detailTriCount * 9);
var walls = new List<float>();
void Vtx(List<float> to, float x, float up, float ns) { to.Add(x - ox); to.Add(up); to.Add(ns - oy); }
for (int i = 0; i < md.header.polyCount; i++)
{
DtPoly p = md.polys[i];
if (p.GetPolyType() != DtPolyTypes.DT_POLYTYPE_GROUND) continue;
int nv = p.vertCount;
// Edges nothing is joined to (not a tile border: those carry DT_EXT_LINK, so they're nonzero).
for (int j = 0; j < nv; j++)
{
if (p.neis[j] != 0) continue;
int a = p.verts[j] * 3, b = p.verts[(j + 1) % nv] * 3;
Vtx(walls, md.verts[a], md.verts[a + 1], md.verts[a + 2]);
Vtx(walls, md.verts[b], md.verts[b + 1], md.verts[b + 2]);
}
// The ground: the polygon's detail triangles (they follow the height), else a fan.
DtPolyDetail[]? dm = md.detailMeshes;
if (dm != null && i < dm.Length && dm[i].triCount > 0)
{
DtPolyDetail pd = dm[i];
for (int k = 0; k < pd.triCount; k++)
for (int c = 0; c < 3; c++)
{
int idx = md.detailTris[(pd.triBase + k) * 4 + c];
if (idx < nv) { int v = p.verts[idx] * 3; Vtx(floor, md.verts[v], md.verts[v + 1], md.verts[v + 2]); }
else { int v = (pd.vertBase + idx - nv) * 3; Vtx(floor, md.detailVerts[v], md.detailVerts[v + 1], md.detailVerts[v + 2]); }
}
}
else
{
for (int k = 1; k + 1 < nv; k++)
foreach (int idx in new[] { 0, k, k + 1 })
{ int v = p.verts[idx] * 3; Vtx(floor, md.verts[v], md.verts[v + 1], md.verts[v + 2]); }
}
}
t.Floor = floor.ToArray();
t.Walls = walls.ToArray();
return t;
}
private Tile? TileFor(uint key)
{
if (_built.TryGetValue(key, out Tile? t)) return t;
t = _data.TryGetValue(key, out Reg? r) ? BuildTile(r.Md, r.MeshOx, r.MeshOy, r.WorldOx, r.WorldOy) : null;
_built[key] = t;
return t;
}
// ── Choosing what to draw ────────────────────────────────────────────────
private void Repick(double px, double py, float pz, in Options o)
{
_picks.Clear(); _cands.Clear();
float r = o.Radius, r2 = r * r;
int cost = 0;
foreach (var kv in _data)
{
uint lb = kv.Key;
if (kv.Value.Layer != o.Layer) continue;
float x0 = kv.Value.WorldOx, y0 = kv.Value.WorldOy;
// Distance from the character to the tile's square.
double dx = Math.Max(Math.Max(x0 - px, px - (x0 + TileSize)), 0), dy = Math.Max(Math.Max(y0 - py, py - (y0 + TileSize)), 0);
if (dx * dx + dy * dy > (double)r2) continue;
Tile? t = TileFor(lb);
if (t == null) continue;
float ox = t.OriginX - (float)px, oy = t.OriginY - (float)py; // tile corner relative to the character
if (o.Floor)
{
float[] f = t.Floor;
for (int k = 0, n = t.FloorCount; k < n; k++)
{
int b = k * 9;
float cx = ox + (f[b] + f[b + 3] + f[b + 6]) / 3f, cy = oy + (f[b + 2] + f[b + 5] + f[b + 8]) / 3f;
float d2 = cx * cx + cy * cy;
if (d2 > r2) continue;
if (Math.Abs((f[b + 1] + f[b + 4] + f[b + 7]) / 3f - pz) > o.MaxUpDown) continue;
_cands.Add(new Pick(t, k, false, d2));
cost++;
}
}
if (o.Walls)
{
float[] w = t.Walls;
for (int k = 0, n = t.WallCount; k < n; k++)
{
int b = k * 6;
float cx = ox + (w[b] + w[b + 3]) * 0.5f, cy = oy + (w[b + 2] + w[b + 5]) * 0.5f;
float d2 = cx * cx + cy * cy;
if (d2 > r2) continue;
if (Math.Abs((w[b + 1] + w[b + 4]) * 0.5f - pz) > o.MaxUpDown) continue;
_cands.Add(new Pick(t, k, true, d2 * WallPriority));
cost += 2;
}
}
}
if (cost > o.MaxTriangles) _cands.Sort((a, b) => a.Key.CompareTo(b.Key));
int used = 0;
foreach (Pick c in _cands)
{
int c2 = c.Wall ? 2 : 1;
if (used + c2 > o.MaxTriangles) { if (cost > o.MaxTriangles) break; continue; }
_picks.Add(c);
used += c2;
}
_cands.Clear();
_pickVersion = _version; _pickX = px; _pickY = py; _pickUp = pz;
_pickRadius = o.Radius; _pickBudget = o.MaxTriangles; _pickFloor = o.Floor; _pickWalls = o.Walls; _pickLayer = o.Layer;
}
// ── Drawing ──────────────────────────────────────────────────────────────
/// <summary>
/// Submits the mesh near the character (world metres east/north/up) to the sink, in the Nav3D
/// frame: the character's landblock, X = east, Y = height, Z = north. Returns triangles submitted.
/// </summary>
public int Emit(INav3DSink sink, double px, double py, double pz, in Options o)
{
LastTriangles = 0;
if (_data.Count == 0 || o.MaxTriangles <= 0 || (!o.Floor && !o.Walls)) return 0;
double dxm = px - _pickX, dym = py - _pickY;
bool stale = _pickVersion != _version || double.IsNaN(_pickX) || dxm * dxm + dym * dym > RepickMetres * RepickMetres
|| Math.Abs(pz - _pickUp) > 2f || o.Radius != _pickRadius || o.MaxTriangles != _pickBudget
|| o.Floor != _pickFloor || o.Walls != _pickWalls || o.Layer != _pickLayer;
if (stale) Repick(px, py, (float)pz, o);
// Outdoors the character is inside its landblock, so its corner is the frame; in a dungeon the
// character's local x/y can be anywhere (down to -360), and the caller names the landblock.
double baseX = double.IsNaN(o.FrameX) ? Math.Floor(px / TileSize) * TileSize : o.FrameX;
double baseY = double.IsNaN(o.FrameY) ? Math.Floor(py / TileSize) * TileSize : o.FrameY;
int tris = 0;
foreach (Pick c in _picks)
{
Tile t = c.T;
float ox = (float)(t.OriginX - baseX), oy = (float)(t.OriginY - baseY);
if (!c.Wall)
{
float[] f = t.Floor; int b = c.Index * 9;
sink.Triangle(ox + f[b], f[b + 1] + o.Lift, oy + f[b + 2],
ox + f[b + 3], f[b + 4] + o.Lift, oy + f[b + 5],
ox + f[b + 6], f[b + 7] + o.Lift, oy + f[b + 8], o.FloorColor);
tris++;
}
else
{
float[] w = t.Walls; int b = c.Index * 6;
float ax = ox + w[b], ay = w[b + 1] + o.Lift, az = oy + w[b + 2];
float bx = ox + w[b + 3], by = w[b + 4] + o.Lift, bz = oy + w[b + 5];
sink.Triangle(ax, ay, az, bx, by, bz, bx, by + o.WallHeight, bz, o.WallColor);
sink.Triangle(ax, ay, az, bx, by + o.WallHeight, bz, ax, ay + o.WallHeight, az, o.WallColor);
tris += 2;
}
}
LastTriangles = tris;
return tris;
}
}

View file

@ -58,11 +58,12 @@ public sealed partial class RynthNavPlugin
{
_tileRegions[lb] = NavRegions.Build(md, out _);
_tilePrints[lb] = NavRegions.Fingerprint(md);
_meshView.Register(lb, md);
NavGraph? g = _graph;
if (g != null && ReferenceEquals(g, _graphChecked)) CheckTile(g, lb);
}
private void OnTileUnloaded(uint lb) { _tileRegions.Remove(lb); _tilePrints.Remove(lb); }
private void OnTileUnloaded(uint lb) { _tileRegions.Remove(lb); _tilePrints.Remove(lb); _meshView.Unregister(lb); }
private void CheckTile(NavGraph g, uint lb)
{

View file

@ -49,6 +49,55 @@ public sealed partial class RynthNavPlugin
_markerGuide = NavDataConfig.ReadSwitch("markerGuide", false);
}
// ── The walking path, for the engine's World Map ─────────────────────
// The trip's walks (and the walks inside the Town Network) as the status JSON's "path": an array of
// segments, each a flat list of ns, ew pairs in map degrees (4 decimals: 0.02 yd), thinned to about
// MaxPathPoints in all (a segment keeps its ends). Built once per TripPath and kept; empty (the field
// is left out) while the markers are off the ground or the path isn't worked out yet. Pump thread.
private const int MaxPathPoints = 800;
private TripPath? _pathJsonFor;
private string _pathJson = "";
private string PathJson()
{
TripPath? p = _tripPath;
if (p == null || !_tripShown) return "";
lock (_gate)
{
if (ReferenceEquals(p, _pathJsonFor)) return _pathJson;
var segs = new List<WorldPt[]>();
for (int i = 0; i < p.Walks.Length; i++)
{
if (p.Walks[i] is { Length: >= 2 } w) segs.Add(w);
if (i < p.Hub.Length && p.Hub[i] is { Length: >= 2 } h) segs.Add(h);
}
int total = 0;
foreach (WorldPt[] s in segs) total += s.Length;
int stride = Math.Max(1, (total + MaxPathPoints - 1) / MaxPathPoints);
var ci = System.Globalization.CultureInfo.InvariantCulture;
var sb = new System.Text.StringBuilder(total * 20 + 8);
sb.Append('[');
bool firstSeg = true;
foreach (WorldPt[] s in segs)
{
if (!firstSeg) sb.Append(',');
firstSeg = false;
sb.Append('[');
for (int i = 0; i < s.Length; i++)
{
if (i % stride != 0 && i != s.Length - 1) continue;
if (i > 0) sb.Append(',');
sb.Append(NavCoords.NsFromWorld(s[i].Y).ToString("F4", ci)).Append(',').Append(NavCoords.EwFromWorld(s[i].X).ToString("F4", ci));
}
sb.Append(']');
}
sb.Append(']');
_pathJsonFor = p;
_pathJson = segs.Count == 0 ? "" : sb.ToString();
return _pathJson;
}
}
// ── The trip ─────────────────────────────────────────────────────────
/// <summary>A new plan (Route) or goto (Go): its trip, shown, its path worked out. Tick thread.</summary>

View file

@ -0,0 +1,114 @@
using System;
using System.Globalization;
using RynthNav.Routing;
namespace RynthCore.Plugin.RynthNav;
// The navmesh on the ground (NavMeshView): green where nav can take you, red walls where the mesh
// ends (buildings, trees, rocks, cliffs, steep slopes, and the margin round them). Drawn on the
// engine's Nav3D buffer like the path markers. Off by default; it is a look-at-it tool, not part
// of walking. Switches in rynthnav.json: meshView, meshFloor, meshWalls, meshRadius, meshTriangles.
// /rnav mesh changes them. In a dungeon it draws NavData\dun_LLLL.tile (a dungeon's own mesh, baked by
// RynthNav.Baker --dungeons), the floor you're on; with no such file it draws nothing there. Not drawn while portaling.
public sealed partial class RynthNavPlugin
{
private const double MeshRadiusDefault = 40, MeshRadiusMin = 10, MeshRadiusMax = 150;
private const int MeshTrianglesDefault = 3000, MeshTrianglesMin = 200, MeshTrianglesMax = 7000;
private volatile bool _meshOn, _meshFloor = true, _meshWalls = true;
private double _meshRadius = MeshRadiusDefault;
private int _meshBudget = MeshTrianglesDefault;
private readonly NavMeshView _meshView = new();
private volatile int _meshDrawn;
private void LoadMeshSettings()
{
_meshOn = NavDataConfig.ReadSwitch("meshView", false);
_meshFloor = NavDataConfig.ReadSwitch("meshFloor", true);
_meshWalls = NavDataConfig.ReadSwitch("meshWalls", true);
_meshRadius = Math.Clamp(NavDataConfig.ReadNumber("meshRadius", MeshRadiusDefault), MeshRadiusMin, MeshRadiusMax);
_meshBudget = (int)Math.Clamp(NavDataConfig.ReadNumber("meshTriangles", MeshTrianglesDefault), MeshTrianglesMin, MeshTrianglesMax);
}
// A dungeon draws only the floor you're on, give or take: the floors above and below sit metres away.
private const float MeshDungeonUpDown = 8f;
private uint _meshDunLb; // the landblock a dungeon file was last looked for (0 = outdoors / none yet)
private string _meshDunStatus = "";
private void TickMeshView()
{
if (!_meshOn || !_hasPose || !Host.HasNav3D || !Host.HasNav3DTriangle) { _meshDrawn = 0; return; }
if ((_cellId >> 16) == 0 || (Host.HasIsPortaling && Host.IsPortaling())) { _meshDrawn = 0; return; }
try
{
// Cells from 0x100 up are buildings or a dungeon. A landblock with a dungeon file (dun_LLLL.tile)
// is drawn from it; a building in an outdoor landblock keeps the outdoor mesh.
uint lb = CurrentLandblock;
bool indoors = (_cellId & 0xFFFF) >= 0x100;
if (indoors && lb != _meshDunLb)
{
_meshDunLb = lb;
LoadMeshDungeon(lb);
}
else if (!indoors && _meshDunLb != 0)
{
_meshDunLb = 0;
_meshView.UnregisterDungeon();
_meshDunStatus = "";
}
bool dungeon = indoors && _meshView.DungeonLandblock == lb;
NavMeshView.Options opts = dungeon
? new NavMeshView.Options((float)_meshRadius, _meshBudget, _meshFloor, _meshWalls, maxUpDown: MeshDungeonUpDown,
layer: 1, frameX: ((lb >> 8) & 0xFF) * 192.0, frameY: (lb & 0xFF) * 192.0)
: new NavMeshView.Options((float)_meshRadius, _meshBudget, _meshFloor, _meshWalls);
_meshDrawn = _meshView.Emit(_markerSink ??= new HostMarkerSink(Host), _wx, _wy, _wz, opts);
}
catch (Exception ex) { _meshDrawn = 0; Host.Log($"[RynthNav] mesh view: {ex.Message}"); }
}
/// <summary>Reads NavData\dun_LLLL.tile into the mesh view's dungeon layer (none: the layer is emptied). Tick thread.</summary>
private void LoadMeshDungeon(uint lb)
{
_meshView.UnregisterDungeon();
string path = System.IO.Path.Combine(NavDataDir, DungeonTileFile.FileName(lb));
if (!System.IO.File.Exists(path)) { _meshDunStatus = $"no dungeon tile for 0x{lb:X4}"; return; }
DungeonTileFile? f = DungeonTileFile.Read(path);
if (f == null) { _meshDunStatus = $"dungeon tile 0x{lb:X4} unreadable"; Host.Log($"[RynthNav] {_meshDunStatus}"); return; }
_meshView.RegisterDungeon(lb, f);
_meshDunStatus = $"dungeon 0x{lb:X4}: {f.Tiles.Count} tiles";
Host.Log($"[RynthNav] mesh view: dungeon 0x{lb:X4} loaded ({f.Tiles.Count} tiles)");
}
/// <summary>/rnav mesh [on|off | floor on|off | walls on|off | radius &lt;m&gt; | triangles &lt;n&gt;]</summary>
private void CmdMesh(string rest)
{
string[] a = rest.ToLowerInvariant().Split(' ', StringSplitOptions.RemoveEmptyEntries);
bool isNum = a.Length == 2 && double.TryParse(a[1], NumberStyles.Float, CultureInfo.InvariantCulture, out _);
double num = isNum ? double.Parse(a[1], CultureInfo.InvariantCulture) : 0;
if (a.Length == 1 && a[0] is "on" or "off")
{
_meshOn = a[0] == "on";
NavDataConfig.WriteSwitch("meshView", _meshOn);
}
else if (a.Length == 2 && a[0] == "floor" && a[1] is "on" or "off")
{ _meshFloor = a[1] == "on"; NavDataConfig.WriteSwitch("meshFloor", _meshFloor); }
else if (a.Length == 2 && a[0] == "walls" && a[1] is "on" or "off")
{ _meshWalls = a[1] == "on"; NavDataConfig.WriteSwitch("meshWalls", _meshWalls); }
else if (a.Length == 2 && a[0] == "radius" && isNum)
{ _meshRadius = Math.Clamp(num, MeshRadiusMin, MeshRadiusMax); NavDataConfig.WriteNumber("meshRadius", _meshRadius); }
else if (a.Length == 2 && a[0] == "triangles" && isNum)
{ _meshBudget = (int)Math.Clamp(num, MeshTrianglesMin, MeshTrianglesMax); NavDataConfig.WriteNumber("meshTriangles", _meshBudget); }
else if (a.Length > 0)
{
Say("/rnav mesh on|off, mesh floor on|off, mesh walls on|off, mesh radius <m> (10-150), mesh triangles <n> (200-7000)");
return;
}
bool inDungeonMesh = _hasPose && (_cellId & 0xFFFF) >= 0x100 && _meshView.DungeonLandblock == CurrentLandblock;
string where = !_hasPose ? ""
: (_cellId & 0xFFFF) >= 0x100 && _meshDunStatus.StartsWith("no dungeon tile", StringComparison.Ordinal) && InDungeon(_cellId) ? $" — {_meshDunStatus}: bake it with RynthNav.Baker --dungeons"
: inDungeonMesh ? (_meshOn ? $" — {_meshDunStatus}, {_meshDrawn} triangles drawn" : $" — {_meshDunStatus}")
: _meshView.TileCount == 0 ? " — no tiles loaded here" : _meshOn ? $" — {_meshDrawn} triangles drawn, {_meshView.TileCount} tiles loaded" : "";
Say($"navmesh view {(_meshOn ? "ON" : "OFF")}: green floor {(_meshFloor ? "on" : "off")}, red walls {(_meshWalls ? "on" : "off")}, " +
$"{_meshRadius:0} m, at most {_meshBudget} triangles{where}. Green = nav can walk here; red = the mesh ends (building, tree, cliff, steep ground).");
}
}

View file

@ -153,11 +153,16 @@ public sealed partial class RynthNavPlugin
.Append("\",\"tileHere\":").Append(_tileHere).Append(",\"indoors\":").Append(_hasPose && (cell & 0xFFFF) >= 0x100 ? 1 : 0)
.Append(",\"onDisk\":").Append(_tilesOnDisk)
.Append(",\"townNet\":").Append(_townNet != null ? 1 : 0).Append(",\"townNetStatus\":\"").Append(Esc(_townNetStatus)).Append("\"}");
// Path markers (RynthNavPlugin.Markers.cs) and "save as nav route" (RynthNavPlugin.SaveRoute.cs), 0.6.6+.
// Path markers (RynthNavPlugin.Markers.cs) and "save as nav route" (RynthNavPlugin.SaveRoute.cs), 0.6.6+. The mesh view (RynthNavPlugin.MeshView.cs), 0.6.7+.
sb.Append(",\"mesh\":{\"on\":").Append(_meshOn ? 1 : 0).Append(",\"floor\":").Append(_meshFloor ? 1 : 0)
.Append(",\"walls\":").Append(_meshWalls ? 1 : 0).Append(",\"radius\":").Append(_meshRadius.ToString("F0", ci))
.Append(",\"triangles\":").Append(_meshBudget).Append(",\"drawn\":").Append(_meshDrawn).Append('}');
PlannedTrip? trip = _trip;
sb.Append(",\"markers\":{\"on\":").Append(_markersOn ? 1 : 0).Append(",\"labels\":").Append(_markerLabels ? 1 : 0)
.Append(",\"guide\":").Append(_markerGuide ? 1 : 0).Append(",\"shown\":").Append(trip != null && _tripShown ? 1 : 0)
.Append(",\"status\":\"").Append(Esc(_markerStatus)).Append("\"}");
string pathJson = PathJson(); // the walking path, for the engine's World Map
if (pathJson.Length > 0) sb.Append(",\"path\":").Append(pathJson);
sb.Append(",\"save\":{\"can\":").Append(trip != null ? 1 : 0).Append(",\"for\":\"").Append(Esc(trip?.Goal ?? ""))
.Append("\",\"name\":\"").Append(Esc(_saveDefault)).Append("\",\"conflict\":\"").Append(Esc(_saveConflict))
.Append("\",\"busy\":").Append(_saveBusy ? 1 : 0).Append(",\"last\":\"").Append(Esc(_saveLast)).Append("\"}");

View file

@ -986,6 +986,7 @@ public sealed partial class RynthNavPlugin
"/rnav goto <coords> | preview <coords> | portals on|off | stop | here | load | test | navdata\n" +
"/rnav avoid — show; avoid portals on|off|<m> | walls on|off|<m> | corners <m>\n" +
"/rnav markers on|off | markers labels on|off | markers guide on|off — the trip on the ground\n" +
"/rnav mesh on|off | floor on|off | walls on|off | radius <m> | triangles <n> — draw the navmesh: green floor, red walls\n" +
"/rnav saveroute [name] [overwrite] — save the last trip as a RynthAi nav route (NavProfiles)";
/// <summary>One /rnav command. Tick thread.</summary>
@ -1029,6 +1030,7 @@ public sealed partial class RynthNavPlugin
case "recalls": CmdRecalls(rest); break;
case "tie": CmdTie(rest); break;
case "markers": CmdMarkers(rest); break;
case "mesh": CmdMesh(rest); break;
case "saveroute": CmdSaveRoute(rest); break;
case "arrive":
if (double.TryParse(rest, NumberStyles.Float, CultureInfo.InvariantCulture, out double yd) && yd >= 2 && yd <= 200)

View file

@ -25,7 +25,7 @@ namespace RynthCore.Plugin.RynthNav;
public sealed partial class RynthNavPlugin : RynthPluginBase
{
internal static readonly IntPtr NamePointer = Marshal.StringToHGlobalAnsi("RynthNav");
internal const string PluginVersion = "0.6.6";
internal const string PluginVersion = "0.6.7";
internal static readonly IntPtr VersionPointer = Marshal.StringToHGlobalAnsi(PluginVersion);
/// <summary>Lets PluginExports log through this plugin's host (the base Log is protected).</summary>
@ -144,6 +144,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase
_recallsEnabled = NavDataConfig.ReadSwitch("recalls", true);
LoadAvoidSettings();
LoadMarkerSettings();
LoadMeshSettings();
Host.Log($"[RynthNav] Initialized v{PluginVersion} (tiled streaming + long-range goto + portal/recall routing + arrow + atlas). Panel: RynthNav. Tiles: {NavDataDir} ({NavConfig.Source})");
InitTravel();
LoadGraph();
@ -185,6 +186,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase
_chatOut.Clear();
_goNote = "";
HideMarkers("logged out");
_meshView.Clear(); _meshDunLb = 0;
_trip = null; _tripPath = null;
OnLogoutTravel();
}
@ -206,6 +208,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase
ProcessRequests();
ApplyMovement();
TickMarkers();
TickMeshView();
UpdateGoLine();
FlushChat();
}
@ -1192,10 +1195,15 @@ public sealed partial class RynthNavPlugin : RynthPluginBase
bool exists = File.Exists(Path.Combine(NavDataDir, $"nav_{lb:X4}.tile"));
int onDisk = 0;
try { if (Directory.Exists(NavDataDir)) onDisk = Directory.GetFiles(NavDataDir, "nav_*.tile").Length; } catch { }
bool indoors = (_cellId & 0xFFFF) >= 0x0100, dungeon = InDungeon(_cellId);
bool indoors = (_cellId & 0xFFFF) >= 0x0100;
bool dunFile = indoors && File.Exists(Path.Combine(NavDataDir, DungeonTileFile.FileName(lb)));
bool dungeon = InDungeon(_cellId) || dunFile;
string status; lock (_gate) status = _status;
return $"landblock 0x{lb:X4}{(dungeon ? " (a dungeon)" : indoors ? " (indoors)" : "")} — tile "
+ $"{(dungeon ? (exists ? "surface only, no dungeon navmesh" : "MISSING") : exists ? "FOUND" : "MISSING")}, {_tileCount} loaded, "
// Where exactly: the cell and the landblock-local position (what a dungeon's tile and its objects are placed in).
double lx = _wx - ((_cellId >> 24) & 0xFF) * 192.0, ly = _wy - ((_cellId >> 16) & 0xFF) * 192.0;
string at = $" cell {_cellId:X8} local ({lx:F1}, {ly:F1}, {_wz:F1}),";
return $"landblock 0x{lb:X4}{(dungeon ? " (a dungeon)" : indoors ? " (indoors)" : "")},{at} — tile "
+ $"{(dungeon ? (dunFile ? $"dungeon navmesh {DungeonTileFile.FileName(lb)} FOUND (the mesh view draws it; goto doesn't walk dungeons yet)" : "no dungeon navmesh baked") : exists ? "FOUND" : "MISSING")}, {_tileCount} loaded, "
+ $"{onDisk} tile(s) in {NavDataDir}; route graph: {_graphStatus}; Town Network: {_townNetStatus}; goto {(_gotoActive ? "ACTIVE" : "off")}"
+ $"{(_coarse != null ? $" (route {_coarse.Crossed}/{_coarse.Count})" : "")}, portals {(_portalsEnabled ? "on" : "off")}; status: {status}";
}

View file

@ -39,6 +39,9 @@ internal static class DoorTests
r.Add("door: nothing in portal space, nor just after it", NothingInPortalSpace);
r.Add("door: a door that opens is released at once (no fixed waits)", OpensFast);
r.Add("door: 'locked' from chat counts only as the server's line, not a player's", LockedChatLine);
r.Add("door: Only Doors On My Path - a door beside the way is left shut, one straight ahead is opened", PathOnlyAhead);
r.Add("door: Only Doors On My Path - on a route the door on the next leg goes, not a nearer one beside it", PathOnlyRoute);
r.Add("door: Only Doors On My Path - not a door past the range along the path, nor one behind the route's direction", PathOnlyRange);
}
// ── Rig ─────────────────────────────────────────────────────────────────
@ -297,6 +300,94 @@ internal static class DoorTests
Check.Eq(b.State, "None", "done without waiting for anything else");
});
// ── Only Doors On My Path (OpenDoorsOnPathOnly) ──────────────────────────────
private const uint Door2 = 0x701C913A;
private static int Uses(uint id) => FakeHost.Uses.Count(u => u == id);
/// <summary>A second closed door at an offset from where the player stands (world units: east, north).</summary>
private static void AddDoor(Bot b, uint id, float east, float north)
{
FakeHost.Names[id] = "Door";
FakeHost.Positions[id] = (Me0.Cell, Me0.X + east, Me0.Y + north, Me0.Z);
FakeHost.Bitfields[id] = BfDoor;
FakeHost.ObjectStates[id] = Closed;
b.Cache.OnCreateObject(id);
b.Cache.Tick();
}
private static void MoveDoor(uint id, float east, float north) => FakeHost.Positions[id] = (Me0.Cell, Me0.X + east, Me0.Y + north, Me0.Z);
/// <summary>A route of straight points from the player: each (east, north) offset in world units, as nav coordinates.</summary>
private static void SetRoute(Bot b, params (float East, float North)[] points)
{
double ax = ((Me0.Cell >> 24) & 0xFF) * 192.0 + Me0.X, ay = ((Me0.Cell >> 16) & 0xFF) * 192.0 + Me0.Y;
var route = new NavRouteParser { RouteType = NavRouteType.Linear };
foreach (var (e, n) in points)
route.Points.Add(new NavPoint { Type = NavPointType.Point, EW = ((ax + e) / 24.0 - 1019.5) / 10.0, NS = ((ay + n) / 24.0 - 1019.5) / 10.0 });
b.S.CurrentRoute = route;
b.S.ActiveNavIndex = 0;
b.S.EnableNavigation = true;
}
private static void PathOnlyAhead() => With(() =>
{
// No route, the character faces north. A door 2 yd east is beside the way.
FakeHost.HeadingDeg = 0;
var off = new Bot(); off.S.OpenDoorsOnPathOnly = false;
off.Tick(); off.Run(600);
Check.Eq(Uses(Door), 1, "control: with the setting off the door beside the character is opened");
FakeHost.Uses.Clear();
var b = new Bot(); b.S.OpenDoorsOnPathOnly = true;
b.Tick(); b.Run(600);
Check.Eq(Uses(Door), 0, "with it on, a door 2 yd to the east of a character facing north is left shut");
Check.Eq(b.State, "None", "and no door is being handled");
MoveDoor(Door, 0f, 2f); // now straight ahead
b.Tick(); b.Run(600);
Check.Eq(Uses(Door), 1, "a door 2 yd straight ahead is opened");
});
private static void PathOnlyRoute() => With(() =>
{
// The route runs east. Door2 stands 2.5 yd south of the character (nearer, beside the way); Door is 4 yd ahead on it.
FakeHost.HeadingDeg = 0;
MoveDoor(Door, 4f, 0f);
var off = new Bot(); AddDoor(off, Door2, 0f, -2.5f); MoveDoor(Door, 4f, 0f); SetRoute(off, (12f, 0f));
off.S.OpenDoorsOnPathOnly = false;
off.Tick(); off.Run(600);
Check.Eq(Uses(Door2), 1, "control: with the setting off the nearer door beside the route goes first");
FakeHost.Uses.Clear();
var b = new Bot(); AddDoor(b, Door2, 0f, -2.5f); MoveDoor(Door, 4f, 0f); SetRoute(b, (12f, 0f));
b.S.OpenDoorsOnPathOnly = true;
b.Tick(); b.Run(600);
Check.Eq(Uses(Door2), 0, "with it on, the door beside the route is not touched");
Check.Eq(Uses(Door), 1, "the door 4 yd along the route is opened");
});
private static void PathOnlyRange() => With(() =>
{
FakeHost.HeadingDeg = 0;
// 9 yd along the route, range 5: not yet.
var b = new Bot(); b.S.OpenDoorsOnPathOnly = true; MoveDoor(Door, 9f, 0f); SetRoute(b, (20f, 0f));
b.Tick(); b.Run(600);
Check.Eq(Uses(Door), 0, "a door 9 yd along the route is past the 5 yd range");
// The character walks on: now 3 yd along.
FakeHost.PlayerPose = (Me0.Cell, Me0.X + 6f, Me0.Y, Me0.Z);
FakeHost.Positions[Player] = FakeHost.PlayerPose;
b.Tick(); b.Run(600);
Check.Eq(Uses(Door), 1, "3 yd along it, it is opened");
// A route going west, the door east of the character: behind the way it is going.
FakeHost.Uses.Clear();
var c = new Bot(); c.S.OpenDoorsOnPathOnly = true; MoveDoor(Door, 3f, 0f); SetRoute(c, (-12f, 0f));
c.Tick(); c.Run(600);
Check.Eq(Uses(Door), 0, "a door 3 yd east of a route going west is not on the path");
});
private static void LockedChatLine() => With(() =>
{
var b = new Bot(lockpick: true);

View file

@ -30,6 +30,9 @@ internal static class ManaStoneChoiceTests
r.Add("mana stones: worn gear is identified again, so a stale-high read follows the gear", GearReadRefreshed);
r.Add("mana charges: overnight idle, the gear never runs dry (re-identify)", () => Overnight(identify: true));
r.Add("mana charges: overnight idle, the gear never runs dry (server warnings only)", () => Overnight(identify: false));
r.Add("mana tapping: one item at a time - the stone first, then one item, drained before the next", OneTapItemAtATime);
r.Add("mana tapping: no drain until the pickup is confirmed in the pack", NoDrainBeforeArrival);
r.Add("mana tapping: a drain that never completes keeps the item's place, tries the next stone, then gives up", FailedDrainKeepsPlace);
}
private const uint ChargeA = 0x80400031, ChargeB = 0x80400032, ChargeC = 0x80400033;
@ -223,7 +226,8 @@ internal static class ManaStoneChoiceTests
/// <param name="stones">Stone id and its charge read (null = can't be read).</param>
/// <param name="identify">The engine can identify objects (RequestId).</param>
public Rig(bool tapping, (uint Id, int? Mana)[] stones, bool ringToDrain = false,
string stoneName = "Moderate Mana Stone", int maceMana = 0, bool identify = true)
string stoneName = "Moderate Mana Stone", int maceMana = 0, bool identify = true,
bool ringArrived = true)
{
FakeHost.Reset();
FakeHost.UseOnCalls = true;
@ -259,7 +263,7 @@ internal static class ManaStoneChoiceTests
S.IsMacroRunning = true;
ManaStoneManager.Clock = () => Now;
M = new ManaStoneManager(host, S, C);
if (ringToDrain) M.MarkLootedForTap(unchecked((int)Ring));
if (ringToDrain) M.MarkLootedForTap(unchecked((int)Ring), arrived: ringArrived);
}
public static void SetMana(uint id, int? mana)
@ -299,12 +303,78 @@ internal static class ManaStoneChoiceTests
C.OnDeleteObject(id);
}
/// <summary>A ring with mana lands in the pack (looted).</summary>
public void AddRing()
{
FakeHost.Names[Ring] = "Ring";
FakeHost.Containers[Ring] = Player;
FakeHost.Ints[(Ring, MaxManaKey)] = 4000;
FakeHost.Ints[(Ring, CurManaKey)] = 4000;
_ = C[unchecked((int)Ring)];
}
public List<uint> OnPlayer => FakeHost.UsesOn.Where(u => u.Target == Player).Select(u => u.Source).ToList();
public List<uint> OnRing => FakeHost.UsesOn.Where(u => u.Target == Ring).Select(u => u.Source).ToList();
public void Dispose() => ManaStoneManager.Clock = static () => Environment.TickCount64;
}
// 2026-10-15: the pack filled with items looted to tap. A drain that never completed shelved
// its item for 5 minutes and the item stopped counting against the empty stones, so the looter
// took another in its place; and the looter went on opening corpses over the drain.
private static void OneTapItemAtATime()
{
using var rig = new Rig(tapping: true, new (uint, int?)[] { (StoneA, null), (StoneB, null), (StoneC, null) }, maceMana: 5000);
Check.Eq(rig.M.FreeEmptyStoneSlots(), 1, "three empty stones: one item may be looted to tap");
Check.False(rig.M.HoldsLootForDrain(), "nothing to drain: the looter goes on");
rig.AddRing();
rig.M.MarkLootedForTap(unchecked((int)Ring), arrived: false);
Check.Eq(rig.M.FreeEmptyStoneSlots(), 0, "the pickup is out: no second item");
rig.M.MarkLootedForTap(unchecked((int)Ring), arrived: true);
rig.Run(600);
Check.True(rig.M.HoldsLootForDrain(), "the ring is in the pack with a stone ready: the looter waits");
rig.Run(1000);
Check.Eq(rig.OnRing.Count, 1, "the ring is drained");
Check.True(rig.M.HoldsLootForDrain(), "the drain is out: the looter still waits");
Check.Eq(rig.M.FreeEmptyStoneSlots(), 0, "still no second item");
rig.Chat("The Mana Stone drains 3,600 points of mana from the Ring.\nThe Ring is destroyed.");
rig.Destroy(Ring);
rig.Run(200);
Check.False(rig.M.HoldsLootForDrain(), "drained: the looter goes on");
Check.Eq(rig.M.FreeEmptyStoneSlots(), 1, "the next item may be looted");
}
private static void NoDrainBeforeArrival()
{
using var rig = new Rig(tapping: true, new (uint, int?)[] { (StoneA, null) }, ringToDrain: true, maceMana: 5000, ringArrived: false);
rig.Run(2000);
Check.Eq(rig.OnRing.Count, 0, "the pickup is only sent: no drain yet");
Check.False(rig.M.HoldsLootForDrain(), "the pickup's answer is what the looter waits for, not the drain");
rig.M.MarkLootedForTap(unchecked((int)Ring), arrived: true);
rig.Run(1000);
Check.Eq(rig.OnRing.Count, 1, "confirmed in the pack: drained");
}
private static void FailedDrainKeepsPlace()
{
using var rig = new Rig(tapping: true, new (uint, int?)[] { (StoneA, null), (StoneB, null), (StoneC, null) }, ringToDrain: true, maceMana: 5000);
rig.Run(1000);
Check.Eq(rig.OnRing.Count, 1, "first try");
rig.Run(9000); // no answer: the drain times out
Check.Eq(rig.M.FreeEmptyStoneSlots(), 0, "the ring keeps its place: nothing else is looted to tap");
Check.False(rig.M.HoldsLootForDrain(), "waiting to retry does not hold the looter");
rig.Run(21_000);
Check.Eq(rig.OnRing.Count, 2, "second try");
Check.True(rig.OnRing[1] != rig.OnRing[0], "with another stone");
rig.Run(30_000);
Check.Eq(rig.OnRing.Count, 3, "third try");
rig.Run(10_000);
Check.Eq(rig.M.FreeEmptyStoneSlots(), 1, "given up after three: the next item may be looted");
rig.Run(60_000);
Check.Eq(rig.OnRing.Count, 3, "a given-up item is never drained again");
Check.True(FakeHost.Chat.Any(c => c.Contains("would not drain")), "the player is told");
}
private static void KnownChargedRefills()
{
using var rig = new Rig(tapping: true, new (uint, int?)[] { (StoneA, null), (StoneB, null) }, ringToDrain: true);

View file

@ -31,6 +31,7 @@ internal static class RadarSnapshotTests
r.Add("radar kinds: undead (CreatureType 14) are monsters, not NPCs", UndeadIsMonster);
r.Add("radar kinds: a settled kind is kept, an unreadable bitfield is asked again", KindCaching);
r.Add("radar kinds: fellowship membership is read live", FellowLive);
r.Add("radar markers: objects over a landblock border show outdoors, not in a dungeon", AdjacentLandblocks);
}
// ── Marker kinds (2026-10-04) ─────────────────────────────────────────────
@ -261,6 +262,53 @@ internal static class RadarSnapshotTests
Check.Eq(s.Markers[0].Label, "Drudge Skulker", "and its label");
}
// ── Neighbouring landblocks (2026-10-15) ──────────────────────────────────
private static Dictionary<uint, (float X, float Y)> Positions(RynthRadarUi radar)
{
var at = new Dictionary<uint, (float X, float Y)>();
EngineSnapshot? s = EngineSnapshot.Parse(radar.BuildSnapshotJson(0));
Check.NotNull(s, "parsed");
if (s == null) return at;
foreach (var m in s.Markers) at[m.Id] = (m.X, m.Y);
return at;
}
/// <summary>
/// Outdoors, objects over a landblock border show at once, placed by their own landblock's origin
/// (they used to appear only after you crossed). In a dungeon only your own landblock counts.
/// </summary>
private static void AdjacentLandblocks()
{
var at = Setup();
uint lbx = (at.Cell >> 24) & 0xFF, lby = (at.Cell >> 16) & 0xFF;
uint same = 0x80001103, east = 0x80001101, north = 0x80001102;
Put(same, "Drudge Skulker", 0x10, at, 3f, 0x10);
Put(east, "Mosswart", 0x10, at, 3f, 0x10);
Put(north, "Olthoi", 0x10, at, 3f, 0x10);
FakeHost.Positions[east] = (at.Cell + 0x01000000u, 5f, 40f, 0f); // the landblock to the east
FakeHost.Positions[north] = (at.Cell + 0x00010000u, 60f, 7f, 0f); // and to the north
var host = FakeHost.Create(Player);
var radar = new RynthRadarUi(host, new LegacyUiSettings());
radar.SetWorldObjectCache(FakeHost.MakeCache(host, Player, new[] { same, east, north }));
var pos = Positions(radar);
Check.True(pos.ContainsKey(same), "an object in your own landblock shows");
Check.True(pos.TryGetValue(east, out var pe), "an object in the landblock to the east shows");
Check.True(pos.TryGetValue(north, out var pn), "an object in the landblock to the north shows");
Check.Near(pe.X, 5f + (lbx + 1) * 192f, 1e-3, "east object: x is local + the east landblock's origin");
Check.Near(pe.Y, 40f + lby * 192f, 1e-3, "east object: y is local + this landblock's origin");
Check.Near(pn.X, 60f + lbx * 192f, 1e-3, "north object: x");
Check.Near(pn.Y, 7f + (lby + 1) * 192f, 1e-3, "north object: y is local + the north landblock's origin");
// In a dungeon (an interior cell of your landblock) the neighbours' objects are other places: left out.
FakeHost.PlayerPose = ((at.Cell & 0xFFFF0000u) | 0x0105u, at.X, at.Y, 0f);
FakeHost.Positions[same] = ((at.Cell & 0xFFFF0000u) | 0x0105u, 4f, 6f, 0f);
var indoor = Positions(radar);
Check.True(indoor.ContainsKey(same), "in a dungeon, an object in your landblock shows");
Check.False(indoor.ContainsKey(east) || indoor.ContainsKey(north), "in a dungeon, other landblocks' objects stay out");
}
/// <summary>
/// RynthAi's real BuildSnapshotJson on the fake host: the player outdoors, two monsters of
/// the same name a couple of metres apart, and a portal, all in the player's landblock.

View file

@ -0,0 +1,114 @@
using DotRecast.Core.Numerics;
using DotRecast.Detour;
using DotRecast.Detour.Io;
namespace RynthNav.Baker;
// --buildings-check LLLL[,LLLL...] --tiles <dir>
// Can nav walk into buildings? For each building cell that has a doorway to the outside (an EnvCell portal to
// 0xFFFF), is there walkable mesh at the cell, and is it joined to the main outdoor ground around it?
internal static class BuildingCheck
{
private sealed record Entrance(uint Cell, float X, float Y, float Z);
private static List<Entrance> ReadEntrances(RynthCore2.Raycast.GeometryLoader geo, uint lb)
{
var list = new List<Entrance>();
float offX = ((lb >> 8) & 0xFF) * 192f, offY = (lb & 0xFF) * 192f;
foreach (uint cellId in geo.CellDat.GetLandblockCellIds(lb))
{
byte[]? data = geo.CellDat.GetFileData(cellId);
if (data == null || data.Length < 36) continue;
try
{
using var ms = new MemoryStream(data);
using var r = new BinaryReader(ms);
r.ReadUInt32(); uint flags = r.ReadUInt32(); r.ReadUInt32();
byte numSurf = r.ReadByte(), numPortals = r.ReadByte(); r.ReadUInt16();
if ((flags & 0x01) == 0) continue; // a dungeon cell
ms.Seek(numSurf * 2L, SeekOrigin.Current);
r.ReadUInt16(); r.ReadUInt16();
float x = r.ReadSingle(), y = r.ReadSingle(), z = r.ReadSingle();
r.ReadSingle(); r.ReadSingle(); r.ReadSingle(); r.ReadSingle();
bool outside = false;
for (int i = 0; i < numPortals; i++) { r.ReadUInt16(); r.ReadUInt16(); ushort other = r.ReadUInt16(); r.ReadUInt16(); if (other == 0xFFFF) outside = true; }
if (outside) list.Add(new Entrance(cellId, x + offX, y + offY, z));
}
catch { }
}
return list;
}
/// <summary>--buildings-list: every landblock with a building that has a doorway to the outside (one hex landblock per line to stdout).</summary>
public static int List(RynthCore2.Raycast.GeometryLoader geo, Action<string> log)
{
int lbs = 0, entrances = 0;
for (uint lb = 0; lb <= 0xFFFF; lb++)
{
int n = ReadEntrances(geo, lb).Count;
if (n == 0) continue;
lbs++; entrances += n;
Console.WriteLine($"{lb:X4}");
}
log($"{lbs} landblocks have a building with an outside doorway ({entrances} entrance cells)");
return 0;
}
public static int Run(RynthCore2.Raycast.GeometryLoader geo, string spec, string tilesDir, Action<string> log)
{
int total = 0, noMesh = 0, isolated = 0, joined = 0;
foreach (uint lb in spec.Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries).Select(s => Convert.ToUInt32(s, 16)))
{
// The landblock and its neighbours, as the plugin loads them.
var nav = new DtNavMesh();
var p = new DtNavMeshParams { orig = new RcVec3f(0, 0, 0), tileWidth = 192f, tileHeight = 192f, maxTiles = 64, maxPolys = 1 << 16 };
nav.Init(ref p, 6);
for (int dx = -1; dx <= 1; dx++)
for (int dy = -1; dy <= 1; dy++)
{
uint t = (uint)((((int)(lb >> 8) + dx) << 8) | ((int)(lb & 0xFF) + dy));
string path = Path.Combine(tilesDir, $"nav_{t:X4}.tile");
if (!File.Exists(path)) continue;
using var fr = File.OpenRead(path); using var br = new BinaryReader(fr);
nav.AddTile(new DtMeshDataReader().Read(br, 6), 0, 0, out _);
}
var piece = new Dictionary<long, int>(); var size = new List<int>();
for (int ti = 0; ti < nav.GetMaxTiles(); ti++)
{
DtMeshTile? tile = nav.GetTile(ti);
if (tile?.data?.header == null) continue;
long baseRef = nav.GetPolyRefBase(tile);
for (int pi = 0; pi < tile.data.header.polyCount; pi++)
{
long start = baseRef | (long)pi;
if (piece.ContainsKey(start)) continue;
int id = size.Count, n = 0; size.Add(0);
var stack = new Stack<long>(); stack.Push(start); piece[start] = id;
while (stack.Count > 0)
{
long rf = stack.Pop(); n++;
if (nav.GetTileAndPolyByRef(rf, out DtMeshTile t2, out DtPoly pl).Failed()) continue;
for (int k = pl.firstLink; k != DtDetour.DT_NULL_LINK; k = t2.links[k].next)
{ long nb = t2.links[k].refs; if (nb != 0 && !piece.ContainsKey(nb)) { piece[nb] = id; stack.Push(nb); } }
}
size[id] = n;
}
}
if (size.Count == 0) { log($" 0x{lb:X4}: no tiles in {tilesDir}"); continue; }
int main = size.IndexOf(size.Max());
var q = new DtNavMeshQuery(nav); var filter = new DtQueryDefaultFilter();
int tn = 0, tj = 0, ti2 = 0, tt = 0;
foreach (Entrance e in ReadEntrances(geo, lb))
{
tt++;
q.FindNearestPoly(new RcVec3f(e.X, e.Z, e.Y), new RcVec3f(2.5f, 3f, 2.5f), filter, out long rf, out _, out _);
if (rf == 0 || !piece.TryGetValue(rf, out int pc)) { tn++; continue; }
if (pc == main) tj++; else ti2++;
}
total += tt; noMesh += tn; isolated += ti2; joined += tj;
log($" 0x{lb:X4}: {tt} building entrance cells: {tj} joined to the main ground, {ti2} on an isolated piece, {tn} with no mesh at the cell");
}
log($"entrance cells: {total}; joined {joined}, isolated {isolated}, no mesh {noMesh}");
return 0;
}
}

View file

@ -332,10 +332,40 @@ internal sealed class CollisionGeometry
/// <summary>
/// The cells of the landblock's buildings (EnvCells flagged SeenOutside): their walls and floors
/// (CellStruct physics polygons) and the static objects inside them. Dungeon cells are left out.
/// (CellStruct physics polygons) and the static objects inside them. Dungeon cells are left out
/// (<see cref="AppendDungeonCells"/> reads those).
/// Stab frames in an EnvCell are landblock positions already (ACE uses them as they are).
/// </summary>
public void AppendBuildingCells(uint lb, List<Tri> outTris, Func<Placement, bool>? objFilter = null)
=> AppendCells(lb, outTris, dungeon: false, objFilter);
/// <summary>
/// The cells of a dungeon landblock (EnvCells not flagged SeenOutside): the other half of
/// <see cref="AppendBuildingCells"/>. Returns how many cells were read.
/// </summary>
public int AppendDungeonCells(uint lb, List<Tri> outTris, Func<Placement, bool>? objFilter = null)
{
int before = CellsRead;
AppendCells(lb, outTris, dungeon: true, objFilter);
return CellsRead - before;
}
/// <summary>How many EnvCells the landblock has that are dungeon cells (0 for a plain outdoor landblock).</summary>
public int DungeonCellCount(uint lb)
{
byte[]? info = _cell.GetFileData((lb << 16) | 0xFFFE);
if (info == null || info.Length < 8) return 0;
uint numCells = BitConverter.ToUInt32(info, 4);
int n = 0;
for (uint c = 0; c < numCells && c < 0xFE00; c++)
{
byte[]? data = _cell.GetFileData((lb << 16) | (0x0100 + c));
if (data != null && data.Length >= 20 && (BitConverter.ToUInt32(data, 4) & 0x01) == 0) n++;
}
return n;
}
private void AppendCells(uint lb, List<Tri> outTris, bool dungeon, Func<Placement, bool>? objFilter)
{
byte[]? info = _cell.GetFileData((lb << 16) | 0xFFFE);
if (info == null || info.Length < 8) return;
@ -351,7 +381,7 @@ internal sealed class CollisionGeometry
using var r = new BinaryReader(ms);
r.ReadUInt32();
uint flags = r.ReadUInt32();
if ((flags & 0x01) == 0) continue; // not SeenOutside: a dungeon cell
if (((flags & 0x01) == 0) != dungeon) continue; // SeenOutside = a building cell, else a dungeon cell
r.ReadUInt32();
byte numSurf = r.ReadByte(), numPortals = r.ReadByte();
ushort numStabs = r.ReadUInt16();
@ -384,7 +414,10 @@ internal sealed class CollisionGeometry
CellObjects++;
int first = outTris.Count;
AppendModel(id, f, 1f, offX, offY, outTris);
RaiseIfLow(outTris, first, null); // on a floor: its base is its own lowest point
// On a floor, at its origin: the base is where the origin stands, not the object's own lowest point (a
// panel modelled around its origin goes 1 m under the floor; measured from there it is 2 m tall and the
// part above the floor, 1 m, read as a step the mesh can climb: the Town Network's wooden panels).
RaiseIfLow(outTris, first, f.OriginZ);
}
}
}
@ -449,7 +482,8 @@ internal sealed class CollisionGeometry
{
int first = outTris.Count;
AppendModel(p.Model, p.Frame, 1f, offX, offY, outTris);
if (p.Kind == "obj") RaiseIfLow(outTris, first, groundLocal?.Invoke(p.Frame.OriginX, p.Frame.OriginY));
// Outdoors the base is the ground under the object; in a dungeon (no terrain) it is where the object's origin stands.
if (p.Kind == "obj") RaiseIfLow(outTris, first, groundLocal != null ? groundLocal(p.Frame.OriginX, p.Frame.OriginY) : p.Frame.OriginZ);
}
}

View file

@ -0,0 +1,310 @@
using RynthCore2.TerrainData;
using System.Diagnostics;
using DotRecast.Core.Numerics;
using DotRecast.Detour;
using DotRecast.Recast.Geom;
using DotRecast.Recast.Toolset.Builder;
using RynthNav.Routing;
using V3 = System.Numerics.Vector3;
namespace RynthNav.Baker;
// Dungeons: the EnvCells that are not buildings (CollisionGeometry.AppendDungeonCells), baked into
// dun_LLLL.tile (DungeonTileFile: every Detour tile of the dungeon in one file, on a frame shifted so it
// is positive). A dungeon landblock keeps its surface tile (nav_LLLL.tile, the terrain nobody can use
// from inside), so the dungeon's file has its own name and the plugin keeps it in a mesh of its own.
// --dungeons-survey [--limit n] read every dungeon landblock and print its size and bounds (writes nothing)
// --dungeons all|LLLL,LLLL --out <dir> bake them
internal static class DungeonBake
{
private const float Lb = 192f;
/// <summary>The cell dat's landblocks that have dungeon cells, ascending.</summary>
public static List<uint> Find(CollisionGeometry cg, Action<string>? log = null)
{
var list = new List<uint>();
for (uint lb = 0; lb <= 0xFFFF; lb++)
if (cg.DungeonCellCount(lb) > 0) list.Add(lb);
log?.Invoke($"{list.Count} landblocks have dungeon cells");
return list;
}
/// <summary>A dungeon landblock's collision triangles (world metres, AC frame: x east, y north, z up).</summary>
public static List<CollisionGeometry.Tri> Gather(CollisionGeometry cg, uint lb, out int cells)
{
var tris = new List<CollisionGeometry.Tri>();
CollisionGeometry.Climb = NavBake.AgentMaxClimb;
cells = 0;
try { cells = cg.AppendDungeonCells(lb, tris); } catch { }
try { cg.AppendStatics(lb, tris); } catch { } // objects the landblock places (no terrain to stand on: lowest point is the base)
return tris;
}
private static bool Fin(float a, float b, float c) => float.IsFinite(a) && float.IsFinite(b) && float.IsFinite(c);
// ── Survey ───────────────────────────────────────────────────────────────
public static int Survey(CollisionGeometry cg, int limit, Action<string> log)
{
var sw = Stopwatch.StartNew();
List<uint> all = Find(cg, log);
int n = 0, outside = 0, empty = 0; long totalTris = 0;
var rows = new List<(uint lb, int cells, int tris, float x0, float x1, float y0, float y1, float z0, float z1, bool outs)>();
foreach (uint lb in all)
{
if (n++ >= limit) break;
var tris = Gather(cg, lb, out int cells);
if (tris.Count == 0) { empty++; continue; }
float x0 = float.MaxValue, x1 = float.MinValue, y0 = float.MaxValue, y1 = float.MinValue, z0 = float.MaxValue, z1 = float.MinValue;
float offX = ((lb >> 8) & 0xFF) * Lb, offY = (lb & 0xFF) * Lb;
foreach (var t in tris)
foreach (V3 v in new[] { t.A, t.B, t.C })
{
if (!Fin(v.X, v.Y, v.Z)) continue;
x0 = Math.Min(x0, v.X - offX); x1 = Math.Max(x1, v.X - offX);
y0 = Math.Min(y0, v.Y - offY); y1 = Math.Max(y1, v.Y - offY);
z0 = Math.Min(z0, v.Z); z1 = Math.Max(z1, v.Z);
}
bool outs = x0 < -0.01f || y0 < -0.01f || x1 > Lb + 0.01f || y1 > Lb + 0.01f;
if (outs) outside++;
totalTris += tris.Count;
rows.Add((lb, cells, tris.Count, x0, x1, y0, y1, z0, z1, outs));
}
foreach (var r in rows.OrderByDescending(r => r.tris).Take(10))
log($" 0x{r.lb:X4}: {r.cells} cells, {r.tris} tris, x {r.x0:F0}..{r.x1:F0} y {r.y0:F0}..{r.y1:F0} z {r.z0:F0}..{r.z1:F0}{(r.outs ? " OUTSIDE THE LANDBLOCK" : "")}");
log($"surveyed {rows.Count} dungeons ({empty} without geometry): {totalTris} triangles, avg {(rows.Count == 0 ? 0 : totalTris / rows.Count)}; " +
$"{outside} reach outside their landblock; cells read {cg.CellsRead}, failed {cg.CellsFailed}, objects {cg.CellObjects}; {sw.Elapsed.TotalSeconds:F1} s");
return 0;
}
// ── Models: what the bake does with each object of a landblock ──────────────
/// <summary>--dungeon-models LLLL: every model placed in the landblock's dungeon cells and info, how many collision triangles each gives.</summary>
public static int Models(CollisionGeometry cg, uint lb, Action<string> log)
{
var count = new Dictionary<uint, int>();
var cellTris = new List<CollisionGeometry.Tri>();
cg.AppendDungeonCells(lb, cellTris, pl => { count[pl.Model] = count.GetValueOrDefault(pl.Model) + 1; return true; });
foreach (var pl in cg.ReadLandBlockInfo(lb)) count[pl.Model] = count.GetValueOrDefault(pl.Model) + 1;
int zero = 0, zeroPlacements = 0;
foreach (var kv in count.OrderByDescending(k => k.Value))
{
var tris = new List<CollisionGeometry.Tri>();
cg.AppendModel(kv.Key, new Frame(), 1f, 0, 0, tris);
if (tris.Count > 0) continue;
zero++; zeroPlacements += kv.Value;
string detail;
if ((kv.Key >> 24) == 0x01)
{
var g = cg.GfxObj(kv.Key);
detail = g == null ? "GfxObj unreadable" : $"GfxObj flags 0x{g.Flags:X} physics polys {g.Phys.Count}, drawing polys {g.Draw.Count}";
}
else
{
var st = cg.SetupModel(kv.Key);
if (st == null) detail = "Setup unreadable";
else
{
var parts = st.Parts.Select(pid => cg.GfxObj(pid)).ToList();
detail = $"Setup flags 0x{st.Flags:X}, {st.Parts.Length} parts (physics BSP {parts.Count(g => g != null && (g.Flags & 1) != 0 && g.Phys.Count > 0)}, drawing only {parts.Count(g => g != null && g.Draw.Count > 0 && g.Phys.Count == 0)}), cylinders {st.Cyl.Count}, spheres {st.Sph.Count}, height {st.Height:F2} radius {st.Radius:F2}";
}
}
// Size of what is drawn (all parts, ignoring part frames): a panel is tall and thin.
var meshes = (kv.Key >> 24) == 0x01 ? new[] { cg.GfxObj(kv.Key) } : (cg.SetupModel(kv.Key)?.Parts.Select(pid => cg.GfxObj(pid)).ToArray() ?? Array.Empty<CollisionGeometry.Mesh?>());
V3 lo = new(float.MaxValue), hi = new(float.MinValue);
foreach (var m in meshes)
if (m != null) foreach (var poly in m.Draw) foreach (int vid in poly) if (m.Verts.TryGetValue(vid, out V3 v)) { lo = V3.Min(lo, v); hi = V3.Max(hi, v); }
string size = hi.X < lo.X ? "" : $" size {hi.X - lo.X:F1} x {hi.Y - lo.Y:F1} x {hi.Z - lo.Z:F1} m";
log($" {kv.Key:X8} x{kv.Value}: no collision - {detail};{size}");
}
log($"0x{lb:X4}: {count.Count} distinct models, {count.Values.Sum()} placements; {zero} models ({zeroPlacements} placements) give no collision triangles");
return 0;
}
/// <summary>--dungeons near --lb LLLL --at x,y[,r]: the collision triangles gathered within r metres (default 1) of a landblock-local point.</summary>
public static int Near(CollisionGeometry cg, uint lb, string at, Action<string> log)
{
var a = at.Split(',');
float x = float.Parse(a[0], System.Globalization.CultureInfo.InvariantCulture), y = float.Parse(a[1], System.Globalization.CultureInfo.InvariantCulture);
float r = a.Length > 2 ? float.Parse(a[2], System.Globalization.CultureInfo.InvariantCulture) : 1f;
float offX = ((lb >> 8) & 0xFF) * Lb, offY = (lb & 0xFF) * Lb;
var tris = Gather(cg, lb, out int cells);
int n = 0;
foreach (var t in tris)
{
V3 c = (t.A + t.B + t.C) / 3f;
if (Math.Abs(c.X - offX - x) > r || Math.Abs(c.Y - offY - y) > r) continue;
n++;
if (n <= 40)
{
V3 lo = V3.Min(t.A, V3.Min(t.B, t.C)), hi = V3.Max(t.A, V3.Max(t.B, t.C));
log($" tri: x {lo.X - offX:F2}..{hi.X - offX:F2} y {lo.Y - offY:F2}..{hi.Y - offY:F2} z {lo.Z:F2}..{hi.Z:F2}");
}
}
log($"{n} of {tris.Count} triangles within {r} m of ({x}, {y}) in 0x{lb:X4}");
return 0;
}
/// <summary>--dungeons model --model HEX: one model's collision as the bake sees it (triangles, size, shape).</summary>
public static int ModelInfo(CollisionGeometry cg, uint model, Action<string> log)
{
var tris = new List<CollisionGeometry.Tri>();
cg.AppendModel(model, new Frame(), 1f, 0, 0, tris);
V3 lo = new(float.MaxValue), hi = new(float.MinValue);
foreach (var t in tris) foreach (V3 v in new[] { t.A, t.B, t.C }) { lo = V3.Min(lo, v); hi = V3.Max(hi, v); }
string kind;
if ((model >> 24) == 0x01) kind = "GfxObj";
else
{
var st = cg.SetupModel(model);
if (st == null) { log($"{model:X8}: Setup unreadable"); return 1; }
var parts = st.Parts.Select(pid => cg.GfxObj(pid)).ToList();
kind = $"Setup flags 0x{st.Flags:X}, {st.Parts.Length} parts; physics BSP {parts.Count(g => g != null && (g.Flags & 1) != 0 && g.Phys.Count > 0)}, cylinders {st.Cyl.Count}, spheres {st.Sph.Count}, height {st.Height:F2} radius {st.Radius:F2}, step up {st.StepUp:F2}";
foreach (var c in st.Cyl) log($" cylinder: bottom ({c.BottomCenter.X:F2}, {c.BottomCenter.Y:F2}, {c.BottomCenter.Z:F2}) radius {c.Radius:F2} height {c.Height:F2}");
}
log($"{model:X8}: {kind}");
log(tris.Count == 0 ? " no collision triangles" : $" {tris.Count} collision triangles, x {lo.X:F2}..{hi.X:F2} y {lo.Y:F2}..{hi.Y:F2} z {lo.Z:F2}..{hi.Z:F2} (size {hi.X - lo.X:F2} x {hi.Y - lo.Y:F2} x {hi.Z - lo.Z:F2} m)");
return 0;
}
// ── Bake ─────────────────────────────────────────────────────────────────
public sealed class Result
{
public int Cells, Tris, Tiles, Polys, ShiftX, ShiftY, Pieces;
public double Share; // polygons in the largest connected piece / all polygons
public List<int> PieceSizes = new();
public bool Written;
public string Note = "";
}
private static int FloorDiv192(double v) => (int)Math.Floor(v / Lb);
/// <summary>One dungeon landblock into <paramref name="outDir"/>\dun_LLLL.tile (see DungeonTileFile for the frame).</summary>
public static Result BakeOne(CollisionGeometry cg, uint lb, string outDir, float agentRadius)
{
var res = new Result();
var tris = Gather(cg, lb, out res.Cells);
float offX = ((lb >> 8) & 0xFF) * Lb, offY = (lb & 0xFF) * Lb;
// Landblock-local bounds of what is usable.
float minX = float.MaxValue, maxX = float.MinValue, minY = float.MaxValue, maxY = float.MinValue, minZ = float.MaxValue, maxZ = float.MinValue;
var good = new List<CollisionGeometry.Tri>(tris.Count);
foreach (var t in tris)
{
if (!Fin(t.A.X, t.A.Y, t.A.Z) || !Fin(t.B.X, t.B.Y, t.B.Z) || !Fin(t.C.X, t.C.Y, t.C.Z)) continue;
if (V3.Cross(t.B - t.A, t.C - t.A).LengthSquared() < 1e-10f) continue; // degenerate
good.Add(t);
foreach (V3 v in new[] { t.A, t.B, t.C })
{
minX = Math.Min(minX, v.X - offX); maxX = Math.Max(maxX, v.X - offX);
minY = Math.Min(minY, v.Y - offY); maxY = Math.Max(maxY, v.Y - offY);
minZ = Math.Min(minZ, v.Z); maxZ = Math.Max(maxZ, v.Z);
}
}
res.Tris = good.Count;
if (good.Count == 0) { res.Note = "no geometry"; return res; }
// Shift so every mesh coordinate is positive and the tile grid starts on a multiple of 192.
int sx = minX < 0 ? (int)(Lb * Math.Ceiling(-minX / Lb)) : 0, sy = minY < 0 ? (int)(Lb * Math.Ceiling(-minY / Lb)) : 0;
res.ShiftX = sx; res.ShiftY = sy;
var verts = new List<float>(good.Count * 9); var faces = new List<int>(good.Count * 3);
int Add(V3 v) { verts.Add(v.X - offX + sx); verts.Add(v.Z); verts.Add(v.Y - offY + sy); return verts.Count / 3 - 1; } // AC (x, y, z) -> Recast (EW, up, NS)
foreach (var t in good)
{
int a = Add(t.A), b = Add(t.B), c = Add(t.C);
faces.Add(a); faces.Add(c); faces.Add(b); // reversed winding (+Y up), as the terrain bake
}
// Two unused vertices put the bounds (so the tile grid and the height origin) on 192 m lines.
float boxMinX = FloorDiv192(minX + sx) * Lb, boxMinZ = FloorDiv192(minY + sy) * Lb;
float boxMaxX = (FloorDiv192(maxX + sx) + 1) * Lb, boxMaxZ = (FloorDiv192(maxY + sy) + 1) * Lb;
verts.Add(boxMinX); verts.Add(minZ); verts.Add(boxMinZ);
verts.Add(boxMaxX); verts.Add(maxZ); verts.Add(boxMaxZ);
var geom = new RcSampleInputGeomProvider(verts.ToArray(), faces.ToArray());
geom.CalculateNormals();
var settings = NavBake.Settings(agentRadius, tiled: true, cellSize: NavBake.TiledCellSizeValue);
NavMeshBuildResult nm = new TileNavMeshBuilder().Build(geom, settings);
if (!nm.Success || nm.NavMesh == null) { res.Note = "Recast failed"; return res; }
RcVec3f bmin = geom.GetMeshBoundsMin();
if (Math.Abs(bmin.X - boxMinX) > 0.01f || Math.Abs(bmin.Z - boxMinZ) > 0.01f) { res.Note = $"grid offset ({bmin.X - boxMinX:F2}, {bmin.Z - boxMinZ:F2})"; return res; }
int baseTx = (int)Math.Round(bmin.X / Lb), baseTy = (int)Math.Round(bmin.Z / Lb);
DtNavMesh nav = nm.NavMesh;
var tiles = new List<DtMeshData>();
for (int i = 0; i < nav.GetMaxTiles(); i++)
{
DtMeshTile? tile = nav.GetTile(i);
if (tile?.data?.header == null || tile.data.header.polyCount == 0) continue;
DtMeshData md = tile.data;
md.header.x = baseTx + md.header.x; // absolute index on the shifted frame
md.header.y = baseTy + md.header.y;
tiles.Add(md);
res.Polys += md.header.polyCount;
}
if (tiles.Count == 0) { res.Note = "no polygons"; return res; }
res.PieceSizes = Components(nav).OrderByDescending(x => x).ToList();
res.Pieces = res.PieceSizes.Count; res.Share = res.PieceSizes.Count == 0 ? 0 : (double)res.PieceSizes[0] / res.PieceSizes.Sum();
OutputGuard.Check(outDir);
DungeonTileFile.Write(Path.Combine(outDir, DungeonTileFile.FileName(lb)), sx, sy, tiles);
res.Tiles = tiles.Count; res.Written = true;
return res;
}
/// <summary>Sizes (polygon counts) of the connected pieces of a navmesh, joined by Detour's polygon links.</summary>
public static List<int> Components(DtNavMesh nav)
{
var seen = new HashSet<long>();
var sizes = new List<int>();
for (int ti = 0; ti < nav.GetMaxTiles(); ti++)
{
DtMeshTile? tile = nav.GetTile(ti);
if (tile?.data?.header == null) continue;
long baseRef = nav.GetPolyRefBase(tile);
for (int pi = 0; pi < tile.data.header.polyCount; pi++)
{
long start = baseRef | (long)pi;
if (!seen.Add(start)) continue;
int size = 0;
var stack = new Stack<long>(); stack.Push(start);
while (stack.Count > 0)
{
long r = stack.Pop(); size++;
if (nav.GetTileAndPolyByRef(r, out DtMeshTile t, out DtPoly p).Failed()) continue;
for (int k = p.firstLink; k != DtDetour.DT_NULL_LINK; k = t.links[k].next)
{
long n = t.links[k].refs;
if (n != 0 && seen.Add(n)) stack.Push(n);
}
}
sizes.Add(size);
}
}
return sizes;
}
public static int Run(CollisionGeometry cg, string spec, int limit, string outDir, float agentRadius, Action<string> log)
{
List<uint> lbs = spec.Equals("all", StringComparison.OrdinalIgnoreCase)
? Find(cg, log)
: spec.Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries).Select(s => Convert.ToUInt32(s, 16)).ToList();
var sw = Stopwatch.StartNew();
int ok = 0, none = 0, done = 0, tilesN = 0, lowShare = 0; long polys = 0, bytes = 0; double shareSum = 0;
foreach (uint lb in lbs)
{
if (done++ >= limit) break;
Result r;
try { r = BakeOne(cg, lb, outDir, agentRadius); }
catch (InvalidOperationException) { throw; }
catch (Exception ex) { r = new Result { Note = ex.GetType().Name + ": " + ex.Message }; }
if (r.Written) { ok++; polys += r.Polys; tilesN += r.Tiles; bytes += new FileInfo(Path.Combine(outDir, DungeonTileFile.FileName(lb))).Length; }
else { none++; log($" 0x{lb:X4}: not written ({r.Note})"); }
if (lbs.Count <= 20) log($" 0x{lb:X4}: {r.Cells} cells, {r.Tris} tris -> {r.Tiles} tile(s), {r.Polys} polys, shift ({r.ShiftX}, {r.ShiftY}); biggest piece {r.Share:P0} of {r.Pieces} pieces (largest {string.Join(",", r.PieceSizes.Take(6))}){(r.Note.Length > 0 ? ", " + r.Note : "")}");
if (r.Written) { shareSum += r.Share; if (r.Share < 0.5) lowShare++; }
if (done % 50 == 0) log($" {done}/{lbs.Count} ... ({ok} dungeons, {sw.Elapsed.TotalSeconds:F0} s)");
}
log($"dungeon bake DONE: {ok} dungeons ({tilesN} tiles, {polys} polygons, {bytes / 1024} KB), {none} not written; mean biggest-piece share {(ok == 0 ? 0 : shareSum / ok):P0}, {lowShare} under 50%; {sw.Elapsed.TotalSeconds:F1} s.");
return 0;
}
}

View file

@ -0,0 +1,123 @@
using DotRecast.Core.Numerics;
using DotRecast.Detour;
using RynthNav.Routing;
namespace RynthNav.Baker;
// --dungeons-check LLLL[,LLLL...] --tiles <dir>
// Compares a baked dungeon with the game's own doorway graph (the EnvCell portal records, which is what
// RynthAi's DungeonPathfinder walks): every cell is put on the mesh at its position, and every doorway
// between two cells that isn't a drop should join two places of the same connected piece. Doorways whose
// two ends land in different pieces are the mesh's gaps.
internal static class DungeonCheck
{
private sealed record Cell(uint Id, float X, float Y, float Z, List<uint> Doors);
private static List<Cell> ReadCells(RynthCore2.Raycast.GeometryLoader geo, uint lb)
{
var cells = new List<Cell>();
foreach (uint cellId in geo.CellDat.GetLandblockCellIds(lb))
{
byte[]? data = geo.CellDat.GetFileData(cellId);
if (data == null || data.Length < 36) continue;
try
{
using var ms = new MemoryStream(data);
using var r = new BinaryReader(ms);
r.ReadUInt32(); uint flags = r.ReadUInt32(); r.ReadUInt32();
byte numSurf = r.ReadByte(), numPortals = r.ReadByte(); r.ReadUInt16();
if ((flags & 0x01) != 0) continue; // a building cell
ms.Seek(numSurf * 2L, SeekOrigin.Current);
r.ReadUInt16(); r.ReadUInt16();
float x = r.ReadSingle(), y = r.ReadSingle(), z = r.ReadSingle();
r.ReadSingle(); r.ReadSingle(); r.ReadSingle(); r.ReadSingle();
var doors = new List<uint>();
for (int i = 0; i < numPortals; i++)
{
r.ReadUInt16(); r.ReadUInt16(); ushort other = r.ReadUInt16(); r.ReadUInt16();
if (other != 0xFFFF && other >= 0x100) doors.Add(((uint)lb << 16) | other);
}
cells.Add(new Cell(cellId, x, y, z, doors));
}
catch { }
}
return cells;
}
// Same rule as RynthAi's IsDropEdge: a step of 0.5 m or more at over 45 degrees is a drop, not a walk.
private static bool IsDrop(Cell a, Cell b)
{
double dz = Math.Abs(b.Z - a.Z);
if (dz < 0.5) return false;
double dh = Math.Sqrt((b.X - a.X) * (b.X - a.X) + (b.Y - a.Y) * (b.Y - a.Y));
return dh < 1.0 || Math.Atan2(dz, dh) * 180.0 / Math.PI > 45.0;
}
public static int Run(RynthCore2.Raycast.GeometryLoader geo, string spec, string tilesDir, Action<string> log)
{
long cellsAll = 0, cellsOn = 0, edgesAll = 0, edgesBoth = 0, edgesSame = 0;
int dungeons = 0;
var worst = new List<(uint lb, double bad, long edges)>();
foreach (uint lb in spec.Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries).Select(s => Convert.ToUInt32(s, 16)))
{
var f = DungeonTileFile.Read(Path.Combine(tilesDir, DungeonTileFile.FileName(lb)));
if (f == null) { log($" 0x{lb:X4}: no readable dungeon tile in {tilesDir}"); continue; }
DtNavMesh nav = f.BuildNavMesh();
var q = new DtNavMeshQuery(nav);
var filter = new DtQueryDefaultFilter();
// Piece of every polygon.
var piece = new Dictionary<long, int>(); int pieces = 0;
for (int ti = 0; ti < nav.GetMaxTiles(); ti++)
{
DtMeshTile? tile = nav.GetTile(ti);
if (tile?.data?.header == null) continue;
long baseRef = nav.GetPolyRefBase(tile);
for (int pi = 0; pi < tile.data.header.polyCount; pi++)
{
long start = baseRef | (long)pi;
if (piece.ContainsKey(start)) continue;
int id = pieces++;
var stack = new Stack<long>(); stack.Push(start); piece[start] = id;
while (stack.Count > 0)
{
long rf = stack.Pop();
if (nav.GetTileAndPolyByRef(rf, out DtMeshTile t, out DtPoly p).Failed()) continue;
for (int k = p.firstLink; k != DtDetour.DT_NULL_LINK; k = t.links[k].next)
{
long n = t.links[k].refs;
if (n != 0 && !piece.ContainsKey(n)) { piece[n] = id; stack.Push(n); }
}
}
}
}
List<Cell> cells = ReadCells(geo, lb);
var at = new Dictionary<uint, int>(); // cell -> piece it stands on
foreach (Cell c in cells)
{
// The cell's origin is near its floor: look for walkable ground close by (within a cell's reach sideways, a floor's height up and down).
var centre = new RcVec3f(c.X + f.ShiftX, c.Z, c.Y + f.ShiftY);
q.FindNearestPoly(centre, new RcVec3f(3f, 2.5f, 3f), filter, out long rf, out _, out _);
if (rf != 0 && piece.TryGetValue(rf, out int pc)) at[c.Id] = pc;
}
var byId = cells.ToDictionary(c => c.Id);
long e = 0, both = 0, same = 0;
foreach (Cell a in cells)
foreach (uint nb in a.Doors)
{
if (nb <= a.Id || !byId.TryGetValue(nb, out Cell? b) || IsDrop(a, b)) continue; // each doorway once
e++;
if (at.TryGetValue(a.Id, out int pa) && at.TryGetValue(b.Id, out int pb)) { both++; if (pa == pb) same++; }
}
cellsAll += cells.Count; cellsOn += at.Count; edgesAll += e; edgesBoth += both; edgesSame += same; dungeons++;
double badShare = both == 0 ? 0 : 1.0 - (double)same / both;
worst.Add((lb, badShare, both));
if (spec.Count(ch => ch == ',') < 12)
log($" 0x{lb:X4}: {cells.Count} cells, {at.Count} found on the mesh; {e} doorways, {both} with both ends found, {same} joined ({(both == 0 ? 0 : 100.0 * same / both):F0}%); mesh pieces {pieces}");
}
log($"checked {dungeons} dungeons: cells on the mesh {cellsOn}/{cellsAll} ({(cellsAll == 0 ? 0 : 100.0 * cellsOn / cellsAll):F0}%); doorways joined {edgesSame}/{edgesBoth} ({(edgesBoth == 0 ? 0 : 100.0 * edgesSame / edgesBoth):F1}%) of {edgesAll}");
foreach (var w in worst.Where(w => w.edges >= 20).OrderByDescending(w => w.bad).Take(5)) log($" worst: 0x{w.lb:X4}: {w.bad:P0} of {w.edges} doorways broken");
return 0;
}
}

View file

@ -0,0 +1,172 @@
namespace RynthNav.Baker;
/// <summary>
/// DXT1 (BC1) texture compression: each 4x4 block of RGB pixels becomes 8 bytes (two RGB565 endpoints and
/// 16 two-bit indices), 6:1 against 24-bit RGB, and a D3D9 device holds the blocks as they are, so the
/// engine uploads them untouched. The endpoints are found along the block's principal colour axis (a few
/// power iterations on its covariance), then the pixels take the nearest of the four palette colours.
/// Used for the World Map's tiles (worldmap.rmap version 2); Decode is the reference for tests.
/// </summary>
internal static class Dxt1
{
public const int BlockBytes = 8;
/// <summary>Compresses a w x h RGB image (both multiples of 4) to w/4 * h/4 blocks, row-major, top row first.</summary>
public static byte[] Encode(byte[] rgb, int w, int h)
{
if (w % 4 != 0 || h % 4 != 0) throw new ArgumentException("size must be a multiple of 4");
var outp = new byte[(w / 4) * (h / 4) * BlockBytes];
Span<int> px = stackalloc int[48];
int o = 0;
for (int by = 0; by < h; by += 4)
for (int bx = 0; bx < w; bx += 4)
{
for (int y = 0; y < 4; y++)
for (int x = 0; x < 4; x++)
{
int s = ((by + y) * w + bx + x) * 3, d = (y * 4 + x) * 3;
px[d] = rgb[s]; px[d + 1] = rgb[s + 1]; px[d + 2] = rgb[s + 2];
}
EncodeBlock(px, outp.AsSpan(o, BlockBytes));
o += BlockBytes;
}
return outp;
}
private static ushort To565(float r, float g, float b)
{
int ri = Math.Clamp((int)MathF.Round(r * 31f / 255f), 0, 31), gi = Math.Clamp((int)MathF.Round(g * 63f / 255f), 0, 63), bi = Math.Clamp((int)MathF.Round(b * 31f / 255f), 0, 31);
return (ushort)((ri << 11) | (gi << 5) | bi);
}
private static void From565(ushort c, out int r, out int g, out int b)
{
int r5 = c >> 11, g6 = (c >> 5) & 63, b5 = c & 31;
r = (r5 << 3) | (r5 >> 2); g = (g6 << 2) | (g6 >> 4); b = (b5 << 3) | (b5 >> 2);
}
private static void EncodeBlock(ReadOnlySpan<int> px, Span<byte> block)
{
// Mean and covariance.
float mr = 0, mg = 0, mb = 0;
int minR = 255, minG = 255, minB = 255, maxR = 0, maxG = 0, maxB = 0;
for (int i = 0; i < 16; i++)
{
int r = px[i * 3], g = px[i * 3 + 1], b = px[i * 3 + 2];
mr += r; mg += g; mb += b;
if (r < minR) minR = r; if (g < minG) minG = g; if (b < minB) minB = b;
if (r > maxR) maxR = r; if (g > maxG) maxG = g; if (b > maxB) maxB = b;
}
mr /= 16; mg /= 16; mb /= 16;
if (maxR == minR && maxG == minG && maxB == minB)
{
ushort solid = To565(minR, minG, minB);
block[0] = (byte)solid; block[1] = (byte)(solid >> 8); block[2] = block[0]; block[3] = block[1];
block[4] = block[5] = block[6] = block[7] = 0;
return;
}
float crr = 0, crg = 0, crb = 0, cgg = 0, cgb = 0, cbb = 0;
for (int i = 0; i < 16; i++)
{
float r = px[i * 3] - mr, g = px[i * 3 + 1] - mg, b = px[i * 3 + 2] - mb;
crr += r * r; crg += r * g; crb += r * b; cgg += g * g; cgb += g * b; cbb += b * b;
}
// Dominant axis by power iteration, started along the box diagonal.
float ax = maxR - minR, ay = maxG - minG, az = maxB - minB;
for (int it = 0; it < 4; it++)
{
float nx = crr * ax + crg * ay + crb * az, ny = crg * ax + cgg * ay + cgb * az, nz = crb * ax + cgb * ay + cbb * az;
float len = MathF.Sqrt(nx * nx + ny * ny + nz * nz);
if (len < 1e-6f) break;
ax = nx / len; ay = ny / len; az = nz / len;
}
// Extent of the pixels along it: the endpoints.
float tMin = float.MaxValue, tMax = float.MinValue;
for (int i = 0; i < 16; i++)
{
float t = (px[i * 3] - mr) * ax + (px[i * 3 + 1] - mg) * ay + (px[i * 3 + 2] - mb) * az;
if (t < tMin) tMin = t; if (t > tMax) tMax = t;
}
ushort c0 = To565(mr + ax * tMax, mg + ay * tMax, mb + az * tMax);
ushort c1 = To565(mr + ax * tMin, mg + ay * tMin, mb + az * tMin);
if (c0 == c1)
{
block[0] = (byte)c0; block[1] = (byte)(c0 >> 8); block[2] = block[0]; block[3] = block[1];
block[4] = block[5] = block[6] = block[7] = 0;
return;
}
if (c0 < c1) (c0, c1) = (c1, c0); // c0 > c1: the four-colour mode
From565(c0, out int r0, out int g0, out int b0);
From565(c1, out int r1, out int g1, out int b1);
Span<int> pal = stackalloc int[12];
pal[0] = r0; pal[1] = g0; pal[2] = b0;
pal[3] = r1; pal[4] = g1; pal[5] = b1;
pal[6] = (2 * r0 + r1) / 3; pal[7] = (2 * g0 + g1) / 3; pal[8] = (2 * b0 + b1) / 3;
pal[9] = (r0 + 2 * r1) / 3; pal[10] = (g0 + 2 * g1) / 3; pal[11] = (b0 + 2 * b1) / 3;
block[0] = (byte)c0; block[1] = (byte)(c0 >> 8); block[2] = (byte)c1; block[3] = (byte)(c1 >> 8);
for (int row = 0; row < 4; row++)
{
int bits = 0;
for (int col = 0; col < 4; col++)
{
int i = row * 4 + col;
int r = px[i * 3], g = px[i * 3 + 1], b = px[i * 3 + 2];
int best = 0, bestD = int.MaxValue;
for (int k = 0; k < 4; k++)
{
int dr = r - pal[k * 3], dg = g - pal[k * 3 + 1], db = b - pal[k * 3 + 2];
int d = dr * dr + dg * dg + db * db;
if (d < bestD) { bestD = d; best = k; }
}
bits |= best << (col * 2);
}
block[4 + row] = (byte)bits;
}
}
/// <summary>Decompresses one block to 16 RGB pixels (row-major) - the reference a GPU follows. For tests.</summary>
public static void DecodeBlock(ReadOnlySpan<byte> block, Span<byte> rgb48)
{
ushort c0 = (ushort)(block[0] | (block[1] << 8)), c1 = (ushort)(block[2] | (block[3] << 8));
From565(c0, out int r0, out int g0, out int b0);
From565(c1, out int r1, out int g1, out int b1);
Span<int> pal = stackalloc int[12];
pal[0] = r0; pal[1] = g0; pal[2] = b0; pal[3] = r1; pal[4] = g1; pal[5] = b1;
if (c0 > c1)
{
pal[6] = (2 * r0 + r1) / 3; pal[7] = (2 * g0 + g1) / 3; pal[8] = (2 * b0 + b1) / 3;
pal[9] = (r0 + 2 * r1) / 3; pal[10] = (g0 + 2 * g1) / 3; pal[11] = (b0 + 2 * b1) / 3;
}
else
{
pal[6] = (r0 + r1) / 2; pal[7] = (g0 + g1) / 2; pal[8] = (b0 + b1) / 2;
pal[9] = 0; pal[10] = 0; pal[11] = 0;
}
for (int row = 0; row < 4; row++)
for (int col = 0; col < 4; col++)
{
int idx = (block[4 + row] >> (col * 2)) & 3, d = (row * 4 + col) * 3;
rgb48[d] = (byte)pal[idx * 3]; rgb48[d + 1] = (byte)pal[idx * 3 + 1]; rgb48[d + 2] = (byte)pal[idx * 3 + 2];
}
}
/// <summary>Decompresses a whole w x h image (for tests).</summary>
public static byte[] Decode(byte[] blocks, int w, int h)
{
var rgb = new byte[w * h * 3];
Span<byte> px = stackalloc byte[48];
int o = 0;
for (int by = 0; by < h; by += 4)
for (int bx = 0; bx < w; bx += 4)
{
DecodeBlock(blocks.AsSpan(o, BlockBytes), px);
o += BlockBytes;
for (int y = 0; y < 4; y++)
for (int x = 0; x < 4; x++)
Buffer.BlockCopy(px.Slice((y * 4 + x) * 3, 3).ToArray(), 0, rgb, ((by + y) * w + bx + x) * 3, 3);
}
return rgb;
}
}

View file

@ -22,8 +22,14 @@ internal static class NavBake
private const float CL = LandblockData.CellLength; // 24
public const int VertsPerPoly = 6;
// Tiled tiles align 1:1 to landblocks: tileSize(cells) * cellSize = 192.
private const float TiledCellSize = 0.5f;
private const int TiledTileSize = 384; // 384 * 0.5 = 192
/// <summary>
/// The tiled bake's cell size (--cell). Recast erodes the walkable ground by ceil(agentRadius / cell) whole
/// cells, so a 0.6 m radius at 0.5 m cells takes 1.0 m off each side and shuts every doorway under 2 m;
/// finer cells keep the erosion near the real radius. Tiles stay one landblock: tileSize = 192 / cell.
/// </summary>
internal static float TiledCellSizeValue = 0.5f;
private static float TiledCellSize => TiledCellSizeValue;
private static int TiledTileSize => (int)Math.Round(192f / TiledCellSizeValue);
/// <summary>--draw-geometry: bake from the drawing meshes like before (for comparisons only).</summary>
public static bool DrawMeshes;
@ -113,7 +119,7 @@ internal static class NavBake
/// </summary>
internal static float EdgeMaxError(float radius) => Math.Min(1.3f, radius + 0.15f);
private static RcNavMeshBuildSettings Settings(float radius, bool tiled, float cellSize)
internal static RcNavMeshBuildSettings Settings(float radius, bool tiled, float cellSize)
{
float slopeDeg = (float)(Math.Acos(TerrainSampler.FloorZ) * 180.0 / Math.PI);
return new RcNavMeshBuildSettings
@ -305,7 +311,7 @@ internal static class NavBake
// Written to a .tmp and moved into place, so a bake stopped half way never
// leaves a truncated tile behind (a resumed batch bake trusts tiles on disk).
private static void WriteTile(string path, DtMeshData md)
internal static void WriteTile(string path, DtMeshData md)
{
OutputGuard.Check(Path.GetDirectoryName(path)!);
string tmp = path + ".tmp";

View file

@ -0,0 +1,123 @@
using System.Numerics;
using RynthCore2.Raycast;
using Vector3 = System.Numerics.Vector3;
namespace RynthNav.Baker;
// The world seen from straight above: the game's own static objects (buildings with their roofs,
// walls, bridges, statues) and scenery (trees, rocks, bushes), textured, drawn over the terrain by a
// small CPU rasteriser with a depth buffer: --map --textured --objects.
// - Orthographic, looking down: a point's pixel is its world x, y; the higher one wins.
// - Each triangle is filled from its surface's texture (alpha-tested, so leaves cut out); a surface
// with no texture uses its flat colour; the translucent panes of doors and windows are skipped.
// - Lit from the north-west, high up: a flat roof is full bright, a wall in shade.
internal sealed class ObjectRaster
{
internal sealed record Tex(int W, int H, byte[]? Px, uint Solid, float Alpha);
/// <summary>Decoded object surfaces, shared by every raster and thread (the decoder itself is not thread-safe).</summary>
internal sealed class SurfaceStore
{
private readonly AcClientReborn.AcTextureDecoder _dec;
private readonly System.Collections.Concurrent.ConcurrentDictionary<uint, Tex?> _cache = new();
private readonly object _gate = new();
public SurfaceStore(AcClientReborn.AcTextureDecoder dec) { _dec = dec; }
public int Count => _cache.Count;
public Tex? Get(uint surface)
{
if (_cache.TryGetValue(surface, out Tex? t)) return t;
lock (_gate)
{
if (_cache.TryGetValue(surface, out t)) return t;
var d = _dec.GetSurface(surface);
t = d == null ? null : new Tex(d.Width, d.Height, d.Rgba, d.SolidColor, d.Alpha);
_cache[surface] = t;
return t;
}
}
}
private readonly byte[] _rgb;
private readonly float[] _depth;
private readonly int _w, _h, _ppc;
private readonly double _cx0, _cy0;
private readonly SurfaceStore _surfaces;
private static readonly Vector3 Light = Vector3.Normalize(new Vector3(-0.35f, 0.35f, 0.87f));
public long Triangles { get; private set; }
public ObjectRaster(byte[] rgb, int w, int h, int cx0, int cy0, int ppc, SurfaceStore surfaces)
{
_rgb = rgb; _w = w; _h = h; _cx0 = cx0; _cy0 = cy0; _ppc = ppc; _surfaces = surfaces;
_depth = new float[w * h];
Array.Fill(_depth, float.NegativeInfinity);
}
// World yards to pixels (x grows east; row 0 is the north edge).
private float Px(float worldX) => (float)((worldX / 24.0 - _cx0) * _ppc);
private float Py(float worldY) => (float)(_h - (worldY / 24.0 - _cy0) * _ppc);
public void Add(IEnumerable<GeometryLoader.TexTri> tris)
{
foreach (var t in tris)
{
Triangles++;
Tex? tex = _surfaces.Get(t.Surface);
if (tex != null && tex.Alpha < 0.9f) continue; // a door or window pane
float e1x = t.B.X - t.A.X, e1y = t.B.Y - t.A.Y, e1z = t.B.Z - t.A.Z, e2x = t.C.X - t.A.X, e2y = t.C.Y - t.A.Y, e2z = t.C.Z - t.A.Z;
float nx = e1y * e2z - e1z * e2y, ny = e1z * e2x - e1x * e2z, nz = e1x * e2y - e1y * e2x;
float len = MathF.Sqrt(nx * nx + ny * ny + nz * nz);
if (len < 1e-6f) continue;
nx /= len; ny /= len; nz /= len;
if (nz < 0) { nx = -nx; ny = -ny; nz = -nz; } // two-sided
float lit = TexturedTerrain.Gain * (0.7f + 0.45f * Math.Max(nx * Light.X + ny * Light.Y + nz * Light.Z, 0f));
Raster(t, tex, lit);
}
}
private void Raster(GeometryLoader.TexTri t, Tex? tex, float lit)
{
float ax = Px(t.A.X), ay = Py(t.A.Y), bx = Px(t.B.X), by = Py(t.B.Y), cx = Px(t.C.X), cy = Py(t.C.Y);
float minX = Math.Min(ax, Math.Min(bx, cx)), maxX = Math.Max(ax, Math.Max(bx, cx));
float minY = Math.Min(ay, Math.Min(by, cy)), maxY = Math.Max(ay, Math.Max(by, cy));
int x0 = Math.Max(0, (int)MathF.Floor(minX)), x1 = Math.Min(_w - 1, (int)MathF.Ceiling(maxX));
int y0 = Math.Max(0, (int)MathF.Floor(minY)), y1 = Math.Min(_h - 1, (int)MathF.Ceiling(maxY));
if (x1 < x0 || y1 < y0) return;
float area = (bx - ax) * (cy - ay) - (by - ay) * (cx - ax);
if (MathF.Abs(area) < 1e-6f) return; // edge-on from above (a wall)
float inv = 1f / area;
for (int y = y0; y <= y1; y++)
{
float py = y + 0.5f;
for (int x = x0; x <= x1; x++)
{
float px = x + 0.5f;
float w0 = ((bx - px) * (cy - py) - (by - py) * (cx - px)) * inv; // weight of A
float w1 = ((cx - px) * (ay - py) - (cy - py) * (ax - px)) * inv; // weight of B
float w2 = 1f - w0 - w1; // weight of C
if (w0 < 0 || w1 < 0 || w2 < 0) continue;
float z = w0 * t.A.Z + w1 * t.B.Z + w2 * t.C.Z;
int idx = y * _w + x;
if (z <= _depth[idx]) continue;
byte r, g, b;
if (tex?.Px != null)
{
float u = w0 * t.Au + w1 * t.Bu + w2 * t.Cu, v = w0 * t.Av + w1 * t.Bv + w2 * t.Cv;
u -= MathF.Floor(u); v -= MathF.Floor(v);
int tx = Math.Min((int)(u * tex.W), tex.W - 1), ty = Math.Min((int)(v * tex.H), tex.H - 1);
int o = (ty * tex.W + tx) * 4;
if (tex.Px[o + 3] < 128) continue; // a cut-out (leaf gap, window)
r = tex.Px[o]; g = tex.Px[o + 1]; b = tex.Px[o + 2];
}
else if (tex != null) { r = (byte)(tex.Solid >> 16); g = (byte)(tex.Solid >> 8); b = (byte)tex.Solid; }
else continue;
_depth[idx] = z;
long q = (long)idx * 3;
_rgb[q] = (byte)Math.Min(255, r * lit);
_rgb[q + 1] = (byte)Math.Min(255, g * lit);
_rgb[q + 2] = (byte)Math.Min(255, b * lit);
}
}
}
}

View file

@ -0,0 +1,142 @@
using DotRecast.Core.Numerics;
using DotRecast.Detour;
using DotRecast.Detour.Io;
using RynthCore.TerrainData;
namespace RynthNav.Baker;
// --probe wx,wy[,radius[,step]] --tiles <dir>
// A top-down look at one spot (world metres: east, north): for each sample, is the terrain's slope one a
// character can walk (TerrainSampler.FloorZ) and is there navmesh under it?
// . walkable slope, mesh x walkable slope, NO mesh <- the mesh lost ground it should have
// m steep slope, mesh # steep slope, no mesh (the mesh is right)
// @ the centre
internal static class ProbeCheck
{
/// <summary>
/// --probe-dungeon LLLL:x,y[,z[,radius]] [x,y ...] --tiles dir : in a baked dungeon (dun_LLLL.tile), the walkable
/// surface heights found at each landblock-local point (within 0.4 m sideways, 3 m up and down).
/// </summary>
public static int Dungeon(string spec, string[] points, string tilesDir, Action<string> log)
{
uint lb = Convert.ToUInt32(spec, 16);
var f = RynthNav.Routing.DungeonTileFile.Read(Path.Combine(tilesDir, RynthNav.Routing.DungeonTileFile.FileName(lb)));
if (f == null) { log($"no readable dungeon tile for 0x{lb:X4} in {tilesDir}"); return 1; }
var nav = f.BuildNavMesh(); var q = new DtNavMeshQuery(nav); var filter = new DtQueryDefaultFilter();
foreach (string pt in points)
{
string[] a = pt.Split(',');
float x = float.Parse(a[0], System.Globalization.CultureInfo.InvariantCulture), y = float.Parse(a[1], System.Globalization.CultureInfo.InvariantCulture);
float z = a.Length > 2 ? float.Parse(a[2], System.Globalization.CultureInfo.InvariantCulture) : 0f;
// Heights of every polygon under the point: sample the detail surface by querying at several heights.
var found = new SortedSet<float>();
for (float zz = z - 3f; zz <= z + 3f; zz += 0.25f)
{
q.FindNearestPoly(new RcVec3f(x + f.ShiftX, zz, y + f.ShiftY), new RcVec3f(0.4f, 0.12f, 0.4f), filter, out long rf, out RcVec3f near, out bool over);
if (rf != 0 && over) found.Add((float)Math.Round(near.Y, 1));
}
log($" ({x:F1}, {y:F1}, around z {z:F1}): " + (found.Count == 0 ? "NO walkable mesh here (an obstacle, or off the floor)" : "walkable surface at z " + string.Join(", ", found)));
}
return 0;
}
public static int Run(TerrainSampler sampler, string spec, string tilesDir, Action<string> log)
{
string[] a = spec.Split(',', StringSplitOptions.TrimEntries);
double cx = double.Parse(a[0], System.Globalization.CultureInfo.InvariantCulture), cy = double.Parse(a[1], System.Globalization.CultureInfo.InvariantCulture);
double radius = a.Length > 2 ? double.Parse(a[2], System.Globalization.CultureInfo.InvariantCulture) : 30;
double step = a.Length > 3 ? double.Parse(a[3], System.Globalization.CultureInfo.InvariantCulture) : 1.0;
int lbx = (int)Math.Floor(cx / 192), lby = (int)Math.Floor(cy / 192);
var nav = new DtNavMesh();
var p = new DtNavMeshParams { orig = new RcVec3f(0, 0, 0), tileWidth = 192f, tileHeight = 192f, maxTiles = 64, maxPolys = 1 << 16 };
nav.Init(ref p, 6);
for (int dx = -2; dx <= 2; dx++)
for (int dy = -2; dy <= 2; dy++)
{
uint t = (uint)(((lbx + dx) << 8) | (lby + dy));
string path = Path.Combine(tilesDir, $"nav_{t:X4}.tile");
if (!File.Exists(path)) continue;
using var fr = File.OpenRead(path); using var br = new BinaryReader(fr);
nav.AddTile(new DtMeshDataReader().Read(br, 6), 0, 0, out _);
}
var q = new DtNavMeshQuery(nav); var filter = new DtQueryDefaultFilter();
// Connected pieces of the loaded mesh (polygon links, across tiles): size and an id per polygon.
var piece = new Dictionary<long, int>(); var pieceSize = new List<int>();
for (int ti = 0; ti < nav.GetMaxTiles(); ti++)
{
DtMeshTile? tile = nav.GetTile(ti);
if (tile?.data?.header == null) continue;
long baseRef = nav.GetPolyRefBase(tile);
for (int pi = 0; pi < tile.data.header.polyCount; pi++)
{
long start = baseRef | (long)pi;
if (piece.ContainsKey(start)) continue;
int id = pieceSize.Count, cnt = 0; pieceSize.Add(0);
var stack = new Stack<long>(); stack.Push(start); piece[start] = id;
while (stack.Count > 0)
{
long rf0 = stack.Pop(); cnt++;
if (nav.GetTileAndPolyByRef(rf0, out DtMeshTile t2, out DtPoly pl).Failed()) continue;
for (int k = pl.firstLink; k != DtDetour.DT_NULL_LINK; k = t2.links[k].next)
{ long nb = t2.links[k].refs; if (nb != 0 && !piece.ContainsKey(nb)) { piece[nb] = id; stack.Push(nb); } }
}
pieceSize[id] = cnt;
}
}
int centrePiece = -1;
{
double cz = 0; { int bx = (int)Math.Floor(cx / 192), by = (int)Math.Floor(cy / 192); }
}
var lands = new Dictionary<uint, RynthCore.Plugin.RynthAi.Raycasting.LandblockData?>();
float Z(double wx, double wy)
{
int bx = (int)Math.Floor(wx / 192), by = (int)Math.Floor(wy / 192);
uint key = (uint)((bx << 8) | by);
if (!lands.TryGetValue(key, out var land)) lands[key] = land = sampler.LoadLandblock(key);
return land == null ? float.NaN : TerrainSampler.GetTerrainZ(land, (float)(wx - bx * 192), (float)(wy - by * 192));
}
{
q.FindNearestPoly(new RcVec3f((float)cx, Z(cx, cy), (float)cy), new RcVec3f(3f, 3f, 3f), filter, out long crf, out _, out _);
if (crf != 0 && piece.TryGetValue(crf, out int cp)) centrePiece = cp;
}
var letters = new Dictionary<int, char>();
char LetterFor(int id) { if (id == centrePiece) return '.'; if (!letters.TryGetValue(id, out char c)) { c = (char)('a' + letters.Count % 26); letters[id] = c; } return c; }
int n = (int)(radius / step);
int walkMesh = 0, walkNo = 0, steepMesh = 0, steepNo = 0;
double maxDrop = 0;
log($"probe around ({cx:F1}, {cy:F1}) lb 0x{(lbx << 8) | lby:X4} local ({cx - lbx * 192:F1}, {cy - lby * 192:F1}); {step} m per character; north is up; FloorZ {TerrainSampler.FloorZ:F3}");
for (int j = n; j >= -n; j--)
{
var row = new System.Text.StringBuilder();
for (int i = -n; i <= n; i++)
{
double wx = cx + i * step, wy = cy + j * step;
float z = Z(wx, wy);
if (float.IsNaN(z)) { row.Append(' '); continue; }
const double h = 0.75;
double gx = (Z(wx + h, wy) - Z(wx - h, wy)) / (2 * h), gy = (Z(wx, wy + h) - Z(wx, wy - h)) / (2 * h);
double nz = 1.0 / Math.Sqrt(1 + gx * gx + gy * gy);
bool walk = nz >= TerrainSampler.FloorZ;
q.FindNearestPoly(new RcVec3f((float)wx, z, (float)wy), new RcVec3f(0.6f, 1.2f, 0.6f), filter, out long rf, out _, out _);
bool mesh = rf != 0;
if (i == 0 && j == 0) { row.Append('@'); continue; }
if (walk && mesh) { row.Append(piece.TryGetValue(rf, out int pid) ? LetterFor(pid) : '?'); walkMesh++; }
else if (walk) { row.Append('x'); walkNo++; }
else if (mesh) { row.Append('m'); steepMesh++; }
else { row.Append('#'); steepNo++; }
}
log(row.ToString());
}
log("legend: '.' = the centre's connected piece; a,b,c... = other pieces " + string.Join(", ", letters.Select(kv => $"{kv.Value}={pieceSize[kv.Key]} polys")) + $"; centre piece {(centrePiece >= 0 ? pieceSize[centrePiece] : 0)} polys");
log($"walkable slope with mesh {walkMesh}, walkable slope WITHOUT mesh {walkNo}, steep with mesh {steepMesh}, steep without {steepNo}");
// Terrain height profile west-east and south-north through the centre, to see the rises.
var prof = new System.Text.StringBuilder("west->east z: ");
for (int i = -n; i <= n; i += Math.Max(1, (int)(3 / step))) prof.Append($"{Z(cx + i * step, cy):F1} ");
log(prof.ToString());
return 0;
}
}

View file

@ -12,6 +12,9 @@ using RynthNav.Baker;
// pauses when the output drive has under --min-free-mb (default 1024) left;
// --priority <locations.json> bakes the chunks nearest a town first
// survey: --survey --out <dir> (classify landblocks: land / water / none; no baking)
// map: --map --out <dir> [--ppc 2] [--area x0,x1,y0,y1] [--map-tiles] [--textured [--objects]]
// world: --map-world --ppc 2|4|8|16|32 --out <dir> [--no-objects] [--threads n] [--name f.rmap] [--chunks x0,x1,y0,y1] (the whole world, textured: worldmap.rmap v2, DXT1 tiles; resumable)
// (map: (and --map-vectors: worldmap.vec, building outlines + roads; with --area also a PNG preview) (top-down render of Dereth, world_map.png; --map-tiles also writes worldmap.rmap, the in-game map's tile pyramid)
// seams: --seams <tile dir> (how many neighbouring tiles link at their shared edge)
// graph: --graph <tile dir> [--graph-out <file>] (the coarse route graph, navgraph.bin; no rebake)
// watch: --watch --out <dir> --force-live (bake ahead of the player; the live folder needs --force-live)
@ -86,6 +89,8 @@ if (graphDir != null)
}
string acFolder = GetArg("--ac") ?? @"C:\Games\ACE\Dats";
if (float.TryParse(GetArg("--cell"), NumberStyles.Float, CultureInfo.InvariantCulture, out float cellArg) && cellArg >= 0.1f && Math.Abs(192f / cellArg - Math.Round(192f / cellArg)) < 1e-3)
NavBake.TiledCellSizeValue = cellArg;
// ── Path query (reads tiles + dats; writes nothing) ───────────────────────────
// --path LLLL:x,y LLLL:x,y --tiles <dir> (landblock hex : local metres)
@ -99,6 +104,63 @@ if (args.Contains("--audit"))
return 0;
}
// ── Dungeons (the cell dat's non-building EnvCells) ───────────────────────────
// --dungeons-survey [--limit n] read them all and print sizes/bounds; writes nothing
// --dungeons all|LLLL,LLLL --out <dir> [--radius r] [--limit n] bake dun_LLLL.tile for each
if (GetArg("--probe-dungeon") is string pdSpec)
{
var pts = args.SkipWhile(a => a != "--probe-dungeon").Skip(2).TakeWhile(a => !a.StartsWith("--")).ToArray();
return ProbeCheck.Dungeon(pdSpec, pts, GetArg("--tiles") ?? OutputGuard.LiveNavData, Console.WriteLine);
}
if (GetArg("--probe") is string probeSpec)
{
using var samplerPr = new TerrainSampler();
if (!samplerPr.Initialize(acFolder)) { Console.Error.WriteLine(samplerPr.Status); return 1; }
return ProbeCheck.Run(samplerPr, probeSpec, GetArg("--tiles") ?? OutputGuard.LiveNavData, Console.WriteLine);
}
if (args.Contains("--buildings-list"))
{
var geoL = new RynthCore2.Raycast.GeometryLoader();
if (!geoL.Initialize(acFolder)) { Console.Error.WriteLine(geoL.StatusMessage); return 1; }
return BuildingCheck.List(geoL, Console.Error.WriteLine);
}
if (GetArg("--buildings-check") is string bcheck)
{
var geoB = new RynthCore2.Raycast.GeometryLoader();
if (!geoB.Initialize(acFolder)) { Console.Error.WriteLine(geoB.StatusMessage); return 1; }
return BuildingCheck.Run(geoB, bcheck, GetArg("--tiles") ?? OutputGuard.LiveNavData, Console.WriteLine);
}
if (GetArg("--dungeons-check") is string dcheck)
{
var geoK = new RynthCore2.Raycast.GeometryLoader();
if (!geoK.Initialize(acFolder)) { Console.Error.WriteLine(geoK.StatusMessage); return 1; }
return DungeonCheck.Run(geoK, dcheck, GetArg("--tiles") ?? "", Console.WriteLine);
}
if (args.Contains("--dungeons-survey") || GetArg("--dungeons") != null)
{
var geoD = new RynthCore2.Raycast.GeometryLoader();
if (!geoD.Initialize(acFolder)) { Console.Error.WriteLine(geoD.StatusMessage); return 1; }
var cgD = NavBake.Collision(geoD);
int limD = int.TryParse(GetArg("--limit"), out int ld) ? ld : int.MaxValue;
if (args.Contains("--dungeons-survey")) return DungeonBake.Survey(cgD, limD, Console.WriteLine);
if (GetArg("--dungeons") == "near") return DungeonBake.Near(cgD, Convert.ToUInt32(GetArg("--lb") ?? "7", 16), GetArg("--at") ?? "0,0", Console.WriteLine);
if (GetArg("--dungeons") == "model") return DungeonBake.ModelInfo(cgD, Convert.ToUInt32(GetArg("--model") ?? "0", 16), Console.WriteLine);
if (GetArg("--dungeons") == "models") return DungeonBake.Models(cgD, Convert.ToUInt32(GetArg("--lb") ?? "7", 16), Console.WriteLine);
string? dOut = GetArg("--out");
if (dOut == null) { Console.Error.WriteLine("--out <folder> is required for --dungeons"); return 2; }
dOut = Path.GetFullPath(dOut);
OutputGuard.ForceLive = args.Contains("--force-live");
try { OutputGuard.Check(dOut); } catch (InvalidOperationException ex) { Console.Error.WriteLine(ex.Message); return 2; }
Directory.CreateDirectory(dOut);
float radD = float.TryParse(GetArg("--radius"), NumberStyles.Float, CultureInfo.InvariantCulture, out float rD) ? rD : 0.6f;
return DungeonBake.Run(cgD, GetArg("--dungeons")!, limD, dOut, radD, Console.WriteLine);
}
if (args.Contains("--check"))
{
var geoC = new RynthCore2.Raycast.GeometryLoader();
@ -234,6 +296,54 @@ if (args.Contains("--survey"))
return 0;
}
if (GetArg("--rmap-png") is string rmapFile)
return WorldMapBake.ExtractPng(rmapFile, int.TryParse(GetArg("--level"), out int rlv) ? rlv : 0, GetArg("--tiles"), outDir, Console.WriteLine);
if (args.Contains("--map-world"))
{
// The in-game world map in the game's own look (worldmap.rmap version 2, DXT1 tiles). See WorldMapBake.
var geoW2 = new RynthCore2.Raycast.GeometryLoader();
if (!geoW2.Initialize(acFolder)) { Console.Error.WriteLine(geoW2.StatusMessage); return 1; }
int wppc = int.TryParse(GetArg("--ppc"), out int wp) ? wp : 8;
int wthreads = int.TryParse(GetArg("--threads"), out int wt) ? wt : Math.Max(1, Environment.ProcessorCount - 1);
int cx0 = 0, cx1 = 255, cy0 = 0, cy1 = 255;
if (GetArg("--chunks") is string chunkArg)
{
var cp = chunkArg.Split(',', StringSplitOptions.TrimEntries);
if (cp.Length != 4 || !int.TryParse(cp[0], out cx0) || !int.TryParse(cp[1], out cx1) || !int.TryParse(cp[2], out cy0) || !int.TryParse(cp[3], out cy1))
{ Console.Error.WriteLine("--chunks needs x0,x1,y0,y1 (chunk columns from the west, rows from the north, decimal)"); return 1; }
}
var wopts = new WorldMapBake.Options(wppc, !args.Contains("--no-objects"), wthreads, GetArg("--name") ?? WorldMapBake.DefaultName(wppc), cx0, cx1, cy0, cy1);
return WorldMapBake.Run(sampler, geoW2, outDir, wopts, Console.WriteLine);
}
if (args.Contains("--map-vectors"))
{
// worldmap.vec: building outlines and roads for the World Map. With --area (and --ppc) also a PNG crop of the terrain with them drawn on, to check by eye.
using var geoV = new RynthCore2.Raycast.GeometryLoader();
if (!geoV.Initialize(acFolder)) { Console.Error.WriteLine(geoV.StatusMessage); return 1; }
var vec = WorldMapVectors.Build(sampler, geoV, Console.WriteLine);
OutputGuard.Check(outDir);
string vecFile = Path.Combine(outDir, "worldmap.vec");
WorldMapVectors.Write(vecFile, vec);
Console.WriteLine($"wrote {vecFile} ({new FileInfo(vecFile).Length / 1024} KB)");
if (GetArg("--area") != null)
return WorldMapRender.Run(sampler, outDir, int.TryParse(GetArg("--ppc"), out int ppcV) ? ppcV : 8, GetArg("--area"), acFolder, false, vec);
return 0;
}
if (args.Contains("--map"))
{
// --textured: the game's own terrain textures, blended per cell as the client does (TexturedTerrain), instead of flat colours.
RynthCore2.Raycast.GeometryLoader? geoM = null;
if (args.Contains("--textured"))
{
geoM = new RynthCore2.Raycast.GeometryLoader();
if (!geoM.Initialize(acFolder)) { Console.Error.WriteLine(geoM.StatusMessage); return 1; }
}
return WorldMapRender.Run(sampler, outDir, int.TryParse(GetArg("--ppc"), out int ppcArg) ? ppcArg : 2, GetArg("--area"), acFolder, args.Contains("--map-tiles"), null, geoM, args.Contains("--objects"));
}
if (args.Contains("--world"))
{
int chunk = int.TryParse(GetArg("--chunk"), out int c) && c >= 1 && c <= 32 ? c : 8;

View file

@ -22,6 +22,8 @@
<!-- The coarse route graph (graph mode): same region numbering and file format as the plugin. -->
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\NavRegions.cs" Link="Shared\NavRegions.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\NavGraph.cs" Link="Shared\NavGraph.cs" />
<!-- A dungeon's tiles in one file (dun_LLLL.tile), the same code the plugin reads it with. -->
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\DungeonTileFile.cs" Link="Shared\DungeonTileFile.cs" />
<!-- Portal avoidance exactly as the plugin plans with it (the portal-reach items of the check mode). -->
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\PortalAvoid.cs" Link="Shared\PortalAvoid.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\AvoidFilter.cs" Link="Shared\AvoidFilter.cs" />

View file

@ -0,0 +1,64 @@
using System.Text;
using RynthCore.TerrainData;
using RynthCore.Plugin.RynthAi.Raycasting;
namespace RynthNav.Baker;
/// <summary>
/// The terrain types of Dereth as the game's Region file (portal.dat 0x13000000) lists them: a name and
/// a colour per type index 0..31 (the index in bits 2-6 of a landblock's terrain words). The table
/// sits behind SkyDesc / SoundDesc / SceneDesc blocks, so rather than walk those it is found by
/// shape: a count, then that many entries of (PString name, uint colour, uint sceneCount, scene ids),
/// every name printable, ending inside the file. Null if no table of that shape turns up.
/// </summary>
internal sealed class TerrainPalette
{
public string[] Names { get; }
public uint[] Argb { get; }
private TerrainPalette(string[] names, uint[] argb) { Names = names; Argb = argb; }
public static TerrainPalette? Load(string acFolder)
{
string? path = new[] { "client_portal.dat", "portal.dat" }.Select(n => Path.Combine(acFolder, n)).FirstOrDefault(File.Exists);
if (path == null) return null;
using var dat = new DatDatabase();
if (!dat.Open(path)) return null;
byte[]? data = dat.GetFileData(0x13000000);
return data == null ? null : Find(data);
}
private static TerrainPalette? Find(byte[] d)
{
for (int start = 12; start + 8 < d.Length; start++)
{
uint n = BitConverter.ToUInt32(d, start);
if (n < 16 || n > 64) continue;
var t = TryParse(d, start + 4, (int)n);
if (t != null) return t;
}
return null;
}
private static TerrainPalette? TryParse(byte[] d, int pos, int n)
{
var names = new string[n];
var cols = new uint[n];
for (int i = 0; i < n; i++)
{
if (pos + 2 > d.Length) return null;
int len = BitConverter.ToUInt16(d, pos);
if (len < 3 || len > 40 || pos + 2 + len > d.Length) return null;
for (int k = 0; k < len; k++) { byte c = d[pos + 2 + k]; if (c < 0x20 || c > 0x7E) return null; }
names[i] = Encoding.ASCII.GetString(d, pos + 2, len);
pos += 2 + len;
pos = (pos + 3) & ~3; // PString pads to 4 (the file starts 4-aligned)
if (pos + 8 > d.Length) return null;
cols[i] = BitConverter.ToUInt32(d, pos);
uint scenes = BitConverter.ToUInt32(d, pos + 4);
if (scenes > 200) return null;
pos += 8 + (int)scenes * 4;
if (pos > d.Length) return null;
}
return new TerrainPalette(names, cols);
}
}

View file

@ -0,0 +1,311 @@
using System.Numerics;
namespace RynthNav.Baker;
// The game's own terrain look, drawn top-down on the CPU: --map --textured.
// Each 24-yard cell is blended the way the client's TexMerge does it (ported from AcClientReborn's
// Program.cs, which does it on the GPU): the cell's four corner terrain types and road bits make a
// palette code; that picks a base ground texture, up to three overlay textures (the neighbouring
// types) each cut by a corner/side alpha mask under one of four rotations, and a road texture cut
// by a road mask. Ground textures cover one cell (u, v run 0..1 across it); masks are single-channel.
// Then the cell is lit from the terrain's slope (the vertex shade the flat render uses).
// The textures come from portal.dat through AcClientReborn's AcTextureDecoder.
internal sealed class TexturedTerrain
{
private readonly record struct Img(int W, int H, byte[] Px);
// Atlas layers as in AcClientReborn: 0-31 terrain-type ground, 40 road stone, 50-62 road masks, 64+ terrain masks.
private readonly Img?[] _layers = new Img?[128];
private int _stone = -1;
private readonly List<(uint Code, int Layer)> _road = new(), _corner = new(), _side = new();
// AC's LandblockStruct.LandUVs (cell-corner UVs: SW, SE, NE, NW) and the 4 rotation permutations.
private static readonly (float U, float V)[] LandUV = { (0, 1), (1, 1), (1, 0), (0, 0) };
private static readonly int[][] LandUVRot = { new[] { 0, 1, 2, 3 }, new[] { 3, 0, 1, 2 }, new[] { 2, 3, 0, 1 }, new[] { 1, 2, 3, 0 } };
/// <summary>The client lights terrain with sun and ambient on top of what the textures hold; this stands in for it.</summary>
public const float Gain = 1.55f;
public int Layers { get; private set; }
public AcClientReborn.AcTextureDecoder Decoder { get; private set; } = null!;
public static TexturedTerrain? Load(RynthCore2.Raycast.GeometryLoader geo, Action<string> log)
{
var ss = geo.ScatterSystemRef;
if (ss == null) { log("textured terrain: no region description"); return null; }
var dec = new AcClientReborn.AcTextureDecoder(geo.PortalDat);
var t = new TexturedTerrain { Decoder = dec };
Img? Decode(uint gid)
{
var d = dec.DecodeAny(gid);
return d?.Rgba != null ? new Img(d.Width, d.Height, d.Rgba) : null;
}
foreach (var kv in ss.TerrainTexGIDs)
{
if (kv.Key >= 40) continue;
if (Decode(kv.Value) is Img i) { t._layers[kv.Key] = i; t.Layers++; }
}
if (ss.TerrainTexGIDs.TryGetValue(0x20u, out uint stone) && Decode(stone) is Img si) { t._layers[40] = si; t._stone = 40; t.Layers++; }
var maskLayer = new Dictionary<uint, int>();
int next = 64;
int Mask(uint gid)
{
if (gid == 0) return -1;
if (maskLayer.TryGetValue(gid, out int l)) return l;
l = next++;
if (l < 128 && Decode(gid) is Img mi) { t._layers[l] = mi; t.Layers++; }
maskLayer[gid] = l;
return l;
}
foreach (var (code, gid) in ss.CornerTerrainMaps) t._corner.Add((code, Mask(gid)));
foreach (var (code, gid) in ss.SideTerrainMaps) t._side.Add((code, Mask(gid)));
var roadLayer = new Dictionary<uint, int>();
foreach (var (rcode, gid) in ss.RoadMaps)
{
if (!roadLayer.TryGetValue(gid, out int l))
{
l = 50 + roadLayer.Count;
if (l <= 62 && Decode(gid) is Img ri) { t._layers[l] = ri; t.Layers++; }
roadLayer[gid] = l;
}
t._road.Add((rcode, l));
}
int types = 0; for (int i = 0; i < 32; i++) if (t._layers[i] != null) types++;
log($"textured terrain: {types} ground textures, stone road L{t._stone}, {t._corner.Count} corner + {t._side.Count} side + {t._road.Count} road masks ({t.Layers} images)");
foreach (int l in new[] { 0, 1, 3, 20, 40 }) if (t._layers[l] is Img im) log($" layer {l}: {im.W}x{im.H}");
return t;
}
// ── TexMerge (AcClientReborn Program.cs) ────────────────────────────
private static uint PalCode(int r1, int r2, int r3, int r4, int t1, int t2, int t3, int t4)
=> (uint)((1 << 28) | (r1 << 26 | r2 << 24 | r3 << 22 | r4 << 20) | (t1 << 15 | t2 << 10 | t3 << 5 | t4));
private static (uint c0, uint c1, bool all) RoadCode(uint pcode)
{
uint mask = 0;
if ((pcode & 0xC000000) != 0) mask = 1;
if ((pcode & 0x3000000) != 0) mask |= 2;
if ((pcode & 0xC00000) != 0) mask |= 4;
if ((pcode & 0x300000) != 0) mask |= 8;
return mask switch
{
0xF => (0u, 0u, true),
0xE => (6u, 12u, false),
0xD => (9u, 12u, false),
0xB => (9u, 3u, false),
0x7 => (3u, 6u, false),
0x0 => (0u, 0u, false),
_ => (mask, 0u, false),
};
}
private (int layer, int rot) FindRoadAlpha(uint pcode, uint rcode)
{
int n = _road.Count;
if (n == 0 || rcode == 0) return (-1, 0);
int prng = (int)Math.Floor((1379576222.0 * pcode - 1372186442.0) * 2.3283064e-10 * n);
for (int i = 0; i < n; i++)
{
int idx = ((i + prng) % n + n) % n;
uint alphaCode = _road[idx].Code;
for (int j = 0; j < 4; j++)
{
if (alphaCode == rcode) return (_road[idx].Layer, j);
alphaCode *= 2;
if (alphaCode >= 16) alphaCode -= 15;
}
}
return (-1, 0);
}
private static int[] TerrainCodes(uint pcode) => new[] { (int)((pcode >> 15) & 0x1F), (int)((pcode >> 10) & 0x1F), (int)((pcode >> 5) & 0x1F), (int)(pcode & 0x1F) };
private static (int baseType, (int type, uint tcode)[] overlays) BuildTCodes(int[] p, int baseIdx)
{
int baseType = p[baseIdx], t2 = -1, ov0 = -1, ov1 = -1;
uint tc0 = 0, tc1 = 0;
for (int k = 0; k < 4; k++)
{
if (baseType == p[k]) continue;
if (tc0 == 0) { tc0 = (uint)(1 << k); t2 = p[k]; ov0 = t2; }
else
{
if (t2 == p[k] && tc0 == (uint)(1 << (k - 1))) tc0 += (uint)(1 << k);
else { ov1 = p[k]; tc1 = (uint)(1 << k); }
break;
}
}
var list = new List<(int, uint)>();
if (ov0 >= 0) list.Add((ov0, tc0));
if (ov1 >= 0) list.Add((ov1, tc1));
return (baseType, list.ToArray());
}
private static (int baseType, (int type, uint tcode)[] overlays) Terrain(uint pcode)
{
var p = TerrainCodes(pcode);
for (int i = 0; i < 4; i++)
for (int j = i + 1; j < 4; j++)
if (p[i] == p[j]) return BuildTCodes(p, i);
return (p[0], new (int, uint)[] { (p[1], 2u), (p[2], 4u), (p[3], 8u) });
}
private (int layer, int rot) FindTerrainAlpha(uint pcode, uint tcode)
{
var maps = (tcode == 1 || tcode == 2 || tcode == 4 || tcode == 8) ? _corner : _side;
int n = maps.Count;
if (n == 0) return (-1, 0);
int prng = (int)Math.Floor((1379576222.0 * pcode - 1372186442.0) * 2.3283064e-10 * n);
if (prng >= n || prng < 0) prng = 0;
uint alphaCode = maps[prng].Code;
for (int i = 0; ; i++)
{
if (alphaCode == tcode) return (maps[prng].Layer, i);
alphaCode *= 2;
if (alphaCode >= 16) alphaCode -= 15;
if (i >= 3) return (-1, 0);
}
}
/// <summary>
/// A cell's merge result, flat: [0] base layer; [1..3], [4..6], [7..9] overlay i (colour layer, mask layer, rotation);
/// [10] road stone layer; [11, 12] road 0 (mask layer, rotation); [13, 14] road 1. -1 = unused.
/// </summary>
private int[] CellSurf(int t1, int t2, int t3, int t4, int r1, int r2, int r3, int r4)
{
var s = new int[15];
Array.Fill(s, -1);
uint pcode = PalCode(r1, r2, r3, r4, t1, t2, t3, t4);
var (c0, c1, allRoad) = RoadCode(pcode);
if (allRoad && _stone >= 0) { s[0] = _stone; return s; }
var (baseType, overlays) = Terrain(pcode);
s[0] = baseType;
int slot = 0;
foreach (var (otype, tcode) in overlays)
{
if (tcode == 0 || slot >= 3) continue;
var (mlayer, rot) = FindTerrainAlpha(pcode, tcode);
if (mlayer < 0) continue;
s[1 + slot * 3] = otype; s[2 + slot * 3] = mlayer; s[3 + slot * 3] = rot;
slot++;
}
if (_stone >= 0 && (r1 | r2 | r3 | r4) != 0)
{
var (l0, rot0) = FindRoadAlpha(pcode, c0);
if (l0 >= 0)
{
s[10] = _stone; s[11] = l0; s[12] = rot0;
if (c1 != 0) { var (l1, rot1) = FindRoadAlpha(pcode, c1); if (l1 >= 0) { s[13] = l1; s[14] = rot1; } }
}
}
return s;
}
// ── Sampling ─────────────────────────────────────────────────────────
/// <summary>Bilinear sample of a layer; u, v in 0..1 (repeat). r, g, b 0..1, a 0..1.</summary>
private void Sample(int layer, float u, float v, bool wrap, out float r, out float g, out float b, out float a)
{
r = g = b = 0; a = 1;
if ((uint)layer >= 128 || _layers[layer] is not Img im) return;
float x = u * im.W - 0.5f, y = v * im.H - 0.5f;
int x0 = (int)MathF.Floor(x), y0 = (int)MathF.Floor(y);
float fx = x - x0, fy = y - y0;
int x1 = x0 + 1, y1 = y0 + 1;
if (wrap) { x0 = ((x0 % im.W) + im.W) % im.W; x1 = ((x1 % im.W) + im.W) % im.W; y0 = ((y0 % im.H) + im.H) % im.H; y1 = ((y1 % im.H) + im.H) % im.H; }
else { x0 = Math.Clamp(x0, 0, im.W - 1); x1 = Math.Clamp(x1, 0, im.W - 1); y0 = Math.Clamp(y0, 0, im.H - 1); y1 = Math.Clamp(y1, 0, im.H - 1); }
int o00 = (y0 * im.W + x0) * 4, o10 = (y0 * im.W + x1) * 4, o01 = (y1 * im.W + x0) * 4, o11 = (y1 * im.W + x1) * 4;
float w00 = (1 - fx) * (1 - fy), w10 = fx * (1 - fy), w01 = (1 - fx) * fy, w11 = fx * fy;
byte[] p = im.Px;
r = (p[o00] * w00 + p[o10] * w10 + p[o01] * w01 + p[o11] * w11) / 255f;
g = (p[o00 + 1] * w00 + p[o10 + 1] * w10 + p[o01 + 1] * w01 + p[o11 + 1] * w11) / 255f;
b = (p[o00 + 2] * w00 + p[o10 + 2] * w10 + p[o01 + 2] * w01 + p[o11 + 2] * w11) / 255f;
a = (p[o00 + 3] * w00 + p[o10 + 3] * w10 + p[o01 + 3] * w01 + p[o11 + 3] * w11) / 255f;
}
/// <summary>The cell-local u, v of a pixel in a mask rotated by <paramref name="rot"/> (bilinear of the permuted corner UVs).</summary>
private static void MaskUV(int rot, float fx, float fy, out float u, out float v)
{
// Corners SW, SE, NE, NW with weights (1-fx)(1-fy), fx(1-fy), fx*fy, (1-fx)fy.
var perm = LandUVRot[rot];
var c0 = LandUV[perm[0]]; var c1 = LandUV[perm[1]]; var c2 = LandUV[perm[2]]; var c3 = LandUV[perm[3]];
float w0 = (1 - fx) * (1 - fy), w1 = fx * (1 - fy), w2 = fx * fy, w3 = (1 - fx) * fy;
u = c0.U * w0 + c1.U * w1 + c2.U * w2 + c3.U * w3;
v = c0.V * w0 + c1.V * w1 + c2.V * w2 + c3.V * w3;
}
// ── A cell ───────────────────────────────────────────────────────────
/// <summary>
/// Paints one cell (its south-west vertex gx, gy) as a ppc x ppc block into <paramref name="rgb"/>, whose top-left pixel
/// is (px0, py0) in an image <paramref name="width"/> pixels wide. <paramref name="shade"/> is the per-vertex light (1 = flat).
/// </summary>
public void PaintCell(int gx, int gy, byte[] type, byte[] road, float[] shade, int V, int ppc, byte[] rgb, int width, int px0, int py0)
{
int Ti(int x, int y) => type[Math.Min(y, V - 1) * V + Math.Min(x, V - 1)] == 255 ? 20 : type[Math.Min(y, V - 1) * V + Math.Min(x, V - 1)];
int Ri(int x, int y) => road[Math.Min(y, V - 1) * V + Math.Min(x, V - 1)];
int[] s = CellSurf(Ti(gx, gy), Ti(gx + 1, gy), Ti(gx + 1, gy + 1), Ti(gx, gy + 1), Ri(gx, gy), Ri(gx + 1, gy), Ri(gx + 1, gy + 1), Ri(gx, gy + 1));
float sSW = shade[Math.Min(gy, V - 1) * V + Math.Min(gx, V - 1)], sSE = shade[Math.Min(gy, V - 1) * V + Math.Min(gx + 1, V - 1)],
sNE = shade[Math.Min(gy + 1, V - 1) * V + Math.Min(gx + 1, V - 1)], sNW = shade[Math.Min(gy + 1, V - 1) * V + Math.Min(gx, V - 1)];
bool anyOv = s[1] >= 0 && s[2] >= 0;
bool anyRoad = s[10] >= 0 && s[11] >= 0;
for (int j = 0; j < ppc; j++)
{
float fy = 1f - (j + 0.5f) / ppc; // j = 0 is the cell's north edge
for (int i = 0; i < ppc; i++)
{
float fx = (i + 0.5f) / ppc;
float bu = fx, bv = 1f - fy;
Sample(s[0], bu, bv, true, out float br, out float bg, out float bb, out _);
// Overlays (maskBlend3).
float or_ = 0, og = 0, ob = 0, oa = 0;
if (anyOv)
{
float ar0 = 1, ar1 = 1, ar2 = 1;
float cr0 = 0, cg0 = 0, cb0 = 0, cr1 = 0, cg1 = 0, cb1 = 0, cr2 = 0, cg2 = 0, cb2 = 0;
bool h0 = s[1] >= 0 && s[2] >= 0, h1 = s[4] >= 0 && s[5] >= 0, h2 = s[7] >= 0 && s[8] >= 0;
if (h0) { Sample(s[1], bu, bv, true, out cr0, out cg0, out cb0, out _); MaskUV(s[3], fx, fy, out float mu, out float mv); Sample(s[2], mu, mv, false, out float m, out _, out _, out _); ar0 = m; }
if (h1) { Sample(s[4], bu, bv, true, out cr1, out cg1, out cb1, out _); MaskUV(s[6], fx, fy, out float mu, out float mv); Sample(s[5], mu, mv, false, out float m, out _, out _, out _); ar1 = m; }
if (h2) { Sample(s[7], bu, bv, true, out cr2, out cg2, out cb2, out _); MaskUV(s[9], fx, fy, out float mu, out float mv); Sample(s[8], mu, mv, false, out float m, out _, out _, out _); ar2 = m; }
// t.a of an absent overlay counts as 1 in the shader's product; present ones use their mask.
float a0 = h0 ? ar0 : 1f, a1 = h1 ? ar1 : 1f, a2 = h2 ? ar2 : 1f;
float aR = 1f - a0 * a1 * a2;
if (aR >= 1e-4f)
{
float b0 = 1 - a0, b1 = 1 - a1, b2 = 1 - a2;
or_ = (b0 * cr0 + (1 - b0) * b1 * cr1 + (1 - b1) * b2 * cr2) / aR;
og = (b0 * cg0 + (1 - b0) * b1 * cg1 + (1 - b1) * b2 * cg2) / aR;
ob = (b0 * cb0 + (1 - b0) * b1 * cb1 + (1 - b1) * b2 * cb2) / aR;
oa = aR;
}
}
// Road.
float rr = 0, rg = 0, rb = 0, ra = 0;
if (anyRoad)
{
Sample(s[10], bu, bv, true, out rr, out rg, out rb, out _);
MaskUV(s[12], fx, fy, out float mu, out float mv);
Sample(s[11], mu, mv, false, out float a0, out _, out _, out _);
ra = 1f - a0;
if (s[13] >= 0)
{
MaskUV(s[14], fx, fy, out float mu1, out float mv1);
Sample(s[13], mu1, mv1, false, out float a1, out _, out _, out _);
ra = 1f - a0 * a1;
}
}
float baseK = (1f - oa) * (1f - ra), ovK = oa * (1f - ra);
float r = Math.Clamp(br * baseK, 0, 1) + Math.Clamp(or_ * ovK, 0, 1) + rr * ra;
float g = Math.Clamp(bg * baseK, 0, 1) + Math.Clamp(og * ovK, 0, 1) + rg * ra;
float b = Math.Clamp(bb * baseK, 0, 1) + Math.Clamp(ob * ovK, 0, 1) + rb * ra;
float light = (sSW * (1 - fx) * (1 - fy) + sSE * fx * (1 - fy) + sNE * fx * fy + sNW * (1 - fx) * fy);
long o = ((long)(py0 + j) * width + px0 + i) * 3;
rgb[o] = (byte)Math.Clamp(r * light * Gain * 255f, 0, 255);
rgb[o + 1] = (byte)Math.Clamp(g * light * Gain * 255f, 0, 255);
rgb[o + 2] = (byte)Math.Clamp(b * light * Gain * 255f, 0, 255);
}
}
}
}

View file

@ -111,8 +111,8 @@ internal static class WorldBake
string settingsFile = Path.Combine(bakeDir, "settings.txt");
// geometry= names what the obstacles are made from: tiles from the drawing meshes (before
// 2026-10-02) and from the collision geometry must not be mixed in one set.
string geometry = NavBake.DrawMeshes ? "" : $" geometry=collision-v1" + (NavBake.AgentMaxClimb != 1f ? $" climb={NavBake.AgentMaxClimb:0.##}" : "");
string settings = string.Create(System.Globalization.CultureInfo.InvariantCulture, $"radius={radius:0.###} chunk={chunk}{geometry}");
string geometry = NavBake.DrawMeshes ? "" : $" geometry=collision-v2" + (NavBake.AgentMaxClimb != 1f ? $" climb={NavBake.AgentMaxClimb:0.##}" : "");
string settings = string.Create(System.Globalization.CultureInfo.InvariantCulture, $"radius={radius:0.###} chunk={chunk}{geometry}{(NavBake.TiledCellSizeValue != 0.5f ? $" cell={NavBake.TiledCellSizeValue:0.###}" : "")}");
if (File.Exists(settingsFile))
{
string was = File.ReadAllText(settingsFile).Trim();

View file

@ -0,0 +1,83 @@
using RynthCore.Plugin.RynthAi.Raycasting;
using RynthCore.TerrainData;
namespace RynthNav.Baker;
/// <summary>
/// Dereth's terrain as one global vertex grid (2049 x 2049: the east / north edge vertex of a landblock is
/// the west / south edge vertex of its neighbour), read from client_cell_1.dat: per vertex the terrain type
/// (0-31; 255 = no landblock, open sea), the road bits and the height. Row-major, index y * V + x, y
/// north. Shared by the flat map render, the textured render and the world bake.
/// </summary>
internal sealed class WorldGrid
{
public const int Blocks = 256, Side = 8, V = Blocks * Side + 1;
public const float CellUnits = 24f;
public readonly byte[] Type = new byte[V * V];
public readonly byte[] Road = new byte[V * V];
public readonly float[] Height = new float[V * V];
public int Loaded { get; private set; }
private WorldGrid() { Array.Fill(Type, (byte)255); }
/// <summary>Reads landblocks lx0..lx1, ly0..ly1 (inclusive; the rest stay open sea).</summary>
public static WorldGrid Load(TerrainSampler sampler, int lx0, int lx1, int ly0, int ly1, Action<string>? log = null)
{
var g = new WorldGrid();
lx0 = Math.Max(0, lx0); ly0 = Math.Max(0, ly0); lx1 = Math.Min(Blocks - 1, lx1); ly1 = Math.Min(Blocks - 1, ly1);
for (int lx = lx0; lx <= lx1; lx++)
{
for (int ly = ly0; ly <= ly1; ly++)
{
LandblockData? lb = null;
try { lb = sampler.LoadLandblock((uint)((lx << 8) | ly)); } catch { }
if (lb == null || lb.TerrainWords == null) continue;
g.Loaded++;
for (int ix = 0; ix <= Side; ix++)
for (int iy = 0; iy <= Side; iy++)
{
int gi = (ly * Side + iy) * V + (lx * Side + ix);
ushort w = lb.TerrainWords[ix * 9 + iy];
g.Type[gi] = (byte)((w >> 2) & 0x1F);
g.Road[gi] = (byte)(w & 3);
g.Height[gi] = lb.HeightsZ[ix, iy];
}
}
if (log != null && lx % 16 == 0) log($" read landblock column {lx:X2}");
}
return g;
}
/// <summary>How many vertices of each terrain type (0-31).</summary>
public long[] TypeCounts()
{
var seen = new long[32];
foreach (byte t in Type) if (t < 32) seen[t]++;
return seen;
}
/// <summary>
/// Light per vertex from the slope (central differences of the heights, lit from the north-west, 45 degrees
/// up): 1.0 on flat ground. <paramref name="exaggeration"/> stretches the relief (Dereth's is gentle).
/// </summary>
public float[] Shade(float exaggeration)
{
var shade = new float[V * V];
for (int gy = 0; gy < V; gy++)
for (int gx = 0; gx < V; gx++)
{
int gi = gy * V + gx;
if (Type[gi] == 255) { shade[gi] = 1f; continue; }
float hE = Height[gy * V + Math.Min(gx + 1, V - 1)], hW = Height[gy * V + Math.Max(gx - 1, 0)];
float hN = Height[Math.Min(gy + 1, V - 1) * V + gx], hS = Height[Math.Max(gy - 1, 0) * V + gx];
float dx = (hE - hW) / (2 * CellUnits), dy = (hN - hS) / (2 * CellUnits);
float nx = -dx * exaggeration, ny = -dy * exaggeration, nz = 1f;
float inv = 1f / MathF.Sqrt(nx * nx + ny * ny + nz * nz);
const float lx = -0.5f, ly = 0.5f, lz = 0.707f; // toward the light
float lit = (nx * lx + ny * ly + nz * lz) * inv;
shade[gi] = Math.Clamp(lit / lz, 0.55f, 1.35f);
}
return shade;
}
}

View file

@ -0,0 +1,352 @@
using System.Diagnostics;
using System.IO.Compression;
using RynthCore.TerrainData;
namespace RynthNav.Baker;
// --map-world: the whole of Dereth, in the game's own look, as an in-game map file (worldmap.rmap version 2).
//
// --map-world --ppc 2|4|8|16|32 --out <dir> [--no-objects] [--threads n] [--name file.rmap] [--chunks x0,x1,y0,y1]
//
// Tiers (the engine uses the best file it finds in NavData): ppc 2 = worldmap.rmap (Standard), 8 = worldmap-hd.rmap,
// 16 = worldmap-ultra.rmap. ppc is pixels per 24-yard cell; the picture is 2048 * ppc pixels square.
//
// How: the world is cut into chunks of landblocks (8 x 8, or more when a 256 px tile is wider than that). Each
// chunk is drawn with a landblock of margin all round (so a roof or a tree that crosses the edge, and the
// slope light, match across it): the ground cell by cell from the game's textures (TexturedTerrain), then the
// static objects and scenery from above (ObjectRaster). The middle is cut into 256 px tiles, the coarser zoom
// levels the chunk can make by itself are made by halving, and every tile is DXT1-compressed (Dxt1) and
// deflated. A chunk's result goes to its own file under _work-<name>, so an interrupted bake resumes where it
// stopped; the one-tile "apex" of each chunk is kept for the end, when the levels above the chunks are made
// from them and everything is laid out in the final file.
//
// File (little-endian, as version 1 in WorldMapRender.WriteRmap except each tile is the deflate of its DXT1
// blocks, 256 x 256 px = 32 KB, instead of RGB): "RMAP", u32 version (2), u32 tile size, u32 levels, u32 pixels
// per cell at level 0, u32 cells wide, u32 cells high; per level u32 width, height, columns, rows, first tile;
// u32 tile count; per tile u64 offset + u32 length (0 length: no tile); then the tiles. Row 0 is the north edge.
internal static class WorldMapBake
{
private const int Tile = 256, Margin = 1; // tile px; margin in landblocks
internal sealed record Options(int Ppc, bool Objects, int Threads, string Name, int ChunkX0 = 0, int ChunkX1 = 255, int ChunkY0 = 0, int ChunkY1 = 255);
private sealed class Ctx
{
public required WorldGrid Grid; public required float[] Shade; public required TexturedTerrain Terrain;
public required ObjectRaster.SurfaceStore Surfaces; public required RynthCore2.Raycast.GeometryLoader Geo;
public required object GeoLock; public required int Ppc, ChunkLb, ChunkPx, TilesPerChunk, ChunkLevels, ChunksPerSide;
public required bool Objects; public required string Work;
}
private static int Log2(int n) { int l = 0; while ((1 << l) < n) l++; return l; }
public static string DefaultName(int ppc) => ppc switch { 2 => "worldmap.rmap", 8 => "worldmap-hd.rmap", 16 => "worldmap-ultra.rmap", _ => $"worldmap-p{ppc}.rmap" };
public static int Run(TerrainSampler sampler, RynthCore2.Raycast.GeometryLoader geo, string outDir, Options o, Action<string> log)
{
int ppc = o.Ppc;
if (ppc < 2 || ppc > 128 || (ppc & (ppc - 1)) != 0) { log("--ppc must be 2, 4, 8, 16, 32, 64 or 128 for the world bake (a power of two)"); return 1; }
int tileCells = Tile / ppc; // cells across a tile (a tile can be smaller than a landblock: chunks are what align)
if (ppc >= 64) log($"note: at {ppc} px per cell a chunk's drawing buffer is {(8 + 2 * Margin) * 8 * ppc} px square (about {(long)(8 + 2 * Margin) * 8 * ppc * (8 + 2 * Margin) * 8 * ppc * 7 / (1 << 20)} MB a thread); use --threads to fit your memory, and expect roughly {ppc * ppc * 0.86 / 1024:F1} GB of tiles (scaled from the 32 px bake)");
int tileLb = Math.Max(1, tileCells / 8);
int chunkLb = Math.Max(8, tileLb);
int chunksPerSide = 256 / chunkLb;
int chunkPx = chunkLb * 8 * ppc, tilesPerChunk = chunkPx / Tile;
int worldPx = 2048 * ppc, worldTiles = worldPx / Tile;
int levels = Log2(worldTiles) + 1, chunkLevels = Log2(tilesPerChunk) + 1;
log($"world bake: {worldPx} x {worldPx} px ({ppc} px per cell), {worldTiles} x {worldTiles} tiles at level 0, {levels} levels; chunks of {chunkLb} x {chunkLb} landblocks ({chunkPx} px), {chunksPerSide * chunksPerSide} of them");
OutputGuard.Check(outDir);
Directory.CreateDirectory(outDir);
string work = Path.Combine(outDir, "_work-" + Path.GetFileNameWithoutExtension(o.Name));
Directory.CreateDirectory(work);
var sw = Stopwatch.StartNew();
WorldGrid grid = WorldGrid.Load(sampler, 0, 255, 0, 255);
log($"terrain read: {grid.Loaded} landblocks ({sw.Elapsed.TotalSeconds:F1}s)");
float[] shade = grid.Shade(1.3f);
TexturedTerrain? terrain = TexturedTerrain.Load(geo, log);
if (terrain == null) return 1;
var ctx = new Ctx
{
Grid = grid, Shade = shade, Terrain = terrain, Surfaces = new ObjectRaster.SurfaceStore(terrain.Decoder), Geo = geo, GeoLock = new object(),
Ppc = ppc, ChunkLb = chunkLb, ChunkPx = chunkPx, TilesPerChunk = tilesPerChunk, ChunkLevels = chunkLevels, ChunksPerSide = chunksPerSide,
Objects = o.Objects, Work = work,
};
// The chunks to bake: those inside the requested range (all, normally), by chunk column and row (row 0 = north).
var todo = new List<(int Cc, int Cr)>();
for (int cr = 0; cr < chunksPerSide; cr++)
for (int cc = 0; cc < chunksPerSide; cc++)
if (cc >= o.ChunkX0 && cc <= o.ChunkX1 && cr >= o.ChunkY0 && cr <= o.ChunkY1) todo.Add((cc, cr));
int done = 0, skipped = 0;
int total = todo.Count;
var failures = new System.Collections.Concurrent.ConcurrentBag<string>();
Parallel.ForEach(todo, new ParallelOptions { MaxDegreeOfParallelism = Math.Max(1, o.Threads) }, cell =>
{
string file = ChunkFile(work, cell.Cc, cell.Cr);
try
{
if (File.Exists(file)) { Interlocked.Increment(ref skipped); }
else BakeChunk(ctx, cell.Cc, cell.Cr, file);
}
catch (Exception ex) { failures.Add($"chunk {cell.Cc},{cell.Cr}: {ex.Message}"); }
int n = Interlocked.Increment(ref done);
if (n % 8 == 0 || n == total)
{
double el = sw.Elapsed.TotalSeconds, perChunk = el / Math.Max(1, n - skipped);
log($" {n}/{total} chunks ({skipped} already done), {el / 60:F1} min, about {(total - n) * perChunk / 60:F0} min left");
}
});
foreach (string f in failures) log("FAILED " + f);
if (!failures.IsEmpty) { log("some chunks failed: fix and rerun (finished chunks are kept), no file written"); return 1; }
log($"surfaces decoded: {ctx.Surfaces.Count}");
string final = Path.Combine(outDir, o.Name);
Assemble(ctx, ppc, worldTiles, levels, final, log);
log($"wrote {final} ({new FileInfo(final).Length / (1024 * 1024)} MB) in {sw.Elapsed.TotalMinutes:F1} min");
return 0;
}
private static string ChunkFile(string work, int cc, int cr) => Path.Combine(work, $"chunk_{cc:D2}_{cr:D2}.bin");
// ── One chunk ────────────────────────────────────────────────────────
private static void BakeChunk(Ctx c, int cc, int cr, string file)
{
int ppc = c.Ppc;
int lx0 = cc * c.ChunkLb, ly0 = (c.ChunksPerSide - 1 - cr) * c.ChunkLb; // south-west landblock of the chunk (row 0 = north)
int bufCx0 = (lx0 - Margin) * 8, bufCy0 = (ly0 - Margin) * 8; // buffer origin, in cells
int bufCells = (c.ChunkLb + 2 * Margin) * 8, W = bufCells * ppc, H = W;
var rgb = new byte[(long)W * H * 3];
// Ground, cell by cell (cells outside the world stay black; the crop never reaches them).
for (int cj = 0; cj < bufCells; cj++)
{
int gy = bufCy0 + (bufCells - 1 - cj); // north first
if (gy < 0 || gy >= 2048) continue;
for (int ci = 0; ci < bufCells; ci++)
{
int gx = bufCx0 + ci;
if (gx < 0 || gx >= 2048) continue;
c.Terrain.PaintCell(gx, gy, c.Grid.Type, c.Grid.Road, c.Shade, WorldGrid.V, ppc, rgb, W, ci * ppc, cj * ppc);
}
}
// Objects and scenery from above, from this chunk's landblocks and the margin round it.
if (c.Objects)
{
var raster = new ObjectRaster(rgb, W, H, bufCx0, bufCy0, ppc, c.Surfaces);
for (int lx = lx0 - Margin; lx < lx0 + c.ChunkLb + Margin; lx++)
for (int ly = ly0 - Margin; ly < ly0 + c.ChunkLb + Margin; ly++)
{
if (lx < 0 || ly < 0 || lx > 255 || ly > 255) continue;
uint key = (uint)((lx << 8) | ly);
List<RynthCore2.Raycast.GeometryLoader.TexTri> statics, scatter;
lock (c.GeoLock)
{
statics = c.Geo.GetTexturedStaticObjects(key);
scatter = c.Geo.GetTexturedScatter(key, (wx, wy) => c.Geo.GetTerrainZWorld(wx, wy));
}
raster.Add(statics);
raster.Add(scatter);
}
}
// The middle of the buffer is the chunk.
int m = Margin * 8 * ppc, cp = c.ChunkPx;
var level = new byte[(long)cp * cp * 3];
for (int y = 0; y < cp; y++) Buffer.BlockCopy(rgb, ((y + m) * W + m) * 3, level, y * cp * 3, cp * 3);
// The chunk's own pyramid: level 0 and as many halvings as reach a single tile (the apex).
var tiles = new List<(int Level, int Col, int Row, byte[] Blob)>();
int size = cp;
byte[]? apex = null;
for (int k = 0; k < c.ChunkLevels; k++)
{
int n = size / Tile;
for (int tr = 0; tr < n; tr++)
for (int tc = 0; tc < n; tc++)
tiles.Add((k, cc * n + tc, cr * n + tr, EncodeTile(level, size, tc * Tile, tr * Tile)));
if (k == c.ChunkLevels - 1) apex = level;
else { level = Downsample(level, size); size /= 2; }
}
string tmp = file + ".tmp";
using (var fs = new FileStream(tmp, FileMode.Create, FileAccess.Write))
using (var w = new BinaryWriter(fs))
{
w.Write(new byte[] { (byte)'R', (byte)'C', (byte)'H', (byte)'K' });
w.Write((uint)tiles.Count);
foreach (var t in tiles) { w.Write((byte)t.Level); w.Write((ushort)t.Col); w.Write((ushort)t.Row); w.Write((uint)t.Blob.Length); w.Write(t.Blob); }
w.Write(apex!); // 256 x 256 RGB, for the levels above
}
File.Move(tmp, file, overwrite: true);
}
/// <summary>The 256 x 256 tile at (x0, y0) of a square RGB image, as the deflate of its DXT1 blocks.</summary>
private static byte[] EncodeTile(byte[] img, int size, int x0, int y0)
{
var tile = new byte[Tile * Tile * 3];
for (int y = 0; y < Tile; y++) Buffer.BlockCopy(img, ((y0 + y) * size + x0) * 3, tile, y * Tile * 3, Tile * 3);
return Deflate(Dxt1.Encode(tile, Tile, Tile));
}
private static byte[] Deflate(byte[] data)
{
using var ms = new MemoryStream();
using (var z = new ZLibStream(ms, CompressionLevel.Optimal, leaveOpen: true)) z.Write(data);
return ms.ToArray();
}
/// <summary>Half the size of a square RGB image, each pixel the mean of four.</summary>
private static byte[] Downsample(byte[] src, int size)
{
int h = size / 2;
var d = new byte[(long)h * h * 3];
for (int y = 0; y < h; y++)
for (int x = 0; x < h; x++)
{
long a = ((long)(2 * y) * size + 2 * x) * 3, b = a + 3, cc = a + (long)size * 3, e = cc + 3;
long o = ((long)y * h + x) * 3;
d[o] = (byte)((src[a] + src[b] + src[cc] + src[e] + 2) >> 2);
d[o + 1] = (byte)((src[a + 1] + src[b + 1] + src[cc + 1] + src[e + 1] + 2) >> 2);
d[o + 2] = (byte)((src[a + 2] + src[b + 2] + src[cc + 2] + src[e + 2] + 2) >> 2);
}
return d;
}
// ── Putting it together ──────────────────────────────────────────────
private static void Assemble(Ctx c, int ppc, int worldTiles, int levels, string final, Action<string> log)
{
var first = new int[levels];
var cols = new int[levels];
int count = 0;
for (int k = 0; k < levels; k++) { first[k] = count; cols[k] = worldTiles >> k; count += cols[k] * cols[k]; }
var offsets = new ulong[count];
var lengths = new uint[count];
string dataFile = final + ".data.tmp";
long pos = 0;
var apexes = new byte[]?[c.ChunksPerSide * c.ChunksPerSide];
using (var data = new FileStream(dataFile, FileMode.Create, FileAccess.Write))
{
void Put(int level, int col, int row, byte[] blob)
{
int idx = first[level] + row * cols[level] + col;
offsets[idx] = (ulong)pos; lengths[idx] = (uint)blob.Length;
data.Write(blob);
pos += blob.Length;
}
// The chunks' own tiles, and their apexes.
foreach (string f in Directory.EnumerateFiles(c.Work, "chunk_*.bin").OrderBy(s => s, StringComparer.Ordinal))
{
string[] parts = Path.GetFileNameWithoutExtension(f).Split('_');
int cc = int.Parse(parts[1]), cr = int.Parse(parts[2]);
using var fs = File.OpenRead(f);
using var r = new BinaryReader(fs);
if (r.ReadUInt32() != 0x4B484352u) throw new InvalidDataException(f + " is not a chunk file"); // "RCHK"
uint n = r.ReadUInt32();
for (uint i = 0; i < n; i++)
{
int level = r.ReadByte(), col = r.ReadUInt16(), row = r.ReadUInt16();
byte[] blob = r.ReadBytes((int)r.ReadUInt32());
Put(level, col, row, blob);
}
apexes[cr * c.ChunksPerSide + cc] = r.ReadBytes(Tile * Tile * 3);
}
// The levels above the chunks, each tile the halved mean of four below it.
int side = c.ChunksPerSide;
var cur = apexes;
for (int k = c.ChunkLevels; k < levels; k++)
{
int ns = side / 2;
var next = new byte[ns * ns][];
for (int tr = 0; tr < ns; tr++)
for (int tc = 0; tc < ns; tc++)
{
var comp = new byte[Tile * 2 * Tile * 2 * 3];
for (int dy = 0; dy < 2; dy++)
for (int dx = 0; dx < 2; dx++)
{
byte[]? child = cur[(2 * tr + dy) * side + 2 * tc + dx];
if (child == null) continue;
for (int y = 0; y < Tile; y++)
Buffer.BlockCopy(child, y * Tile * 3, comp, ((dy * Tile + y) * Tile * 2 + dx * Tile) * 3, Tile * 3);
}
byte[] half = Downsample(comp, Tile * 2);
next[tr * ns + tc] = half;
Put(k, tc, tr, Deflate(Dxt1.Encode(half, Tile, Tile)));
}
cur = next; side = ns;
}
}
long headerSize = 4 + 6 * 4 + levels * 20 + 4 + (long)count * 12;
string tmp = final + ".tmp";
using (var fs = new FileStream(tmp, FileMode.Create, FileAccess.Write))
using (var w = new BinaryWriter(fs))
{
w.Write(new byte[] { (byte)'R', (byte)'M', (byte)'A', (byte)'P' });
w.Write(2u); w.Write((uint)Tile); w.Write((uint)levels); w.Write((uint)ppc);
w.Write(2048u); w.Write(2048u);
for (int k = 0; k < levels; k++)
{ w.Write((uint)(worldTiles * Tile >> k)); w.Write((uint)(worldTiles * Tile >> k)); w.Write((uint)cols[k]); w.Write((uint)cols[k]); w.Write((uint)first[k]); }
w.Write((uint)count);
for (int i = 0; i < count; i++) { w.Write(lengths[i] == 0 ? 0UL : offsets[i] + (ulong)headerSize); w.Write(lengths[i]); }
using var data = File.OpenRead(dataFile);
data.CopyTo(fs);
}
File.Move(tmp, final, overwrite: true);
File.Delete(dataFile);
int present = lengths.Count(l => l > 0);
log($"tiles: {present} of {count}");
}
// ── Look inside a map file: --rmap-png <file> --level k [--tiles c0,c1,r0,r1] --out <dir> ──────────────
public static int ExtractPng(string file, int level, string? tiles, string outDir, Action<string> log)
{
using var fs = File.OpenRead(file);
using var r = new BinaryReader(fs);
if (r.ReadUInt32() != 0x5041_4D52u) { log("not a map file"); return 1; }
uint version = r.ReadUInt32(); uint tile = r.ReadUInt32(), lv = r.ReadUInt32(), ppc = r.ReadUInt32(); r.ReadUInt32(); r.ReadUInt32();
var info = new (uint W, uint H, uint Cols, uint Rows, uint First)[lv];
for (int i = 0; i < lv; i++) info[i] = (r.ReadUInt32(), r.ReadUInt32(), r.ReadUInt32(), r.ReadUInt32(), r.ReadUInt32());
int count = (int)r.ReadUInt32();
var off = new ulong[count]; var len = new uint[count];
for (int i = 0; i < count; i++) { off[i] = r.ReadUInt64(); len[i] = r.ReadUInt32(); }
if (level < 0 || level >= lv) { log($"the file has levels 0..{lv - 1}"); return 1; }
var L = info[level];
int c0 = 0, c1 = (int)L.Cols - 1, r0 = 0, r1 = (int)L.Rows - 1;
if (tiles != null)
{
var p = tiles.Split(',', StringSplitOptions.TrimEntries);
if (p.Length != 4) { log("--tiles needs c0,c1,r0,r1"); return 1; }
c0 = int.Parse(p[0]); c1 = int.Parse(p[1]); r0 = int.Parse(p[2]); r1 = int.Parse(p[3]);
}
int w = (c1 - c0 + 1) * Tile, h = (r1 - r0 + 1) * Tile;
var img = new byte[(long)w * h * 3];
int shown = 0;
for (int row = r0; row <= r1; row++)
for (int col = c0; col <= c1; col++)
{
int idx = (int)L.First + row * (int)L.Cols + col;
if (len[idx] == 0) continue;
fs.Seek((long)off[idx], SeekOrigin.Begin);
var comp = r.ReadBytes((int)len[idx]);
byte[] raw;
using (var z = new ZLibStream(new MemoryStream(comp), CompressionMode.Decompress)) { var ms = new MemoryStream(); z.CopyTo(ms); raw = ms.ToArray(); }
byte[] rgb;
if (version == 2) rgb = Dxt1.Decode(raw, Tile, Tile);
else rgb = raw;
for (int y = 0; y < Tile; y++) Buffer.BlockCopy(rgb, y * Tile * 3, img, (((row - r0) * Tile + y) * w + (col - c0) * Tile) * 3, Tile * 3);
shown++;
}
Directory.CreateDirectory(outDir);
string png = Path.Combine(outDir, $"rmap_L{level}_{c0}-{c1}_{r0}-{r1}.png");
WorldMapRender.WritePngPublic(png, img, w, h);
log($"{shown} tiles, {w} x {h} px (level {level}, {L.W} px wide, {ppc} px per cell at level 0, version {version}) -> {png}");
return 0;
}
}

View file

@ -0,0 +1,344 @@
using System.Diagnostics;
using System.IO.Compression;
using RynthCore.TerrainData;
using RynthCore.Plugin.RynthAi.Raycasting;
namespace RynthNav.Baker;
// --map: renders Dereth top-down from client_cell_1.dat, the source image for RynthNav's world map.
// - Every landblock's 9x9 vertices go into one global grid (the east/north edge vertex of a landblock
// is the west/south edge vertex of its neighbour), so each pixel blends four real vertices and
// there are no seams at landblock borders.
// - Land is a bilinear blend of the vertices' terrain-type colours with a hillshade from the vertex
// heights; water is decided per pixel from the water share of the four vertices, so shorelines are
// crisp, not smeared. Roads (terrain-word bits 0-1) are tinted on top.
// - --ppc pixels per 24-unit cell (default 2: 4096x4096 for all of Dereth); --area x0,x1,y0,y1 (hex
// landblocks) renders a crop. North is at the top.
internal static class WorldMapRender
{
private const int Blocks = 256, Side = 8; // landblocks per axis, cells per landblock
private const int V = Blocks * Side + 1; // vertices per axis
private const float CellUnits = 24f;
// Terrain type indices (TerrainTextureType): 16..20 are water.
private static readonly (byte R, byte G, byte B)[] Land =
{
(140, 125, 110), // 0 BarrenRock
(110, 150, 70), // 1 Grassland
(225, 240, 250), // 2 Ice
( 60, 130, 55), // 3 LushGrass
( 85, 110, 70), // 4 MarshSparseSwamp
(110, 80, 55), // 5 MudRichDirt
( 60, 55, 65), // 6 ObsidianPlain
(150, 125, 85), // 7 PackedDirt
(135, 115, 75), // 8 PatchyDirt
(125, 150, 80), // 9 PatchyGrassland
(215, 190, 120), // 10 SandYellow
(170, 165, 150), // 11 SandGrey
(185, 165, 125), // 12 SandRockStrewn
(160, 120, 90), // 13 SedimentaryRock
(130, 120, 100), // 14 SemiBarrenRock
(245, 248, 252), // 15 Snow
( 0, 0, 0), // 16..20 water: WaterColour
( 0, 0, 0), ( 0, 0, 0), ( 0, 0, 0), ( 0, 0, 0),
( 44, 104, 50), // 21 forestfloor
( 0, 0, 0), // 22 FauxWaterRunning: counted as water by name
( 92, 120, 72), // 23 SeaSlime
(172, 112, 82), // 24 Argila
( 84, 52, 46), // 25 Volcano1
(112, 58, 42), // 26 Volcano2
(190, 215, 235), // 27 BlueIce
( 92, 128, 72), // 28 Moss
( 62, 94, 56), // 29 DarkMoss
(122, 96, 70), // 30 olthoi (hive resin)
(132, 116, 96), // 31 DesolateLands
};
private static readonly (byte R, byte G, byte B) RoadColour = (176, 152, 108);
private static (byte R, byte G, byte B) WaterColour(int t) => t switch
{
16 or 17 => (82, 142, 186), // running / standing fresh
18 or 19 => (60, 120, 168), // shallow sea
_ => (28, 66, 118), // deep sea (and open sea with no landblock)
};
public static int Run(TerrainSampler sampler, string outDir, int ppc, string? area, string acFolder, bool tiles = false, WorldMapVectors.Data? overlay = null, RynthCore2.Raycast.GeometryLoader? textureGeo = null, bool objects = false)
{
var pal = TerrainPalette.Load(acFolder);
var landRgb = new (byte R, byte G, byte B)[32];
var water = new bool[32];
for (int t = 0; t < 32; t++) { landRgb[t] = Land[t]; water[t] = t >= 16 && t <= 20; }
if (pal == null) Console.WriteLine("terrain palette: not found in the Region file; using the built-in colours");
else
{
Console.WriteLine($"terrain palette: {pal.Names.Length} types from the Region file");
for (int t = 0; t < Math.Min(32, pal.Names.Length); t++)
{
Console.WriteLine($" {t,2} {pal.Names[t],-28} 0x{pal.Argb[t]:X8}");
water[t] = pal.Names[t].Contains("Water", StringComparison.OrdinalIgnoreCase);
}
}
int x0 = 0, x1 = Blocks - 1, y0 = 0, y1 = Blocks - 1;
if (area != null)
{
var p = area.Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries);
if (p.Length != 4) { Console.Error.WriteLine("--area needs minX,maxX,minY,maxY (hex)"); return 1; }
x0 = Convert.ToInt32(p[0], 16); x1 = Convert.ToInt32(p[1], 16);
y0 = Convert.ToInt32(p[2], 16); y1 = Convert.ToInt32(p[3], 16);
if (x0 > x1 || y0 > y1 || x0 < 0 || y0 < 0 || x1 >= Blocks || y1 >= Blocks) { Console.Error.WriteLine("--area out of range 00..FF"); return 1; }
}
ppc = Math.Clamp(ppc, 1, 24);
var sw = Stopwatch.StartNew();
// One landblock of margin so edge pixels in the crop still blend with real neighbours.
WorldGrid grid = WorldGrid.Load(sampler, x0 - 1, x1 + 1, y0 - 1, y1 + 1, m => Console.WriteLine($"{m} ({sw.Elapsed.TotalSeconds:F0}s)"));
byte[] type = grid.Type, road = grid.Road;
long[] seen = grid.TypeCounts();
Console.WriteLine($"read {grid.Loaded} landblocks in {sw.Elapsed.TotalSeconds:F1}s; terrain types seen:");
for (int t = 0; t < 32; t++) if (seen[t] > 0) Console.WriteLine($" type {t,2}: {seen[t]} vertices");
float[] shade = grid.Shade(textureGeo != null ? 1.3f : 2.2f); // exaggeration: Dereth's relief is gentle (less under real textures)
int cx0 = x0 * Side, cy0 = y0 * Side; // crop origin in cells
int wCells = (x1 - x0 + 1) * Side, hCells = (y1 - y0 + 1) * Side;
int W = wCells * ppc, H = hCells * ppc;
var rgb = new byte[(long)W * H * 3];
Console.WriteLine($"rendering {W}x{H} ({ppc} px per cell)...");
TexturedTerrain? tex = textureGeo != null ? TexturedTerrain.Load(textureGeo, Console.WriteLine) : null;
if (tex != null)
{
// The game's own look: each cell blended from its textures (TexturedTerrain), lit by the slope.
int cellsW = (x1 - x0 + 1) * Side, cellsH = (y1 - y0 + 1) * Side;
Parallel.For(0, cellsH, cj =>
{
int gy = cy0 + (cellsH - 1 - cj); // north first
for (int ci = 0; ci < cellsW; ci++) tex.PaintCell(cx0 + ci, gy, type, road, shade, V, ppc, rgb, W, ci * ppc, cj * ppc);
});
Console.WriteLine($"terrain painted ({sw.Elapsed.TotalSeconds:F1}s)");
if (objects)
{
// Buildings, walls and scenery from above, over the ground.
var raster = new ObjectRaster(rgb, W, H, cx0, cy0, ppc, new ObjectRaster.SurfaceStore(tex.Decoder));
float GroundZ(float wx, float wy) => textureGeo!.GetTerrainZWorld(wx, wy);
for (int lx = x0; lx <= x1; lx++)
for (int ly = y0; ly <= y1; ly++)
{
uint key = (uint)((lx << 8) | ly);
raster.Add(textureGeo!.GetTexturedStaticObjects(key));
raster.Add(textureGeo.GetTexturedScatter(key, GroundZ));
}
Console.WriteLine($"objects drawn: {raster.Triangles} triangles ({sw.Elapsed.TotalSeconds:F1}s)");
}
}
else
{
Parallel.For(0, H, py =>
{
float fy = cy0 + (H - 1 - py + 0.5f) / ppc; // north at the top
int gy0 = Math.Min((int)fy, V - 2);
float ty = fy - gy0;
for (int px = 0; px < W; px++)
{
float fx = cx0 + (px + 0.5f) / ppc;
int gx0 = Math.Min((int)fx, V - 2);
float tx = fx - gx0;
float wWater = 0, rW = 0, gW = 0, bW = 0; // water share + weighted water colour
float wLand = 0, rL = 0, gL = 0, bL = 0, shd = 0, rd = 0;
for (int c = 0; c < 4; c++)
{
int ox = c & 1, oy = c >> 1;
float wt = (ox == 0 ? 1 - tx : tx) * (oy == 0 ? 1 - ty : ty);
int gi = (gy0 + oy) * V + gx0 + ox;
int t = type[gi];
if (t == 255 || water[t])
{
var wc = WaterColour(t == 255 ? 20 : t);
wWater += wt; rW += wc.R * wt; gW += wc.G * wt; bW += wc.B * wt;
}
else
{
var lc = landRgb[t];
wLand += wt; rL += lc.R * wt; gL += lc.G * wt; bL += lc.B * wt;
shd += shade[gi] * wt;
rd += (road[gi] != 0 ? 1f : 0f) * wt;
}
}
float r, g, b;
if (wWater >= 0.5f)
{
r = rW / wWater; g = gW / wWater; b = bW / wWater;
}
else
{
float inv = 1f / wLand;
r = rL * inv; g = gL * inv; b = bL * inv;
float s = shd * inv;
float road01 = rd * inv;
if (road01 > 0.5f && ppc >= 2)
{
float a = Math.Clamp((road01 - 0.5f) * 2f, 0f, 0.85f);
r += (RoadColour.R - r) * a; g += (RoadColour.G - g) * a; b += (RoadColour.B - b) * a;
}
r *= s; g *= s; b *= s;
if (wWater > 0f && wWater > 0.35f) // a darker rim just inside the shoreline
{
float a = (wWater - 0.35f) / 0.15f * 0.25f;
r *= 1 - a; g *= 1 - a; b *= 1 - a;
}
}
long o = ((long)py * W + px) * 3;
rgb[o] = (byte)Math.Clamp(r, 0, 255);
rgb[o + 1] = (byte)Math.Clamp(g, 0, 255);
rgb[o + 2] = (byte)Math.Clamp(b, 0, 255);
}
});
}
if (overlay != null && area != null) WorldMapVectors.DrawOverlay(rgb, W, H, cx0, cy0, ppc, overlay); // a preview of the vector layers
OutputGuard.Check(outDir);
Directory.CreateDirectory(outDir);
string file = Path.Combine(outDir, area == null ? "world_map.png" : $"world_map_{x0:X2}-{x1:X2}_{y0:X2}-{y1:X2}.png");
WritePng(file, rgb, W, H);
Console.WriteLine($"wrote {file} ({new FileInfo(file).Length / 1024} KB) in {sw.Elapsed.TotalSeconds:F1}s");
if (tiles)
{
if (area != null || W != H || W % TileSize != 0 || (W / TileSize & (W / TileSize - 1)) != 0)
{ Console.Error.WriteLine("--map-tiles needs the whole world at a --ppc that makes a square power-of-two number of 256 px tiles (ppc 2 = 4096 px)"); return 1; }
string rmap = Path.Combine(outDir, "worldmap.rmap");
WriteRmap(rmap, rgb, W, H, ppc);
Console.WriteLine($"wrote {rmap} ({new FileInfo(rmap).Length / 1024} KB) in {sw.Elapsed.TotalSeconds:F1}s");
}
return 0;
}
// ── worldmap.rmap: the whole map as a pyramid of 256 px tiles, one file ───────────────────
// All little-endian. Header: "RMAP", u32 version (1), u32 tile size, u32 level count, u32 pixels per
// cell at level 0, u32 cells wide, u32 cells high; then per level u32 width, height, columns, rows,
// first tile number; then u32 tile count and per tile u64 file offset + u32 length; then the tiles,
// each the zlib stream of its 256x256 RGB pixels (row 0 = north). Level 0 is the full-resolution
// image, each level above it half the size, down to one tile. Tiles are numbered level by level,
// row by row. The engine's WorldMapTiles reads this.
public const int TileSize = 256;
private static void WriteRmap(string file, byte[] rgb, int W, int H, int ppc0)
{
var levels = new List<(byte[] Px, int W, int H)> { (rgb, W, H) };
while (levels[^1].W > TileSize) levels.Add(Half(levels[^1]));
var jobs = new List<(int Level, int Col, int Row)>();
var first = new int[levels.Count];
for (int l = 0; l < levels.Count; l++)
{
first[l] = jobs.Count;
for (int r = 0; r < levels[l].H / TileSize; r++)
for (int c = 0; c < levels[l].W / TileSize; c++) jobs.Add((l, c, r));
}
var blobs = new byte[jobs.Count][];
Parallel.For(0, jobs.Count, i =>
{
var (l, c, r) = jobs[i];
var (px, w, _) = levels[l];
var raw = new byte[TileSize * TileSize * 3];
for (int y = 0; y < TileSize; y++)
Buffer.BlockCopy(px, ((r * TileSize + y) * w + c * TileSize) * 3, raw, y * TileSize * 3, TileSize * 3);
using var ms = new MemoryStream();
using (var z = new ZLibStream(ms, CompressionLevel.Optimal, leaveOpen: true)) z.Write(raw);
blobs[i] = ms.ToArray();
});
long headerSize = 4 + 6 * 4 + levels.Count * 5 * 4 + 4 + (long)jobs.Count * 12;
string tmp = file + ".tmp";
using (var fs = new FileStream(tmp, FileMode.Create, FileAccess.Write))
using (var bw = new BinaryWriter(fs))
{
bw.Write(new byte[] { (byte)'R', (byte)'M', (byte)'A', (byte)'P' });
bw.Write(1u); bw.Write((uint)TileSize); bw.Write((uint)levels.Count); bw.Write((uint)ppc0);
bw.Write((uint)(W / ppc0)); bw.Write((uint)(H / ppc0));
for (int l = 0; l < levels.Count; l++)
{
bw.Write((uint)levels[l].W); bw.Write((uint)levels[l].H);
bw.Write((uint)(levels[l].W / TileSize)); bw.Write((uint)(levels[l].H / TileSize));
bw.Write((uint)first[l]);
}
bw.Write((uint)jobs.Count);
long off = headerSize;
foreach (byte[] b in blobs) { bw.Write((ulong)off); bw.Write((uint)b.Length); off += b.Length; }
foreach (byte[] b in blobs) bw.Write(b);
}
File.Move(tmp, file, overwrite: true);
Console.WriteLine($" {levels.Count} levels, {jobs.Count} tiles");
}
private static (byte[] Px, int W, int H) Half((byte[] Px, int W, int H) s)
{
int w = s.W / 2, h = s.H / 2;
var d = new byte[w * h * 3];
Parallel.For(0, h, y =>
{
for (int x = 0; x < w; x++)
for (int k = 0; k < 3; k++)
{
int a = ((2 * y) * s.W + 2 * x) * 3 + k, b = a + 3, c = a + s.W * 3, e = c + 3;
d[(y * w + x) * 3 + k] = (byte)((s.Px[a] + s.Px[b] + s.Px[c] + s.Px[e] + 2) >> 2);
}
});
return (d, w, h);
}
// ── Minimal PNG writer (8-bit RGB, no filter): no imaging dependency in the baker ──────────
internal static void WritePngPublic(string path, byte[] rgb, int w, int h) => WritePng(path, rgb, w, h);
private static void WritePng(string path, byte[] rgb, int w, int h)
{
string tmp = path + ".tmp";
using (var fs = new FileStream(tmp, FileMode.Create, FileAccess.Write))
{
fs.Write(new byte[] { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A });
var ihdr = new byte[13];
BE(ihdr, 0, (uint)w); BE(ihdr, 4, (uint)h);
ihdr[8] = 8; ihdr[9] = 2; // 8 bits, RGB
Chunk(fs, "IHDR", ihdr);
using var raw = new MemoryStream();
using (var z = new ZLibStream(raw, CompressionLevel.Optimal, leaveOpen: true))
{
var zero = new byte[] { 0 };
for (int y = 0; y < h; y++)
{
z.Write(zero); // filter type 0
z.Write(rgb, (int)((long)y * w * 3), w * 3);
}
}
Chunk(fs, "IDAT", raw.ToArray());
Chunk(fs, "IEND", Array.Empty<byte>());
}
File.Move(tmp, path, overwrite: true);
}
private static void BE(byte[] b, int o, uint v) { b[o] = (byte)(v >> 24); b[o + 1] = (byte)(v >> 16); b[o + 2] = (byte)(v >> 8); b[o + 3] = (byte)v; }
private static void Chunk(Stream s, string type, byte[] data)
{
var len = new byte[4]; BE(len, 0, (uint)data.Length); s.Write(len);
var td = new byte[4 + data.Length];
for (int i = 0; i < 4; i++) td[i] = (byte)type[i];
Buffer.BlockCopy(data, 0, td, 4, data.Length);
s.Write(td);
var crc = new byte[4]; BE(crc, 0, Crc32(td)); s.Write(crc);
}
private static uint[]? _crcTable;
private static uint Crc32(byte[] d)
{
if (_crcTable == null)
{
var t = new uint[256];
for (uint n = 0; n < 256; n++) { uint c = n; for (int k = 0; k < 8; k++) c = (c & 1) != 0 ? 0xEDB88320u ^ (c >> 1) : c >> 1; t[n] = c; }
_crcTable = t;
}
uint crc = 0xFFFFFFFFu;
foreach (byte b in d) crc = _crcTable[(crc ^ b) & 0xFF] ^ (crc >> 8);
return crc ^ 0xFFFFFFFFu;
}
}

View file

@ -0,0 +1,256 @@
using System.Numerics;
using Vector3 = System.Numerics.Vector3;
using RynthCore.Plugin.RynthAi.Raycasting;
using RynthCore.TerrainData;
namespace RynthNav.Baker;
// --map-vectors: the World Map's vector layers, worldmap.vec, drawn over the tiles when you zoom in.
// - Buildings: each landblock's building list (LandBlockInfo, file 0xLLLLFFFE in the cell dat), the
// model's triangles from GeometryLoader.GetTexturedModel, their ground outline (convex hull, cut
// down to at most MaxHullPoints corners) placed by the building's frame. Outlines are in map cells.
// - Roads: the terrain words' road bits (vertex bits 0-1): a segment between every two neighbouring
// road vertices (east, north, and both diagonals), in whole cells.
// File (little-endian): "RVEC", u32 version (1), u32 building count, u32 road segment count; per
// building u8 corner count then that many (f32 x, f32 y) in cells; per road segment u16 x0, y0, x1, y1
// (cells). The engine's WorldMapVectors reads this.
internal static class WorldMapVectors
{
private const int Blocks = 256, Side = 8, V = Blocks * Side + 1;
private const int MaxHullPoints = 10;
public sealed class Data
{
public readonly List<Vector2[]> Buildings = new();
public readonly List<(ushort X0, ushort Y0, ushort X1, ushort Y1)> Roads = new();
}
public static Data Build(TerrainSampler sampler, RynthCore2.Raycast.GeometryLoader geo, Action<string> log)
{
var d = new Data();
BuildRoads(sampler, d, log);
BuildBuildings(geo, d, log);
return d;
}
// ── Roads ────────────────────────────────────────────────────────────
private static void BuildRoads(TerrainSampler sampler, Data d, Action<string> log)
{
var road = new byte[V * V];
int loaded = 0;
for (int lx = 0; lx < Blocks; lx++)
for (int ly = 0; ly < Blocks; ly++)
{
LandblockData? lb = null;
try { lb = sampler.LoadLandblock((uint)((lx << 8) | ly)); } catch { }
if (lb?.TerrainWords == null) continue;
loaded++;
for (int ix = 0; ix <= Side; ix++)
for (int iy = 0; iy <= Side; iy++)
road[(ly * Side + iy) * V + lx * Side + ix] = (byte)(lb.TerrainWords[ix * 9 + iy] & 3);
}
int verts = 0;
for (int y = 0; y < V; y++)
for (int x = 0; x < V; x++)
{
if (road[y * V + x] == 0) continue;
verts++;
// East, north, north-east, north-west: each pair once.
if (x + 1 < V && road[y * V + x + 1] != 0) d.Roads.Add(((ushort)x, (ushort)y, (ushort)(x + 1), (ushort)y));
if (y + 1 < V && road[(y + 1) * V + x] != 0) d.Roads.Add(((ushort)x, (ushort)y, (ushort)x, (ushort)(y + 1)));
if (x + 1 < V && y + 1 < V && road[(y + 1) * V + x + 1] != 0) d.Roads.Add(((ushort)x, (ushort)y, (ushort)(x + 1), (ushort)(y + 1)));
if (x > 0 && y + 1 < V && road[(y + 1) * V + x - 1] != 0) d.Roads.Add(((ushort)x, (ushort)y, (ushort)(x - 1), (ushort)(y + 1)));
}
log($"roads: {verts} road vertices in {loaded} landblocks, {d.Roads.Count} segments");
}
// ── Buildings ────────────────────────────────────────────────────────
private static void BuildBuildings(RynthCore2.Raycast.GeometryLoader geo, Data d, Action<string> log)
{
var hulls = new Dictionary<uint, Vector2[]?>(); // model -> its outline in model space
int blocksWith = 0, noHull = 0;
for (int lx = 0; lx < Blocks; lx++)
for (int ly = 0; ly < Blocks; ly++)
{
uint lb = (uint)((lx << 8) | ly);
byte[]? data = null;
try { data = geo.CellDat.GetFileData((lb << 16) | 0xFFFE); } catch { }
if (data == null || data.Length < 16) continue;
int count = 0;
foreach (var (model, origin, rot) in ReadBuildings(data))
{
if (!hulls.TryGetValue(model, out Vector2[]? hull)) { hull = ModelOutline(geo, model); hulls[model] = hull; }
if (hull == null || hull.Length < 3) { noHull++; continue; }
var pts = new Vector2[hull.Length];
for (int i = 0; i < hull.Length; i++)
{
Vector3 p = Vector3.Transform(new Vector3(hull[i].X, hull[i].Y, 0), rot) + origin;
// Landblock-local yards to map cells (24 yards each); the landblock is 8 cells wide.
pts[i] = new Vector2(lx * 8f + p.X / 24f, ly * 8f + p.Y / 24f);
}
d.Buildings.Add(pts);
count++;
}
if (count > 0) blocksWith++;
}
log($"buildings: {d.Buildings.Count} in {blocksWith} landblocks ({hulls.Count} models, {noHull} with no outline)");
}
/// <summary>The buildings in a LandBlockInfo: model id, origin and rotation (the layout GeometryLoader.ParseLandblockObjects reads).</summary>
private static IEnumerable<(uint Model, Vector3 Origin, Quaternion Rot)> ReadBuildings(byte[] data)
{
uint numObjects = BitConverter.ToUInt32(data, 8);
if (numObjects > 5000) numObjects = 5000;
int off = 12 + (int)numObjects * 32;
if (off + 4 > data.Length) yield break;
ushort numBuildings = BitConverter.ToUInt16(data, off);
off += 4;
for (int b = 0; b < numBuildings && off + 36 <= data.Length; b++)
{
uint model = BitConverter.ToUInt32(data, off);
var origin = new Vector3(BitConverter.ToSingle(data, off + 4), BitConverter.ToSingle(data, off + 8), BitConverter.ToSingle(data, off + 12));
float rw = BitConverter.ToSingle(data, off + 16), rx = BitConverter.ToSingle(data, off + 20),
ry = BitConverter.ToSingle(data, off + 24), rz = BitConverter.ToSingle(data, off + 28);
off += 36;
if (off + 4 > data.Length) yield break;
uint numPortals = BitConverter.ToUInt32(data, off);
off += 4;
for (uint p = 0; p < numPortals && off + 8 <= data.Length; p++)
{
ushort numStabs = BitConverter.ToUInt16(data, off + 6);
int psz = 8 + numStabs * 2; psz += (4 - (psz & 3)) & 3;
off += psz;
}
if (float.IsNaN(origin.X) || Math.Abs(origin.X) > 50000) continue;
yield return (model, origin, new Quaternion(rx, ry, rz, rw));
}
}
/// <summary>The ground outline of a model: the hull of its triangles' x, y, cut to a few corners. Null when it has no triangles.</summary>
private static Vector2[]? ModelOutline(RynthCore2.Raycast.GeometryLoader geo, uint model)
{
List<RynthCore2.Raycast.GeometryLoader.TexTri> tris;
try { tris = geo.GetTexturedModel(model); } catch { return null; }
if (tris.Count == 0) return null;
var pts = new List<Vector2>(tris.Count * 3);
foreach (var t in tris) { pts.Add(new Vector2(t.A.X, t.A.Y)); pts.Add(new Vector2(t.B.X, t.B.Y)); pts.Add(new Vector2(t.C.X, t.C.Y)); }
Vector2[] hull = Hull(pts);
return hull.Length <= MaxHullPoints ? hull : Reduce(hull, MaxHullPoints);
}
/// <summary>Convex hull (Andrew's monotone chain), counter-clockwise.</summary>
private static Vector2[] Hull(List<Vector2> pts)
{
pts.Sort((a, b) => a.X != b.X ? a.X.CompareTo(b.X) : a.Y.CompareTo(b.Y));
var u = new List<Vector2>();
foreach (Vector2 p in pts)
{
if (u.Count > 0 && u[^1] == p) continue;
u.Add(p);
}
if (u.Count < 3) return u.ToArray();
var h = new Vector2[2 * u.Count];
int k = 0;
float Cross(Vector2 o, Vector2 a, Vector2 b) => (a.X - o.X) * (b.Y - o.Y) - (a.Y - o.Y) * (b.X - o.X);
for (int i = 0; i < u.Count; i++) { while (k >= 2 && Cross(h[k - 2], h[k - 1], u[i]) <= 0) k--; h[k++] = u[i]; }
for (int i = u.Count - 2, t = k + 1; i >= 0; i--) { while (k >= t && Cross(h[k - 2], h[k - 1], u[i]) <= 0) k--; h[k++] = u[i]; }
return h.AsSpan(0, k - 1).ToArray();
}
/// <summary>Drops the corner whose removal changes the area least, until <paramref name="max"/> are left.</summary>
private static Vector2[] Reduce(Vector2[] hull, int max)
{
var l = new List<Vector2>(hull);
while (l.Count > max)
{
int best = 0; float bestArea = float.MaxValue;
for (int i = 0; i < l.Count; i++)
{
Vector2 a = l[(i + l.Count - 1) % l.Count], b = l[i], c = l[(i + 1) % l.Count];
float area = MathF.Abs((b.X - a.X) * (c.Y - a.Y) - (b.Y - a.Y) * (c.X - a.X)) * 0.5f;
if (area < bestArea) { bestArea = area; best = i; }
}
l.RemoveAt(best);
}
return l.ToArray();
}
// ── File ─────────────────────────────────────────────────────────────
public static void Write(string file, Data d)
{
string tmp = file + ".tmp";
using (var fs = new FileStream(tmp, FileMode.Create, FileAccess.Write))
using (var w = new BinaryWriter(fs))
{
w.Write(new byte[] { (byte)'R', (byte)'V', (byte)'E', (byte)'C' });
w.Write(1u); w.Write((uint)d.Buildings.Count); w.Write((uint)d.Roads.Count);
foreach (Vector2[] b in d.Buildings)
{
w.Write((byte)b.Length);
foreach (Vector2 p in b) { w.Write(p.X); w.Write(p.Y); }
}
foreach (var r in d.Roads) { w.Write(r.X0); w.Write(r.Y0); w.Write(r.X1); w.Write(r.Y1); }
}
File.Move(tmp, file, overwrite: true);
}
// ── Preview: the vectors drawn over a crop of the terrain render, to check them by eye ────
public static void DrawOverlay(byte[] rgb, int w, int h, int cx0, int cy0, int ppc, Data d)
{
// Pixel of a map cell position: x grows east; image row 0 is the north edge.
Vector2 Px(float cx, float cy) => new((cx - cx0) * ppc, h - (cy - cy0) * ppc);
foreach (var r in d.Roads)
{
Vector2 a = Px(r.X0, r.Y0), b = Px(r.X1, r.Y1);
if (a.X < -4 || b.X < -4 || a.Y < -4 || b.Y < -4 || a.X > w + 4 || b.X > w + 4 || a.Y > h + 4 || b.Y > h + 4) continue;
Line(rgb, w, h, a, b, (230, 205, 120), Math.Max(1, ppc / 5));
}
foreach (Vector2[] bld in d.Buildings)
{
var poly = new Vector2[bld.Length];
bool any = false;
for (int i = 0; i < bld.Length; i++) { poly[i] = Px(bld[i].X, bld[i].Y); if (poly[i].X >= 0 && poly[i].X < w && poly[i].Y >= 0 && poly[i].Y < h) any = true; }
if (!any) continue;
Fill(rgb, w, h, poly, (150, 70, 60));
for (int i = 0; i < poly.Length; i++) Line(rgb, w, h, poly[i], poly[(i + 1) % poly.Length], (40, 20, 20), 1);
}
}
private static void Plot(byte[] rgb, int w, int h, int x, int y, (byte R, byte G, byte B) c)
{
if ((uint)x >= (uint)w || (uint)y >= (uint)h) return;
long o = ((long)y * w + x) * 3;
rgb[o] = c.R; rgb[o + 1] = c.G; rgb[o + 2] = c.B;
}
private static void Line(byte[] rgb, int w, int h, Vector2 a, Vector2 b, (byte R, byte G, byte B) c, int thick)
{
float len = Vector2.Distance(a, b);
int steps = Math.Max(1, (int)(len * 1.5f));
for (int i = 0; i <= steps; i++)
{
Vector2 p = Vector2.Lerp(a, b, i / (float)steps);
for (int dx = -(thick - 1) / 2; dx <= thick / 2; dx++)
for (int dy = -(thick - 1) / 2; dy <= thick / 2; dy++)
Plot(rgb, w, h, (int)MathF.Round(p.X) + dx, (int)MathF.Round(p.Y) + dy, c);
}
}
private static void Fill(byte[] rgb, int w, int h, Vector2[] poly, (byte R, byte G, byte B) c)
{
float minY = poly.Min(p => p.Y), maxY = poly.Max(p => p.Y);
for (int y = Math.Max(0, (int)MathF.Floor(minY)); y <= Math.Min(h - 1, (int)MathF.Ceiling(maxY)); y++)
{
var xs = new List<float>();
for (int i = 0; i < poly.Length; i++)
{
Vector2 a = poly[i], b = poly[(i + 1) % poly.Length];
if ((a.Y <= y + 0.5f && b.Y > y + 0.5f) || (b.Y <= y + 0.5f && a.Y > y + 0.5f))
xs.Add(a.X + (y + 0.5f - a.Y) / (b.Y - a.Y) * (b.X - a.X));
}
xs.Sort();
for (int i = 0; i + 1 < xs.Count; i += 2)
for (int x = (int)MathF.Round(xs[i]); x <= (int)MathF.Round(xs[i + 1]); x++) Plot(rgb, w, h, x, y, c);
}
}
}

View file

@ -39,6 +39,11 @@ internal static class Program
Run(nameof(PathGoesRoundAPortal), PathGoesRoundAPortal);
Run(nameof(TripWalkFromTileFiles), TripWalkFromTileFiles);
Run(nameof(RealTripWalk), RealTripWalk);
Run(nameof(MeshViewFloorAndWalls), MeshViewFloorAndWalls);
Run(nameof(MeshViewEmitBudgetAndFrame), MeshViewEmitBudgetAndFrame);
Run(nameof(RealMeshView), RealMeshView);
Run(nameof(DungeonFileAndLayer), DungeonFileAndLayer);
Run(nameof(RealDungeons), RealDungeons);
}
finally { try { Directory.Delete(_root, true); } catch { } }
Console.WriteLine();
@ -426,6 +431,285 @@ internal static class Program
Check(own != null && Math.Abs(own[^1].X - 95) < 3, "walking into that portal: it's the goal, not avoided");
}
// ── The navmesh view (NavMeshView) ───────────────────────────────────────────
private sealed class TriSink : RynthCore.Plugin.Shared.INav3DSink
{
public readonly List<(float X1, float Y1, float Z1, float X2, float Y2, float Z2, float X3, float Y3, float Z3, uint Color)> Tris = new();
public int Lines;
public void Line(float x1, float y1, float z1, float x2, float y2, float z2, float t, uint c) => Lines++;
public void Triangle(float x1, float y1, float z1, float x2, float y2, float z2, float x3, float y3, float z3, uint c)
=> Tris.Add((x1, y1, z1, x2, y2, z2, x3, y3, z3, c));
}
private static void MeshViewFloorAndWalls()
{
// Two floors with a 40 m gap between them (x 70..110): green on the floors, nothing in the gap,
// red walls along the lips of the gap (and the floors' outer edges).
string dir = Bake("meshview", (10, 10, 70, 180), (110, 10, 180, 180));
var t = NavMeshView.BuildTile(0, ReadTile(dir, 0));
Check(t.FloorCount > 0 && t.WallCount > 0, $"floor and walls found ({t.FloorCount} triangles, {t.WallCount} wall edges)");
bool inGap = false; float minY = float.MaxValue, maxY = float.MinValue;
for (int k = 0; k < t.FloorCount; k++)
for (int v = 0; v < 3; v++)
{
float x = t.Floor[k * 9 + v * 3], y = t.Floor[k * 9 + v * 3 + 1];
if (x > 71 && x < 109) inGap = true;
minY = Math.Min(minY, y); maxY = Math.Max(maxY, y);
}
Check(!inGap, "no floor triangle reaches into the gap");
Check(minY > -1 && maxY < 1, $"the floor lies at the floor's height ({minY:F2}..{maxY:F2})");
// Wall edges along the gap: the west lip (x about 68, the floor shrunk by the 2 m body radius) and the east lip (about 112).
int west = 0, east = 0;
for (int k = 0; k < t.WallCount; k++)
{
float mx = (t.Walls[k * 6] + t.Walls[k * 6 + 3]) / 2, mz = (t.Walls[k * 6 + 2] + t.Walls[k * 6 + 5]) / 2;
if (mx > 60 && mx < 71 && mz > 12 && mz < 178) west++;
if (mx > 109 && mx < 120 && mz > 12 && mz < 178) east++;
}
Check(west > 0 && east > 0, $"walls stand along both lips of the gap (west {west}, east {east})");
// Every wall edge is on the floor's edge, none out in the middle of a floor.
bool stray = false;
for (int k = 0; k < t.WallCount; k++)
{
float mx = (t.Walls[k * 6] + t.Walls[k * 6 + 3]) / 2, mz = (t.Walls[k * 6 + 2] + t.Walls[k * 6 + 5]) / 2;
bool nearEdge = Math.Abs(mx - 68) < 3 || Math.Abs(mx - 112) < 3 || Math.Abs(mx - 12) < 3 || Math.Abs(mx - 178) < 3
|| Math.Abs(mz - 12) < 3 || Math.Abs(mz - 178) < 3;
if (!nearEdge) stray = true;
}
Check(!stray, "no wall edge inside a floor");
}
private static void MeshViewEmitBudgetAndFrame()
{
string dir = Bake("meshview2", (10, 10, 70, 180), (110, 10, 180, 180));
DtMeshData md = ReadTile(dir, 0);
var view = new NavMeshView();
view.Register(0, md);
var big = new NavMeshView.Options(500f, 100000, true, true);
var all = new TriSink();
int n = view.Emit(all, 40, 100, 0, big);
var tile = NavMeshView.BuildTile(0, md);
Check(n == tile.FloorCount + tile.WallCount * 2 && all.Tris.Count == n, $"everything in range is drawn ({n} = {tile.FloorCount} floor + 2 x {tile.WallCount} walls)");
Check(all.Tris.Any(x => x.Color == NavMeshView.DefaultFloorColor) && all.Tris.Any(x => x.Color == NavMeshView.DefaultWallColor), "green and red both drawn");
float meshY = tile.Floor[1]; // the mesh surface sits a voxel above the input floor
Check(all.Tris.Where(x => x.Color == NavMeshView.DefaultFloorColor).All(x => Math.Abs(x.Y1 - (meshY + 0.15f)) < 0.01f), "floor is lifted 15 cm off the mesh");
float wallTop = all.Tris.Where(x => x.Color == NavMeshView.DefaultWallColor).Max(x => Math.Max(x.Y1, Math.Max(x.Y2, x.Y3)));
Check(Math.Abs(wallTop - (meshY + 0.15f + 1.5f)) < 0.01f, $"walls stand 1.5 m high ({wallTop - meshY - 0.15f:F2})");
// Radius: a small circle at the west floor leaves the east floor out.
var near = new TriSink();
view.Emit(near, 30, 100, 0, new NavMeshView.Options(20f, 100000, true, true));
Check(near.Tris.Count > 0 && near.Tris.Count < n && near.Tris.All(x => x.X1 < 100), "a small radius draws only what is near");
// The cap holds, and walls survive it (nearest first, walls favoured).
var capped = new TriSink();
int c = view.Emit(capped, 66, 100, 0, new NavMeshView.Options(500f, 40, true, true));
Check(c <= 40 && c > 30, $"a 40-triangle budget draws about 40 ({c})");
Check(capped.Tris.Any(x => x.Color == NavMeshView.DefaultWallColor), "walls are kept under the cap");
var wallsOnly = new TriSink();
view.Emit(wallsOnly, 40, 100, 0, new NavMeshView.Options(500f, 100000, false, true));
Check(wallsOnly.Tris.Count > 0 && wallsOnly.Tris.All(x => x.Color == NavMeshView.DefaultWallColor), "walls alone");
var floorOnly = new TriSink();
view.Emit(floorOnly, 40, 100, 0, new NavMeshView.Options(500f, 100000, true, false));
Check(floorOnly.Tris.Count == tile.FloorCount && floorOnly.Tris.All(x => x.Color == NavMeshView.DefaultFloorColor), "floor alone");
// Frame: the same tile registered as landblock 0x0100 (east of the first), character at world x = 192 + 40.
string dir2 = Bake("meshview3", (192 + 10, 10, 192 + 70, 180), (192 + 110, 10, 192 + 180, 180));
var shifted = new NavMeshView();
shifted.Register(0x0100, ReadTile(dir2, 0x0100));
var s = new TriSink();
int sn = shifted.Emit(s, 192 + 40, 100, 0, big);
Check(sn == n, "the same floors one landblock east draw the same");
Check(Math.Abs(s.Tris.Min(x => x.X1) - all.Tris.Min(x => x.X1)) < 0.01f, "positions are in the character's landblock (X = east metres)");
// ...and from the next landblock over (character at world x = 192 + 4): the tile is one landblock west of the character's.
var west = new TriSink();
shifted.Emit(west, 192 * 2 + 4, 100, 0, new NavMeshView.Options(500f, 100000, true, true));
Check(west.Tris.Count == 0 || west.Tris.Min(x => x.X1) < 0, "a tile in the landblock to the west is drawn at negative X");
// The pick follows the character: moving 50 m re-picks.
var moved = new TriSink();
int a1 = view.Emit(moved, 30, 100, 0, new NavMeshView.Options(20f, 100000, true, true));
moved.Tris.Clear();
int a2 = view.Emit(moved, 150, 100, 0, new NavMeshView.Options(20f, 100000, true, true));
Check(a1 > 0 && a2 > 0 && moved.Tris.All(x => x.X1 > 100), "after moving to the east floor, it is the east floor that is drawn");
view.Unregister(0);
moved.Tris.Clear();
Check(view.Emit(moved, 150, 100, 0, big) == 0, "an unloaded tile is no longer drawn");
}
/// <summary>
/// A dungeon file: tiles on a shifted frame (mesh = local + shift) that read back, draw in the character's
/// landblock-local frame (negative x/y included) and stay apart from the outdoor tiles.
/// </summary>
private static void DungeonFileAndLayer()
{
// A floor at mesh x 10..70, y 10..180 with shift (192, 192): landblock-local x -182..-122, y -182..-12.
string dir = Bake("dun1", (10, 10, 70, 180));
DtMeshData md = ReadTile(dir, 0);
string file = Path.Combine(_root, DungeonTileFile.FileName(0x0505));
DungeonTileFile.Write(file, 192, 192, new[] { md });
var back = DungeonTileFile.Read(file);
Check(back != null && back.ShiftX == 192 && back.ShiftY == 192 && back.Tiles.Count == 1, "the dungeon file reads back");
Check(back != null && back.Tiles[0].header.polyCount == md.header.polyCount && back.Tiles[0].header.x == 0, "its tile is intact");
Check(DungeonTileFile.Read(Path.Combine(_root, "nonexistent.tile")) == null, "a missing file is null, not a throw");
File.WriteAllBytes(Path.Combine(_root, "junk.tile"), new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 });
Check(DungeonTileFile.Read(Path.Combine(_root, "junk.tile")) == null, "junk is null");
byte[] cut = File.ReadAllBytes(file); File.WriteAllBytes(Path.Combine(_root, "cut.tile"), cut.AsSpan(0, cut.Length / 2).ToArray());
Check(DungeonTileFile.Read(Path.Combine(_root, "cut.tile")) == null, "a cut-short file is null");
// The mesh navigates on its own frame: a point on the floor is found at mesh (40, 100).
var nav = back!.BuildNavMesh();
var q = new DtNavMeshQuery(nav);
q.FindNearestPoly(new RcVec3f(40, 0.2f, 100), new RcVec3f(2, 4, 2), new DtQueryDefaultFilter(), out long poly, out _, out _);
Check(poly != 0, "the dungeon's own navmesh finds the floor at its mesh position");
// Drawing: landblock 0x0505 is world (960, 960); the character stands at local (-150, -100) = world (810, 860).
var view = new NavMeshView();
view.RegisterDungeon(0x0505, back);
Check(view.DungeonLandblock == 0x0505, "the dungeon is registered");
var s = new TriSink();
var dun = new NavMeshView.Options(100f, 100000, true, true, layer: 1, frameX: 960, frameY: 960);
int n = view.Emit(s, 810, 860, 0, dun);
Check(n > 0, "the dungeon draws");
float lo = s.Tris.Min(t => Math.Min(t.X1, Math.Min(t.X2, t.X3))), hi = s.Tris.Max(t => Math.Max(t.X1, Math.Max(t.X2, t.X3)));
Check(lo > -184 && hi < -120, $"drawn in the landblock-local frame, negative x ({lo:F1}..{hi:F1})");
float zlo = s.Tris.Min(t => Math.Min(t.Z1, Math.Min(t.Z2, t.Z3))), zhi = s.Tris.Max(t => Math.Max(t.Z1, Math.Max(t.Z2, t.Z3)));
Check(zlo > -184 && zhi < -10, $"and negative z/north ({zlo:F1}..{zhi:F1})");
// Layers: asking for the outdoor layer draws none of the dungeon, and an outdoor tile never shows in the dungeon.
var outdoor = new TriSink();
Check(view.Emit(outdoor, 810, 860, 0, new NavMeshView.Options(100f, 100000, true, true)) == 0, "the outdoor layer is empty while only a dungeon is registered");
view.Register(0x0505, md);
var again = new TriSink();
int n2 = view.Emit(again, 810, 860, 0, dun);
Check(n2 == n, "registering an outdoor tile doesn't change the dungeon's draw");
view.UnregisterDungeon();
Check(view.DungeonLandblock == 0 && view.Emit(new TriSink(), 810, 860, 0, dun) == 0, "unregistering the dungeon empties its layer");
// Floors above and below the character are left out (maxUpDown).
var tall = new NavMeshView();
tall.RegisterDungeon(0x0505, back);
var farUp = new TriSink();
Check(tall.Emit(farUp, 810, 860, 50, new NavMeshView.Options(100f, 100000, true, true, maxUpDown: 8f, layer: 1, frameX: 960, frameY: 960)) == 0, "a floor 50 m away vertically isn't drawn");
}
/// <summary>The dungeon tiles a bake wrote (RYNTHNAV_DUNGEONS, or the live NavData), when there are any.</summary>
private static void RealDungeons()
{
string dir = Environment.GetEnvironmentVariable("RYNTHNAV_DUNGEONS") ?? @"C:\Projects\meshview\_dun";
if (!Directory.Exists(dir) || !Directory.EnumerateFiles(dir, "dun_*.tile").Any()) { Console.WriteLine(" (no baked dungeons here: skipped)"); return; }
int files = 0, tiles = 0, bad = 0; long polys = 0, wallEdges = 0, floorTris = 0;
var sw = System.Diagnostics.Stopwatch.StartNew();
foreach (string f in Directory.EnumerateFiles(dir, "dun_*.tile"))
{
files++;
var d = DungeonTileFile.Read(f);
if (d == null) { bad++; continue; }
tiles += d.Tiles.Count;
uint lb = Convert.ToUInt32(Path.GetFileNameWithoutExtension(f).Substring(4), 16);
var view = new NavMeshView(); view.RegisterDungeon(lb, d);
foreach (var md in d.Tiles)
{
polys += md.header.polyCount;
var t = NavMeshView.BuildTile(md, md.header.x * 192, md.header.y * 192, 0, 0);
floorTris += t.FloorCount; wallEdges += t.WallCount;
if (!t.Floor.All(float.IsFinite)) bad++;
}
}
Console.WriteLine($" {files} dungeon files: {tiles} tiles, {polys} polygons, {floorTris} floor triangles, {wallEdges} wall edges; {sw.ElapsedMilliseconds} ms to read all");
Check(bad == 0, $"every dungeon file reads and is finite ({bad} bad)");
// Connectivity: how much of a dungeon's walkable ground is one connected piece (polygon links, across tiles).
// A sound mesh has most of its area in one region; a low share means stairs, ramps or doorways were lost.
var shares = new List<(uint lb, double share, int regions, int polys)>();
foreach (string f in Directory.EnumerateFiles(dir, "dun_*.tile").Take(400))
{
var d = DungeonTileFile.Read(f);
if (d == null) continue;
uint lb = Convert.ToUInt32(Path.GetFileNameWithoutExtension(f).Substring(4), 16);
var comp = Components(d.BuildNavMesh());
if (comp.Count == 0) continue;
int total = comp.Sum(), big = comp.Max();
shares.Add((lb, (double)big / total, comp.Count, total));
}
if (shares.Count == 0) return;
var sorted = shares.Select(s => s.share).OrderBy(x => x).ToList();
double Pct(double p) => sorted[Math.Min(sorted.Count - 1, (int)(p * sorted.Count))];
Console.WriteLine($" connectivity of {shares.Count} dungeons (share of polygons in the largest piece): " +
$"worst {sorted[0]:P0}, 10th pct {Pct(0.10):P0}, median {Pct(0.5):P0}; {shares.Count(s => s.share >= 0.9)} are 90%+ one piece, {shares.Count(s => s.share < 0.5)} under 50%");
foreach (var s in shares.OrderBy(s => s.share).Take(5)) Console.WriteLine($" 0x{s.lb:X4}: {s.share:P0} of {s.polys} polygons in the biggest of {s.regions} pieces");
// No assertion on the share: many dungeons are areas joined by drops and teleports, so a low share is the dungeon, not the mesh.
// The baker's --dungeons-check compares against the game's own doorway graph, which is the fidelity measure.
}
/// <summary>Sizes (polygon counts) of the connected pieces of a navmesh, joined by Detour's polygon links.</summary>
private static List<int> Components(DtNavMesh nav)
{
var seen = new HashSet<long>();
var sizes = new List<int>();
for (int ti = 0; ti < nav.GetMaxTiles(); ti++)
{
DtMeshTile? tile = nav.GetTile(ti);
if (tile?.data?.header == null) continue;
long baseRef = nav.GetPolyRefBase(tile);
for (int pi = 0; pi < tile.data.header.polyCount; pi++)
{
long start = baseRef | (long)pi;
if (!seen.Add(start)) continue;
int size = 0;
var stack = new Stack<long>(); stack.Push(start);
while (stack.Count > 0)
{
long r = stack.Pop(); size++;
if (nav.GetTileAndPolyByRef(r, out DtMeshTile t, out DtPoly p).Failed()) continue;
for (int k = p.firstLink; k != DtDetour.DT_NULL_LINK; k = t.links[k].next)
{
long n = t.links[k].refs;
if (n != 0 && seen.Add(n)) stack.Push(n);
}
}
sizes.Add(size);
}
}
return sizes;
}
/// <summary>Real tiles (when installed): the triangle and wall counts of a town tile, and a whole 5 x 5 window.</summary>
private static void RealMeshView()
{
string dir = Environment.GetEnvironmentVariable("RYNTHNAV_NAVDATA") ?? @"C:\Games\RynthCore\NavData";
uint holtburg = 0xA9B4; // Holtburg
string file = Path.Combine(dir, $"nav_{holtburg:X4}.tile");
if (!File.Exists(file)) { Console.WriteLine(" (no real NavData here: skipped)"); return; }
var sw = System.Diagnostics.Stopwatch.StartNew();
var view = new NavMeshView();
int loaded = 0, floor = 0, walls = 0;
for (int dx = -2; dx <= 2; dx++)
for (int dy = -2; dy <= 2; dy++)
{
uint lb = (uint)((((int)(holtburg >> 8) + dx) << 8) | ((int)(holtburg & 0xFF) + dy));
if (!File.Exists(Path.Combine(dir, $"nav_{lb:X4}.tile"))) continue;
DtMeshData md = ReadTile(dir, lb);
view.Register(lb, md); loaded++;
var t = NavMeshView.BuildTile(lb, md);
floor += t.FloorCount; walls += t.WallCount;
Check(t.Floor.All(float.IsFinite) && t.Walls.All(float.IsFinite), $"tile 0x{lb:X4}: all finite");
}
long buildMs = sw.ElapsedMilliseconds;
var s = new TriSink();
double px = (holtburg >> 8) * 192.0 + 96, py = (holtburg & 0xFF) * 192.0 + 96;
sw.Restart();
int n = view.Emit(s, px, py, 100, new NavMeshView.Options(40f, 3000, true, true, maxUpDown: 1000f));
long emitMs = sw.ElapsedMilliseconds;
Console.WriteLine($" Holtburg window: {loaded} tiles, {floor} floor triangles, {walls} wall edges in all; {buildMs} ms to read+build; a 40 m draw = {n} triangles in {emitMs} ms");
Check(loaded > 0 && floor > 0, "real tiles read");
Check(n <= 3000, $"the budget holds on real tiles ({n})");
}
/// <summary>
/// The real map (read only, when it's installed): Holtburg to Lytelthorpe, about 11k yd over
/// land, as the path markers and "save as nav route" would work it out. Prints the size and time.

View file

@ -21,6 +21,10 @@
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\NavCoarse.cs" Link="Linked\NavCoarse.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\PortalAvoid.cs" Link="Linked\PortalAvoid.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\AvoidFilter.cs" Link="Linked\AvoidFilter.cs" />
<!-- The navmesh drawn in the world (green floor, red walls) and the sink it writes to. -->
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\NavMeshView.cs" Link="Linked\NavMeshView.cs" />
<Compile Include="..\..\Plugins\Shared\Nav3DText.cs" Link="Linked\Nav3DText.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\DungeonTileFile.cs" Link="Linked\DungeonTileFile.cs" />
<Compile Include="..\RynthNav.Baker\GraphBuild.cs" Link="Linked\GraphBuild.cs" />
<!-- A planned trip's walk from the tile files (TilePathFinder) and what it needs. -->
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\TilePathFinder.cs" Link="Linked\TilePathFinder.cs" />

View file

@ -0,0 +1,131 @@
using RynthNav.Baker;
namespace RynthNav.MapTests;
/// <summary>The baker's DXT1 encoder against the standard decode (what a GPU does with the blocks).</summary>
internal static class Program
{
private static int _checks, _failed;
private static int Main()
{
Sizes();
Solid();
TwoColours();
Gradient();
Noise();
Rejects();
Console.WriteLine(_failed == 0 ? $"OK: {_checks} checks" : $"FAILED: {_failed} of {_checks} checks");
return _failed == 0 ? 0 : 1;
}
private static void Check(bool ok, string what)
{
_checks++;
if (!ok) { _failed++; Console.WriteLine("FAIL: " + what); }
}
private static byte[] Fill(int w, int h, Func<int, int, (int R, int G, int B)> f)
{
var img = new byte[w * h * 3];
for (int y = 0; y < h; y++)
for (int x = 0; x < w; x++)
{
var (r, g, b) = f(x, y);
int o = (y * w + x) * 3;
img[o] = (byte)r; img[o + 1] = (byte)g; img[o + 2] = (byte)b;
}
return img;
}
private static double MeanAbsError(byte[] a, byte[] b)
{
long sum = 0;
for (int i = 0; i < a.Length; i++) sum += Math.Abs(a[i] - b[i]);
return sum / (double)a.Length;
}
private static double Psnr(byte[] a, byte[] b)
{
double mse = 0;
for (int i = 0; i < a.Length; i++) { double d = a[i] - b[i]; mse += d * d; }
mse /= a.Length;
return mse == 0 ? 99 : 10 * Math.Log10(255.0 * 255.0 / mse);
}
private static void Sizes()
{
byte[] blocks = Dxt1.Encode(new byte[256 * 256 * 3], 256, 256);
Check(blocks.Length == 256 * 256 / 2, "a 256 x 256 tile is 32768 bytes (4 bits a pixel), got " + blocks.Length);
Check(Dxt1.Encode(new byte[8 * 4 * 3], 8, 4).Length == 16, "an 8 x 4 image is two blocks");
}
private static void Solid()
{
foreach (var c in new[] { (0, 0, 0), (255, 255, 255), (28, 66, 118), (120, 150, 60) })
{
byte[] img = Fill(8, 8, (x, y) => c);
byte[] back = Dxt1.Decode(Dxt1.Encode(img, 8, 8), 8, 8);
// RGB565 keeps 5/6/5 bits: within 8 of the colour on each channel.
bool near = true;
for (int i = 0; i < back.Length; i += 3)
if (Math.Abs(back[i] - c.Item1) > 8 || Math.Abs(back[i + 1] - c.Item2) > 4 || Math.Abs(back[i + 2] - c.Item3) > 8) near = false;
Check(near, $"a solid {c} block comes back within the 565 step");
}
// A solid block never uses the transparent mode: every index is 0 (the colour itself).
byte[] blk = Dxt1.Encode(Fill(4, 4, (x, y) => (50, 100, 150)), 4, 4);
Check(blk[4] == 0 && blk[5] == 0 && blk[6] == 0 && blk[7] == 0, "a solid block's indices are all 0");
}
private static void TwoColours()
{
byte[] img = Fill(4, 4, (x, y) => x < 2 ? (200, 40, 40) : (30, 60, 220));
byte[] blocks = Dxt1.Encode(img, 4, 4);
ushort c0 = (ushort)(blocks[0] | (blocks[1] << 8)), c1 = (ushort)(blocks[2] | (blocks[3] << 8));
Check(c0 > c1, "the four-colour mode (colour 0 above colour 1), never the transparent one");
Check(MeanAbsError(img, Dxt1.Decode(blocks, 4, 4)) < 6, "two flat colours come back close");
}
private static void Gradient()
{
byte[] img = Fill(256, 256, (x, y) => (x, y, (x + y) / 2));
byte[] blocks = Dxt1.Encode(img, 256, 256);
byte[] back = Dxt1.Decode(blocks, 256, 256);
double mae = MeanAbsError(img, back), psnr = Psnr(img, back);
Check(mae < 5, $"a colour gradient: mean error {mae:F2} (under 5)");
Check(psnr > 33, $"a colour gradient: PSNR {psnr:F1} dB (over 33)");
// No block uses the transparent mode.
bool fourColour = true;
for (int i = 0; i < blocks.Length; i += 8)
{
ushort a = (ushort)(blocks[i] | (blocks[i + 1] << 8)), b = (ushort)(blocks[i + 2] | (blocks[i + 3] << 8));
if (a < b) fourColour = false;
}
Check(fourColour, "every block of the gradient is in the four-colour mode");
}
private static void Noise()
{
// Ground texture stand-in: a mid green-brown with grain. DXT1 is lossy but must stay recognisable.
var rnd = new Random(11);
byte[] img = Fill(128, 128, (x, y) =>
{
int n = rnd.Next(-25, 26);
return (110 + n, 120 + n + rnd.Next(-6, 7), 60 + n / 2);
});
byte[] back = Dxt1.Decode(Dxt1.Encode(img, 128, 128), 128, 128);
double psnr = Psnr(img, back);
Check(psnr > 24, $"grainy ground: PSNR {psnr:F1} dB (over 24)");
// The average colour of the tile is kept (a map zoomed out averages these).
double ma = 0, mb = 0;
for (int i = 0; i < img.Length; i++) { ma += img[i]; mb += back[i]; }
Check(Math.Abs(ma - mb) / img.Length < 2, "the average colour of grainy ground is kept");
}
private static void Rejects()
{
bool threw = false;
try { Dxt1.Encode(new byte[5 * 4 * 3], 5, 4); } catch (ArgumentException) { threw = true; }
Check(threw, "a width that isn't a multiple of 4 is refused");
}
}

View file

@ -0,0 +1,22 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
Offline checks for the World Map's compressed tiles (the baker's Dxt1.cs, compiled in): the block
layout and sizes, the four-colour mode (never the transparent one), that solid and two-colour blocks
survive, and how close gradients and noisy textures come back through the standard DXT1 decode.
Run: dotnet run -c Release (exit 0 = pass, 1 = fail)
-->
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<InvariantGlobalization>true</InvariantGlobalization>
<RootNamespace>RynthNav.MapTests</RootNamespace>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\RynthNav.Baker\Dxt1.cs" Link="Linked\Dxt1.cs" />
</ItemGroup>
</Project>

View file

@ -86,7 +86,10 @@ var doc = TownNetFile.Load(inPath);
var sw = Stopwatch.StartNew();
var world = WorldLoader.Load(doc, cellDat, portalDat, out var reachable);
var grid = new NavGrid(world, reachable);
var planner = new WalkPlanner(world, grid);
// --extra <m>: the margin kept beyond the walker's body (default 0.5; a walk with no room at that margin is planned at 0.25).
float extra = Arg("--extra") is string ex ? float.Parse(ex, CultureInfo.InvariantCulture) : WalkPlanner.DefaultExtra;
var planner = new WalkPlanner(world, grid, extra);
var fallbackPlanner = extra > 0.25f ? new WalkPlanner(world, grid, 0.25f) : null;
Console.WriteLine($"{reachable.Count} cells, {grid.Nodes.Count:N0} floor samples, {world.Solids.Count:N0} solid shapes, " +
$"{world.Portals.Count} exit portals; walker radius {world.AgentRadius:F2} m ({sw.Elapsed.TotalSeconds:F1} s)");
foreach (var n in world.Notes) Console.WriteLine(" " + n);
@ -111,6 +114,16 @@ if (cmd == "build")
foreach (var a in arrivals)
{
var ws = planner.PlanFrom(a.Id, a.Cell, a.P, world.Portals);
if (fallbackPlanner != null && ws.Any(w => w.Error != null))
{
var alt = fallbackPlanner.PlanFrom(a.Id, a.Cell, a.P, world.Portals);
for (int i = 0; i < ws.Count; i++)
if (ws[i].Error != null)
{
var better = alt.FirstOrDefault(x => x.To == ws[i].To && x.Error == null);
if (better != null) { ws[i] = better; Console.WriteLine($" {better.ExitName}: no room at {extra:0.##} m, planned at 0.25 m"); }
}
}
walks.AddRange(ws);
var ok = ws.Where(w => w.Error == null).ToList();
Console.WriteLine($"{a.Id} {a.Cell:X8} ({a.P.X:F1},{a.P.Y:F1}): {ok.Count}/{ws.Count} exits, " +
@ -130,6 +143,7 @@ if (cmd == "build")
["grid"] = NavGrid.Cell,
["walkerRadius"] = R2(world.AgentRadius),
["clearance"] = R2(planner.MustClear),
["margin"] = R2(extra),
["portalClearance"] = R2(planner.MustPortal),
["cells"] = reachable.Count,
["walks"] = walks.Count,

View file

@ -27,13 +27,18 @@ internal sealed class WalkPlanner
/// checked exactly, so this slack only matters at drops with no wall.</summary>
public const float EdgeSlack = NavGrid.Cell;
public WalkPlanner(Indoor w, NavGrid g)
/// <summary>The margin the search keeps beyond the walker's body (m). A walk that is only the body's width from a
/// wall or object gets the character stuck on it (steering is not exact): the patrol keeps about 1 m, so
/// this is 0.5 and the search falls back to the old 0.25 for a walk with no room at 0.5 (see PlanFrom).</summary>
public const float DefaultExtra = 0.5f;
public WalkPlanner(Indoor w, NavGrid g, float extra = DefaultExtra)
{
_w = w; _g = g;
float r = w.AgentRadius;
PassClear = r + 0.25f; // grid search: keep this far from walls and objects
PassPortal = r + 0.5f; // ... and from other portals (touching one uses it)
SmoothClear = r + 0.15f; // straightened segments
PassClear = r + extra; // grid search: keep this far from walls and objects
PassPortal = r + extra + 0.25f; // ... and from other portals (touching one uses it)
SmoothClear = r + extra - 0.10f; // straightened segments
MustClear = r; // the check: the walker's body never touches a wall or object
MustPortal = r + 0.25f; // ... and stays a step away from every other portal
}