Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,12 @@ All notable changes to the `IfcIO` library are documented in this file.
## [Unreleased]

### Fixed
- 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.
- IFC export rejects unsupported compound or incomplete Boolean bodies instead of silently dropping operations
or writing missing operand references.
- IFC4 `IfcTriangulatedFaceSet` import reads nested coordinate and triangle lists, including `PnIndex`.
- STEP import indexes entities by type once, reuses repeated type names, and reads typed arguments from lazy slices.
- Faceted face import triangulates concave polygons and holes, keeps disjoint bounds as separate regions,
and omits invalid contours rather than substituting zero coordinates.
Expand Down
13 changes: 13 additions & 0 deletions docs/public-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,19 @@ among generated product GlobalIds and does not rewrite explicit GlobalIds.
For faceted faces, the reader triangulates planar concave bounds and holes without adding vertices. Disjoint
bounds remain separate regions. Invalid contours or faces that exceed the triangulation work limit are omitted.

Imported meshes use world coordinates. If a swept body cannot be represented by one equivalent parametric
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.
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.

The reader uses standard IFC sweep coordinates. Older IfcIO exports that encoded a tilted authored extrusion
without its profile frame, or a translated revolution's axis in absolute coordinates, may reopen differently.
New exports write the extrusion frame and the revolution's local axis explicitly.
Revolutions whose axis does not lie in the authored profile plane are exported as a mesh.
For non-tessellated mesh export, disconnected closed shells are written separately and open meshes use a surface model.

## Import & Export

| Type | Description |
Expand Down
4 changes: 0 additions & 4 deletions docs/scene-adapter.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,10 +79,6 @@ rebases them, for example on `ComputeBounds().Center`, before narrowing them to

## Limits

- **IFC4 tessellated geometry is not read.** IfcIO's reader returns no mesh for `IfcTriangulatedFaceSet`, including
the one IfcIO itself writes for IFC4 models: the point and index lists lose their inner brackets while being parsed,
so no triangle is found. Such elements are in the scene without geometry and reported as `no-geometry`. Verified
with an IFC4 model saved by IfcIO and opened again; a test pins this behaviour.
- Mapped items (`IfcMappedItem`) are baked into each element's world mesh, so shared geometry is not shared in the
scene.
- IfcIO places an element in a storey only through `IfcRelContainedInSpatialStructure`. Elements contained in the site
Expand Down
8 changes: 3 additions & 5 deletions src/IfcIO/Core/StepWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -102,11 +102,9 @@ public static string Real(double v)
public static string RealExact(double v)
{
string text = v.ToString("G15", CultureInfo.InvariantCulture);
if (!text.Contains('.') && !text.Contains('E') && !text.Contains('e'))
{
text += ".";
}
return text;
if (text.Contains('.')) return text;
int exponent = text.IndexOf('E');
return exponent < 0 ? text + "." : text.Insert(exponent, ".");
}

/// <summary>
Expand Down
3 changes: 2 additions & 1 deletion src/IfcIO/Geometry/CsgTypes.cs
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,8 @@ public sealed class IfcBooleanResult
/// <summary>
/// True if this represents an IFCBOOLEANCLIPPINGRESULT (difference with a half-space solid).
/// </summary>
public bool IsClippingResult => SecondHalfSpace is not null || Operator == IfcBooleanOperator.Difference;
public bool IsClippingResult => Operator == IfcBooleanOperator.Difference
&& SecondHalfSpace is not null && (FirstSolid is not null || FirstRevolved is not null);

public IfcBooleanResult() { }

Expand Down
67 changes: 46 additions & 21 deletions src/IfcIO/Geometry/SweptSolidTypes.cs
Original file line number Diff line number Diff line change
Expand Up @@ -123,47 +123,43 @@ public IfcExtrudedAreaSolid(IfcProfileDef profile, double depth, IfcVector3? pos
Direction = direction ?? IfcVector3.UnitZ;
}

// The authoring API defines the profile in a plane perpendicular to Direction.
internal IfcTransform GetProfileFrame()
{
var z = Direction.Normalized();
if (z.Length < 1e-6) z = IfcVector3.UnitZ;

var x = Math.Abs(z.Z) > 0.999
? IfcVector3.Cross(IfcVector3.Cross(z, IfcVector3.UnitX).Normalized(), z).Normalized()
: IfcVector3.Cross(IfcVector3.UnitZ, z).Normalized();
return new IfcTransform(x, IfcVector3.Cross(z, x).Normalized(), z, Position);
}

