Cut 13b: watertight CGA city baker, RCGA v1 loader, and SionCityCatalog

This commit is contained in:
Meta Vens 2026-12-06 02:07:58 +01:00
commit 9798d1b868
5 changed files with 3276 additions and 118 deletions

View file

@ -0,0 +1,673 @@
using System;
using System.Buffers.Binary;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Numerics;
using System.Text;
namespace RustToDust.Core
{
public enum CgaZoneKind : byte
{
Plinth = 0,
WallBay = 1,
FloorSlab = 2,
InteriorCore = 3,
RoofSegment = 4,
}
public enum CgaMaterialClass : byte
{
FortressStone = 0,
Concrete = 1,
Masonry = 2,
Steel = 3,
TimberOrGlass = 4,
}
public enum CgaMicroZone : byte
{
OldTown = 0,
Clavau = 1,
Vissigen = 2,
Ronquoz = 3,
Suburban = 4,
Fortress = 5,
Civic = 6,
}
public enum CgaArchStyle : byte
{
Residential = 0,
Industrial = 1,
Fortress = 2,
}
[Flags]
public enum CgaZoneFlags : byte
{
None = 0,
GroundAnchored = 1 << 0,
HasWindowOpenings = 1 << 1,
Exterior = 1 << 2,
}
public readonly record struct CgaZoneMeta(
ulong SupportMask,
CgaZoneKind Kind,
CgaMaterialClass MaterialClass,
CgaZoneFlags Flags,
byte ZoneIndex,
float MaxHp,
float MassKg,
Vector3 BoundsMin,
Vector3 BoundsMax)
{
public bool IsGroundAnchored => (Flags & CgaZoneFlags.GroundAnchored) != 0;
public bool HasWindowOpenings => (Flags & CgaZoneFlags.HasWindowOpenings) != 0;
public bool IsExterior => (Flags & CgaZoneFlags.Exterior) != 0;
}
public readonly record struct CgaBuildingMeta(
ushort BuildingId,
byte Tx,
byte Tz,
byte LocalSlot,
CgaMicroZone MicroZone,
CgaArchStyle ArchStyle,
byte ZoneCount,
int FirstZoneIndex,
uint Egid,
Vector3 BoundsMin,
Vector3 BoundsMax,
float GroundY,
float RoofY,
ulong GroundAnchoredMask,
string Name);
public readonly record struct RcgaPackedVertex(
short Qx,
short Qy,
short Qz,
sbyte OctNx,
sbyte OctNy,
ushort Qu,
ushort Qv,
byte ZoneIndex,
byte MaterialPaletteId,
byte EdgeWearAo,
byte BldgLocalSlot);
public readonly record struct RcgaDecodedVertex(
Vector3 Position,
Vector3 Normal,
Vector2 Uv,
byte ZoneIndex,
byte MaterialPaletteId,
byte EdgeWearAo,
byte BldgLocalSlot);
public readonly record struct RcgaBuildingHeader(
ushort BuildingId,
byte ZoneCount,
byte LocalSlot,
Vector3 PosOrigin,
Vector3 PosScale,
int FirstZoneSliceIndex);
public readonly record struct RcgaZoneSlice(
int RenderVertOffset,
int RenderVertCount,
int RenderIndexOffset,
int RenderIndexCount,
int ColVertOffset,
int ColVertCount,
int ColIndexOffset,
int ColIndexCount);
public sealed class RcgaTileGeometry
{
internal RcgaTileGeometry(
int tx,
int tz,
RcgaBuildingHeader[] buildings,
RcgaZoneSlice[] slices,
RcgaPackedVertex[] vertices,
ushort[] indices)
{
Tx = tx;
Tz = tz;
Buildings = buildings;
Slices = slices;
Vertices = vertices;
Indices = indices;
}
public int Tx { get; }
public int Tz { get; }
public RcgaBuildingHeader[] Buildings { get; }
public RcgaZoneSlice[] Slices { get; }
public RcgaPackedVertex[] Vertices { get; }
public ushort[] Indices { get; }
public Vector3 DecodePosition(in RcgaBuildingHeader bldg, in RcgaPackedVertex v) =>
new(
bldg.PosOrigin.X + v.Qx * bldg.PosScale.X,
bldg.PosOrigin.Y + v.Qy * bldg.PosScale.Y,
bldg.PosOrigin.Z + v.Qz * bldg.PosScale.Z);
public static Vector3 DecodeOctNormal(sbyte qx, sbyte qy)
{
float ox = Math.Clamp(qx / 127f, -1f, 1f);
float oy = Math.Clamp(qy / 127f, -1f, 1f);
float nz = 1f - MathF.Abs(ox) - MathF.Abs(oy);
if (nz < 0f)
{
float oldOx = ox;
ox = (1f - MathF.Abs(oy)) * (oldOx >= 0f ? 1f : -1f);
oy = (1f - MathF.Abs(oldOx)) * (oy >= 0f ? 1f : -1f);
}
var n = new Vector3(ox, oy, nz);
float len = n.Length();
return len > 1e-6f ? n / len : Vector3.UnitY;
}
public RcgaDecodedVertex DecodeVertex(in RcgaBuildingHeader bldg, in RcgaPackedVertex v) =>
new(
Position: DecodePosition(in bldg, in v),
Normal: DecodeOctNormal(v.OctNx, v.OctNy),
Uv: new Vector2(v.Qu * SionCityCatalog.UvScale, v.Qv * SionCityCatalog.UvScale),
ZoneIndex: v.ZoneIndex,
MaterialPaletteId: v.MaterialPaletteId,
EdgeWearAo: v.EdgeWearAo,
BldgLocalSlot: v.BldgLocalSlot);
}
public sealed class SionCityCatalog
{
public const int TileGrid = 16;
public const int TileCount = TileGrid * TileGrid;
public const float TileSizeMeters = 192f;
public const float UvScale = 1f / 1024f;
private readonly string _sionDirectory;
private readonly CgaBuildingMeta[] _buildings;
private readonly CgaZoneMeta[] _zones;
private readonly int[][] _tileBuildingIndices;
private readonly object _tileLock = new();
private readonly RcgaTileGeometry?[] _tileCache = new RcgaTileGeometry?[TileCount];
private SionCityCatalog(
string sionDirectory,
string assetFingerprint,
CgaBuildingMeta[] buildings,
CgaZoneMeta[] zones,
int[][] tileBuildingIndices)
{
_sionDirectory = sionDirectory;
AssetFingerprint = assetFingerprint;
_buildings = buildings;
_zones = zones;
_tileBuildingIndices = tileBuildingIndices;
}
public string AssetFingerprint { get; }
public IReadOnlyList<CgaBuildingMeta> Buildings => _buildings;
public IReadOnlyList<CgaZoneMeta> Zones => _zones;
public ReadOnlySpan<CgaZoneMeta> GetZonesForBuilding(ushort buildingId)
{
ref readonly var b = ref _buildings[buildingId];
return _zones.AsSpan(b.FirstZoneIndex, b.ZoneCount);
}
public IReadOnlyList<int> GetBuildingIdsForTile(int tx, int tz)
{
if ((uint)tx >= TileGrid || (uint)tz >= TileGrid)
{
return Array.Empty<int>();
}
return _tileBuildingIndices[tz * TileGrid + tx];
}
public static SionCityCatalog Load(string sionDirectory)
{
string cgaPath = Path.Combine(sionDirectory, "buildings_cga.bin");
byte[] raw = File.ReadAllBytes(cgaPath);
if (raw.Length < 64)
{
throw new InvalidDataException($"buildings_cga.bin '{cgaPath}' too small ({raw.Length} bytes).");
}
ReadOnlySpan<byte> hdr = raw.AsSpan(0, 64);
if (hdr[0] != (byte)'R' || hdr[1] != (byte)'C' || hdr[2] != (byte)'G' || hdr[3] != (byte)'B')
{
throw new InvalidDataException($"Invalid RCGB magic in '{cgaPath}'.");
}
uint version = BinaryPrimitives.ReadUInt32LittleEndian(hdr.Slice(4, 4));
if (version != 1)
{
throw new InvalidDataException($"Unsupported RCGB version {version} in '{cgaPath}'.");
}
int bldgCount = checked((int)BinaryPrimitives.ReadUInt32LittleEndian(hdr.Slice(8, 4)));
int totalZoneCount = checked((int)BinaryPrimitives.ReadUInt32LittleEndian(hdr.Slice(12, 4)));
uint tileGrid = BinaryPrimitives.ReadUInt32LittleEndian(hdr.Slice(16, 4));
if (tileGrid != TileGrid)
{
throw new InvalidDataException($"Unexpected RCGB tileGrid {tileGrid} != {TileGrid} in '{cgaPath}'.");
}
string fingerprint = "rcga:" + Convert.ToHexString(hdr.Slice(24, 32)).ToLowerInvariant();
uint flags = BinaryPrimitives.ReadUInt32LittleEndian(hdr.Slice(56, 4));
int uncompLen = checked((int)BinaryPrimitives.ReadUInt32LittleEndian(hdr.Slice(60, 4)));
byte[] body;
if ((flags & 1u) != 0)
{
body = new byte[uncompLen];
using var ms = new MemoryStream(raw, 64, raw.Length - 64, writable: false);
using var z = new ZLibStream(ms, CompressionMode.Decompress);
ReadExact(z, body, cgaPath);
}
else
{
body = raw.AsSpan(64).ToArray();
}
int expectedMin = bldgCount * 64 + totalZoneCount * 44 + 4;
if (body.Length < expectedMin)
{
throw new InvalidDataException($"RCGB body truncated in '{cgaPath}': {body.Length} < {expectedMin}.");
}
ReadOnlySpan<byte> bSpan = body;
int zBase = bldgCount * 64;
int strTableOffset = zBase + totalZoneCount * 44;
int strBytesLen = checked((int)BinaryPrimitives.ReadUInt32LittleEndian(bSpan.Slice(strTableOffset, 4)));
ReadOnlySpan<byte> strBytes = bSpan.Slice(strTableOffset + 4, strBytesLen);
var buildings = new CgaBuildingMeta[bldgCount];
var tileLists = new List<int>[TileCount];
for (int i = 0; i < TileCount; i++)
{
tileLists[i] = new List<int>(4);
}
for (int i = 0; i < bldgCount; i++)
{
int off = i * 64;
ushort bid = BinaryPrimitives.ReadUInt16LittleEndian(bSpan.Slice(off, 2));
byte tx = bSpan[off + 2];
byte tz = bSpan[off + 3];
byte localSlot = bSpan[off + 4];
var microZone = (CgaMicroZone)bSpan[off + 5];
var archStyle = (CgaArchStyle)bSpan[off + 6];
byte zoneCount = bSpan[off + 7];
int firstZone = checked((int)BinaryPrimitives.ReadUInt32LittleEndian(bSpan.Slice(off + 8, 4)));
uint egid = BinaryPrimitives.ReadUInt32LittleEndian(bSpan.Slice(off + 12, 4));
var bmin = ReadVec3(bSpan.Slice(off + 16, 12));
var bmax = ReadVec3(bSpan.Slice(off + 28, 12));
float groundY = BinaryPrimitives.ReadSingleLittleEndian(bSpan.Slice(off + 40, 4));
float roofY = BinaryPrimitives.ReadSingleLittleEndian(bSpan.Slice(off + 44, 4));
ulong groundAnchoredMask = BinaryPrimitives.ReadUInt64LittleEndian(bSpan.Slice(off + 48, 8));
uint nameOff = BinaryPrimitives.ReadUInt32LittleEndian(bSpan.Slice(off + 56, 4));
ushort nameLen = BinaryPrimitives.ReadUInt16LittleEndian(bSpan.Slice(off + 60, 2));
string name = "";
if (nameOff != 0xFFFFFFFFu && nameLen > 0 && nameOff + nameLen <= (uint)strBytes.Length)
{
name = Encoding.UTF8.GetString(strBytes.Slice((int)nameOff, nameLen));
}
buildings[i] = new CgaBuildingMeta(
bid, tx, tz, localSlot, microZone, archStyle, zoneCount, firstZone, egid,
bmin, bmax, groundY, roofY, groundAnchoredMask, name);
if (tx < TileGrid && tz < TileGrid)
{
tileLists[tz * TileGrid + tx].Add(bid);
}
}
var zones = new CgaZoneMeta[totalZoneCount];
for (int z = 0; z < totalZoneCount; z++)
{
int off = zBase + z * 44;
ulong supportMask = BinaryPrimitives.ReadUInt64LittleEndian(bSpan.Slice(off, 8));
var kind = (CgaZoneKind)bSpan[off + 8];
var matClass = (CgaMaterialClass)bSpan[off + 9];
var zFlags = (CgaZoneFlags)bSpan[off + 10];
byte zIdx = bSpan[off + 11];
float maxHp = BinaryPrimitives.ReadSingleLittleEndian(bSpan.Slice(off + 12, 4));
float massKg = BinaryPrimitives.ReadSingleLittleEndian(bSpan.Slice(off + 16, 4));
var zMin = ReadVec3(bSpan.Slice(off + 20, 12));
var zMax = ReadVec3(bSpan.Slice(off + 32, 12));
zones[z] = new CgaZoneMeta(supportMask, kind, matClass, zFlags, zIdx, maxHp, massKg, zMin, zMax);
}
var tileArrays = new int[TileCount][];
for (int i = 0; i < TileCount; i++)
{
tileArrays[i] = tileLists[i].Count == 0 ? Array.Empty<int>() : tileLists[i].ToArray();
}
return new SionCityCatalog(sionDirectory, fingerprint, buildings, zones, tileArrays);
}
public bool TryGetTileGeometry(int tx, int tz, out RcgaTileGeometry? tile)
{
if ((uint)tx >= TileGrid || (uint)tz >= TileGrid)
{
tile = null;
return false;
}
int idx = tz * TileGrid + tx;
if (_tileBuildingIndices[idx].Length == 0)
{
tile = null;
return false;
}
lock (_tileLock)
{
tile = _tileCache[idx];
if (tile is not null)
{
return true;
}
}
string path = Path.Combine(_sionDirectory, "tiles", $"city_{tx}_{tz}.rcga");
if (!File.Exists(path))
{
tile = null;
return false;
}
var loaded = LoadRcgaTile(path, tx, tz);
lock (_tileLock)
{
_tileCache[idx] ??= loaded;
tile = _tileCache[idx];
}
return tile is not null;
}
public void BuildTileCollisionMesh(
int tx,
int tz,
Func<ushort, ulong>? getCollapsedMask,
List<Vector3> outVerts,
List<int> outIndices)
{
outVerts.Clear();
outIndices.Clear();
if (!TryGetTileGeometry(tx, tz, out var tile) || tile is null)
{
return;
}
var bldgs = tile.Buildings;
var slices = tile.Slices;
var verts = tile.Vertices;
var indices = tile.Indices;
for (int b = 0; b < bldgs.Length; b++)
{
ref readonly var bh = ref bldgs[b];
ulong collapsed = getCollapsedMask is not null ? getCollapsedMask(bh.BuildingId) : 0UL;
for (int z = 0; z < bh.ZoneCount; z++)
{
if ((collapsed & (1UL << z)) != 0)
{
continue;
}
ref readonly var sl = ref slices[bh.FirstZoneSliceIndex + z];
int baseVertex = outVerts.Count;
for (int vi = 0; vi < sl.ColVertCount; vi++)
{
outVerts.Add(tile.DecodePosition(in bh, in verts[sl.ColVertOffset + vi]));
}
for (int ii = 0; ii < sl.ColIndexCount; ii++)
{
outIndices.Add(baseVertex + indices[sl.ColIndexOffset + ii]);
}
}
}
}
/// <summary>
/// Flood-check over SupportMask DAG: returns updated collapsed mask including any
/// above-ground zones that can no longer transitively reach an IsGroundAnchored zone.
/// </summary>
public ulong ComputeUnsupportedCollapsedMask(ushort buildingId, ulong collapsedMask)
{
ref readonly var b = ref _buildings[buildingId];
int n = b.ZoneCount;
if (n == 0)
{
return collapsedMask;
}
var zones = _zones.AsSpan(b.FirstZoneIndex, n);
ulong alive = (~collapsedMask) & (n == 64 ? ulong.MaxValue : ((1UL << n) - 1UL));
ulong supported = alive & b.GroundAnchoredMask;
bool changed = true;
while (changed)
{
changed = false;
for (int i = 0; i < n; i++)
{
ulong bit = 1UL << i;
if ((alive & bit) == 0 || (supported & bit) != 0)
{
continue;
}
if ((zones[i].SupportMask & supported) != 0)
{
supported |= bit;
changed = true;
}
}
}
ulong allMask = n == 64 ? ulong.MaxValue : ((1UL << n) - 1UL);
return collapsedMask | (allMask & ~supported);
}
public bool ValidateSupportDag(ushort buildingId, out bool hasCycle, out bool allReachGround)
{
ref readonly var b = ref _buildings[buildingId];
int n = b.ZoneCount;
var zones = _zones.AsSpan(b.FirstZoneIndex, n);
Span<byte> color = stackalloc byte[n];
hasCycle = false;
for (int i = 0; i < n; i++)
{
if (color[i] == 0)
{
DfsCycle(i, zones, color, ref hasCycle);
}
}
ulong collapsedAfterFlood = ComputeUnsupportedCollapsedMask(buildingId, 0UL);
allReachGround = collapsedAfterFlood == 0UL;
return !hasCycle && allReachGround;
static void DfsCycle(int u, ReadOnlySpan<CgaZoneMeta> zs, Span<byte> c, ref bool cycle)
{
c[u] = 1;
ulong sm = zs[u].SupportMask;
for (int v = 0; v < zs.Length; v++)
{
if (((sm >> v) & 1UL) != 0)
{
if (c[v] == 1)
{
cycle = true;
}
else if (c[v] == 0)
{
DfsCycle(v, zs, c, ref cycle);
}
}
}
c[u] = 2;
}
}
public static RcgaTileGeometry LoadRcgaTile(string path, int expectedTx = -1, int expectedTz = -1)
{
byte[] raw = File.ReadAllBytes(path);
if (raw.Length < 24)
{
throw new InvalidDataException($"RCGA file '{path}' too small ({raw.Length} bytes).");
}
ReadOnlySpan<byte> hdr = raw.AsSpan(0, 24);
if (hdr[0] != (byte)'R' || hdr[1] != (byte)'C' || hdr[2] != (byte)'G' || hdr[3] != (byte)'A')
{
throw new InvalidDataException($"Invalid RCGA magic in '{path}'.");
}
uint version = BinaryPrimitives.ReadUInt32LittleEndian(hdr.Slice(4, 4));
if (version != 1)
{
throw new InvalidDataException($"Unsupported RCGA version {version} in '{path}'.");
}
int tx = BinaryPrimitives.ReadInt32LittleEndian(hdr.Slice(8, 4));
int tz = BinaryPrimitives.ReadInt32LittleEndian(hdr.Slice(12, 4));
if ((expectedTx >= 0 && tx != expectedTx) || (expectedTz >= 0 && tz != expectedTz))
{
throw new InvalidDataException($"RCGA tile mismatch in '{path}': ({tx},{tz}) != ({expectedTx},{expectedTz}).");
}
int bldgCount = checked((int)BinaryPrimitives.ReadUInt32LittleEndian(hdr.Slice(16, 4)));
int uncompBytes = checked((int)BinaryPrimitives.ReadUInt32LittleEndian(hdr.Slice(20, 4)));
byte[] payload = new byte[uncompBytes];
using (var ms = new MemoryStream(raw, 24, raw.Length - 24, writable: false))
using (var z = new ZLibStream(ms, CompressionMode.Decompress))
{
ReadExact(z, payload, path);
}
ReadOnlySpan<byte> p = payload;
int off = 0;
var bldgs = new RcgaBuildingHeader[bldgCount];
int totalSlices = 0;
for (int i = 0; i < bldgCount; i++)
{
ushort bid = BinaryPrimitives.ReadUInt16LittleEndian(p.Slice(off, 2));
byte zCnt = p[off + 2];
byte localSlot = p[off + 3];
var origin = ReadVec3(p.Slice(off + 4, 12));
var scale = ReadVec3(p.Slice(off + 16, 12));
int firstSlice = checked((int)BinaryPrimitives.ReadUInt32LittleEndian(p.Slice(off + 28, 4)));
bldgs[i] = new RcgaBuildingHeader(bid, zCnt, localSlot, origin, scale, firstSlice);
totalSlices += zCnt;
off += 36;
}
var slices = new RcgaZoneSlice[totalSlices];
int totalVerts = 0;
int totalIndices = 0;
for (int s = 0; s < totalSlices; s++)
{
int rvCnt = checked((int)BinaryPrimitives.ReadUInt32LittleEndian(p.Slice(off, 4)));
int riCnt = checked((int)BinaryPrimitives.ReadUInt32LittleEndian(p.Slice(off + 4, 4)));
int cvCnt = checked((int)BinaryPrimitives.ReadUInt32LittleEndian(p.Slice(off + 8, 4)));
int ciCnt = checked((int)BinaryPrimitives.ReadUInt32LittleEndian(p.Slice(off + 12, 4)));
off += 16;
int rVertOff = totalVerts;
totalVerts += rvCnt;
int rIdxOff = totalIndices;
totalIndices += riCnt;
int cVertOff = totalVerts;
totalVerts += cvCnt;
int cIdxOff = totalIndices;
totalIndices += ciCnt;
slices[s] = new RcgaZoneSlice(rVertOff, rvCnt, rIdxOff, riCnt, cVertOff, cvCnt, cIdxOff, ciCnt);
}
var allVerts = new RcgaPackedVertex[totalVerts];
var allIndices = new ushort[totalIndices];
for (int s = 0; s < totalSlices; s++)
{
ref readonly var sl = ref slices[s];
ReadVertices(p, ref off, allVerts.AsSpan(sl.RenderVertOffset, sl.RenderVertCount));
ReadIndices(p, ref off, allIndices.AsSpan(sl.RenderIndexOffset, sl.RenderIndexCount));
ReadVertices(p, ref off, allVerts.AsSpan(sl.ColVertOffset, sl.ColVertCount));
ReadIndices(p, ref off, allIndices.AsSpan(sl.ColIndexOffset, sl.ColIndexCount));
}
if (off != payload.Length)
{
throw new InvalidDataException($"RCGA payload byte mismatch in '{path}': parsed {off} != {payload.Length}.");
}
return new RcgaTileGeometry(tx, tz, bldgs, slices, allVerts, allIndices);
}
private static void ReadVertices(ReadOnlySpan<byte> src, ref int off, Span<RcgaPackedVertex> dst)
{
for (int i = 0; i < dst.Length; i++)
{
short qx = BinaryPrimitives.ReadInt16LittleEndian(src.Slice(off, 2));
short qy = BinaryPrimitives.ReadInt16LittleEndian(src.Slice(off + 2, 2));
short qz = BinaryPrimitives.ReadInt16LittleEndian(src.Slice(off + 4, 2));
sbyte nx = unchecked((sbyte)src[off + 6]);
sbyte ny = unchecked((sbyte)src[off + 7]);
ushort qu = BinaryPrimitives.ReadUInt16LittleEndian(src.Slice(off + 8, 2));
ushort qv = BinaryPrimitives.ReadUInt16LittleEndian(src.Slice(off + 10, 2));
byte c0 = src[off + 12];
byte c1 = src[off + 13];
byte c2 = src[off + 14];
byte c3 = src[off + 15];
dst[i] = new RcgaPackedVertex(qx, qy, qz, nx, ny, qu, qv, c0, c1, c2, c3);
off += 16;
}
}
private static void ReadIndices(ReadOnlySpan<byte> src, ref int off, Span<ushort> dst)
{
for (int i = 0; i < dst.Length; i++)
{
dst[i] = BinaryPrimitives.ReadUInt16LittleEndian(src.Slice(off, 2));
off += 2;
}
}
private static Vector3 ReadVec3(ReadOnlySpan<byte> src) =>
new(
BinaryPrimitives.ReadSingleLittleEndian(src.Slice(0, 4)),
BinaryPrimitives.ReadSingleLittleEndian(src.Slice(4, 4)),
BinaryPrimitives.ReadSingleLittleEndian(src.Slice(8, 4)));
private static void ReadExact(Stream s, byte[] dst, string path)
{
int total = 0;
while (total < dst.Length)
{
int read = s.Read(dst, total, dst.Length - total);
if (read <= 0)
{
throw new InvalidDataException($"Unexpected EOF decompressing '{path}' at {total}/{dst.Length}.");
}
total += read;
}
}
}
}

