feat(content): S1 exact CellStruct surface-index construction, recipe 8

Campaign OVERHAUL S1 chunk A. Retail's D3DPolyRender::ConstructMesh
@0x0059DFA0 is ported as one pure Core descriptor plus the Content
extraction that consumes it:

- side candidates come only from sides_type (0/1/2); NoPos/NoNeg mean
  UV-array absence only and never suppress a side (CPolygon::UnPack
  @0x00538650);
- ST_DOUBLE's second copy is reversed with a negative normal; ST_BOTH's
  negative side has a negative normal and forward fan order (reverse is on
  the copy ordinal, not the side ordinal);
- an absent UV-index array is UV index 0 (ConstructMesh @0x0059E691
  xor ebx,ebx, arbitrated on the PDB-paired binary); copyVert @0x0059C080
  zeroes coordinates only for a negative or out-of-range index or a vertex
  without UVs, never by clamping to slot 0;
- the subset owner is the source surface-array index, emitted in ascending
  slot order with retail's per-slot mask (2 > 8 > 4 precedence, positive
  surface OR on signed stippling > 0);
- built-EnvCell admission is (Surface.Type & (BASE1_IMAGE|BASE1_CLIPMAP))
  != 0 after surface resolution (DrawEnvCell @0x0059F170 -> DrawMesh
  @0x0059D4A0 arg4=1); untextured slots are constructed but not emitted;
- cell batches carry SourceSurfaceIndex, RetailSurfaceMask, RawSurfaceType,
  IsCellShell, and fixed clockwise raster cull (RenderMeshSubset
  @0x0059CA10); authored sides_type is no longer stored as GPU cull.

Prepared-mesh serializer gains the four fields; bake recipe 7 -> 8 with a
FullRebuild migration; pak format stays 2 (pinned). Ordinary GfxObj
extraction is unchanged. AP-234's register row and CellMesh unification
land in chunk B.

Core: 32 descriptor tests. Content: 170/170. Bake: 18/18. Launcher.Core:
365/365 (Lane!=Linux). Solution Release build 0 warnings / 0 errors.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
Erik 2026-09-02 18:40:33 +02:00
parent 14d8fe6478
commit acf172469e
15 changed files with 1746 additions and 296 deletions

View file

