diff --git a/src/RustToDust.Core/SionCityCatalog.cs b/src/RustToDust.Core/SionCityCatalog.cs new file mode 100644 index 0000000..ae658a5 --- /dev/null +++ b/src/RustToDust.Core/SionCityCatalog.cs @@ -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 Buildings => _buildings; + public IReadOnlyList Zones => _zones; + + public ReadOnlySpan GetZonesForBuilding(ushort buildingId) + { + ref readonly var b = ref _buildings[buildingId]; + return _zones.AsSpan(b.FirstZoneIndex, b.ZoneCount); + } + + public IReadOnlyList GetBuildingIdsForTile(int tx, int tz) + { + if ((uint)tx >= TileGrid || (uint)tz >= TileGrid) + { + return Array.Empty(); + } + 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 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 bSpan = body; + int zBase = bldgCount * 64; + int strTableOffset = zBase + totalZoneCount * 44; + int strBytesLen = checked((int)BinaryPrimitives.ReadUInt32LittleEndian(bSpan.Slice(strTableOffset, 4))); + ReadOnlySpan strBytes = bSpan.Slice(strTableOffset + 4, strBytesLen); + + var buildings = new CgaBuildingMeta[bldgCount]; + var tileLists = new List[TileCount]; + for (int i = 0; i < TileCount; i++) + { + tileLists[i] = new List(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() : 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? getCollapsedMask, + List outVerts, + List 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]); + } + } + } + } + + /// + /// Flood-check over SupportMask DAG: returns updated collapsed mask including any + /// above-ground zones that can no longer transitively reach an IsGroundAnchored zone. + /// + 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 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 zs, Span 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 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 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 src, ref int off, Span 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 src, ref int off, Span dst) + { + for (int i = 0; i < dst.Length; i++) + { + dst[i] = BinaryPrimitives.ReadUInt16LittleEndian(src.Slice(off, 2)); + off += 2; + } + } + + private static Vector3 ReadVec3(ReadOnlySpan 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; + } + } + } +} diff --git a/src/RustToDust.Core/SionMapLoader.cs b/src/RustToDust.Core/SionMapLoader.cs index 6b01875..407e8a3 100644 --- a/src/RustToDust.Core/SionMapLoader.cs +++ b/src/RustToDust.Core/SionMapLoader.cs @@ -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 Buildings => _buildings; public IReadOnlyList 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; diff --git a/tests/RustToDust.Tests/SionCityCatalogTests.cs b/tests/RustToDust.Tests/SionCityCatalogTests.cs new file mode 100644 index 0000000..90d0317 --- /dev/null +++ b/tests/RustToDust.Tests/SionCityCatalogTests.cs @@ -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(); + var indicesFull = new List(); + 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(); + var indicesDamaged = new List(); + 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(); + var indicesEmpty = new List(); + 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"); + } + } +} diff --git a/tools/maps/sion/bake_sion.py b/tools/maps/sion/bake_sion.py index 18a2658..affe2d4 100644 --- a/tools/maps/sion/bake_sion.py +++ b/tools/maps/sion/bake_sion.py @@ -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="> 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__.rcga + tiles/city_lod2__.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") diff --git a/tools/maps/sion/cga_builder.py b/tools/maps/sion/cga_builder.py new file mode 100644 index 0000000..b8afcb4 --- /dev/null +++ b/tools/maps/sion/cga_builder.py @@ -0,0 +1,2007 @@ +#!/usr/bin/env python3 +""" +Watertight CGA Shape-Grammar Building Decomposer for Sion, Switzerland (`swissBUILDINGS3D 3.0`). + +Produces strictly closed 2-manifold zones (<= 64 zones/building -> uint64 bitmask) +with deterministic SupportMask DAGs, Sion micro-zone vernacular rules, per-zone render +triangles (with 0.22m window reveals, lintels, sills, shutters & interior walls) and +per-zone watertight box-hull collision triangles. +""" + +from __future__ import annotations + +from collections import Counter, defaultdict +from dataclasses import dataclass +import hashlib +import math +import struct +from typing import Iterable +import zlib + +import numpy as np +import pygltflib +import shapely +from shapely.geometry import MultiPolygon, Polygon, box +from shapely.ops import unary_union + + +# --------------------------------------------------------------------------- +# Enumerations & Constants (must match C# SionCityCatalog.cs byte-for-byte) +# --------------------------------------------------------------------------- +ZONE_PLINTH = 0 +ZONE_WALL_BAY = 1 +ZONE_FLOOR_SLAB = 2 +ZONE_INTERIOR_CORE = 3 +ZONE_ROOF_SEGMENT = 4 + +MAT_CLASS_FORTRESS_STONE = 0 +MAT_CLASS_CONCRETE = 1 +MAT_CLASS_MASONRY = 2 +MAT_CLASS_STEEL = 3 +MAT_CLASS_TIMBER_OR_GLASS = 4 + +MICRO_OLD_TOWN = 0 +MICRO_CLAVAU = 1 +MICRO_VISSIGEN = 2 +MICRO_RONQUOZ = 3 +MICRO_SUBURBAN = 4 +MICRO_FORTRESS = 5 +MICRO_CIVIC = 6 + +ARCH_RESIDENTIAL = 0 +ARCH_INDUSTRIAL = 1 +ARCH_FORTRESS = 2 + +# MaterialPaletteId values (COLOR_0.g) +PAL_PLINTH_STONE = 0 +PAL_FORTRESS_STONE = 1 +PAL_CREPIS_OCHRE = 2 +PAL_CREPIS_CREAM = 3 +PAL_CREPIS_VENETIAN_RED = 4 +PAL_CREPIS_SAGE = 5 +PAL_CREPIS_SAND = 6 +PAL_CONCRETE_AGGREGATE = 7 +PAL_CONCRETE_SLAB = 8 +PAL_CORRUGATED_STEEL = 9 +PAL_STONE_TRIM = 10 +PAL_WINDOW_DARK_GLASS = 11 +PAL_SHUTTER_GREEN = 12 +PAL_SHUTTER_RED = 13 +PAL_SHUTTER_BROWN = 14 +PAL_ROOF_TERRACOTTA = 15 +PAL_ROOF_LAUZES = 16 +PAL_ROOF_INDUSTRIAL = 17 +PAL_INTERIOR_PLASTER = 18 + +PALETTE_PBR_SPECS: dict[int, tuple[str, tuple[float, float, float, float], float, float]] = { + PAL_PLINTH_STONE: ("plinth_stone", (0.26, 0.24, 0.22, 1.0), 0.02, 0.92), + PAL_FORTRESS_STONE: ("fortress_stone", (0.40, 0.36, 0.31, 1.0), 0.02, 0.90), + PAL_CREPIS_OCHRE: ("crepis_ochre", (0.79, 0.65, 0.46, 1.0), 0.00, 0.87), + PAL_CREPIS_CREAM: ("crepis_cream", (0.87, 0.82, 0.75, 1.0), 0.00, 0.85), + PAL_CREPIS_VENETIAN_RED: ("crepis_venetian_red", (0.72, 0.43, 0.32, 1.0), 0.00, 0.86), + PAL_CREPIS_SAGE: ("crepis_sage", (0.59, 0.64, 0.56, 1.0), 0.00, 0.86), + PAL_CREPIS_SAND: ("crepis_sand", (0.83, 0.75, 0.60, 1.0), 0.00, 0.86), + PAL_CONCRETE_AGGREGATE: ("concrete_aggregate", (0.64, 0.62, 0.59, 1.0), 0.04, 0.88), + PAL_CONCRETE_SLAB: ("concrete_slab", (0.46, 0.46, 0.47, 1.0), 0.05, 0.87), + PAL_CORRUGATED_STEEL: ("corrugated_steel", (0.47, 0.49, 0.52, 1.0), 0.35, 0.62), + PAL_STONE_TRIM: ("stone_trim", (0.55, 0.51, 0.45, 1.0), 0.02, 0.86), + PAL_WINDOW_DARK_GLASS: ("window_dark_glass", (0.05, 0.08, 0.12, 1.0), 0.30, 0.14), + PAL_SHUTTER_GREEN: ("shutter_green", (0.11, 0.25, 0.14, 1.0), 0.02, 0.78), + PAL_SHUTTER_RED: ("shutter_red", (0.54, 0.13, 0.11, 1.0), 0.02, 0.78), + PAL_SHUTTER_BROWN: ("shutter_brown", (0.27, 0.18, 0.11, 1.0), 0.02, 0.82), + PAL_ROOF_TERRACOTTA: ("roof_terracotta", (0.53, 0.20, 0.12, 1.0), 0.02, 0.75), + PAL_ROOF_LAUZES: ("roof_lauzes", (0.24, 0.27, 0.30, 1.0), 0.04, 0.78), + PAL_ROOF_INDUSTRIAL: ("roof_industrial", (0.31, 0.34, 0.37, 1.0), 0.15, 0.78), + PAL_INTERIOR_PLASTER: ("interior_plaster", (0.76, 0.73, 0.68, 1.0), 0.00, 0.90), +} + +ZONE_FLAG_GROUND_ANCHORED = 0x01 +ZONE_FLAG_HAS_WINDOWS = 0x02 +ZONE_FLAG_EXTERIOR = 0x04 + +MAX_ZONES_PER_BUILDING = 64 +UV_QUANT_SCALE = 1024.0 +TILE_GRID = 16 +TILE_SIZE_M = 192.0 +HALF_EXTENT_M = 1536.0 +SKIRT_DEPTH_M = 4.0 + + +@dataclass +class CgaZoneMesh: + zone_index: int + zone_kind: int + material_class: int + flags: int + support_mask: int + max_hp: float + mass_kg: float + bounds_min: np.ndarray # (3,) + bounds_max: np.ndarray # (3,) + # Triangle soup arrays with attributes + render_tris: np.ndarray # (Tr, 3, 3) float64 + render_mats: np.ndarray # (Tr,) uint8 + render_ao: np.ndarray # (Tr, 3) uint8 + render_uvs: np.ndarray # (Tr, 3, 2) float32 + col_tris: np.ndarray # (Tc, 3, 3) float64 + col_mats: np.ndarray # (Tc,) uint8 (for LOD2/fallback) + + +@dataclass +class CgaBuildingResult: + building_id: int + egid: int + uuid: str + name: str + objektart: str + micro_zone: int + arch_style: int + tx: int + tz: int + local_slot: int + bounds_min: np.ndarray + bounds_max: np.ndarray + ground_y: float + roof_y: float + ground_anchored_mask: int + zones: list[CgaZoneMesh] + + +# --------------------------------------------------------------------------- +# Geometry & Manifold Helpers +# --------------------------------------------------------------------------- +def _clean_polygon_2d(poly: Polygon, min_area: float = 0.05) -> Polygon | None: + if poly.is_empty: + return None + p = poly + if not p.is_valid: + p = p.buffer(0) + if p.is_empty: + return None + if isinstance(p, MultiPolygon): + geoms = [g for g in p.geoms if isinstance(g, Polygon) and g.area >= min_area] + if not geoms: + return None + p = max(geoms, key=lambda g: g.area) + if not isinstance(p, Polygon) or p.area < min_area: + return None + # Strip tiny sliver holes + good_holes = [] + for ring in p.interiors: + hp = Polygon(ring) + if hp.area >= 0.15: + good_holes.append(list(ring.coords)) + p = Polygon(list(p.exterior.coords), good_holes) + if not p.is_valid: + p = p.buffer(0) + if isinstance(p, MultiPolygon): + geoms = [g for g in p.geoms if isinstance(g, Polygon) and g.area >= min_area] + if not geoms: + return None + p = max(geoms, key=lambda g: g.area) + if not isinstance(p, Polygon) or p.area < min_area: + return None + return shapely.geometry.polygon.orient(p, sign=1.0) + + +def _triangulate_2d_manifold(poly: Polygon) -> tuple[np.ndarray, np.ndarray, list[tuple[int, int]]]: + """ + Triangulate a 2D polygon (with optional holes) into a verified 2D indexed manifold mesh: + returns (pts2 (V, 2), tris (T, 3) CCW in (u,v), boundary_edges [(a, b), ...]). + Raises ValueError if CDT produces a non-manifold edge or pinch vertex. + """ + cdt = shapely.constrained_delaunay_triangles(poly) + vert_map: dict[tuple[int, int], int] = {} + verts: list[tuple[float, float]] = [] + tris: list[tuple[int, int, int]] = [] + + def get_vid(x: float, y: float) -> int: + key = (int(round(x * 2000.0)), int(round(y * 2000.0))) + vid = vert_map.get(key) + if vid is None: + vid = len(verts) + vert_map[key] = vid + verts.append((key[0] / 2000.0, key[1] / 2000.0)) + return vid + + for tri_poly in cdt.geoms: + coords = list(tri_poly.exterior.coords) + if len(coords) < 4: + continue + ia = get_vid(coords[0][0], coords[0][1]) + ib = get_vid(coords[1][0], coords[1][1]) + ic = get_vid(coords[2][0], coords[2][1]) + if ia == ib or ib == ic or ic == ia: + continue + ax, ay = verts[ia] + bx, by = verts[ib] + cx, cy = verts[ic] + area2 = (bx - ax) * (cy - ay) - (by - ay) * (cx - ax) + if abs(area2) < 1e-6: + continue + if area2 < 0.0: + ib, ic = ic, ib + tris.append((ia, ib, ic)) + + if not tris: + raise ValueError("Empty 2D triangulation") + + dir_edges: Counter[tuple[int, int]] = Counter() + undir_edges: Counter[tuple[int, int]] = Counter() + for a, b, c in tris: + for u, v in ((a, b), (b, c), (c, a)): + dir_edges[(u, v)] += 1 + undir_edges[(min(u, v), max(u, v))] += 1 + + if any(cnt > 1 for cnt in dir_edges.values()) or any(cnt > 2 for cnt in undir_edges.values()): + raise ValueError("Non-manifold 2D triangulation edge") + + boundary: list[tuple[int, int]] = [] + out_deg: Counter[int] = Counter() + in_deg: Counter[int] = Counter() + for (u, v), cnt in dir_edges.items(): + if cnt == 1 and dir_edges.get((v, u), 0) == 0: + boundary.append((u, v)) + out_deg[u] += 1 + in_deg[v] += 1 + + if not boundary: + raise ValueError("Triangulation has no boundary") + for v_id in set(out_deg.keys()) | set(in_deg.keys()): + if out_deg[v_id] != 1 or in_deg[v_id] != 1: + raise ValueError("Pinch / non-manifold boundary vertex") + + return np.asarray(verts, dtype=np.float64), np.asarray(tris, dtype=np.int32), boundary + + +def extrude_2d_poly_prism( + origin: np.ndarray, + u_axis: np.ndarray, + v_axis: np.ndarray, + n_axis: np.ndarray, + poly_2d: Polygon, + d0: float, + d1: float, + mat_top: int, + mat_bot: int, + mat_side: int, + ao_top: int = 235, + ao_bot: int = 180, + ao_side: int = 210, +) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: + """ + Extrude a 2D polygon in local right-handed frame (u, v, n) over [d0, d1] (d1 > d0) + into a strictly closed, outward-wound 2-manifold triangle soup. + Returns (tris (T,3,3), mats (T,), ao (T,3), uvs (T,3,2)). + """ + assert d1 > d0 + 1e-4 + cleaned = _clean_polygon_2d(poly_2d, min_area=0.04) + if cleaned is None: + u0, v0, u1, v1 = poly_2d.bounds + cleaned = box(u0, v0, max(u0 + 0.1, u1), max(v0 + 0.1, v1)) + + tri_result = None + for candidate in ( + cleaned, + cleaned.simplify(0.05, preserve_topology=True), + Polygon(cleaned.exterior.coords), + box(*cleaned.bounds), + ): + cand_clean = _clean_polygon_2d(candidate, min_area=0.02) + if cand_clean is None: + continue + try: + tri_result = _triangulate_2d_manifold(cand_clean) + break + except ValueError: + continue + if tri_result is None: + u0, v0, u1, v1 = poly_2d.bounds + tri_result = _triangulate_2d_manifold(box(u0, v0, max(u0 + 0.2, u1), max(v0 + 0.2, v1))) + + pts2, tris2, boundary = tri_result + p0_3 = origin[None, :] + pts2[:, 0:1] * u_axis[None, :] + pts2[:, 1:2] * v_axis[None, :] + d0 * n_axis[None, :] + p1_3 = origin[None, :] + pts2[:, 0:1] * u_axis[None, :] + pts2[:, 1:2] * v_axis[None, :] + d1 * n_axis[None, :] + + n_cap = len(tris2) + n_side = len(boundary) * 2 + total = n_cap * 2 + n_side + + out_tris = np.empty((total, 3, 3), dtype=np.float64) + out_mats = np.empty((total,), dtype=np.uint8) + out_ao = np.empty((total, 3), dtype=np.uint8) + out_uvs = np.empty((total, 3, 2), dtype=np.float32) + + u_min = float(pts2[:, 0].min()) + v_min = float(pts2[:, 1].min()) + uv2 = np.column_stack([pts2[:, 0] - u_min, pts2[:, 1] - v_min]).astype(np.float32) + + # Top cap (+n_axis) + out_tris[0:n_cap] = p1_3[tris2] + out_mats[0:n_cap] = mat_top + out_ao[0:n_cap] = ao_top + out_uvs[0:n_cap] = uv2[tris2] + + # Bottom cap (-n_axis, reversed winding) + tris2_rev = tris2[:, [0, 2, 1]] + out_tris[n_cap : 2 * n_cap] = p0_3[tris2_rev] + out_mats[n_cap : 2 * n_cap] = mat_bot + out_ao[n_cap : 2 * n_cap] = ao_bot + out_uvs[n_cap : 2 * n_cap] = uv2[tris2_rev] + + # Side walls along boundary edges (a -> b) + idx = 2 * n_cap + depth = float(d1 - d0) + u_acc = 0.0 + for a, b in boundary: + elen = float(math.hypot(pts2[b, 0] - pts2[a, 0], pts2[b, 1] - pts2[a, 1])) + # Outward side quad: (a0, b0, b1) and (a0, b1, a1) + out_tris[idx, 0] = p0_3[a] + out_tris[idx, 1] = p0_3[b] + out_tris[idx, 2] = p1_3[b] + out_mats[idx] = mat_side + out_ao[idx] = ao_side + out_uvs[idx] = np.array([[u_acc, 0.0], [u_acc + elen, 0.0], [u_acc + elen, depth]], dtype=np.float32) + + out_tris[idx + 1, 0] = p0_3[a] + out_tris[idx + 1, 1] = p1_3[b] + out_tris[idx + 1, 2] = p1_3[a] + out_mats[idx + 1] = mat_side + out_ao[idx + 1] = ao_side + out_uvs[idx + 1] = np.array([[u_acc, 0.0], [u_acc + elen, depth], [u_acc, depth]], dtype=np.float32) + + idx += 2 + u_acc += elen + + return out_tris, out_mats, out_ao, out_uvs + + +def make_box_prism( + origin: np.ndarray, + u_axis: np.ndarray, + v_axis: np.ndarray, + n_axis: np.ndarray, + u0: float, + u1: float, + v0: float, + v1: float, + d0: float, + d1: float, + mat_front: int, + mat_back: int, + mat_side: int, + ao_front: int = 230, + ao_back: int = 195, + ao_side: int = 205, +) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: + """Fast exact 12-triangle closed box prism in local right-handed (u, v, n) frame.""" + def pt(u: float, v: float, d: float) -> np.ndarray: + return origin + u * u_axis + v * v_axis + d * n_axis + + p000, p100, p110, p010 = pt(u0, v0, d0), pt(u1, v0, d0), pt(u1, v1, d0), pt(u0, v1, d0) + p001, p101, p111, p011 = pt(u0, v0, d1), pt(u1, v0, d1), pt(u1, v1, d1), pt(u0, v1, d1) + du = max(0.01, u1 - u0) + dv = max(0.01, v1 - v0) + dd = max(0.01, d1 - d0) + + tris = np.array([ + [p001, p101, p111], [p001, p111, p011], # +n front + [p000, p110, p100], [p000, p010, p110], # -n back + [p000, p001, p011], [p000, p011, p010], # -u left + [p101, p100, p110], [p101, p110, p111], # +u right + [p000, p100, p101], [p000, p101, p001], # -v bottom + [p011, p111, p110], [p011, p110, p010], # +v top + ], dtype=np.float64) + mats = np.array([ + mat_front, mat_front, + mat_back, mat_back, + mat_side, mat_side, + mat_side, mat_side, + mat_side, mat_side, + mat_side, mat_side, + ], dtype=np.uint8) + ao = np.array([ + [ao_front]*3, [ao_front]*3, + [ao_back]*3, [ao_back]*3, + [ao_side]*3, [ao_side]*3, + [ao_side]*3, [ao_side]*3, + [max(120, ao_side - 25)]*3, [max(120, ao_side - 25)]*3, + [min(255, ao_side + 20)]*3, [min(255, ao_side + 20)]*3, + ], dtype=np.uint8) + uvs = np.array([ + [[0, 0], [du, 0], [du, dv]], [[0, 0], [du, dv], [0, dv]], + [[0, 0], [du, dv], [du, 0]], [[0, 0], [0, dv], [du, dv]], + [[0, 0], [dd, 0], [dd, dv]], [[0, 0], [dd, dv], [0, dv]], + [[0, 0], [dd, 0], [dd, dv]], [[0, 0], [dd, dv], [0, dv]], + [[0, 0], [du, 0], [du, dd]], [[0, 0], [du, dd], [0, dd]], + [[0, 0], [du, 0], [du, dd]], [[0, 0], [du, dd], [0, dd]], + ], dtype=np.float32) + return tris, mats, ao, uvs + + +def _concat_parts(parts: list[tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]]) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: + tris = np.concatenate([p[0] for p in parts], axis=0) + mats = np.concatenate([p[1] for p in parts], axis=0) + ao = np.concatenate([p[2] for p in parts], axis=0) + uvs = np.concatenate([p[3] for p in parts], axis=0) + return tris, mats, ao, uvs + + +# --------------------------------------------------------------------------- +# Micro-zone Classification & Vernacular Palette Selection +# --------------------------------------------------------------------------- +def classify_sion_micro_zone( + objektart: str, + name: str, + pts_enz: np.ndarray, + roof_faces_rtd: list[np.ndarray], + ground_rel_y: float, + roof_rel_y: float, +) -> tuple[int, int]: + """Return (micro_zone, arch_style) per Sion local flavor rules.""" + nl = name.lower() + ce = float(pts_enz[:, 0].mean()) + cn = float(pts_enz[:, 1].mean()) + min_z = float(pts_enz[:, 2].min()) + + if objektart in ("Sakrales Gebaeude", "Kapelle", "Sakraler Turm", "Mauer gross"): + return MICRO_FORTRESS, ARCH_FORTRESS + if any(k in nl for k in ("valère", "valere", "tourbillon", "basilique", "château", "chateau", "cathédral", "tous-les-saints", "sorciers")): + return MICRO_FORTRESS, ARCH_FORTRESS + if 2594180.0 <= ce <= 2594650.0 and 1120180.0 <= cn <= 1120660.0 and min_z > 545.0: + return MICRO_FORTRESS, ARCH_FORTRESS + + if any(k in nl for k in ("spital", "hôpital", "hopital", "hôtel de ville", "hotel de ville", "palais", "gouvernement", "théâtre", "theatre", "école", "ecole", "collège", "college", "gare", "tribunal", "musée", "musee")): + return MICRO_CIVIC, ARCH_RESIDENTIAL + + if objektart in ("Hochhaus", "Offenes Gebaeude", "Flugdach", "Unterirdisches Gebaeude", "Im Bau", "Lagertank", "Treibhaus"): + return MICRO_RONQUOZ, ARCH_INDUSTRIAL + + dx = float(pts_enz[:, 0].max() - pts_enz[:, 0].min()) + dn = float(pts_enz[:, 1].max() - pts_enz[:, 1].min()) + area_box = dx * dn + if area_box > 750.0 and min_z < 508.0 and roof_faces_rtd: + flat_area = 0.0 + total_area = 0.0 + for rf in roof_faces_rtd: + v0, v1, v2 = rf[0], rf[1], rf[-1] + c = np.cross(v1 - v0, v2 - v0) + a = 0.5 * float(np.linalg.norm(c)) + if a > 1e-6: + ny = abs(float(c[1]) / (2.0 * a)) + total_area += a + if ny > 0.985: + flat_area += a + if total_area > 1.0 and (flat_area / total_area) > 0.75: + return MICRO_RONQUOZ, ARCH_INDUSTRIAL + + if cn < 1119900.0: + return MICRO_RONQUOZ, ARCH_INDUSTRIAL + + if 2593700.0 <= ce <= 2594600.0 and 1120000.0 <= cn <= 1120650.0: + return MICRO_OLD_TOWN, ARCH_RESIDENTIAL + + if cn >= 1120650.0 and ground_rel_y > 14.0: + return MICRO_CLAVAU, ARCH_RESIDENTIAL + + height = roof_rel_y - ground_rel_y + if (ce >= 2594500.0 and cn < 1120350.0) or (height >= 12.5 and cn >= 1119900.0): + return MICRO_VISSIGEN, ARCH_RESIDENTIAL + + return MICRO_SUBURBAN, ARCH_RESIDENTIAL + + +def _choose_building_palette(b_hash: int, micro_zone: int, objektart: str) -> dict[str, int]: + """Select deterministic material palette IDs & structural material classes for a building.""" + crepis_choices = [ + PAL_CREPIS_OCHRE, + PAL_CREPIS_CREAM, + PAL_CREPIS_VENETIAN_RED, + PAL_CREPIS_SAGE, + PAL_CREPIS_SAND, + ] + shutter_choices = [PAL_SHUTTER_GREEN, PAL_SHUTTER_RED, PAL_SHUTTER_BROWN] + + if micro_zone == MICRO_FORTRESS: + return { + "plinth": PAL_PLINTH_STONE, + "wall": PAL_FORTRESS_STONE, + "interior": PAL_FORTRESS_STONE, + "slab": PAL_CONCRETE_SLAB, + "trim": PAL_STONE_TRIM, + "roof": PAL_ROOF_LAUZES, + "shutter": PAL_SHUTTER_BROWN, + "wall_class": MAT_CLASS_FORTRESS_STONE, + "roof_class": MAT_CLASS_FORTRESS_STONE, + "plinth_class": MAT_CLASS_FORTRESS_STONE, + } + if micro_zone == MICRO_OLD_TOWN: + return { + "plinth": PAL_PLINTH_STONE, + "wall": crepis_choices[b_hash % len(crepis_choices)], + "interior": PAL_INTERIOR_PLASTER, + "slab": PAL_CONCRETE_SLAB, + "trim": PAL_STONE_TRIM, + "roof": PAL_ROOF_LAUZES if (b_hash // 5) % 4 == 0 else PAL_ROOF_TERRACOTTA, + "shutter": shutter_choices[(b_hash // 7) % len(shutter_choices)], + "wall_class": MAT_CLASS_MASONRY, + "roof_class": MAT_CLASS_MASONRY, + "plinth_class": MAT_CLASS_FORTRESS_STONE, + } + if micro_zone == MICRO_CLAVAU: + return { + "plinth": PAL_PLINTH_STONE, + "wall": crepis_choices[(b_hash + 1) % 3], # ochre, cream, or venetian red / stone + "interior": PAL_INTERIOR_PLASTER, + "slab": PAL_CONCRETE_SLAB, + "trim": PAL_STONE_TRIM, + "roof": PAL_ROOF_TERRACOTTA, + "shutter": shutter_choices[(b_hash // 3) % len(shutter_choices)], + "wall_class": MAT_CLASS_MASONRY, + "roof_class": MAT_CLASS_MASONRY, + "plinth_class": MAT_CLASS_FORTRESS_STONE, + } + if micro_zone == MICRO_VISSIGEN: + return { + "plinth": PAL_CONCRETE_SLAB, + "wall": PAL_CONCRETE_AGGREGATE, + "interior": PAL_INTERIOR_PLASTER, + "slab": PAL_CONCRETE_SLAB, + "trim": PAL_CONCRETE_SLAB, + "roof": PAL_ROOF_INDUSTRIAL, + "shutter": PAL_SHUTTER_BROWN, + "wall_class": MAT_CLASS_CONCRETE, + "roof_class": MAT_CLASS_CONCRETE, + "plinth_class": MAT_CLASS_CONCRETE, + } + if micro_zone == MICRO_RONQUOZ: + is_glass = objektart in ("Treibhaus",) + return { + "plinth": PAL_CONCRETE_SLAB, + "wall": PAL_CORRUGATED_STEEL if not is_glass else PAL_WINDOW_DARK_GLASS, + "interior": PAL_CONCRETE_SLAB, + "slab": PAL_CONCRETE_SLAB, + "trim": PAL_CONCRETE_SLAB, + "roof": PAL_ROOF_INDUSTRIAL, + "shutter": PAL_SHUTTER_BROWN, + "wall_class": MAT_CLASS_TIMBER_OR_GLASS if is_glass else MAT_CLASS_STEEL, + "roof_class": MAT_CLASS_STEEL, + "plinth_class": MAT_CLASS_CONCRETE, + } + if micro_zone == MICRO_CIVIC: + return { + "plinth": PAL_PLINTH_STONE, + "wall": PAL_CREPIS_CREAM if b_hash % 2 == 0 else PAL_CREPIS_SAND, + "interior": PAL_INTERIOR_PLASTER, + "slab": PAL_CONCRETE_SLAB, + "trim": PAL_STONE_TRIM, + "roof": PAL_ROOF_LAUZES, + "shutter": PAL_SHUTTER_GREEN, + "wall_class": MAT_CLASS_MASONRY, + "roof_class": MAT_CLASS_MASONRY, + "plinth_class": MAT_CLASS_FORTRESS_STONE, + } + # Suburban + return { + "plinth": PAL_CONCRETE_SLAB, + "wall": crepis_choices[(b_hash // 3) % len(crepis_choices)], + "interior": PAL_INTERIOR_PLASTER, + "slab": PAL_CONCRETE_SLAB, + "trim": PAL_STONE_TRIM, + "roof": PAL_ROOF_TERRACOTTA if (b_hash % 3) != 0 else PAL_ROOF_LAUZES, + "shutter": shutter_choices[(b_hash // 5) % len(shutter_choices)], + "wall_class": MAT_CLASS_MASONRY, + "roof_class": MAT_CLASS_MASONRY, + "plinth_class": MAT_CLASS_CONCRETE, + } + + +def _material_hp_density(mat_class: int) -> tuple[float, float]: + """Return (hp_per_m3_scale, density_kg_per_m3) for deterministic zone HP & mass.""" + return { + MAT_CLASS_FORTRESS_STONE: (55.0, 2450.0), + MAT_CLASS_CONCRETE: (42.0, 2350.0), + MAT_CLASS_MASONRY: (26.0, 1850.0), + MAT_CLASS_STEEL: (32.0, 950.0), + MAT_CLASS_TIMBER_OR_GLASS: (14.0, 500.0), + }[mat_class] + + +# --------------------------------------------------------------------------- +# Footprint & Wall Bay / Slab / Roof Builders +# --------------------------------------------------------------------------- +def _extract_footprint_polygons( + fl_rtd: list[np.ndarray], + w_rtd: list[np.ndarray], + r_rtd: list[np.ndarray], + s_rtd: list[np.ndarray], + simplify_tol: float, +) -> list[Polygon]: + polys: list[Polygon] = [] + for src in (fl_rtd, s_rtd, r_rtd): + if not src: + continue + for face in src: + if len(face) < 3: + continue + p = Polygon(face[:, [0, 2]]) + if not p.is_valid: + p = p.buffer(0) + if not p.is_empty and p.area > 0.25: + polys.append(p) + if polys: + break + + if not polys and w_rtd: + for face in w_rtd: + if len(face) < 2: + continue + # Project wall bounding rectangle / polyline buffered in XZ + pts_xz = face[:, [0, 2]] + ls = shapely.LineString(pts_xz) + bp = ls.buffer(0.35, cap_style="square") + if not bp.is_empty and bp.area > 0.25: + polys.append(bp) + + if not polys: + return [] + + merged = unary_union(polys) + geoms = list(merged.geoms) if hasattr(merged, "geoms") else [merged] + out: list[Polygon] = [] + for g in geoms: + if not isinstance(g, Polygon) or g.is_empty or g.area < 1.0: + continue + gs = g.simplify(simplify_tol, preserve_topology=True) + if isinstance(gs, MultiPolygon): + gs = max(gs.geoms, key=lambda item: item.area) + cleaned = _clean_polygon_2d(gs if isinstance(gs, Polygon) and gs.area >= 1.0 else g, min_area=1.0) + if cleaned is not None: + out.append(cleaned) + out.sort(key=lambda p: p.area, reverse=True) + return out[:2] # keep primary footprint (and at most 1 secondary annex) so zones stay well <= 64 + + +def _merge_short_ring_edges(coords: list[tuple[float, float]], min_edge_len: float = 1.2) -> list[tuple[float, float]]: + """Collapse tiny jagged edge steps so wall bays don't fragment into micro-slivers.""" + pts = list(coords[:-1]) # open ring + if len(pts) <= 3: + return pts + changed = True + while changed and len(pts) > 3: + changed = False + new_pts: list[tuple[float, float]] = [] + i = 0 + while i < len(pts): + a = pts[i] + b = pts[(i + 1) % len(pts)] + if math.hypot(b[0] - a[0], b[1] - a[1]) < min_edge_len and len(pts) - (1 if new_pts else 0) > 3: + if i + 1 < len(pts): + new_pts.append((0.5 * (a[0] + b[0]), 0.5 * (a[1] + b[1]))) + i += 2 + changed = True + continue + new_pts.append(a) + i += 1 + pts = new_pts + return pts + + +def _split_ring_into_wall_bays( + ring_pts: list[tuple[float, float]], + max_bay_len: float, + is_hole: bool = False, +) -> list[tuple[np.ndarray, np.ndarray, float]]: + """ + Return list of (p_start_xz (2,), p_end_xz (2,), length) oriented so + outward normal points AWAY from the building solid. + For CCW outer ring in (X, Z): interior is on LEFT in (X, Z) math -> outward is RIGHT = (dz, -dx). + For CW hole ring: interior of building is STILL on LEFT of ring traversal -> outward into courtyard is STILL RIGHT! + """ + bays: list[tuple[np.ndarray, np.ndarray, float]] = [] + n = len(ring_pts) + for k in range(n): + ax, az = ring_pts[k] + bx, bz = ring_pts[(k + 1) % n] + elen = math.hypot(bx - ax, bz - az) + if elen < 0.75: + continue + n_sub = max(1, int(math.ceil(elen / max_bay_len))) + pa = np.array([ax, az], dtype=np.float64) + pb = np.array([bx, bz], dtype=np.float64) + for s in range(n_sub): + t0 = s / n_sub + t1 = (s + 1) / n_sub + sa = pa + (pb - pa) * t0 + sb = pa + (pb - pa) * t1 + slen = float(np.linalg.norm(sb - sa)) + if slen >= 0.75: + bays.append((sa, sb, slen)) + return bays + + +def _build_wall_bay_geometry( + sa_xz: np.ndarray, + sb_xz: np.ndarray, + bay_len: float, + y_bot: float, + y_top: float, + wall_thick: float, + pal: dict[str, int], + micro_zone: int, + allow_details: bool, +) -> tuple[ + tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray], + tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray], + bool, +]: + """ + Construct one watertight WallBayZone (render_parts, col_parts, has_windows). + Frame: + tangent t = (sb - sa) / bay_len = (tx, 0, tz) + u_axis = (-tx, 0, -tz) + v_axis = (0, 1, 0) + n_axis = cross(u_axis, v_axis) = (tz, 0, -tx) [OUTWARD] + origin = (sb_xz[0], y_bot, sb_xz[1]) so u spans [0, bay_len], v spans [0, h] + """ + tx = (sb_xz[0] - sa_xz[0]) / bay_len + tz = (sb_xz[1] - sa_xz[1]) / bay_len + u_axis = np.array([-tx, 0.0, -tz], dtype=np.float64) + v_axis = np.array([0.0, 1.0, 0.0], dtype=np.float64) + n_axis = np.array([tz, 0.0, -tx], dtype=np.float64) # outward + origin = np.array([sb_xz[0], y_bot, sb_xz[1]], dtype=np.float64) + h = y_top - y_bot + + col_parts = make_box_prism( + origin, u_axis, v_axis, n_axis, + 0.0, bay_len, 0.0, h, -wall_thick, 0.0, + pal["wall"], pal["interior"], pal["wall"], + ) + + if not allow_details or bay_len < 2.2 or h < 2.25: + return col_parts, col_parts, False + + # Compute window openings within [0..bay_len] x [0..h] + # Keep at least 0.45m solid jambs on edges and 0.45m sill/header margins + if micro_zone == MICRO_FORTRESS: + win_step = 3.4 + n_win = max(1, min(3, int((bay_len - 0.9) / win_step))) + win_w = min(0.70, (bay_len - 0.9) / n_win * 0.45) + win_h = min(1.75, h * 0.56) + elif micro_zone == MICRO_RONQUOZ: + win_step = 4.2 + n_win = max(1, min(3, int((bay_len - 1.0) / win_step))) + win_w = min(2.20, (bay_len - 1.0) / n_win * 0.64) + win_h = min(1.30, h * 0.40) + else: + win_step = 3.0 + n_win = max(1, min(3, int((bay_len - 0.8) / win_step))) + win_w = min(1.12, (bay_len - 0.8) / n_win * 0.48) + win_h = min(1.42, h * 0.52) + + if win_w < 0.50 or win_h < 0.70: + return col_parts, col_parts, False + + vc = h * 0.54 + wv0 = max(0.45, vc - win_h * 0.5) + wv1 = min(h - 0.35, vc + win_h * 0.5) + if wv1 - wv0 < 0.65: + return col_parts, col_parts, False + + step_u = (bay_len - 0.8) / n_win + holes: list[list[tuple[float, float]]] = [] + win_boxes: list[tuple[float, float, float, float]] = [] + for wi in range(n_win): + uc = 0.4 + (wi + 0.5) * step_u + wu0 = uc - win_w * 0.5 + wu1 = uc + win_w * 0.5 + if wu0 < 0.38 or wu1 > bay_len - 0.38: + continue + holes.append([(wu0, wv0), (wu0, wv1), (wu1, wv1), (wu1, wv0)]) # CW hole + win_boxes.append((wu0, wu1, wv0, wv1)) + + if not holes: + return col_parts, col_parts, False + + # Inner solid wall backing: [-wall_thick .. -0.19] (thickness >= 0.23m) + parts: list[tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]] = [] + parts.append(make_box_prism( + origin, u_axis, v_axis, n_axis, + 0.0, bay_len, 0.0, h, -wall_thick, -0.19, + pal["wall"], pal["interior"], pal["wall"], + ao_front=175, ao_back=195, ao_side=195, + )) + + # Outer pierced facade frame: [-0.22 .. 0.00] (0.22m reveal depth, 3cm overlap with inner wall) + outer_poly = Polygon([(0.0, 0.0), (bay_len, 0.0), (bay_len, h), (0.0, h)], holes) + parts.append(extrude_2d_poly_prism( + origin, u_axis, v_axis, n_axis, outer_poly, + -0.22, 0.0, + mat_top=pal["wall"], mat_bot=pal["wall"], mat_side=pal["trim"], + ao_top=235, ao_bot=190, ao_side=155, + )) + + # Window glass backing + stone sills / lintels / optional Old Town shutters + # Kept strictly disjoint / >= 2cm overlap from coplanar faces so quantized welding stays manifold! + for wu0, wu1, wv0_i, wv1_i in win_boxes: + # Recessed dark glass box inside opening (penetrates jambs 2cm, front at d=-0.16) + parts.append(make_box_prism( + origin, u_axis, v_axis, n_axis, + wu0 - 0.02, wu1 + 0.02, wv0_i - 0.02, wv1_i + 0.02, -0.205, -0.16, + PAL_WINDOW_DARK_GLASS, PAL_WINDOW_DARK_GLASS, PAL_WINDOW_DARK_GLASS, + ao_front=190, ao_back=160, ao_side=150, + )) + + if micro_zone in (MICRO_OLD_TOWN, MICRO_CLAVAU, MICRO_FORTRESS, MICRO_CIVIC): + # Stone sill (projecting 0.10m outward, 0.11m tall) + parts.append(make_box_prism( + origin, u_axis, v_axis, n_axis, + wu0 - 0.06, wu1 + 0.06, max(0.05, wv0_i - 0.12), wv0_i - 0.015, -0.03, 0.10, + pal["trim"], pal["trim"], pal["trim"], + ao_front=235, ao_back=180, ao_side=200, + )) + # Stone lintel + parts.append(make_box_prism( + origin, u_axis, v_axis, n_axis, + wu0 - 0.06, wu1 + 0.06, wv1_i + 0.015, min(h - 0.05, wv1_i + 0.13), -0.03, 0.08, + pal["trim"], pal["trim"], pal["trim"], + ao_front=235, ao_back=180, ao_side=190, + )) + + if micro_zone in (MICRO_OLD_TOWN, MICRO_CLAVAU) and bay_len >= 4.2 and step_u >= 2.6: + sh_w = min(0.36, win_w * 0.40) + if wu0 - sh_w - 0.06 > 0.12 and wu1 + sh_w + 0.06 < bay_len - 0.12: + parts.append(make_box_prism( + origin, u_axis, v_axis, n_axis, + wu0 - sh_w - 0.04, wu0 - 0.03, wv0_i + 0.03, wv1_i - 0.03, -0.02, 0.045, + pal["shutter"], pal["shutter"], pal["shutter"], + ao_front=220, ao_back=170, ao_side=185, + )) + parts.append(make_box_prism( + origin, u_axis, v_axis, n_axis, + wu1 + 0.03, wu1 + sh_w + 0.04, wv0_i + 0.03, wv1_i - 0.03, -0.02, 0.045, + pal["shutter"], pal["shutter"], pal["shutter"], + ao_front=220, ao_back=170, ao_side=185, + )) + + return _concat_parts(parts), col_parts, True + + +def _build_roof_zones( + r_oriented: list[np.ndarray], + footprints: list[Polygon], + eave_y: float, + bldg_center_xz: np.ndarray, + pal: dict[str, int], + max_roof_zones: int, + micro_zone: int, + objektart: str, +) -> list[tuple[tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray], tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray], np.ndarray]]: + """ + Build closed 2-manifold extruded roof plate zones (>= 0.32m thick). + Returns list of (render_parts, col_parts, centroid_xyz). + """ + if objektart == "Mauer gross" or max_roof_zones <= 0: + return [] + + roof_mat = pal["roof"] + roof_thick = 0.34 + out: list[tuple[tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray], tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray], np.ndarray]] = [] + + if r_oriented: + # Merge coplanar roof faces into planar polygons in local (u, v, n) frame + groups: dict[tuple[int, int, int, int], list[tuple[np.ndarray, np.ndarray]]] = defaultdict(list) + for f in r_oriented: + if len(f) < 3: + continue + p0 = f + p1 = np.roll(f, -1, axis=0) + n = np.array([ + np.sum((p0[:, 1] - p1[:, 1]) * (p0[:, 2] + p1[:, 2])), + np.sum((p0[:, 2] - p1[:, 2]) * (p0[:, 0] + p1[:, 0])), + np.sum((p0[:, 0] - p1[:, 0]) * (p0[:, 1] + p1[:, 1])), + ], dtype=np.float64) + ln = float(np.linalg.norm(n)) + if ln < 1e-8: + continue + n /= ln + if n[1] < 0.0: + n = -n + d = float(np.dot(n, f[0])) + key = (int(round(n[0] * 16.0)), int(round(n[1] * 16.0)), int(round(n[2] * 16.0)), int(round(d * 2.0))) + groups[key].append((f, n)) + + up = np.array([0.0, 1.0, 0.0], dtype=np.float64) + planes: list[tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, Polygon]] = [] + for items in groups.values(): + n_avg = np.mean([it[1] for it in items], axis=0) + ln = float(np.linalg.norm(n_avg)) + if ln < 1e-8: + continue + n_axis = n_avg / ln + if n_axis[1] < 0.05: + continue # skip tiny vertical fascia slivers in roof layer + origin = items[0][0][0] + if abs(n_axis[1]) < 0.9: + u_axis = np.cross(up, n_axis) + else: + u_axis = np.cross(np.array([0.0, 0.0, -1.0]), n_axis) + u_axis /= np.linalg.norm(u_axis) + # Ensure right-handed: cross(u_axis, v_axis) == n_axis -> v_axis = cross(n_axis, u_axis) + v_axis = np.cross(n_axis, u_axis) + + polys = [] + for f, _ in items: + rel = f - origin + pts2 = np.column_stack([rel @ u_axis, rel @ v_axis]) + p = Polygon(pts2) + if not p.is_valid: + p = p.buffer(0) + if not p.is_empty and p.area > 0.08: + polys.append(p) + if not polys: + continue + merged = unary_union(polys) + geoms = list(merged.geoms) if hasattr(merged, "geoms") else [merged] + for g in geoms: + if isinstance(g, Polygon) and g.area > 0.6: + gs = g.simplify(0.22, preserve_topology=True) + if isinstance(gs, Polygon) and gs.area > 0.6: + g = gs + # Add gentle eave overhang on pitched slopes + if n_axis[1] < 0.97 and micro_zone in (MICRO_OLD_TOWN, MICRO_CLAVAU, MICRO_SUBURBAN, MICRO_FORTRESS, MICRO_CIVIC): + gb = g.buffer(0.22, join_style="mitre") + if isinstance(gb, Polygon) and gb.area > g.area * 0.9: + g = gb + planes.append((origin, u_axis, v_axis, n_axis, g)) + + # Sort largest planes first; cap at max_roof_zones + planes.sort(key=lambda item: item[4].area, reverse=True) + for origin, u_axis, v_axis, n_axis, poly in planes[:max_roof_zones]: + parts = extrude_2d_poly_prism( + origin, u_axis, v_axis, n_axis, poly, + -roof_thick, 0.0, + mat_top=roof_mat, mat_bot=pal["trim"], mat_side=pal["trim"], + ao_top=245, ao_bot=165, ao_side=200, + ) + rp = poly.representative_point() + c3 = origin + rp.x * u_axis + rp.y * v_axis + out.append((parts, parts, c3)) + + if not out and footprints: + # Flat roof slab cap over primary footprint + origin = np.array([0.0, eave_y, 0.0], dtype=np.float64) + u_axis = np.array([1.0, 0.0, 0.0], dtype=np.float64) + v_axis = np.array([0.0, 0.0, -1.0], dtype=np.float64) + n_axis = np.array([0.0, 1.0, 0.0], dtype=np.float64) + # Project XZ polygon into (u=X, v=-Z) + fp = footprints[0] + ext = [(x, -z) for x, z in fp.exterior.coords] + holes = [[(x, -z) for x, z in h.coords] for h in fp.interiors] + uv_poly = Polygon(ext, holes) + parts = extrude_2d_poly_prism( + origin, u_axis, v_axis, n_axis, uv_poly, + 0.0, roof_thick, + mat_top=roof_mat, mat_bot=pal["slab"], mat_side=pal["trim"], + ao_top=240, ao_bot=175, ao_side=205, + ) + c3 = np.array([bldg_center_xz[0], eave_y + roof_thick * 0.5, bldg_center_xz[1]], dtype=np.float64) + out.append((parts, parts, c3)) + + return out + + +# --------------------------------------------------------------------------- +# Main Building Decomposer -> CgaBuildingResult (<= 64 zones, DAG, watertight) +# --------------------------------------------------------------------------- +def build_cga_building( + building_id: int, + egid: int, + uuid: str, + name: str, + objektart: str, + pts_enz: np.ndarray, + w_rtd: list[np.ndarray], + r_rtd: list[np.ndarray], + fl_rtd: list[np.ndarray], + s_rtd: list[np.ndarray], + terrain_min_y: float, + terrain_max_y: float, + tx: int, + tz: int, + local_slot: int, +) -> CgaBuildingResult: + all_pts = np.vstack(w_rtd + r_rtd + fl_rtd + s_rtd) + raw_min_y = float(all_pts[:, 1].min()) + raw_max_y = float(all_pts[:, 1].max()) + b_hash = int.from_bytes(hashlib.blake2b(uuid.encode("utf-8"), digest_size=4).digest(), "little") + + micro_zone, arch_style = classify_sion_micro_zone(objektart, name, pts_enz, r_rtd, raw_min_y, raw_max_y) + pal = _choose_building_palette(b_hash, micro_zone, objektart) + + simplify_tol = 0.14 if micro_zone == MICRO_FORTRESS else 0.28 + footprints = _extract_footprint_polygons(fl_rtd, w_rtd, r_rtd, s_rtd, simplify_tol=simplify_tol) + if not footprints: + xmin, zmin = float(all_pts[:, 0].min()), float(all_pts[:, 2].min()) + xmax, zmax = float(all_pts[:, 0].max()), float(all_pts[:, 2].max()) + footprints = [_clean_polygon_2d(box(xmin, zmin, max(xmin + 1.5, xmax), max(zmin + 1.5, zmax))) or box(xmin, zmin, xmin + 2.0, zmin + 2.0)] + + primary_fp = footprints[0] + fp_cx, fp_cz = primary_fp.centroid.x, primary_fp.centroid.y + bldg_center_xz = np.array([fp_cx, fp_cz], dtype=np.float64) + + # Determine vertical bounds: Plinth anchors down to terrain_min_y - 4.0m + plinth_bot_y = min(raw_min_y, terrain_min_y) - SKIRT_DEPTH_M + + # Wall top (eave_y) + if w_rtd: + w_pts = np.vstack(w_rtd) + eave_y = float(np.percentile(w_pts[:, 1], 95)) + elif r_rtd: + r_pts = np.vstack(r_rtd) + eave_y = float(r_pts[:, 1].min()) + else: + eave_y = raw_max_y + + # Handle underground / ultra-low structures cleanly + if objektart == "Unterirdisches Gebaeude" or (raw_max_y - raw_min_y < 1.3 and not w_rtd): + plinth_top_y = max(raw_max_y, terrain_min_y + 0.8, plinth_bot_y + 2.0) + eave_y = plinth_top_y + else: + plinth_top_y = min(eave_y - 1.4, max(raw_min_y + 0.55, min(terrain_max_y + 0.35, raw_min_y + 2.4))) + if plinth_top_y <= plinth_bot_y + 1.0: + plinth_top_y = plinth_bot_y + 1.5 + if eave_y < plinth_top_y + 1.2 and w_rtd: + eave_y = plinth_top_y + 2.4 + + zones: list[CgaZoneMesh] = [] + + def add_zone( + zone_kind: int, + mat_class: int, + flags: int, + support_mask: int, + render_parts: tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray], + col_parts: tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray], + ) -> int: + z_idx = len(zones) + assert z_idx < MAX_ZONES_PER_BUILDING, f"Zone count overflow on {uuid}" + r_tris, r_mats, r_ao, r_uvs = render_parts + c_tris, c_mats, _, _ = col_parts + c_pts = c_tris.reshape(-1, 3) + bmin = c_pts.min(axis=0) + bmax = c_pts.max(axis=0) + ext = np.maximum(bmax - bmin, 0.1) + vol = float(ext[0] * ext[1] * ext[2]) + if zone_kind == ZONE_WALL_BAY: + eff_vol = float(max(ext[0], ext[2]) * ext[1] * 0.45) + elif zone_kind == ZONE_FLOOR_SLAB or zone_kind == ZONE_ROOF_SEGMENT: + eff_vol = float(ext[0] * ext[2] * 0.30) + else: + eff_vol = vol * 0.45 + hp_scale, density = _material_hp_density(mat_class) + max_hp = float(max(120.0, min(8500.0, eff_vol * hp_scale))) + mass_kg = float(max(250.0, eff_vol * density)) + zones.append(CgaZoneMesh( + zone_index=z_idx, + zone_kind=zone_kind, + material_class=mat_class, + flags=flags, + support_mask=support_mask, + max_hp=max_hp, + mass_kg=mass_kg, + bounds_min=bmin, + bounds_max=bmax, + render_tris=r_tris, + render_mats=r_mats, + render_ao=r_ao, + render_uvs=r_uvs, + col_tris=c_tris, + col_mats=c_mats, + )) + return z_idx + + # Helper to extrude XZ shapely Polygon over [y0, y1] + u_xz = np.array([1.0, 0.0, 0.0], dtype=np.float64) + v_xz = np.array([0.0, 0.0, -1.0], dtype=np.float64) + n_up = np.array([0.0, 1.0, 0.0], dtype=np.float64) + + def fp_to_uv(fp_poly: Polygon) -> Polygon: + ext = [(x, -z) for x, z in fp_poly.exterior.coords] + holes = [[(x, -z) for x, z in h.coords] for h in fp_poly.interiors] + return Polygon(ext, holes) + + # 1. Zone 0: Plinth / Foundation (IsGroundAnchored = true) + plinth_uv = fp_to_uv(primary_fp) + plinth_parts = extrude_2d_poly_prism( + np.array([0.0, plinth_bot_y, 0.0]), u_xz, v_xz, n_up, plinth_uv, + 0.0, plinth_top_y - plinth_bot_y, + mat_top=pal["slab"], mat_bot=pal["plinth"], mat_side=pal["plinth"], + ao_top=195, ao_bot=140, ao_side=165, + ) + plinth_idx = add_zone( + ZONE_PLINTH, pal["plinth_class"], + ZONE_FLAG_GROUND_ANCHORED | ZONE_FLAG_EXTERIOR, + 0, plinth_parts, plinth_parts, + ) + plinth_bit = 1 << plinth_idx + + wall_h = max(0.0, eave_y - plinth_top_y) + is_canopy_only = (len(w_rtd) == 0 and wall_h > 1.2) or objektart in ("Flugdach",) + is_mauer = (objektart == "Mauer gross") + + # Early exit for low/underground single-zone structures + if wall_h < 0.9 and not r_rtd: + c_pts = np.vstack([z.col_tris.reshape(-1, 3) for z in zones]) + return CgaBuildingResult( + building_id=building_id, egid=egid, uuid=uuid, name=name, objektart=objektart, + micro_zone=micro_zone, arch_style=arch_style, tx=tx, tz=tz, local_slot=local_slot, + bounds_min=c_pts.min(axis=0), bounds_max=c_pts.max(axis=0), + ground_y=float(c_pts[:, 1].min()), roof_y=float(c_pts[:, 1].max()), + ground_anchored_mask=plinth_bit, zones=zones, + ) + + # 2. Precompute Roof Zones so we know exact zone budget + max_roofs = 0 if is_mauer else 6 + roof_items = _build_roof_zones( + r_rtd, footprints, eave_y, bldg_center_xz, pal, max_roofs, micro_zone, objektart + ) + n_roofs = len(roof_items) + + # 3. Canopy / Open Shed without walls (columns/core + roof) + if is_canopy_only or wall_h < 1.2: + # Add 1 InteriorCore pier supporting the roof + minx, minz, maxx, maxz = primary_fp.bounds + cw = max(0.6, min(2.4, (maxx - minx) * 0.22)) + cd = max(0.6, min(2.4, (maxz - minz) * 0.22)) + core_top = max(plinth_top_y + 0.8, eave_y) + core_parts = make_box_prism( + np.array([fp_cx, plinth_top_y, fp_cz]), u_xz, v_xz, n_up, + -cw * 0.5, cw * 0.5, -cd * 0.5, cd * 0.5, 0.0, core_top - plinth_top_y, + pal["slab"], pal["slab"], pal["trim"], + ) + core_idx = add_zone(ZONE_INTERIOR_CORE, pal["plinth_class"], 0, plinth_bit, core_parts, core_parts) + core_bit = 1 << core_idx + for r_render, r_col, _ in roof_items: + if len(zones) >= MAX_ZONES_PER_BUILDING: + break + add_zone(ZONE_ROOF_SEGMENT, pal["roof_class"], ZONE_FLAG_EXTERIOR, core_bit, r_render, r_col) + else: + # 4. Standard Multi-Story Decomposition (Core + WallBays + FloorSlabs + Roofs) + story_h_target = { + MICRO_OLD_TOWN: 3.1, + MICRO_CLAVAU: 3.0, + MICRO_VISSIGEN: 2.9, + MICRO_RONQUOZ: 4.0, + MICRO_SUBURBAN: 3.0, + MICRO_FORTRESS: 3.8, + MICRO_CIVIC: 3.2, + }[micro_zone] + + n_stories = max(1, int(round(wall_h / story_h_target))) + # Extract simplified perimeter segments for WallBays + ext_pts = _merge_short_ring_edges(list(primary_fp.exterior.coords), min_edge_len=1.6) + raw_bays_len = max(3, len(ext_pts)) + + # Budget: 1 (Plinth) + 1 (Core) + n_roofs + n_tiers * (bays_per_tier + 1 slab) <= 64 + avail_for_stories = MAX_ZONES_PER_BUILDING - (2 + n_roofs) + n_tiers = min(n_stories, max(1, avail_for_stories // max(4, min(raw_bays_len + 1, 10)))) + n_tiers = max(1, min(n_tiers, 8)) + + # Max bays per tier that fits inside budget + max_bays_per_tier = max(3, (avail_for_stories // n_tiers) - 1) + + # Dynamically choose max_bay_len so bay count fits max_bays_per_tier cleanly + perim = float(primary_fp.exterior.length) + base_bay_len = 10.0 if (is_mauer or perim > 60.0) else 8.0 + bays_2d: list[tuple[np.ndarray, np.ndarray, float]] = [] + for mult in (1.0, 1.4, 2.0, 3.0, 5.0, 10.0): + cand = _split_ring_into_wall_bays(ext_pts, base_bay_len * mult) + if len(cand) <= max_bays_per_tier: + bays_2d = cand + break + if not bays_2d: + # Simplify footprint more aggressively to a clean bounding/octagonal hull + simple_fp = primary_fp.simplify(max(0.6, perim * 0.03), preserve_topology=True) + if isinstance(simple_fp, Polygon) and not simple_fp.is_empty: + ext_pts = _merge_short_ring_edges(list(simple_fp.exterior.coords), min_edge_len=2.2) + cand = _split_ring_into_wall_bays(ext_pts, max(base_bay_len, perim / max(3, max_bays_per_tier))) + if len(cand) <= max_bays_per_tier: + bays_2d = cand + else: + # Guaranteed 4-bay oriented bounding box fallback + minx, minz, maxx, maxz = primary_fp.bounds + box_pts = [(minx, minz), (maxx, minz), (maxx, maxz), (minx, maxz)] + bays_2d = _split_ring_into_wall_bays(box_pts, max(maxx - minx, maxz - minz) + 1.0) + + # 4a. InteriorCore zone (spans full height plinth_top_y .. eave_y - 0.15) + minx, minz, maxx, maxz = primary_fp.bounds + cw = max(0.8, min(3.0, (maxx - minx) * 0.24)) + cd = max(0.8, min(3.0, (maxz - minz) * 0.24)) + core_h = max(0.8, wall_h - 0.15) + core_parts = make_box_prism( + np.array([fp_cx, plinth_top_y, fp_cz]), u_xz, v_xz, n_up, + -cw * 0.5, cw * 0.5, -cd * 0.5, cd * 0.5, 0.0, core_h, + pal["slab"], pal["slab"], pal["interior"], + ao_front=185, ao_back=185, ao_side=185, + ) + core_idx = add_zone(ZONE_INTERIOR_CORE, pal["plinth_class"], 0, plinth_bit, core_parts, core_parts) + core_bit = 1 << core_idx + + wall_thick = 0.85 if is_mauer else (0.68 if micro_zone == MICRO_FORTRESS else 0.45) + slab_inset = min(wall_thick * 0.45, 0.20) + slab_fp = primary_fp.buffer(-slab_inset, join_style="mitre") + if not isinstance(slab_fp, Polygon) or slab_fp.is_empty or slab_fp.area < 0.8: + slab_fp = primary_fp + slab_uv = fp_to_uv(slab_fp) + slab_thick = 0.28 + + tier_h = wall_h / n_tiers + prev_bay_indices: list[int] = [] + prev_bay_mids: list[np.ndarray] = [] + all_tier_supports_mask = plinth_bit | core_bit + + # Allow detailed windowed bays while keeping total city triangles crisp & compact + perim_details = (micro_zone in (MICRO_OLD_TOWN, MICRO_FORTRESS, MICRO_CIVIC, MICRO_CLAVAU)) or (perim <= 85.0) + + for t_idx in range(n_tiers): + y0 = plinth_top_y + t_idx * tier_h + y1 = plinth_top_y + (t_idx + 1) * tier_h + bay_y_top = y1 - (slab_thick if not is_mauer else 0.0) + if bay_y_top <= y0 + 0.6: + bay_y_top = y1 + + cur_bay_indices: list[int] = [] + cur_bay_mids: list[np.ndarray] = [] + for b_i, (sa, sb, blen) in enumerate(bays_2d): + if len(zones) >= MAX_ZONES_PER_BUILDING - n_roofs - 1: + break + r_parts, c_parts, has_win = _build_wall_bay_geometry( + sa, sb, blen, y0, bay_y_top, wall_thick, pal, micro_zone, + allow_details=(not is_mauer) and (perim_details or (b_i % 2 == 0)), + ) + if t_idx == 0: + sup_mask = plinth_bit + else: + # Supported by vertically aligned lower wall bay + sup_idx = prev_bay_indices[min(b_i, len(prev_bay_indices) - 1)] + sup_mask = 1 << sup_idx + + z_flags = ZONE_FLAG_EXTERIOR | (ZONE_FLAG_HAS_WINDOWS if has_win else 0) + bz_idx = add_zone(ZONE_WALL_BAY, pal["wall_class"], z_flags, sup_mask, r_parts, c_parts) + cur_bay_indices.append(bz_idx) + cur_bay_mids.append(0.5 * (sa + sb)) + + # Horizontal FloorSlab at top of tier t_idx (ceiling / upper story deck) + tier_wall_mask = 0 + for idx_b in cur_bay_indices: + tier_wall_mask |= (1 << idx_b) + + if not is_mauer and len(zones) < MAX_ZONES_PER_BUILDING - n_roofs: + slab_y0 = max(y0 + 0.4, y1 - slab_thick) + slab_parts = extrude_2d_poly_prism( + np.array([0.0, slab_y0, 0.0]), u_xz, v_xz, n_up, slab_uv, + 0.0, slab_thick, + mat_top=pal["slab"], mat_bot=pal["interior"], mat_side=pal["trim"], + ao_top=205, ao_bot=165, ao_side=195, + ) + slab_sup = (tier_wall_mask if tier_wall_mask else plinth_bit) | core_bit + slab_idx = add_zone(ZONE_FLOOR_SLAB, MAT_CLASS_CONCRETE, 0, slab_sup, slab_parts, slab_parts) + all_tier_supports_mask = tier_wall_mask | core_bit | (1 << slab_idx) + else: + all_tier_supports_mask = tier_wall_mask | core_bit + + if cur_bay_indices: + prev_bay_indices = cur_bay_indices + prev_bay_mids = cur_bay_mids + + # 5. Roof Zones supported by top-tier WallBays nearest to roof centroid + InteriorCore + for r_render, r_col, r_c3 in roof_items: + if len(zones) >= MAX_ZONES_PER_BUILDING: + break + r_sup = core_bit + if prev_bay_indices: + r_xz = np.array([r_c3[0], r_c3[2]], dtype=np.float64) + dists = [(float(np.linalg.norm(m - r_xz)), idx_b) for idx_b, m in zip(prev_bay_indices, prev_bay_mids)] + dists.sort() + # Attach to closest 2 top-tier bays so destroying that corner drops the roof segment + for _, idx_b in dists[:2]: + r_sup |= (1 << idx_b) + elif all_tier_supports_mask: + r_sup = all_tier_supports_mask + add_zone(ZONE_ROOF_SEGMENT, pal["roof_class"], ZONE_FLAG_EXTERIOR, r_sup, r_render, r_col) + + all_c_pts = np.vstack([z.col_tris.reshape(-1, 3) for z in zones]) + bmin = all_c_pts.min(axis=0) + bmax = all_c_pts.max(axis=0) + g_mask = 0 + for z in zones: + if z.flags & ZONE_FLAG_GROUND_ANCHORED: + g_mask |= (1 << z.zone_index) + + return CgaBuildingResult( + building_id=building_id, + egid=egid, + uuid=uuid, + name=name, + objektart=objektart, + micro_zone=micro_zone, + arch_style=arch_style, + tx=tx, + tz=tz, + local_slot=local_slot, + bounds_min=bmin, + bounds_max=bmax, + ground_y=float(bmin[1]), + roof_y=float(bmax[1]), + ground_anchored_mask=g_mask, + zones=zones, + ) + + +# --------------------------------------------------------------------------- +# Quantization, Octahedral Normals, Manifold Audit & RCGA v1 / RCGB v1 Packing +# --------------------------------------------------------------------------- +def encode_oct_normal(normals: np.ndarray) -> np.ndarray: + """Encode unit normals (N, 3) -> int8[N, 2] octahedral normals.""" + nx = normals[:, 0] + ny = normals[:, 1] + nz = normals[:, 2] + l1 = np.maximum(1e-8, np.abs(nx) + np.abs(ny) + np.abs(nz)) + ox = nx / l1 + oy = ny / l1 + neg = nz < 0.0 + if np.any(neg): + ox_n = (1.0 - np.abs(oy[neg])) * np.where(ox[neg] >= 0.0, 1.0, -1.0) + oy_n = (1.0 - np.abs(ox[neg])) * np.where(oy[neg] >= 0.0, 1.0, -1.0) + ox[neg] = ox_n + oy[neg] = oy_n + qx = np.clip(np.round(ox * 127.0), -127, 127).astype(np.int8) + qy = np.clip(np.round(oy * 127.0), -127, 127).astype(np.int8) + return np.column_stack([qx, qy]) + + +def decode_oct_normal(q: np.ndarray) -> np.ndarray: + ox = np.clip(q[:, 0].astype(np.float32) / 127.0, -1.0, 1.0) + oy = np.clip(q[:, 1].astype(np.float32) / 127.0, -1.0, 1.0) + nz = 1.0 - np.abs(ox) - np.abs(oy) + neg = nz < 0.0 + if np.any(neg): + old_ox = ox[neg].copy() + ox[neg] = (1.0 - np.abs(oy[neg])) * np.where(old_ox >= 0.0, 1.0, -1.0) + oy[neg] = (1.0 - np.abs(old_ox)) * np.where(oy[neg] >= 0.0, 1.0, -1.0) + v = np.column_stack([ox, oy, nz]) + ln = np.maximum(1e-8, np.linalg.norm(v, axis=1, keepdims=True)) + return v / ln + + +def _pack_zone_mesh_16b( + tris: np.ndarray, + mats: np.ndarray, + ao: np.ndarray, + uvs: np.ndarray, + pos_origin: np.ndarray, + pos_scale: np.ndarray, + zone_index: int, + bldg_slot: int, +) -> tuple[bytes, bytes, int, int]: + """ + Pack triangle soup -> 16 B/vert vertex buffer + uint16 index buffer: + int16[3] qpos (6B), int8[2] oct_norm (2B), uint16[2] uv (4B), uint8[4] COLOR_0 (4B). + Guarantees zero quantized degenerate triangles and exact vertex deduplication. + """ + qpos_all = np.clip(np.round((tris - pos_origin[None, None, :]) / pos_scale[None, None, :]), -32767, 32767).astype(np.int16) + + # Filter out any triangle whose quantized vertices collapse or are collinear + v0 = qpos_all[:, 0, :].astype(np.int64) + v1 = qpos_all[:, 1, :].astype(np.int64) + v2 = qpos_all[:, 2, :].astype(np.int64) + e1q = v1 - v0 + e2q = v2 - v0 + cross_q = np.cross(e1q, e2q) + valid = np.sum(cross_q * cross_q, axis=1) > 0 + if not np.any(valid): + # Fallback to single minimal valid box from raw tris bounds + bmin = tris.reshape(-1, 3).min(axis=0) + bmax = np.maximum(bmin + pos_scale * 2.0, tris.reshape(-1, 3).max(axis=0)) + box_t, box_m, box_ao, box_uv = make_box_prism( + bmin, np.array([1.0, 0.0, 0.0]), np.array([0.0, 0.0, -1.0]), np.array([0.0, 1.0, 0.0]), + 0.0, float(bmax[0] - bmin[0]), -float(bmax[2] - bmin[2]), 0.0, 0.0, float(bmax[1] - bmin[1]), + int(mats[0]), int(mats[0]), int(mats[0]), + ) + return _pack_zone_mesh_16b(box_t, box_m, box_ao, box_uv, pos_origin, pos_scale, zone_index, bldg_slot) + + tris = tris[valid] + qpos_all = qpos_all[valid] + mats = mats[valid] + ao = ao[valid] + uvs = uvs[valid] + + e1 = tris[:, 1] - tris[:, 0] + e2 = tris[:, 2] - tris[:, 0] + cross = np.cross(e1, e2) + nlen = np.maximum(1e-9, np.linalg.norm(cross, axis=1, keepdims=True)) + face_norms = cross / nlen + qnorm_face = encode_oct_normal(face_norms) # (T, 2) + + T = len(tris) + flat_qpos = qpos_all.reshape(-1, 3) # (3T, 3) int16 + flat_qnorm = np.repeat(qnorm_face, 3, axis=0) # (3T, 2) int8 + flat_uv = np.clip(np.round(uvs.reshape(-1, 2) * UV_QUANT_SCALE), 0, 65535).astype(np.uint16) + flat_col = np.empty((T * 3, 4), dtype=np.uint8) + flat_col[:, 0] = zone_index & 0xFF + flat_col[:, 1] = np.repeat(mats, 3) + flat_col[:, 2] = ao.reshape(-1) + flat_col[:, 3] = bldg_slot & 0xFF + + # Pack into 16B structured record array for instant deduplication + vert_dtype = np.dtype([ + ("qx", " tuple[int, int, int]: + """ + Weld vertices by exact quantized int16[3] position and verify closed 2-manifold topology. + Returns (open_boundary_edges, non_manifold_edges, degenerate_tris). + """ + tri_idx = indices.reshape(-1, 3) + # Map each vertex index to unique quantized position id + pos_keys = [tuple(int(v) for v in qpos_verts[i]) for i in range(len(qpos_verts))] + pos_map: dict[tuple[int, int, int], int] = {} + vid_to_pid = np.empty(len(qpos_verts), dtype=np.int32) + for i, k in enumerate(pos_keys): + pid = pos_map.get(k) + if pid is None: + pid = len(pos_map) + pos_map[k] = pid + vid_to_pid[i] = pid + + p_tris = vid_to_pid[tri_idx] + degenerate = 0 + dir_edges: Counter[tuple[int, int]] = Counter() + undir_edges: Counter[tuple[int, int]] = Counter() + + for a, b, c in p_tris: + if a == b or b == c or c == a: + degenerate += 1 + continue + pa, pb, pc = qpos_verts[tri_idx[0]] if False else None, None, None # checked via cross below + for u, v in ((int(a), int(b)), (int(b), int(c)), (int(c), int(a))): + dir_edges[(u, v)] += 1 + undir_edges[(min(u, v), max(u, v))] += 1 + + # Vectorized collinearity check in quantized space + vp = qpos_verts[tri_idx].astype(np.int64) + cr = np.cross(vp[:, 1] - vp[:, 0], vp[:, 2] - vp[:, 0]) + degenerate += int(np.sum(np.sum(cr * cr, axis=1) == 0)) + + open_edges = 0 + non_manifold = 0 + for (u, v), cnt in dir_edges.items(): + opp = dir_edges.get((v, u), 0) + if cnt > 1: + non_manifold += 1 + elif opp == 0: + open_edges += 1 + for (u, v), cnt in undir_edges.items(): + if cnt != 2: + if cnt > 2: + non_manifold += 1 + + return open_edges, non_manifold, degenerate + + +def verify_support_dag(zones: list[CgaZoneMesh]) -> tuple[int, bool]: + """Return (cycle_count, all_reach_ground).""" + n = len(zones) + if n == 0: + return 0, False + # Cycle detection via DFS color (0=unvisited, 1=visiting, 2=done) + color = [0] * n + cycles = 0 + + def dfs(u: int) -> None: + nonlocal cycles + color[u] = 1 + mask = zones[u].support_mask + for v in range(n): + if (mask >> v) & 1: + if color[v] == 1: + cycles += 1 + elif color[v] == 0: + dfs(v) + color[u] = 2 + + for i in range(n): + if color[i] == 0: + dfs(i) + + # Ground reachability via BFS/fixed point from IsGroundAnchored zones + reachable = 0 + for i, z in enumerate(zones): + if z.flags & ZONE_FLAG_GROUND_ANCHORED: + reachable |= (1 << i) + changed = True + while changed: + changed = False + for i, z in enumerate(zones): + if not ((reachable >> i) & 1): + if (z.support_mask & reachable) != 0: + reachable |= (1 << i) + changed = True + + all_reach = (reachable == ((1 << n) - 1)) + return cycles, all_reach + + +def export_rcga_tile(tx: int, tz: int, buildings: list[CgaBuildingResult], out_path) -> tuple[int, int, int]: + """ + Export compact ZLib-compressed RCGA v1 binary tile: + Outer header (24 B): magic="RCGA", uint32 ver=1, int32 tx, int32 tz, uint32 buildingCount, uint32 uncompressedBytes + ZLib payload: + buildingHeaders: N * 36B + zoneSliceHeaders: Z * 16B + per-zone renderVerts (16B*V), renderIndices (2B*I), colVerts (16B*Vc), colIndices (2B*Ic) + Returns (file_bytes, total_render_tris, total_col_tris). + """ + bldg_hdrs = bytearray() + zone_hdrs = bytearray() + geo_blob = bytearray() + zone_slice_idx = 0 + total_r_tris = 0 + total_c_tris = 0 + + for b in buildings: + ext = np.maximum(b.bounds_max - b.bounds_min, 0.1) + pos_origin = 0.5 * (b.bounds_min + b.bounds_max) + pos_scale = np.maximum(1e-4, (ext * 0.501) / 32767.0) + + bldg_hdrs.extend(struct.pack( + " tuple[int, int]: + """Export simplified watertight LOD2 GLB (Plinth + Wall collision hulls + Roof hulls) on 16x16 grid.""" + mat_tris: dict[int, list[np.ndarray]] = defaultdict(list) + for b in buildings: + for z in b.zones: + if z.zone_kind in (ZONE_FLOOR_SLAB, ZONE_INTERIOR_CORE): + continue + for tri, mid in zip(z.col_tris, z.col_mats): + mat_tris[int(mid)].append(tri) + + out_path.parent.mkdir(parents=True, exist_ok=True) + blob = bytearray() + buffer_views = [] + accessors = [] + materials = [] + primitives = [] + total_tris = 0 + + for pal_id, tri_list in sorted(mat_tris.items()): + if not tri_list: + continue + tris = np.asarray(tri_list, dtype=np.float32) + e1 = tris[:, 1] - tris[:, 0] + e2 = tris[:, 2] - tris[:, 0] + cross = np.cross(e1, e2) + nlen = np.linalg.norm(cross, axis=1) + valid = nlen > 1e-6 + tris = tris[valid] + if len(tris) == 0: + continue + n_face = (cross[valid] / nlen[valid, None]).astype(np.float32) + total_tris += len(tris) + + raw_verts = tris.reshape(-1, 3) + raw_norms = np.repeat(n_face, 3, axis=0) + q_pos = np.round(raw_verts * 500.0).astype(np.int64) + q_nrm = np.round(raw_norms * 120.0).astype(np.int64) + keys = np.ascontiguousarray(np.hstack([q_pos, q_nrm])).view(np.dtype((np.void, 6 * 8))).ravel() + _, uniq_idx, inv_idx = np.unique(keys, return_index=True, return_inverse=True) + verts = np.ascontiguousarray(raw_verts[uniq_idx], dtype=" tuple[str, int]: + """ + Export buildings_cga.bin (RCGB v1, zlib-compressed body after 64-byte header): + Header (64 B): + magic="RCGB", uint32 ver=1, uint32 buildingCount, uint32 totalZoneCount, + uint32 tileGrid=16, float32 tileSizeM=192.0, uint8[32] sha256, uint32 flags=1(zlib), uint32 uncompressedBodyBytes + Body (zlib-compressed): + buildingCount * 64B BuildingRecords + totalZoneCount * 44B ZoneRecords + uint32 nameTableBytes + UTF-8 bytes + Returns (asset_fingerprint_hex, file_bytes). + """ + bldg_buf = bytearray() + zone_buf = bytearray() + str_buf = bytearray() + first_zone = 0 + + for b in buildings: + if b.name: + name_bytes = b.name.encode("utf-8") + name_off = len(str_buf) + name_len = min(65535, len(name_bytes)) + str_buf.extend(name_bytes[:name_len]) + else: + name_off = 0xFFFFFFFF + name_len = 0 + + bldg_buf.extend(struct.pack( + " dict[str, int | float | str]: + """ + Mechanically verify ALL buildings in buildings_cga.bin + tiles/city_*.rcga + tiles/city_lod2_*.glb: + - open_boundary_edges == 0 + - non_manifold_edges == 0 + - degenerate_tris == 0 + - support_dag_cycles == 0 + - 100% above-ground zones reach an IsGroundAnchored zone + - combined city_*.rcga + city_lod2_*.glb <= 16 MiB + """ + cga_bin = sion_dir / "buildings_cga.bin" + if not cga_bin.exists(): + raise RuntimeError(f"Missing {cga_bin}") + raw = cga_bin.read_bytes() + if len(raw) < 64 or raw[:4] != b"RCGB": + raise RuntimeError("Invalid RCGB header") + magic, ver, bldg_cnt, total_zones, tile_grid, tile_size_m, digest, flags, uncomp_len = struct.unpack_from("<4sIIIIf32sII", raw, 0) + if ver != 1: + raise RuntimeError(f"Unsupported RCGB version {ver}") + body = zlib.decompress(raw[64:]) if (flags & 1) else raw[64:] + if len(body) != uncomp_len: + raise RuntimeError("RCGB uncompressed length mismatch") + + bldg_recs_end = bldg_cnt * 64 + zone_recs_end = bldg_recs_end + total_zones * 44 + + # Parse buildings & zones + buildings_meta = [] + for i in range(bldg_cnt): + rec = struct.unpack_from(" MAX_ZONES_PER_BUILDING: + raise RuntimeError(f"Building {bid} invalid zoneCount={z_cnt}") + + # Build lightweight DAG check + n = z_cnt + color = [0] * n + def dfs(u: int) -> None: + nonlocal dag_cycles + color[u] = 1 + sm = zones_meta[first_z + u][0] + for v in range(n): + if (sm >> v) & 1: + if color[v] == 1: + dag_cycles += 1 + elif color[v] == 0: + dfs(v) + color[u] = 2 + + for u in range(n): + if color[u] == 0: + dfs(u) + + reachable = 0 + for u in range(n): + if zones_meta[first_z + u][3] & ZONE_FLAG_GROUND_ANCHORED: + reachable |= (1 << u) + changed = True + while changed: + changed = False + for u in range(n): + if not ((reachable >> u) & 1): + if (zones_meta[first_z + u][0] & reachable) != 0: + reachable |= (1 << u) + changed = True + if reachable != ((1 << n) - 1): + ground_unreachable += 1 + + # Verify every RCGA tile mesh slice + tiles_dir = sion_dir / "tiles" + rcga_files = sorted(tiles_dir.glob("city_[0-9]*_[0-9]*.rcga")) + lod2_files = sorted(tiles_dir.glob("city_lod2_*_*.glb")) + + open_edges_total = 0 + non_manifold_total = 0 + degenerate_total = 0 + verified_buildings = 0 + total_render_tris = 0 + total_col_tris = 0 + + for rpath in rcga_files: + rdata = rpath.read_bytes() + rmagic, rver, rtx, rtz, rb_cnt, runcomp = struct.unpack_from("<4sIiiII", rdata, 0) + if rmagic != b"RCGA" or rver != 1: + raise RuntimeError(f"Bad RCGA header in {rpath.name}") + rpayload = zlib.decompress(rdata[24:]) + if len(rpayload) != runcomp: + raise RuntimeError(f"RCGA payload size mismatch in {rpath.name}") + + off = 0 + rb_hdrs = [] + total_slices = 0 + for _ in range(rb_cnt): + hdr = struct.unpack_from(" 16 * 1024 * 1024: + raise RuntimeError(f"Combined city_*.rcga + city_lod2_*.glb exceeds 16 MiB: {combined_bytes:,} bytes") + + return stats