diff --git a/README.md b/README.md index bf3724f1..f78661f1 100644 --- a/README.md +++ b/README.md @@ -61,10 +61,11 @@ Export full JSON, including every parameter and geometry: rvtio project.rvt project.full.json --json-full ``` -Export IFC with Revit parameters as property sets: +Export IFC with Revit parameters as property sets (optionally converting values to IFC/SI units and using display names): ```sh rvtio project.rvt project.parameters.ifc --ifc-revit-parameters +rvtio project.rvt project.parameters.ifc --ifc-revit-parameters --ifc-revit-parameter-units ifc --ifc-revit-parameter-names display ``` Export IFC4 (`ReferenceView_V1.2` by default, or `DesignTransferView_V1.0`) independently of `Current`/`Legacy` profiles, or drive exports through a shared JSON configuration preset (`--ifc-preset`, `--ifc-config`, `--ifc-save-config`, `--ifc-capabilities`): diff --git a/docs/ifc-export.md b/docs/ifc-export.md index fbf4e3b5..1b0c6d7e 100644 --- a/docs/ifc-export.md +++ b/docs/ifc-export.md @@ -113,6 +113,8 @@ Calling `configuration.Validate()`, `configuration.Resolve()`, or running an exp | `propertySets.exportIfcCommonPropertySets` | `SchemaOrViewScoped` | `true` | `true` | Standard `Pset_*Common` property sets are always emitted. | | `propertySets.exportRevitPropertySets` | `Supported` | `true`, `false` | `false` | Opt-in export of Revit parameters. | | `propertySets.groupRevitParametersByGroup` | `Supported` | `true`, `false` | `false` | Groups Revit parameter sets per group (implies `exportRevitPropertySets`). | +| `propertySets.revitParameterUnits` | `Supported` | `internal`, `ifc` | `internal` (untyped) | Converts length, area, volume, and angle to IFC units and other physical specs to SI units when `ifc`, and assigns the project unit of each converted measure. A parameter whose spec neither the file nor the API definitions give keeps its stored number as `IfcReal`; `IfcMonetaryMeasure` has no currency unit. | +| `propertySets.revitParameterNames` | `Supported` | `builtin`, `display` | `builtin` (untyped) | Uses parameter display names (with `BuiltInParameter` in `Description`) and resolves user parameter names when `display`. Property names are unique within a set: when two parameters share a name, each gets ` [parameter id]` appended (also with an explicit `builtin`). The CLI options for names and units turn the Revit property sets on, with `--ifc-config` too. | | `propertySets.exportSchedulesAsPropertySets` | `Unsupported` | `false` | `false` | Schedule Psets are not implemented; `true` fails validation. | | `mappings.useRevitIfcExportAsParameters` | `Supported` | `true` | `true` | Reads `IfcExportAs` / `IfcExportType`; `false` fails validation. | | `mappings.familyMappingTablePath` | `Unsupported` | `null` | `null` | External mapping files fail validation if non-empty. | diff --git a/src/RvtIO.Cli/IfcConfigurationOptions.cs b/src/RvtIO.Cli/IfcConfigurationOptions.cs index 13814268..3323b8b9 100644 --- a/src/RvtIO.Cli/IfcConfigurationOptions.cs +++ b/src/RvtIO.Cli/IfcConfigurationOptions.cs @@ -11,7 +11,9 @@ internal sealed record IfcCliOptions( string? ConfigPath, string? SaveConfigPath, bool NoSpaces, - bool ShowCapabilities); + bool ShowCapabilities, + IfcRevitParameterUnits? RevitParameterUnits, + IfcRevitParameterNames? RevitParameterNames); internal static class IfcConfigurationOptions { @@ -23,10 +25,12 @@ internal static class IfcConfigurationOptions public const string SaveConfigOption = "--ifc-save-config"; public const string NoSpacesOption = "--ifc-no-spaces"; public const string CapabilitiesOption = "--ifc-capabilities"; + public const string RevitParameterUnitsOption = "--ifc-revit-parameter-units"; + public const string RevitParameterNamesOption = "--ifc-revit-parameter-names"; public static bool TryParse(string[] args, out IfcCliOptions options, out string? error) { - options = new IfcCliOptions(null, null, null, null, null, false, false); + options = new IfcCliOptions(null, null, null, null, null, false, false, null, null); error = null; IfcSchema? schema = null; @@ -36,6 +40,8 @@ public static bool TryParse(string[] args, out IfcCliOptions options, out string string? saveConfigPath = null; bool noSpaces = false; bool showCapabilities = false; + IfcRevitParameterUnits? revitParameterUnits = null; + IfcRevitParameterNames? revitParameterNames = null; string? ReadSingleValue(string flag, ref int index, ref bool seen) { @@ -48,6 +54,7 @@ public static bool TryParse(string[] args, out IfcCliOptions options, out string } bool seenSchema = false, seenView = false, seenPreset = false, seenConfig = false, seenSaveConfig = false; + bool seenParamUnits = false, seenParamNames = false; for (int i = 0; i < args.Length; i++) { switch (args[i]) @@ -114,10 +121,33 @@ public static bool TryParse(string[] args, out IfcCliOptions options, out string case CapabilitiesOption: showCapabilities = true; break; + case RevitParameterUnitsOption: + { + string? raw = ReadSingleValue(RevitParameterUnitsOption, ref i, ref seenParamUnits); + if (raw is null || !IfcExportOptionParser.TryParseRevitParameterUnits(raw, out var parsed)) + { + error = $"{RevitParameterUnitsOption} requires a supported unit system: ifc, internal."; + return false; + } + revitParameterUnits = parsed; + break; + } + case RevitParameterNamesOption: + { + string? raw = ReadSingleValue(RevitParameterNamesOption, ref i, ref seenParamNames); + if (raw is null || !IfcExportOptionParser.TryParseRevitParameterNames(raw, out var parsed)) + { + error = $"{RevitParameterNamesOption} requires a supported naming mode: display, builtin."; + return false; + } + revitParameterNames = parsed; + break; + } } } - options = new IfcCliOptions(schema, modelView, preset, configPath, saveConfigPath, noSpaces, showCapabilities); + options = new IfcCliOptions(schema, modelView, preset, configPath, saveConfigPath, noSpaces, showCapabilities, + revitParameterUnits, revitParameterNames); return true; } @@ -210,8 +240,12 @@ public static bool TryBuildConfiguration( }, PropertySets = new IfcPropertySetConfiguration { - ExportRevitPropertySets = revitParameters || revitParameterGroups ? true : null, + ExportRevitPropertySets = revitParameters || revitParameterGroups + || cliOptions.RevitParameterUnits.HasValue || cliOptions.RevitParameterNames.HasValue + ? true : null, GroupRevitParametersByGroup = revitParameterGroups ? true : null, + RevitParameterUnits = cliOptions.RevitParameterUnits, + RevitParameterNames = cliOptions.RevitParameterNames, }, }; diff --git a/src/RvtIO.Cli/Program.cs b/src/RvtIO.Cli/Program.cs index e9094abe..7245cf27 100644 --- a/src/RvtIO.Cli/Program.cs +++ b/src/RvtIO.Cli/Program.cs @@ -28,6 +28,13 @@ Diagnostics go to standard error. --ifc-profile IFC output profile (default: current) --ifc-revit-parameters write the Revit parameters as IFC property sets --ifc-revit-parameter-groups write them as one property set per parameter group (implies --ifc-revit-parameters) + --ifc-revit-parameter-units + unit system for Revit parameters: ifc (IFC length/area/volume/angle units and SI + units for other physical specs; implies --ifc-revit-parameters) or internal (default) + --ifc-revit-parameter-names + property naming for Revit parameters: display (display names with BuiltInParameter + in Description, user parameter names instead of IDs; implies --ifc-revit-parameters) + or builtin (default) --ifc-no-base-quantities leave out the base quantity sets --ifc-opening-legacy-axes name the sides of the opening of a door or window by the frame they are measured in (Height along the wall, Width vertical), as earlier releases did; by default the opening has the Width @@ -131,6 +138,8 @@ apply an ordered batch of supported parameter assignments and clears atomically RvtIO.Cli.IfcConfigurationOptions.PresetOption, RvtIO.Cli.IfcConfigurationOptions.ConfigOption, RvtIO.Cli.IfcConfigurationOptions.SaveConfigOption, + RvtIO.Cli.IfcConfigurationOptions.RevitParameterUnitsOption, + RvtIO.Cli.IfcConfigurationOptions.RevitParameterNamesOption, RvtIO.Cli.IfcLengthUnitOption.Name, RvtIO.Cli.IfcTimestampOption.Name, "--json-class-prefix", "--revit-localization", "--inspect", "--diag-dump", "--find-str", "--sketch-owner-dump", "--dev-external-dump", "--dev-external-dump-prefix", "--dev-candidates", "--dev-trace", "--dev-facts", "--dev-fact-names", "--dev-user-params", "--dev-collisions", "--dev-solids", "--dev-native", "--class-census", "--episode-check", @@ -388,9 +397,9 @@ static bool IsNonJsonPositionalExtension(string path) => Console.Error.WriteLine("--ifc-length-unit requires IFC output."); return 1; } - if ((cliIfcOptions.Schema.HasValue || cliIfcOptions.ModelView.HasValue || cliIfcOptions.Preset.HasValue || cliIfcOptions.ConfigPath != null || cliIfcOptions.NoSpaces) && !hasIfcOutput && cliIfcOptions.SaveConfigPath == null) + if ((cliIfcOptions.Schema.HasValue || cliIfcOptions.ModelView.HasValue || cliIfcOptions.Preset.HasValue || cliIfcOptions.ConfigPath != null || cliIfcOptions.NoSpaces || cliIfcOptions.RevitParameterUnits.HasValue || cliIfcOptions.RevitParameterNames.HasValue) && !hasIfcOutput && cliIfcOptions.SaveConfigPath == null) { - Console.Error.WriteLine("IFC schema, model view, preset, config, and space options require IFC output."); + Console.Error.WriteLine("IFC schema, model view, preset, config, Revit parameter formatting, and space options require IFC output."); return 1; } diff --git a/src/RvtIO/Ifc/IfcExportConfiguration.cs b/src/RvtIO/Ifc/IfcExportConfiguration.cs index f8296b36..166ca736 100644 --- a/src/RvtIO/Ifc/IfcExportConfiguration.cs +++ b/src/RvtIO/Ifc/IfcExportConfiguration.cs @@ -83,6 +83,26 @@ public enum IfcRoomPhaseScope SpecificPhase, } +/// Unit system used when exporting Revit parameters to IFC property sets. +public enum IfcRevitParameterUnits +{ + /// Preserve Revit internal values as raw reals (feet, radians, etc.). + Internal, + + /// Convert length, area, volume, and angle parameters to the IFC file units, and other physical spec types to SI units. + Ifc, +} + +/// Property naming convention used when exporting Revit parameters to IFC property sets. +public enum IfcRevitParameterNames +{ + /// Use the built-in parameter enum name or stored definition name. + BuiltIn, + + /// Use each parameter's display name (and place the built-in name in Description). + Display, +} + /// Coordinate frame used for opening Width and Height base quantities. public enum IfcOpeningQuantityFrame { @@ -282,6 +302,12 @@ public sealed record IfcPropertySetConfiguration /// Group Revit parameters into one property set per Revit parameter group (implies ). public bool? GroupRevitParametersByGroup { get; init; } + /// Unit system used when exporting Revit parameters (Internal or Ifc). + public IfcRevitParameterUnits? RevitParameterUnits { get; init; } + + /// Property naming convention used when exporting Revit parameters (BuiltIn or Display). + public IfcRevitParameterNames? RevitParameterNames { get; init; } + /// Export Revit schedules as custom property sets (not implemented; must remain null/false). public bool? ExportSchedulesAsPropertySets { get; init; } } @@ -359,6 +385,8 @@ private static JsonSerializerOptions CreateSerializerOptions() options.Converters.Add(new FlexibleEnumJsonConverter(IfcExportOptionParser.TryParsePreset, IfcExportOptionParser.FormatPreset)); options.Converters.Add(new FlexibleEnumJsonConverter(IfcExportOptionParser.TryParseUnitFamily, IfcExportOptionParser.FormatUnitFamily)); options.Converters.Add(new FlexibleEnumJsonConverter(IfcExportOptionParser.TryParseProfile, IfcExportOptionParser.FormatProfile)); + options.Converters.Add(new FlexibleEnumJsonConverter(IfcExportOptionParser.TryParseRevitParameterUnits, IfcExportOptionParser.FormatRevitParameterUnits)); + options.Converters.Add(new FlexibleEnumJsonConverter(IfcExportOptionParser.TryParseRevitParameterNames, IfcExportOptionParser.FormatRevitParameterNames)); options.Converters.Add(new JsonStringEnumConverter(JsonNamingPolicy.CamelCase, allowIntegerValues: false)); return options; } @@ -561,6 +589,8 @@ public IfcExportConfiguration Merge(IfcExportConfiguration? overrides) ExportIfcCommonPropertySets = overrides.PropertySets.ExportIfcCommonPropertySets ?? PropertySets.ExportIfcCommonPropertySets, ExportRevitPropertySets = overrides.PropertySets.ExportRevitPropertySets ?? PropertySets.ExportRevitPropertySets, GroupRevitParametersByGroup = overrides.PropertySets.GroupRevitParametersByGroup ?? PropertySets.GroupRevitParametersByGroup, + RevitParameterUnits = overrides.PropertySets.RevitParameterUnits ?? PropertySets.RevitParameterUnits, + RevitParameterNames = overrides.PropertySets.RevitParameterNames ?? PropertySets.RevitParameterNames, ExportSchedulesAsPropertySets = overrides.PropertySets.ExportSchedulesAsPropertySets ?? PropertySets.ExportSchedulesAsPropertySets, }, Mappings = new IfcMappingConfiguration @@ -692,6 +722,16 @@ private ResolvedIfcExportConfiguration ResolveCore(bool throwOnError) ValidatePhase(effective.Phases, diagnostics); ValidateUnsupportedFlags(effective, diagnostics); + if (effective.PropertySets.RevitParameterUnits is { } paramUnits && !Enum.IsDefined(paramUnits)) + diagnostics.Add(new IfcConfigurationDiagnostic( + "invalid-revit-parameter-units", IfcConfigurationDiagnosticSeverity.Error, "propertySets.revitParameterUnits", + $"Unsupported Revit parameter units '{paramUnits}'. Supported values: Internal, Ifc.")); + + if (effective.PropertySets.RevitParameterNames is { } paramNames && !Enum.IsDefined(paramNames)) + diagnostics.Add(new IfcConfigurationDiagnostic( + "invalid-revit-parameter-names", IfcConfigurationDiagnosticSeverity.Error, "propertySets.revitParameterNames", + $"Unsupported Revit parameter naming '{paramNames}'. Supported values: BuiltIn, Display.")); + bool revitGroups = effective.PropertySets.GroupRevitParametersByGroup ?? false; bool revitPsets = (effective.PropertySets.ExportRevitPropertySets ?? false) || revitGroups; @@ -718,6 +758,8 @@ private ResolvedIfcExportConfiguration ResolveCore(bool throwOnError) ExportIfcCommonPropertySets = effective.PropertySets.ExportIfcCommonPropertySets ?? true, ExportRevitPropertySets = revitPsets, RevitParameterGroups = revitGroups, + RevitParameterUnits = effective.PropertySets.RevitParameterUnits, + RevitParameterNames = effective.PropertySets.RevitParameterNames, RespectExportToIfcParameter = effective.Scope.RespectExportToIfcParameter ?? true, UseRevitIfcExportAsParameters = effective.Mappings.UseRevitIfcExportAsParameters ?? true, Diagnostics = diagnostics, @@ -860,6 +902,10 @@ public sealed record ResolvedIfcExportConfiguration public bool ExportRevitPropertySets { get; init; } /// True when Revit parameter property sets are grouped per Revit parameter group. public bool RevitParameterGroups { get; init; } + /// Unit conversion mode for exported Revit parameters (null keeps mode default). + public IfcRevitParameterUnits? RevitParameterUnits { get; init; } + /// Property naming mode for exported Revit parameters (null keeps mode default). + public IfcRevitParameterNames? RevitParameterNames { get; init; } /// True when the Export to IFC parameter filters elements. public bool RespectExportToIfcParameter { get; init; } /// True when IfcExportAs/IfcExportType parameters override category mappings. @@ -929,6 +975,12 @@ public static class IfcExportCapabilities "true, false", "false", "Exports Revit instance and type parameters in IfcPropertySet entities."), new("propertySets.groupRevitParametersByGroup", "Property Sets", "Group Revit Parameters", IfcCapabilitySupportStatus.Supported, "true, false", "false", "Splits Revit parameters into one IfcPropertySet per parameter group (implies exportRevitPropertySets)."), + new("propertySets.revitParameterUnits", "Property Sets", "Revit Parameter Units", IfcCapabilitySupportStatus.Supported, + "internal, ifc", "internal (legacy/untyped) / length-area-volume-angle in grouped mode", + "Converts length, area, volume, and angle to IFC file units and other known physical specs to SI units when set to ifc."), + new("propertySets.revitParameterNames", "Property Sets", "Revit Parameter Names", IfcCapabilitySupportStatus.Supported, + "builtin, display", "builtin (or display in grouped mode)", + "Uses display names as property names (preserving BuiltInParameter in Description) and resolves user parameter names when set to display."), new("propertySets.exportSchedulesAsPropertySets", "Property Sets", "Revit Schedules as Psets", IfcCapabilitySupportStatus.Unsupported, "false (default)", "false", "Schedule-to-Pset export is not implemented; true fails validation."), new("mappings.useRevitIfcExportAsParameters", "Mappings", "IfcExportAs / IfcExportType", IfcCapabilitySupportStatus.Supported, @@ -1123,6 +1175,52 @@ public static bool TryParseUnitFamily(string? text, out IfcUnitFamily unit) IfcUnitFamily.Foot => "ft", _ => unit.ToString(), }; + + public static bool TryParseRevitParameterUnits(string? text, out IfcRevitParameterUnits units) + { + switch (text?.Trim().ToLowerInvariant()) + { + case "internal": + units = IfcRevitParameterUnits.Internal; + return true; + case "ifc": + units = IfcRevitParameterUnits.Ifc; + return true; + default: + units = default; + return false; + } + } + + public static string FormatRevitParameterUnits(IfcRevitParameterUnits units) => units switch + { + IfcRevitParameterUnits.Internal => "internal", + IfcRevitParameterUnits.Ifc => "ifc", + _ => units.ToString(), + }; + + public static bool TryParseRevitParameterNames(string? text, out IfcRevitParameterNames names) + { + switch (text?.Trim().ToLowerInvariant().Replace("-", "")) + { + case "builtin": + names = IfcRevitParameterNames.BuiltIn; + return true; + case "display": + names = IfcRevitParameterNames.Display; + return true; + default: + names = default; + return false; + } + } + + public static string FormatRevitParameterNames(IfcRevitParameterNames names) => names switch + { + IfcRevitParameterNames.BuiltIn => "builtin", + IfcRevitParameterNames.Display => "display", + _ => names.ToString(), + }; } internal sealed class FlexibleEnumJsonConverter : JsonConverter where T : struct, Enum diff --git a/src/RvtIO/Ifc/IfcExporter.PropertyValueCacheCurrent.cs b/src/RvtIO/Ifc/IfcExporter.PropertyValueCacheCurrent.cs index 1c983f72..8036950e 100644 --- a/src/RvtIO/Ifc/IfcExporter.PropertyValueCacheCurrent.cs +++ b/src/RvtIO/Ifc/IfcExporter.PropertyValueCacheCurrent.cs @@ -56,7 +56,7 @@ internal static int ApplyCurrentPropertyValueCache(StepWriter w) else if (type == "IFCPROPERTYSET") setIndexes.Add(i); } - var pooled = new Dictionary<(string Name, string Value), int>(); + var pooled = new Dictionary<(string Name, string Description, string Value), int>(); var taken = new HashSet(); var dropped = new HashSet(); foreach (int setIndex in setIndexes) @@ -78,9 +78,9 @@ internal static int ApplyCurrentPropertyValueCache(StepWriter w) int target = valueId; if (value.Length != 4 || CachesPropertyValueCurrent(value[2])) { - if (value.Length == 4 && !pooled.TryAdd((value[0], value[2]), valueId)) + if (value.Length == 4 && !pooled.TryAdd((value[0], value[1], value[2]), valueId)) { - target = pooled[(value[0], value[2])]; + target = pooled[(value[0], value[1], value[2])]; if (target != valueId) dropped.Add(valueId); } } diff --git a/src/RvtIO/Ifc/IfcExporter.RevitParameters.cs b/src/RvtIO/Ifc/IfcExporter.RevitParameters.cs new file mode 100644 index 00000000..603dfed3 --- /dev/null +++ b/src/RvtIO/Ifc/IfcExporter.RevitParameters.cs @@ -0,0 +1,419 @@ +using System.Collections.Frozen; +using System.Globalization; +using RvtIO.Compact; +using RvtIO.Lookup; +using RvtIO.Model; +using RvtIO.Parsing; + +namespace RvtIO.Ifc; + +public partial class IfcExporter +{ + private enum RevitSpecKind + { + Length, + Area, + Volume, + Angle, + SiMeasure, + } + + private readonly record struct SpecConversion(RevitSpecKind Kind, string MeasureName = "", int LengthExponent = 0); + + private static readonly FrozenDictionary SpecConversions = + new Dictionary(StringComparer.Ordinal) + { + // Length specs -> IFCLENGTHMEASURE(mm), then IfcLengthUnit.ToFamily scales to the file's length unit. + ["autodesk.spec.aec:length"] = new(RevitSpecKind.Length), + ["autodesk.spec.aec:sheetLength"] = new(RevitSpecKind.Length), + ["autodesk.spec.aec:decimalSheetLength"] = new(RevitSpecKind.Length), + ["autodesk.spec.aec:distance"] = new(RevitSpecKind.Length), + ["autodesk.spec.aec.electrical:cableTraySize"] = new(RevitSpecKind.Length), + ["autodesk.spec.aec.electrical:conduitSize"] = new(RevitSpecKind.Length), + ["autodesk.spec.aec.electrical:wireDiameter"] = new(RevitSpecKind.Length), + ["autodesk.spec.aec.hvac:ductInsulationThickness"] = new(RevitSpecKind.Length), + ["autodesk.spec.aec.hvac:ductLiningThickness"] = new(RevitSpecKind.Length), + ["autodesk.spec.aec.hvac:ductSize"] = new(RevitSpecKind.Length), + ["autodesk.spec.aec.hvac:roughness"] = new(RevitSpecKind.Length), + ["autodesk.spec.aec.piping:pipeInsulationThickness"] = new(RevitSpecKind.Length), + ["autodesk.spec.aec.piping:pipeSize"] = new(RevitSpecKind.Length), + ["autodesk.spec.aec.piping:pipeDimension"] = new(RevitSpecKind.Length), + ["autodesk.spec.aec.piping:roughness"] = new(RevitSpecKind.Length), + ["autodesk.spec.aec.structural:barDiameter"] = new(RevitSpecKind.Length), + ["autodesk.spec.aec.structural:crackWidth"] = new(RevitSpecKind.Length), + ["autodesk.spec.aec.structural:displacement"] = new(RevitSpecKind.Length), + ["autodesk.spec.aec.structural:reinforcementCover"] = new(RevitSpecKind.Length), + ["autodesk.spec.aec.structural:reinforcementLength"] = new(RevitSpecKind.Length), + ["autodesk.spec.aec.structural:reinforcementSpacing"] = new(RevitSpecKind.Length), + ["autodesk.spec.aec.structural:sectionDimension"] = new(RevitSpecKind.Length), + ["autodesk.spec.aec.structural:sectionProperty"] = new(RevitSpecKind.Length), + + // Area specs -> IFCAREAMEASURE(m^2), then IfcLengthUnit.ToFamily scales to the file's area unit. + ["autodesk.spec.aec:area"] = new(RevitSpecKind.Area), + ["autodesk.spec.aec.structural:crossSection"] = new(RevitSpecKind.Area), + ["autodesk.spec.aec.structural:sectionArea"] = new(RevitSpecKind.Area), + + // Volume specs -> IFCVOLUMEMEASURE(m^3), then IfcLengthUnit.ToFamily scales to the file's volume unit. + ["autodesk.spec.aec:volume"] = new(RevitSpecKind.Volume), + ["autodesk.spec.aec.piping:volume"] = new(RevitSpecKind.Volume), + ["autodesk.spec.aec.structural:reinforcementVolume"] = new(RevitSpecKind.Volume), + + // Angle specs -> IFCPLANEANGLEMEASURE(deg in Current, rad in Legacy). + ["autodesk.spec.aec:angle"] = new(RevitSpecKind.Angle), + ["autodesk.spec.aec:siteAngle"] = new(RevitSpecKind.Angle), + + // Physical specs converted to SI units (Revit internal units are SI except feet^L for length^L). + ["autodesk.spec.aec.structural:stress"] = new(RevitSpecKind.SiMeasure, "IFCPRESSUREMEASURE", -1), + ["autodesk.spec.aec.hvac:pressure"] = new(RevitSpecKind.SiMeasure, "IFCPRESSUREMEASURE", -1), + ["autodesk.spec.aec.piping:pressure"] = new(RevitSpecKind.SiMeasure, "IFCPRESSUREMEASURE", -1), + ["autodesk.spec.aec.structural:areaForce"] = new(RevitSpecKind.SiMeasure, "IFCPLANARFORCEMEASURE", -1), + ["autodesk.spec.aec.hvac:viscosity"] = new(RevitSpecKind.SiMeasure, "IFCDYNAMICVISCOSITYMEASURE", -1), + ["autodesk.spec.aec.piping:viscosity"] = new(RevitSpecKind.SiMeasure, "IFCDYNAMICVISCOSITYMEASURE", -1), + ["autodesk.spec.aec.energy:permeability"] = new(RevitSpecKind.SiMeasure, "IFCVAPORPERMEABILITYMEASURE", -1), + ["autodesk.spec.aec.structural:massPerUnitLength"] = new(RevitSpecKind.SiMeasure, "IFCMASSPERLENGTHMEASURE", -1), + ["autodesk.spec.aec.structural:momentScale"] = new(RevitSpecKind.SiMeasure, "IFCREAL", -1), + + ["autodesk.spec.aec.structural:force"] = new(RevitSpecKind.SiMeasure, "IFCFORCEMEASURE", 1), + ["autodesk.spec.aec.hvac:velocity"] = new(RevitSpecKind.SiMeasure, "IFCLINEARVELOCITYMEASURE", 1), + ["autodesk.spec.aec.piping:velocity"] = new(RevitSpecKind.SiMeasure, "IFCLINEARVELOCITYMEASURE", 1), + ["autodesk.spec.aec:speed"] = new(RevitSpecKind.SiMeasure, "IFCLINEARVELOCITYMEASURE", 1), + ["autodesk.spec.aec.energy:thermalConductivity"] = new(RevitSpecKind.SiMeasure, "IFCTHERMALCONDUCTIVITYMEASURE", 1), + ["autodesk.spec.aec.structural:linearMoment"] = new(RevitSpecKind.SiMeasure, "IFCLINEARMOMENTMEASURE", 1), + ["autodesk.spec.aec.hvac:airFlowDensity"] = new(RevitSpecKind.SiMeasure, "IFCREAL", 1), + ["autodesk.spec.aec.structural:reinforcementAreaPerUnitLength"] = new(RevitSpecKind.SiMeasure, "IFCREAL", 1), + ["autodesk.spec.aec.structural:surfaceAreaPerUnitLength"] = new(RevitSpecKind.SiMeasure, "IFCREAL", 1), + ["autodesk.spec.aec.structural:linearForceScale"] = new(RevitSpecKind.SiMeasure, "IFCREAL", 1), + + ["autodesk.spec.aec.electrical:power"] = new(RevitSpecKind.SiMeasure, "IFCPOWERMEASURE", 2), + ["autodesk.spec.aec.electrical:wattage"] = new(RevitSpecKind.SiMeasure, "IFCPOWERMEASURE", 2), + ["autodesk.spec.aec.hvac:coolingLoad"] = new(RevitSpecKind.SiMeasure, "IFCPOWERMEASURE", 2), + ["autodesk.spec.aec.hvac:heatingLoad"] = new(RevitSpecKind.SiMeasure, "IFCPOWERMEASURE", 2), + ["autodesk.spec.aec.hvac:heatGain"] = new(RevitSpecKind.SiMeasure, "IFCPOWERMEASURE", 2), + ["autodesk.spec.aec.electrical:apparentPower"] = new(RevitSpecKind.SiMeasure, "IFCREAL", 2), + ["autodesk.spec.aec.structural:areaForceScale"] = new(RevitSpecKind.SiMeasure, "IFCREAL", 2), + ["autodesk.spec.aec.electrical:potential"] = new(RevitSpecKind.SiMeasure, "IFCELECTRICVOLTAGEMEASURE", 2), + ["autodesk.spec.aec.energy:specificHeat"] = new(RevitSpecKind.SiMeasure, "IFCSPECIFICHEATCAPACITYMEASURE", 2), + ["autodesk.spec.aec.energy:specificHeatOfVaporization"] = new(RevitSpecKind.SiMeasure, "IFCHEATINGVALUEMEASURE", 2), + ["autodesk.spec.aec.structural:moment"] = new(RevitSpecKind.SiMeasure, "IFCTORQUEMEASURE", 2), + ["autodesk.spec.aec:energy"] = new(RevitSpecKind.SiMeasure, "IFCENERGYMEASURE", 2), + ["autodesk.spec.aec.structural:energy"] = new(RevitSpecKind.SiMeasure, "IFCENERGYMEASURE", 2), + + ["autodesk.spec.aec.electrical:illuminance"] = new(RevitSpecKind.SiMeasure, "IFCILLUMINANCEMEASURE", -2), + ["autodesk.spec.aec.electrical:efficacy"] = new(RevitSpecKind.SiMeasure, "IFCREAL", -2), + ["autodesk.spec.aec.hvac:friction"] = new(RevitSpecKind.SiMeasure, "IFCREAL", -2), + ["autodesk.spec.aec.piping:friction"] = new(RevitSpecKind.SiMeasure, "IFCREAL", -2), + ["autodesk.spec.aec.structural:unitWeight"] = new(RevitSpecKind.SiMeasure, "IFCREAL", -2), + ["autodesk.spec.aec.structural:massPerUnitArea"] = new(RevitSpecKind.SiMeasure, "IFCREAL", -2), + + ["autodesk.spec.aec.hvac:airFlow"] = new(RevitSpecKind.SiMeasure, "IFCVOLUMETRICFLOWRATEMEASURE", 3), + ["autodesk.spec.aec.piping:flow"] = new(RevitSpecKind.SiMeasure, "IFCVOLUMETRICFLOWRATEMEASURE", 3), + ["autodesk.spec.aec.structural:sectionModulus"] = new(RevitSpecKind.SiMeasure, "IFCSECTIONMODULUSMEASURE", 3), + ["autodesk.spec.aec.electrical:resistivity"] = new(RevitSpecKind.SiMeasure, "IFCREAL", 3), + + ["autodesk.spec.aec:massDensity"] = new(RevitSpecKind.SiMeasure, "IFCMASSDENSITYMEASURE", -3), + ["autodesk.spec.aec.piping:density"] = new(RevitSpecKind.SiMeasure, "IFCMASSDENSITYMEASURE", -3), + + ["autodesk.spec.aec.structural:momentOfInertia"] = new(RevitSpecKind.SiMeasure, "IFCMOMENTOFINERTIAMEASURE", 4), + ["autodesk.spec.aec.structural:warpingConstant"] = new(RevitSpecKind.SiMeasure, "IFCWARPINGCONSTANTMEASURE", 6), + + // Specs whose Revit internal unit is already SI (lengthExponent == 0). + ["autodesk.spec.aec.electrical:powerDensity"] = new(RevitSpecKind.SiMeasure, "IFCREAL", 0), + ["autodesk.spec.aec.structural:forceScale"] = new(RevitSpecKind.SiMeasure, "IFCREAL", 0), + ["autodesk.spec.aec.energy:heatTransferCoefficient"] = new(RevitSpecKind.SiMeasure, "IFCTHERMALTRANSMITTANCEMEASURE", 0), + ["autodesk.spec.aec.energy:thermalResistance"] = new(RevitSpecKind.SiMeasure, "IFCTHERMALRESISTANCEMEASURE", 0), + ["autodesk.spec.aec.energy:heatCapacityPerArea"] = new(RevitSpecKind.SiMeasure, "IFCREAL", 0), + ["autodesk.spec.aec.electrical:current"] = new(RevitSpecKind.SiMeasure, "IFCELECTRICCURRENTMEASURE", 0), + ["autodesk.spec.aec.electrical:luminousFlux"] = new(RevitSpecKind.SiMeasure, "IFCLUMINOUSFLUXMEASURE", 0), + ["autodesk.spec.aec.electrical:luminousIntensity"] = new(RevitSpecKind.SiMeasure, "IFCLUMINOUSINTENSITYMEASURE", 0), + ["autodesk.spec.aec.electrical:colorTemperature"] = new(RevitSpecKind.SiMeasure, "IFCTHERMODYNAMICTEMPERATUREMEASURE", 0), + ["autodesk.spec.aec.hvac:temperature"] = new(RevitSpecKind.SiMeasure, "IFCTHERMODYNAMICTEMPERATUREMEASURE", 0), + ["autodesk.spec.aec.piping:temperature"] = new(RevitSpecKind.SiMeasure, "IFCTHERMODYNAMICTEMPERATUREMEASURE", 0), + ["autodesk.spec.aec.structural:mass"] = new(RevitSpecKind.SiMeasure, "IFCMASSMEASURE", 0), + ["autodesk.spec.aec.structural:linearForce"] = new(RevitSpecKind.SiMeasure, "IFCLINEARFORCEMEASURE", 0), + ["autodesk.spec.aec.structural:weightPerUnitLength"] = new(RevitSpecKind.SiMeasure, "IFCLINEARFORCEMEASURE", 0), + ["autodesk.spec.aec.structural:thermalExpansionCoefficient"] = new(RevitSpecKind.SiMeasure, "IFCTHERMALEXPANSIONCOEFFICIENTMEASURE", 0), + ["autodesk.spec.aec:time"] = new(RevitSpecKind.SiMeasure, "IFCTIMEMEASURE", 0), + ["autodesk.spec.aec:frequency"] = new(RevitSpecKind.SiMeasure, "IFCFREQUENCYMEASURE", 0), + ["autodesk.spec.measurable:currency"] = new(RevitSpecKind.SiMeasure, "IFCMONETARYMEASURE", 0), + ["autodesk.spec.aec:number"] = new(RevitSpecKind.SiMeasure, "IFCREAL", 0), + ["autodesk.spec.aec.hvac:factor"] = new(RevitSpecKind.SiMeasure, "IFCREAL", 0), + ["autodesk.spec.aec.electrical:demandFactor"] = new(RevitSpecKind.SiMeasure, "IFCREAL", 0), + ["autodesk.spec.aec:slope"] = new(RevitSpecKind.SiMeasure, "IFCREAL", 0), + ["autodesk.spec.aec.hvac:slope"] = new(RevitSpecKind.SiMeasure, "IFCREAL", 0), + ["autodesk.spec.aec.piping:slope"] = new(RevitSpecKind.SiMeasure, "IFCREAL", 0), + ["autodesk.spec.aec.hvac:coolingLoadDividedByArea"] = new(RevitSpecKind.SiMeasure, "IFCREAL", 0), + ["autodesk.spec.aec.hvac:heatingLoadDividedByArea"] = new(RevitSpecKind.SiMeasure, "IFCREAL", 0), + ["autodesk.spec.aec.hvac:areaDividedByCoolingLoad"] = new(RevitSpecKind.SiMeasure, "IFCREAL", 0), + ["autodesk.spec.aec.hvac:areaDividedByHeatingLoad"] = new(RevitSpecKind.SiMeasure, "IFCREAL", 0), + }.ToFrozenDictionary(StringComparer.Ordinal); + + // The unit of each measure SpecConversions writes: a named SI unit, or the powers of kilogram, metre, + // second and kelvin of a derived one. IfcMonetaryMeasure has none: the currency is not decoded. + private static readonly (string Measure, string UnitType, string SiUnit)[] NamedMeasureUnits = + [ + ("IFCPRESSUREMEASURE", "PRESSUREUNIT", "$,.PASCAL."), + ("IFCFORCEMEASURE", "FORCEUNIT", "$,.NEWTON."), + ("IFCPOWERMEASURE", "POWERUNIT", "$,.WATT."), + ("IFCENERGYMEASURE", "ENERGYUNIT", "$,.JOULE."), + ("IFCELECTRICVOLTAGEMEASURE", "ELECTRICVOLTAGEUNIT", "$,.VOLT."), + ("IFCELECTRICCURRENTMEASURE", "ELECTRICCURRENTUNIT", "$,.AMPERE."), + ("IFCILLUMINANCEMEASURE", "ILLUMINANCEUNIT", "$,.LUX."), + ("IFCLUMINOUSFLUXMEASURE", "LUMINOUSFLUXUNIT", "$,.LUMEN."), + ("IFCLUMINOUSINTENSITYMEASURE", "LUMINOUSINTENSITYUNIT", "$,.CANDELA."), + ("IFCTHERMODYNAMICTEMPERATUREMEASURE", "THERMODYNAMICTEMPERATUREUNIT", "$,.KELVIN."), + ("IFCMASSMEASURE", "MASSUNIT", ".KILO.,.GRAM."), + ("IFCTIMEMEASURE", "TIMEUNIT", "$,.SECOND."), + ("IFCFREQUENCYMEASURE", "FREQUENCYUNIT", "$,.HERTZ."), + ]; + + private static readonly (string Measure, string UnitType, int Kilogram, int Metre, int Second, int Kelvin)[] DerivedMeasureUnits = + [ + ("IFCPLANARFORCEMEASURE", "PLANARFORCEUNIT", 1, -1, -2, 0), + ("IFCDYNAMICVISCOSITYMEASURE", "DYNAMICVISCOSITYUNIT", 1, -1, -1, 0), + ("IFCVAPORPERMEABILITYMEASURE", "VAPORPERMEABILITYUNIT", 0, -1, 1, 0), + ("IFCMASSPERLENGTHMEASURE", "MASSPERLENGTHUNIT", 1, -1, 0, 0), + ("IFCLINEARVELOCITYMEASURE", "LINEARVELOCITYUNIT", 0, 1, -1, 0), + ("IFCTHERMALCONDUCTIVITYMEASURE", "THERMALCONDUCTANCEUNIT", 1, 1, -3, -1), + ("IFCLINEARMOMENTMEASURE", "LINEARMOMENTUNIT", 1, 1, -2, 0), + ("IFCSPECIFICHEATCAPACITYMEASURE", "SPECIFICHEATCAPACITYUNIT", 0, 2, -2, -1), + ("IFCHEATINGVALUEMEASURE", "HEATINGVALUEUNIT", 0, 2, -2, 0), + ("IFCTORQUEMEASURE", "TORQUEUNIT", 1, 2, -2, 0), + ("IFCVOLUMETRICFLOWRATEMEASURE", "VOLUMETRICFLOWRATEUNIT", 0, 3, -1, 0), + ("IFCSECTIONMODULUSMEASURE", "SECTIONMODULUSUNIT", 0, 3, 0, 0), + ("IFCMASSDENSITYMEASURE", "MASSDENSITYUNIT", 1, -3, 0, 0), + ("IFCMOMENTOFINERTIAMEASURE", "MOMENTOFINERTIAUNIT", 0, 4, 0, 0), + ("IFCWARPINGCONSTANTMEASURE", "WARPINGCONSTANTUNIT", 0, 6, 0, 0), + ("IFCTHERMALTRANSMITTANCEMEASURE", "THERMALTRANSMITTANCEUNIT", 1, 0, -3, -1), + ("IFCTHERMALRESISTANCEMEASURE", "THERMALRESISTANCEUNIT", -1, 0, 3, 1), + ("IFCLINEARFORCEMEASURE", "LINEARFORCEUNIT", 1, 0, -2, 0), + ("IFCTHERMALEXPANSIONCOEFFICIENTMEASURE", "THERMALEXPANSIONCOEFFICIENTUNIT", 0, 0, 0, -1), + ]; + + // the measure types written with RevitParameterUnits = Ifc in the running export + private readonly HashSet _revitParameterMeasures = new(StringComparer.Ordinal); + + /// Assigns the project unit of every measure the Revit parameters were converted to. The values are + /// in unprefixed SI units whatever the length unit of the file is. + private void DeclareRevitParameterUnits(StepWriter w) + { + // assigned elsewhere: the current profile adds power and thermal transmittance from the finished + // property values, the legacy header has the second + bool AlreadyAssigned(string unitType) => CurrentProfile + ? unitType is "POWERUNIT" or "THERMALTRANSMITTANCEUNIT" + : unitType is "TIMEUNIT"; + int SiUnit(string unitType, string unit) => w.Add("IFCSIUNIT", $"*,.{unitType}.,{unit}"); + + var added = new List(); + foreach (var (measure, unitType, unit) in NamedMeasureUnits) + { + if (_revitParameterMeasures.Contains(measure) && !AlreadyAssigned(unitType)) + added.Add(R(SiUnit(unitType, unit))); + } + foreach (var (measure, unitType, kilogram, metre, second, kelvin) in DerivedMeasureUnits) + { + if (!_revitParameterMeasures.Contains(measure) || AlreadyAssigned(unitType)) continue; + var elements = new List(); + void Factor(int exponent, string baseType, string baseUnit) + { + if (exponent != 0) + elements.Add(R(w.Add("IFCDERIVEDUNITELEMENT", $"{R(SiUnit(baseType, baseUnit))},{exponent}"))); + } + Factor(kilogram, "MASSUNIT", ".KILO.,.GRAM."); + Factor(metre, "LENGTHUNIT", "$,.METRE."); + Factor(second, "TIMEUNIT", "$,.SECOND."); + Factor(kelvin, "THERMODYNAMICTEMPERATUREUNIT", "$,.KELVIN."); + added.Add(R(w.Add("IFCDERIVEDUNIT", $"{StepWriter.List(elements)},.{unitType}.,$"))); + } + if (added.Count == 0) return; + + for (int i = 0; i < w.EntityCount; i++) + { + var (_, type, args) = w.EntityAt(i); + if (type != "IFCUNITASSIGNMENT") continue; + // the attribute text is the one list "(#1,#2)" + w.ReplaceArgs(i, $"{args[..^1]},{string.Join(",", added)})"); + return; + } + throw new InvalidOperationException("The export has no IfcUnitAssignment for the Revit parameter units."); + } + + private static double PowerOfFeetToMetres(int positiveExponent) => positiveExponent switch + { + 1 => FeetToMetres, + 2 => FeetToMetres * FeetToMetres, + 3 => FeetToMetres * FeetToMetres * FeetToMetres, + 4 => FeetToMetres * FeetToMetres * FeetToMetres * FeetToMetres, + 6 => FeetToMetres * FeetToMetres * FeetToMetres * FeetToMetres * FeetToMetres * FeetToMetres, + _ => Math.Pow(FeetToMetres, positiveExponent), + }; + + private static double ConvertInternalToSi(double value, int lengthExponent) => lengthExponent switch + { + 0 => value, + > 0 => value * PowerOfFeetToMetres(lengthExponent), + < 0 => value / PowerOfFeetToMetres(-lengthExponent), + }; + + internal static string? ConvertDoubleToIfcOrSi(double value, string? spec, bool currentProfile) + { + if (!double.IsFinite(value) || string.IsNullOrWhiteSpace(spec)) + return null; + + string key = UnitSchemaEvaluator.DisplayNameKey(spec); + if (!SpecConversions.TryGetValue(key, out var conversion)) + return null; + + string Real(double v) => currentProfile ? D17(v) : D(v); + return conversion.Kind switch + { + RevitSpecKind.Length => $"IFCLENGTHMEASURE({D17(value * 304.8)})", + RevitSpecKind.Area => $"IFCAREAMEASURE({Real(value * FeetToMetres * FeetToMetres)})", + RevitSpecKind.Volume => $"IFCVOLUMEMEASURE({Real(value * FeetToMetres * FeetToMetres * FeetToMetres)})", + RevitSpecKind.Angle => $"IFCPLANEANGLEMEASURE({(currentProfile ? D17(value * (180.0 / Math.PI)) : D(value))})", + RevitSpecKind.SiMeasure => $"{conversion.MeasureName}({Real(ConvertInternalToSi(value, conversion.LengthExponent))})", + _ => null, + }; + } + + private string? ResolveParameterSpec(Parameter p, string? apiDataType) + { + if (!string.IsNullOrEmpty(apiDataType)) + return apiDataType; + if (p.Id > 0 && _userParameters?.TryGetDefinition(p.Id, out var userDef) == true && !string.IsNullOrEmpty(userDef.Spec)) + return userDef.Spec; + // a parameter without a known spec keeps its stored number: its name does not say what it measures + return string.IsNullOrEmpty(p.SpecType) ? null : p.SpecType; + } + + private string? FormatRevitParameterValue( + Element elem, + Parameter p, + string? apiDataType, + IReadOnlyDictionary elemById, + bool useIfcUnits, + bool useInternalUnits, + bool isGrouped) + { + string rawValue; + switch (p.StorageType) + { + case StorageType.Double: + if (p.Value is double dv && double.IsFinite(dv)) + rawValue = $"IFCREAL({(CurrentProfile ? D17(dv) : D(dv))})"; + else + return null; + break; + case StorageType.String: + rawValue = $"IFCLABEL({S(p.Value?.ToString() ?? "")})"; + break; + case StorageType.Integer: + rawValue = p.Value is bool bv + ? $"IFCINTEGER({(bv ? 1 : 0)})" + : $"IFCINTEGER({p.Value})"; + break; + case StorageType.ElementId: + rawValue = $"IFCINTEGER({p.Value})"; + break; + default: + return null; + } + + if (useIfcUnits) + { + if (isGrouped && !string.IsNullOrEmpty(apiDataType) + && TypedApiParameterValue(elem, p, apiDataType, elemById, CurrentProfile, convertAllSpecs: true) is { } groupedTyped) + { + return groupedTyped; + } + if (p.StorageType == StorageType.Double && p.Value is double d && double.IsFinite(d)) + { + string? spec = ResolveParameterSpec(p, apiDataType); + return ConvertDoubleToIfcOrSi(d, spec, CurrentProfile) ?? rawValue; + } + if (isGrouped && p.Id < 0 + && TypedApiParameterValue(elem, p, apiDataType ?? "", elemById, CurrentProfile, convertAllSpecs: true) is { } groupedRef) + { + return groupedRef; + } + return rawValue; + } + + if (useInternalUnits) + { + if (isGrouped && p.StorageType != StorageType.Double && p.Id < 0) + return TypedApiParameterValue(elem, p, apiDataType ?? "", elemById, CurrentProfile) ?? rawValue; + return rawValue; + } + + // Unspecified mode: keep existing RevitParameterGroups vs RevitParameters behavior unchanged. + if (isGrouped && p.Id < 0 && apiDataType != null) + return TypedApiParameterValue(elem, p, apiDataType, elemById, CurrentProfile) ?? rawValue; + + return rawValue; + } + + private (string Name, string? Description) ResolveRevitParameterNameAndDescription( + Parameter p, + bool hasApiDef, + string apiName, + bool useDisplayNames, + bool useBuiltInNames, + bool isGrouped) + { + static bool IsPlaceholderName(string? candidate, int id) => + string.IsNullOrWhiteSpace(candidate) + || candidate == id.ToString(CultureInfo.InvariantCulture) + || candidate == $"Param_{id}"; + + if (useDisplayNames) + { + if (p.Id < 0) + { + string? bipName = p.DefinitionBuiltIn ?? (BipNames.Lookup.TryGetValue(p.Id, out var foundBip) ? foundBip : null); + string displayName = p.Id switch + { + -1002502 => "Classification Number", + -1002503 => "Classification Title", + _ when hasApiDef && !string.IsNullOrWhiteSpace(apiName) => apiName, + _ when CompactLabels.TryGetParameterLabel(p.Id, out var compactLabel) && !string.IsNullOrWhiteSpace(compactLabel) => compactLabel, + _ => p.DefinitionName ?? bipName ?? $"Param_{p.Id}", + }; + return (displayName, bipName); + } + + if (_userParameters?.TryGetDefinition(p.Id, out var userDef) == true && !string.IsNullOrWhiteSpace(userDef.Caption)) + return (userDef.Caption, null); + + if (!IsPlaceholderName(p.DefinitionName, p.Id)) + return (p.DefinitionName!, null); + + return ($"Param_{p.Id}", null); + } + + if (useBuiltInNames) + { + if (p.Id < 0) + { + string builtIn = p.DefinitionBuiltIn + ?? (BipNames.Lookup.TryGetValue(p.Id, out var foundBip) ? foundBip : null) + ?? p.DefinitionName + ?? $"Param_{p.Id}"; + return (builtIn, null); + } + return (p.DefinitionName ?? $"Param_{p.Id}", null); + } + + if (isGrouped && hasApiDef) + { + string groupedName = p.Id switch + { + -1002502 => "Classification Number", + -1002503 => "Classification Title", + _ => apiName, + }; + return (groupedName, null); + } + + return (p.DefinitionName ?? $"Param_{p.Id}", null); + } +} diff --git a/src/RvtIO/Ifc/IfcExporter.cs b/src/RvtIO/Ifc/IfcExporter.cs index f0b0a496..e1378166 100644 --- a/src/RvtIO/Ifc/IfcExporter.cs +++ b/src/RvtIO/Ifc/IfcExporter.cs @@ -231,6 +231,9 @@ private readonly record struct RepresentationMapCacheEntry( private bool? _exportRoomsOfAllPhases; private IfcProfile? _profile; private bool? _revitParameterGroups; + private IfcRevitParameterUnits? _revitParameterUnits; + private IfcRevitParameterNames? _revitParameterNames; + private Parsing.UserParameterCatalog? _userParameters; private DateTimeOffset? _timestamp; private IfcUnitFamily? _lengthUnit; private IfcSchema? _schema; @@ -323,6 +326,21 @@ public IfcProfile Profile /// public bool RevitParameterGroups { get => _revitParameterGroups ?? _resolvedConfig.RevitParameterGroups; init => _revitParameterGroups = value; } + /// + /// Unit system used for numeric Revit parameters when exporting Revit property sets + /// ( preserves raw internal units; + /// converts length, area, volume, and angle to IFC units + /// and other known physical spec types to SI units). + /// + public IfcRevitParameterUnits? RevitParameterUnits { get => _revitParameterUnits ?? _resolvedConfig.RevitParameterUnits; init => _revitParameterUnits = value; } + + /// + /// Property naming convention used when exporting Revit parameters + /// ( keeps built-in/definition names; + /// uses display names with built-in names in Description). + /// + public IfcRevitParameterNames? RevitParameterNames { get => _revitParameterNames ?? _resolvedConfig.RevitParameterNames; init => _revitParameterNames = value; } + private ResolvedIfcExportConfiguration BuildEffectiveConfiguration() { IfcExportConfiguration baseConfig = Configuration ?? new IfcExportConfiguration(); @@ -368,6 +386,8 @@ private ResolvedIfcExportConfiguration BuildEffectiveConfiguration() { ExportRevitPropertySets = _revitPropertySetsExplicit ? true : null, GroupRevitParametersByGroup = _revitParameterGroups, + RevitParameterUnits = _revitParameterUnits, + RevitParameterNames = _revitParameterNames, }, }; @@ -378,6 +398,10 @@ private void ValidateExplicitApiOverrides(RevitFileInfo info) { if (_lengthUnit is { } explicitUnit && !Enum.IsDefined(explicitUnit)) throw new ArgumentOutOfRangeException(nameof(LengthUnit), explicitUnit, "Unsupported IFC length unit family."); + if (_revitParameterUnits is { } explicitParamUnits && !Enum.IsDefined(explicitParamUnits)) + throw new ArgumentOutOfRangeException(nameof(RevitParameterUnits), explicitParamUnits, "Unsupported Revit parameter unit system."); + if (_revitParameterNames is { } explicitParamNames && !Enum.IsDefined(explicitParamNames)) + throw new ArgumentOutOfRangeException(nameof(RevitParameterNames), explicitParamNames, "Unsupported Revit parameter naming convention."); if (_exportPhaseId != null && info.SerializedProjectPhaseIds?.Contains(_exportPhaseId.Value) != true) throw new InvalidOperationException("The requested export phase is not in a validated project phase order."); if (_roomExportPhaseId == null) return; @@ -464,6 +488,7 @@ public void Export(RevitFileInfo info, TextWriter output) info.Elements = allElements; foreach (var (element, original) in computedSymbolGeometry) element.Geometry = original; _facetedPlans.Clear(); // plans nobody asked for must not outlive the export + _userParameters = null; } } /// Whether any of the elements holds a decoded body: a solid or a face. @@ -528,6 +553,8 @@ private void UpdateDecomposedStairQualities( private void ExportDocument(RevitFileInfo info, TextWriter output) { ValidateRoomExportPhase(info); + _userParameters = info.UserParameters; + _revitParameterMeasures.Clear(); _geometryUndecoded = info.GeometryUndecoded; _exportedElementQualities.Clear(); _usedExportIds.Clear(); @@ -6889,6 +6916,7 @@ void AddWallConnection(int relating, int related, string relatingType, string re _diag?.WriteLine($"The current profile string property byte limits: {limitedStrings} values shortened"); FinalizeUnitAssignmentCurrent(w, unitsCurrent!); } + DeclareRevitParameterUnits(w); if (CurrentProfile) ApplyCurrentOpeningOrder(w, openingOrderKeys); if (_resolvedConfig.Schema == IfcSchema.Ifc4) { @@ -66375,7 +66403,7 @@ private static bool MullionEdgeIsParallelOnLattice( /// name="angleInDegrees"/> (the The current profile plane angle unit). /// internal static string? TypedApiParameterValue(Element elem, Parameter p, string dataType, - IReadOnlyDictionary elemById, bool angleInDegrees = false) + IReadOnlyDictionary elemById, bool angleInDegrees = false, bool convertAllSpecs = false) { // Element references and the type-derived identity parameters are written as the referenced // text, as Revit's parameter display does. @@ -66411,6 +66439,8 @@ private static bool MullionEdgeIsParallelOnLattice( switch (p.StorageType) { case StorageType.Double when p.Value is double d && double.IsFinite(d): + if (convertAllSpecs) + return ConvertDoubleToIfcOrSi(d, dataType, angleInDegrees); return dataType switch { "autodesk.spec.aec:length" => $"IFCLENGTHMEASURE({D17(d * 304.8)})", @@ -66434,55 +66464,62 @@ private void ExportPropertySets(StepWriter w, Element elem, int elemEntityId, in IReadOnlyDictionary elemById) { // Group parameters by a common property set name Revit params -> "PSet_Revit_Parameters" + var properties = new List<(string Group, string Name, string? Description, string Value, int ParameterId)>(); var propIds = new List(); var propIdsByGroup = new Dictionary>(StringComparer.Ordinal); + bool useDisplayNames = RevitParameterNames == IfcRevitParameterNames.Display; + bool useBuiltInNames = RevitParameterNames == IfcRevitParameterNames.BuiltIn; + bool useIfcUnits = RevitParameterUnits == IfcRevitParameterUnits.Ifc; + bool useInternalUnits = RevitParameterUnits == IfcRevitParameterUnits.Internal; foreach (var p in elem.Parameters) { if (!p.HasRevitValue) continue; - string propValue; + string apiName = ""; + int apiGroupId = -1; + string apiDataType = ""; + bool hasApiDef = p.Id < 0 && Parsing.ApiParameterDefinitions.TryGet( + p.Id, out apiName, out apiGroupId, out apiDataType); - switch (p.StorageType) + string? propValue = FormatRevitParameterValue( + elem, p, hasApiDef ? apiDataType : null, elemById, + useIfcUnits, useInternalUnits, RevitParameterGroups); + if (propValue == null) continue; + if (useIfcUnits) _revitParameterMeasures.Add(propValue[..propValue.IndexOf('(')]); + + var (paramName, paramDescription) = ResolveRevitParameterNameAndDescription( + p, hasApiDef, apiName, useDisplayNames, useBuiltInNames, RevitParameterGroups); + + string groupName = "Other"; + if (RevitParameterGroups && hasApiDef + && BuiltIns.BuiltInParameterGroupLabels.ToEnglishLabel((BuiltIns.BuiltInParameterGroup)apiGroupId, out string label)) { - case StorageType.Double: - if (p.Value is double dv && double.IsFinite(dv)) - { - propValue = $"IFCREAL({(CurrentProfile ? D17(dv) : D(dv))})"; - } - else continue; - break; - case StorageType.String: - propValue = $"IFCLABEL({S(p.Value?.ToString() ?? "")})"; - break; - case StorageType.Integer: - propValue = p.Value is bool bv - ? $"IFCINTEGER({(bv ? 1 : 0)})" - : $"IFCINTEGER({p.Value})"; - break; - case StorageType.ElementId: - propValue = $"IFCINTEGER({p.Value})"; - break; - default: - continue; + groupName = label; } - string paramName = p.DefinitionName ?? $"Param_{p.Id}"; - string groupName = "Other"; - if (RevitParameterGroups && Parsing.ApiParameterDefinitions.TryGet( - p.Id, out string apiName, out int apiGroupId, out string apiDataType)) + properties.Add((groupName, paramName, paramDescription, propValue, p.Id)); + } + + // IfcPropertySet requires unique property names, and distinct parameters can share one: in the + // requested naming modes every member of a clash gets its parameter id. The default naming is + // left as it was. + var clashes = RevitParameterNames == null + ? null + : properties.GroupBy(x => (x.Group, x.Name)).Where(g => g.Count() > 1).Select(g => g.Key).ToHashSet(); + var takenNames = new HashSet<(string, string)>(); + foreach (var (groupName, paramName, paramDescription, propValue, parameterId) in properties) + { + string name = paramName; + if (clashes != null) { - paramName = p.Id switch - { - -1002502 => "Classification Number", - -1002503 => "Classification Title", - _ => apiName, - }; - if (BuiltIns.BuiltInParameterGroupLabels.ToEnglishLabel((BuiltIns.BuiltInParameterGroup)apiGroupId, out string label)) - groupName = label; - propValue = TypedApiParameterValue(elem, p, apiDataType, elemById, CurrentProfile) ?? propValue; + if (clashes.Contains((groupName, paramName))) name = $"{paramName} [{parameterId}]"; + string unique = name; + for (int n = 2; !takenNames.Add((groupName, unique)); n++) unique = $"{name} #{n}"; + name = unique; } - int propId = w.Add("IFCPROPERTYSINGLEVALUE", $"{S(paramName)},$,{propValue},$"); + string descToken = paramDescription != null ? S(paramDescription) : "$"; + int propId = w.Add("IFCPROPERTYSINGLEVALUE", $"{S(name)},{descToken},{propValue},$"); if (RevitParameterGroups) { if (!propIdsByGroup.TryGetValue(groupName, out var groupIds)) diff --git a/tests/RvtIO.Tests/IfcExportConfigurationTests.cs b/tests/RvtIO.Tests/IfcExportConfigurationTests.cs index 86cea45b..25714387 100644 --- a/tests/RvtIO.Tests/IfcExportConfigurationTests.cs +++ b/tests/RvtIO.Tests/IfcExportConfigurationTests.cs @@ -254,6 +254,21 @@ public void FromJson_RejectsNullSections(string section) Assert.Contains(section, error.Message); } + [Theory] + [InlineData("--ifc-revit-parameter-units", "ifc")] + [InlineData("--ifc-revit-parameter-names", "display")] + public void Cli_RevitParameterOptionsImplyRevitPropertySetsWithAConfigurationFile(string option, string value) + { + using var temp = new ConfigurationTestDirectory(); + string source = Path.Combine(temp.Path, "input.json"); + string saved = Path.Combine(temp.Path, "saved.json"); + File.WriteAllText(source, "{}"); + + Assert.Equal(0, Program.Main(["--ifc-config", source, option, value, "--ifc-save-config", saved])); + + Assert.True(IfcExportConfiguration.FromJson(File.ReadAllText(saved)).Resolve().ExportRevitPropertySets); + } + [Fact] public void Cli_SaveConfigurationRejectsCollidingPaths() { diff --git a/tests/RvtIO.Tests/IfcExporterRevitParameterFormattingTests.cs b/tests/RvtIO.Tests/IfcExporterRevitParameterFormattingTests.cs new file mode 100644 index 00000000..ee933138 --- /dev/null +++ b/tests/RvtIO.Tests/IfcExporterRevitParameterFormattingTests.cs @@ -0,0 +1,638 @@ +using System.Globalization; +using System.Text.RegularExpressions; +using RvtIO.Cli; +using RvtIO.Ifc; +using RvtIO.Internal; +using RvtIO.Model; +using RvtIO.Parsing; +using Xunit; + +namespace RvtIO.Tests; + +public class IfcExporterRevitParameterFormattingTests +{ + private static string TempIfcPath(string tag) => + Path.Combine(Path.GetTempPath(), $"rvtio-paramfmt-{tag}-{Guid.NewGuid():N}.ifc"); + + private static RevitFileInfo SampleModelWithParameters() + { + var info = new RevitFileInfo(); + var phase = new Element { Id = 3, CategoryId = -2000112, Category = "OST_Phases", Name = "New Construction" }; + var level = new Element + { + Id = 10, + CategoryId = -2000240, + Category = "OST_Levels", + Name = "Basement", + IsNativeLevel = true, + Parameters = + [ + new Parameter { Id = -1012100, StorageType = StorageType.ElementId, Value = 3 }, + new Parameter + { + Id = -1007102, + Definition = new Definition { Id = -1007102, BuiltInParameter = "LEVEL_ELEV", Name = "LEVEL_ELEV" }, + StorageType = StorageType.Double, + Value = -5.0 / 0.3048, // -5 m = -500 cm + }, + new Parameter { Id = -1007111, StorageType = StorageType.Integer, Value = 1 }, + ], + }; + + double[][] points = + [ + [-0.2, 0, 3.7], [0.2, 0, 3.7], [0.2, 0, 4.3], [-0.2, 0, 4.3], + [-0.2, 10, 3.7], [0.2, 10, 3.7], [0.2, 10, 4.3], [-0.2, 10, 4.3], + ]; + int[][] faceIndices = + [ + [0, 1, 2, 3], [4, 7, 6, 5], [0, 4, 5, 1], + [1, 5, 6, 2], [2, 6, 7, 3], [3, 7, 4, 0], + ]; + double[] bounds = [-0.2, 0, 3.7, 0.2, 10, 4.3]; + var beamGeo = new GeometryData + { + BoundingBox = bounds, + Faces = faceIndices.Select(idx => new GeoFace { OuterVertices = idx.Select(i => points[i]).ToList() }).ToList(), + BrepSolids = [new GeoBrepSolid { IsClosed = true, FaceIndices = [0, 1, 2, 3, 4, 5] }], + }; + + var wall = new Element + { + Id = 20, + TypeId = 21, + IsDiscovered = true, + CategoryId = -2001320, + Category = "OST_StructuralFraming", + Name = "Beam_Test", + References = [3], + BoundingBox = bounds, + Geometry = beamGeo, + Parameters = + [ + new Parameter { Id = -1012100, StorageType = StorageType.ElementId, Value = 3 }, + new Parameter + { + Id = -1007102, + Definition = new Definition { Id = -1007102, BuiltInParameter = "LEVEL_ELEV", Name = "LEVEL_ELEV" }, + StorageType = StorageType.Double, + Value = -5.0 / 0.3048, // -5 m = -500 cm + }, + new Parameter + { + Id = -1001108, + Definition = new Definition { Id = -1001108, BuiltInParameter = "WALL_BASE_OFFSET", Name = "WALL_BASE_OFFSET" }, + StorageType = StorageType.Double, + Value = -3.0 / 0.3048, // -300 cm + }, + new Parameter + { + Id = -1001951, + Definition = new Definition { Id = -1001951, BuiltInParameter = "FLOOR_HEIGHTABOVELEVEL_PARAM", Name = "FLOOR_HEIGHTABOVELEVEL_PARAM" }, + StorageType = StorageType.Double, + Value = 0.75 / 0.3048, // 75 cm + }, + new Parameter + { + Id = -1140414, + Definition = new Definition { Id = -1140414, BuiltInParameter = "PHY_MATERIAL_PARAM_BENDING", Name = "PHY_MATERIAL_PARAM_BENDING" }, + StorageType = StorageType.Double, + Value = 304800.0, // internal kg/(ft s^2) -> 1,000,000 Pa + }, + new Parameter + { + Id = -1001133, + Definition = new Definition { Id = -1001133, BuiltInParameter = "HOST_AREA_COMPUTED", Name = "HOST_AREA_COMPUTED" }, + StorageType = StorageType.Double, + Value = 1.0 / (0.3048 * 0.3048), // 1 m^2 = 10000 cm^2 + }, + new Parameter + { + Id = -1001129, + Definition = new Definition { Id = -1001129, BuiltInParameter = "HOST_VOLUME_COMPUTED", Name = "HOST_VOLUME_COMPUTED" }, + StorageType = StorageType.Double, + Value = 1.0 / (0.3048 * 0.3048 * 0.3048), // 1 m^3 = 1000000 cm^3 + }, + new Parameter + { + Id = -1155217, + Definition = new Definition { Id = -1155217, BuiltInParameter = "REBAR_ELEM_HOOK_ROTATION_AT_END", Name = "REBAR_ELEM_HOOK_ROTATION_AT_END" }, + StorageType = StorageType.Double, + Value = Math.PI / 2, // 90 deg + }, + new Parameter + { + Id = -1152308, + Definition = new Definition { Id = -1152308, BuiltInParameter = "PHY_MATERIAL_PARAM_THERMAL_CONDUCTIVITY", Name = "PHY_MATERIAL_PARAM_THERMAL_CONDUCTIVITY" }, + StorageType = StorageType.Double, + Value = 5.0, // 5 * 0.3048 = 1.524 W/(m K) + }, + new Parameter + { + Id = -1005430, + Definition = new Definition { Id = -1005430, BuiltInParameter = "ANALYTICAL_HEAT_TRANSFER_COEFFICIENT", Name = "ANALYTICAL_HEAT_TRANSFER_COEFFICIENT" }, + StorageType = StorageType.Double, + Value = 2.25, // 2.25 W/(m^2 K) + }, + new Parameter + { + Id = -1152313, + Definition = new Definition { Id = -1152313, BuiltInParameter = "PHY_MATERIAL_PARAM_STRUCTURAL_DENSITY", Name = "PHY_MATERIAL_PARAM_STRUCTURAL_DENSITY" }, + StorageType = StorageType.Double, + Value = 2400.0 * (0.3048 * 0.3048 * 0.3048), // 2400 kg/m^3 + }, + new Parameter + { + Id = 900001, + Definition = new Definition { Id = 900001, Name = "900001" }, + StorageType = StorageType.String, + Value = "Z-1", + }, + new Parameter + { + Id = 900002, + StorageType = StorageType.Double, + Value = 2.0, // 2 ft = 60.96 cm + }, + ], + }; + + var state = new ParsingState(); + state.ElemClassIdx[900001] = 2873; + var np1 = new TfBlockDeserializer.NativeParams(); + np1.Fields[TfClassNames.Key("ParamDef", "m_paramElemId")] = 900001; + np1.Fields["2870:m_pParamDef.class"] = 606; + np1.Fields[TfClassNames.Key("ParamDef", "m_groupElemId")] = -5000100; + np1.StringFields[TfClassNames.Key("ParamDef", "m_caption")] = "Test Zone"; + state.NativeParams[900001] = np1; + + state.ElemClassIdx[900002] = 2873; + var np2 = new TfBlockDeserializer.NativeParams(); + np2.Fields[TfClassNames.Key("ParamDef", "m_paramElemId")] = 900002; + np2.Fields["2870:m_pParamDef.class"] = 612; + np2.Fields[TfClassNames.Key("ParamDef", "m_groupElemId")] = -5000101; + np2.StringFields[TfClassNames.Key("ParamDef", "m_caption")] = "Test Clearance"; + np2.StringFields[TfClassNames.Key("ParamDefValue", "m_specTypeId")] = "autodesk.spec.aec:length-2.0.0"; + state.NativeParams[900002] = np2; + info.UserParameters = UserParameterCatalog.Build(state); + info.Elements.Add(phase); + info.Elements.Add(level); + info.Elements.Add(wall); + return info; + } + + [Fact] + public void RevitParameters_DefaultMode_PreservesInternalUnitsAndBuiltInNames() + { + var info = SampleModelWithParameters(); + string path = TempIfcPath("default"); + try + { + new IfcExporter(includeRevitPropertySets: true) + { + LengthUnit = IfcUnitFamily.Centimetre, + }.Export(info, path); + string ifc = File.ReadAllText(path); + + Assert.Contains("IFCPROPERTYSINGLEVALUE('WALL_BASE_OFFSET','',IFCREAL(", ifc); + Assert.Contains("IFCPROPERTYSINGLEVALUE('PHY_MATERIAL_PARAM_BENDING','',IFCREAL(304800.),$)", ifc); + Assert.Contains("IFCPROPERTYSINGLEVALUE('900001','',IFCLABEL('Z-1'),$)", ifc); + } + finally + { + if (File.Exists(path)) File.Delete(path); + } + } + + [Fact] + public void RevitParameters_WithIfcUnitsAndDisplayNames_ConvertsUnitsAndResolvesNamesAndDescriptions() + { + var info = SampleModelWithParameters(); + string path = TempIfcPath("ifc-display"); + try + { + new IfcExporter(includeRevitPropertySets: true) + { + LengthUnit = IfcUnitFamily.Centimetre, + RevitParameterUnits = IfcRevitParameterUnits.Ifc, + RevitParameterNames = IfcRevitParameterNames.Display, + }.Export(info, path); + string ifc = File.ReadAllText(path); + + Assert.Contains("IFCPROPERTYSINGLEVALUE('Elevation','LEVEL_ELEV',IFCLENGTHMEASURE(-500.),$)", ifc); + Assert.Contains("IFCPROPERTYSINGLEVALUE('Base Offset','WALL_BASE_OFFSET',IFCLENGTHMEASURE(-300.),$)", ifc); + Assert.Contains("IFCPROPERTYSINGLEVALUE('Height Offset From Level','FLOOR_HEIGHTABOVELEVEL_PARAM',IFCLENGTHMEASURE(75.),$)", ifc); + Assert.Contains("IFCPROPERTYSINGLEVALUE('Bending','PHY_MATERIAL_PARAM_BENDING',IFCPRESSUREMEASURE(1000000.),$)", ifc); + Assert.Contains("IFCPROPERTYSINGLEVALUE('Area','HOST_AREA_COMPUTED',IFCAREAMEASURE(10000.),$)", ifc); + Assert.Contains("IFCPROPERTYSINGLEVALUE('Volume','HOST_VOLUME_COMPUTED',IFCVOLUMEMEASURE(1000000.),$)", ifc); + Assert.Contains("IFCPROPERTYSINGLEVALUE('Hook Rotation At End','REBAR_ELEM_HOOK_ROTATION_AT_END',IFCPLANEANGLEMEASURE(90.),$)", ifc); + Assert.Contains("IFCPROPERTYSINGLEVALUE('Thermal Conductivity','PHY_MATERIAL_PARAM_THERMAL_CONDUCTIVITY',IFCTHERMALCONDUCTIVITYMEASURE(1.524),$)", ifc); + Assert.Contains("IFCPROPERTYSINGLEVALUE('Heat Transfer Coefficient (U)','ANALYTICAL_HEAT_TRANSFER_COEFFICIENT',IFCTHERMALTRANSMITTANCEMEASURE(2.25),$)", ifc); + Assert.Contains("IFCPROPERTYSINGLEVALUE('Density','PHY_MATERIAL_PARAM_STRUCTURAL_DENSITY',IFCMASSDENSITYMEASURE(2400.),$)", ifc); + Assert.Contains("IFCPROPERTYSINGLEVALUE('Test Zone','',IFCLABEL('Z-1'),$)", ifc); + Assert.Matches(@"IFCPROPERTYSINGLEVALUE\('Test Clearance','',IFCLENGTHMEASURE\(60\.96\d*\),\$\)", ifc); + Assert.Contains(".THERMALTRANSMITTANCEUNIT.", ifc); + } + finally + { + if (File.Exists(path)) File.Delete(path); + } + } + + [Fact] + public void RevitParameters_DisplayNames_DoesNotMergeDifferentBuiltInsInPropertyValueCache() + { + double[][] points = + [ + [-0.2, 0, 3.7], [0.2, 0, 3.7], [0.2, 0, 4.3], [-0.2, 0, 4.3], + [-0.2, 10, 3.7], [0.2, 10, 3.7], [0.2, 10, 4.3], [-0.2, 10, 4.3], + ]; + int[][] faceIndices = + [ + [0, 1, 2, 3], [4, 7, 6, 5], [0, 4, 5, 1], + [1, 5, 6, 2], [2, 6, 7, 3], [3, 7, 4, 0], + ]; + double[] bounds = [-0.2, 0, 3.7, 0.2, 10, 4.3]; + var wall1 = new Element + { + Id = 20, + TypeId = 21, + IsDiscovered = true, + CategoryId = -2001320, + Category = "OST_StructuralFraming", + Name = "Beam 1", + References = [3], + BoundingBox = bounds, + Geometry = new GeometryData + { + BoundingBox = bounds, + Faces = faceIndices.Select(idx => new GeoFace { OuterVertices = idx.Select(i => points[i]).ToList() }).ToList(), + BrepSolids = [new GeoBrepSolid { IsClosed = true, FaceIndices = [0, 1, 2, 3, 4, 5] }], + }, + Parameters = + [ + new Parameter { Id = -1012100, StorageType = StorageType.ElementId, Value = 3 }, + new Parameter { Id = -1001108, StorageType = StorageType.Double, Value = 0.0 }, // WALL_BASE_OFFSET ("Base Offset") + new Parameter { Id = -1001357, StorageType = StorageType.Double, Value = 1.0 }, // FAMILY_BASE_LEVEL_OFFSET_PARAM ("Base Offset") + ], + }; + // carries one of the two only, with the same value: nothing to suffix, and nothing to share + var wall2 = new Element + { + Id = 22, + TypeId = 21, + IsDiscovered = true, + CategoryId = wall1.CategoryId, + Category = wall1.Category, + Name = "Beam 2", + References = [3], + BoundingBox = bounds, + Geometry = wall1.Geometry, + Parameters = + [ + new Parameter { Id = -1012100, StorageType = StorageType.ElementId, Value = 3 }, + new Parameter { Id = -1001357, StorageType = StorageType.Double, Value = 0.0 }, + ], + }; + var info = new RevitFileInfo(); + info.Elements.Add(new Element { Id = 3, CategoryId = -2000112, Category = "OST_Phases", Name = "New Construction" }); + info.Elements.Add(wall1); + info.Elements.Add(wall2); + + string path = TempIfcPath("cache-desc"); + try + { + new IfcExporter(includeRevitPropertySets: true) + { + RevitParameterUnits = IfcRevitParameterUnits.Ifc, + RevitParameterNames = IfcRevitParameterNames.Display, + }.Export(info, path); + string ifc = File.ReadAllText(path); + + // IfcPropertySet requires unique property names: both values survive, each under its parameter id + Assert.Contains("IFCPROPERTYSINGLEVALUE('Base Offset [-1001108]','WALL_BASE_OFFSET',IFCLENGTHMEASURE(0.),$)", ifc); + Assert.Matches(@"IFCPROPERTYSINGLEVALUE\('Base Offset \[-1001357\]','FAMILY_BASE_LEVEL_OFFSET_PARAM',IFCLENGTHMEASURE\(304\.8\d*\),\$\)", ifc); + // without a clash the name stays plain, and the cache does not hand out another parameter's description + Assert.Contains("IFCPROPERTYSINGLEVALUE('Base Offset','FAMILY_BASE_LEVEL_OFFSET_PARAM',IFCLENGTHMEASURE(0.),$)", ifc); + } + finally + { + if (File.Exists(path)) File.Delete(path); + } + } + + [Fact] + public void RevitParameters_DisplayNames_ResolvesCompactOnlyBuiltInDisplayName() + { + double[][] points = + [ + [-0.2, 0, 3.7], [0.2, 0, 3.7], [0.2, 0, 4.3], [-0.2, 0, 4.3], + [-0.2, 10, 3.7], [0.2, 10, 3.7], [0.2, 10, 4.3], [-0.2, 10, 4.3], + ]; + int[][] faceIndices = + [ + [0, 1, 2, 3], [4, 7, 6, 5], [0, 4, 5, 1], + [1, 5, 6, 2], [2, 6, 7, 3], [3, 7, 4, 0], + ]; + double[] bounds = [-0.2, 0, 3.7, 0.2, 10, 4.3]; + var wall = new Element + { + Id = 20, + TypeId = 21, + IsDiscovered = true, + CategoryId = -2001320, + Category = "OST_StructuralFraming", + Name = "Beam 1", + References = [3], + BoundingBox = bounds, + Geometry = new GeometryData + { + BoundingBox = bounds, + Faces = faceIndices.Select(idx => new GeoFace { OuterVertices = idx.Select(i => points[i]).ToList() }).ToList(), + BrepSolids = [new GeoBrepSolid { IsClosed = true, FaceIndices = [0, 1, 2, 3, 4, 5] }], + }, + Parameters = + [ + new Parameter { Id = -1012100, StorageType = StorageType.ElementId, Value = 3 }, + new Parameter + { + Id = -1155224, // present in compact_builtin_parameters.tsv, absent from api_parameter_definitions_2022.json + Definition = new Definition { Id = -1155224, BuiltInParameter = "REBAR_INSTANCE_BAR_MODEL_DIAMETER", Name = "REBAR_INSTANCE_BAR_MODEL_DIAMETER" }, + StorageType = StorageType.Double, + Value = 0.25, + }, + ], + }; + var info = new RevitFileInfo(); + info.Elements.Add(new Element { Id = 3, CategoryId = -2000112, Category = "OST_Phases", Name = "New Construction" }); + info.Elements.Add(wall); + + string path = TempIfcPath("compact-only"); + try + { + new IfcExporter(includeRevitPropertySets: true) + { + RevitParameterNames = IfcRevitParameterNames.Display, + }.Export(info, path); + string ifc = File.ReadAllText(path); + + Assert.Contains("IFCPROPERTYSINGLEVALUE('Model Bar Diameter','REBAR_INSTANCE_BAR_MODEL_DIAMETER',IFCREAL(0.25),$)", ifc); + } + finally + { + if (File.Exists(path)) File.Delete(path); + } + } + + [Theory] + [InlineData("autodesk.spec.aec.electrical:powerDensity", "IFCREAL", 1.0)] // W/m^2 = kg/s^3 + [InlineData("autodesk.spec.aec.structural:forceScale", "IFCREAL", 1.0)] // m/kN = s^2/kg + [InlineData("autodesk.spec.aec.structural:areaForceScale", "IFCREAL", 0.3048 * 0.3048)] // m^3/kN + [InlineData("autodesk.spec.aec.structural:momentScale", "IFCREAL", 1 / 0.3048)] // 1/kN + [InlineData("autodesk.spec.aec.structural:linearForceScale", "IFCREAL", 0.3048)] // m^2/kN + [InlineData("autodesk.spec.aec.structural:sectionProperty", "IFCLENGTHMEASURE", 304.8)] // a length, in mm before the file unit + public void ConvertDoubleToIfcOrSi_UsesTheLengthExponentOfTheSpec(string spec, string measure, double expected) + { + string? converted = IfcExporter.ConvertDoubleToIfcOrSi(1.0, spec, currentProfile: true); + + Assert.NotNull(converted); + Assert.StartsWith(measure + "(", converted); + double actual = double.Parse(converted[(measure.Length + 1)..^1], CultureInfo.InvariantCulture); + Assert.Equal(expected, actual, expected * 1e-12); + } + + [Fact] + public void RevitParameters_WithIfcUnits_DoNotGuessASpecFromTheParameterName() + { + var info = SingleElementModel( + [ + new Parameter + { + Id = -999999001, + Definition = new Definition { Id = -999999001, BuiltInParameter = "TEST_ONLY_SLOPE_AREA", Name = "TEST_ONLY_SLOPE_AREA" }, + StorageType = StorageType.Double, + Value = 0.5, + }, + ]); + + string ifc = ExportText(info, new IfcExporter(includeRevitPropertySets: true) { RevitParameterUnits = IfcRevitParameterUnits.Ifc }); + + Assert.Contains("IFCPROPERTYSINGLEVALUE('TEST_ONLY_SLOPE_AREA','',IFCREAL(0.5),$)", ifc); + } + + // spec, and the project unit that gives its measure a meaning: a named SI unit, or the factors of a derived one + private static readonly (string Spec, string Unit)[] MeasureUnits = + [ + ("autodesk.spec.aec.structural:stress", "PRESSUREUNIT=PASCAL"), + ("autodesk.spec.aec.structural:areaForce", "PLANARFORCEUNIT=KILOGRAM^1 METRE^-1 SECOND^-2"), + ("autodesk.spec.aec.hvac:viscosity", "DYNAMICVISCOSITYUNIT=KILOGRAM^1 METRE^-1 SECOND^-1"), + ("autodesk.spec.aec.energy:permeability", "VAPORPERMEABILITYUNIT=METRE^-1 SECOND^1"), + ("autodesk.spec.aec.structural:massPerUnitLength", "MASSPERLENGTHUNIT=KILOGRAM^1 METRE^-1"), + ("autodesk.spec.aec.structural:force", "FORCEUNIT=NEWTON"), + ("autodesk.spec.aec.hvac:velocity", "LINEARVELOCITYUNIT=METRE^1 SECOND^-1"), + ("autodesk.spec.aec.energy:thermalConductivity", "THERMALCONDUCTANCEUNIT=KELVIN^-1 KILOGRAM^1 METRE^1 SECOND^-3"), + ("autodesk.spec.aec.structural:linearMoment", "LINEARMOMENTUNIT=KILOGRAM^1 METRE^1 SECOND^-2"), + ("autodesk.spec.aec.electrical:power", "POWERUNIT=WATT"), + ("autodesk.spec.aec.electrical:potential", "ELECTRICVOLTAGEUNIT=VOLT"), + ("autodesk.spec.aec.energy:specificHeat", "SPECIFICHEATCAPACITYUNIT=KELVIN^-1 METRE^2 SECOND^-2"), + ("autodesk.spec.aec.energy:specificHeatOfVaporization", "HEATINGVALUEUNIT=METRE^2 SECOND^-2"), + ("autodesk.spec.aec.structural:moment", "TORQUEUNIT=KILOGRAM^1 METRE^2 SECOND^-2"), + ("autodesk.spec.aec:energy", "ENERGYUNIT=JOULE"), + ("autodesk.spec.aec.electrical:illuminance", "ILLUMINANCEUNIT=LUX"), + ("autodesk.spec.aec.hvac:airFlow", "VOLUMETRICFLOWRATEUNIT=METRE^3 SECOND^-1"), + ("autodesk.spec.aec.structural:sectionModulus", "SECTIONMODULUSUNIT=METRE^3"), + ("autodesk.spec.aec:massDensity", "MASSDENSITYUNIT=KILOGRAM^1 METRE^-3"), + ("autodesk.spec.aec.structural:momentOfInertia", "MOMENTOFINERTIAUNIT=METRE^4"), + ("autodesk.spec.aec.structural:warpingConstant", "WARPINGCONSTANTUNIT=METRE^6"), + ("autodesk.spec.aec.energy:heatTransferCoefficient", "THERMALTRANSMITTANCEUNIT=KELVIN^-1 KILOGRAM^1 SECOND^-3"), + ("autodesk.spec.aec.energy:thermalResistance", "THERMALRESISTANCEUNIT=KELVIN^1 KILOGRAM^-1 SECOND^3"), + ("autodesk.spec.aec.electrical:current", "ELECTRICCURRENTUNIT=AMPERE"), + ("autodesk.spec.aec.electrical:luminousFlux", "LUMINOUSFLUXUNIT=LUMEN"), + ("autodesk.spec.aec.electrical:luminousIntensity", "LUMINOUSINTENSITYUNIT=CANDELA"), + ("autodesk.spec.aec.hvac:temperature", "THERMODYNAMICTEMPERATUREUNIT=KELVIN"), + ("autodesk.spec.aec.structural:mass", "MASSUNIT=KILOGRAM"), + ("autodesk.spec.aec.structural:linearForce", "LINEARFORCEUNIT=KILOGRAM^1 SECOND^-2"), + ("autodesk.spec.aec.structural:thermalExpansionCoefficient", "THERMALEXPANSIONCOEFFICIENTUNIT=KELVIN^-1"), + ("autodesk.spec.aec:time", "TIMEUNIT=SECOND"), + ("autodesk.spec.aec:frequency", "FREQUENCYUNIT=HERTZ"), + ]; + + [Theory] + [InlineData(IfcProfile.Current)] + [InlineData(IfcProfile.Legacy)] + public void RevitParameters_WithIfcUnits_DeclareTheUnitOfEveryMeasureOnce(IfcProfile profile) + { + var info = SingleElementModel(MeasureUnits.Select((entry, i) => new Parameter + { + Id = 900100 + i, + Definition = new Definition { Id = 900100 + i, Name = $"Test {i}" }, + SpecType = entry.Spec + "-2.0.0", + StorageType = StorageType.Double, + Value = 1.0, + }).ToList()); + + var declared = ProjectUnits(ExportText(info, new IfcExporter(includeRevitPropertySets: true) + { + Profile = profile, + RevitParameterUnits = IfcRevitParameterUnits.Ifc, + })); + + Assert.Equal(declared.Count, declared.Select(unit => unit.Split('=')[0]).Distinct().Count()); + Assert.All(MeasureUnits, entry => Assert.Contains(entry.Unit, declared)); + } + + [Theory] + [InlineData(IfcProfile.Current)] + [InlineData(IfcProfile.Legacy)] + public void RevitParameters_WithoutIfcUnits_DeclareNoAdditionalUnits(IfcProfile profile) + { + var info = SingleElementModel( + [ + new Parameter { Id = 900100, SpecType = "autodesk.spec.aec.structural:stress-2.0.0", StorageType = StorageType.Double, Value = 1.0 }, + ]); + + var declared = ProjectUnits(ExportText(info, new IfcExporter(includeRevitPropertySets: true) { Profile = profile })); + + Assert.DoesNotContain(declared, unit => unit.StartsWith("PRESSUREUNIT=", StringComparison.Ordinal)); + } + + private static RevitFileInfo SingleElementModel(List parameters) + { + double[][] points = + [ + [-0.2, 0, 3.7], [0.2, 0, 3.7], [0.2, 0, 4.3], [-0.2, 0, 4.3], + [-0.2, 10, 3.7], [0.2, 10, 3.7], [0.2, 10, 4.3], [-0.2, 10, 4.3], + ]; + int[][] faceIndices = + [ + [0, 1, 2, 3], [4, 7, 6, 5], [0, 4, 5, 1], + [1, 5, 6, 2], [2, 6, 7, 3], [3, 7, 4, 0], + ]; + double[] bounds = [-0.2, 0, 3.7, 0.2, 10, 4.3]; + parameters.Insert(0, new Parameter { Id = -1012100, StorageType = StorageType.ElementId, Value = 3 }); + var info = new RevitFileInfo(); + info.Elements.Add(new Element { Id = 3, CategoryId = -2000112, Category = "OST_Phases", Name = "New Construction" }); + info.Elements.Add(new Element + { + Id = 20, + TypeId = 21, + IsDiscovered = true, + CategoryId = -2001320, + Category = "OST_StructuralFraming", + Name = "Beam 1", + References = [3], + BoundingBox = bounds, + Geometry = new GeometryData + { + BoundingBox = bounds, + Faces = faceIndices.Select(idx => new GeoFace { OuterVertices = idx.Select(i => points[i]).ToList() }).ToList(), + BrepSolids = [new GeoBrepSolid { IsClosed = true, FaceIndices = [0, 1, 2, 3, 4, 5] }], + }, + Parameters = parameters, + }); + return info; + } + + private static string ExportText(RevitFileInfo info, IfcExporter exporter) + { + var text = new StringWriter(); + exporter.Export(info, text); + return text.ToString(); + } + + /// The assigned project units as TYPE=NAME, or TYPE=FACTOR^exponent ... with the factors by name. + private static List ProjectUnits(string ifc) + { + var entities = Regex.Matches(ifc, @"^#(\d+)\s*=\s*([A-Z0-9]+)\((.*)\);\r?$", RegexOptions.Multiline) + .ToDictionary(m => m.Groups[1].Value, m => (Type: m.Groups[2].Value, Args: m.Groups[3].Value)); + static IEnumerable References(string args) => Regex.Matches(args, @"#(\d+)").Select(m => m.Groups[1].Value); + static string SiName(string args) + { + string[] parts = args.Split(','); + return (parts[2] == ".KILO." ? "KILO" : "") + parts[3].Trim('.'); + } + + var assignment = Assert.Single(entities.Values, e => e.Type == "IFCUNITASSIGNMENT"); + return References(assignment.Args).Select(id => + { + var (type, args) = entities[id]; + string unitType = Regex.Match(args, @"\.([A-Z]+UNIT)\.").Groups[1].Value; + if (type == "IFCSIUNIT") return $"{unitType}={SiName(args)}"; + if (type != "IFCDERIVEDUNIT") return $"{unitType}={type}"; + var factors = References(args).Select(element => + { + string[] parts = entities[element].Args.Split(','); + return $"{SiName(entities[parts[0].TrimStart('#')].Args)}^{parts[1]}"; + }); + return $"{unitType}={string.Join(' ', factors.Order(StringComparer.Ordinal))}"; + }).ToList(); + } + + [Fact] + public void Configuration_RoundTripsRevitParameterUnitsAndNamesThroughJson() + { + var config = new IfcExportConfiguration + { + PropertySets = new IfcPropertySetConfiguration + { + ExportRevitPropertySets = true, + RevitParameterUnits = IfcRevitParameterUnits.Ifc, + RevitParameterNames = IfcRevitParameterNames.Display, + }, + }; + + string json = config.ToJson(); + Assert.Contains("\"revitParameterUnits\": \"ifc\"", json); + Assert.Contains("\"revitParameterNames\": \"display\"", json); + + var reloaded = IfcExportConfiguration.FromJson(json); + var resolved = reloaded.Resolve(); + Assert.True(resolved.ExportRevitPropertySets); + Assert.Equal(IfcRevitParameterUnits.Ifc, resolved.RevitParameterUnits); + Assert.Equal(IfcRevitParameterNames.Display, resolved.RevitParameterNames); + } + + [Fact] + public void CliOptions_ParsesRevitParameterUnitsAndNamesAndRejectsInvalidValues() + { + Assert.True(IfcConfigurationOptions.TryParse( + ["--ifc-revit-parameter-units", "ifc", "--ifc-revit-parameter-names", "display"], + out var parsed, out string? error)); + Assert.Null(error); + Assert.Equal(IfcRevitParameterUnits.Ifc, parsed.RevitParameterUnits); + Assert.Equal(IfcRevitParameterNames.Display, parsed.RevitParameterNames); + + Assert.True(IfcConfigurationOptions.TryBuildConfiguration( + parsed, IfcProfile.Current, false, + revitParameters: false, revitParameterGroups: false, + baseQuantities: true, false, false, false, + null, false, false, null, false, false, null, null, + out _, out var resolved, out string? buildError)); + Assert.Null(buildError); + Assert.True(resolved.ExportRevitPropertySets); + Assert.Equal(IfcRevitParameterUnits.Ifc, resolved.RevitParameterUnits); + Assert.Equal(IfcRevitParameterNames.Display, resolved.RevitParameterNames); + + Assert.False(IfcConfigurationOptions.TryParse(["--ifc-revit-parameter-units", "metric"], out _, out _)); + Assert.False(IfcConfigurationOptions.TryParse(["--ifc-revit-parameter-names", "localized"], out _, out _)); + } + + [Fact] + public void Cli_CapabilitiesListsRevitParameterUnitsAndNames() + { + using var sw = new StringWriter(); + IfcConfigurationOptions.WriteCapabilities(sw); + string text = sw.ToString(); + Assert.Contains("propertySets.revitParameterUnits", text); + Assert.Contains("propertySets.revitParameterNames", text); + } + + [Fact] + public void Cli_RejectsInvalidRevitParameterFormattingFlagsAndRequiresIfcOutput() + { + Assert.NotEqual(0, Program.Main(["model.rvt", "out.ifc", "--ifc-revit-parameter-units", "bogus"])); + Assert.NotEqual(0, Program.Main(["model.rvt", "out.ifc", "--ifc-revit-parameter-names", "bogus"])); + Assert.NotEqual(0, Program.Main(["model.rvt", "--ifc-revit-parameter-units", "ifc"])); + Assert.NotEqual(0, Program.Main(["model.rvt", "--ifc-revit-parameter-names", "display"])); + } +}