diff --git a/docs/tools-changelog.md b/docs/tools-changelog.md
index 7cd8eaf..2ec173c 100644
--- a/docs/tools-changelog.md
+++ b/docs/tools-changelog.md
@@ -4,7 +4,7 @@
- `IOScene.Formats` reads embedded GLB and OBJ geometry and writes GLB from an IOScene document.
- `IOCoord` provides measurements, surface clearance, hard clashes with an estimated depth, box overlap checks,
- duplicate geometry detection, grid queries, revision comparison and BCF 2.1 export.
+ duplicate geometry detection, solid containment, grid queries, revision comparison and BCF 2.1 export.
- Both packages use the public IOScene 0.1 API and can be installed independently.
See [Optional IOScene tools](tools.md) for supported inputs and scope.
diff --git a/docs/tools.md b/docs/tools.md
index 0b37611..b9ed6e1 100644
--- a/docs/tools.md
+++ b/docs/tools.md
@@ -55,11 +55,17 @@ gap. Surface contacts report zero using the same tolerance.
of the two contacting mesh bounds, as in NwcIO. It reports negative depth in metres, skips positive depths
below the requested minimum, and keeps zero-depth contacts. `SceneClash.FindBoundingBoxOverlaps` uses the same
overlap metric and reports the centre of overlapping instance boxes without checking their surfaces. A box
-overlap can include empty space. Exact depth and closed-solid containment are outside these queries.
+overlap can include empty space. These two queries approximate depth using bounds.
`SceneClash.FindDuplicates` compares placed vertices and effective index order within a tolerance in metres.
It reports a pair when any two of its instances match, independent of material and display name.
+`SceneClash.FindSolidContainments` finds a closed mesh that is fully enclosed by another closed mesh
+without surface contact. It reports the contained element first. Meshes must have consistently oriented,
+paired edges and no self-intersections. Reversed cavity shells represent empty space. The winding-number
+test uses oriented triangle solid angles. [Triangle solid angle](https://doi.org/10.1109/TBME.1983.325207),
+[generalized winding numbers](https://users.cs.utah.edu/~ladislav/jacobson13robust/jacobson13robust.pdf)
+
`SceneDiff.Compare` matches elements by model key and source id. It compares names and types, ordered property sets,
and ordered vertices and indices in scene coordinates. It reports elements without an identity separately and refuses
duplicate persistent ids. The comparison uses exact geometry values.
diff --git a/src/IOCoord/SceneClash.Containment.cs b/src/IOCoord/SceneClash.Containment.cs
new file mode 100644
index 0000000..26bb42e
--- /dev/null
+++ b/src/IOCoord/SceneClash.Containment.cs
@@ -0,0 +1,152 @@
+using IOScene;
+
+namespace IOCoord;
+
+public static partial class SceneClash
+{
+ /// Finds placed solids fully enclosed by another placed solid without surface contact.
+ /// The scene whose placed triangle meshes are tested.
+ /// Ids of elements that may be contained.
+ /// Ids of elements that may contain them.
+ /// Cancellation token for the query.
+ /// One result per element pair with at least one contained instance. The contained id comes first.
+ /// Triangle meshes must describe closed, consistently oriented boundaries without self-intersections.
+ /// Opposite orientation distinguishes cavities from exterior shells. Lines and points are ignored.
+ /// A selected triangle mesh has a degenerate face or an unpaired or inconsistently oriented edge.
+ public static SceneClashTest FindSolidContainments(SceneDocument scene, IEnumerable inner, IEnumerable outer,
+ CancellationToken cancellationToken = default) =>
+ Find(scene, inner, outer, Query.Containment, 0, cancellationToken);
+
+ private static bool StrictlyWithin(BoundingBox3d inner, BoundingBox3d outer) =>
+ inner.Min.X > outer.Min.X && inner.Min.Y > outer.Min.Y && inner.Min.Z > outer.Min.Z
+ && inner.Max.X < outer.Max.X && inner.Max.Y < outer.Max.Y && inner.Max.Z < outer.Max.Z;
+
+ private static ClosedSolid BuildClosedSolid(SceneGeometry geometry, Transform3d transform, long elementId,
+ CancellationToken cancellationToken)
+ {
+ var vertices = new Vector3d[geometry.Vertices.Count];
+ var vertexIds = new int[vertices.Length];
+ var welded = new Dictionary();
+ for (int i = 0; i < vertices.Length; i++)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ vertices[i] = PlaceVertex(geometry.Vertices[i], transform);
+ welded.TryAdd(vertices[i], i);
+ vertexIds[i] = welded[vertices[i]];
+ }
+
+ bool indexed = geometry.Indices.Count != 0;
+ int count = (indexed ? geometry.Indices.Count : vertices.Length) / 3;
+ if (count == 0) throw InvalidMesh();
+ var triangles = new Primitive[count];
+ var components = new int[count];
+ var edges = new Dictionary<(int First, int Second), (int Face, bool Forward, bool Paired)>();
+ for (int i = 0; i < count; i++)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ int offset = i * 3;
+ int ai = indexed ? geometry.Indices[offset] : offset;
+ int bi = indexed ? geometry.Indices[offset + 1] : offset + 1;
+ int ci = indexed ? geometry.Indices[offset + 2] : offset + 2;
+ var a = vertices[ai];
+ var b = vertices[bi];
+ var c = vertices[ci];
+ var normal = Vector3d.Cross(b - a, c - a);
+ double length = SceneMeasure.Length(normal);
+ if (length == 0) throw InvalidMesh();
+ triangles[i] = new(elementId, BoundingBox3d.Empty.Encapsulate(a).Encapsulate(b).Encapsulate(c),
+ a, b, c, normal / length);
+ components[i] = i;
+ AddEdge(vertexIds[ai], vertexIds[bi], i);
+ AddEdge(vertexIds[bi], vertexIds[ci], i);
+ AddEdge(vertexIds[ci], vertexIds[ai], i);
+ }
+ if (edges.Values.Any(edge => !edge.Paired)) throw InvalidMesh();
+
+ var boundaryPoints = new List();
+ for (int i = 0; i < count; i++)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ if (components[i] == i) boundaryPoints.Add(triangles[i].A);
+ }
+ return new(triangles, Build(triangles, 0, triangles.Length, cancellationToken), boundaryPoints);
+
+ void AddEdge(int from, int to, int face)
+ {
+ bool forward = from < to;
+ var key = forward ? (from, to) : (to, from);
+ if (!edges.TryGetValue(key, out var other))
+ {
+ edges.Add(key, (face, forward, false));
+ return;
+ }
+ if (other.Paired || other.Forward == forward) throw InvalidMesh();
+ edges[key] = (other.Face, other.Forward, true);
+ components[Root(face)] = Root(other.Face);
+ }
+
+ int Root(int face)
+ {
+ while (components[face] != face)
+ {
+ components[face] = components[components[face]];
+ face = components[face];
+ }
+ return face;
+ }
+
+ InvalidDataException InvalidMesh() =>
+ new($"Geometry {geometry.Id} of element {elementId} must have nondegenerate faces and consistently oriented paired edges.");
+ }
+
+ private static bool IsContained(ClosedSolid inner, ClosedSolid outer, CancellationToken token)
+ {
+ if (SurfacesTouch(inner, outer, inner.Tree, outer.Tree, token)) return false;
+ // Disjoint boundaries lie on one side per connected component. Test both boundaries to account for cavities.
+ return inner.BoundaryPoints.All(point => IsInside(outer, point, token))
+ && !outer.BoundaryPoints.Any(point => IsInside(inner, point, token));
+ }
+
+ private static bool SurfacesTouch(ClosedSolid a, ClosedSolid b, Node one, Node two, CancellationToken token)
+ {
+ token.ThrowIfCancellationRequested();
+ if (!Overlaps(one.Bounds, two.Bounds, Tolerance)) return false;
+ if (one.First is not null && (two.First is null || one.Count >= two.Count))
+ return SurfacesTouch(a, b, one.First, two, token) || SurfacesTouch(a, b, one.Second!, two, token);
+ if (two.First is not null)
+ return SurfacesTouch(a, b, one, two.First, token) || SurfacesTouch(a, b, one, two.Second!, token);
+ for (int i = one.Start; i < one.Start + one.Count; i++)
+ for (int j = two.Start; j < two.Start + two.Count; j++)
+ {
+ var x = a.Triangles[i];
+ var y = b.Triangles[j];
+ if (Overlaps(x.Bounds, y.Bounds, Tolerance) && Contact(x, y) is not null) return true;
+ }
+ return false;
+ }
+
+ private static bool IsInside(ClosedSolid solid, Vector3d point, CancellationToken token)
+ {
+ if (!StrictlyWithin(new(point, point), solid.Tree.Bounds)) return false;
+ double angle = 0, compensation = 0;
+ foreach (var triangle in solid.Triangles)
+ {
+ token.ThrowIfCancellationRequested();
+ var a = Unit(triangle.A - point);
+ var b = Unit(triangle.B - point);
+ var c = Unit(triangle.C - point);
+ // Van Oosterom and Strackee's oriented solid angle, using unit vectors from the query point.
+ double numerator = Vector3d.Dot(a, Vector3d.Cross(b, c));
+ double denominator = 1 + Vector3d.Dot(a, b) + Vector3d.Dot(b, c) + Vector3d.Dot(c, a);
+ double term = 2 * Math.Atan2(numerator, denominator) - compensation;
+ double sum = angle + term;
+ compensation = (sum - angle) - term;
+ angle = sum;
+ }
+ return Math.Abs(angle) > 2 * Math.PI;
+
+ static Vector3d Unit(Vector3d vector) => vector / SceneMeasure.Length(vector);
+ }
+
+ private sealed record ClosedSolid(Primitive[] Triangles, Node Tree, List BoundaryPoints);
+}
diff --git a/src/IOCoord/SceneClash.cs b/src/IOCoord/SceneClash.cs
index 8de3106..5c58832 100644
--- a/src/IOCoord/SceneClash.cs
+++ b/src/IOCoord/SceneClash.cs
@@ -41,6 +41,7 @@ private static SceneClashTest Find(SceneDocument scene, IEnumerable first,
var leftPrimitives = new List();
var rightPrimitives = new List();
var meshBounds = query == Query.Hard ? new List() : null;
+ var solids = query == Query.Containment ? new List() : null;
for (int placement = 0; placement < scene.Instances.Count; placement++)
{
cancellationToken.ThrowIfCancellationRequested();
@@ -51,6 +52,14 @@ private static SceneClashTest Find(SceneDocument scene, IEnumerable first,
if (query is not (Query.Overlap or Query.Duplicate) && geometry.Topology != SceneTopology.Triangles) continue;
var transform = instance.Transform ?? Transform3d.Identity;
+ if (solids is not null)
+ {
+ var solid = BuildClosedSolid(geometry, transform, instance.ElementId, cancellationToken);
+ Add(new(instance.ElementId, solid.Tree.Bounds, MeshIndex: solids.Count));
+ solids.Add(solid);
+ continue;
+ }
+
int meshIndex = -1;
if (query is Query.Overlap or Query.Hard or Query.Duplicate)
{
@@ -58,7 +67,7 @@ private static SceneClashTest Find(SceneDocument scene, IEnumerable first,
foreach (var vertex in geometry.Vertices)
{
cancellationToken.ThrowIfCancellationRequested();
- bounds = bounds.Encapsulate(WorldVertex(vertex));
+ bounds = bounds.Encapsulate(PlaceVertex(vertex, transform));
}
if (bounds.IsEmpty) continue;
if (meshBounds is null)
@@ -76,9 +85,9 @@ private static SceneClashTest Find(SceneDocument scene, IEnumerable first,
for (int offset = 0; offset < count; offset += 3)
{
cancellationToken.ThrowIfCancellationRequested();
- var a = WorldVertex(geometry.Vertices[indexed ? indices[offset] : offset]);
- var b = WorldVertex(geometry.Vertices[indexed ? indices[offset + 1] : offset + 1]);
- var c = WorldVertex(geometry.Vertices[indexed ? indices[offset + 2] : offset + 2]);
+ var a = PlaceVertex(geometry.Vertices[indexed ? indices[offset] : offset], transform);
+ var b = PlaceVertex(geometry.Vertices[indexed ? indices[offset + 1] : offset + 1], transform);
+ var c = PlaceVertex(geometry.Vertices[indexed ? indices[offset + 2] : offset + 2], transform);
var faceNormal = Vector3d.Cross(b - a, c - a);
double length = faceNormal.Length;
if (!double.IsFinite(length)) throw new InvalidDataException("A triangle normal is outside the finite range.");
@@ -92,14 +101,6 @@ void Add(Primitive primitive)
if (inLeft) leftPrimitives.Add(primitive);
if (inRight) rightPrimitives.Add(primitive);
}
-
- Vector3d WorldVertex(Vector3d vertex)
- {
- var point = transform.Apply(vertex);
- if (!double.IsFinite(point.X) || !double.IsFinite(point.Y) || !double.IsFinite(point.Z))
- throw new InvalidDataException("The transformed coordinates are outside the finite range.");
- return point;
- }
}
var test = new SceneClashTest
@@ -110,6 +111,7 @@ Vector3d WorldVertex(Vector3d vertex)
Query.Hard => "Hard clashes",
Query.Overlap => "Bounding box overlaps",
Query.Duplicate => "Duplicate geometry",
+ Query.Containment => "Solid containments",
_ => "Surface intersections",
},
};
@@ -119,7 +121,7 @@ Vector3d WorldVertex(Vector3d vertex)
var bRoot = Build(bPrimitives, 0, bPrimitives.Length, cancellationToken);
double margin = query switch
{
- Query.Overlap => 0,
+ Query.Overlap or Query.Containment => 0,
Query.Clearance => Math.Max(Tolerance, limit),
Query.Duplicate => limit,
_ => Tolerance,
@@ -151,7 +153,9 @@ Vector3d WorldVertex(Vector3d vertex)
{
var two = bPrimitives[j];
if (one.ElementId == two.ElementId || !Overlaps(one.Bounds, two.Bounds, margin)) continue;
- var key = (Math.Min(one.ElementId, two.ElementId), Math.Max(one.ElementId, two.ElementId));
+ var key = query == Query.Containment
+ ? (one.ElementId, two.ElementId)
+ : (Math.Min(one.ElementId, two.ElementId), Math.Max(one.ElementId, two.ElementId));
bool found = contacts.TryGetValue(key, out var best);
switch (query)
{
@@ -176,6 +180,11 @@ Vector3d WorldVertex(Vector3d vertex)
contacts[key] = (Midpoint(centreA, centreB), 0);
}
break;
+ case Query.Containment:
+ if (!found && StrictlyWithin(one.Bounds, two.Bounds)
+ && IsContained(solids![one.MeshIndex], solids[two.MeshIndex], cancellationToken))
+ contacts[key] = (solids[one.MeshIndex].BoundaryPoints[0], null);
+ break;
case Query.Clearance:
if (best.Distance == 0) break;
if (best.Distance is double distance
@@ -219,6 +228,14 @@ Vector3d WorldVertex(Vector3d vertex)
return test;
}
+ private static Vector3d PlaceVertex(Vector3d vertex, Transform3d transform)
+ {
+ var point = transform.Apply(vertex);
+ if (!double.IsFinite(point.X) || !double.IsFinite(point.Y) || !double.IsFinite(point.Z))
+ throw new InvalidDataException("The transformed coordinates are outside the finite range.");
+ return point;
+ }
+
private static Node Build(Primitive[] primitives, int start, int count, CancellationToken token)
{
token.ThrowIfCancellationRequested();
@@ -288,7 +305,7 @@ bool HasLeftSide(Vector3d from, Vector3d to)
private static readonly Comparer ByY = Comparer.Create((a, b) => a.Bounds.Center.Y.CompareTo(b.Bounds.Center.Y));
private static readonly Comparer ByZ = Comparer.Create((a, b) => a.Bounds.Center.Z.CompareTo(b.Bounds.Center.Z));
- private enum Query { Intersection, Clearance, Hard, Overlap, Duplicate }
+ private enum Query { Intersection, Clearance, Hard, Overlap, Duplicate, Containment }
private readonly record struct Primitive(long ElementId, BoundingBox3d Bounds,
Vector3d A = default, Vector3d B = default, Vector3d C = default, Vector3d Normal = default, int MeshIndex = -1);
diff --git a/tests/IOScene.Tools.Tests/SceneClashTests.cs b/tests/IOScene.Tools.Tests/SceneClashTests.cs
index 9fe8d1d..24653d4 100644
--- a/tests/IOScene.Tools.Tests/SceneClashTests.cs
+++ b/tests/IOScene.Tools.Tests/SceneClashTests.cs
@@ -160,6 +160,52 @@ public void Duplicates_ComparePlacedVerticesAndEffectiveIndexOrder()
Assert.Empty(SceneClash.FindDuplicates(scene, [original.Id], selection, 0.124).Clashes);
}
+ [Fact]
+ public void Containment_IsDirectionalAndAcceptsMirroredClosedGeometry()
+ {
+ var scene = new SceneDocument();
+ var outer = AddBox(scene, "Outer", Vector3d.Zero, 4);
+ var inner = AddBox(scene, "Inner", Vector3d.Zero, 1);
+ scene.Instances[1].Transform = new(-Vector3d.UnitX, Vector3d.UnitY, Vector3d.UnitZ, new(2, 1, 1));
+
+ var match = Assert.Single(SceneClash.FindSolidContainments(scene, [inner.Id], [outer.Id]).Clashes);
+ Assert.Equal(inner.Id, match.Element1Id);
+ Assert.Equal(outer.Id, match.Element2Id);
+ Assert.Null(match.Distance);
+ Assert.Empty(SceneClash.FindSolidContainments(scene, [outer.Id], [inner.Id]).Clashes);
+ }
+
+ [Fact]
+ public void Containment_DistinguishesMaterialFromAnEnclosedCavity()
+ {
+ var scene = new SceneDocument();
+ var outer = AddBox(scene, "Outer", Vector3d.Zero, 4);
+ var geometry = scene.Geometries[0];
+ int offset = geometry.Vertices.Count;
+ var cavityVertices = geometry.Vertices.Select(point => new Vector3d(1, 1, 1) + point * 0.5).ToArray();
+ var cavityIndices = geometry.Indices.Chunk(3).SelectMany(face => new[] { face[0] + offset, face[2] + offset, face[1] + offset }).ToArray();
+ geometry.Vertices = [.. geometry.Vertices, .. cavityVertices];
+ geometry.Indices = [.. geometry.Indices, .. cavityIndices];
+ var insideCavity = AddBox(scene, "In the void", new(1.25, 1.25, 1.25), 0.5);
+ var surroundsCavity = AddBox(scene, "Around the void", new(0.5, 0.5, 0.5), 3);
+ var touchesCavity = AddBox(scene, "Touches the void", new(0.5, 1.5, 1.5), 0.5);
+ var insideMaterial = AddBox(scene, "In material", new(0.25, 0.25, 0.25), 0.5);
+
+ var match = Assert.Single(SceneClash.FindSolidContainments(scene,
+ [insideCavity.Id, surroundsCavity.Id, touchesCavity.Id, insideMaterial.Id], [outer.Id]).Clashes);
+ Assert.Equal(insideMaterial.Id, match.Element1Id);
+ }
+
+ [Fact]
+ public void Containment_RejectsAnOpenTriangleMesh()
+ {
+ var scene = new SceneDocument();
+ var outer = AddBox(scene, "Outer", Vector3d.Zero, 4);
+ var open = scene.AddMesh("Open", [new(1, 1, 1), new(2, 1, 1), new(1, 2, 1)], []);
+
+ Assert.Throws(() => SceneClash.FindSolidContainments(scene, [open.Id], [outer.Id]));
+ }
+
private static SceneElement AddBox(SceneDocument scene, string name, Vector3d position, double side)
{
var element = scene.AddMesh(name,