View file

@ -99,7 +99,8 @@ namespace RustToDust.Core
float baseDemMinY,
float baseDemScale,
SionBuildingAabb[] buildings,
SionCollisionMesh[] collisionMeshes)
SionCollisionMesh[] collisionMeshes,
SionCityCatalog? cityCatalog = null)
{
DirectoryPath = directoryPath;
Metadata = metadata;
@ -111,6 +112,7 @@ namespace RustToDust.Core
: $"sion:{metadata.GridRes}:{metadata.CellSizeMeters:F3}";
_buildings = buildings;
CollisionMeshes = collisionMeshes;
CityCatalog = cityCatalog;
_halfExtent = metadata.SizeMeters * 0.5f;
_cellSize = metadata.SizeMeters / SpatialGridRes;
@ -153,6 +155,7 @@ namespace RustToDust.Core
public float SampleBaseDemAtIndex(int index) => BaseDemMinY + _baseDem[index] * BaseDemScale;
public IReadOnlyList<SionBuildingAabb> Buildings => _buildings;
public IReadOnlyList<SionCollisionMesh> CollisionMeshes { get; }
public SionCityCatalog? CityCatalog { get; }
public bool IsInsideAnyBuildingXz(float x, float z, float padding = 0f)
{
@ -378,7 +381,11 @@ namespace RustToDust.Core
colMeshes[i] = LoadRcolFile(colPath, t.Tx, t.Tz);
}
var data = new SionMapData(root, meta, baseDem, demMinY, demScale, buildings, colMeshes);
SionCityCatalog? cityCatalog = File.Exists(Path.Combine(root, "buildings_cga.bin"))
? SionCityCatalog.Load(root)
: null;
var data = new SionMapData(root, meta, baseDem, demMinY, demScale, buildings, colMeshes, cityCatalog);
lock (CacheLock)
{
Cache[root] = data;

View file

@ -0,0 +1,212 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Numerics;
using RustToDust.Core;
using Xunit;
namespace RustToDust.Tests
{
public sealed class SionCityCatalogTests
{
[Fact]
public void SionCityCatalog_LoadsAll2319BuildingsAndValidatesSupportDags()
{
var sion = SionMapLoader.Load();
var catalog = sion.CityCatalog;
Assert.NotNull(catalog);
Assert.StartsWith("rcga:", catalog!.AssetFingerprint, StringComparison.Ordinal);
Assert.Equal(2319, catalog.Buildings.Count);
Assert.True(catalog.Zones.Count >= 2319, $"Expected >= 2319 total zones, got {catalog.Zones.Count}");
bool foundValere = false;
var microZoneCounts = new int[7];
int multiZoneBuildings = 0;
for (int i = 0; i < catalog.Buildings.Count; i++)
{
var b = catalog.Buildings[i];
Assert.Equal(i, b.BuildingId);
Assert.InRange(b.Tx, 0, SionCityCatalog.TileGrid - 1);
Assert.InRange(b.Tz, 0, SionCityCatalog.TileGrid - 1);
Assert.InRange(b.ZoneCount, 1, 64);
Assert.NotEqual(0UL, b.GroundAnchoredMask);
Assert.True(b.RoofY >= b.GroundY, $"Building {b.BuildingId} invalid Y span [{b.GroundY}, {b.RoofY}]");
microZoneCounts[(int)b.MicroZone]++;
if (b.ZoneCount > 1)
{
multiZoneBuildings++;
}
if (b.Name.Contains("Val", StringComparison.OrdinalIgnoreCase))
{
foundValere = true;
Assert.Equal(CgaMicroZone.Fortress, b.MicroZone);
Assert.Equal(CgaArchStyle.Fortress, b.ArchStyle);
}
bool valid = catalog.ValidateSupportDag(b.BuildingId, out bool hasCycle, out bool allReachGround);
Assert.False(hasCycle, $"Building {b.BuildingId} ({b.Name}) has a SupportMask cycle");
Assert.True(allReachGround, $"Building {b.BuildingId} ({b.Name}) has an unreachable above-ground zone");
Assert.True(valid);
// Destroying all ground-anchored zones must cascade collapse to every zone in the building
ulong allMask = b.ZoneCount == 64 ? ulong.MaxValue : ((1UL << b.ZoneCount) - 1UL);
ulong cascaded = catalog.ComputeUnsupportedCollapsedMask(b.BuildingId, b.GroundAnchoredMask);
Assert.Equal(allMask, cascaded);
}
Assert.True(foundValere, "Expected Valère fortress building in CGA catalog");
Assert.True(multiZoneBuildings > 2000, $"Expected > 2000 multi-zone buildings, got {multiZoneBuildings}");
Assert.True(microZoneCounts[(int)CgaMicroZone.OldTown] > 50, "Expected OldTown buildings");
Assert.True(microZoneCounts[(int)CgaMicroZone.Ronquoz] > 50, "Expected Ronquoz/Industrial buildings");
Assert.True(microZoneCounts[(int)CgaMicroZone.Fortress] >= 10, "Expected Fortress buildings");
}
[Fact]
public void SionCityCatalog_RcgaTilesDecodeExactFiniteVerticesAndNormals()
{
var sion = SionMapLoader.Load();
var catalog = sion.CityCatalog!;
Assert.NotNull(catalog);
int nonEmptyTiles = 0;
int totalDecodedRenderVerts = 0;
int totalDecodedColTris = 0;
for (int tz = 0; tz < SionCityCatalog.TileGrid; tz++)
{
for (int tx = 0; tx < SionCityCatalog.TileGrid; tx++)
{
var bldgIds = catalog.GetBuildingIdsForTile(tx, tz);
if (bldgIds.Count == 0)
{
Assert.False(catalog.TryGetTileGeometry(tx, tz, out _));
continue;
}
nonEmptyTiles++;
Assert.True(catalog.TryGetTileGeometry(tx, tz, out var tile));
Assert.NotNull(tile);
Assert.Equal(bldgIds.Count, tile!.Buildings.Length);
for (int bi = 0; bi < tile.Buildings.Length; bi++)
{
ref readonly var bh = ref tile.Buildings[bi];
var meta = catalog.Buildings[bh.BuildingId];
Assert.Equal(meta.ZoneCount, bh.ZoneCount);
for (int z = 0; z < bh.ZoneCount; z++)
{
ref readonly var sl = ref tile.Slices[bh.FirstZoneSliceIndex + z];
Assert.True(sl.RenderVertCount >= 4);
Assert.True(sl.RenderIndexCount >= 12 && sl.RenderIndexCount % 3 == 0);
Assert.True(sl.ColVertCount >= 4);
Assert.True(sl.ColIndexCount >= 12 && sl.ColIndexCount % 3 == 0);
totalDecodedRenderVerts += sl.RenderVertCount;
totalDecodedColTris += sl.ColIndexCount / 3;
for (int vi = 0; vi < sl.RenderVertCount; vi++)
{
var dv = tile.DecodeVertex(in bh, in tile.Vertices[sl.RenderVertOffset + vi]);
Assert.True(float.IsFinite(dv.Position.X) && float.IsFinite(dv.Position.Y) && float.IsFinite(dv.Position.Z));
Assert.True(float.IsFinite(dv.Normal.X) && float.IsFinite(dv.Normal.Y) && float.IsFinite(dv.Normal.Z));
Assert.InRange(dv.Normal.Length(), 0.96f, 1.04f);
Assert.Equal((byte)z, dv.ZoneIndex);
Assert.Equal(bh.LocalSlot, dv.BldgLocalSlot);
// Decoded vertex must lie inside building bounds (within quantization tolerance)
Assert.InRange(dv.Position.X, meta.BoundsMin.X - 0.15f, meta.BoundsMax.X + 0.15f);
Assert.InRange(dv.Position.Y, meta.BoundsMin.Y - 0.15f, meta.BoundsMax.Y + 0.15f);
Assert.InRange(dv.Position.Z, meta.BoundsMin.Z - 0.15f, meta.BoundsMax.Z + 0.15f);
}
for (int ii = 0; ii < sl.RenderIndexCount; ii++)
{
Assert.True(tile.Indices[sl.RenderIndexOffset + ii] < sl.RenderVertCount);
}
for (int ii = 0; ii < sl.ColIndexCount; ii++)
{
Assert.True(tile.Indices[sl.ColIndexOffset + ii] < sl.ColVertCount);
}
}
}
}
}
Assert.InRange(nonEmptyTiles, 60, 256);
Assert.True(totalDecodedRenderVerts > 50_000);
Assert.True(totalDecodedColTris > 50_000);
}
[Fact]
public void SionCityCatalog_BuildTileCollisionMeshOmitsCollapsedZonesWhilePreservingNeighbors()
{
var sion = SionMapLoader.Load();
var catalog = sion.CityCatalog!;
Assert.NotNull(catalog);
// Pick a dense OldTown multi-zone building tile
var target = catalog.Buildings.First(b => b.MicroZone == CgaMicroZone.OldTown && b.ZoneCount >= 8);
var vertsFull = new List<Vector3>();
var indicesFull = new List<int>();
catalog.BuildTileCollisionMesh(target.Tx, target.Tz, null, vertsFull, indicesFull);
Assert.True(vertsFull.Count > 0 && indicesFull.Count > 0 && indicesFull.Count % 3 == 0);
// Find a ground-story WallBay zone in target building and compute cascade collapse
var zones = catalog.GetZonesForBuilding(target.BuildingId);
int wallBayIdx = -1;
for (int z = 0; z < zones.Length; z++)
{
if (zones[z].Kind == CgaZoneKind.WallBay)
{
wallBayIdx = z;
break;
}
}
Assert.True(wallBayIdx >= 0);
ulong collapsedMask = catalog.ComputeUnsupportedCollapsedMask(target.BuildingId, 1UL << wallBayIdx);
Assert.NotEqual(0UL, collapsedMask & (1UL << wallBayIdx));
// Plinth (zone 0) and InteriorCore must remain intact!
Assert.Equal(0UL, collapsedMask & target.GroundAnchoredMask);
var vertsDamaged = new List<Vector3>();
var indicesDamaged = new List<int>();
catalog.BuildTileCollisionMesh(
target.Tx,
target.Tz,
bid => bid == target.BuildingId ? collapsedMask : 0UL,
vertsDamaged,
indicesDamaged);
Assert.True(indicesDamaged.Count > 0, "Neighboring bays & plinth must remain intact");
Assert.True(indicesDamaged.Count < indicesFull.Count, "Collapsed zone triangles must be omitted");
// Collapsing every building in the tile produces an empty collision mesh cleanly
var vertsEmpty = new List<Vector3>();
var indicesEmpty = new List<int>();
catalog.BuildTileCollisionMesh(target.Tx, target.Tz, _ => ulong.MaxValue, vertsEmpty, indicesEmpty);
Assert.Empty(vertsEmpty);
Assert.Empty(indicesEmpty);
}
[Fact]
public void SionCityCatalog_CombinedRcgaAndLod2SizeWithin16MiBBudget()
{
var sion = SionMapLoader.Load();
string tilesDir = Path.Combine(sion.DirectoryPath, "tiles");
long rcgaBytes = Directory.EnumerateFiles(tilesDir, "city_*.rcga").Sum(p => new FileInfo(p).Length);
long lod2Bytes = Directory.EnumerateFiles(tilesDir, "city_lod2_*.glb").Sum(p => new FileInfo(p).Length);
long combined = rcgaBytes + lod2Bytes;
Assert.True(rcgaBytes > 0, "Expected city_*.rcga files");
Assert.True(lod2Bytes > 0, "Expected city_lod2_*.glb files");
Assert.True(combined <= 16L * 1024L * 1024L,
$"Combined city_*.rcga ({rcgaBytes:N0} B) + city_lod2_*.glb ({lod2Bytes:N0} B) = {combined:N0} B exceeds 16 MiB");
}
}
}

View file

@ -17,6 +17,7 @@ from __future__ import annotations
import argparse
import ctypes
import ctypes.util
import glob
import hashlib
import json
@ -24,6 +25,7 @@ import math
import os
import re
import struct
import sys
import urllib.parse
import urllib.request
import zipfile
@ -82,20 +84,36 @@ SKIRT_DEPTH_M = 4.0
MAX_LOD1_TRIS = 275_000
MAX_TILES_GLB_BYTES = 28_000_000
MAX_SURFACE_PNG_BYTES = 14_000_000
MAX_TOTAL_ASSETS_BYTES = 85_000_000
MAX_TOTAL_ASSETS_BYTES = 85 * 1024 * 1024 # 85 MiB
MAX_RCGA_AND_LOD2_BYTES = 16 * 1024 * 1024 # 16 MiB
sys.path.insert(0, str(Path(__file__).resolve().parent))
import cga_builder # noqa: E402
# ---------------------------------------------------------------------------
# GDAL / OGR ctypes wrapper (uses pyogrio's bundled GDAL 3.12+ DLL)
# GDAL / OGR ctypes wrapper (cross-platform: pyogrio bundled DLL / SO or system GDAL)
# ---------------------------------------------------------------------------
class OgrReader:
def __init__(self) -> None:
libs_dir = os.path.abspath(os.path.join(os.path.dirname(pyogrio.__file__), "..", "pyogrio.libs"))
os.add_dll_directory(libs_dir)
dlls = glob.glob(os.path.join(libs_dir, "gdal-*.dll"))
if not dlls:
raise RuntimeError(f"Could not locate gdal-*.dll in {libs_dir}")
g = ctypes.CDLL(dlls[0])
lib_path: str | None = None
if os.name == "nt":
if os.path.isdir(libs_dir):
os.add_dll_directory(libs_dir)
dlls = sorted(glob.glob(os.path.join(libs_dir, "gdal-*.dll")))
if dlls:
lib_path = dlls[0]
else:
if os.path.isdir(libs_dir):
sos = sorted(glob.glob(os.path.join(libs_dir, "libgdal*.so*")))
if sos:
lib_path = sos[0]
if lib_path is None:
lib_path = ctypes.util.find_library("gdal")
if not lib_path:
raise RuntimeError(f"Could not locate GDAL shared library in {libs_dir} or system library path")
g = ctypes.CDLL(lib_path)
g.GDALAllRegister()
g.GDALOpenEx.argtypes = [ctypes.c_char_p, ctypes.c_uint, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p]
g.GDALOpenEx.restype = ctypes.c_void_p
@ -247,6 +265,47 @@ def fetch_stac_items(base_url: str, wgs84_bbox: tuple[float, float, float, float
return items
def acquire_swisstopo_buildings(
cache_dir: Path, e0: float, n0: float, e1: float, n1: float
) -> tuple[list[Path], list[str]]:
tr = pyproj.Transformer.from_crs("EPSG:2056", "EPSG:4326", always_xy=True)
lon0, lat0 = tr.transform(e0 - 20.0, n0 - 20.0)
lon1, lat1 = tr.transform(e1 + 20.0, n1 + 20.0)
wgs_bbox = (lon0, lat0, lon1, lat1)
bldg_items = fetch_stac_items(STAC_BLDG_URL, wgs_bbox)
best_sheets: dict[str, tuple[int, str, str, str]] = {}
for item in bldg_items:
m = re.match(r"swissbuildings3d_3_0_(\d{4})_(\d{4}-\d{2})$", item["id"])
if not m:
continue
yr, sheet = int(m.group(1)), m.group(2)
for asset_name, asset in item.get("assets", {}).items():
if asset_name.endswith(".gdb.zip"):
prev = best_sheets.get(sheet)
if prev is None or yr > prev[0]:
best_sheets[sheet] = (yr, item["id"], asset_name, asset["href"])
if not best_sheets:
raise RuntimeError("No per-sheet swissBUILDINGS3D 3.0 GDB assets returned from STAC")
gdb_paths: list[Path] = []
stac_ids: list[str] = []
for sheet, (_, item_id, fname, href) in sorted(best_sheets.items()):
zip_path = download_cached(href, cache_dir / fname)
stac_ids.append(item_id)
with zipfile.ZipFile(zip_path) as zf:
gdb_roots = {name.split("/")[0] for name in zf.namelist() if ".gdb/" in name}
for root in sorted(gdb_roots):
gdb_dir = cache_dir / root
if not gdb_dir.exists():
print(f" [Extract GDB] {fname} -> {root}")
zf.extractall(cache_dir)
gdb_paths.append(gdb_dir)
return gdb_paths, stac_ids
def acquire_swisstopo_data(
cache_dir: Path, e0: float, n0: float, e1: float, n1: float
) -> tuple[dict[tuple[int, int], Path], list[Path], list[str]]:
@ -285,36 +344,9 @@ def acquire_swisstopo_data(
tif_paths[key] = download_cached(href, cache_dir / fname)
stac_ids.append(item_id)
# 2. swissBUILDINGS3D 3.0: pick latest per-sheet tiled GDB (skip multi-GB whole-CH monoliths)
bldg_items = fetch_stac_items(STAC_BLDG_URL, wgs_bbox)
best_sheets: dict[str, tuple[int, str, str, str]] = {}
for item in bldg_items:
m = re.match(r"swissbuildings3d_3_0_(\d{4})_(\d{4}-\d{2})$", item["id"])
if not m:
continue
yr, sheet = int(m.group(1)), m.group(2)
for asset_name, asset in item.get("assets", {}).items():
if asset_name.endswith(".gdb.zip"):
prev = best_sheets.get(sheet)
if prev is None or yr > prev[0]:
best_sheets[sheet] = (yr, item["id"], asset_name, asset["href"])
if not best_sheets:
raise RuntimeError("No per-sheet swissBUILDINGS3D 3.0 GDB assets returned from STAC")
gdb_paths: list[Path] = []
for sheet, (_, item_id, fname, href) in sorted(best_sheets.items()):
zip_path = download_cached(href, cache_dir / fname)
stac_ids.append(item_id)
with zipfile.ZipFile(zip_path) as zf:
gdb_roots = {name.split("/")[0] for name in zf.namelist() if ".gdb/" in name}
for root in sorted(gdb_roots):
gdb_dir = cache_dir / root
if not gdb_dir.exists():
print(f" [Extract GDB] {fname} -> {root}")
zf.extractall(cache_dir)
gdb_paths.append(gdb_dir)
# 2. swissBUILDINGS3D 3.0
gdb_paths, bldg_stac = acquire_swisstopo_buildings(cache_dir, e0, n0, e1, n1)
stac_ids.extend(bldg_stac)
return tif_paths, gdb_paths, stac_ids
@ -397,6 +429,25 @@ def export_heightmap_u16z(hm: np.ndarray, out_path: Path) -> tuple[float, float,
return min_y, scale, dem_hash
def load_heightmap_u16z(in_path: Path) -> np.ndarray:
"""Decode heightmap_05m.u16z back into float32 (gridRes, gridRes) array."""
raw = in_path.read_bytes()
magic, ver, grid_res, min_y, scale, raw_len = struct.unpack_from("<4sIIffI", raw, 0)
if magic != b"RDHM" or ver != 2:
raise RuntimeError(f"Unsupported heightmap format in {in_path}")
payload = zlib.decompress(raw[24:])
zz = np.frombuffer(payload, dtype="<u2").reshape(grid_res, grid_res)
diff = ((zz.astype(np.int32) >> 1) ^ -(zz.astype(np.int32) & 1)).astype(np.int32)
q = np.empty((grid_res, grid_res), dtype=np.uint16)
for r in range(grid_res):
pred = int(q[r - 1, 0]) if r > 0 else 0
row_d = diff[r]
for c in range(grid_res):
pred = (pred + int(row_d[c])) & 0xFFFF
q[r, c] = pred
return min_y + q.astype(np.float32) * scale
def acquire_wms_masks(
cache_dir: Path, e0: float, n0: float, e1: float, n1: float, res: int = SURFACE_TEX_RES
) -> dict[str, np.ndarray]:
@ -1765,6 +1816,237 @@ def export_collision_bin(
return v_count, i_count // 3, out_path.stat().st_size, [round(v, 3) for v in bmin], [round(v, 3) for v in bmax]
def _read_swissbuildings_records(
gdb_paths: list[Path],
e0: float,
n0: float,
e1: float,
n1: float,
) -> list[tuple[str, dict, list[np.ndarray], list[np.ndarray], list[np.ndarray], list[np.ndarray]]]:
print("[Sion Baker] Reading swissBUILDINGS3D 3.0 layers (Building_solid, Wall, Roof, Floor)...")
reader = OgrReader()
bbox = (e0, n0, e1, n1)
fields = ["UUID", "OBJEKTART", "NAME_KOMPLETT", "DACH_MIN", "DACH_MAX", "GELAENDEPUNKT", "EGID"]
solids_by_uuid: dict[str, tuple[dict, list[np.ndarray]]] = {}
walls_by_uuid: dict[str, tuple[dict, list[np.ndarray]]] = {}
floors_by_uuid: dict[str, tuple[dict, list[np.ndarray]]] = {}
roofs_list: list[tuple[dict, list[np.ndarray]]] = []
for gdb in gdb_paths:
for attrs, faces in reader.read_layer(str(gdb), "Building_solid", bbox, fields):
u = str(attrs.get("UUID", ""))
if u and u not in solids_by_uuid:
solids_by_uuid[u] = (attrs, faces)
for attrs, faces in reader.read_layer(str(gdb), "Wall", bbox, fields):
u = str(attrs.get("UUID", ""))
if u and u not in walls_by_uuid:
walls_by_uuid[u] = (attrs, faces)
for attrs, faces in reader.read_layer(str(gdb), "Floor", bbox, fields):
u = str(attrs.get("UUID", ""))
if u and u not in floors_by_uuid:
floors_by_uuid[u] = (attrs, faces)
for attrs, faces in reader.read_layer(str(gdb), "Roof", bbox, fields):
roofs_list.append((attrs, faces))
roofs_by_uuid: dict[str, list[list[np.ndarray]]] = defaultdict(list)
bldg_egids: dict[str, str] = {}
bldg_boxes: list[tuple[str, float, float, float, float]] = []
for u, (attrs, faces) in walls_by_uuid.items():
pts = np.vstack(faces)
bldg_boxes.append((u, float(pts[:, 0].min()), float(pts[:, 1].min()), float(pts[:, 0].max()), float(pts[:, 1].max())))
egid = str(attrs.get("EGID", "")).strip()
if egid:
bldg_egids[egid] = u
standalone_roofs: list[tuple[str, dict, list[np.ndarray]]] = []
seen_roof_sigs: set[tuple[int, int, int]] = set()
for idx_r, (attrs, faces) in enumerate(roofs_list):
pts = np.vstack(faces)
sig = (int(round(pts[:, 0].mean() * 10)), int(round(pts[:, 1].mean() * 10)), len(faces))
if sig in seen_roof_sigs:
continue
seen_roof_sigs.add(sig)
u = str(attrs.get("UUID", "")).strip()
if u and u in walls_by_uuid:
roofs_by_uuid[u].append(faces)
continue
egid = str(attrs.get("EGID", "")).strip()
if egid and egid in bldg_egids:
roofs_by_uuid[bldg_egids[egid]].append(faces)
continue
rx, ry = float(pts[:, 0].mean()), float(pts[:, 1].mean())
matched_u = None
for bu, bx0, by0, bx1, by1 in bldg_boxes:
if bx0 - 0.5 <= rx <= bx1 + 0.5 and by0 - 0.5 <= ry <= by1 + 0.5:
matched_u = bu
break
if matched_u:
roofs_by_uuid[matched_u].append(faces)
else:
standalone_roofs.append((u or f"roof_{idx_r:04d}", attrs, faces))
print(
f" Raw extracted: {len(walls_by_uuid)} wall-buildings, "
f"{len(roofs_by_uuid)} matched roofs, {len(standalone_roofs)} roof-only structures"
)
all_records: list[tuple[str, dict, list[np.ndarray], list[np.ndarray], list[np.ndarray], list[np.ndarray]]] = []
for u, (attrs, w_faces) in walls_by_uuid.items():
r_faces = [f for grp in roofs_by_uuid.get(u, []) for f in grp]
fl_faces = floors_by_uuid[u][1] if u in floors_by_uuid else []
s_faces = solids_by_uuid[u][1] if u in solids_by_uuid else []
all_records.append((u, attrs, w_faces, r_faces, fl_faces, s_faces))
for u, attrs, r_faces in standalone_roofs:
all_records.append((u, attrs, [], r_faces, [], []))
return all_records
def bake_cga_city(
all_records: list[tuple[str, dict, list[np.ndarray], list[np.ndarray], list[np.ndarray], list[np.ndarray]]],
hm: np.ndarray,
out_dir: Path,
tiles_dir: Path,
cE: float,
cN: float,
base_elev: float,
e0: float,
n0: float,
e1: float,
n1: float,
) -> tuple[str, list[dict]]:
"""
Build watertight CGA zone decompositions for all buildings inside the 3km arena,
export tiles/city_<tx>_<tz>.rcga + tiles/city_lod2_<tx>_<tz>.glb + buildings_cga.bin,
and run automated watertightness & SupportMask DAG verification.
"""
for stale in tiles_dir.glob("city_*.rcga"):
stale.unlink()
for stale in tiles_dir.glob("city_lod2_*.glb"):
stale.unlink()
filtered: list[tuple[tuple[str, str], str, dict, list[np.ndarray], list[np.ndarray], list[np.ndarray], list[np.ndarray]]] = []
for u, attrs, w_faces_enz, r_faces_enz, fl_faces_enz, s_faces_enz in all_records:
all_enz = np.vstack(w_faces_enz + r_faces_enz + fl_faces_enz)
cx_enz, cy_enz = float(all_enz[:, 0].mean()), float(all_enz[:, 1].mean())
if not (e0 + 2.0 <= cx_enz <= e1 - 2.0 and n0 + 2.0 <= cy_enz <= n1 - 2.0):
continue
egid_str = str(attrs.get("EGID", "")).strip()
sort_key = (egid_str.zfill(12) if egid_str.isdigit() else "~" + egid_str, u)
filtered.append((sort_key, u, attrs, w_faces_enz, r_faces_enz, fl_faces_enz, s_faces_enz))
filtered.sort(key=lambda item: item[0])
tile_buildings: dict[tuple[int, int], list[cga_builder.CgaBuildingResult]] = defaultdict(list)
tile_slot_counter: Counter[tuple[int, int]] = Counter()
all_cga_buildings: list[cga_builder.CgaBuildingResult] = []
micro_counts: Counter[int] = Counter()
for bldg_id, (_sk, u, attrs, w_faces_enz, r_faces_enz, fl_faces_enz, s_faces_enz) in enumerate(filtered):
all_enz = np.vstack(w_faces_enz + r_faces_enz + fl_faces_enz)
objektart = str(attrs.get("OBJEKTART", "") or "Gebaeude Einzelhaus")
name = str(attrs.get("NAME_KOMPLETT", "") or "")
egid_raw = str(attrs.get("EGID", "")).strip()
egid_int = int(egid_raw) if egid_raw.isdigit() else 0
w_rtd = [enz_to_rtd(f, cE, cN, base_elev) for f in w_faces_enz]
r_rtd = [enz_to_rtd(f, cE, cN, base_elev) for f in r_faces_enz]
fl_rtd = [enz_to_rtd(f, cE, cN, base_elev) for f in fl_faces_enz]
s_rtd = [enz_to_rtd(f, cE, cN, base_elev) for f in s_faces_enz]
all_rtd_pts = np.vstack(w_rtd + r_rtd + fl_rtd)
bmin = all_rtd_pts.min(axis=0)
bmax = all_rtd_pts.max(axis=0)
box_center = 0.5 * (bmin + bmax)
tx = max(0, min(TILE_GRID - 1, int(math.floor((float(box_center[0]) + HALF_EXTENT_M) / TILE_SIZE_M))))
tz = max(0, min(TILE_GRID - 1, int(math.floor((float(box_center[2]) + HALF_EXTENT_M) / TILE_SIZE_M))))
slot = tile_slot_counter[(tx, tz)]
tile_slot_counter[(tx, tz)] += 1
gx = np.linspace(float(bmin[0]), float(bmax[0]), 5)
gz = np.linspace(float(bmin[2]), float(bmax[2]), 5)
mx, mz = np.meshgrid(gx, gz)
t_vals = sample_heightmap(hm, mx, mz)
t_min_y = float(np.min(t_vals))
t_max_y = float(np.max(t_vals))
# Orient raw walls/roofs outward when needed
s_tris = np.concatenate([triangulate_polygon_3d(f) for f in s_rtd], axis=0) if s_rtd else None
bldg_center = all_rtd_pts.mean(axis=0)
r_oriented = orient_faces_outward(r_rtd, s_tris, "Roof", bldg_center)
res = cga_builder.build_cga_building(
building_id=bldg_id,
egid=egid_int,
uuid=u,
name=name,
objektart=objektart,
pts_enz=all_enz,
w_rtd=w_rtd,
r_rtd=r_oriented,
fl_rtd=fl_rtd,
s_rtd=s_rtd,
terrain_min_y=t_min_y,
terrain_max_y=t_max_y,
tx=tx,
tz=tz,
local_slot=slot,
)
all_cga_buildings.append(res)
tile_buildings[(tx, tz)].append(res)
micro_counts[res.micro_zone] += 1
print(
f"[Sion CGA] Built {len(all_cga_buildings)} watertight CGA buildings across "
f"{len(tile_buildings)}/{TILE_GRID*TILE_GRID} 192m tiles | microZones={dict(sorted(micro_counts.items()))}"
)
rcga_hashes: list[bytes] = []
cga_tile_entries: list[dict] = []
for (tx, tz), bldgs in sorted(tile_buildings.items()):
rcga_path = tiles_dir / f"city_{tx}_{tz}.rcga"
lod2_path = tiles_dir / f"city_lod2_{tx}_{tz}.glb"
r_bytes, r_tris, c_tris = cga_builder.export_rcga_tile(tx, tz, bldgs, rcga_path)
l2_tris, l2_bytes = cga_builder.export_city_lod2_glb(tx, tz, bldgs, lod2_path)
rcga_hashes.append(hashlib.sha256(rcga_path.read_bytes()).digest())
bmins = np.vstack([b.bounds_min for b in bldgs]).min(axis=0)
bmaxs = np.vstack([b.bounds_max for b in bldgs]).max(axis=0)
tile_cx = -HALF_EXTENT_M + (tx + 0.5) * TILE_SIZE_M
tile_cz = -HALF_EXTENT_M + (tz + 0.5) * TILE_SIZE_M
cga_tile_entries.append({
"tx": tx,
"tz": tz,
"rcga": f"tiles/city_{tx}_{tz}.rcga",
"lod2": f"tiles/city_lod2_{tx}_{tz}.glb",
"buildingCount": len(bldgs),
"renderTris": int(r_tris),
"colTris": int(c_tris),
"rcgaBytes": int(r_bytes),
"lod2Tris": int(l2_tris),
"lod2Bytes": int(l2_bytes),
"center": [round(tile_cx, 2), 0.0, round(tile_cz, 2)],
"boundsMin": [round(float(v), 3) for v in bmins],
"boundsMax": [round(float(v), 3) for v in bmaxs],
})
cga_bin_path = out_dir / "buildings_cga.bin"
fingerprint, bin_bytes = cga_builder.export_buildings_cga_bin(all_cga_buildings, rcga_hashes, cga_bin_path)
print(f"[Sion CGA] Exported buildings_cga.bin ({bin_bytes:,} bytes, fingerprint={fingerprint[:16]}...)")
audit = cga_builder.verify_rcga_outputs(out_dir)
print(
f"[Sion CGA Verify] buildings={audit['verified_buildings']}, zones={audit['zones']}, "
f"renderTris={audit['render_tris']:,}, colTris={audit['col_tris']:,}, "
f"open={audit['open_boundary_edges']}, nonManifold={audit['non_manifold_edges']}, "
f"deg={audit['degenerate_tris']}, cycles={audit['support_dag_cycles']}, "
f"unreachable={audit['ground_unreachable']}, "
f"rcga={audit['rcga_bytes']/1e6:.2f} MB, lod2={audit['lod2_bytes']/1e6:.2f} MB, "
f"combined={audit['combined_bytes']/1048576:.2f} MiB (<= 16 MiB)"
)
return fingerprint, cga_tile_entries
# ---------------------------------------------------------------------------
# Main pipeline
# ---------------------------------------------------------------------------
@ -1775,6 +2057,9 @@ def main() -> None:
parser.add_argument("--center-e", type=float, default=DEFAULT_CENTER_E)
parser.add_argument("--center-n", type=float, default=DEFAULT_CENTER_N)
parser.add_argument("--terrain-only", action="store_true", help="Re-bake 0.5m DEM, surface, mask & metadata.json while preserving existing tiles/ & buildings_manifest.json")
parser.add_argument("--cga-only", action="store_true", help="Re-bake Cut 13b CGA city (buildings_cga.bin, city_*.rcga, city_lod2_*.glb) preserving existing DEM & legacy tiles")
parser.add_argument("--verify-rcga", action="store_true", help="Mechanically verify buildings_cga.bin + city_*.rcga + city_lod2_*.glb and exit")
parser.add_argument("--clean-legacy", action="store_true", help="Remove legacy lod1/lod2/col tiles (Cut 13c+)")
args = parser.parse_args()
repo_root = Path(args.repo_root).resolve()
@ -1785,13 +2070,49 @@ def main() -> None:
cache_dir = Path(args.cache_dir)
cache_dir.mkdir(parents=True, exist_ok=True)
if args.verify_rcga:
audit = cga_builder.verify_rcga_outputs(out_dir)
print(json.dumps(audit, indent=2))
return
cE, cN = args.center_e, args.center_n
e0, n0, e1, n1 = cE - HALF_EXTENT_M, cN - HALF_EXTENT_M, cE + HALF_EXTENT_M, cN + HALF_EXTENT_M
if args.cga_only:
meta_path = out_dir / "metadata.json"
existing_meta = json.loads(meta_path.read_text(encoding="utf-8"))
base_elev = float(existing_meta["baseElevationM"])
hm = load_heightmap_u16z(out_dir / existing_meta.get("heightmapFile", "heightmap_05m.u16z"))
gdb_paths, _ = acquire_swisstopo_buildings(cache_dir, e0, n0, e1, n1)
all_records = _read_swissbuildings_records(gdb_paths, e0, n0, e1, n1)
fingerprint, cga_tiles = bake_cga_city(all_records, hm, out_dir, tiles_dir, cE, cN, base_elev, e0, n0, e1, n1)
existing_meta["cgaCatalogFile"] = "buildings_cga.bin"
existing_meta["cgaAssetFingerprint"] = f"rcga:{fingerprint}"
existing_meta["cgaTileGrid"] = TILE_GRID
existing_meta["cgaTileSizeMeters"] = TILE_SIZE_M
existing_meta["rcgaFormat"] = {
"magic": "RCGA",
"version": 1,
"vertexStrideBytes": 16,
"vertexLayout": "int16[3] qpos, int8[2] octNormal, uint16[2] uv, uint8[4] color0(ZoneIndex, MaterialPaletteId, EdgeWearAO, BldgLocalSlot)",
"uvScale": 1.0 / cga_builder.UV_QUANT_SCALE,
}
existing_meta["cgaTileCount"] = len(cga_tiles)
existing_meta["cgaTiles"] = cga_tiles
meta_path.write_text(json.dumps(existing_meta, indent=2), encoding="utf-8")
total_assets_bytes = sum(p.stat().st_size for p in out_dir.rglob("*") if p.is_file())
print(f"[Sion Baker] CGA-only complete | Total assets/maps/sion = {total_assets_bytes/1048576:.2f} MiB ({total_assets_bytes:,} B)")
if total_assets_bytes > MAX_TOTAL_ASSETS_BYTES:
raise RuntimeError(f"Total asset budget exceeded: {total_assets_bytes} bytes > {MAX_TOTAL_ASSETS_BYTES}")
return
# Cut obsolete single-monolith GLBs & legacy float32 heightmap
for obsolete in ("sion_lod2.glb", "sion_lod1.glb", "heightmap.f32"):
obs_path = out_dir / obsolete
if obs_path.exists():
obs_path.unlink()
print(f"[Sion Baker] Removed obsolete {obs_path.name}")
if not args.terrain_only:
if args.clean_legacy and not args.terrain_only:
for stale in tiles_dir.iterdir():
if stale.is_file():
stale.unlink()
@ -1911,75 +2232,7 @@ def main() -> None:
raise RuntimeError(f"Total asset budget exceeded: {total_assets_bytes} bytes >= {MAX_TOTAL_ASSETS_BYTES}")
return
# Read semantic layers across intersecting GDB tiles
print("[Sion Baker] Reading swissBUILDINGS3D 3.0 layers (Building_solid, Wall, Roof, Floor)...")
reader = OgrReader()
bbox = (e0, n0, e1, n1)
fields = ["UUID", "OBJEKTART", "NAME_KOMPLETT", "DACH_MIN", "DACH_MAX", "GELAENDEPUNKT", "EGID"]
solids_by_uuid: dict[str, tuple[dict, list[np.ndarray]]] = {}
walls_by_uuid: dict[str, tuple[dict, list[np.ndarray]]] = {}
floors_by_uuid: dict[str, tuple[dict, list[np.ndarray]]] = {}
roofs_list: list[tuple[dict, list[np.ndarray]]] = []
for gdb in gdb_paths:
for attrs, faces in reader.read_layer(str(gdb), "Building_solid", bbox, fields):
u = str(attrs.get("UUID", ""))
if u and u not in solids_by_uuid:
solids_by_uuid[u] = (attrs, faces)
for attrs, faces in reader.read_layer(str(gdb), "Wall", bbox, fields):
u = str(attrs.get("UUID", ""))
if u and u not in walls_by_uuid:
walls_by_uuid[u] = (attrs, faces)
for attrs, faces in reader.read_layer(str(gdb), "Floor", bbox, fields):
u = str(attrs.get("UUID", ""))
if u and u not in floors_by_uuid:
floors_by_uuid[u] = (attrs, faces)
for attrs, faces in reader.read_layer(str(gdb), "Roof", bbox, fields):
roofs_list.append((attrs, faces))
# Index roofs by UUID, and attach orphan/empty-UUID roofs by EGID or 2D AABB overlap
roofs_by_uuid: dict[str, list[list[np.ndarray]]] = defaultdict(list)
bldg_egids: dict[str, str] = {}
bldg_boxes: list[tuple[str, float, float, float, float]] = []
for u, (attrs, faces) in walls_by_uuid.items():
pts = np.vstack(faces)
bldg_boxes.append((u, float(pts[:, 0].min()), float(pts[:, 1].min()), float(pts[:, 0].max()), float(pts[:, 1].max())))
egid = str(attrs.get("EGID", "")).strip()
if egid:
bldg_egids[egid] = u
standalone_roofs: list[tuple[str, dict, list[np.ndarray]]] = []
seen_roof_sigs: set[tuple[int, int, int]] = set()
for idx_r, (attrs, faces) in enumerate(roofs_list):
pts = np.vstack(faces)
sig = (int(round(pts[:, 0].mean() * 10)), int(round(pts[:, 1].mean() * 10)), len(faces))
if sig in seen_roof_sigs:
continue
seen_roof_sigs.add(sig)
u = str(attrs.get("UUID", "")).strip()
if u and u in walls_by_uuid:
roofs_by_uuid[u].append(faces)
continue
egid = str(attrs.get("EGID", "")).strip()
if egid and egid in bldg_egids:
roofs_by_uuid[bldg_egids[egid]].append(faces)
continue
rx, ry = float(pts[:, 0].mean()), float(pts[:, 1].mean())
matched_u = None
for bu, bx0, by0, bx1, by1 in bldg_boxes:
if bx0 - 0.5 <= rx <= bx1 + 0.5 and by0 - 0.5 <= ry <= by1 + 0.5:
matched_u = bu
break
if matched_u:
roofs_by_uuid[matched_u].append(faces)
else:
standalone_roofs.append((u or f"roof_{idx_r:04d}", attrs, faces))
print(
f" Raw extracted: {len(walls_by_uuid)} wall-buildings, "
f"{len(roofs_by_uuid)} matched roofs, {len(standalone_roofs)} roof-only structures"
)
all_records = _read_swissbuildings_records(gdb_paths, e0, n0, e1, n1)
# Spatial 6x6 tile buckets
tile_lod2_mats: dict[tuple[int, int], dict[str, list[np.ndarray]]] = defaultdict(lambda: defaultdict(list))
@ -1994,15 +2247,6 @@ def main() -> None:
manifest_entries: list[dict] = []
class_counts: Counter[str] = Counter()
all_records: list[tuple[str, dict, list[np.ndarray], list[np.ndarray], list[np.ndarray], list[np.ndarray]]] = []
for u, (attrs, w_faces) in walls_by_uuid.items():
r_faces = [f for grp in roofs_by_uuid.get(u, []) for f in grp]
fl_faces = floors_by_uuid[u][1] if u in floors_by_uuid else []
s_faces = solids_by_uuid[u][1] if u in solids_by_uuid else []
all_records.append((u, attrs, w_faces, r_faces, fl_faces, s_faces))
for u, attrs, r_faces in standalone_roofs:
all_records.append((u, attrs, [], r_faces, [], []))
bldg_seq = 0
for u, attrs, w_faces_enz, r_faces_enz, fl_faces_enz, s_faces_enz in all_records:
all_enz = np.vstack(w_faces_enz + r_faces_enz + fl_faces_enz)
@ -2199,6 +2443,8 @@ def main() -> None:
manifest_path = out_dir / "buildings_manifest.json"
manifest_path.write_text(json.dumps(manifest, indent=2), encoding="utf-8")
cga_fingerprint, cga_tiles = bake_cga_city(all_records, hm, out_dir, tiles_dir, cE, cN, base_elev, e0, n0, e1, n1)
meta = {
"name": "Sion, Valais, Switzerland",
"attribution": "Federal Office of Topography swisstopo",
@ -2251,6 +2497,19 @@ def main() -> None:
},
"tileCount": len(non_empty_tiles),
"tiles": [tile_stats[k] for k in non_empty_tiles],
"cgaCatalogFile": "buildings_cga.bin",
"cgaAssetFingerprint": f"rcga:{cga_fingerprint}",
"cgaTileGrid": TILE_GRID,
"cgaTileSizeMeters": TILE_SIZE_M,
"rcgaFormat": {
"magic": "RCGA",
"version": 1,
"vertexStrideBytes": 16,
"vertexLayout": "int16[3] qpos, int8[2] octNormal, uint16[2] uv, uint8[4] color0(ZoneIndex, MaterialPaletteId, EdgeWearAO, BldgLocalSlot)",
"uvScale": 1.0 / cga_builder.UV_QUANT_SCALE,
},
"cgaTileCount": len(cga_tiles),
"cgaTiles": cga_tiles,
}
meta_path = out_dir / "metadata.json"
meta_path.write_text(json.dumps(meta, indent=2), encoding="utf-8")

File diff suppressed because it is too large Load diff