diff --git a/CHANGELOG.md b/CHANGELOG.md index 3cdd353..aa9b29e 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 +- IFC import reads wrapped and direct surface colours, rendering transparency and material definition styles. + Explicit geometry styles take precedence over associated material colours. - IFC import recognizes IFC4.3 separately and reports unknown, missing and multiple schema identifiers. IFC4.3 is read as a subset and is not silently rewritten as IFC4. - Element factories allocate IDs across the model rather than per storey; the writer avoids generated GlobalId diff --git a/docs/scene-adapter.md b/docs/scene-adapter.md index 7ab4092..b702ecd 100644 --- a/docs/scene-adapter.md +++ b/docs/scene-adapter.md @@ -97,7 +97,9 @@ rebases them, for example on `ComputeBounds().Center`, before narrowing them to unit (for example centimetres). Area, volume and weight quantities retain the file's values. - An element without a GlobalId in the file gets a new random GlobalId from IfcIO each time it is read, so its `SourceId` is not stable. -- Transparency is not read from files by IfcIO; materials built in memory keep their alpha. +- Colours and transparency from IFC surface styles are read separately from physical materials. The imported mesh + still uses one colour per element: the first readable styled item takes precedence over an associated material or + the material of a single layer/profile. - Tasks without planned start and finish are left out (IfcIO reads task times from IFC4 files only); their subtasks are kept. Task costs and progress are not converted. Openings, ports, grids, zones, systems and cost schedules are not converted. diff --git a/src/IfcIO.Scene/IfcSceneReader.cs b/src/IfcIO.Scene/IfcSceneReader.cs index 4d2cee3..c519818 100644 --- a/src/IfcIO.Scene/IfcSceneReader.cs +++ b/src/IfcIO.Scene/IfcSceneReader.cs @@ -37,7 +37,7 @@ namespace IfcIO.Scene; /// means dimensionless and the adapter converts no value to SI. Property values are text /// as IfcIO reads them, because IfcIO does not report the measure of a value read from a file. A count quantity is a /// number with a null unit; length, area, volume and weight quantities are in the file's units, so they are text with -/// the number as IfcIO reads it. Colour and transparency come from ; +/// the number as IfcIO reads it. Colour and transparency come from ; /// elements without one get a colour for their IFC class. Work schedules become schedules. Openings are not converted. /// /// @@ -240,7 +240,7 @@ private static bool IsNotProduct(string ifcType) => int geometryId = doc.Geometries.Count + 1; doc.Geometries.Add(new SceneGeometry { Id = geometryId, Topology = SceneTopology.Triangles, Vertices = vertices, Indices = [.. source.Indices] }); var instance = new SceneInstance { ElementId = element.Id, GeometryId = geometryId }; - if (element.Material is { } material) instance.MaterialId = MaterialId(doc, material, materials); + if (element.GetEffectiveMaterial() is { } material) instance.MaterialId = MaterialId(doc, material, materials); else instance.Color = DefaultColor(element); doc.Instances.Add(instance); return null; diff --git a/src/IfcIO/Compatibility/Exporters/IfcGlbExporter.cs b/src/IfcIO/Compatibility/Exporters/IfcGlbExporter.cs index 1d65e01..04feeb0 100644 --- a/src/IfcIO/Compatibility/Exporters/IfcGlbExporter.cs +++ b/src/IfcIO/Compatibility/Exporters/IfcGlbExporter.cs @@ -92,18 +92,18 @@ public static void Write(IfcModel model, Stream output) { int? matId = null; - if (elem.Material is not null) + if (elem.GetEffectiveMaterial() is { } material) { - if (!matIndexMap.TryGetValue(elem.Material, out int existingMat)) + if (!matIndexMap.TryGetValue(material, out int existingMat)) { existingMat = gltfMaterials.Count; - matIndexMap[elem.Material] = existingMat; + matIndexMap[material] = existingMat; gltfMaterials.Add(new MaterialDef { - Name = elem.Material.Name, + Name = material.Name, Pbr = new PbrDef { - BaseColorFactor = [(float)elem.Material.R, (float)elem.Material.G, (float)elem.Material.B, (float)elem.Material.Alpha], + BaseColorFactor = [(float)material.R, (float)material.G, (float)material.B, (float)material.Alpha], MetallicFactor = 0.1f, RoughnessFactor = 0.7f, }, diff --git a/src/IfcIO/Compatibility/Exporters/IfcHtmlViewerExporter.cs b/src/IfcIO/Compatibility/Exporters/IfcHtmlViewerExporter.cs index f51dcba..efdc852 100644 --- a/src/IfcIO/Compatibility/Exporters/IfcHtmlViewerExporter.cs +++ b/src/IfcIO/Compatibility/Exporters/IfcHtmlViewerExporter.cs @@ -1078,9 +1078,9 @@ private static string BuildJsonPayload(IfcModel model, IfcHtmlViewerOptions opti private static (double r, double g, double b, double a) GetElementColor(IfcElement elem) { - if (elem.Material is not null) + if (elem.GetEffectiveMaterial() is { } material) { - return (elem.Material.R, elem.Material.G, elem.Material.B, elem.Material.Alpha); + return (material.R, material.G, material.B, material.Alpha); } string type = elem.IfcType.ToUpperInvariant(); diff --git a/src/IfcIO/Compatibility/Exporters/IfcObjExporter.cs b/src/IfcIO/Compatibility/Exporters/IfcObjExporter.cs index 5d8f5de..1ef43dc 100644 --- a/src/IfcIO/Compatibility/Exporters/IfcObjExporter.cs +++ b/src/IfcIO/Compatibility/Exporters/IfcObjExporter.cs @@ -76,13 +76,13 @@ public static void Write(IfcModel model, TextWriter objWriter, TextWriter mtlWri objWriter.WriteLine($"g {safeName}_{elem.Id}"); objWriter.WriteLine($"o {safeName}_{elem.Id}"); - if (elem.Material is not null) + if (elem.GetEffectiveMaterial() is { } material) { - if (writtenMaterials.Add(elem.Material.Name)) + if (writtenMaterials.Add(material.Name)) { - WriteMaterial(mtlWriter, elem.Material, inv); + WriteMaterial(mtlWriter, material, inv); } - objWriter.WriteLine($"usemtl {SanitizeName(elem.Material.Name)}"); + objWriter.WriteLine($"usemtl {SanitizeName(material.Name)}"); } var vertices = mesh.Vertices; diff --git a/src/IfcIO/IfcModel.SurfaceStyles.cs b/src/IfcIO/IfcModel.SurfaceStyles.cs new file mode 100644 index 0000000..ed5e08b --- /dev/null +++ b/src/IfcIO/IfcModel.SurfaceStyles.cs @@ -0,0 +1,85 @@ +using IfcIO.Core; +using IfcIO.Model; + +namespace IfcIO; + +public sealed partial class IfcModel +{ + private static (Dictionary Geometry, Dictionary Materials) + ReadSurfaceStyles(StepFile step) + { + var styles = new Dictionary(); + foreach (var style in step.OfType("IFCSURFACESTYLE")) + { + foreach (int appearanceId in style.GetRefList(2)) + { + var appearance = step.Find(appearanceId); + if (appearance is null || !(appearance.Type.Equals("IFCSURFACESTYLESHADING", StringComparison.OrdinalIgnoreCase) + || appearance.Type.Equals("IFCSURFACESTYLERENDERING", StringComparison.OrdinalIgnoreCase))) + continue; + + var rgb = step.Find(appearance.GetRef(0)); + if (rgb is null || !rgb.Type.Equals("IFCCOLOURRGB", StringComparison.OrdinalIgnoreCase)) continue; + + var material = new IfcMaterial + { + Name = style.GetString(0) ?? "Material", + R = RestrictToUnitInterval(rgb.GetReal(1), 0.8), + G = RestrictToUnitInterval(rgb.GetReal(2), 0.8), + B = RestrictToUnitInterval(rgb.GetReal(3), 0.8), + Alpha = 1.0 - RestrictToUnitInterval(appearance.GetReal(1), 0.0), + }; + styles.Add(style.Id, material); + break; + } + } + + // A styled item can reference a surface style directly, or through the IFC2x3 assignment wrapper. + var assignments = new Dictionary(); + foreach (var assignment in step.OfType("IFCPRESENTATIONSTYLEASSIGNMENT")) + { + foreach (int styleId in assignment.GetRefList(0)) + { + if (!styles.TryGetValue(styleId, out var material)) continue; + assignments.Add(assignment.Id, material); + break; + } + } + + var byStyledItem = new Dictionary(); + var byGeometry = new Dictionary(); + foreach (var item in step.OfType("IFCSTYLEDITEM")) + { + foreach (int styleId in item.GetRefList(1)) + { + if (!styles.TryGetValue(styleId, out var material) && !assignments.TryGetValue(styleId, out material)) + continue; + byStyledItem.Add(item.Id, material); + if (item.GetRef(0) is int geometryId) byGeometry[geometryId] = material; + break; + } + } + + // In a material representation the styled item itself is the appearance; its Item may be unset. + var byMaterial = new Dictionary(); + foreach (var definition in step.OfType("IFCMATERIALDEFINITIONREPRESENTATION")) + { + if (definition.GetRef(3) is not int materialId || byMaterial.ContainsKey(materialId)) continue; + foreach (int representationId in definition.GetRefList(2)) + { + var representation = step.Find(representationId); + if (representation is null || !representation.Type.Equals("IFCSTYLEDREPRESENTATION", StringComparison.OrdinalIgnoreCase)) + continue; + var appearance = representation.GetRefList(3).Select(id => byStyledItem.GetValueOrDefault(id)).FirstOrDefault(m => m is not null); + if (appearance is null) continue; + byMaterial.Add(materialId, appearance); + break; + } + } + + return (byGeometry, byMaterial); + } + + private static double RestrictToUnitInterval(double? value, double fallback) => + value is double channel && double.IsFinite(channel) ? Math.Clamp(channel, 0, 1) : fallback; +} diff --git a/src/IfcIO/IfcModel.cs b/src/IfcIO/IfcModel.cs index 5ae609a..d05a2de 100644 --- a/src/IfcIO/IfcModel.cs +++ b/src/IfcIO/IfcModel.cs @@ -773,11 +773,7 @@ public void Save(TextWriter writer, string fileName = "model.ifc") $"{StepWriter.Str(IfcGuid.NewGuid())},{StepWriter.Ref(ownerHistoryId)},$,$,{StepWriter.Ref(siteId)},({StepWriter.Ref(buildingId)})"); // 4. Materials Cache - var styleCache = new Dictionary(StringComparer.OrdinalIgnoreCase); - foreach (var mat in Materials) - { - GetOrCreateSurfaceStyle(w, mat, styleCache); - } + var styleCache = new Dictionary(); // 5. Type Products var typeIdMap = new Dictionary(); @@ -1243,10 +1239,31 @@ string ProductGuid(IfcElement element, string domain) // 9. Material Layers & Profiles var materialEntityMap = new Dictionary(); - foreach (var mat in Materials) + int WriteMaterial(IfcMaterial material) { - int matId = w.Add("IFCMATERIAL", StepWriter.Str(mat.Name)); - materialEntityMap[mat] = matId; + if (materialEntityMap.TryGetValue(material, out int existing)) return existing; + string attributes = StepWriter.Str(material.Name) + (Schema == IfcSchema.Ifc4 ? ",$,$" : ""); + int id = w.Add("IFCMATERIAL", attributes); + materialEntityMap.Add(material, id); + if ((material.R, material.G, material.B, material.Alpha) != (0.8, 0.8, 0.8, 1.0)) + { + int style = GetOrCreateSurfaceStyle(w, material, styleCache); + int item = w.Add("IFCSTYLEDITEM", $"$,({StepWriter.Ref(style)}),$"); + int representation = w.Add("IFCSTYLEDREPRESENTATION", + $"{StepWriter.Ref(mainContextId)},'Style','Material',({StepWriter.Ref(item)})"); + w.Add("IFCMATERIALDEFINITIONREPRESENTATION", $"$,$,({StepWriter.Ref(representation)}),{StepWriter.Ref(id)}"); + } + return id; + } + + foreach (var material in Materials) WriteMaterial(material); + foreach (var (element, id) in elementEntityMap) + { + if (element.AssignedMaterial is not { } material || element.MaterialLayerSet is not null || element.MaterialProfileSet is not null) + continue; + int matId = WriteMaterial(material); + w.Add("IFCRELASSOCIATESMATERIAL", + $"{StepWriter.Str(IfcGuid.NewGuid())},{StepWriter.Ref(ownerHistoryId)},$,$,({StepWriter.Ref(id)}),{StepWriter.Ref(matId)}"); } var layerSetMap = new Dictionary(); @@ -1255,11 +1272,7 @@ string ProductGuid(IfcElement element, string domain) var layerIds = new List(); foreach (var layer in ls.Layers) { - if (!materialEntityMap.TryGetValue(layer.Material, out int matId)) - { - matId = w.Add("IFCMATERIAL", StepWriter.Str(layer.Material.Name)); - materialEntityMap[layer.Material] = matId; - } + int matId = WriteMaterial(layer.Material); string isVent = layer.IsVentilated ? ".T." : ".F."; int layId = w.Add("IFCMATERIALLAYER", $"{StepWriter.Ref(matId)},{StepWriter.Real(layer.LayerThickness)},{isVent},{StepWriter.Str(layer.Name)},{StepWriter.Str(layer.Description)}"); @@ -1280,11 +1293,7 @@ string ProductGuid(IfcElement element, string domain) var layerIds = new List(); foreach (var layer in usage.ForLayerSet.Layers) { - if (!materialEntityMap.TryGetValue(layer.Material, out int matId)) - { - matId = w.Add("IFCMATERIAL", StepWriter.Str(layer.Material.Name)); - materialEntityMap[layer.Material] = matId; - } + int matId = WriteMaterial(layer.Material); string isVent = layer.IsVentilated ? ".T." : ".F."; int layId = w.Add("IFCMATERIALLAYER", $"{StepWriter.Ref(matId)},{StepWriter.Real(layer.LayerThickness)},{isVent},{StepWriter.Str(layer.Name)},{StepWriter.Str(layer.Description)}"); @@ -1308,15 +1317,7 @@ string ProductGuid(IfcElement element, string domain) var mpIds = new List(); foreach (var mp in ps.MaterialProfiles) { - int matId = 0; - if (mp.Material is not null) - { - if (!materialEntityMap.TryGetValue(mp.Material, out matId)) - { - matId = w.Add("IFCMATERIAL", StepWriter.Str(mp.Material.Name)); - materialEntityMap[mp.Material] = matId; - } - } + int matId = mp.Material is null ? 0 : WriteMaterial(mp.Material); int profDefId = WriteProfileDef(w, mp.Profile); string matRef = matId > 0 ? StepWriter.Ref(matId) : "$"; int mpId = w.Add("IFCMATERIALPROFILE", @@ -1338,15 +1339,7 @@ string ProductGuid(IfcElement element, string domain) var mpIds = new List(); foreach (var mp in usage.ForProfileSet.MaterialProfiles) { - int matId = 0; - if (mp.Material is not null) - { - if (!materialEntityMap.TryGetValue(mp.Material, out matId)) - { - matId = w.Add("IFCMATERIAL", StepWriter.Str(mp.Material.Name)); - materialEntityMap[mp.Material] = matId; - } - } + int matId = mp.Material is null ? 0 : WriteMaterial(mp.Material); int profDefId = WriteProfileDef(w, mp.Profile); string matRef = matId > 0 ? StepWriter.Ref(matId) : "$"; int mpId = w.Add("IFCMATERIALPROFILE", @@ -1648,51 +1641,7 @@ public static IfcModel Open(TextReader reader, string? modelName, IfcReadOptions } // 3. Parse Materials & Styles - var styleToMaterialMap = new Dictionary(); - foreach (var styleEnt in step.OfType("IFCSURFACESTYLE")) - { - string matName = styleEnt.GetString(0) ?? "Material"; - var styles = styleEnt.GetRefList(2); - foreach (int shadingId in styles) - { - var shadingEnt = step.Find(shadingId); - if (shadingEnt is not null && shadingEnt.Type.Equals("IFCSURFACESTYLESHADING", StringComparison.OrdinalIgnoreCase)) - { - int? colId = shadingEnt.GetRef(0); - var colEnt = step.Find(colId); - if (colEnt is not null && colEnt.Type.Equals("IFCCOLOURRGB", StringComparison.OrdinalIgnoreCase)) - { - double r = colEnt.GetReal(1) ?? 0.8; - double g = colEnt.GetReal(2) ?? 0.8; - double b = colEnt.GetReal(3) ?? 0.8; - - var mat = new IfcMaterial { Name = matName, R = r, G = g, B = b }; - styleToMaterialMap[styleEnt.Id] = mat; - if (!model.Materials.Contains(mat)) model.Materials.Add(mat); - break; - } - } - } - } - - // Map styled items to materials - var geomToMaterialMap = new Dictionary(); - foreach (var styledItem in step.OfType("IFCSTYLEDITEM")) - { - int? geomId = styledItem.GetRef(0); - var styles = styledItem.GetRefList(1); - if (geomId.HasValue) - { - foreach (int sId in styles) - { - if (styleToMaterialMap.TryGetValue(sId, out var mat)) - { - geomToMaterialMap[geomId.Value] = mat; - break; - } - } - } - } + var (geomToMaterialMap, materialAppearances) = ReadSurfaceStyles(step); // 4. Map Elements to Storeys var elementToStoreyMap = new Dictionary(); @@ -1928,7 +1877,7 @@ public static IfcModel Open(TextReader reader, string? modelName, IfcReadOptions } if (mat is not null) { - element.Material = mat; + element.SurfaceMaterial = mat; } } else if (shapeDefId.HasValue) @@ -2370,13 +2319,11 @@ openElem is IfcOpeningElement opening && foreach (var matEnt in step.OfType("IFCMATERIAL")) { string name = matEnt.GetString(0) ?? "Material"; - var existing = model.Materials.FirstOrDefault(m => m.Name.Equals(name, StringComparison.OrdinalIgnoreCase)); - if (existing is null) - { - existing = new IfcMaterial { Name = name }; - model.Materials.Add(existing); - } - materialMap[matEnt.Id] = existing; + var material = materialAppearances.TryGetValue(matEnt.Id, out var appearance) + ? new IfcMaterial { Name = name, R = appearance.R, G = appearance.G, B = appearance.B, Alpha = appearance.Alpha } + : new IfcMaterial { Name = name }; + model.Materials.Add(material); + materialMap.Add(matEnt.Id, material); } var layerMap = new Dictionary(); @@ -2590,12 +2537,13 @@ private static bool IsIfc4x3Identifier(string? identifier) => return identifier[..brace].TrimEnd(' '); } - private int WriteElementShape(StepWriter w, IfcElement element, int bodySubContextId, Dictionary styleCache, bool useTessellation) + private int WriteElementShape(StepWriter w, IfcElement element, int bodySubContextId, Dictionary styleCache, bool useTessellation) { int? styleId = null; - if (element.Material is not null) + var appearance = element.GetEffectiveMaterial(); + if (appearance is not null) { - styleId = GetOrCreateSurfaceStyle(w, element.Material, styleCache); + styleId = GetOrCreateSurfaceStyle(w, appearance, styleCache); } if (element.Solid is not null) @@ -2603,7 +2551,7 @@ private int WriteElementShape(StepWriter w, IfcElement element, int bodySubConte int solidGeomId = WriteExtrudedAreaSolid(w, element.Solid); if (styleId.HasValue) { - w.Add("IFCSTYLEDITEM", $"{StepWriter.Ref(solidGeomId)},({StepWriter.Ref(styleId.Value)}),{StepWriter.Str(element.Material?.Name)}"); + w.Add("IFCSTYLEDITEM", $"{StepWriter.Ref(solidGeomId)},({StepWriter.Ref(styleId.Value)}),{StepWriter.Str(appearance?.Name)}"); } int shapeRepId = w.Add("IFCSHAPEREPRESENTATION", $"{StepWriter.Ref(bodySubContextId)},'Body','SweptSolid',({StepWriter.Ref(solidGeomId)})"); @@ -2616,7 +2564,7 @@ private int WriteElementShape(StepWriter w, IfcElement element, int bodySubConte int solidGeomId = WriteRevolvedAreaSolid(w, element.RevolvedSolid); if (styleId.HasValue) { - w.Add("IFCSTYLEDITEM", $"{StepWriter.Ref(solidGeomId)},({StepWriter.Ref(styleId.Value)}),{StepWriter.Str(element.Material?.Name)}"); + w.Add("IFCSTYLEDITEM", $"{StepWriter.Ref(solidGeomId)},({StepWriter.Ref(styleId.Value)}),{StepWriter.Str(appearance?.Name)}"); } int shapeRepId = w.Add("IFCSHAPEREPRESENTATION", $"{StepWriter.Ref(bodySubContextId)},'Body','SweptSolid',({StepWriter.Ref(solidGeomId)})"); @@ -2629,7 +2577,7 @@ private int WriteElementShape(StepWriter w, IfcElement element, int bodySubConte int solidGeomId = WriteBooleanResult(w, element.BooleanResult, useTessellation); if (styleId.HasValue) { - w.Add("IFCSTYLEDITEM", $"{StepWriter.Ref(solidGeomId)},({StepWriter.Ref(styleId.Value)}),{StepWriter.Str(element.Material?.Name)}"); + w.Add("IFCSTYLEDITEM", $"{StepWriter.Ref(solidGeomId)},({StepWriter.Ref(styleId.Value)}),{StepWriter.Str(appearance?.Name)}"); } string repType = element.BooleanResult.IsClippingResult ? "Clipping" : "CSG"; int shapeRepId = w.Add("IFCSHAPEREPRESENTATION", @@ -2656,7 +2604,7 @@ private int WriteElementShape(StepWriter w, IfcElement element, int bodySubConte if (styleId.HasValue) { - w.Add("IFCSTYLEDITEM", $"{StepWriter.Ref(geomId)},({StepWriter.Ref(styleId.Value)}),{StepWriter.Str(element.Material?.Name)}"); + w.Add("IFCSTYLEDITEM", $"{StepWriter.Ref(geomId)},({StepWriter.Ref(styleId.Value)}),{StepWriter.Str(appearance?.Name)}"); } int shapeRepId = w.Add("IFCSHAPEREPRESENTATION", @@ -2919,13 +2867,10 @@ public void ChargeVertices(int count) var itemEnt = ctx.Step.Find(itemId); if (itemEnt is null) continue; - if (material is null && ctx.GeomToMaterialMap.TryGetValue(itemId, out var mat)) - { - material = mat; - } - - var mesh = ParseRepresentationItem(ctx, itemEnt, meshName, ref material, out var itemParametric); + var itemMaterial = ctx.GeomToMaterialMap.GetValueOrDefault(itemId); + var mesh = ParseRepresentationItem(ctx, itemEnt, meshName, ref itemMaterial, out var itemParametric); if (mesh is null) continue; + material ??= itemMaterial; ctx.ChargeVertices(mesh.Vertices.Count); if (parts.Count == 0) parametric = itemParametric; parts.Add(mesh); @@ -2974,6 +2919,8 @@ public void ChargeVertices(int count) { var boolRes = ParseBooleanResult(step, itemEnt, ctx.RadiansPerAngleUnit); if (boolRes is null) return null; + if (itemEnt.GetRef(1) is int firstOperand) + material ??= ctx.GeomToMaterialMap.GetValueOrDefault(firstOperand); parametric = new ParametricBody(null, null, boolRes); return boolRes.ToMesh(meshName); } @@ -3802,9 +3749,11 @@ private static int WriteMeshFacetedBrep(StepWriter w, IReadOnlyList return w.Add("IFCFACETEDBREP", StepWriter.Ref(shellId)); } - private static int GetOrCreateSurfaceStyle(StepWriter w, IfcMaterial mat, Dictionary cache) + private readonly record struct SurfaceStyleKey(string Name, double R, double G, double B, double Alpha); + + private int GetOrCreateSurfaceStyle(StepWriter w, IfcMaterial mat, Dictionary cache) { - string key = $"{mat.Name}_{mat.R:F2}_{mat.G:F2}_{mat.B:F2}"; + var key = new SurfaceStyleKey(mat.Name, mat.R, mat.G, mat.B, mat.Alpha); if (cache.TryGetValue(key, out int existingId)) { return existingId; @@ -3812,10 +3761,15 @@ private static int GetOrCreateSurfaceStyle(StepWriter w, IfcMaterial mat, Dictio int colorId = w.Add("IFCCOLOURRGB", $"$,{StepWriter.Real(mat.R)},{StepWriter.Real(mat.G)},{StepWriter.Real(mat.B)}"); - int shadingId = w.Add("IFCSURFACESTYLESHADING", StepWriter.Ref(colorId)); + string colour = StepWriter.Ref(colorId); + int shadingId = mat.Alpha == 1.0 + ? w.Add("IFCSURFACESTYLESHADING", Schema == IfcSchema.Ifc2x3 ? colour : $"{colour},$") + : w.Add("IFCSURFACESTYLERENDERING", $"{colour},{StepWriter.Real(1.0 - mat.Alpha)},$,$,$,$,$,$,.NOTDEFINED."); int styleId = w.Add("IFCSURFACESTYLE", $"{StepWriter.Str(mat.Name)},.BOTH.,({StepWriter.Ref(shadingId)})"); + if (Schema == IfcSchema.Ifc2x3) + styleId = w.Add("IFCPRESENTATIONSTYLEASSIGNMENT", $"({StepWriter.Ref(styleId)})"); cache[key] = styleId; return styleId; } diff --git a/src/IfcIO/Model/IfcModelTypes.cs b/src/IfcIO/Model/IfcModelTypes.cs index c4fa521..36ad8bf 100644 --- a/src/IfcIO/Model/IfcModelTypes.cs +++ b/src/IfcIO/Model/IfcModelTypes.cs @@ -348,7 +348,12 @@ public class IfcElement public IfcExtrudedAreaSolid? Solid { get; set; } public IfcRevolvedAreaSolid? RevolvedSolid { get; set; } public IfcBooleanResult? BooleanResult { get; set; } - public IfcMaterial? Material { get; set; } + private IfcMaterial? _material; + /// The assigned material, or the surface style when no material is assigned. + public IfcMaterial? Material { get => _material ?? SurfaceMaterial; set => _material = value; } + /// Explicit visual appearance, separate from the assigned construction material. + public IfcMaterial? SurfaceMaterial { get; set; } + internal IfcMaterial? AssignedMaterial => _material; public IfcMaterialLayerSetUsage? MaterialLayerSet { get; set; } public IfcMaterialProfileSetUsage? MaterialProfileSet { get; set; } public List Ports { get; } = []; @@ -361,6 +366,15 @@ public class IfcElement /// public IfcMesh? GetEffectiveMesh() => Mesh ?? BooleanResult?.ToMesh() ?? Solid?.ToMesh() ?? RevolvedSolid?.ToMesh(); + /// Gets the appearance of the element. An explicit style takes precedence over the material. + public IfcMaterial? GetEffectiveMaterial() + { + if ((SurfaceMaterial ?? _material) is { } material) return material; + if (MaterialLayerSet?.ForLayerSet.Layers is { Count: 1 } layers) return layers[0].Material; + if (MaterialProfileSet?.ForProfileSet.MaterialProfiles is { Count: 1 } profiles) return profiles[0].Material; + return null; + } + public IfcPropertySet GetOrCreatePropertySet(string name) { var existing = PropertySets.Find(p => p.Name.Equals(name, StringComparison.OrdinalIgnoreCase)); diff --git a/src/IfcIO/Patch/IfcPatch.cs b/src/IfcIO/Patch/IfcPatch.cs index 1cff9db..0898aa7 100644 --- a/src/IfcIO/Patch/IfcPatch.cs +++ b/src/IfcIO/Patch/IfcPatch.cs @@ -301,7 +301,8 @@ private static IfcElement CloneElement(IfcElement source, int newId) GlobalId = source.GlobalId ?? Guid.NewGuid().ToString("N")[..22], Tag = source.Tag, TypeProduct = source.TypeProduct, - Material = source.Material, + Material = source.AssignedMaterial, + SurfaceMaterial = source.SurfaceMaterial, Mesh = source.Mesh is not null ? IfcMesh.Create( newId, source.Mesh.Name, diff --git a/src/IfcIO/Validation/Ids/IfcIdsValidator.cs b/src/IfcIO/Validation/Ids/IfcIdsValidator.cs index 146bfc7..247d403 100644 --- a/src/IfcIO/Validation/Ids/IfcIdsValidator.cs +++ b/src/IfcIO/Validation/Ids/IfcIdsValidator.cs @@ -154,7 +154,7 @@ private static List FindApplicableElements(List elements foreach (var me in matElems) { string? matVal = GetFacetValue(me.Elements().FirstOrDefault(e => e.Name.LocalName.Equals("value", StringComparison.OrdinalIgnoreCase))); - if (elem.Material is not null && (string.IsNullOrEmpty(matVal) || elem.Material.Name.Contains(matVal, StringComparison.OrdinalIgnoreCase))) + if (elem.AssignedMaterial is { } material && (string.IsNullOrEmpty(matVal) || material.Name.Contains(matVal, StringComparison.OrdinalIgnoreCase))) { matchesMat = true; break; @@ -211,7 +211,7 @@ private static void EvaluateRequirements(IfcElement elem, string specName, XElem if (minOccurs == "0") continue; string? expectedMat = GetFacetValue(mr.Elements().FirstOrDefault(e => e.Name.LocalName.Equals("value", StringComparison.OrdinalIgnoreCase))); - if (elem.Material is null) + if (elem.AssignedMaterial is not { } material) { failures.Add(new IfcIdsFailure { @@ -224,7 +224,7 @@ private static void EvaluateRequirements(IfcElement elem, string specName, XElem Message = $"Element lacks required material assignment (expected '{expectedMat ?? "Any"}')", }); } - else if (!string.IsNullOrEmpty(expectedMat) && !elem.Material.Name.Contains(expectedMat, StringComparison.OrdinalIgnoreCase)) + else if (!string.IsNullOrEmpty(expectedMat) && !material.Name.Contains(expectedMat, StringComparison.OrdinalIgnoreCase)) { failures.Add(new IfcIdsFailure { @@ -234,7 +234,7 @@ private static void EvaluateRequirements(IfcElement elem, string specName, XElem ElementName = elem.Name, ElementType = elem.IfcType, FacetType = "Material", - Message = $"Material '{elem.Material.Name}' does not match required '{expectedMat}'", + Message = $"Material '{material.Name}' does not match required '{expectedMat}'", }); } } diff --git a/tests/IfcIO.Scene.Tests/IfcSceneReaderTests.cs b/tests/IfcIO.Scene.Tests/IfcSceneReaderTests.cs index 373467b..7df9302 100644 --- a/tests/IfcIO.Scene.Tests/IfcSceneReaderTests.cs +++ b/tests/IfcIO.Scene.Tests/IfcSceneReaderTests.cs @@ -194,6 +194,24 @@ public void Read_Storeys_BecomeLevelsAndTreeNodes() }); } + [Fact] + public void Read_PreservesWrappedIfc2x3ColourAndTransparencyInTheScene() + { + const string styledFitting = """ + #500=IFCCOLOURRGB($,0.2,0.4,0.8); + #501=IFCSURFACESTYLERENDERING(#500,0.25,$,$,$,$,$,$,.NOTDEFINED.); + #502=IFCSURFACESTYLE('Blue glass',.BOTH.,(#501)); + #503=IFCPRESENTATIONSTYLEASSIGNMENT((#502)); + #504=IFCSTYLEDITEM(#306,(#503),$); + """; + var scene = Valid(Read(OpenText(PlacedIfc(Millimetre, styledFitting)))).Document; + var material = Assert.Single(scene.Materials, candidate => candidate.Name == "Blue glass"); + + Assert.Equal(new RgbaColor(51, 102, 204, 191), material.Color); + Assert.Equal(material.Id, InstanceOf(scene, 300).MaterialId); + Assert.NotEqual(material.Id, InstanceOf(scene, 310).MaterialId); + } + [Fact] public void Read_TypeObjectsAndLiningProperties_AreNotElements() { diff --git a/tests/IfcIO.Tests/SurfaceStyleTests.cs b/tests/IfcIO.Tests/SurfaceStyleTests.cs new file mode 100644 index 0000000..cf43b93 --- /dev/null +++ b/tests/IfcIO.Tests/SurfaceStyleTests.cs @@ -0,0 +1,199 @@ +using System.Xml.Linq; +using IfcIO.Core; +using Xunit; + +namespace IfcIO.Tests; + +public sealed class SurfaceStyleTests +{ + [Theory] + [InlineData("IFC2X3", true, true, 0.75)] + [InlineData("IFC2X3", true, false, 1.0)] + [InlineData("IFC2X3", false, false, 1.0)] + [InlineData("IFC2X3", false, true, 0.75)] + [InlineData("IFC4", false, true, 0.75)] + [InlineData("IFC4", false, false, 0.75)] + public void Open_ReadsDirectAndWrappedSurfaceStyles(string schema, bool wrapped, bool rendering, double alpha) + { + var model = IfcModel.Open(new StringReader(StyledWall(schema, wrapped, rendering, + itemStyle: true, materialStyle: false, associateMaterial: false))); + + var wall = Assert.Single(model.AllElements); + Assert.NotNull(wall.Mesh); + Assert.NotNull(wall.Material); + Assert.Equal("Surface colour", wall.Material.Name); + Assert.Equal(0.2, wall.Material.R); + Assert.Equal(0.4, wall.Material.G); + Assert.Equal(0.8, wall.Material.B); + Assert.Equal(alpha, wall.Material.Alpha); + } + + [Fact] + public void Open_GeometryStyleTakesPrecedenceOverAColouredMaterialAssociation() + { + var model = IfcModel.Open(new StringReader(StyledWall("IFC2X3", wrapped: true, rendering: true, itemStyle: true, materialStyle: true))); + + var wall = Assert.Single(model.AllElements); + Assert.Equal("Physical material", wall.Material!.Name); + Assert.Equal("Surface colour", wall.GetEffectiveMaterial()!.Name); + Assert.Equal(0.2, wall.GetEffectiveMaterial()!.R); + var material = Assert.Single(model.Materials, candidate => candidate.Name == "Physical material"); + Assert.Equal(0.9, material.R); + Assert.Equal(0.6, material.Alpha, 8); + } + + [Fact] + public void Open_UsesTheMaterialDefinitionRepresentationAsAFallback() + { + var model = IfcModel.Open(new StringReader(StyledWall("IFC2X3", wrapped: true, rendering: true, itemStyle: false, materialStyle: true))); + + var material = Assert.Single(model.AllElements).Material; + Assert.NotNull(material); + Assert.Equal("Physical material", material.Name); + Assert.Equal(0.9, material.R); + Assert.Equal(0.3, material.G); + Assert.Equal(0.1, material.B); + Assert.Equal(0.6, material.Alpha, 8); + } + + [Fact] + public void Open_PlainMaterialAssociationRemainsAvailableWithoutAnyStyle() + { + var model = IfcModel.Open(new StringReader(StyledWall("IFC2X3", wrapped: false, rendering: false, itemStyle: false, materialStyle: false))); + + var material = Assert.Single(model.AllElements).Material; + Assert.NotNull(material); + Assert.Equal("Physical material", material.Name); + Assert.Equal(0.8, material.R); + Assert.Equal(1.0, material.Alpha); + } + + [Fact] + public void Open_DoesNotBorrowAnUnrelatedStyleWithTheSameName() + { + var input = StyledWall("IFC2X3", wrapped: true, rendering: true, itemStyle: false, materialStyle: false) + .Replace("IFCMATERIAL('Physical material')", "IFCMATERIAL('Surface colour')", StringComparison.Ordinal); + var model = IfcModel.Open(new StringReader(input)); + + var material = Assert.Single(model.AllElements).Material; + Assert.NotNull(material); + Assert.Equal(0.8, material.R); + Assert.Equal(1.0, material.Alpha); + } + + [Fact] + public void SaveAndOpen_KeepsPhysicalMaterialAndVisualStyleSeparate() + { + var model = IfcModel.Open(new StringReader(StyledWall("IFC2X3", wrapped: true, rendering: true, + itemStyle: true, materialStyle: true))); + var specification = XDocument.Parse(""" + + + + IFCWALL + Physical material + + + + """); + + for (int pass = 0; pass < 3; pass++) + { + Assert.True(model.ValidateIds(specification).IsPassed); + var step = model.ToStepString(); + Assert.Single(StepReader.Read(new StringReader(step)).OfType("IFCMATERIAL")); + model = IfcModel.Open(new StringReader(step)); + var wall = Assert.Single(model.AllElements); + Assert.Equal("Physical material", wall.Material!.Name); + Assert.Equal(0.6, wall.Material.Alpha, 8); + var visual = wall.GetEffectiveMaterial(); + Assert.NotNull(visual); + Assert.Equal("Surface colour", visual.Name); + Assert.Equal(0.75, visual.Alpha); + } + } + + [Theory] + [InlineData(false, "Surface colour")] + [InlineData(true, "Material colour")] + public void Open_UsesTheStyleOfTheClippingResultBeforeTheFirstOperand(bool styleResult, string expectedStyle) + { + const string clipping = """ + #50=IFCBOOLEANCLIPPINGRESULT(.DIFFERENCE.,#22,#51); + #51=IFCHALFSPACESOLID(#52,.T.); + #52=IFCPLANE(#53); + #53=IFCAXIS2PLACEMENT3D(#54,$,$); + #54=IFCCARTESIANPOINT((0.,0.,5.)); + """; + string extra = clipping + (styleResult ? "\n#55=IFCSTYLEDITEM(#50,(#45),$);" : ""); + string input = StyledWall("IFC2X3", wrapped: true, rendering: true, itemStyle: true, materialStyle: true, extra: extra) + .Replace("'SweptSolid',(#22)", "'Clipping',(#50)", StringComparison.Ordinal); + var wall = Assert.Single(IfcModel.Open(new StringReader(input)).AllElements); + + Assert.NotNull(wall.Mesh); + Assert.Equal(expectedStyle, wall.GetEffectiveMaterial()!.Name); + } + + [Fact] + public void Open_SingleLayerMaterialProvidesAnAppearanceWhenNoGeometryStyleExists() + { + const string layer = """ + #50=IFCMATERIALLAYER(#40,2.,$); + #51=IFCMATERIALLAYERSET((#50),'Single layer'); + #52=IFCMATERIALLAYERSETUSAGE(#51,.AXIS2.,.POSITIVE.,0.); + """; + var input = StyledWall("IFC2X3", wrapped: true, rendering: true, itemStyle: false, materialStyle: true, extra: layer) + .Replace("(#2),#40);", "(#2),#52);", StringComparison.Ordinal); + var wall = Assert.Single(IfcModel.Open(new StringReader(input)).AllElements); + + Assert.NotNull(wall.MaterialLayerSet); + Assert.Null(wall.SurfaceMaterial); + Assert.Equal(0.9, wall.GetEffectiveMaterial()!.R); + } + + private static string StyledWall(string schema, bool wrapped, bool rendering, bool itemStyle, bool materialStyle, + bool associateMaterial = true, string extra = "") + { + string assignments = wrapped ? "#33=IFCPRESENTATIONSTYLEASSIGNMENT((#30));" : ""; + string shading = rendering + ? "#31=IFCSURFACESTYLERENDERING(#32,0.25,$,$,$,$,$,$,.NOTDEFINED.);" + : schema == "IFC4" ? "#31=IFCSURFACESTYLESHADING(#32,0.25);" : "#31=IFCSURFACESTYLESHADING(#32);"; + string materialRepresentations = materialStyle ? """ + #42=IFCMATERIALDEFINITIONREPRESENTATION($,$,(#43),#40); + #43=IFCSTYLEDREPRESENTATION(#10,'Style','Material',(#44)); + #44=IFCSTYLEDITEM($,(#45),$); + #45=IFCPRESENTATIONSTYLEASSIGNMENT((#46)); + #46=IFCSURFACESTYLE('Material colour',.BOTH.,(#47)); + #47=IFCSURFACESTYLERENDERING(#48,0.4,$,$,$,$,$,$,.NOTDEFINED.); + #48=IFCCOLOURRGB($,0.9,0.3,0.1); + """ : ""; + return $""" + ISO-10303-21; + HEADER; FILE_SCHEMA(('{schema}')); ENDSEC; + DATA; + #1=IFCPROJECT('01vctVUKr0kugbFTf53O9L',$,'Colours',$,$,$,$,(#10),$); + #2=IFCWALL('02vctVUKr0kugbFTf53O9L',$,'Wall',$,$,$,#20,${(schema == "IFC4" ? ",$" : "")}); + #10=IFCGEOMETRICREPRESENTATIONCONTEXT($,'Model',3,1.E-05,#11,$); + #11=IFCAXIS2PLACEMENT3D(#12,$,$); + #12=IFCCARTESIANPOINT((0.,0.,0.)); + #20=IFCPRODUCTDEFINITIONSHAPE($,$,(#21)); + #21=IFCSHAPEREPRESENTATION(#10,'Body','SweptSolid',(#22)); + #22=IFCEXTRUDEDAREASOLID(#23,#11,#24,10.); + #23=IFCRECTANGLEPROFILEDEF(.AREA.,$,#25,2.,3.); + #24=IFCDIRECTION((0.,0.,1.)); + #25=IFCAXIS2PLACEMENT2D(#26,$); + #26=IFCCARTESIANPOINT((0.,0.)); + #30=IFCSURFACESTYLE('Surface colour',.BOTH.,(#31)); + {shading} + #32=IFCCOLOURRGB($,0.2,0.4,0.8); + {assignments} + {(itemStyle ? $"#34=IFCSTYLEDITEM(#22,(#{(wrapped ? 33 : 30)}),$);" : "")} + #40=IFCMATERIAL('Physical material'{(schema == "IFC4" ? ",$,$" : "")}); + {(associateMaterial ? "#41=IFCRELASSOCIATESMATERIAL('03vctVUKr0kugbFTf53O9L',$,$,$,(#2),#40);" : "")} + {materialRepresentations} + {extra} + ENDSEC; + END-ISO-10303-21; + """; + } +}