diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7273f32..0388366 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,8 @@ All notable changes to the `IfcIO` library are documented in this file.
## [Unreleased]
### Fixed
+- Boolean import preserves nested operands and evaluates chains of plane clips. It reports skipped bounded
+ half-spaces and Boolean operations not evaluated in the mesh, and rejects cyclic or excessive trees.
- Swept-solid import applies the profile, solid and object placements to inclined extrusions, revolutions and
both Boolean operands. IFC re-export preserves world placement and multiple swept body items when a single
parametric solid cannot represent the result. Mesh export distinguishes open surfaces from closed shells.
diff --git a/docs/public-api.md b/docs/public-api.md
index d1d1348..b449c10 100644
--- a/docs/public-api.md
+++ b/docs/public-api.md
@@ -53,6 +53,9 @@ Imported meshes use world coordinates. If a swept body cannot be represented by
solid, the reader keeps its placed mesh instead; IFC export writes that mesh rather than a partial or
misplaced solid. Boolean operands also use placed meshes where necessary. Applying arbitrary solid-to-solid
Boolean operations to the mesh is not supported; the mesher clips against half-spaces only.
+Nested plane clips trim the existing mesh faces in order; they do not add faces on the cut planes.
+`IfcModel.BooleanImportWarnings` lists skipped operands (including polygonal bounded half-spaces) and
+operations not evaluated in the mesh. These diagnostics refer to the source IFC, including after extraction.
IFC export rejects compound Boolean bodies and Boolean results with missing operands rather than
writing a mesh that drops the operations or an invalid STEP reference.
diff --git a/src/IfcIO.Cli/Program.cs b/src/IfcIO.Cli/Program.cs
index f43d204..c126b5b 100644
--- a/src/IfcIO.Cli/Program.cs
+++ b/src/IfcIO.Cli/Program.cs
@@ -181,7 +181,7 @@ private static int ExecuteInfo(string[] args)
var sw = Stopwatch.StartNew();
var model = IfcModel.Open(inputPath);
- WarnOnPartialIfc4x3Import(model);
+ WarnOnPartialImport(model);
sw.Stop();
int elementCount = 0;
@@ -322,7 +322,7 @@ private static int ExecuteExport(string[] args)
Console.Error.WriteLine("Error: IFC4X3 is supported for subset import only. Rewriting it as IFC is not supported.");
return 1;
}
- WarnOnPartialIfc4x3Import(model);
+ WarnOnPartialImport(model);
if (schemaOpt is { } requested) model.Schema = requested;
if (glbPath is not null)
@@ -658,8 +658,10 @@ private static string PhysicalPath(string path)
};
}
- private static void WarnOnPartialIfc4x3Import(IfcModel model)
+ private static void WarnOnPartialImport(IfcModel model)
{
+ foreach (string warning in model.BooleanImportWarnings)
+ Console.Error.WriteLine($"Warning: {warning}");
if (model.Schema != IfcSchema.Ifc4x3) return;
Console.Error.WriteLine($"Warning: {model.SourceSchemaIdentifier} is read as a subset. Uninterpreted content is omitted.");
if (model.UnsupportedPlacementCount > 0)
@@ -762,6 +764,7 @@ private static int ExecutePatch(string[] args)
{
LegacyIfcIoRevolvedAnglesInRadians = args.Contains("--legacy-ifcio-radian-sweeps", StringComparer.OrdinalIgnoreCase),
});
+ WarnOnPartialImport(model);
if (!string.IsNullOrEmpty(extractQuery))
{
@@ -1043,10 +1046,12 @@ private static int ExecuteClash(string[] args)
};
var modelA = IfcModel.Open(fileA);
+ WarnOnPartialImport(modelA);
Clash.IfcClashReport report;
if (fileB is not null)
{
var modelB = IfcModel.Open(fileB);
+ WarnOnPartialImport(modelB);
report = modelA.DetectClashes(modelB, options);
}
else
@@ -1159,6 +1164,8 @@ private static int ExecuteDiff(string[] args)
var baselineModel = IfcModel.Open(baselineFile);
var revisionModel = IfcModel.Open(revisionFile);
+ WarnOnPartialImport(baselineModel);
+ WarnOnPartialImport(revisionModel);
var report = baselineModel.Compare(revisionModel, options);
Console.ForegroundColor = report.TotalChangesCount > 0 ? ConsoleColor.Cyan : ConsoleColor.Green;
@@ -1206,7 +1213,7 @@ private static int ExecuteView(string[] args)
var sw = Stopwatch.StartNew();
var model = IfcModel.Open(inputPath);
- WarnOnPartialIfc4x3Import(model);
+ WarnOnPartialImport(model);
if (gridsPath is not null)
{
diff --git a/src/IfcIO/Geometry/CsgTypes.cs b/src/IfcIO/Geometry/CsgTypes.cs
index a38ad37..ffd33ca 100644
--- a/src/IfcIO/Geometry/CsgTypes.cs
+++ b/src/IfcIO/Geometry/CsgTypes.cs
@@ -82,17 +82,22 @@ public sealed class IfcBooleanResult
public IfcMesh? FirstMesh { get; set; }
public IfcExtrudedAreaSolid? FirstSolid { get; set; }
public IfcRevolvedAreaSolid? FirstRevolved { get; set; }
+ internal IfcBooleanResult? FirstBoolean { get; set; }
/// Second operand (clipping half-space, cutting solid, or joining solid).
public IfcHalfSpaceSolid? SecondHalfSpace { get; set; }
public IfcExtrudedAreaSolid? SecondSolid { get; set; }
+ /// Parametric form of a revolved second operand, when representable.
+ public IfcRevolvedAreaSolid? SecondRevolved { get; set; }
public IfcMesh? SecondMesh { get; set; }
+ internal IfcBooleanResult? SecondBoolean { get; set; }
///
/// True if this represents an IFCBOOLEANCLIPPINGRESULT (difference with a half-space solid).
///
public bool IsClippingResult => Operator == IfcBooleanOperator.Difference
- && SecondHalfSpace is not null && (FirstSolid is not null || FirstRevolved is not null);
+ && SecondHalfSpace is not null && (FirstSolid is not null || FirstRevolved is not null
+ || FirstBoolean?.IsClippingResult == true);
public IfcBooleanResult() { }
@@ -119,27 +124,31 @@ public IfcBooleanResult(
///
/// Computes the resulting triangulated 3D mesh by applying the CSG clipping operation.
///
- public IfcMesh ToMesh(string meshName = "BooleanResult")
+ public IfcMesh ToMesh(string meshName = "BooleanResult") => ToMesh(meshName, null);
+
+ internal IfcMesh ToMesh(string meshName, Action? chargeVertices)
{
- var baseMesh = FirstMesh ?? FirstSolid?.ToMesh() ?? FirstRevolved?.ToMesh();
+ var baseMesh = FirstMesh ?? FirstSolid?.ToMesh() ?? FirstRevolved?.ToMesh() ?? FirstBoolean?.ToMesh(meshName, chargeVertices);
if (baseMesh is null)
{
return IfcMesh.Create(0, meshName, Array.Empty(), Array.Empty());
}
- if (SecondHalfSpace is null)
+ if (SecondHalfSpace is null || Operator == IfcBooleanOperator.Union)
{
return baseMesh;
}
- return ClipMeshByHalfSpace(baseMesh, SecondHalfSpace, meshName);
+ return ClipMeshByHalfSpace(baseMesh, SecondHalfSpace, Operator == IfcBooleanOperator.Intersection, meshName, chargeVertices);
}
- private static IfcMesh ClipMeshByHalfSpace(IfcMesh input, IfcHalfSpaceSolid halfSpace, string meshName)
+ private static IfcMesh ClipMeshByHalfSpace(
+ IfcMesh input, IfcHalfSpaceSolid halfSpace, bool keepHalfSpace, string meshName, Action? chargeVertices)
{
var plane = halfSpace.BaseSurface;
var normal = plane.Normal.Normalized();
- if (!halfSpace.AgreementFlag) normal = -normal;
+ // IFC AgreementFlag=true places the material opposite the normal.
+ if (halfSpace.AgreementFlag == keepHalfSpace) normal = -normal;
// Plane equation: N . X + d = 0
double planeD = -IfcVector3.Dot(normal, plane.Location);
@@ -174,7 +183,7 @@ private static IfcMesh ClipMeshByHalfSpace(IfcMesh input, IfcHalfSpaceSolid half
if (insideCount == 3)
{
// Entire triangle inside
- AddTriangle(outVertices, outIndices, p0, p1, p2);
+ EmitTriangle(p0, p1, p2);
}
else if (insideCount == 0)
{
@@ -209,7 +218,7 @@ private static IfcMesh ClipMeshByHalfSpace(IfcMesh input, IfcHalfSpaceSolid half
var i1 = IntersectSegment(vIn, vOut1, dIn, dOut1);
var i2 = IntersectSegment(vIn, vOut2, dIn, dOut2);
- AddTriangle(outVertices, outIndices, vIn, i1, i2);
+ EmitTriangle(vIn, i1, i2);
}
else // insideCount == 2
{
@@ -239,12 +248,18 @@ private static IfcMesh ClipMeshByHalfSpace(IfcMesh input, IfcHalfSpaceSolid half
var i1 = IntersectSegment(vIn1, vOut, dIn1, dOut);
var i2 = IntersectSegment(vIn2, vOut, dIn2, dOut);
- AddTriangle(outVertices, outIndices, vIn1, i1, i2);
- AddTriangle(outVertices, outIndices, vIn1, i2, vIn2);
+ EmitTriangle(vIn1, i1, i2);
+ EmitTriangle(vIn1, i2, vIn2);
}
}
return IfcMesh.Create(0, meshName, outVertices, outIndices);
+
+ void EmitTriangle(IfcVector3 a, IfcVector3 b, IfcVector3 c)
+ {
+ chargeVertices?.Invoke(3);
+ AddTriangle(outVertices, outIndices, a, b, c);
+ }
}
private static IfcVector3 IntersectSegment(in IfcVector3 a, in IfcVector3 b, double da, double db)
diff --git a/src/IfcIO/IfcModel.cs b/src/IfcIO/IfcModel.cs
index e8bbf42..b6b4c75 100644
--- a/src/IfcIO/IfcModel.cs
+++ b/src/IfcIO/IfcModel.cs
@@ -24,6 +24,9 @@ public sealed partial class IfcModel
internal bool IsIfc4x3Subset => Schema == IfcSchema.Ifc4x3 || IsIfc4x3Identifier(SourceSchemaIdentifier);
/// Number of IFC4X3 product representations or ports omitted because their placement is unsupported.
public int UnsupportedPlacementCount { get; internal set; }
+
+ /// Boolean import warnings for skipped operands or operations not evaluated in the mesh.
+ public IReadOnlyList BooleanImportWarnings { get; internal set; } = [];
public IfcLengthUnit LengthUnit { get; set; } = IfcLengthUnit.Millimetre;
public IfcPlaneAngleUnit AngleUnit { get; set; } = IfcPlaneAngleUnit.Degree;
@@ -2506,6 +2509,7 @@ openElem is IfcOpeningElement opening &&
}
model._reservedElementIds.UnionWith(allElementsMap.Keys);
+ model.BooleanImportWarnings = geometry.BooleanWarnings.Order(StringComparer.Ordinal).ToArray();
return model;
}
@@ -2685,6 +2689,8 @@ private int WriteBooleanResult(StepWriter w, IfcBooleanResult csg, bool useTesse
firstId = WriteRevolvedAreaSolid(w, revolution);
else if ((csg.FirstMesh ?? csg.FirstRevolved?.ToMesh()) is { } firstMesh)
firstId = WriteBooleanMesh(w, firstMesh, useTessellation);
+ else if (csg.FirstBoolean is { } firstBoolean)
+ firstId = WriteBooleanResult(w, firstBoolean, useTessellation);
int secondId = 0;
if (csg.SecondHalfSpace is not null)
@@ -2703,9 +2709,17 @@ private int WriteBooleanResult(StepWriter w, IfcBooleanResult csg, bool useTesse
{
secondId = WriteExtrudedAreaSolid(w, csg.SecondSolid);
}
- else if (csg.SecondMesh is not null)
+ else if (csg.SecondRevolved is { } secondRevolved && CanWriteRevolution(secondRevolved))
+ {
+ secondId = WriteRevolvedAreaSolid(w, secondRevolved);
+ }
+ else if ((csg.SecondMesh ?? csg.SecondRevolved?.ToMesh()) is { } secondMesh)
+ {
+ secondId = WriteBooleanMesh(w, secondMesh, useTessellation);
+ }
+ else if (csg.SecondBoolean is { } secondBoolean)
{
- secondId = WriteBooleanMesh(w, csg.SecondMesh, useTessellation);
+ secondId = WriteBooleanResult(w, secondBoolean, useTessellation);
}
string op = csg.Operator switch
@@ -2745,8 +2759,10 @@ private static int WriteDirection(StepWriter w, IfcVector3 direction) =>
private static bool CanWriteRevolution(IfcRevolvedAreaSolid solid) =>
solid.Axis.Location.Z == solid.Position.Z && solid.Axis.Axis.Z == 0 && solid.Axis.Axis != IfcVector3.Zero;
- private static bool CanWriteClipping(IfcBooleanResult result) => result.IsClippingResult
- && (result.FirstSolid is not null || result.FirstRevolved is { } revolution && CanWriteRevolution(revolution));
+ private static bool CanWriteClipping(IfcBooleanResult result) =>
+ result.Operator == IfcBooleanOperator.Difference && result.SecondHalfSpace is not null
+ && (result.FirstSolid is not null || result.FirstRevolved is { } revolution && CanWriteRevolution(revolution)
+ || result.FirstBoolean is { } firstBoolean && CanWriteClipping(firstBoolean));
private int WriteRevolvedAreaSolid(StepWriter w, IfcRevolvedAreaSolid solid)
{
@@ -2785,14 +2801,21 @@ private sealed class GeometryReadContext(
public Dictionary Placements { get; } = [];
public Dictionary MappedRepresentations { get; } = [];
public HashSet MapsInProgress { get; } = [];
+ public HashSet BooleanWarnings { get; } = [];
///
- /// Cap on vertices materialised while reading, linear in the file size: nested IfcMappedItems can
- /// otherwise multiply a small file into exponentially many vertices.
+ /// Cap on vertices materialised while reading nested mapped items and Boolean bodies.
///
public long VertexBudget { get; } = MinVertexBudget + (VerticesPerEntity * (long)step.EntityCount);
private long _materialisedVertices;
+ private long _remainingBooleanNodes = 256 + 8L * step.EntityCount;
+
+ public void ChargeBooleanNode(int id)
+ {
+ if (_remainingBooleanNodes-- <= 0)
+ throw new InvalidDataException($"Boolean operands at #{id} exceed the model-wide expansion limit.");
+ }
public void ChargeVertices(int count)
{
@@ -2800,7 +2823,7 @@ public void ChargeVertices(int count)
if (_materialisedVertices > VertexBudget)
{
throw new InvalidDataException(
- $"IFC geometry expands to more than {VertexBudget} vertices (limit for {Step.EntityCount} entities); check for nested IfcMappedItem amplification.");
+ $"IFC geometry expands to more than {VertexBudget} vertices (limit for {Step.EntityCount} entities); check for nested mapped items or Boolean results.");
}
}
}
@@ -2898,7 +2921,8 @@ public void ChargeVertices(int count)
var mesh = ParseRepresentationItem(ctx, itemEnt, meshName, ref itemMaterial, out var itemParametric);
if (mesh is null) continue;
material ??= itemMaterial;
- ctx.ChargeVertices(mesh.Vertices.Count);
+ // The Boolean reader already charges leaf meshes and triangles emitted by each clip.
+ if (itemParametric?.Boolean is null) ctx.ChargeVertices(mesh.Vertices.Count);
hasBoolean |= itemParametric?.Boolean is not null;
parametric = parts.Count == 0 ? itemParametric : null;
parts.Add(mesh);
@@ -2943,15 +2967,13 @@ public void ChargeVertices(int count)
}
// E. IFCBOOLEANRESULT / IFCBOOLEANCLIPPINGRESULT
- if (itemEnt.Type.Equals("IFCBOOLEANRESULT", StringComparison.OrdinalIgnoreCase) ||
- itemEnt.Type.Equals("IFCBOOLEANCLIPPINGRESULT", StringComparison.OrdinalIgnoreCase))
+ if (IsBooleanEntity(itemEnt))
{
- var boolRes = ParseBooleanResult(step, itemEnt, ctx.RadiansPerAngleUnit);
- if (boolRes is null) return null;
+ var boolRes = ParseBooleanResult(ctx, itemEnt, []);
if (itemEnt.GetRef(1) is int firstOperand)
material ??= ctx.GeomToMaterialMap.GetValueOrDefault(firstOperand);
parametric = new ParametricBody(null, null, boolRes);
- return boolRes.ToMesh(meshName);
+ return boolRes.ToMesh(meshName, ctx.ChargeVertices);
}
// F. IFCMAPPEDITEM: MappingTarget * MappingOrigin * mapped representation.
@@ -3384,55 +3406,92 @@ bool TryVertexIndex(string text, out int index)
private static List ParseStepList(string? raw) =>
raw is { Length: >= 2 } && raw[0] == '(' && raw[^1] == ')' ? StepEntity.ParseArguments(raw[1..^1]) : [];
- private static IfcBooleanResult? ParseBooleanResult(StepFile step, StepEntity itemEnt, double radiansPerAngleUnit)
+ private const int MaxBooleanDepth = 64;
+
+ private static bool IsBooleanEntity(StepEntity entity) =>
+ entity.Type.Equals("IFCBOOLEANRESULT", StringComparison.OrdinalIgnoreCase)
+ || entity.Type.Equals("IFCBOOLEANCLIPPINGRESULT", StringComparison.OrdinalIgnoreCase);
+
+ private static IfcBooleanResult ParseBooleanResult(GeometryReadContext ctx, StepEntity itemEnt, HashSet active)
{
- string? opStr = itemEnt.GetRaw(0);
- var op = IfcBooleanOperator.Difference;
- if (opStr?.Contains(".UNION.", StringComparison.OrdinalIgnoreCase) == true)
- op = IfcBooleanOperator.Union;
- else if (opStr?.Contains(".INTERSECTION.", StringComparison.OrdinalIgnoreCase) == true)
- op = IfcBooleanOperator.Intersection;
+ if (active.Contains(itemEnt.Id))
+ throw new InvalidDataException($"Boolean operand cycle at #{itemEnt.Id}.");
+ if (active.Count >= MaxBooleanDepth)
+ throw new InvalidDataException($"Boolean operands at #{itemEnt.Id} exceed the depth limit ({MaxBooleanDepth}).");
+ ctx.ChargeBooleanNode(itemEnt.Id);
+ active.Add(itemEnt.Id);
+
+ var step = ctx.Step;
+ var op = itemEnt.GetRaw(0)?.ToUpperInvariant() switch
+ {
+ ".DIFFERENCE." => IfcBooleanOperator.Difference,
+ ".UNION." => IfcBooleanOperator.Union,
+ ".INTERSECTION." => IfcBooleanOperator.Intersection,
+ _ => throw new InvalidDataException($"Boolean #{itemEnt.Id} has an invalid operator."),
+ };
int? firstOpId = itemEnt.GetRef(1);
int? secondOpId = itemEnt.GetRef(2);
var boolResult = new IfcBooleanResult { Operator = op };
- if (firstOpId.HasValue)
+ if (step.Find(firstOpId) is { } firstEnt)
{
- var firstEnt = step.Find(firstOpId.Value);
- if (firstEnt is not null)
+ if (IsBooleanEntity(firstEnt))
{
- var sweptMesh = ParseSweptSolid(step, firstEnt, "BooleanOperand", radiansPerAngleUnit,
+ boolResult.FirstBoolean = ParseBooleanResult(ctx, firstEnt, active);
+ }
+ else
+ {
+ var sweptMesh = ParseSweptSolid(step, firstEnt, "BooleanOperand", ctx.RadiansPerAngleUnit,
out var extruded, out var revolved);
boolResult.FirstSolid = extruded;
boolResult.FirstRevolved = revolved;
if (extruded is null && revolved is null)
boolResult.FirstMesh = sweptMesh ?? ParseMeshEntity(step, firstEnt);
+ ctx.ChargeVertices((sweptMesh ?? boolResult.FirstMesh)?.Vertices.Count ?? 0);
}
}
- if (secondOpId.HasValue)
+ if (step.Find(secondOpId) is { } secondEnt)
{
- var secondEnt = step.Find(secondOpId.Value);
- if (secondEnt is not null)
+ if (IsBooleanEntity(secondEnt))
{
- if (secondEnt.Type.Equals("IFCHALFSPACESOLID", StringComparison.OrdinalIgnoreCase))
- {
- boolResult.SecondHalfSpace = ParseHalfSpaceSolid(step, secondOpId.Value);
- }
- else
- {
- var sweptMesh = ParseSweptSolid(step, secondEnt, "BooleanOperand", radiansPerAngleUnit,
- out var extruded, out _);
- boolResult.SecondSolid = extruded;
- if (extruded is null)
- boolResult.SecondMesh = sweptMesh ?? ParseMeshEntity(step, secondEnt);
- }
+ boolResult.SecondBoolean = ParseBooleanResult(ctx, secondEnt, active);
+ }
+ else if (secondEnt.Type.Equals("IFCHALFSPACESOLID", StringComparison.OrdinalIgnoreCase))
+ {
+ boolResult.SecondHalfSpace = ParseHalfSpaceSolid(step, secondEnt.Id);
+ }
+ else
+ {
+ var sweptMesh = ParseSweptSolid(step, secondEnt, "BooleanOperand", ctx.RadiansPerAngleUnit,
+ out var extruded, out var revolved);
+ boolResult.SecondSolid = extruded;
+ boolResult.SecondRevolved = revolved;
+ if (extruded is null)
+ boolResult.SecondMesh = sweptMesh ?? ParseMeshEntity(step, secondEnt);
+ ctx.ChargeVertices((sweptMesh ?? boolResult.SecondMesh)?.Vertices.Count ?? 0);
}
}
+ if (boolResult.FirstSolid is null && boolResult.FirstRevolved is null && boolResult.FirstMesh is null && boolResult.FirstBoolean is null)
+ WarnSkipped("first", firstOpId);
+ if (boolResult.SecondHalfSpace is null && boolResult.SecondSolid is null && boolResult.SecondRevolved is null
+ && boolResult.SecondMesh is null && boolResult.SecondBoolean is null)
+ WarnSkipped("second", secondOpId);
+ else if (boolResult.SecondHalfSpace is null || op == IfcBooleanOperator.Union)
+ ctx.BooleanWarnings.Add($"Boolean #{itemEnt.Id}: {op} with this second operand is not evaluated in the mesh.");
+
+ active.Remove(itemEnt.Id);
return boolResult;
+
+ void WarnSkipped(string operand, int? id)
+ {
+ var entity = step.Find(id);
+ string description = entity is not null ? $"{entity.Type} #{entity.Id}" : id.HasValue ? $"missing entity #{id}" : "missing reference";
+ ctx.BooleanWarnings.Add($"Boolean #{itemEnt.Id}: skipped {operand} operand ({description}).");
+ }
}
private static void PlaceBooleanOperands(IfcBooleanResult result, IfcTransform placement)
@@ -3447,29 +3506,40 @@ private static void PlaceBooleanOperands(IfcBooleanResult result, IfcTransform p
revolved.Position += placement.Origin;
revolved.Axis.Location += placement.Origin;
}
+ if (result.SecondRevolved is { } secondRevolved)
+ {
+ secondRevolved.Position += placement.Origin;
+ secondRevolved.Axis.Location += placement.Origin;
+ }
}
else
{
result.FirstMesh ??= result.FirstSolid?.ToMesh() ?? result.FirstRevolved?.ToMesh();
- result.SecondMesh ??= result.SecondSolid?.ToMesh();
+ result.SecondMesh ??= result.SecondSolid?.ToMesh() ?? result.SecondRevolved?.ToMesh();
result.FirstSolid = null;
result.FirstRevolved = null;
result.SecondSolid = null;
+ result.SecondRevolved = null;
}
if (result.FirstMesh is { } firstMesh) result.FirstMesh = placement.ApplyTo(firstMesh);
if (result.SecondMesh is { } secondMesh) result.SecondMesh = placement.ApplyTo(secondMesh);
if (result.SecondHalfSpace?.BaseSurface is { } plane)
result.SecondHalfSpace.BaseSurface = new IfcPlane(placement.Apply(plane.Location), placement.ApplyVector(plane.Normal));
+ if (result.FirstBoolean is { } firstBoolean) PlaceBooleanOperands(firstBoolean, placement);
+ if (result.SecondBoolean is { } secondBoolean) PlaceBooleanOperands(secondBoolean, placement);
}
private static IfcPlane? ParsePlane(StepFile step, int? planeId)
{
- if (!planeId.HasValue) return null;
- var planeEnt = step.Find(planeId.Value);
- if (planeEnt is null) return null;
+ var planeEnt = step.Find(planeId);
+ if (planeEnt is null || !planeEnt.Type.Equals("IFCPLANE", StringComparison.OrdinalIgnoreCase)
+ || step.Find(planeEnt.GetRef(0)) is not { } placementEntity
+ || !placementEntity.Type.Equals("IFCAXIS2PLACEMENT3D", StringComparison.OrdinalIgnoreCase)
+ || step.Find(placementEntity.GetRef(0)) is not { } point
+ || !point.Type.Equals("IFCCARTESIANPOINT", StringComparison.OrdinalIgnoreCase)) return null;
- var placement = ParseAxis2Placement(step, planeEnt.GetRef(0));
+ var placement = ParseAxis2Placement(step, placementEntity.Id);
return new IfcPlane(placement.Origin, placement.Z);
}
@@ -3479,12 +3549,14 @@ private static void PlaceBooleanOperands(IfcBooleanResult result, IfcTransform p
var hsEnt = step.Find(halfSpaceId.Value);
if (hsEnt is null) return null;
- int? planeId = hsEnt.GetRef(0);
- var plane = ParsePlane(step, planeId) ?? new IfcPlane();
- string? rawFlag = hsEnt.GetRaw(1);
- bool flag = rawFlag is null || !rawFlag.Contains(".F.", StringComparison.OrdinalIgnoreCase);
-
- return new IfcHalfSpaceSolid(plane, flag);
+ var plane = ParsePlane(step, hsEnt.GetRef(0));
+ if (plane is null) return null;
+ return hsEnt.GetRaw(1)?.ToUpperInvariant() switch
+ {
+ ".T." => new IfcHalfSpaceSolid(plane, agreementFlag: true),
+ ".F." => new IfcHalfSpaceSolid(plane, agreementFlag: false),
+ _ => null,
+ };
}
private static IfcProfileDef? ParseProfile(StepFile step, int? profileId, out IfcTransform rotation)
diff --git a/src/IfcIO/Patch/IfcPatch.cs b/src/IfcIO/Patch/IfcPatch.cs
index 163f90f..6fe8957 100644
--- a/src/IfcIO/Patch/IfcPatch.cs
+++ b/src/IfcIO/Patch/IfcPatch.cs
@@ -193,6 +193,7 @@ public static IfcModel Extract(IfcModel source, Func predicate
Schema = source.Schema,
SourceSchemaIdentifier = source.SourceSchemaIdentifier,
UnsupportedPlacementCount = source.UnsupportedPlacementCount,
+ BooleanImportWarnings = source.BooleanImportWarnings,
};
target.Storeys.Clear();
@@ -254,6 +255,7 @@ public static IfcModel Merge(IEnumerable models, string mergedProjectN
LengthUnit = baseModel.LengthUnit,
AngleUnit = baseModel.AngleUnit,
Schema = modelList.Any(m => m.Schema == Schema.IfcSchema.Ifc4) ? Schema.IfcSchema.Ifc4 : Schema.IfcSchema.Ifc2x3,
+ BooleanImportWarnings = modelList.SelectMany(m => m.BooleanImportWarnings).ToArray(),
};
merged.Storeys.Clear();
diff --git a/src/IfcIO/Validation/IfcValidator.cs b/src/IfcIO/Validation/IfcValidator.cs
index 4b1c904..bfb0b63 100644
--- a/src/IfcIO/Validation/IfcValidator.cs
+++ b/src/IfcIO/Validation/IfcValidator.cs
@@ -60,6 +60,16 @@ public static IfcValidationResult Validate(IfcModel model)
});
}
+ foreach (string warning in model.BooleanImportWarnings)
+ {
+ issues.Add(new IfcValidationIssue
+ {
+ RuleId = "IFC_BOOLEAN_IMPORT",
+ Severity = IfcIssueSeverity.Warning,
+ Message = warning,
+ });
+ }
+
// 2. GlobalId uniqueness and format
var seenGuids = new Dictionary(StringComparer.Ordinal);
@@ -525,7 +535,7 @@ private static void ValidateProfile(IfcProfileDef? profile, string entityName, L
private static void ValidateCsg(IfcBooleanResult csg, string entityName, List issues)
{
- if (csg.FirstSolid is null && csg.FirstRevolved is null && csg.FirstMesh is null)
+ if (csg.FirstSolid is null && csg.FirstRevolved is null && csg.FirstMesh is null && csg.FirstBoolean is null)
{
issues.Add(new IfcValidationIssue
{
@@ -539,8 +549,13 @@ private static void ValidateCsg(IfcBooleanResult csg, string entityName, List qsets, string entityName, List issues)
diff --git a/tests/IfcIO.Tests/CsgImportTests.cs b/tests/IfcIO.Tests/CsgImportTests.cs
new file mode 100644
index 0000000..0fdf7ff
--- /dev/null
+++ b/tests/IfcIO.Tests/CsgImportTests.cs
@@ -0,0 +1,206 @@
+using IfcIO.Core;
+using IfcIO.Geometry;
+using Xunit;
+
+namespace IfcIO.Tests;
+
+public class CsgImportTests
+{
+ private static string ClippedBeam(int firstOperand, string secondHalfSpace, string extra = "", bool ifc4 = false) => $$"""
+ ISO-10303-21;
+ HEADER;
+ FILE_SCHEMA(('{{(ifc4 ? "IFC4" : "IFC2X3")}}'));
+ ENDSEC;
+ DATA;
+ #1=IFCPROJECT('0YvctVUKr0kugbFTf53O9L',$,'Nested clipping',$,$,$,$,(#30),#2);
+ #2=IFCUNITASSIGNMENT((#3));
+ #3=IFCSIUNIT(*,.LENGTHUNIT.,.MILLI.,.METRE.);
+ #4=IFCCARTESIANPOINT((0.,0.,0.));
+ #5=IFCCARTESIANPOINT((0.,0.));
+ #6=IFCAXIS2PLACEMENT3D(#4,$,$);
+ #7=IFCAXIS2PLACEMENT2D(#5,$);
+ #8=IFCRECTANGLEPROFILEDEF(.AREA.,$,#7,20.,10.);
+ #9=IFCDIRECTION((0.,0.,1.));
+ #10=IFCEXTRUDEDAREASOLID(#8,#6,#9,100.);
+ #11=IFCCARTESIANPOINT((0.,0.,25.));
+ #12=IFCAXIS2PLACEMENT3D(#11,$,$);
+ #13=IFCPLANE(#12);
+ #14=IFCHALFSPACESOLID(#13,.T.);
+ #15=IFCBOOLEANCLIPPINGRESULT(.DIFFERENCE.,#10,#14);
+ #16=IFCCARTESIANPOINT((0.,0.,75.));
+ #17=IFCAXIS2PLACEMENT3D(#16,$,$);
+ #18=IFCPLANE(#17);
+ #19={{secondHalfSpace}};
+ #20=IFCBOOLEANCLIPPINGRESULT(.DIFFERENCE.,#{{firstOperand}},#19);
+ #21=IFCSHAPEREPRESENTATION(#30,'Body','Clipping',(#20));
+ #22=IFCPRODUCTDEFINITIONSHAPE($,$,(#21));
+ #23=IFCBEAM('1YvctVUKr0kugbFTf53O9L',$,'Beam',$,$,$,#22,${{(ifc4 ? ",.NOTDEFINED." : "")}});
+ #30=IFCGEOMETRICREPRESENTATIONCONTEXT($,'Model',3,1.E-05,#6,$);
+ {{extra}}
+ ENDSEC;
+ END-ISO-10303-21;
+ """;
+
+ [Theory]
+ [InlineData(false)]
+ [InlineData(true)]
+ public void OpenAndSave_NestedClipping_AppliesBothPlanes(bool ifc4)
+ {
+ var model = IfcModel.Open(new StringReader(ClippedBeam(15, "IFCHALFSPACESOLID(#18,.F.)", ifc4: ifc4)));
+ Assert.Empty(model.BooleanImportWarnings);
+ var mesh = Assert.Single(model.AllElements).Mesh!;
+ Assert.Equal(new IfcVector3(-10, -5, 25), mesh.BoundingBox.Min);
+ Assert.Equal(new IfcVector3(10, 5, 75), mesh.BoundingBox.Max);
+
+ string saved = model.ToStepString();
+ Assert.Equal(2, StepReader.Read(new StringReader(saved)).OfType("IFCBOOLEANCLIPPINGRESULT").Count());
+ var reopened = Assert.Single(IfcModel.Open(new StringReader(saved)).AllElements).Mesh!;
+ Assert.Equal(mesh.BoundingBox, reopened.BoundingBox);
+ }
+
+ [Fact]
+ public void Open_CyclicBooleanOperand_RejectsInvalidTree()
+ {
+ string ifc = ClippedBeam(20, "IFCHALFSPACESOLID(#18,.F.)");
+ var error = Assert.Throws(() => IfcModel.Open(new StringReader(ifc)));
+ Assert.Contains("cycle", error.Message, StringComparison.OrdinalIgnoreCase);
+ }
+
+ [Fact]
+ public void Open_ExcessiveBooleanDepth_RejectsDeepTree()
+ {
+ string chain = string.Join('\n', Enumerable.Range(100, 64).Select(id =>
+ FormattableString.Invariant($"#{id}=IFCBOOLEANCLIPPINGRESULT(.DIFFERENCE.,#{(id == 100 ? 10 : id - 1)},#14);")));
+ var error = Assert.Throws(() =>
+ IfcModel.Open(new StringReader(ClippedBeam(163, "IFCHALFSPACESOLID(#18,.F.)", chain))));
+ Assert.Contains("depth limit", error.Message, StringComparison.Ordinal);
+ }
+
+ [Fact]
+ public void Open_SharedBooleanSubtrees_ChargeModelWideExpansion()
+ {
+ string tree = string.Join('\n', Enumerable.Range(100, 8).Select(id =>
+ FormattableString.Invariant($"#{id}=IFCBOOLEANRESULT(.UNION.,#{id - 1},#{id - 1});")));
+ string halfSpace = "IFCHALFSPACESOLID(#18,.F.)";
+ Assert.Single(IfcModel.Open(new StringReader(ClippedBeam(107, halfSpace, tree))).AllElements);
+
+ string ifc = ClippedBeam(107, halfSpace, tree + """
+
+ #31=IFCBEAM('2YvctVUKr0kugbFTf53O9L',$,'Second beam',$,$,$,#22,$);
+ #32=IFCBEAM('3YvctVUKr0kugbFTf53O9L',$,'Third beam',$,$,$,#22,$);
+ """);
+ var error = Assert.Throws(() => IfcModel.Open(new StringReader(ifc)));
+ Assert.Contains("model-wide expansion limit", error.Message, StringComparison.Ordinal);
+ }
+
+ [Fact]
+ public void Open_NestedClipping_AppliesProductPlacementToBothPlanes()
+ {
+ string ifc = ClippedBeam(15, "IFCHALFSPACESOLID(#18,.F.)", """
+ #24=IFCCARTESIANPOINT((100.,200.,300.));
+ #25=IFCDIRECTION((1.,0.,0.));
+ #26=IFCDIRECTION((0.,1.,0.));
+ #27=IFCAXIS2PLACEMENT3D(#24,#25,#26);
+ #28=IFCLOCALPLACEMENT($,#27);
+ """).Replace("'Beam',$,$,$,#22", "'Beam',$,$,#28,#22", StringComparison.Ordinal);
+ var model = IfcModel.Open(new StringReader(ifc));
+ var mesh = Assert.Single(model.AllElements).Mesh!;
+ Assert.Equal(new IfcVector3(125, 190, 295), mesh.BoundingBox.Min);
+ Assert.Equal(new IfcVector3(175, 210, 305), mesh.BoundingBox.Max);
+ var reopened = Assert.Single(IfcModel.Open(new StringReader(model.ToStepString())).AllElements).Mesh!;
+ Assert.Equal(mesh.BoundingBox, reopened.BoundingBox);
+ }
+
+ [Fact]
+ public void Open_BoundedHalfSpace_ReportsWhichOperandWasSkipped()
+ {
+ string ifc = ClippedBeam(15, "IFCPOLYGONALBOUNDEDHALFSPACE(#18,.F.,#17,#24)", """
+ #24=IFCPOLYLINE((#5,#25,#26,#27,#5));
+ #25=IFCCARTESIANPOINT((5.,0.));
+ #26=IFCCARTESIANPOINT((5.,5.));
+ #27=IFCCARTESIANPOINT((0.,5.));
+ """);
+ var model = IfcModel.Open(new StringReader(ifc));
+ string warning = Assert.Single(model.BooleanImportWarnings);
+ Assert.Contains("Boolean #20: skipped second operand (IFCPOLYGONALBOUNDEDHALFSPACE #19)", warning, StringComparison.Ordinal);
+ Assert.Contains(model.Validate().Issues, i => i.RuleId == "IFC_BOOLEAN_IMPORT" && i.Message == warning);
+ Assert.Throws(() => model.ToStepString());
+ }
+
+ [Fact]
+ public void Open_HalfSpaceWithMissingPlane_DoesNotInventACut()
+ {
+ var model = IfcModel.Open(new StringReader(ClippedBeam(10, "IFCHALFSPACESOLID(#999,.F.)")));
+ Assert.Contains("skipped second operand", Assert.Single(model.BooleanImportWarnings), StringComparison.Ordinal);
+ var mesh = Assert.Single(model.AllElements).Mesh!;
+ Assert.Equal(100, mesh.BoundingBox.Max.Z);
+ }
+
+ [Fact]
+ public void Open_NestedSecondOperand_PreservesTreeAndWarnsMeshIsIncomplete()
+ {
+ string ifc = ClippedBeam(10, "IFCBOOLEANCLIPPINGRESULT(.DIFFERENCE.,#10,#14)")
+ .Replace("#20=IFCBOOLEANCLIPPINGRESULT", "#20=IFCBOOLEANRESULT", StringComparison.Ordinal)
+ .Replace("'Clipping'", "'CSG'", StringComparison.Ordinal);
+
+ var model = IfcModel.Open(new StringReader(ifc));
+ Assert.Contains("not evaluated", Assert.Single(model.BooleanImportWarnings), StringComparison.Ordinal);
+ var step = StepReader.Read(new StringReader(model.ToStepString()));
+ var result = Assert.Single(step.OfType("IFCBOOLEANRESULT"));
+ Assert.Equal(Assert.Single(step.OfType("IFCBOOLEANCLIPPINGRESULT")).Id, result.GetRef(2));
+ }
+
+ [Theory]
+ [InlineData(".T.", 0, 75)]
+ [InlineData(".F.", 75, 100)]
+ public void Open_Intersection_KeepsHalfSpaceMaterial(string flag, int minZ, int maxZ)
+ {
+ string ifc = ClippedBeam(10, $"IFCHALFSPACESOLID(#18,{flag})", ifc4: true)
+ .Replace("#20=IFCBOOLEANCLIPPINGRESULT(.DIFFERENCE.", "#20=IFCBOOLEANRESULT(.INTERSECTION.", StringComparison.Ordinal)
+ .Replace("'Clipping'", "'CSG'", StringComparison.Ordinal);
+
+ var model = IfcModel.Open(new StringReader(ifc));
+ var mesh = Assert.Single(model.AllElements).Mesh!;
+ Assert.Equal(minZ, mesh.BoundingBox.Min.Z);
+ Assert.Equal(maxZ, mesh.BoundingBox.Max.Z);
+ Assert.Empty(model.BooleanImportWarnings);
+ }
+
+ [Fact]
+ public void Open_UnionWithHalfSpace_WarnsWithoutReplacingSourceMeshWithAClip()
+ {
+ string ifc = ClippedBeam(10, "IFCHALFSPACESOLID(#18,.T.)", ifc4: true)
+ .Replace("#20=IFCBOOLEANCLIPPINGRESULT(.DIFFERENCE.", "#20=IFCBOOLEANRESULT(.UNION.", StringComparison.Ordinal)
+ .Replace("'Clipping'", "'CSG'", StringComparison.Ordinal);
+ var model = IfcModel.Open(new StringReader(ifc));
+ var mesh = Assert.Single(model.AllElements).Mesh!;
+ Assert.Equal(0, mesh.BoundingBox.Min.Z);
+ Assert.Equal(100, mesh.BoundingBox.Max.Z);
+ Assert.Contains("Union", Assert.Single(model.BooleanImportWarnings), StringComparison.Ordinal);
+ }
+
+ [Fact]
+ public void OpenAndSave_SecondRevolution_PreservesParametricOperand()
+ {
+ string ifc = ClippedBeam(10, "IFCREVOLVEDAREASOLID(#24,#6,#27,1.57079632679)", """
+ #24=IFCRECTANGLEPROFILEDEF(.AREA.,$,#25,2.,4.);
+ #25=IFCAXIS2PLACEMENT2D(#26,$);
+ #26=IFCCARTESIANPOINT((4.,6.));
+ #27=IFCAXIS1PLACEMENT(#4,#28);
+ #28=IFCDIRECTION((0.,1.,0.));
+ """, ifc4: true)
+ .Replace("#20=IFCBOOLEANCLIPPINGRESULT", "#20=IFCBOOLEANRESULT", StringComparison.Ordinal)
+ .Replace("'Clipping'", "'CSG'", StringComparison.Ordinal);
+ var model = IfcModel.Open(new StringReader(ifc));
+ Assert.Contains("not evaluated", Assert.Single(model.BooleanImportWarnings), StringComparison.Ordinal);
+ var result = Assert.Single(model.AllElements).BooleanResult!;
+ Assert.NotNull(result.SecondRevolved);
+ Assert.NotNull(result.SecondMesh);
+
+ string saved = model.ToStepString();
+ var step = StepReader.Read(new StringReader(saved));
+ var operand = Assert.Single(step.OfType("IFCREVOLVEDAREASOLID"));
+ Assert.Equal(operand.Id, Assert.Single(step.OfType("IFCBOOLEANRESULT")).GetRef(2));
+ Assert.Single(IfcModel.Open(new StringReader(saved)).BooleanImportWarnings);
+ }
+}
diff --git a/tests/IfcIO.Tests/PlacementGeometryTests.cs b/tests/IfcIO.Tests/PlacementGeometryTests.cs
index aef2dfd..e389794 100644
--- a/tests/IfcIO.Tests/PlacementGeometryTests.cs
+++ b/tests/IfcIO.Tests/PlacementGeometryTests.cs
@@ -344,12 +344,12 @@ public void Save_MultipleBooleanItems_RejectsLosingOperands()
}
[Fact]
- public void Save_NestedUnsupportedBoolean_RejectsMissingOperandInsteadOfWritingRefZero()
+ public void Save_NestedBooleanWithMissingOperand_DoesNotWriteRefZero()
{
string ifc = BuildIfc(Millimetre)
.Replace("'Clipping',(#606));", "'Clipping',(#614));", StringComparison.Ordinal)
.Replace("#606=IFCBOOLEANCLIPPINGRESULT(.DIFFERENCE.,#607,#610);",
- "#606=IFCBOOLEANCLIPPINGRESULT(.DIFFERENCE.,#607,#610); #614=IFCBOOLEANCLIPPINGRESULT(.DIFFERENCE.,#606,#610);",
+ "#606=IFCBOOLEANCLIPPINGRESULT(.DIFFERENCE.,#999,#610); #614=IFCBOOLEANCLIPPINGRESULT(.DIFFERENCE.,#606,#610);",
StringComparison.Ordinal);
var error = Assert.Throws(() => Open(ifc).ToStepString());