/// <summary>
/// Converts the extruded swept solid into a triangulated 3D polygon mesh.
/// </summary>
public IfcMesh ToMesh(int segments = 16, string meshName = "ExtrudedSolid")
{
var boundary2D = Profile.GetBoundaryPoints(segments);
var boundary2D = GetCounterClockwiseBoundary(Profile.GetBoundaryPoints(segments));
int n = boundary2D.Count;
if (n < 3)
{
return IfcMesh.Create(0, meshName, Array.Empty<IfcVector3>(), Array.Empty<int>());
}

// Construct orthonormal coordinate frame
var dirNorm = Direction.Normalized();
if (dirNorm.Length < 1e-6) dirNorm = IfcVector3.UnitZ;

IfcVector3 xAxis, yAxis;
if (Math.Abs(dirNorm.Z) > 0.999)
{
xAxis = IfcVector3.UnitX;
yAxis = IfcVector3.Cross(dirNorm, xAxis).Normalized();
xAxis = IfcVector3.Cross(yAxis, dirNorm).Normalized();
}
else
{
xAxis = IfcVector3.Cross(IfcVector3.UnitZ, dirNorm).Normalized();
yAxis = IfcVector3.Cross(dirNorm, xAxis).Normalized();
}

var frame = GetProfileFrame();
var vertices = new List<IfcVector3>(n * 2);
var indices = new List<int>(n * 6 + (n - 2) * 6);

// Transform 2D profile points to 3D base and top vertices
for (int i = 0; i < n; i++)
{
var p2 = boundary2D[i];
var basePt = Position + (p2.X * xAxis) + (p2.Y * yAxis);
var basePt = frame.Origin + (p2.X * frame.X) + (p2.Y * frame.Y);
vertices.Add(basePt);
}

var extrudeOffset = dirNorm * Depth;
var extrudeOffset = frame.Z * Depth;
for (int i = 0; i < n; i++)
{
vertices.Add(vertices[i] + extrudeOffset);
Expand Down Expand Up @@ -212,6 +208,22 @@ public IfcMesh ToMesh(int segments = 16, string meshName = "ExtrudedSolid")

internal readonly record struct Vector2D(double X, double Y);

internal static IReadOnlyList<IfcVector3> GetCounterClockwiseBoundary(IReadOnlyList<IfcVector3> points)
{
int count = points.Count;
while (count > 1 && points[0] == points[count - 1]) count--;
if (count < 3) return points.Take(count).ToArray();

double area = 0;
var origin = points[0];
for (int i = 1; i < count - 1; i++)
area += IfcVector3.Cross(points[i] - origin, points[i + 1] - origin).Z;

if (area < 0)
return [points[0], ..points.Skip(1).Take(count - 1).Reverse()];
return count == points.Count ? points : points.Take(count).ToArray();
}

internal static List<int> TriangulatePolygon(IReadOnlyList<Vector2D> poly)
{
int n = poly.Count;
Expand Down Expand Up @@ -378,7 +390,7 @@ public IfcRevolvedAreaSolid(IfcProfileDef profile, double angle = 2.0 * Math.PI,
/// </summary>
public IfcMesh ToMesh(int profileSegments = 16, int radialSegments = 24, string meshName = "RevolvedSolid")
{
var boundary2D = Profile.GetBoundaryPoints(profileSegments);
var boundary2D = IfcExtrudedAreaSolid.GetCounterClockwiseBoundary(Profile.GetBoundaryPoints(profileSegments));
int n = boundary2D.Count;
if (n < 3)
{
Expand All @@ -402,6 +414,14 @@ public IfcMesh ToMesh(int profileSegments = 16, int radialSegments = 24, string
basePoints.Add(Position + new IfcVector3(p.X, p.Y, 0));
}

// The sweep can start on either side of the XY profile plane. Match the winding to its motion.
double normalVelocity = 0;
foreach (var point in basePoints)
{
double velocity = IfcVector3.Cross(axisDir, point - axisLoc).Z;
if (Math.Abs(velocity) > Math.Abs(normalVelocity)) normalVelocity = velocity;
}

var vertices = new List<IfcVector3>(ringCount * n);
var indices = new List<int>();

Expand Down Expand Up @@ -472,6 +492,11 @@ public IfcMesh ToMesh(int profileSegments = 16, int radialSegments = 24, string
}
}

if (normalVelocity * Angle < 0)
{
for (int i = 0; i < indices.Count; i += 3)
(indices[i + 1], indices[i + 2]) = (indices[i + 2], indices[i + 1]);
}
return IfcMesh.Create(0, meshName, vertices, indices);
}
}
Expand Down
100 changes: 100 additions & 0 deletions src/IfcIO/IfcModel.MeshExport.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
using IfcIO.Core;
using IfcIO.Geometry;

namespace IfcIO;

public sealed partial class IfcModel
{
private static (string Type, List<int> Ids) WriteBodyMesh(StepWriter w, IfcMesh mesh, bool tessellate)
{
var parts = GetMeshParts(mesh);
if (parts.Count == 0) throw new InvalidDataException("Cannot write a mesh without valid triangles.");

bool closed = parts.All(part => part.Closed);
if (tessellate)
return ("Tessellation", [WriteMeshTriangulatedFaceSet(w, mesh.Vertices, parts.SelectMany(p => p.Indices).ToArray(), closed)]);

var shells = parts.Select(p => WriteMeshShell(w, mesh.Vertices, p.Indices, p.Closed)).ToList();
return closed
? ("Brep", shells.Select(id => w.Add("IFCFACETEDBREP", StepWriter.Ref(id))).ToList())
: ("SurfaceModel", [w.Add("IFCSHELLBASEDSURFACEMODEL", StepWriter.List(shells.Select(StepWriter.Ref)))]);
}

private static int WriteBooleanMesh(StepWriter w, IfcMesh mesh, bool tessellate)
{
var parts = GetMeshParts(mesh);
if (parts.Count == 0 || parts.Any(part => !part.Closed))
throw new InvalidDataException("A Boolean mesh operand must be closed.");
if (tessellate)
return WriteMeshTriangulatedFaceSet(w, mesh.Vertices, parts.SelectMany(p => p.Indices).ToArray(), true);
if (parts.Count != 1)
throw new InvalidDataException("A faceted Boolean mesh operand must have one connected shell.");
return w.Add("IFCFACETEDBREP", StepWriter.Ref(WriteMeshShell(w, mesh.Vertices, parts[0].Indices, true)));
}

private sealed class MeshPart
{
public List<int> Indices { get; } = [];
public bool Closed { get; set; } = true;
}

/// <summary>Groups triangles by shared edges. A closed shell requires paired, oppositely directed edges.</summary>
private static List<MeshPart> GetMeshParts(IfcMesh mesh)
{
var parents = new int[mesh.TriangleCount];
Array.Fill(parents, -1);
var edges = new Dictionary<(int, int), (int Face, int Count, int Balance)>();
for (int i = 0; i < parents.Length; i++)
{
int a = mesh.Indices[i * 3], b = mesh.Indices[i * 3 + 1], c = mesh.Indices[i * 3 + 2];
if ((uint)a >= (uint)mesh.Vertices.Count || (uint)b >= (uint)mesh.Vertices.Count
|| (uint)c >= (uint)mesh.Vertices.Count || a == b || b == c || a == c) continue;
parents[i] = i;
JoinEdge(a, b, i);
JoinEdge(b, c, i);
JoinEdge(c, a, i);
}

var byRoot = new Dictionary<int, MeshPart>();
for (int i = 0; i < parents.Length; i++)
{
if (parents[i] < 0) continue;
int root = Find(i);
if (!byRoot.TryGetValue(root, out var part))
byRoot.Add(root, part = new MeshPart());
part.Indices.Add(mesh.Indices[i * 3]);
part.Indices.Add(mesh.Indices[i * 3 + 1]);
part.Indices.Add(mesh.Indices[i * 3 + 2]);
}
foreach (var edge in edges.Values)
if (edge.Count != 2 || edge.Balance != 0)
byRoot[Find(edge.Face)].Closed = false;
return byRoot.Values.ToList();

int Find(int face)
{
while (parents[face] != face)
{
parents[face] = parents[parents[face]];
face = parents[face];
}
return face;
}

void JoinEdge(int first, int second, int face)
{
bool forward = first < second;
var key = forward ? (first, second) : (second, first);
int sign = forward ? 1 : -1;
if (edges.TryGetValue(key, out var existing))
{
parents[Find(face)] = Find(existing.Face);
edges[key] = (existing.Face, existing.Count + 1, existing.Balance + sign);
}
else
{
edges.Add(key, (face, 1, sign));
}
}
}
}
Loading