From c6b15c33cdbd31c66b53aef9b32dcab4709a7e50 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 6 Dec 2026 02:54:27 +0100 Subject: [PATCH] Cut 13b Soul Pass #1 fixes: grounding, non-overhang slabs, pitched LOD2, Civic zone, RCGB/RCGA validation --- src/RustToDust.Core/SionCityCatalog.cs | 258 ++++++-- src/RustToDust.Core/SionMapLoader.cs | 5 +- .../RustToDust.Tests/SionCityCatalogTests.cs | 115 +++- tools/maps/sion/bake_sion.py | 33 +- tools/maps/sion/cga_builder.py | 552 +++++++++++++----- 5 files changed, 733 insertions(+), 230 deletions(-) diff --git a/src/RustToDust.Core/SionCityCatalog.cs b/src/RustToDust.Core/SionCityCatalog.cs index ae658a5..9cabd67 100644 --- a/src/RustToDust.Core/SionCityCatalog.cs +++ b/src/RustToDust.Core/SionCityCatalog.cs @@ -4,6 +4,7 @@ using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Numerics; +using System.Security.Cryptography; using System.Text; namespace RustToDust.Core @@ -235,58 +236,108 @@ namespace RustToDust.Core { string cgaPath = Path.Combine(sionDirectory, "buildings_cga.bin"); byte[] raw = File.ReadAllBytes(cgaPath); + return ParseCatalogBytes(sionDirectory, raw, cgaPath); + } + + public static SionCityCatalog ParseCatalogBytes(string sionDirectory, ReadOnlySpan raw, string sourceName = "buildings_cga.bin") + { if (raw.Length < 64) { - throw new InvalidDataException($"buildings_cga.bin '{cgaPath}' too small ({raw.Length} bytes)."); + throw new InvalidDataException($"buildings_cga.bin '{sourceName}' too small ({raw.Length} bytes)."); } - ReadOnlySpan hdr = raw.AsSpan(0, 64); + ReadOnlySpan hdr = raw.Slice(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}'."); + throw new InvalidDataException($"Invalid RCGB magic in '{sourceName}'."); } uint version = BinaryPrimitives.ReadUInt32LittleEndian(hdr.Slice(4, 4)); if (version != 1) { - throw new InvalidDataException($"Unsupported RCGB version {version} in '{cgaPath}'."); + throw new InvalidDataException($"Unsupported RCGB version {version} in '{sourceName}'."); } - int bldgCount = checked((int)BinaryPrimitives.ReadUInt32LittleEndian(hdr.Slice(8, 4))); - int totalZoneCount = checked((int)BinaryPrimitives.ReadUInt32LittleEndian(hdr.Slice(12, 4))); + uint bldgCountU = BinaryPrimitives.ReadUInt32LittleEndian(hdr.Slice(8, 4)); + uint totalZoneCountU = 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}'."); + throw new InvalidDataException($"Unexpected RCGB tileGrid {tileGrid} != {TileGrid} in '{sourceName}'."); + } + if (bldgCountU > 65535u || totalZoneCountU > 10_000_000u) + { + throw new InvalidDataException($"Invalid RCGB counts (bldg={bldgCountU}, zones={totalZoneCountU}) in '{sourceName}'."); } - string fingerprint = "rcga:" + Convert.ToHexString(hdr.Slice(24, 32)).ToLowerInvariant(); + int bldgCount = (int)bldgCountU; + int totalZoneCount = (int)totalZoneCountU; + + ReadOnlySpan expectedSha256 = hdr.Slice(24, 32); + string fingerprint = "rcga:" + Convert.ToHexString(expectedSha256).ToLowerInvariant(); uint flags = BinaryPrimitives.ReadUInt32LittleEndian(hdr.Slice(56, 4)); - int uncompLen = checked((int)BinaryPrimitives.ReadUInt32LittleEndian(hdr.Slice(60, 4))); + if ((flags & ~1u) != 0) + { + throw new InvalidDataException($"Unsupported RCGB flags 0x{flags:X} in '{sourceName}'."); + } + + uint uncompLenU = BinaryPrimitives.ReadUInt32LittleEndian(hdr.Slice(60, 4)); + if (uncompLenU > 256u * 1024u * 1024u) + { + throw new InvalidDataException($"Unreasonable RCGB uncompressed length {uncompLenU} in '{sourceName}'."); + } + int uncompLen = (int)uncompLenU; 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); + try + { + using var ms = new MemoryStream(raw.Slice(64).ToArray(), writable: false); + using var z = new ZLibStream(ms, CompressionMode.Decompress); + ReadExact(z, body, sourceName); + } + catch (InvalidDataException) + { + throw; + } + catch (Exception ex) + { + throw new InvalidDataException($"Failed to decompress RCGB body in '{sourceName}': {ex.Message}", ex); + } } else { - body = raw.AsSpan(64).ToArray(); + if (raw.Length - 64 != uncompLen) + { + throw new InvalidDataException($"Uncompressed RCGB body length mismatch in '{sourceName}'."); + } + body = raw.Slice(64).ToArray(); } - int expectedMin = bldgCount * 64 + totalZoneCount * 44 + 4; + Span actualSha = stackalloc byte[32]; + SHA256.HashData(body, actualSha); + if (!CryptographicOperations.FixedTimeEquals(actualSha, expectedSha256)) + { + throw new InvalidDataException($"RCGB SHA-256 integrity check failed in '{sourceName}'."); + } + + long expectedMin = (long)bldgCount * 64L + (long)totalZoneCount * 44L + 4L; if (body.Length < expectedMin) { - throw new InvalidDataException($"RCGB body truncated in '{cgaPath}': {body.Length} < {expectedMin}."); + throw new InvalidDataException($"RCGB body truncated in '{sourceName}': {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))); + uint strBytesLenU = BinaryPrimitives.ReadUInt32LittleEndian(bSpan.Slice(strTableOffset, 4)); + if (strBytesLenU > (uint)(body.Length - strTableOffset - 4)) + { + throw new InvalidDataException($"RCGB string table length {strBytesLenU} out of bounds in '{sourceName}'."); + } + int strBytesLen = (int)strBytesLenU; ReadOnlySpan strBytes = bSpan.Slice(strTableOffset + 4, strBytesLen); var buildings = new CgaBuildingMeta[bldgCount]; @@ -300,13 +351,30 @@ namespace RustToDust.Core { int off = i * 64; ushort bid = BinaryPrimitives.ReadUInt16LittleEndian(bSpan.Slice(off, 2)); + if (bid != i) + { + throw new InvalidDataException($"RCGB building id mismatch at index {i}: got {bid} in '{sourceName}'."); + } byte tx = bSpan[off + 2]; byte tz = bSpan[off + 3]; + if (tx >= TileGrid || tz >= TileGrid) + { + throw new InvalidDataException($"RCGB building {bid} tile ({tx},{tz}) out of [0..{TileGrid - 1}] in '{sourceName}'."); + } 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))); + if (zoneCount < 1 || zoneCount > 64) + { + throw new InvalidDataException($"RCGB building {bid} invalid zoneCount={zoneCount} (must be 1..64) in '{sourceName}'."); + } + uint firstZoneU = BinaryPrimitives.ReadUInt32LittleEndian(bSpan.Slice(off + 8, 4)); + if (firstZoneU > (uint)totalZoneCount || (ulong)firstZoneU + zoneCount > (ulong)totalZoneCount) + { + throw new InvalidDataException($"RCGB building {bid} zone slice [{firstZoneU}+{zoneCount}] exceeds totalZoneCount={totalZoneCount} in '{sourceName}'."); + } + int firstZone = (int)firstZoneU; 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)); @@ -317,19 +385,23 @@ namespace RustToDust.Core ushort nameLen = BinaryPrimitives.ReadUInt16LittleEndian(bSpan.Slice(off + 60, 2)); string name = ""; - if (nameOff != 0xFFFFFFFFu && nameLen > 0 && nameOff + nameLen <= (uint)strBytes.Length) + if (nameOff != 0xFFFFFFFFu) { - name = Encoding.UTF8.GetString(strBytes.Slice((int)nameOff, nameLen)); + if ((ulong)nameOff + nameLen > (ulong)strBytesLen) + { + throw new InvalidDataException($"RCGB building {bid} name slice [{nameOff}+{nameLen}] out of bounds in '{sourceName}'."); + } + if (nameLen > 0) + { + 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); - } + tileLists[tz * TileGrid + tx].Add(bid); } var zones = new CgaZoneMeta[totalZoneCount]; @@ -450,9 +522,9 @@ namespace RustToDust.Core { ref readonly var b = ref _buildings[buildingId]; int n = b.ZoneCount; - if (n == 0) + if (n <= 0 || n > 64) { - return collapsedMask; + throw new InvalidDataException($"Building {buildingId} has invalid ZoneCount={n} (expected 1..64)."); } var zones = _zones.AsSpan(b.FirstZoneIndex, n); @@ -527,41 +599,71 @@ namespace RustToDust.Core public static RcgaTileGeometry LoadRcgaTile(string path, int expectedTx = -1, int expectedTz = -1) { byte[] raw = File.ReadAllBytes(path); + return ParseRcgaTileBytes(raw, expectedTx, expectedTz, path); + } + + public static RcgaTileGeometry ParseRcgaTileBytes(ReadOnlySpan raw, int expectedTx = -1, int expectedTz = -1, string sourceName = "") + { if (raw.Length < 24) { - throw new InvalidDataException($"RCGA file '{path}' too small ({raw.Length} bytes)."); + throw new InvalidDataException($"RCGA file '{sourceName}' too small ({raw.Length} bytes)."); } - ReadOnlySpan hdr = raw.AsSpan(0, 24); + ReadOnlySpan hdr = raw.Slice(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}'."); + throw new InvalidDataException($"Invalid RCGA magic in '{sourceName}'."); } uint version = BinaryPrimitives.ReadUInt32LittleEndian(hdr.Slice(4, 4)); if (version != 1) { - throw new InvalidDataException($"Unsupported RCGA version {version} in '{path}'."); + throw new InvalidDataException($"Unsupported RCGA version {version} in '{sourceName}'."); } int tx = BinaryPrimitives.ReadInt32LittleEndian(hdr.Slice(8, 4)); int tz = BinaryPrimitives.ReadInt32LittleEndian(hdr.Slice(12, 4)); + if (tx < 0 || tx >= TileGrid || tz < 0 || tz >= TileGrid) + { + throw new InvalidDataException($"RCGA tile coords ({tx},{tz}) out of bounds in '{sourceName}'."); + } if ((expectedTx >= 0 && tx != expectedTx) || (expectedTz >= 0 && tz != expectedTz)) { - throw new InvalidDataException($"RCGA tile mismatch in '{path}': ({tx},{tz}) != ({expectedTx},{expectedTz})."); + throw new InvalidDataException($"RCGA tile mismatch in '{sourceName}': ({tx},{tz}) != ({expectedTx},{expectedTz})."); } - int bldgCount = checked((int)BinaryPrimitives.ReadUInt32LittleEndian(hdr.Slice(16, 4))); - int uncompBytes = checked((int)BinaryPrimitives.ReadUInt32LittleEndian(hdr.Slice(20, 4))); + uint bldgCountU = BinaryPrimitives.ReadUInt32LittleEndian(hdr.Slice(16, 4)); + uint uncompBytesU = BinaryPrimitives.ReadUInt32LittleEndian(hdr.Slice(20, 4)); + if (bldgCountU > 65535u || uncompBytesU > 256u * 1024u * 1024u) + { + throw new InvalidDataException($"Invalid RCGA header counts (bldg={bldgCountU}, uncomp={uncompBytesU}) in '{sourceName}'."); + } + int bldgCount = (int)bldgCountU; + int uncompBytes = (int)uncompBytesU; 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)) + try { - ReadExact(z, payload, path); + using var ms = new MemoryStream(raw.Slice(24).ToArray(), writable: false); + using var z = new ZLibStream(ms, CompressionMode.Decompress); + ReadExact(z, payload, sourceName); + } + catch (InvalidDataException) + { + throw; + } + catch (Exception ex) + { + throw new InvalidDataException($"Failed to decompress RCGA payload in '{sourceName}': {ex.Message}", ex); } ReadOnlySpan p = payload; + long bldgHdrBytes = (long)bldgCount * 36L; + if (p.Length < bldgHdrBytes) + { + throw new InvalidDataException($"RCGA payload truncated before building headers in '{sourceName}'."); + } + int off = 0; var bldgs = new RcgaBuildingHeader[bldgCount]; int totalSlices = 0; @@ -569,53 +671,80 @@ namespace RustToDust.Core { ushort bid = BinaryPrimitives.ReadUInt16LittleEndian(p.Slice(off, 2)); byte zCnt = p[off + 2]; + if (zCnt < 1 || zCnt > 64) + { + throw new InvalidDataException($"RCGA building {bid} invalid zoneCount={zCnt} (must be 1..64) in '{sourceName}'."); + } 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); + uint firstSliceU = BinaryPrimitives.ReadUInt32LittleEndian(p.Slice(off + 28, 4)); + if (firstSliceU != (uint)totalSlices) + { + throw new InvalidDataException($"RCGA building {bid} slice offset {firstSliceU} != expected {totalSlices} in '{sourceName}'."); + } + bldgs[i] = new RcgaBuildingHeader(bid, zCnt, localSlot, origin, scale, (int)firstSliceU); totalSlices += zCnt; off += 36; } + long sliceHdrBytes = (long)totalSlices * 16L; + if ((long)off + sliceHdrBytes > p.Length) + { + throw new InvalidDataException($"RCGA payload truncated before zone slice headers in '{sourceName}'."); + } + var slices = new RcgaZoneSlice[totalSlices]; - int totalVerts = 0; - int totalIndices = 0; + long totalVertsL = 0; + long totalIndicesL = 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))); + uint rvCntU = BinaryPrimitives.ReadUInt32LittleEndian(p.Slice(off, 4)); + uint riCntU = BinaryPrimitives.ReadUInt32LittleEndian(p.Slice(off + 4, 4)); + uint cvCntU = BinaryPrimitives.ReadUInt32LittleEndian(p.Slice(off + 8, 4)); + uint ciCntU = BinaryPrimitives.ReadUInt32LittleEndian(p.Slice(off + 12, 4)); off += 16; - int rVertOff = totalVerts; - totalVerts += rvCnt; - int rIdxOff = totalIndices; - totalIndices += riCnt; + if (rvCntU > 65535u || cvCntU > 65535u || (riCntU % 3u) != 0 || (ciCntU % 3u) != 0) + { + throw new InvalidDataException($"RCGA slice {s} invalid vertex/index counts in '{sourceName}'."); + } - int cVertOff = totalVerts; - totalVerts += cvCnt; - int cIdxOff = totalIndices; - totalIndices += ciCnt; + int rvCnt = (int)rvCntU; + int riCnt = (int)riCntU; + int cvCnt = (int)cvCntU; + int ciCnt = (int)ciCntU; + + int rVertOff = checked((int)totalVertsL); + totalVertsL += rvCnt; + int rIdxOff = checked((int)totalIndicesL); + totalIndicesL += riCnt; + + int cVertOff = checked((int)totalVertsL); + totalVertsL += cvCnt; + int cIdxOff = checked((int)totalIndicesL); + totalIndicesL += ciCnt; slices[s] = new RcgaZoneSlice(rVertOff, rvCnt, rIdxOff, riCnt, cVertOff, cvCnt, cIdxOff, ciCnt); } - var allVerts = new RcgaPackedVertex[totalVerts]; - var allIndices = new ushort[totalIndices]; + long expectedGeoBytes = totalVertsL * 16L + totalIndicesL * 2L; + if ((long)off + expectedGeoBytes != p.Length) + { + throw new InvalidDataException($"RCGA geometry byte length mismatch in '{sourceName}': {(long)off + expectedGeoBytes} != {p.Length}."); + } + + var allVerts = new RcgaPackedVertex[checked((int)totalVertsL)]; + var allIndices = new ushort[checked((int)totalIndicesL)]; 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)); + var rIdxSpan = allIndices.AsSpan(sl.RenderIndexOffset, sl.RenderIndexCount); + ReadIndices(p, ref off, rIdxSpan, sl.RenderVertCount, sourceName); 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}."); + var cIdxSpan = allIndices.AsSpan(sl.ColIndexOffset, sl.ColIndexCount); + ReadIndices(p, ref off, cIdxSpan, sl.ColVertCount, sourceName); } return new RcgaTileGeometry(tx, tz, bldgs, slices, allVerts, allIndices); @@ -641,11 +770,16 @@ namespace RustToDust.Core } } - private static void ReadIndices(ReadOnlySpan src, ref int off, Span dst) + private static void ReadIndices(ReadOnlySpan src, ref int off, Span dst, int vertCount, string sourceName) { for (int i = 0; i < dst.Length; i++) { - dst[i] = BinaryPrimitives.ReadUInt16LittleEndian(src.Slice(off, 2)); + ushort idx = BinaryPrimitives.ReadUInt16LittleEndian(src.Slice(off, 2)); + if (idx >= vertCount) + { + throw new InvalidDataException($"RCGA vertex index {idx} >= vertCount {vertCount} in '{sourceName}'."); + } + dst[i] = idx; off += 2; } } diff --git a/src/RustToDust.Core/SionMapLoader.cs b/src/RustToDust.Core/SionMapLoader.cs index 407e8a3..0e9d30f 100644 --- a/src/RustToDust.Core/SionMapLoader.cs +++ b/src/RustToDust.Core/SionMapLoader.cs @@ -107,9 +107,12 @@ namespace RustToDust.Core _baseDem = baseDem; BaseDemMinY = baseDemMinY; BaseDemScale = baseDemScale; - AssetFingerprint = !string.IsNullOrWhiteSpace(metadata.DemAssetHash) + string baseFp = !string.IsNullOrWhiteSpace(metadata.DemAssetHash) ? $"sion:{metadata.DemAssetHash}" : $"sion:{metadata.GridRes}:{metadata.CellSizeMeters:F3}"; + AssetFingerprint = cityCatalog is not null + ? $"{baseFp}:{cityCatalog.AssetFingerprint}" + : baseFp; _buildings = buildings; CollisionMeshes = collisionMeshes; CityCatalog = cityCatalog; diff --git a/tests/RustToDust.Tests/SionCityCatalogTests.cs b/tests/RustToDust.Tests/SionCityCatalogTests.cs index 90d0317..8a28b84 100644 --- a/tests/RustToDust.Tests/SionCityCatalogTests.cs +++ b/tests/RustToDust.Tests/SionCityCatalogTests.cs @@ -1,8 +1,11 @@ using System; +using System.Buffers.Binary; using System.Collections.Generic; using System.IO; +using System.IO.Compression; using System.Linq; using System.Numerics; +using System.Security.Cryptography; using RustToDust.Core; using Xunit; @@ -17,10 +20,12 @@ namespace RustToDust.Tests var catalog = sion.CityCatalog; Assert.NotNull(catalog); Assert.StartsWith("rcga:", catalog!.AssetFingerprint, StringComparison.Ordinal); + Assert.Contains(catalog.AssetFingerprint, sion.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; + bool foundStadeTourbillon = false; var microZoneCounts = new int[7]; int multiZoneBuildings = 0; @@ -34,6 +39,29 @@ namespace RustToDust.Tests Assert.NotEqual(0UL, b.GroundAnchoredMask); Assert.True(b.RoofY >= b.GroundY, $"Building {b.BuildingId} invalid Y span [{b.GroundY}, {b.RoofY}]"); + // Tile assignment must match final baked bounds midpoint (zero drift) + float midX = 0.5f * (b.BoundsMin.X + b.BoundsMax.X); + float midZ = 0.5f * (b.BoundsMin.Z + b.BoundsMax.Z); + int expTx = Math.Clamp((int)MathF.Floor((midX + 1536f) / SionCityCatalog.TileSizeMeters), 0, SionCityCatalog.TileGrid - 1); + int expTz = Math.Clamp((int)MathF.Floor((midZ + 1536f) / SionCityCatalog.TileSizeMeters), 0, SionCityCatalog.TileGrid - 1); + Assert.Equal(expTx, b.Tx); + Assert.Equal(expTz, b.Tz); + + // Every FloorSlab must stay strictly inside Zone 0 Plinth XZ bounds (zero overhang) + var zones = catalog.GetZonesForBuilding(b.BuildingId); + ref readonly var plinth = ref zones[0]; + Assert.Equal(CgaZoneKind.Plinth, plinth.Kind); + for (int z = 1; z < zones.Length; z++) + { + if (zones[z].Kind == CgaZoneKind.FloorSlab) + { + Assert.True(zones[z].BoundsMin.X >= plinth.BoundsMin.X - 0.08f && zones[z].BoundsMax.X <= plinth.BoundsMax.X + 0.08f, + $"Building {b.BuildingId} FloorSlab X overhang"); + Assert.True(zones[z].BoundsMin.Z >= plinth.BoundsMin.Z - 0.08f && zones[z].BoundsMax.Z <= plinth.BoundsMax.Z + 0.08f, + $"Building {b.BuildingId} FloorSlab Z overhang"); + } + } + microZoneCounts[(int)b.MicroZone]++; if (b.ZoneCount > 1) { @@ -45,6 +73,13 @@ namespace RustToDust.Tests foundValere = true; Assert.Equal(CgaMicroZone.Fortress, b.MicroZone); Assert.Equal(CgaArchStyle.Fortress, b.ArchStyle); + Assert.True(b.RoofY > 155f, $"Expected Basilique de Valère spire preserved (RoofY={b.RoofY:F2})"); + } + if (b.Name.Contains("Stade", StringComparison.OrdinalIgnoreCase)) + { + foundStadeTourbillon = true; + Assert.Equal(CgaMicroZone.Civic, b.MicroZone); + Assert.NotEqual(CgaMicroZone.Fortress, b.MicroZone); } bool valid = catalog.ValidateSupportDag(b.BuildingId, out bool hasCycle, out bool allReachGround); @@ -58,11 +93,13 @@ namespace RustToDust.Tests Assert.Equal(allMask, cascaded); } - Assert.True(foundValere, "Expected Valère fortress building in CGA catalog"); + Assert.True(foundValere, "Expected Basilique de Valère in CGA catalog"); + Assert.True(foundStadeTourbillon, "Expected Stade de Tourbillon 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"); + Assert.True(microZoneCounts[(int)CgaMicroZone.Civic] > 0, "Expected Civic buildings"); } [Fact] @@ -192,6 +229,82 @@ namespace RustToDust.Tests catalog.BuildTileCollisionMesh(target.Tx, target.Tz, _ => ulong.MaxValue, vertsEmpty, indicesEmpty); Assert.Empty(vertsEmpty); Assert.Empty(indicesEmpty); + + // Destroying ALL WallBays must also collapse every RoofSegment (never left floating on InteriorCore) + ulong allWallsMask = 0UL; + ulong roofMask = 0UL; + for (int z = 0; z < zones.Length; z++) + { + if (zones[z].Kind == CgaZoneKind.WallBay) allWallsMask |= 1UL << z; + else if (zones[z].Kind == CgaZoneKind.RoofSegment) roofMask |= 1UL << z; + } + Assert.NotEqual(0UL, roofMask); + ulong afterAllWalls = catalog.ComputeUnsupportedCollapsedMask(target.BuildingId, allWallsMask); + Assert.Equal(roofMask, afterAllWalls & roofMask); + } + + [Fact] + public void SionCityCatalog_RejectsMalformedAndTruncatedRcgbAndRcgaWithInvalidDataException() + { + var sion = SionMapLoader.Load(); + string cgaPath = Path.Combine(sion.DirectoryPath, "buildings_cga.bin"); + byte[] validCga = File.ReadAllBytes(cgaPath); + + // Truncated RCGB + Assert.Throws(() => SionCityCatalog.ParseCatalogBytes(sion.DirectoryPath, validCga.AsSpan(0, 32))); + Assert.Throws(() => SionCityCatalog.ParseCatalogBytes(sion.DirectoryPath, validCga.AsSpan(0, validCga.Length - 20))); + + // Bad SHA-256 in header + byte[] badHash = (byte[])validCga.Clone(); + badHash[24] ^= 0xFF; + Assert.Throws(() => SionCityCatalog.ParseCatalogBytes(sion.DirectoryPath, badHash)); + + // Synthetic uncompressed RCGB with ZoneCount = 65 and ZoneCount = 200 + foreach (byte badZoneCount in new byte[] { 65, 200 }) + { + byte[] body = new byte[64 + 44 + 4]; + BinaryPrimitives.WriteUInt16LittleEndian(body.AsSpan(0, 2), 0); + body[7] = badZoneCount; + BinaryPrimitives.WriteUInt32LittleEndian(body.AsSpan(8, 4), 0); + byte[] badRcgb = new byte[64 + body.Length]; + badRcgb[0] = (byte)'R'; badRcgb[1] = (byte)'C'; badRcgb[2] = (byte)'G'; badRcgb[3] = (byte)'B'; + BinaryPrimitives.WriteUInt32LittleEndian(badRcgb.AsSpan(4, 4), 1); + BinaryPrimitives.WriteUInt32LittleEndian(badRcgb.AsSpan(8, 4), 1); + BinaryPrimitives.WriteUInt32LittleEndian(badRcgb.AsSpan(12, 4), 1); + BinaryPrimitives.WriteUInt32LittleEndian(badRcgb.AsSpan(16, 4), 16); + BinaryPrimitives.WriteSingleLittleEndian(badRcgb.AsSpan(20, 4), 192f); + SHA256.HashData(body, badRcgb.AsSpan(24, 32)); + BinaryPrimitives.WriteUInt32LittleEndian(badRcgb.AsSpan(56, 4), 0); // uncompressed + BinaryPrimitives.WriteUInt32LittleEndian(badRcgb.AsSpan(60, 4), (uint)body.Length); + body.CopyTo(badRcgb, 64); + Assert.Throws(() => SionCityCatalog.ParseCatalogBytes(sion.DirectoryPath, badRcgb)); + } + + // Truncated & malformed RCGA tile + var firstNonEmpty = sion.CityCatalog!.Buildings[0]; + string rcgaPath = Path.Combine(sion.DirectoryPath, "tiles", $"city_{firstNonEmpty.Tx}_{firstNonEmpty.Tz}.rcga"); + byte[] validRcga = File.ReadAllBytes(rcgaPath); + Assert.Throws(() => SionCityCatalog.ParseRcgaTileBytes(validRcga.AsSpan(0, 12))); + Assert.Throws(() => SionCityCatalog.ParseRcgaTileBytes(validRcga.AsSpan(0, validRcga.Length - 16))); + + // Synthetic RCGA with ZoneCount = 65 + byte[] badPayload = new byte[36]; + badPayload[2] = 65; + using var ms = new MemoryStream(); + using (var z = new ZLibStream(ms, CompressionLevel.Fastest, leaveOpen: true)) + { + z.Write(badPayload, 0, badPayload.Length); + } + byte[] comp = ms.ToArray(); + byte[] badRcga = new byte[24 + comp.Length]; + badRcga[0] = (byte)'R'; badRcga[1] = (byte)'C'; badRcga[2] = (byte)'G'; badRcga[3] = (byte)'A'; + BinaryPrimitives.WriteUInt32LittleEndian(badRcga.AsSpan(4, 4), 1); + BinaryPrimitives.WriteUInt32LittleEndian(badRcga.AsSpan(8, 4), 0); + BinaryPrimitives.WriteUInt32LittleEndian(badRcga.AsSpan(12, 4), 0); + BinaryPrimitives.WriteUInt32LittleEndian(badRcga.AsSpan(16, 4), 1); + BinaryPrimitives.WriteUInt32LittleEndian(badRcga.AsSpan(20, 4), (uint)badPayload.Length); + comp.CopyTo(badRcga, 24); + Assert.Throws(() => SionCityCatalog.ParseRcgaTileBytes(badRcga, 0, 0)); } [Fact] diff --git a/tools/maps/sion/bake_sion.py b/tools/maps/sion/bake_sion.py index affe2d4..ea22e1a 100644 --- a/tools/maps/sion/bake_sion.py +++ b/tools/maps/sion/bake_sion.py @@ -1955,22 +1955,8 @@ def bake_cga_city( 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 + # Orient raw 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) @@ -1986,12 +1972,19 @@ def bake_cga_city( 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, + sample_terrain_fn=lambda xs, zs: sample_heightmap(hm, xs, zs), + tx=0, + tz=0, + local_slot=0, ) + final_center = 0.5 * (res.bounds_min + res.bounds_max) + tx = max(0, min(TILE_GRID - 1, int(math.floor((float(final_center[0]) + HALF_EXTENT_M) / TILE_SIZE_M)))) + tz = max(0, min(TILE_GRID - 1, int(math.floor((float(final_center[2]) + HALF_EXTENT_M) / TILE_SIZE_M)))) + slot = tile_slot_counter[(tx, tz)] + tile_slot_counter[(tx, tz)] += 1 + res.tx = tx + res.tz = tz + res.local_slot = slot all_cga_buildings.append(res) tile_buildings[(tx, tz)].append(res) micro_counts[res.micro_zone] += 1 diff --git a/tools/maps/sion/cga_builder.py b/tools/maps/sion/cga_builder.py index 6ee3fb2..6012c27 100644 --- a/tools/maps/sion/cga_builder.py +++ b/tools/maps/sion/cga_builder.py @@ -147,6 +147,7 @@ class CgaBuildingResult: zones: list[CgaZoneMesh] lod2_tris: np.ndarray lod2_mats: np.ndarray + lod2_solids: list[tuple[np.ndarray, int]] # --------------------------------------------------------------------------- @@ -446,14 +447,24 @@ def classify_sion_micro_zone( 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: + # Hilltop historic fortifications (Valère / Tourbillon >= 70m above valley floor, or city wall towers) + if (ground_rel_y >= 70.0 and ( + objektart in ("Sakrales Gebaeude", "Kapelle", "Sakraler Turm", "Mauer gross") + or any(k in nl for k in ("valère", "valere", "tourbillon", "basilique", "château", "chateau", "tous-les-saints")) + or (2594180.0 <= ce <= 2594650.0 and 1120180.0 <= cn <= 1120660.0) + )) or ("sorciers" in nl) or (objektart == "Mauer gross" and ground_rel_y >= 40.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")): + # Valley monumental, sacred, educational, medical, stadium & civic structures + if ( + objektart in ("Sakrales Gebaeude", "Kapelle", "Sakraler Turm") + or 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", "cathédral", "stade", "piscine", "patinoire", + )) + or (objektart == "Offenes Gebaeude" and cn >= 1119900.0 and ground_rel_y < 55.0) + ): return MICRO_CIVIC, ARCH_RESIDENTIAL if objektart in ("Hochhaus", "Offenes Gebaeude", "Flugdach", "Unterirdisches Gebaeude", "Im Bau", "Lagertank", "Treibhaus"): @@ -661,7 +672,7 @@ def _extract_footprint_polygons( 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 + return [p for p in out[:4] if p.area >= 3.0] or out[:1] def _merge_short_ring_edges(coords: list[tuple[float, float]], min_edge_len: float = 1.2) -> list[tuple[float, float]]: @@ -944,9 +955,30 @@ def _build_roof_zones( 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]: + # Select planes keeping highest-elevation peaks/spires FIRST so towers aren't truncated, + # then largest-area slopes up to max_roof_zones. + def plane_max_y(item) -> float: + orig, u_ax, v_ax, _, poly = item + pts2 = np.array(poly.exterior.coords) + ys = orig[1] + pts2[:, 0] * u_ax[1] + pts2[:, 1] * v_ax[1] + return float(ys.max()) + + by_height = sorted(planes, key=plane_max_y, reverse=True) + by_area = sorted(planes, key=lambda item: item[4].area, reverse=True) + selected: list[tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, Polygon]] = [] + seen_ids: set[int] = set() + # Keep top 2 highest roof planes (spires/belltowers) when max_roof_zones >= 2 + for item in by_height[: (2 if max_roof_zones >= 2 else 1)]: + selected.append(item) + seen_ids.add(id(item)) + for item in by_area: + if len(selected) >= max_roof_zones: + break + if id(item) not in seen_ids: + selected.append(item) + seen_ids.add(id(item)) + + for origin, u_axis, v_axis, n_axis, poly in selected: parts = extrude_2d_poly_prism( origin, u_axis, v_axis, n_axis, poly, -roof_thick, 0.0, @@ -958,28 +990,53 @@ def _build_roof_zones( out.append((parts, parts, c3)) if not out and footprints: - # Flat roof slab cap over primary footprint + # Flat roof slab cap over footprints 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)) + for fp in footprints[:max_roof_zones]: + 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, + ) + rp = fp.representative_point() + c3 = np.array([rp.x, eave_y + roof_thick * 0.5, rp.y], dtype=np.float64) + out.append((parts, parts, c3)) return out +def _sample_terrain_over_polygons( + polys: list[Polygon], sample_terrain_fn +) -> tuple[float, float]: + """Sample terrain height across every polygon's exterior/interior vertices plus 5x5 interior grid.""" + xs_list: list[float] = [] + zs_list: list[float] = [] + for p in polys: + for x, z in p.exterior.coords: + xs_list.append(float(x)) + zs_list.append(float(z)) + for ring in p.interiors: + for x, z in ring.coords: + xs_list.append(float(x)) + zs_list.append(float(z)) + minx, minz, maxx, maxz = p.bounds + gx = np.linspace(minx, maxx, 5) + gz = np.linspace(minz, maxz, 5) + mx, mz = np.meshgrid(gx, gz) + for px, pz in zip(mx.ravel(), mz.ravel()): + xs_list.append(float(px)) + zs_list.append(float(pz)) + vals = sample_terrain_fn(np.asarray(xs_list, dtype=np.float64), np.asarray(zs_list, dtype=np.float64)) + return float(np.min(vals)), float(np.max(vals)) + + # --------------------------------------------------------------------------- # Main Building Decomposer -> CgaBuildingResult (<= 64 zones, DAG, watertight) # --------------------------------------------------------------------------- @@ -994,8 +1051,7 @@ def build_cga_building( r_rtd: list[np.ndarray], fl_rtd: list[np.ndarray], s_rtd: list[np.ndarray], - terrain_min_y: float, - terrain_max_y: float, + sample_terrain_fn, tx: int, tz: int, local_slot: int, @@ -1008,7 +1064,7 @@ def build_cga_building( 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.40 if micro_zone in (MICRO_FORTRESS, MICRO_OLD_TOWN) else 0.95 + simplify_tol = 0.25 if micro_zone in (MICRO_FORTRESS, MICRO_OLD_TOWN, MICRO_CIVIC) else 0.55 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()) @@ -1019,7 +1075,19 @@ def build_cga_building( 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 + # Final Plinth polygons (NO minimum_rotated_rectangle expansion -> 0 floating overhang) + plinth_tol = 0.30 if micro_zone in (MICRO_FORTRESS, MICRO_OLD_TOWN, MICRO_CIVIC) else 0.70 + plinth_fps: list[Polygon] = [] + for fp in footprints: + ps = fp.simplify(plinth_tol, preserve_topology=True) + pc = _clean_polygon_2d(ps if isinstance(ps, Polygon) else fp, min_area=0.8) or fp + plinth_fps.append(pc) + plinth_fp = plinth_fps[0] + + # Sample terrain height across the FINAL baked Plinth footprint polygons + terrain_min_y, terrain_max_y = _sample_terrain_over_polygons(plinth_fps, sample_terrain_fn) + + # Plinth anchors strictly -4.0m below the lowest terrain under the final Plinth polygon plinth_bot_y = min(raw_min_y, terrain_min_y) - SKIRT_DEPTH_M # Wall top (eave_y) @@ -1100,18 +1168,17 @@ def build_cga_building( 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_fp = primary_fp.simplify(1.35, preserve_topology=True) - plinth_fp = _clean_polygon_2d(plinth_fp if isinstance(plinth_fp, Polygon) else primary_fp, min_area=0.8) or primary_fp - if len(plinth_fp.exterior.coords) > 7 and not plinth_fp.interiors: - plinth_fp = plinth_fp.minimum_rotated_rectangle - plinth_uv = fp_to_uv(plinth_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, - ) + # 1. Zone 0: Plinth / Foundation (IsGroundAnchored = true) across all footprint components + plinth_parts_list = [ + extrude_2d_poly_prism( + np.array([0.0, plinth_bot_y, 0.0]), u_xz, v_xz, n_up, fp_to_uv(pfp), + 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, + ) + for pfp in plinth_fps + ] + plinth_parts = _concat_parts(plinth_parts_list) plinth_idx = add_zone( ZONE_PLINTH, pal["plinth_class"], ZONE_FLAG_GROUND_ANCHORED | ZONE_FLAG_EXTERIOR, @@ -1120,49 +1187,55 @@ def build_cga_building( 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",) + # Only explicit open canopies / sheds without enclosing walls skip WallBays + is_canopy_only = objektart in ("Offenes Gebaeude", "Flugdach") is_mauer = (objektart == "Mauer gross") - # Build lean watertight LOD2 silhouette (single OBB prism, uniform wall material to minimize draw calls & JSON overhead) - lod2_fp = primary_fp.minimum_rotated_rectangle - lod2_uv = Polygon([(x, -z) for x, z in lod2_fp.exterior.coords]) - lod2_h = max(1.2, max(eave_y, raw_max_y) - plinth_bot_y) - lod2_t, lod2_m, _, _ = extrude_2d_poly_prism( - np.array([0.0, plinth_bot_y, 0.0]), u_xz, v_xz, n_up, lod2_uv, - 0.0, lod2_h, - mat_top=pal["wall"], mat_bot=pal["wall"], mat_side=pal["wall"], - ) + # Build real-footprint + pitched-roof watertight LOD2 solids + lod2_solids: list[tuple[np.ndarray, int]] = [] + lod2_body_h = max(1.0, eave_y - plinth_bot_y - 0.02) + for pfp in plinth_fps: + l2_fp = pfp.simplify(0.65, preserve_topology=True) + l2_fp = _clean_polygon_2d(l2_fp if isinstance(l2_fp, Polygon) else pfp, min_area=0.5) or pfp + l2_t, _, _, _ = extrude_2d_poly_prism( + np.array([0.0, plinth_bot_y, 0.0]), u_xz, v_xz, n_up, fp_to_uv(l2_fp), + 0.0, lod2_body_h, + mat_top=pal["wall"], mat_bot=pal["wall"], mat_side=pal["wall"], + ) + lod2_solids.append((l2_t, pal["wall"])) # 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]) + lod2_tris_cat = np.concatenate([s[0] for s in lod2_solids], axis=0) + lod2_mats_cat = np.concatenate([np.full(len(s[0]), s[1], dtype=np.uint8) for s in lod2_solids], axis=0) 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, - lod2_tris=lod2_t, lod2_mats=lod2_m, + lod2_tris=lod2_tris_cat, lod2_mats=lod2_mats_cat, lod2_solids=lod2_solids, ) - # 2. Precompute Roof Zones so we know exact zone budget + # 2. Precompute Roof Zones so we know exact zone budget (keep spires & multi-wing roofs intact!) if is_mauer: max_roofs = 0 - elif micro_zone in (MICRO_FORTRESS, MICRO_OLD_TOWN, MICRO_CIVIC): + elif micro_zone in (MICRO_FORTRESS, MICRO_CIVIC): + max_roofs = 8 + elif micro_zone in (MICRO_OLD_TOWN, MICRO_CLAVAU, MICRO_SUBURBAN): max_roofs = 4 - elif micro_zone in (MICRO_CLAVAU, MICRO_SUBURBAN): - max_roofs = 2 else: - max_roofs = 1 + max_roofs = 3 roof_items = _build_roof_zones( - r_rtd, footprints, eave_y, bldg_center_xz, pal, max_roofs, micro_zone, objektart + r_rtd, plinth_fps, 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: + if is_canopy_only or (wall_h < 1.2 and len(w_rtd) == 0): # Add 1 InteriorCore pier supporting the roof - minx, minz, maxx, maxz = primary_fp.bounds + minx, minz, maxx, maxz = plinth_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) @@ -1176,7 +1249,8 @@ def build_cga_building( 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) + r_idx = add_zone(ZONE_ROOF_SEGMENT, pal["roof_class"], ZONE_FLAG_EXTERIOR, core_bit, r_render, r_col) + lod2_solids.append((zones[r_idx].col_tris, pal["roof"])) else: # 4. Standard Multi-Story Decomposition (Core + WallBays + FloorSlabs + Roofs) story_h_target = { @@ -1190,20 +1264,20 @@ def build_cga_building( }[micro_zone] n_stories = max(1, int(round(wall_h / story_h_target))) - min_edge = 2.6 if micro_zone in (MICRO_OLD_TOWN, MICRO_FORTRESS) else 3.8 - ext_pts = _merge_short_ring_edges(list(primary_fp.exterior.coords), min_edge_len=min_edge) + min_edge = 2.6 if micro_zone in (MICRO_OLD_TOWN, MICRO_FORTRESS, MICRO_CIVIC) else 3.6 + ext_pts = _merge_short_ring_edges(list(plinth_fp.exterior.coords), min_edge_len=min_edge) raw_bays_len = max(3, len(ext_pts)) # Cap structural tiers cleanly so total city RCGA + LOD2 fits well <= 16 MiB avail_for_stories = MAX_ZONES_PER_BUILDING - (2 + n_roofs) - max_tiers = 4 if n_stories >= 8 else (3 if micro_zone in (MICRO_OLD_TOWN, MICRO_FORTRESS) and n_stories >= 3 else 2) + max_tiers = 4 if n_stories >= 8 else (3 if micro_zone in (MICRO_OLD_TOWN, MICRO_FORTRESS, MICRO_CIVIC) and n_stories >= 3 else 2) n_tiers = min(n_stories, max_tiers, max(1, avail_for_stories // max(4, min(raw_bays_len + 1, 7)))) n_tiers = max(1, n_tiers) max_bays_per_tier = max(3, min(7, (avail_for_stories // n_tiers) - 1)) - perim = float(primary_fp.exterior.length) - base_bay_len = 12.0 if micro_zone in (MICRO_OLD_TOWN, MICRO_FORTRESS) else (18.0 if (is_mauer or micro_zone == MICRO_RONQUOZ or perim > 70.0) else 16.0) + perim = float(plinth_fp.exterior.length) + base_bay_len = 12.0 if micro_zone in (MICRO_OLD_TOWN, MICRO_FORTRESS, MICRO_CIVIC) else (18.0 if (is_mauer or micro_zone == MICRO_RONQUOZ or perim > 70.0) else 16.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) @@ -1211,19 +1285,21 @@ def build_cga_building( bays_2d = cand break if not bays_2d: - simple_fp = primary_fp.simplify(max(0.8, perim * 0.04), 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=3.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: - 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) + # Simplify plinth_fp progressively until edge count fits max_bays_per_tier (never OBB-expand!) + for simp_f in (0.04, 0.08, 0.14): + sfp = plinth_fp.simplify(max(0.8, perim * simp_f), preserve_topology=True) + if isinstance(sfp, Polygon) and not sfp.is_empty: + spts = _merge_short_ring_edges(list(sfp.exterior.coords), min_edge_len=3.2) + cand = _split_ring_into_wall_bays(spts, max(base_bay_len, perim / max(3, max_bays_per_tier))) + if len(cand) <= max_bays_per_tier: + bays_2d = cand + break + if not bays_2d: + cand = _split_ring_into_wall_bays(ext_pts, perim + 1.0) + bays_2d = cand[:max_bays_per_tier] if len(cand) > max_bays_per_tier else cand # 4a. InteriorCore zone (spans full height plinth_top_y .. eave_y - 0.15) - minx, minz, maxx, maxz = primary_fp.bounds + minx, minz, maxx, maxz = plinth_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) @@ -1238,15 +1314,19 @@ def build_cga_building( 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_fp_s = slab_fp.simplify(1.15, preserve_topology=True) - if isinstance(slab_fp_s, Polygon) and not slab_fp_s.is_empty and slab_fp_s.area >= 0.8: - slab_fp = slab_fp_s - if len(slab_fp.exterior.coords) > 5 and not slab_fp.interiors: - slab_fp = slab_fp.minimum_rotated_rectangle - slab_uv = fp_to_uv(slab_fp) + slab_polys_uv: list[Polygon] = [] + for pfp in plinth_fps: + sfp = pfp.buffer(-slab_inset, join_style="mitre") + if not isinstance(sfp, (Polygon, MultiPolygon)) or sfp.is_empty: + sfp = pfp.buffer(-0.05, join_style="mitre") + sfp = sfp.intersection(pfp) + geoms = list(sfp.geoms) if hasattr(sfp, "geoms") else [sfp] + valid_geoms = [_clean_polygon_2d(g, min_area=0.4) for g in geoms if isinstance(g, Polygon)] + valid_geoms = [g for g in valid_geoms if g is not None] + if not valid_geoms: + valid_geoms = [pfp] + for vg in valid_geoms: + slab_polys_uv.append(fp_to_uv(vg)) slab_thick = 0.28 tier_h = wall_h / n_tiers @@ -1281,7 +1361,6 @@ def build_cga_building( 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 @@ -1290,19 +1369,22 @@ def build_cga_building( 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) + # Horizontal FloorSlab at top of tier t_idx (strictly inset inside plinth_fps, 0 overhang) 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_parts = _concat_parts([ + extrude_2d_poly_prism( + np.array([0.0, slab_y0, 0.0]), u_xz, v_xz, n_up, suv, + 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, + ) + for suv in slab_polys_uv + ]) 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) @@ -1313,21 +1395,23 @@ def build_cga_building( 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 + # 5. Roof Zones anchored to top-tier perimeter WallBays (never floating solely on 0.8m core) 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 = 0 + for _, idx_b in dists[:3]: 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) + else: + r_sup = plinth_bit + r_idx = add_zone(ZONE_ROOF_SEGMENT, pal["roof_class"], ZONE_FLAG_EXTERIOR, r_sup, r_render, r_col) + lod2_solids.append((zones[r_idx].col_tris, pal["roof"])) all_pts_bounds = np.vstack([z.render_tris.reshape(-1, 3) for z in zones] + [z.col_tris.reshape(-1, 3) for z in zones]) bmin = all_pts_bounds.min(axis=0) @@ -1337,6 +1421,9 @@ def build_cga_building( if z.flags & ZONE_FLAG_GROUND_ANCHORED: g_mask |= (1 << z.zone_index) + lod2_tris_cat = np.concatenate([s[0] for s in lod2_solids], axis=0) + lod2_mats_cat = np.concatenate([np.full(len(s[0]), s[1], dtype=np.uint8) for s in lod2_solids], axis=0) + return CgaBuildingResult( building_id=building_id, egid=egid, @@ -1354,8 +1441,9 @@ def build_cga_building( roof_y=float(bmax[1]), ground_anchored_mask=g_mask, zones=zones, - lod2_tris=lod2_t, - lod2_mats=lod2_m, + lod2_tris=lod2_tris_cat, + lod2_mats=lod2_mats_cat, + lod2_solids=lod2_solids, ) @@ -1436,8 +1524,10 @@ def _pack_zone_mesh_16b( ao = ao[valid] uvs = uvs[valid] - e1 = tris[:, 1] - tris[:, 0] - e2 = tris[:, 2] - tris[:, 0] + # Compute face normals from post-quantization positions so decoded normals match quantized geometry + deq_tris = pos_origin[None, None, :] + qpos_all.astype(np.float64) * pos_scale[None, None, :] + e1 = deq_tris[:, 1] - deq_tris[:, 0] + e2 = deq_tris[:, 2] - deq_tris[:, 0] cross = np.cross(e1, e2) nlen = np.maximum(1e-9, np.linalg.norm(cross, axis=1, keepdims=True)) face_norms = cross / nlen @@ -1648,11 +1738,16 @@ def export_rcga_tile(tx: int, tz: int, buildings: list[CgaBuildingResult], out_p def export_city_lod2_glb(tx: int, tz: int, buildings: list[CgaBuildingResult], out_path) -> tuple[int, int]: - """Export simplified watertight LOD2 GLB (one simplified silhouette hull per building) on 16x16 grid.""" - mat_tris: dict[int, list[np.ndarray]] = defaultdict(list) + """ + Export real-footprint + pitched-roof watertight LOD2 GLB on 16x16 grid. + Deduplicates vertices per closed solid component so adjacent roof slopes / rowhouses + never merge across disjoint solid boundaries. + """ + mat_solids: dict[int, list[np.ndarray]] = defaultdict(list) for b in buildings: - for tri, mid in zip(b.lod2_tris, b.lod2_mats): - mat_tris[int(mid)].append(tri) + for solid_tris, mid in b.lod2_solids: + if len(solid_tris) > 0: + mat_solids[int(mid)].append(solid_tris) out_path.parent.mkdir(parents=True, exist_ok=True) blob = bytearray() @@ -1662,35 +1757,54 @@ def export_city_lod2_glb(tx: int, tz: int, buildings: list[CgaBuildingResult], o 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) + for pal_id, solid_list in sorted(mat_solids.items()): + part_verts: list[np.ndarray] = [] + part_norms: list[np.ndarray] = [] + part_indices: list[np.ndarray] = [] + vert_offset = 0 - 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=" 1e-6 + if not np.all(valid): + tris = tris[valid] + cross = cross[valid] + nlen = nlen[valid] + if len(tris) == 0: + continue + n_face = (cross / nlen[:, 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) + s_verts = np.ascontiguousarray(raw_verts[uniq_idx], dtype=" np.ndarray | None: + if not hm_path.exists(): + return None + raw = hm_path.read_bytes() + magic, ver, grid_res, min_y, scale, _ = struct.unpack_from("<4sIIffI", raw, 0) + if magic != b"RDHM" or ver != 2: + return None + 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 _sample_hm_verify(hm: np.ndarray, xs: np.ndarray, zs: np.ndarray) -> np.ndarray: + grid_res = hm.shape[0] + cell = (HALF_EXTENT_M * 2.0) / (grid_res - 1) + fx = np.clip((xs + HALF_EXTENT_M) / cell, 0.0, grid_res - 1.00001) + fz = np.clip((zs + HALF_EXTENT_M) / cell, 0.0, grid_res - 1.00001) + ix = np.floor(fx).astype(np.int32) + iz = np.floor(fz).astype(np.int32) + tx = fx - ix + tz = fz - iz + return ( + (hm[iz, ix] * (1.0 - tx) + hm[iz, ix + 1] * tx) * (1.0 - tz) + + (hm[iz + 1, ix] * (1.0 - tx) + hm[iz + 1, ix + 1] * tx) * tz + ) + + def verify_rcga_outputs(sion_dir) -> 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 + - SHA-256 integrity of buildings_cga.bin body + - open_boundary_edges == 0, non_manifold_edges == 0, degenerate_tris == 0 (RCGA & LOD2 GLB) + - LOD2 GLB outward signed_volume > 0 per component + - support_dag_cycles == 0 & 100% ground reachability + - grounding: plinth.bmin.y <= min_terrain_under_plinth - 3.90m (0 floating plinths) + - FloorSlab non-overhang: every FloorSlab XZ lies strictly inside Zone 0 Plinth footprint + - tx, tz match final building bounds midpoint - combined city_*.rcga + city_lod2_*.glb <= 16 MiB """ cga_bin = sion_dir / "buildings_cga.bin" @@ -1871,6 +2027,8 @@ def verify_rcga_outputs(sion_dir) -> dict[str, int | float | str]: body = zlib.decompress(raw[64:]) if (flags & 1) else raw[64:] if len(body) != uncomp_len: raise RuntimeError("RCGB uncompressed length mismatch") + if hashlib.sha256(body).digest() != digest: + raise RuntimeError("RCGB body SHA-256 digest mismatch") bldg_recs_end = bldg_cnt * 64 zone_recs_end = bldg_recs_end + total_zones * 44 @@ -1886,18 +2044,26 @@ def verify_rcga_outputs(sion_dir) -> dict[str, int | float | str]: zrec = 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: @@ -1931,7 +2097,9 @@ def verify_rcga_outputs(sion_dir) -> dict[str, int | float | str]: if reachable != ((1 << n) - 1): ground_unreachable += 1 - # Verify every RCGA tile mesh slice + hm = _load_heightmap_u16z_for_verify(sion_dir / "heightmap_05m.u16z") + + # Verify every RCGA tile mesh slice + Grounding + FloorSlab non-overhang 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")) @@ -1939,6 +2107,12 @@ def verify_rcga_outputs(sion_dir) -> dict[str, int | float | str]: open_edges_total = 0 non_manifold_total = 0 degenerate_total = 0 + lod2_open_total = 0 + lod2_non_manifold_total = 0 + lod2_deg_total = 0 + lod2_inverted_solids = 0 + grounding_violations = 0 + floorslab_overhangs = 0 verified_buildings = 0 total_render_tris = 0 total_col_tris = 0 @@ -1970,12 +2144,17 @@ def verify_rcga_outputs(sion_dir) -> dict[str, int | float | str]: s_ptr = 0 for hdr in rb_hdrs: bid, z_cnt = hdr[0], hdr[1] + origin = np.array(hdr[3:6], dtype=np.float64) + scale = np.array(hdr[6:9], dtype=np.float64) + first_z = buildings_meta[bid][7] verified_buildings += 1 - for _ in range(z_cnt): + plinth_verts_xz: np.ndarray | None = None + plinth_min_y = 0.0 + + for zi in range(z_cnt): rv_cnt, ri_cnt, cv_cnt, ci_cnt = slice_hdrs[s_ptr] s_ptr += 1 - # Read render verts (extract int16[3] pos at start of 16B record) rv_arr = np.frombuffer(rpayload, dtype=" dict[str, int | float | str]: total_render_tris += ri_cnt // 3 total_col_tris += ci_cnt // 3 + z_kind = zones_meta[first_z + zi][1] + c_pos = origin[None, :] + cv_arr.astype(np.float64) * scale[None, :] + if zi == 0 and z_kind == ZONE_PLINTH: + plinth_verts_xz = c_pos[:, [0, 2]] + plinth_min_y = float(c_pos[:, 1].min()) + if hm is not None and len(plinth_verts_xz) > 0: + t_vals = _sample_hm_verify(hm, plinth_verts_xz[:, 0], plinth_verts_xz[:, 1]) + if plinth_min_y > float(np.min(t_vals)) - 3.90: + grounding_violations += 1 + elif z_kind == ZONE_FLOOR_SLAB and plinth_verts_xz is not None: + p_x0, p_z0 = float(plinth_verts_xz[:, 0].min()), float(plinth_verts_xz[:, 1].min()) + p_x1, p_z1 = float(plinth_verts_xz[:, 0].max()), float(plinth_verts_xz[:, 1].max()) + s_x0, s_z0 = float(c_pos[:, 0].min()), float(c_pos[:, 2].min()) + s_x1, s_z1 = float(c_pos[:, 0].max()), float(c_pos[:, 2].max()) + if s_x0 < p_x0 - 0.08 or s_x1 > p_x1 + 0.08 or s_z0 < p_z0 - 0.08 or s_z1 > p_z1 + 0.08: + floorslab_overhangs += 1 + + # Verify every city_lod2_*.glb primitive & connected solid component + for lpath in lod2_files: + gltf = pygltflib.GLTF2().load_binary(str(lpath)) + blob = gltf.binary_blob() + for mesh in gltf.meshes: + for prim in mesh.primitives: + pos_acc = gltf.accessors[prim.attributes.POSITION] + pos_bv = gltf.bufferViews[pos_acc.bufferView] + pos = np.frombuffer( + blob, dtype=" int: + while parent[x] != x: + parent[x] = parent[parent[x]] + x = parent[x] + return x + for a, b, c in tri_idx: + ra, rb, rc = find(int(a)), find(int(b)), find(int(c)) + if rb != ra: + parent[rb] = ra + if rc != ra: + parent[rc] = ra + comp_tris: dict[int, list[int]] = defaultdict(list) + for ti, (a, _, _) in enumerate(tri_idx): + comp_tris[find(int(a))].append(ti) + for tlist in comp_tris.values(): + ct = pos[tri_idx[tlist]].astype(np.float64) + vol6 = float(np.sum(np.sum(ct[:, 0, :] * np.cross(ct[:, 1, :], ct[:, 2, :]), axis=1))) + if vol6 <= 1e-4: + lod2_inverted_solids += 1 + rcga_bytes = sum(p.stat().st_size for p in rcga_files) lod2_bytes = sum(p.stat().st_size for p in lod2_files) combined_bytes = rcga_bytes + lod2_bytes @@ -2010,6 +2255,13 @@ def verify_rcga_outputs(sion_dir) -> dict[str, int | float | str]: "open_boundary_edges": open_edges_total, "non_manifold_edges": non_manifold_total, "degenerate_tris": degenerate_total, + "lod2_open_edges": lod2_open_total, + "lod2_non_manifold_edges": lod2_non_manifold_total, + "lod2_degenerate_tris": lod2_deg_total, + "lod2_inverted_solids": lod2_inverted_solids, + "grounding_violations": grounding_violations, + "floorslab_overhangs": floorslab_overhangs, + "tile_drift_count": tile_drift_count, "support_dag_cycles": dag_cycles, "ground_unreachable": ground_unreachable, "rcga_bytes": rcga_bytes, @@ -2023,7 +2275,15 @@ def verify_rcga_outputs(sion_dir) -> dict[str, int | float | str]: raise RuntimeError(f"Verified buildings mismatch: {verified_buildings} != {bldg_cnt}") if open_edges_total != 0 or non_manifold_total != 0 or degenerate_total != 0: raise RuntimeError( - f"Watertight audit FAILED: open={open_edges_total}, non_manifold={non_manifold_total}, deg={degenerate_total}" + f"RCGA watertight audit FAILED: open={open_edges_total}, non_manifold={non_manifold_total}, deg={degenerate_total}" + ) + if lod2_open_total != 0 or lod2_non_manifold_total != 0 or lod2_deg_total != 0 or lod2_inverted_solids != 0: + raise RuntimeError( + f"LOD2 GLB watertight audit FAILED: open={lod2_open_total}, nm={lod2_non_manifold_total}, deg={lod2_deg_total}, inv={lod2_inverted_solids}" + ) + if grounding_violations != 0 or floorslab_overhangs != 0 or tile_drift_count != 0: + raise RuntimeError( + f"Spatial audit FAILED: grounding={grounding_violations}, floorslab_overhang={floorslab_overhangs}, tile_drift={tile_drift_count}" ) if dag_cycles != 0 or ground_unreachable != 0: raise RuntimeError(f"Support DAG audit FAILED: cycles={dag_cycles}, unreachable={ground_unreachable}")