@ -222,9 +222,166 @@ public sealed class MeshExtractorSolidFaceExtractionTests
Assert.Equal(4 * 4 * 4, Assert.Single(group.Value).TextureData.Length);
}
/// <summary>
/// OH2/S1 chunk-2 (2026-09-02): these two winding tests used to register
/// an UNTEXTURED (Base1Solid) surface. Under the exact contract, an
/// untextured surface slot is constructed but never EMITTED (built-
/// EnvCell admission, contract §4) — so the winding assertions need a
/// TEXTURED surface to have a batch to inspect at all. Geometry/winding
/// output is independent of texturing, so switching to Base1Image does
/// not change what these tests actually pin (verified by hand against
/// CellStructSideCandidates.TriangleFanIndices before this change).
/// </summary>
private static void RegisterCellTexturedSurface(FakeMeshExtractorDats dats)
{
dats.Register(TexturedSurfaceId, new Surface
{
Type = SurfaceType.Base1Image,
OrigTextureId = SurfaceTextureId,
});
dats.Register(SurfaceTextureId, new SurfaceTexture
{
Textures = new List<QualifiedDataId<RenderSurface>> { RenderSurfaceId },
});
dats.Register(RenderSurfaceId, new RenderSurface
{
Width = 1,
Height = 1,
Format = PixelFormat.PFID_A8R8G8B8,
SourceData = new byte[] { 10, 20, 30, 255 },
});
}
[Fact]
public void PrepareCellStructMeshData_LandblockSide_PreservesRetailTriangleFanWinding()
{
var dats = new FakeMeshExtractorDats();
RegisterCellTexturedSurface(dats);
var extractor = new MeshExtractor(dats, NullLogger.Instance, sideStagedSink: null);
ObjectMeshData mesh = Assert.IsType<ObjectMeshData>(
extractor.PrepareCellStructMeshData(
id: 1,
BuildQuadCellStruct(RetailCullMode.Landblock),
surfaceOverrides: [2],
Matrix4x4.Identity,
CancellationToken.None));
TextureBatchData batch = Assert.Single(Assert.Single(mesh.TextureBatches).Value);
// Contract §3.6 + EnvCellRenderer.Rhi.cs's
// ResolveRetailCellShellCullMode: cell shells now always draw
// fixed D3DCULL_CW; the authored sides_type (ST_SINGLE here) no
// longer flows into CullMode.
Assert.Equal(RetailCullMode.Clockwise, batch.CullMode);
Assert.True(batch.IsCellShell);
Assert.Equal(0, batch.SourceSurfaceIndex);
Assert.Equal([0, 1, 2, 0, 2, 3], batch.Indices);
Assert.Equal(4, mesh.Vertices.Length);
Assert.All(mesh.Vertices, vertex => Assert.Equal(Vector3.UnitZ, vertex.Normal));
}
[Fact]
public void PrepareCellStructMeshData_NoneSide_ExpandsReversedFaceExactlyLikeRetailConstructMesh()
{
var dats = new FakeMeshExtractorDats();
RegisterCellTexturedSurface(dats);
var extractor = new MeshExtractor(dats, NullLogger.Instance, sideStagedSink: null);
ObjectMeshData mesh = Assert.IsType<ObjectMeshData>(
extractor.PrepareCellStructMeshData(
id: 1,
BuildQuadCellStruct(RetailCullMode.None),
surfaceOverrides: [2],
Matrix4x4.Identity,
CancellationToken.None));
TextureBatchData batch = Assert.Single(Assert.Single(mesh.TextureBatches).Value);
Assert.Equal(RetailCullMode.Clockwise, batch.CullMode);
Assert.True(batch.IsCellShell);
Assert.Equal(0, batch.SourceSurfaceIndex);
Assert.Equal(
[0, 1, 2, 0, 2, 3, 6, 5, 4, 7, 6, 4],
batch.Indices);
Assert.Equal(8, mesh.Vertices.Length);
Assert.All(mesh.Vertices.Take(4), vertex => Assert.Equal(Vector3.UnitZ, vertex.Normal));
Assert.All(mesh.Vertices.Skip(4), vertex => Assert.Equal(-Vector3.UnitZ, vertex.Normal));
}
[Fact]
public void PrepareCellStructMeshData_BothSide_NegativeCandidateIsNotWindingReversed()
{
// Contract §3.4's binding, counterintuitive fact: ST_BOTH's negative
// candidate changes the SIDE ordinal, not the COPY ordinal, so its
// fan order stays FORWARD even though its normal is negated. Only
// ST_DOUBLE's second COPY reverses winding. Two DISTINCT surface
// slots (0 and 1) so this also exercises "two subsets, one per
// side" for ST_BOTH.
var dats = new FakeMeshExtractorDats();
dats.Register(0x0800000Au, new Surface { Type = SurfaceType.Base1Image, OrigTextureId = SurfaceTextureId });
dats.Register(0x08000014u, new Surface { Type = SurfaceType.Base1Image, OrigTextureId = SurfaceTextureId });
dats.Register(SurfaceTextureId, new SurfaceTexture
{
Textures = new List<QualifiedDataId<RenderSurface>> { RenderSurfaceId },
});
dats.Register(RenderSurfaceId, new RenderSurface
{
Width = 1,
Height = 1,
Format = PixelFormat.PFID_A8R8G8B8,
SourceData = new byte[] { 1, 2, 3, 255 },
});
var cellStruct = new CellStruct
{
VertexArray = new VertexArray
{
Vertices = new Dictionary<ushort, SWVertex>
{
[0] = new() { Origin = new Vector3(0, 0, 0), Normal = Vector3.UnitZ },
[1] = new() { Origin = new Vector3(1, 0, 0), Normal = Vector3.UnitZ },
[2] = new() { Origin = new Vector3(1, 1, 0), Normal = Vector3.UnitZ },
[3] = new() { Origin = new Vector3(0, 1, 0), Normal = Vector3.UnitZ },
},
},
Polygons = new Dictionary<ushort, Polygon>
{
// Raw sides_type 2 == ST_BOTH. DatReaderWriter names this
// CullMode member "Clockwise" too, but on Polygon.SidesType
// it means ST_BOTH, NOT a GPU cull state (see
// CellStructSideCandidates' remarks) -- unrelated to the
// FIXED batch.CullMode this method now writes.
[0] = new() { SidesType = RetailCullMode.Clockwise, PosSurface = 0, NegSurface = 1, VertexIds = [0, 1, 2, 3] },
},
};
var extractor = new MeshExtractor(dats, NullLogger.Instance, sideStagedSink: null);
ObjectMeshData mesh = Assert.IsType<ObjectMeshData>(
extractor.PrepareCellStructMeshData(
id: 1, cellStruct, surfaceOverrides: [10, 20], Matrix4x4.Identity, CancellationToken.None));
List<TextureBatchData> batches = mesh.TextureBatches.Values.SelectMany(b => b).OrderBy(b => b.SourceSurfaceIndex).ToList();
Assert.Equal(2, batches.Count);
TextureBatchData positive = batches[0];
Assert.Equal(0, positive.SourceSurfaceIndex);
Assert.Equal([0, 1, 2, 0, 2, 3], positive.Indices);
TextureBatchData negative = batches[1];
Assert.Equal(1, negative.SourceSurfaceIndex);
// NOT reversed: forward fan order over the negative-lane vertices.
Assert.Equal([4, 5, 6, 4, 6, 7], negative.Indices);
Assert.All(mesh.Vertices.Take(4), vertex => Assert.Equal(Vector3.UnitZ, vertex.Normal));
Assert.All(mesh.Vertices.Skip(4), vertex => Assert.Equal(-Vector3.UnitZ, vertex.Normal));
}
[Fact]
public void PrepareCellStructMeshData_UntexturedSlot_ConstructedButNotEmitted()
{
// Contract §4: RenderDeviceD3D::DrawEnvCell (arg4=1) admits a
// subset iff (Surface.Type & (BASE1_IMAGE|BASE1_CLIPMAP)) != 0. A
// Base1Solid surface fails that test, so the slot is fully
// constructed (mask/ownership facts exist) but the mesh must carry
// ZERO texture batches for it.
var dats = new FakeMeshExtractorDats();
dats.Register(SolidSurfaceId, new Surface
{
@ -241,40 +398,279 @@ public sealed class MeshExtractorSolidFaceExtractionTests
Matrix4x4.Identity,
CancellationToken.None));
TextureBatchData batch = Assert.Single(Assert.Single(mesh.TextureBatches).Value);
Assert.Equal(RetailCullMode.Landblock, batch.CullMode);
Assert.Equal([0, 1, 2, 0, 2, 3], batch.Indices);
Assert.Equal(4, mesh.Vertices.Length);
Assert.All(mesh.Vertices, vertex => Assert.Equal(Vector3.UnitZ, vertex.Normal));
Assert.Empty(mesh.TextureBatches);
}
[Fact]
public void PrepareCellStructMeshData_NoneSide_ExpandsReversedFaceExactlyLikeRetailConstructMesh()
public void PrepareCellStructMeshData_TexturedNoPos_ReadsVertexUvSlotZero()
{
// Contract §3.5 as arbitrated on the PDB-paired binary (2026-09-02,
// ConstructMesh @0x0059E683-0x0059E693): when the polygon's UV-index
// array is absent (NoPos) the caller ZEROES THE INDEX (xor ebx,ebx)
// and copyVert @0x0059C080 reads the vertex's own UV slot 0 like any
// other index. This fixture carries a NON-zero UV at slot 0 to prove
// the read-through; the zero-coordinate cases are the two tests
// below (no vertex UV array; out-of-range index).
var dats = new FakeMeshExtractorDats();
dats.Register(SolidSurfaceId, new Surface
RegisterCellTexturedSurface(dats);
var cellStruct = new CellStruct
{
Type = SurfaceType.Base1Solid,
ColorValue = new ColorARGB { Alpha = 255, Red = 64, Green = 96, Blue = 128 },
});
VertexArray = new VertexArray
{
Vertices = new Dictionary<ushort, SWVertex>
{
[0] = new() { Origin = new Vector3(0, 0, 0), Normal = Vector3.UnitZ, UVs = { new Vec2Duv { U = 0.5f, V = 0.5f } } },
[1] = new() { Origin = new Vector3(1, 0, 0), Normal = Vector3.UnitZ, UVs = { new Vec2Duv { U = 0.5f, V = 0.5f } } },
[2] = new() { Origin = new Vector3(1, 1, 0), Normal = Vector3.UnitZ, UVs = { new Vec2Duv { U = 0.5f, V = 0.5f } } },
[3] = new() { Origin = new Vector3(0, 1, 0), Normal = Vector3.UnitZ, UVs = { new Vec2Duv { U = 0.5f, V = 0.5f } } },
},
},
Polygons = new Dictionary<ushort, Polygon>
{
[0] = new() { SidesType = RetailCullMode.Landblock, Stippling = StipplingType.NoPos, PosSurface = 0, NegSurface = -1, VertexIds = [0, 1, 2, 3] },
},
};
var extractor = new MeshExtractor(dats, NullLogger.Instance, sideStagedSink: null);
ObjectMeshData mesh = Assert.IsType<ObjectMeshData>(
extractor.PrepareCellStructMeshData(
id: 1,
BuildQuadCellStruct(RetailCullMode.None),
surfaceOverrides: [1],
Matrix4x4.Identity,
CancellationToken.None));
id: 1, cellStruct, surfaceOverrides: [2], Matrix4x4.Identity, CancellationToken.None));
TextureBatchData batch = Assert.Single(Assert.Single(mesh.TextureBatches).Value);
Assert.Equal(RetailCullMode.None, batch.CullMode);
Assert.Equal(
[0, 1, 2, 0, 2, 3, 6, 5, 4, 7, 6, 4],
batch.Indices);
Assert.Equal(8, mesh.Vertices.Length);
Assert.All(mesh.Vertices.Take(4), vertex => Assert.Equal(Vector3.UnitZ, vertex.Normal));
Assert.All(mesh.Vertices.Skip(4), vertex => Assert.Equal(-Vector3.UnitZ, vertex.Normal));
Assert.False(batch.Key.IsSolid);
Assert.Equal(4, mesh.Vertices.Length);
Assert.All(mesh.Vertices, vertex => Assert.Equal(new Vector2(0.5f, 0.5f), vertex.UV));
}
[Fact]
public void PrepareCellStructMeshData_TexturedNoPos_VertexWithoutUvArray_EmitsZeroUVs()
{
// copyVert @0x0059C080 zeroes the coordinate when the vertex has no
// UV array (edi[4] == 0) — the only absent-array case that yields
// (0,0). Same polygon shape as the read-through test, no vertex UVs.
var dats = new FakeMeshExtractorDats();
RegisterCellTexturedSurface(dats);
var cellStruct = BuildQuadCellStruct(RetailCullMode.Landblock);
cellStruct.Polygons[0].Stippling = StipplingType.NoPos;
var extractor = new MeshExtractor(dats, NullLogger.Instance, sideStagedSink: null);
ObjectMeshData mesh = Assert.IsType<ObjectMeshData>(
extractor.PrepareCellStructMeshData(
id: 1, cellStruct, surfaceOverrides: [2], Matrix4x4.Identity, CancellationToken.None));
Assert.Equal(4, mesh.Vertices.Length);
Assert.All(mesh.Vertices, vertex => Assert.Equal(Vector2.Zero, vertex.UV));
}
[Fact]
public void PrepareCellStructMeshData_OutOfRangeUvIndex_EmitsZeroUVs_NotSlotZero()
{
// copyVert @0x0059C080: index >= the vertex's uv count -> zero
// coordinate. Retail never clamps to slot 0. Each vertex has one
// UV (slot 0, non-zero) and the polygon asks for slot 5.
var dats = new FakeMeshExtractorDats();
RegisterCellTexturedSurface(dats);
var cellStruct = new CellStruct
{
VertexArray = new VertexArray
{
Vertices = new Dictionary<ushort, SWVertex>
{
[0] = new() { Origin = new Vector3(0, 0, 0), Normal = Vector3.UnitZ, UVs = { new Vec2Duv { U = 0.5f, V = 0.5f } } },
[1] = new() { Origin = new Vector3(1, 0, 0), Normal = Vector3.UnitZ, UVs = { new Vec2Duv { U = 0.5f, V = 0.5f } } },
[2] = new() { Origin = new Vector3(1, 1, 0), Normal = Vector3.UnitZ, UVs = { new Vec2Duv { U = 0.5f, V = 0.5f } } },
[3] = new() { Origin = new Vector3(0, 1, 0), Normal = Vector3.UnitZ, UVs = { new Vec2Duv { U = 0.5f, V = 0.5f } } },
},
},
Polygons = new Dictionary<ushort, Polygon>
{
[0] = new() { SidesType = RetailCullMode.Landblock, Stippling = default, PosSurface = 0, NegSurface = -1, VertexIds = [0, 1, 2, 3], PosUVIndices = [5, 5, 5, 5] },
},
};
var extractor = new MeshExtractor(dats, NullLogger.Instance, sideStagedSink: null);
ObjectMeshData mesh = Assert.IsType<ObjectMeshData>(
extractor.PrepareCellStructMeshData(
id: 1, cellStruct, surfaceOverrides: [2], Matrix4x4.Identity, CancellationToken.None));
Assert.Equal(4, mesh.Vertices.Length);
Assert.All(mesh.Vertices, vertex => Assert.Equal(Vector2.Zero, vertex.UV));
}
[Fact]
public void PrepareCellStructMeshData_TwoSlotsSameSurfaceDid_RemainTwoDistinctSubsets()
{
// Contract §3.6 point 2: the subset owner is the SOURCE
// SURFACE-ARRAY INDEX, not the resolved Surface DID -- two
// different slots that happen to resolve to the SAME override
// value (and therefore the same Surface DID) must stay two
// separate subsets.
var dats = new FakeMeshExtractorDats();
RegisterCellTexturedSurface(dats);
var cellStruct = new CellStruct
{
VertexArray = new VertexArray
{
Vertices = new Dictionary<ushort, SWVertex>
{
[0] = new() { Origin = new Vector3(0, 0, 0), Normal = Vector3.UnitZ },
[1] = new() { Origin = new Vector3(1, 0, 0), Normal = Vector3.UnitZ },
[2] = new() { Origin = new Vector3(1, 1, 0), Normal = Vector3.UnitZ },
[3] = new() { Origin = new Vector3(0, 1, 0), Normal = Vector3.UnitZ },
[4] = new() { Origin = new Vector3(2, 0, 0), Normal = Vector3.UnitZ },
[5] = new() { Origin = new Vector3(3, 0, 0), Normal = Vector3.UnitZ },
[6] = new() { Origin = new Vector3(3, 1, 0), Normal = Vector3.UnitZ },
},
},
Polygons = new Dictionary<ushort, Polygon>
{
[0] = new() { SidesType = RetailCullMode.Landblock, PosSurface = 0, NegSurface = -1, VertexIds = [0, 1, 2, 3] },
[1] = new() { SidesType = RetailCullMode.Landblock, PosSurface = 1, NegSurface = -1, VertexIds = [4, 5, 6] },
},
};
var extractor = new MeshExtractor(dats, NullLogger.Instance, sideStagedSink: null);
// Both slots resolve to override value 2 -> the SAME Surface DID.
ObjectMeshData mesh = Assert.IsType<ObjectMeshData>(
extractor.PrepareCellStructMeshData(
id: 1, cellStruct, surfaceOverrides: [2, 2], Matrix4x4.Identity, CancellationToken.None));
List<TextureBatchData> batches = mesh.TextureBatches.Values.SelectMany(b => b).OrderBy(b => b.SourceSurfaceIndex).ToList();
Assert.Equal(2, batches.Count);
Assert.Equal(0, batches[0].SourceSurfaceIndex);
Assert.Equal(1, batches[1].SourceSurfaceIndex);
Assert.Equal(batches[0].Key.SurfaceId, batches[1].Key.SurfaceId);
Assert.NotSame(batches[0], batches[1]);
}
[Fact]
public void PrepareCellStructMeshData_DifferentStipplingOnOneSlot_StaysOneSubsetWithAggregatedMask()
{
// Contract §3.6 point 3 + §3.2: two polygons on the SAME slot with
// DIFFERENT stippling values must remain ONE subset, and the
// slot's final mask is the OR of every polygon's positive-surface
// stippling bit.
var dats = new FakeMeshExtractorDats();
RegisterCellTexturedSurface(dats);
var cellStruct = new CellStruct
{
VertexArray = new VertexArray
{
Vertices = new Dictionary<ushort, SWVertex>
{
[0] = new() { Origin = new Vector3(0, 0, 0), Normal = Vector3.UnitZ },
[1] = new() { Origin = new Vector3(1, 0, 0), Normal = Vector3.UnitZ },
[2] = new() { Origin = new Vector3(1, 1, 0), Normal = Vector3.UnitZ },
[3] = new() { Origin = new Vector3(0, 1, 0), Normal = Vector3.UnitZ },
},
},
Polygons = new Dictionary<ushort, Polygon>
{
[0] = new() { SidesType = RetailCullMode.Landblock, Stippling = StipplingType.None, PosSurface = 0, NegSurface = -1, VertexIds = [0, 1, 2] },
[1] = new() { SidesType = RetailCullMode.Landblock, Stippling = StipplingType.Positive, PosSurface = 0, NegSurface = -1, VertexIds = [0, 2, 3] },
},
};
var extractor = new MeshExtractor(dats, NullLogger.Instance, sideStagedSink: null);
ObjectMeshData mesh = Assert.IsType<ObjectMeshData>(
extractor.PrepareCellStructMeshData(
id: 1, cellStruct, surfaceOverrides: [2], Matrix4x4.Identity, CancellationToken.None));
TextureBatchData batch = Assert.Single(Assert.Single(mesh.TextureBatches).Value);
// Base1Image alone carries no alpha/clip/translucent bits -> initial
// mask 0; the second polygon's nonzero (signed-positive) stippling
// ORs bit 0 in. The first polygon's None (0) stippling does not.
Assert.Equal((byte)1, batch.RetailSurfaceMask);
Assert.Equal(6, batch.Indices.Count); // both triangles landed in the one subset
}
[Fact]
public void PrepareCellStructMeshData_DifferentSidesValuesOnOneSlot_StaysOneSubset()
{
// Contract §3.6 point 3: two polygons on the SAME slot with
// DIFFERENT sides_type values (ST_SINGLE and ST_DOUBLE here) must
// stay one subset, in source polygon order.
var dats = new FakeMeshExtractorDats();
RegisterCellTexturedSurface(dats);
var cellStruct = new CellStruct
{
VertexArray = new VertexArray
{
Vertices = new Dictionary<ushort, SWVertex>
{
[0] = new() { Origin = new Vector3(0, 0, 0), Normal = Vector3.UnitZ },
[1] = new() { Origin = new Vector3(1, 0, 0), Normal = Vector3.UnitZ },
[2] = new() { Origin = new Vector3(1, 1, 0), Normal = Vector3.UnitZ },
},
},
Polygons = new Dictionary<ushort, Polygon>
{
[0] = new() { SidesType = RetailCullMode.Landblock, PosSurface = 0, NegSurface = -1, VertexIds = [0, 1, 2] },
[1] = new() { SidesType = RetailCullMode.None, PosSurface = 0, NegSurface = -1, VertexIds = [0, 1, 2] },
},
};
var extractor = new MeshExtractor(dats, NullLogger.Instance, sideStagedSink: null);
ObjectMeshData mesh = Assert.IsType<ObjectMeshData>(
extractor.PrepareCellStructMeshData(
id: 1, cellStruct, surfaceOverrides: [2], Matrix4x4.Identity, CancellationToken.None));
TextureBatchData batch = Assert.Single(Assert.Single(mesh.TextureBatches).Value);
Assert.Equal(0, batch.SourceSurfaceIndex);
// poly0 (ST_SINGLE): one forward triangle. poly1 (ST_DOUBLE): one
// forward + one reversed copy. 3 triangles total, in polygon order.
Assert.Equal(9, batch.Indices.Count);
}
[Fact]
public void PrepareCellStructMeshData_SubsetOrder_IsAscendingSurfaceIndexAcrossTextureFormats()
{
// Contract §3.6 point 1/5: subset order is ascending SOURCE SURFACE
// INDEX, independent of the (Width,Height,Format) storage
// grouping. Two slots resolve to DIFFERENT texture dimensions (so
// they land in different TextureBatches dictionary buckets), and
// the higher slot number is authored/processed FIRST.
var dats = new FakeMeshExtractorDats();
dats.Register(0x08000005u, new Surface { Type = SurfaceType.Base1Image, OrigTextureId = 0x05000005u });
dats.Register(0x05000005u, new SurfaceTexture { Textures = new List<QualifiedDataId<RenderSurface>> { 0x06000005u } });
dats.Register(0x06000005u, new RenderSurface { Width = 8, Height = 8, Format = PixelFormat.PFID_A8R8G8B8, SourceData = new byte[8 * 8 * 4] });
dats.Register(0x08000002u, new Surface { Type = SurfaceType.Base1Image, OrigTextureId = SurfaceTextureId });
dats.Register(SurfaceTextureId, new SurfaceTexture { Textures = new List<QualifiedDataId<RenderSurface>> { RenderSurfaceId } });
dats.Register(RenderSurfaceId, new RenderSurface { Width = 1, Height = 1, Format = PixelFormat.PFID_A8R8G8B8, SourceData = new byte[] { 1, 2, 3, 255 } });
var cellStruct = new CellStruct
{
VertexArray = new VertexArray
{
Vertices = new Dictionary<ushort, SWVertex>
{
[0] = new() { Origin = new Vector3(0, 0, 0), Normal = Vector3.UnitZ },
[1] = new() { Origin = new Vector3(1, 0, 0), Normal = Vector3.UnitZ },
[2] = new() { Origin = new Vector3(1, 1, 0), Normal = Vector3.UnitZ },
},
},
Polygons = new Dictionary<ushort, Polygon>
{
// Higher slot (5, the wide texture) authored/iterated FIRST.
[0] = new() { SidesType = RetailCullMode.Landblock, PosSurface = 5, NegSurface = -1, VertexIds = [0, 1, 2] },
[1] = new() { SidesType = RetailCullMode.Landblock, PosSurface = 2, NegSurface = -1, VertexIds = [0, 1, 2] },
},
};
var extractor = new MeshExtractor(dats, NullLogger.Instance, sideStagedSink: null);
ObjectMeshData mesh = Assert.IsType<ObjectMeshData>(
extractor.PrepareCellStructMeshData(
id: 1, cellStruct, surfaceOverrides: [0, 0, 2, 0, 0, 5], Matrix4x4.Identity, CancellationToken.None));
// At least two distinct (Width,Height,Format) buckets prove this
// isn't accidentally passing because everything landed in one list.
Assert.True(mesh.TextureBatches.Count >= 2);
List<int> order = CellSurfaceSubsets.InAscendingSurfaceOrder(mesh)
.Select(b => b.SourceSurfaceIndex)
.ToList();
Assert.Equal([2, 5], order);
}
private static void RegisterTexturedQuad(

View file

@ -100,6 +100,10 @@ public static class ObjectMeshDataEquality {
Assert.True(expected.IsTransparent == actual.IsTransparent, $"{path}.IsTransparent: expected {expected.IsTransparent}, got {actual.IsTransparent}");
Assert.True(expected.IsAdditive == actual.IsAdditive, $"{path}.IsAdditive: expected {expected.IsAdditive}, got {actual.IsAdditive}");
Assert.True(expected.HasWrappingUVs == actual.HasWrappingUVs, $"{path}.HasWrappingUVs: expected {expected.HasWrappingUVs}, got {actual.HasWrappingUVs}");
Assert.True(expected.SourceSurfaceIndex == actual.SourceSurfaceIndex, $"{path}.SourceSurfaceIndex: expected {expected.SourceSurfaceIndex}, got {actual.SourceSurfaceIndex}");
Assert.True(expected.RetailSurfaceMask == actual.RetailSurfaceMask, $"{path}.RetailSurfaceMask: expected {expected.RetailSurfaceMask}, got {actual.RetailSurfaceMask}");
Assert.True(expected.RawSurfaceType == actual.RawSurfaceType, $"{path}.RawSurfaceType: expected {expected.RawSurfaceType}, got {actual.RawSurfaceType}");
Assert.True(expected.IsCellShell == actual.IsCellShell, $"{path}.IsCellShell: expected {expected.IsCellShell}, got {actual.IsCellShell}");
}
private static void AssertTextureBatchesEqual(

View file

@ -176,6 +176,54 @@ public class ObjectMeshDataSerializerTests {
return data;
}
/// <summary>
/// OH2/S1 chunk-2: a cell-shell batch with non-default values for all
/// four new fields (SourceSurfaceIndex, RetailSurfaceMask,
/// RawSurfaceType, IsCellShell), proving the round-trip preserves them
/// and not just their zero/-1 neutral defaults.
/// </summary>
private static ObjectMeshData WithCellShellSubset() {
var data = EmptyObject();
data.ObjectId = 0x0700_0001u;
data.TextureBatches[(64, 64, TextureFormat.RGBA8)] = new List<TextureBatchData> {
new() {
Key = new TextureKey { SurfaceId = 0x08000BFFu, PaletteId = 0, Stippling = StipplingType.None, IsSolid = false },
TextureData = new byte[] { 1, 2, 3, 4 },
Indices = new List<ushort> { 0, 1, 2 },
CullMode = CullMode.Clockwise,
Translucency = TranslucencyKind.Opaque,
IsTransparent = false,
IsAdditive = false,
HasWrappingUVs = false,
SourceSurfaceIndex = 7,
RetailSurfaceMask = 0b0000_1101,
RawSurfaceType = 0x11u,
IsCellShell = true,
},
};
return data;
}
/// <summary>
/// An ordinary (non-cell) GfxObj-shaped batch — the four new fields are
/// left entirely unset, exercising their class-level neutral defaults
/// (SourceSurfaceIndex = -1, RetailSurfaceMask = 0, RawSurfaceType = 0,
/// IsCellShell = false) through the same round-trip path.
/// </summary>
private static ObjectMeshData WithGfxObjNeutralDefaults() {
var data = EmptyObject();
data.ObjectId = 0x0700_0002u;
data.TextureBatches[(32, 32, TextureFormat.RGBA8)] = new List<TextureBatchData> {
new() {
Key = new TextureKey { SurfaceId = 0x08000001u, PaletteId = 0, Stippling = StipplingType.Positive, IsSolid = true },
TextureData = new byte[] { 9, 9, 9, 9 },
Indices = new List<ushort> { 0, 1, 2 },
CullMode = CullMode.None,
},
};
return data;
}
public static IEnumerable<object[]> AllFixtures() {
yield return new object[] { EmptyObject() };
yield return new object[] { VerticesAndIndicesOnly() };
@ -186,6 +234,21 @@ public class ObjectMeshDataSerializerTests {
yield return new object[] { WithNullableFieldsAbsent() };
yield return new object[] { WithEdgeLines() };
yield return new object[] { WithNestedEnvCellGeometry() };
yield return new object[] { WithCellShellSubset() };
yield return new object[] { WithGfxObjNeutralDefaults() };
}
[Fact]
public void WithGfxObjNeutralDefaults_Fixture_HasClassLevelNeutralDefaults() {
// Sanity check on the fixture itself (not the serializer): proves
// the "neutral default" claim is a property of TextureBatchData's
// own field initializers, not something MeshExtractor's GfxObj path
// has to opt into.
TextureBatchData batch = Assert.Single(Assert.Single(WithGfxObjNeutralDefaults().TextureBatches).Value);
Assert.Equal(-1, batch.SourceSurfaceIndex);
Assert.Equal((byte)0, batch.RetailSurfaceMask);
Assert.Equal(0u, batch.RawSurfaceType);
Assert.False(batch.IsCellShell);
}
// ---- round-trip tests ----------------------------------------------------
@ -286,6 +349,43 @@ public class ObjectMeshDataSerializerTests {
Assert.True(iB < iC, $"markerB (width=1,height=100) must precede markerC (width=100,height=1): iB={iB} iC={iC}");
}
// ---- truncated/corrupt new-field rejection (OH2/S1 chunk-2, contract §10.5) ----
[Theory]
[InlineData(1)]
[InlineData(5)]
[InlineData(10)]
[InlineData(20)]
[InlineData(46)]
[InlineData(60)]
public void Read_TruncatedTail_ThrowsDeterministically(int bytesRemoved) {
// WithCellShellSubset's one small batch is the object's only
// populated collection, so the LAST ~55 bytes of its serialized
// form span exactly: the four new OH2 fields (SourceSurfaceIndex
// int32, RetailSurfaceMask byte, RawSurfaceType uint32, IsCellShell
// bool -- 10 bytes) immediately followed by the fixed
// BoundingBox+SortCenter+DIDDegrade+SelectionSphere-flag+EdgeLines-
// count tail every ObjectMeshData writes (45 bytes for this
// fixture). Sweeping removal depths across that whole span proves
// every cut inside or around the new fields fails closed --
// EndOfStreamException from the underlying BinaryReader, never a
// silently substituted default or a misread of a later field as one
// of the new ones.
var data = WithCellShellSubset();
using var full = new MemoryStream();
ObjectMeshDataSerializer.Write(data, full);
byte[] fullBytes = full.ToArray();
byte[] truncated = fullBytes[..^bytesRemoved];
Assert.Throws<EndOfStreamException>(() => ObjectMeshDataSerializer.Read(truncated));
}
[Fact]
public void Read_EmptyStream_ThrowsDeterministically() {
Assert.Throws<EndOfStreamException>(() => ObjectMeshDataSerializer.Read(Array.Empty<byte>()));
}
private static int IndexOfSequence(byte[] haystack, byte[] needle) {
for (int i = 0; i <= haystack.Length - needle.Length; i++) {
bool match = true;

View file

@ -9,6 +9,18 @@ public class PakFormatTests {
Assert.Equal(64, PakHeader.Size);
}
/// <summary>
/// OH2/S1 contract §8.3 point 5: the recipe 7 -&gt; 8 bump (exact
/// CellStruct surface-index subset construction) is a serialized
/// PAYLOAD/recipe change, not a container framing change — this pin
/// makes that decision explicit and test-visible rather than implicit.
/// </summary>
[Fact]
public void FormatVersion_StaysAtTwo_AcrossTheOH2RecipeBump() {
Assert.Equal(2u, PakFormat.CurrentFormatVersion);
Assert.Equal(8u, PakFormat.CurrentBakeToolVersion);
}
[Fact]
public void TocEntry_Size_Is24Bytes() {
Assert.Equal(24, PakTocEntry.Size);

View file

@ -135,6 +135,42 @@ public sealed class PreparedAssetSourceTests : IDisposable
}
}
/// <summary>
/// OH2/S1 contract §10.5: an OLDER-recipe (7) package must be rejected
/// by a CURRENT-recipe (8) consumer through the catalog-identity check
/// alone, BEFORE any TextureBatchData payload field is ever
/// deserialized -- so an older pak can never be silently misread as
/// carrying the new SourceSurfaceIndex/RetailSurfaceMask/RawSurfaceType/
/// IsCellShell fields.
/// </summary>
[Fact]
public void Constructor_RejectsOlderRecipePackageBeforePayloadDecode()
{
// PakWriter stamps BakeToolVersion to PakFormat.CurrentBakeToolVersion
// unconditionally (the header-template default-0 footgun guard), so
// an "older recipe" file has to be produced by patching the on-disk
// header dword directly -- the same technique
// PakRoundTripTests.Reader_RejectsWrongFormatVersion uses for the
// sibling FormatVersion field. BakeToolVersion is offset 36 per
// PakHeader's normative layout.
string path = WritePak(
(PakAssetType.EnvCellMesh, 1u, Mesh(1u)));
using (var fs = new FileStream(path, FileMode.Open, FileAccess.ReadWrite))
{
fs.Position = 36;
Span<byte> buf = stackalloc byte[4];
System.Buffers.Binary.BinaryPrimitives.WriteUInt32LittleEndian(
buf, PakFormat.CurrentBakeToolVersion - 1);
fs.Write(buf);
}
InvalidDataException error = Assert.Throws<InvalidDataException>(
() => new PakPreparedAssetSource(path, Identity));
Assert.Contains("does not match the installed DAT set", error.Message);
Assert.Contains("Re-bake", error.Message);
}
[Fact]
public void Read_PreCanceledTokenPropagatesWithoutStartingRead()
{